From 4e1de8186f91b7640e4157772f5155db862cc15d Mon Sep 17 00:00:00 2001
From: Branimir Georgiev <66906831+braboj@users.noreply.github.com>
Date: Sun, 15 Nov 2026 18:48:46 +0200
Subject: [PATCH 1/7] feat(emit): build section files an agent reads one topic
at a time (#2466)
`resolve_chain.py --emit
--sections ...` builds one file per
heading of each template, under `.agents/sections//`, and a
root file that maps each topic to its file, to be read when the work
first touches it.
- Each file carries the rules under its template's title, each section
it extends or names by ID, and each extension of its own, in chain
order, so precedence holds and no rule is left to a reference
- Overrides, the declined list and the checked cut apply as in the other
modes; the root file and skills, inlined or not, are byte-identical
- SYS-28 checks that the files together hold exactly the inlined root
file's rules, that copies match, and that the map reads on demand, for
planted templates and every root, and that two runs agree
- SYS-27 scans the section files for template paths too
- ADR-060 records the mode, outside the frozen surface until a benchmark
round measures it; FR-06-08 and FR-06-09 state it
Closes #2466.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3
---
AGENTS.md | 1 +
docs/architecture/05-building-block-view.md | 1 +
docs/architecture/08-crosscutting-concepts.md | 1 +
.../architecture/09-architecture-decisions.md | 1 +
docs/architecture/12-glossary.md | 1 +
.../060-section-files-load-on-demand.md | 118 ++++++
docs/requirements.md | 2 +
docs/tests/index.md | 1 +
docs/tests/specs/SAIT-SMK-SYS-27-001A.md | 11 +-
docs/tests/specs/SAIT-SMK-SYS-28-001A.md | 101 +++++
tests/smoke/registry.py | 7 +
tests/smoke/system.py | 363 +++++++++++++++++-
tools/emit_context.py | 282 +++++++++++++-
tools/resolve_chain.py | 31 +-
14 files changed, 885 insertions(+), 36 deletions(-)
create mode 100644 docs/decisions/060-section-files-load-on-demand.md
create mode 100644 docs/tests/specs/SAIT-SMK-SYS-28-001A.md
diff --git a/AGENTS.md b/AGENTS.md
index bb87454d..84335fbe 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -26,6 +26,7 @@ py tools/sync_docs.py --check # exit 1 if any is stale
py tools/resolve_chain.py --roots # every root a project can pick
py tools/resolve_chain.py # one root's resolved file list
py tools/resolve_chain.py --emit ... # root file and task skills
+py tools/resolve_chain.py --emit --sections ... # map and section files
py tests/run.py smoke # structure and resolution
py tests/run.py conformance # the templates' own checks, run here
py tests/run.py fork_sync # the change merged into a simulated fork
diff --git a/docs/architecture/05-building-block-view.md b/docs/architecture/05-building-block-view.md
index c2d636b0..a9c4a380 100644
--- a/docs/architecture/05-building-block-view.md
+++ b/docs/architecture/05-building-block-view.md
@@ -89,6 +89,7 @@ misses it and reports nothing, because nothing declares what is absent.
| `--emit ...` | Roots and the declined list | The root file and one skill per kind of task | FR-06-03, FR-06-04, FR-06-06 |
| `--inline-skills` | As `--emit` | One root file with the skills inlined, for an agent without skills | ADR-058 |
| `--mirror ` | As `--emit` | A copy of the skills where an agent reads only its own folder | ADR-058 |
+| `--sections` | As `--emit` | A root file that maps each topic to its file, and one file per topic under `.agents/sections/`, read on demand | FR-06-08, FR-06-09 |
## 5.5 Level 2: self-checks
diff --git a/docs/architecture/08-crosscutting-concepts.md b/docs/architecture/08-crosscutting-concepts.md
index 6df541ed..1c71075b 100644
--- a/docs/architecture/08-crosscutting-concepts.md
+++ b/docs/architecture/08-crosscutting-concepts.md
@@ -160,6 +160,7 @@ These elements are not frozen.
| The wording inside a section | Prose is free while the section keeps its ID | ADR-051 |
| The declaration block | A target with no producer and no reader | ADR-053 |
| The fixture, `stack-fixture` and `platform-fixture` | Test input; no listing offers it and no project resolves it | - |
+| The emitter's `--sections` flag and the `.agents/sections/` layout it writes | Opt-in and not yet measured; a benchmark round decides whether it is a delivery | ADR-060 |
| The helpers `bind()` hands `fork_checks.py` | Every name in the smoke modules; a change to one is listed in the changelog | - |
## 8.8 Deprecation
diff --git a/docs/architecture/09-architecture-decisions.md b/docs/architecture/09-architecture-decisions.md
index 27da1e92..90ee15e4 100644
--- a/docs/architecture/09-architecture-decisions.md
+++ b/docs/architecture/09-architecture-decisions.md
@@ -43,6 +43,7 @@ What a project's generated files hold, and how the rules reach them.
| [ADR-052](../decisions/052-hybrid-is-the-delivery-floor.md) | A context file delivers rules inline or hybrid, never by reference alone, and inlines every rule whose breach is silent and which no tool enforces | Accepted |
| [ADR-053](../decisions/053-declaration-block-is-a-target.md) | The declaration block leaves the frozen surface until a release ships a tool that writes it and one that reads it | Accepted |
| [ADR-058](../decisions/058-task-procedures-load-on-demand.md) | Each section declares where its rules load, and a tool builds the root file and one skill per kind of task from the adopted rules | Accepted |
+| [ADR-060](../decisions/060-section-files-load-on-demand.md) | The emitter can build one file per topic, each with every rule it depends on, and a root file that maps each topic to its file, read on demand | Accepted |
## 9.3 Template content
diff --git a/docs/architecture/12-glossary.md b/docs/architecture/12-glossary.md
index 157cebd9..4b21e8ed 100644
--- a/docs/architecture/12-glossary.md
+++ b/docs/architecture/12-glossary.md
@@ -30,6 +30,7 @@ requirement in [requirements.md](../requirements.md).
| Platform | A fork's template mapping CI and security tools to one hosting platform |
| Root | A template a project picks directly, as a stack, a platform or an extra. Upstream has no stack, so every one of its templates except the fixture is a root |
| Root file | The context file at a project's root, read on every turn, which lists the task skills that load on demand |
+| Section file | A file under `.agents/sections/` holding one heading of a template with every rule it depends on, read when the work first touches its topic |
| Stack | A fork's technology-specific template, the main root of a chain |
| Task kind | A kind of task, such as `release`, that a load directive names and a skill serves, listed under the manifest's `tasks:` |
| Task skill | A folder under `.agents/skills/` holding the rules for one task kind, loaded when that task starts |
diff --git a/docs/decisions/060-section-files-load-on-demand.md b/docs/decisions/060-section-files-load-on-demand.md
new file mode 100644
index 00000000..c19ae40c
--- /dev/null
+++ b/docs/decisions/060-section-files-load-on-demand.md
@@ -0,0 +1,118 @@
+---
+id: "060"
+status: Accepted
+date: 2026-11-15
+category: composition
+supersedes: []
+superseded_by: []
+---
+
+# ADR-060: The emitter can build section files that load on demand
+
+## Context
+
+The emitter's root file holds every rule without a load directive, so an
+agent reads most of its chain on every turn, whatever the task touches.
+The benchmark measures other deliveries against it, each built by script
+from the same chain (solid-ai-dev/solid-ai-benchmark#169).
+
+- Whole templates read on demand from a map, the benchmark's `lazyref`
+ arm, read 11 of 13 templates, about 46k tokens, by turn 3 in its round
+ 5e (15 runs), so an agent that needs one topic reads the whole file
+ (#2466)
+- A template holds several topics; the benchmark chain's run from about
+ 450 to 1,700 words each, and nothing hands an agent one topic of one
+- A topic's rules can depend on rules elsewhere: the rules under the
+ template's title, a section it extends, a section its prose names by
+ ID, and an extension a later template adds on top of it
+- Template paths and section IDs are frozen for 3.x, so a delivery that
+ splits templates or anchors each heading changes the frozen surface
+
+## Decision
+
+The emitter gains an opt-in mode, `--sections`, that builds one file per
+topic, each a heading of a template with every rule it depends on, and a
+root file that maps each topic to its file, to be read when the work
+first touches it.
+
+## Rationale
+
+- One topic, one read: an agent reads the rules of the topic at hand, not
+ the whole template that holds it
+- Same rules, same precedence: the mode applies the overrides, the
+ declined list and the checked cut the other modes apply, so only
+ packaging and loading differ, which is what the benchmark compares
+- Nothing frozen changes: the files are built from the templates as they
+ are, with no new anchor, path or ID
+- Measured before it is endorsed: the mode stays opt-in and outside the
+ frozen surface until a benchmark round compares it with the root file
+ and with whole templates on demand
+
+## Design
+
+1. **Topic** — each heading one level under a template's title, with its
+ subheadings, is a topic with a file of its own. The rules under a
+ title alone get a file only where no topic's file carries them
+2. **Carried rules** — a topic's file carries, in chain order, the rules
+ under its template's title, each section it extends, each section its
+ prose names by ID in backticks, each extension of its own sections,
+ and what each of those carries in turn. Rules carried only because they
+ sit under a title do not bring that title's extensions (MUST)
+3. **Same rule set** — the files together hold exactly the rules the
+ inlined root file holds, and every copy of a rule matches its source
+ (MUST)
+4. **The map** — the root file keeps the facts, states
+ `Model: root and sections`, and lists each template by its title and
+ manifest description, with one row per topic naming its file. It holds
+ no rule, and tells the agent not to read the files before the work
+ starts (MUST)
+5. **Paths** — a file is written to
+ `.agents/sections//.md`, so no emitted path or
+ line names a template file (MUST)
+6. **Deterministic** — the same chain and declined list give
+ byte-identical files (MUST)
+7. **Not frozen** — the flag and the layout may change or go in a minor
+ until a benchmark round decides whether the mode is a delivery
+
+## Alternatives considered
+
+| Alternative | Why not |
+|---|---|
+| Stable anchors per section, the map naming `file#anchor` | Freezes one more name per heading, and an agent's file reader takes no anchor, so it reads the whole file anyway |
+| Split a template over a size limit into topic files | Changes template paths, which 3.x freezes, and leaves a topic's dependencies in other files |
+| Whole templates read on demand from a map | Already measured: the agent read most of the chain within three turns |
+| Leave the root file as it is | Every turn carries most of the chain, which no delivery has yet been measured against topic by topic |
+
+## Consequences
+
+| Consequence | Effect |
+|---|---|
+| Tool | `resolve_chain.py --emit --sections ...` writes the map and the section files; `--inline-skills` with it is refused |
+| Checks | SYS-28 compares the files with the inlined root file's rules, every root built alone, and runs the tool twice under different hash seeds; SYS-27 scans the section files for template paths |
+| Requirements | FR-06-08 and FR-06-09 state the mode |
+| Frozen surface | The mode is listed as not frozen (chapter 8.7) |
+| Benchmark | Builds arm `lazysections` from the mode, beside the arm that reads every template up front and the one that reads whole templates on demand |
+
+## Compatibility
+
+None for an existing project: the root file and skills, inlined or not,
+are byte-identical to what the emitter built before. A project that moves
+to `--sections` keeps its filled-in facts, and the emitter removes the
+skills it wrote before, as it removes any file it no longer emits.
+
+## Security
+
+- Exposes: every rule leaves the root file, a section that guards data,
+ credentials or authentication included, so it is read only when the
+ work touches its topic. The root and skills keep such a section in
+ context on every turn, which is why this mode is opt-in and measured
+ first, on the benchmark's security and data-protection rows as well as
+ every other
+- Protects: a file carries every section its rules extend or name, so no
+ rule in it is left to a reference the agent may not follow
+- Trust boundary: the section files are built by the tool into the
+ project's tree, under the same review as the root file
+
+## Related
+
+- solid-ai-dev/solid-ai-benchmark#169, the arms that compare deliveries
diff --git a/docs/requirements.md b/docs/requirements.md
index bc527737..996752a8 100644
--- a/docs/requirements.md
+++ b/docs/requirements.md
@@ -70,6 +70,8 @@ Status: skeleton. Each cluster holds a few requirements until its fill
| FR-06-05 | The system shall reference a section marked `check` by its command and pass condition, never by copying the script body. | ADR-058 | SYS-26, partial, on a planted fixture |
| FR-06-06 | The system shall build byte-identical files from the same input. | ADR-058 | SYS-26 |
| FR-06-07 | The system shall build files that name no template file, since an emitted project carries no templates. | `AGENTS.md` 4.2 | SYS-27 |
+| FR-06-08 | Where the project asks for section files, the system shall build one file per heading under a template's title, carrying the rules under that title, each section it extends or names by ID, and each extension of its own, so the files together hold every adopted rule and every copy matches its source. | ADR-060 | SYS-28 |
+| FR-06-09 | Where the project asks for section files, the system shall map each file in the root file to its topic, to be read when the work first touches it, and hold no rule in the root file. | ADR-060 | SYS-28 |
### 07. Shipped checks
diff --git a/docs/tests/index.md b/docs/tests/index.md
index b4b4c386..04eea3f7 100644
--- a/docs/tests/index.md
+++ b/docs/tests/index.md
@@ -50,6 +50,7 @@ restated in each.
| `SAIT-SMK-SYS-25-001A` | SMK | P1 | A load directive names a listed task, in its heading's tags |
| `SAIT-SMK-SYS-26-001A` | SMK | P1 | The emitter places each section by its load, the same every run |
| `SAIT-SMK-SYS-27-001A` | SMK | P1 | An emitted file names no template file |
+| `SAIT-SMK-SYS-28-001A` | SMK | P1 | Section files hold every adopted rule, read on demand from a map |
| `SAIT-SMK-TPL-04-001A` | SMK | P1 | All EXTEND and OVERRIDE directives reference existing IDs |
| `SAIT-INT-TPL-01-001A` | INT | P0 | DEPENDS ON chain assembles a complete rule set |
| `SAIT-INT-TPL-02-001A` | INT | P1 | EXTEND adds rules without removing base rules |
diff --git a/docs/tests/specs/SAIT-SMK-SYS-27-001A.md b/docs/tests/specs/SAIT-SMK-SYS-27-001A.md
index 60d393c9..1ef72ed0 100644
--- a/docs/tests/specs/SAIT-SMK-SYS-27-001A.md
+++ b/docs/tests/specs/SAIT-SMK-SYS-27-001A.md
@@ -17,7 +17,8 @@ tags: [tooling, composition, delivery]
## Short description
> **Given** every root a project can pick
-> **When** the emitter builds each root on its own, with skills and inlined
+> **When** the emitter builds each root on its own, with skills, inlined
+> and as section files
> **Then** no line of an emitted file names a template file, because an
> emitted project carries the rules and not the templates, so a named
> template is a file the agent cannot open and the rules it stands for
@@ -31,7 +32,7 @@ names a template in, and the path goes unseen.
| Result | Condition |
|--------|-----------|
-| PASSED | The planted template's two named paths are both found in each mode, the planted override hides one only when the roots are built together, and no file emitted from any root alone, in either mode, names a template file |
+| PASSED | The planted template's two named paths are both found in each mode, the planted override hides one only when the roots are built together, and no file emitted from any root alone, in any mode, names a template file |
| FAILED | An emitted line names a template file, with or without its `templates/` prefix, or the planted scan misses a form |
| SKIPPED | — |
| BLOCKED | — |
@@ -55,8 +56,8 @@ file is written)
`templates/` prefix, in a skill, and once without, in a section a
second planted root overrides
2. Build the planted roots together, then each on its own
-3. Build every root `--roots` lists on its own, with skills and then with
- skills inlined
+3. Build every root `--roots` lists on its own, with skills, with skills
+ inlined, and as section files
4. Scan every emitted line for the path of every template file
### Assertions
@@ -65,7 +66,7 @@ file is written)
each mode
2. Assert the planted roots built together show one of the two paths, and
built each on its own show both
-3. Assert no line emitted from any root, in either mode, names a template
+3. Assert no line emitted from any root, in any mode, names a template
file
### Negative controls
diff --git a/docs/tests/specs/SAIT-SMK-SYS-28-001A.md b/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
new file mode 100644
index 00000000..1a991cd8
--- /dev/null
+++ b/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
@@ -0,0 +1,101 @@
+---
+id: SAIT-SMK-SYS-28-001A
+title: Section files hold every adopted rule, read on demand from a map
+product: sait
+type: smoke
+area: SYS
+priority: p1
+status: ready
+environment: [local, ci]
+automatable: yes
+created: 2026-11-15
+author: Branimir Georgiev
+product-version: "3.x"
+tags: [tooling, composition, delivery, determinism]
+---
+
+## Short description
+
+> **Given** a chain of templates and the sections a project declines
+> **When** `resolve_chain.py --emit --sections` builds one file per topic
+> and the root file's map
+> **Then** the section files together hold exactly the rules the inlined
+> root file holds, each copy of a rule matches its source, a file carries
+> every section it extends or names, and the root file holds only the map,
+> read on demand, because a rule no file holds is one the agent never
+> reads, and a copy that differs contradicts its source
+
+## Results
+
+| Result | Condition |
+|--------|-----------|
+| PASSED | The planted placements are right, each planted fault is reported, every root built alone passes, and two runs under different hash seeds write the same bytes |
+| FAILED | A planted placement is wrong, or a planted fault goes unreported |
+| FAILED | A root's section files miss an adopted rule, hold a line no adopted rule is, hold two different copies of one block, or name a section they do not carry |
+| FAILED | A root's root file holds a rule, maps a section file other than once, maps a file not emitted, or does not say to read a file on demand |
+| FAILED | The two runs differ, or the emitter exits non-zero |
+| SKIPPED | — |
+| BLOCKED | — |
+| ERROR | — |
+
+## Steps
+
+### Prerequisites
+
+- Repository cloned locally
+- Python 3
+
+### Setup
+
+— (operates on planted templates and on every root, built in memory, and
+on two roots written to a temporary directory that is removed afterwards)
+
+### Execution
+
+1. Build a planted base template, a planted layer that extends one of its
+ sections, overrides another and names the first in its title's rules,
+ and a planted template with rules under its title alone, declining one
+ base section
+2. Build every root `--roots` lists on its own, as section files and with
+ skills inlined
+3. Cut every section file at its headings, keep one copy of each block,
+ and count its lines against the inlined root file's rule lines
+4. Plant three faults in the planted output: a file dropped, a copy
+ edited, and a carried section removed
+5. Run `resolve_chain.py --emit --sections` on `backend-auth` and
+ `backend-database` twice, with `PYTHONHASHSEED` 1 and 2, and compare
+ the trees byte for byte
+
+### Assertions
+
+1. Assert the planted override replaces its base, the declined section is
+ absent, the checked rule is left to its check with its command kept,
+ and the procedure is in a section file and not in the root file
+2. Assert a section's file carries its extension after it, and the
+ extension's file carries the section before it
+3. Assert a file carries the rules under its template's title and every
+ section those name, and the bare title gets a file of its own
+4. Assert, for the planted chain and every root, that the lines held equal
+ the adopted lines, that two copies of a block never differ, and that a
+ file naming a section in backticks carries its rules
+5. Assert the root file maps each section file once, maps no other, holds
+ no rule line, and says not to read the files before the work starts
+6. Assert each planted fault is reported
+7. Assert the two runs write the same files with the same bytes
+
+### Negative controls
+
+1. **No extension carried.** With the extension relation ignored, the
+ planted base section's file lacks its extension and the check fails
+2. **No name followed.** With the names in a title's rules ignored, the
+ planted layer's files name a section they do not carry and the check
+ fails
+3. **The planted faults.** A dropped file, an edited copy and a removed
+ carried section each fail the counts or the copy comparison; the check
+ runs all three on every run
+
+## Related
+
+- ADR-060: the emitter builds section files read on demand
+- SYS-26: the emitter places each section by its load
+- SYS-27: an emitted file names no template file, section files included
diff --git a/tests/smoke/registry.py b/tests/smoke/registry.py
index d0e3cc86..ebe13b9f 100644
--- a/tests/smoke/registry.py
+++ b/tests/smoke/registry.py
@@ -38,6 +38,7 @@
check_sys_25,
check_sys_26,
check_sys_27,
+ check_sys_28,
)
from .templates import (
check_tpl_01,
@@ -290,4 +291,10 @@ class Check(TypedDict):
"title": "An emitted file names no template file",
"fn": check_sys_27,
},
+ {
+ "id": "SYS-28",
+ "spec": "SAIT-SMK-SYS-28-001A",
+ "title": "Section files hold every adopted rule, read on demand from a map",
+ "fn": check_sys_28,
+ },
]
diff --git a/tests/smoke/system.py b/tests/smoke/system.py
index e7313b1e..17f9da77 100644
--- a/tests/smoke/system.py
+++ b/tests/smoke/system.py
@@ -13,9 +13,13 @@
# One definition of what a manifest section is, shared with the resolver,
# so a fork's own key is read here exactly as it is resolved there.
from emit_context import EmitError
+from emit_context import BUILT_LINE, MAP_HEADER, SECTIONS_DIR, section_rules
from emit_context import build as emit_build
+from emit_context import build_sections as emit_sections
from emit_context import write as emit_write
from resolve_chain import (
+ FENCE_LINE,
+ HEADING_LINE as LEVEL_HEADING,
LOAD_CHECK,
Entry,
Manifest,
@@ -29,6 +33,7 @@
read_file,
resolve_chain,
task_kinds,
+ template_names,
)
from testkit import ROOT, template_files
@@ -2413,6 +2418,10 @@ def check_sys_26() -> CheckResult:
)
PATH_STACK = "# Stack — Demo\n\n## Naming\n[OVERRIDE: demo-naming]\n\n- Name by role\n"
PATH_KINDS = {"release": "Preparing a release"}
+PATH_TEMPLATES = {
+ "templates/core/demo.md": ("base-demo", "Demo rules"),
+ "templates/fixture/stack.md": ("stack-demo", "Demo stack"),
+}
PATH_CHAINS = {
"demo": [("templates/core/demo.md", PATH_TEMPLATE)],
"stack": [
@@ -2456,17 +2465,22 @@ def root_path_findings(
chains: Mapping[str, Sequence[tuple[str, str]]],
kinds: Mapping[str, str],
paths: Collection[str],
+ templates: Mapping[str, tuple[str, str]],
emitted_counts: Counter[str] | None = None,
) -> list[str]:
"""Each root's emitted lines that name one of `paths`, the root built
- alone with skills and inlined. `chains` maps a root to its (path, text)
- pairs in resolution order; `emitted_counts`, a Counter, takes the files
- emitted per mode."""
+ alone with skills, inlined and as section files. `chains` maps a root to
+ its (path, text) pairs in resolution order, `templates` each path to its
+ manifest ID and description; `emitted_counts`, a Counter, takes the
+ files emitted per mode."""
findings: list[str] = []
for root in sorted(chains):
- for inline in (False, True):
- mode = "inline" if inline else "skills"
- emitted = emit_build(chains[root], kinds, inline_skills=inline)
+ for mode in ("skills", "inline", "sections"):
+ emitted = (
+ emit_sections(chains[root], templates)
+ if mode == "sections"
+ else emit_build(chains[root], kinds, inline_skills=mode == "inline")
+ )
if emitted_counts is not None:
emitted_counts[mode] += len(emitted)
findings.extend(
@@ -2480,21 +2494,23 @@ def check_sys_27() -> CheckResult:
seen = Inspected()
failures: list[str] = []
planted = ["templates/core/demo.md"]
- alone = root_path_findings({"demo": PATH_CHAINS["demo"]}, PATH_KINDS, planted)
- if len(alone) != 4:
+ alone = root_path_findings(
+ {"demo": PATH_CHAINS["demo"]}, PATH_KINDS, planted, PATH_TEMPLATES
+ )
+ if len(alone) != 6:
failures.append(
- f" planted: {len(alone)} of the 4 named paths found, 2 per mode"
+ f" planted: {len(alone)} of the 6 named paths found, 2 per mode"
)
seen.count("planted paths found", len(alone))
# Built together, the stack's override drops the Naming line and only
# the Review line is left; built per root, the demo root still has both.
together = path_findings(emit_build(PATH_CHAINS["stack"], PATH_KINDS), planted)
- split = root_path_findings(PATH_CHAINS, PATH_KINDS, planted)
- if len(together) != 1 or len(split) != 6:
+ split = root_path_findings(PATH_CHAINS, PATH_KINDS, planted, PATH_TEMPLATES)
+ if len(together) != 1 or len(split) != 9:
failures.append(
f" planted override: {len(together)} found built "
- f"together, owed 1; {len(split)} per root, owed 6"
+ f"together, owed 1; {len(split)} per root, owed 9"
)
core_ids, entries, _ = load_manifest()
@@ -2516,8 +2532,327 @@ def check_sys_27() -> CheckResult:
)
emitted: Counter[str] = Counter()
failures.extend(
- f" {finding}" for finding in root_path_findings(chains, kinds, paths, emitted)
+ f" {finding}"
+ for finding in root_path_findings(
+ chains, kinds, paths, template_names(entries), emitted
+ )
)
- for mode in ("skills", "inline"):
+ for mode in ("skills", "inline", "sections"):
seen.count(f"files emitted, {mode}", emitted[mode])
return seen.failures() + failures, seen.notes()
+
+
+# ---------------------------------------------------------------------------
+# SYS-28 -- section files hold every adopted rule, and the map reads them
+# on demand
+# ---------------------------------------------------------------------------
+
+# With `--sections` the emitter builds one file per topic and a root file
+# that maps each topic to its file. The files must hold exactly the rules
+# the other modes deliver: a rule no file holds is one the agent never
+# reads, and a copy that differs from its source contradicts it. A section
+# that extends or names another carries it, since a rule left to a
+# reference is one the agent never reads, and the root file holds only the
+# map, read on demand. Planted templates exercise each of these, every root
+# is built alone, and two runs under different hash seeds agree.
+
+SECTION_BASE = (
+ "# Base — Demo\n[ID: base-demo]\n\nTitle rule for every heading.\n\n"
+ "## Naming\n[ID: demo-naming]\n\n- Name by role\n\n"
+ "## Releases\n[LOAD: release]\n\n- Tag the release\n\n"
+ "## Lint\n[LOAD: check]\n\n- Rule the check enforces\n\n- Run the linter:\n\n"
+ "```bash\nruff check .\n```\n\n"
+ "## Optional\n\n- Declined rule\n\n"
+ "## Render\n[ID: demo-render]\n\n- Overridden rule\n"
+)
+SECTION_LAYER = (
+ "# Layer — Demo\n[ID: layer-demo]\n\n"
+ "The layer adds to the naming rules (`demo-naming`).\n\n"
+ "## Naming\n[EXTEND: demo-naming]\n\n- Prefix a layer name\n\n"
+ "## Render\n[OVERRIDE: demo-render]\n\n- Overriding rule\n\n"
+ "## Paging\n\n- Page every list\n"
+)
+SECTION_TITLE_ONLY = "# Other — Demo\n[ID: other-demo]\n\n- Rule under a bare title\n"
+SECTION_FILES = [
+ ("templates/core/demo.md", SECTION_BASE),
+ ("templates/backend/layer.md", SECTION_LAYER),
+ ("templates/data/other.md", SECTION_TITLE_ONLY),
+]
+SECTION_TEMPLATES = {
+ "templates/core/demo.md": ("base-demo", "Demo rules"),
+ "templates/backend/layer.md": ("backend-layer", "Layer rules"),
+ "templates/data/other.md": ("base-other", "Other rules"),
+}
+SECTION_KINDS = {"release": "Preparing a release"}
+SECTION_DECLINED = ["templates/core/demo.md#Optional"]
+SECTION_LEAD = "read them before the work starts"
+SECTION_PATH = re.compile(r"`(" + re.escape(SECTIONS_DIR) + r"/[^`]+)`")
+
+# The inline root file's own lines, which carry no rule.
+INLINE_OWN = (
+ BUILT_LINE,
+ "The adopted rules that apply on every task.",
+ "This agent loads no skills, so each task's procedures are here.",
+)
+
+
+def unfenced(text: str) -> list[str]:
+ """A Markdown text's lines outside its fences."""
+ kept: list[str] = []
+ fence: str | None = None
+ for line in text.splitlines():
+ run = FENCE_LINE.match(line)
+ if run:
+ mark = run.group(1)
+ if fence is None:
+ fence = mark
+ elif mark[0] == fence[0] and len(mark) >= len(fence):
+ fence = None
+ continue
+ if fence is None:
+ kept.append(line)
+ return kept
+
+
+def heading_blocks(text: str) -> list[tuple[tuple[str, ...], tuple[str, ...]]]:
+ """A Markdown text cut at each heading outside a fence: each block's
+ heading path and its non-blank lines that are not headings."""
+ blocks: list[tuple[tuple[str, ...], list[str]]] = [((), [])]
+ stack: list[tuple[int, str]] = []
+ fence: str | None = None
+ for line in text.splitlines():
+ run = FENCE_LINE.match(line)
+ heading = None if (fence or run) else LEVEL_HEADING.match(line)
+ if run:
+ mark = run.group(1)
+ if fence is None:
+ fence = mark
+ elif mark[0] == fence[0] and len(mark) >= len(fence):
+ fence = None
+ if heading:
+ level = len(heading.group(1))
+ while stack and stack[-1][0] >= level:
+ stack.pop()
+ stack.append((level, line))
+ blocks.append((tuple(h for _, h in stack), []))
+ elif line.strip():
+ blocks[-1][1].append(line)
+ return [(path, tuple(body)) for path, body in blocks]
+
+
+def adopted_lines(
+ files: Sequence[tuple[str, str]],
+ kinds: Mapping[str, str],
+ declined: Iterable[str] = (),
+) -> Counter[str]:
+ """Every rule line the inlined root file delivers, counted: the adopted
+ rule set the other modes carry."""
+ root = emit_build(files, kinds, declined, inline_skills=True)["AGENTS.md"]
+ rules = root.split("\n## Rules\n", 1)[1]
+ lines: Counter[str] = Counter()
+ for path, body in heading_blocks(rules):
+ lines.update(body)
+ # A procedure's heading names its kind, and its first line is the
+ # kind's description, which the emitter writes and no template does.
+ kind = path[-1][len("### ") :] if path and path[-1].startswith("### ") else ""
+ if len(path) == 2 and path[0] == "## Procedures" and kind in kinds:
+ lines[kinds[kind]] -= 1
+ for own in INLINE_OWN:
+ lines[own] -= 1 if lines[own] else 0
+ return +lines
+
+
+def section_findings(
+ files: Sequence[tuple[str, str]],
+ kinds: Mapping[str, str],
+ emitted: Mapping[str, str],
+ declined: Iterable[str] = (),
+) -> list[str]:
+ """What the section files emitted from `files` get wrong: a rule no file
+ holds, a line no adopted rule is, two copies of one block that differ, a
+ named section a file does not carry, and a root file that holds a rule
+ or maps a file other than once."""
+ declined = list(declined)
+ findings: list[str] = []
+ owed = adopted_lines(files, kinds, declined)
+ sections = {rel: text for rel, text in emitted.items() if rel != "AGENTS.md"}
+ seen: dict[tuple[str, ...], tuple[str, ...]] = {}
+ held: Counter[str] = Counter()
+ for rel in sorted(sections):
+ for path, body in heading_blocks(sections[rel]):
+ if path in seen and seen[path] != body:
+ findings.append(f"{rel}: its copy of {' > '.join(path)} differs")
+ elif path not in seen:
+ seen[path] = body
+ held.update(body)
+ findings += [f"no section file holds: {line}" for line in owed - held]
+ findings += [f"no adopted rule is: {line}" for line in held - owed]
+
+ rules = section_rules(files, declined)
+ for rel in sorted(sections):
+ lines = set(sections[rel].splitlines())
+ prose = "\n".join(unfenced(sections[rel]))
+ for name in sorted(set(re.findall(r"`([a-z0-9][a-z0-9-]*)`", prose))):
+ if name in rules and not set(rules[name]) <= lines:
+ findings.append(f"{rel} names `{name}` and does not carry it")
+
+ root = emitted.get("AGENTS.md", "")
+ mapped = Counter(SECTION_PATH.findall(root))
+ findings += [
+ f"the root file maps {rel} {mapped[rel]} times, owed once"
+ for rel in sorted(sections)
+ if mapped[rel] != 1
+ ]
+ findings += [
+ f"the root file maps {rel}, which is not emitted"
+ for rel in sorted(set(mapped) - set(sections))
+ ]
+ # The map's own header rows are the emitter's, and a template's table
+ # may share them.
+ in_root = [
+ line
+ for line in root.split("\n## Rules\n", 1)[-1].splitlines()
+ if owed[line] and line not in MAP_HEADER
+ ]
+ findings += [f"the root file holds a rule: {line}" for line in in_root]
+ if SECTION_LEAD not in " ".join(root.split()):
+ findings.append("the root file does not say to read a file on demand")
+ return findings
+
+
+def planted_section_findings() -> list[str]:
+ """What the planted templates' section files get wrong, beyond the
+ general findings: where each rule lands and what each file carries."""
+ emitted = emit_sections(SECTION_FILES, SECTION_TEMPLATES, SECTION_DECLINED)
+ root = emitted.get("AGENTS.md", "")
+ base = emitted.get(f"{SECTIONS_DIR}/base-demo/naming.md", "")
+ layer = emitted.get(f"{SECTIONS_DIR}/backend-layer/naming.md", "")
+ paging = emitted.get(f"{SECTIONS_DIR}/backend-layer/paging.md", "")
+ other = emitted.get(f"{SECTIONS_DIR}/base-other/other-demo.md", "")
+ everything = "\n".join(emitted.values())
+ owed = [
+ ("the overridden rule is replaced", "Overridden rule" not in everything),
+ ("the override is delivered", "Overriding rule" in everything),
+ ("the declined section is out", "Declined rule" not in everything),
+ ("the checked rule is left to its check", "check enforces" not in everything),
+ ("the check's command is kept", "ruff check ." in everything),
+ ("the procedure is out of the root file", "Tag the release" not in root),
+ ("the procedure has a file", "Tag the release" in everything),
+ (
+ "a section carries its extension, after it",
+ 0 <= base.find("Name by role") < base.find("Prefix a layer name"),
+ ),
+ (
+ "an extension carries the section it extends, before it",
+ 0 <= layer.find("Name by role") < layer.find("Prefix a layer name"),
+ ),
+ ("a section carries the rules under its title", "Title rule" in base),
+ ("a section carries what its title names", "Name by role" in paging),
+ ("a bare title gets a file", "Rule under a bare title" in other),
+ ("the map names a template's topic", "| Paging |" in root),
+ ("the map gives a template's description", "Layer rules" in root),
+ ("the model line names section files", "Model: root and sections" in root),
+ ]
+ findings = [label for label, ok in owed if not ok]
+ findings += section_findings(
+ SECTION_FILES, SECTION_KINDS, emitted, SECTION_DECLINED
+ )
+
+ # Each finding the check owes, planted: a file dropped, a copy edited,
+ # and a carried section left out.
+ controls = {
+ "a dropped file": {
+ rel: text for rel, text in emitted.items() if not rel.endswith("/paging.md")
+ },
+ "an edited copy": dict(
+ emitted,
+ **{
+ f"{SECTIONS_DIR}/backend-layer/paging.md": paging.replace(
+ "Title rule", "Edited rule"
+ )
+ },
+ ),
+ "a reference left alone": dict(
+ emitted,
+ **{
+ f"{SECTIONS_DIR}/backend-layer/paging.md": paging.replace(
+ "- Name by role\n", ""
+ )
+ },
+ ),
+ }
+ for label, mutated in controls.items():
+ if not section_findings(
+ SECTION_FILES, SECTION_KINDS, mutated, SECTION_DECLINED
+ ):
+ findings.append(f"{label} goes unreported")
+ return findings
+
+
+def check_sys_28() -> CheckResult:
+ seen = Inspected()
+ failures = [f" planted: {label}" for label in planted_section_findings()]
+ seen.count("planted section files", 1)
+
+ core_ids, entries, _ = load_manifest()
+ _, offered, catalogue = load_catalogue()
+ roots = [stack["id"] for stack in catalogue] + list(
+ opt_in_roots(core_ids, offered, catalogue)
+ )
+ seen.count("roots built as section files", len(roots))
+ kinds = task_kinds(
+ parse_manifest(read(os.path.join(ROOT, "templates", "manifest.yaml")))
+ )
+ names = template_names(entries)
+ files = 0
+ for root in roots:
+ chain = [
+ (path, read_file(path)) for path in resolve_chain(root, core_ids, entries)
+ ]
+ emitted = emit_sections(chain, names)
+ files += len(emitted)
+ failures += [
+ f" {root}: {finding}"
+ for finding in section_findings(chain, kinds, emitted)
+ ]
+ seen.count("section files emitted", files)
+
+ # Two runs of the real tool, under different hash seeds, over roots
+ # whose chains extend and name sections in another template.
+ trees: list[dict[str, bytes]] = []
+ work = tempfile.mkdtemp(prefix="sait-sections-")
+ try:
+ for seed in ("1", "2"):
+ out = os.path.join(work, seed)
+ proc = subprocess.run(
+ [
+ sys.executable,
+ os.path.join(ROOT, "tools", "resolve_chain.py"),
+ "--emit",
+ out,
+ "--sections",
+ "backend-auth",
+ "backend-database",
+ ],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ env=dict(os.environ, PYTHONHASHSEED=seed),
+ )
+ if proc.returncode != 0:
+ failures.append(
+ f" emit exited {proc.returncode}: "
+ f"{(proc.stdout + proc.stderr).strip()}"
+ )
+ return seen.failures() + failures, seen.notes()
+ trees.append(emitted_tree(out))
+ finally:
+ shutil.rmtree(work, ignore_errors=True)
+ seen.count("files emitted by the tool", trees[0])
+ if trees[0] != trees[1]:
+ differ = sorted(
+ set(trees[0]) ^ set(trees[1])
+ | {k for k in set(trees[0]) & set(trees[1]) if trees[0][k] != trees[1][k]}
+ )
+ failures.append(f" two runs differ in: {', '.join(differ)}")
+ return seen.failures() + failures, seen.notes()
diff --git a/tools/emit_context.py b/tools/emit_context.py
index 6b73a3e6..f27cf4f0 100644
--- a/tools/emit_context.py
+++ b/tools/emit_context.py
@@ -8,10 +8,14 @@
byte-identical files. The project's facts are slots the agent or the
interview fills, and a regeneration keeps what was filled.
+With `--sections` it builds one file per topic instead, each a heading of
+a template with every rule it needs, and a root file that maps each topic
+to its file, to be read when the work first touches it.
+
Run it through the resolver:
py tools/resolve_chain.py --emit [ ...]
- [--declined ] [--inline-skills] [--mirror ]
+ [--declined ] [--inline-skills | --sections] [--mirror ]
"""
from __future__ import annotations
@@ -21,7 +25,8 @@
import os
import re
from collections.abc import Collection, Iterable, Mapping, Sequence
-from typing import TypedDict, cast
+from dataclasses import dataclass, field
+from typing import NamedTuple, TypedDict, cast
from resolve_chain import (
FENCE_LINE,
@@ -32,6 +37,11 @@
)
SKILLS_DIR = ".agents/skills"
+
+# Where the section files go: one folder per template, named by its manifest
+# ID, so no emitted path names a template file.
+SECTIONS_DIR = ".agents/sections"
+
ROOT_FILE = "AGENTS.md"
RULES_HEADING = "## Rules"
@@ -50,6 +60,7 @@
BULLET_LINE = re.compile(r"^(\s*)(?:[-*+]|\d+\.)\s")
ID_TAG = re.compile(r"^\[ID:\s*([^\]]+?)\s*\]$")
OVERRIDE_TAG = re.compile(r"^\[OVERRIDE:\s*([^\]]+?)\s*\]$")
+EXTEND_TAG = re.compile(r"^\[EXTEND:\s*([^\]]+?)\s*\]$")
# The facts no template knows: the agent or the interview replaces each
# slot, and nothing else in the file.
@@ -73,6 +84,26 @@
"""
+# The facts' model line, which names how the rules are delivered.
+MODEL_LINE = "- Model: root and skills"
+SECTIONS_MODEL_LINE = "- Model: root and sections"
+
+# What the root file says of the section files. The map is read on demand:
+# an agent told to read every file at the start loads the whole chain, and
+# the section files would save nothing.
+SECTIONS_LEAD = [
+ "The adopted rules are in the section files below, one topic each. Do not",
+ "read them before the work starts. The first time the work touches a",
+ "section's topic, read its file; then apply every rule it holds.",
+]
+
+# The map's header rows, one table per template.
+MAP_HEADER = ["| When the work first touches | Read first |", "| --- | --- |"]
+
+# A section ID named in a rule's prose, in backticks.
+NAMED_ID = re.compile(r"`([a-z0-9][a-z0-9-]*)`")
+
+
class EmitError(Exception):
"""An emission refused rather than written."""
@@ -299,23 +330,35 @@ def _tidy(lines: Sequence[str]) -> list[str]:
return kept
-def _place(
+class Adopted(NamedTuple):
+ """One file of the chain as the project adopts it: its `path`, its
+ parsed `rows`, tag lines kept and declined ones dropped, and its `runs`,
+ each a load with the rows it keeps, an overridden section dropped and a
+ checked run cut to its command."""
+
+ path: str
+ rows: list[Row]
+ runs: list[tuple[str | None, list[Row]]]
+
+
+def _adopt(
files: Iterable[tuple[str, str]], declined: Collection[str]
-) -> tuple[list[str], dict[str, list[str]]]:
- """Split the chain into the root file's rows and each kind's rows."""
+) -> list[Adopted]:
+ """Each file of the chain as the project adopts it, in chain order."""
+ files = list(files)
parsed = [
[row for row in _blocks(text) if not _declined(row, path, declined)]
for path, text in files
]
overridden = _overridden(parsed)
- root: list[str] = []
- skills: dict[str, list[str]] = {}
- for adopted in parsed:
+ adopted: list[Adopted] = []
+ for (path, _), parsed_rows in zip(files, parsed):
rows = [
row
- for row in adopted
+ for row in parsed_rows
if not row["tag"] and row["section"] not in overridden
]
+ runs: list[tuple[str | None, list[Row]]] = []
i = 0
while i < len(rows):
load = rows[i]["load"]
@@ -325,6 +368,20 @@ def _place(
run = rows[i:j]
if load == LOAD_CHECK:
run = _checked(run)
+ runs.append((load, run))
+ i = j
+ adopted.append(Adopted(path, parsed_rows, runs))
+ return adopted
+
+
+def _place(
+ files: Iterable[tuple[str, str]], declined: Collection[str]
+) -> tuple[list[str], dict[str, list[str]]]:
+ """Split the chain into the root file's rows and each kind's rows."""
+ root: list[str] = []
+ skills: dict[str, list[str]] = {}
+ for adopted in _adopt(files, declined):
+ for load, run in adopted.runs:
if load is None or load == LOAD_CHECK:
# A template's title sits under the root file's `## Rules`.
root += [
@@ -340,7 +397,6 @@ def _place(
else r["line"]
for r in run
)
- i = j
root.append("")
return root, skills
@@ -415,6 +471,205 @@ def build(
return out
+# A topic's place in its template: the headings down to its own, the
+# template's title alone for the rules under the title.
+Key = tuple[tuple[int, str], ...]
+
+
+@dataclass
+class Topic:
+ """One heading under a template's title, with its subheadings, or the
+ rules under the title itself: the unit a section file is built around.
+
+ `order` is its place in the chain, `ids` the section IDs its rows sit
+ in, `extends` and `overrides` the IDs its tags name, and `names` the
+ adopted IDs its prose names.
+ """
+
+ order: int
+ path: str
+ key: Key
+ rows: list[Row] = field(default_factory=list)
+ ids: set[str] = field(default_factory=set)
+ extends: set[str] = field(default_factory=set)
+ overrides: set[str] = field(default_factory=set)
+ names: set[str] = field(default_factory=set)
+
+ def content(self) -> bool:
+ return any(r["line"].strip() and not r["heading"] for r in self.rows)
+
+
+def _topics(adopted: Iterable[Adopted]) -> list[Topic]:
+ """The adopted chain's topics, in chain order. One that holds no rule
+ gets no file, and a title with none still heads the files below it."""
+ topics: list[Topic] = []
+ by_key: dict[tuple[str, Key], Topic] = {}
+ for one in adopted:
+ for _, run in one.runs:
+ for row in run:
+ at = (one.path, tuple(row["path"][:2]))
+ if at not in by_key:
+ by_key[at] = Topic(len(topics), one.path, at[1])
+ topics.append(by_key[at])
+ by_key[at].rows.append(row)
+
+ # A topic sits in the sections its rules do. The blank line
+ # between a heading and its `[ID:]` still belongs to the
+ # section before, and holds no rule of it.
+ if row["section"] and row["line"].strip() and not row["heading"]:
+ by_key[at].ids.add(row["section"])
+ for row in one.rows:
+ topic = by_key.get((one.path, tuple(row["path"][:2])))
+ if not row["tag"] or topic is None:
+ continue
+ for tag, into in (
+ (EXTEND_TAG, topic.extends),
+ (OVERRIDE_TAG, topic.overrides),
+ ):
+ match = tag.match(row["line"].strip())
+ if match:
+ into.add(match.group(1))
+ known = {i for topic in topics if topic.content() for i in topic.ids}
+ known |= {i for topic in topics for i in topic.overrides}
+ for topic in topics:
+ for row in topic.rows:
+ if not row["fence"]:
+ topic.names.update(NAMED_ID.findall(row["line"]))
+ topic.names = (topic.names & known) - topic.ids
+ return topics
+
+
+def _carried(topics: Sequence[Topic]) -> dict[int, list[Topic]]:
+ """Each topic's order mapped to what its section file carries, in chain
+ order: the topic, the rules under its template's title, the sections it
+ extends or names, the extensions of its own, and theirs in turn."""
+ holding: dict[str, list[Topic]] = {}
+ extending: dict[str, list[Topic]] = {}
+ for topic in topics:
+ for i in topic.ids | topic.overrides:
+ holding.setdefault(i, []).append(topic)
+ for i in topic.extends:
+ extending.setdefault(i, []).append(topic)
+
+ def needs(topic: Topic, whole: bool) -> list[tuple[Topic, bool]]:
+ # The rules under a title govern every heading beneath it.
+ found = [
+ (other, False)
+ for other in topics
+ if other.path == topic.path
+ and len(other.key) < len(topic.key)
+ and topic.key[: len(other.key)] == other.key
+ ]
+
+ # A section is read with the one it extends or names, since a rule
+ # left to a reference is one the agent never reads.
+ for i in sorted(topic.extends | topic.names):
+ found += [(other, True) for other in holding.get(i, [])]
+
+ # An extension applies on top of the section it extends, so it goes
+ # with that section's rules. Rules carried only because they govern
+ # a heading do not bring theirs: a title's ID runs to the next ID,
+ # and its extensions extend that run, not every heading below it.
+ if whole:
+ for i in sorted(topic.ids | topic.overrides):
+ found += [(other, True) for other in extending.get(i, [])]
+ return found
+
+ carried: dict[int, list[Topic]] = {}
+ for topic in topics:
+ seen = {topic.order: topic}
+ done: set[tuple[int, bool]] = set()
+ todo = [(topic, True)]
+ while todo:
+ current, whole = todo.pop()
+ if (current.order, whole) in done:
+ continue
+ done.add((current.order, whole))
+ for other, other_whole in needs(current, whole):
+ seen[other.order] = other
+ todo.append((other, other_whole))
+ carried[topic.order] = [seen[order] for order in sorted(seen)]
+ return carried
+
+
+def _slug(text: str) -> str:
+ return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") or "section"
+
+
+def build_sections(
+ files: Iterable[tuple[str, str]],
+ templates: Mapping[str, tuple[str, str]],
+ declined: Iterable[str] = (),
+) -> dict[str, str]:
+ """The root file and one section file per topic, as {relative path:
+ text}.
+
+ `files` is the chain as (path, text) pairs in resolution order,
+ `templates` maps each path to its manifest ID and description, and
+ `declined` holds the `path#Heading` entries the project does not adopt.
+ Every adopted rule is in a section file and none in the root file, which
+ maps each topic to its file.
+ """
+ topics = _topics(_adopt(files, set(declined)))
+ carried = _carried(topics)
+ headings = [topic for topic in topics if len(topic.key) == 2 and topic.content()]
+ governing = {
+ other.order
+ for topic in headings
+ for other in carried[topic.order]
+ if other.path == topic.path and len(other.key) < len(topic.key)
+ }
+
+ # A heading that holds a rule gets a file of its own. The rules under a
+ # title get one only where no such heading's file carries them.
+ owners = [
+ topic
+ for topic in topics
+ if topic.content() and (len(topic.key) == 2 or topic.order not in governing)
+ ]
+ out: dict[str, str] = {}
+ groups: dict[str, list[str]] = {}
+ for topic in owners:
+ if topic.path not in templates:
+ raise EmitError(f"{topic.path} has no manifest entry to name it by")
+ folder = f"{SECTIONS_DIR}/{templates[topic.path][0]}"
+ name = topic.key[-1][1] if topic.key else templates[topic.path][0]
+ rel = f"{folder}/{_slug(name)}.md"
+ suffix = 2
+ while rel in out:
+ rel = f"{folder}/{_slug(name)}-{suffix}.md"
+ suffix += 1
+ lines: list[str] = []
+ for other in carried[topic.order]:
+ lines += [r["line"] for r in other.rows] + [""]
+ out[rel] = "\n".join(_tidy(lines)) + "\n"
+ topic_cell = name.replace("|", "\\|")
+ groups.setdefault(topic.path, []).append(f"| {topic_cell} | `{rel}` |")
+
+ table: list[str] = []
+ for path, rows in groups.items():
+ first = next(t for t in topics if t.path == path)
+ title = first.key[0][1] if first.key else templates[path][0]
+ table += [f"### {title}", "", templates[path][1], ""] + MAP_HEADER + rows + [""]
+ head = [FACTS.replace(MODEL_LINE, SECTIONS_MODEL_LINE).rstrip("\n"), ""]
+ rules = [RULES_HEADING, "", BUILT_LINE, ""] + SECTIONS_LEAD + [""] + table
+ return {ROOT_FILE: "\n".join(_tidy(head + rules)) + "\n", **out}
+
+
+def section_rules(
+ files: Iterable[tuple[str, str]], declined: Iterable[str] = ()
+) -> dict[str, list[str]]:
+ """Each adopted section ID with its rule lines, the non-blank lines that
+ are not headings, in chain order."""
+ rules: dict[str, list[str]] = {}
+ for adopted in _adopt(files, set(declined)):
+ for _, run in adopted.runs:
+ for row in run:
+ if row["section"] and row["line"].strip() and not row["heading"]:
+ rules.setdefault(row["section"], []).append(row["line"])
+ return rules
+
+
def read_declined(path: str | None) -> list[str]:
"""The `path#Heading` entries of a declined list, one per line."""
if not path:
@@ -466,6 +721,13 @@ def _keep_facts(previous: str, emitted: str, recorded: Collection[str]) -> str:
)
facts = ("\n" + previous).split(marker, 1)[0][1:]
rules = ("\n" + emitted).split(marker, 1)[1]
+
+ # The model line is the emitter's, not a fact: a project that moves to
+ # section files, or back, gets the line that names what it now holds.
+ model, other = MODEL_LINE, SECTIONS_MODEL_LINE
+ if "\n" + other + "\n" in "\n" + emitted.split(marker, 1)[0]:
+ model, other = other, model
+ facts = ("\n" + facts).replace("\n" + other + "\n", "\n" + model + "\n")[1:]
return facts + marker[1:] + rules
diff --git a/tools/resolve_chain.py b/tools/resolve_chain.py
index 77573dab..acf3a0bb 100644
--- a/tools/resolve_chain.py
+++ b/tools/resolve_chain.py
@@ -10,7 +10,7 @@
py tools/resolve_chain.py --list # list available stack IDs
py tools/resolve_chain.py --roots # list every root a project picks
py tools/resolve_chain.py --emit ... # build the root file and skills
- [--declined ] [--inline-skills] [--mirror ]
+ [--declined ] [--inline-skills | --sections] [--mirror ]
The resolution algorithm follows ADR-004:
1. Add all core tier IDs
@@ -541,6 +541,7 @@ def check_generated(
"--emit",
"--declined",
"--inline-skills",
+ "--sections",
"--mirror",
}
@@ -548,6 +549,17 @@ def check_generated(
VALUE_FLAGS = ("--emit", "--declined", "--mirror")
+def template_names(entries: dict[str, Entry]) -> dict[str, tuple[str, str]]:
+ """Each template file's manifest ID and description, a live entry
+ before a deprecated one that names the same file."""
+ names: dict[str, tuple[str, str]] = {}
+ for live in (True, False):
+ for eid, entry in entries.items():
+ if "file" in entry and ("deprecated" not in entry) == live:
+ names.setdefault(entry["file"], (eid, entry.get("description", "")))
+ return names
+
+
def _emit(args: list[str], core_ids: Sequence[str], entries: dict[str, Entry]) -> None:
"""--emit: build a project's root file and skills from its roots.
@@ -585,12 +597,17 @@ def _emit(args: list[str], core_ids: Sequence[str], entries: dict[str, Entry]) -
kinds = task_kinds(parse_manifest(io.open(MANIFEST, encoding="utf-8").read()))
declined_paths = values.get("--declined")
declined = emit_context.read_declined(declined_paths[0] if declined_paths else None)
- emitted = emit_context.build(
- [(path, read_file(path)) for path in files],
- kinds,
- declined,
- inline_skills="--inline-skills" in args,
- )
+ chain = [(path, read_file(path)) for path in files]
+ if "--sections" in args:
+ if "--inline-skills" in args:
+ raise ResolveError(
+ "--sections and --inline-skills are two deliveries; pick one"
+ )
+ emitted = emit_context.build_sections(chain, template_names(entries), declined)
+ else:
+ emitted = emit_context.build(
+ chain, kinds, declined, inline_skills="--inline-skills" in args
+ )
out_dir = values["--emit"][0]
try:
written = emit_context.write(out_dir, emitted, values.get("--mirror", []))
From c5327a9bbac27b03dd66e8be3826df189e5fd2dd Mon Sep 17 00:00:00 2001
From: Branimir Georgiev <66906831+braboj@users.noreply.github.com>
Date: Sun, 15 Nov 2026 19:43:19 +0200
Subject: [PATCH 2/7] fix(emit): carry a section's relationships to its last
heading and override
Two faults in the section files, from the review of #2496:
- An `[EXTEND:]` or `[OVERRIDE:]` reached only the heading whose tags
named it, though a section runs to the next `[ID:]`. A later heading
in the same section now carries the section it extends, and that
section's file carries the later heading
- In a three-level override chain, the middle override's rows are all
replaced, so the link from the first ID to the last override was lost.
The relationships are now read before replaced rows are dropped, and
the last surviving override stands for every ID down the chain, so a
rule naming or extending the first ID carries it
SYS-28's planted templates gain both cases; each fails without its fix.
The root file and skills, inlined or not, stay byte-identical.
Part of #2466.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3
---
docs/tests/specs/SAIT-SMK-SYS-28-001A.md | 25 ++++++--
tests/smoke/system.py | 62 +++++++++++++++++-
tools/emit_context.py | 80 ++++++++++++++++++++----
3 files changed, 148 insertions(+), 19 deletions(-)
diff --git a/docs/tests/specs/SAIT-SMK-SYS-28-001A.md b/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
index 1a991cd8..721a8aa9 100644
--- a/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
+++ b/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
@@ -55,7 +55,9 @@ on two roots written to a temporary directory that is removed afterwards)
1. Build a planted base template, a planted layer that extends one of its
sections, overrides another and names the first in its title's rules,
and a planted template with rules under its title alone, declining one
- base section
+ base section; add a three-level override chain, each level declaring an
+ ID of its own, and a template whose extension runs past its heading to
+ the next ID, which names and extends the chain's first ID
2. Build every root `--roots` lists on its own, as section files and with
skills inlined
3. Cut every section file at its headings, keep one copy of each block,
@@ -72,16 +74,20 @@ on two roots written to a temporary directory that is removed afterwards)
absent, the checked rule is left to its check with its command kept,
and the procedure is in a section file and not in the root file
2. Assert a section's file carries its extension after it, and the
- extension's file carries the section before it
+ extension's file carries the section before it, for every heading the
+ extension's section runs over and for none after the next ID
3. Assert a file carries the rules under its template's title and every
section those name, and the bare title gets a file of its own
-4. Assert, for the planted chain and every root, that the lines held equal
+4. Assert each replaced level of the override chain is out, and a section
+ naming or extending its first ID carries the last override, which
+ carries that extension in turn
+5. Assert, for the planted chain and every root, that the lines held equal
the adopted lines, that two copies of a block never differ, and that a
file naming a section in backticks carries its rules
-5. Assert the root file maps each section file once, maps no other, holds
+6. Assert the root file maps each section file once, maps no other, holds
no rule line, and says not to read the files before the work starts
-6. Assert each planted fault is reported
-7. Assert the two runs write the same files with the same bytes
+7. Assert each planted fault is reported
+8. Assert the two runs write the same files with the same bytes
### Negative controls
@@ -93,6 +99,13 @@ on two roots written to a temporary directory that is removed afterwards)
3. **The planted faults.** A dropped file, an edited copy and a removed
carried section each fail the counts or the copy comparison; the check
runs all three on every run
+4. **A relationship tied to its heading.** With an extension or an
+ override given only to the heading whose tags name it, the extension's
+ second heading and the section it extends lack each other's rules, and
+ the check fails
+5. **An override chain cut short.** With an override's relationship read
+ only from the rows that survive, a section naming or extending the
+ chain's first ID lacks the last override, and the check fails
## Related
diff --git a/tests/smoke/system.py b/tests/smoke/system.py
index 17f9da77..1ea529ff 100644
--- a/tests/smoke/system.py
+++ b/tests/smoke/system.py
@@ -2563,7 +2563,9 @@ def check_sys_27() -> CheckResult:
"## Lint\n[LOAD: check]\n\n- Rule the check enforces\n\n- Run the linter:\n\n"
"```bash\nruff check .\n```\n\n"
"## Optional\n\n- Declined rule\n\n"
- "## Render\n[ID: demo-render]\n\n- Overridden rule\n"
+ "## Render\n[ID: demo-render]\n\n- Overridden rule\n\n"
+ "## Target\n[ID: demo-target]\n\n- Target rule\n\n"
+ "## Content\n[ID: demo-content]\n\n- Base content rule\n"
)
SECTION_LAYER = (
"# Layer — Demo\n[ID: layer-demo]\n\n"
@@ -2573,14 +2575,41 @@ def check_sys_27() -> CheckResult:
"## Paging\n\n- Page every list\n"
)
SECTION_TITLE_ONLY = "# Other — Demo\n[ID: other-demo]\n\n- Rule under a bare title\n"
+
+# Three levels of override, each declaring an ID of its own, as a section
+# that expects further specialisation does.
+SECTION_MID = (
+ "# Mid — Demo\n[ID: mid-demo]\n\n"
+ "## Content\n[ID: mid-content]\n[OVERRIDE: demo-content]\n\n- Mid content rule\n"
+)
+SECTION_TOP = (
+ "# Top — Demo\n[ID: top-demo]\n\n"
+ "## Content\n[ID: top-content]\n[OVERRIDE: mid-content]\n\n- Top content rule\n"
+)
+
+# An extension whose section runs past its heading to the next ID, a section
+# naming the base of the override chain, and an extension of that base.
+SECTION_MORE = (
+ "# More — Demo\n[ID: more-demo]\n\n"
+ "## First\n[EXTEND: demo-target]\n\n- First extension rule\n\n"
+ "## Second\n\n- Second extension rule\n\n"
+ "## Later\n[ID: more-later]\n\n- Follow the content rules (`demo-content`)\n\n"
+ "## Extra\n[EXTEND: demo-content]\n\n- Extra content rule\n"
+)
SECTION_FILES = [
("templates/core/demo.md", SECTION_BASE),
("templates/backend/layer.md", SECTION_LAYER),
+ ("templates/backend/mid.md", SECTION_MID),
+ ("templates/fixture/top.md", SECTION_TOP),
+ ("templates/fixture/more.md", SECTION_MORE),
("templates/data/other.md", SECTION_TITLE_ONLY),
]
SECTION_TEMPLATES = {
"templates/core/demo.md": ("base-demo", "Demo rules"),
"templates/backend/layer.md": ("backend-layer", "Layer rules"),
+ "templates/backend/mid.md": ("backend-mid", "Mid rules"),
+ "templates/fixture/top.md": ("stack-top", "Top rules"),
+ "templates/fixture/more.md": ("stack-more", "More rules"),
"templates/data/other.md": ("base-other", "Other rules"),
}
SECTION_KINDS = {"release": "Preparing a release"}
@@ -2729,6 +2758,11 @@ def planted_section_findings() -> list[str]:
layer = emitted.get(f"{SECTIONS_DIR}/backend-layer/naming.md", "")
paging = emitted.get(f"{SECTIONS_DIR}/backend-layer/paging.md", "")
other = emitted.get(f"{SECTIONS_DIR}/base-other/other-demo.md", "")
+ target = emitted.get(f"{SECTIONS_DIR}/base-demo/target.md", "")
+ second = emitted.get(f"{SECTIONS_DIR}/stack-more/second.md", "")
+ later = emitted.get(f"{SECTIONS_DIR}/stack-more/later.md", "")
+ extra = emitted.get(f"{SECTIONS_DIR}/stack-more/extra.md", "")
+ top = emitted.get(f"{SECTIONS_DIR}/stack-top/content.md", "")
everything = "\n".join(emitted.values())
owed = [
("the overridden rule is replaced", "Overridden rule" not in everything),
@@ -2752,6 +2786,32 @@ def planted_section_findings() -> list[str]:
("the map names a template's topic", "| Paging |" in root),
("the map gives a template's description", "Layer rules" in root),
("the model line names section files", "Model: root and sections" in root),
+ (
+ "a section carries an extension's heading up to the next ID",
+ "Second extension rule" in target,
+ ),
+ (
+ "an extension's later heading carries the section it extends",
+ "Target rule" in second,
+ ),
+ ("an extension ends at the next ID", "Target rule" not in later),
+ (
+ "each replaced level of an override chain is out",
+ "Base content rule" not in everything
+ and "Mid content rule" not in everything,
+ ),
+ (
+ "a section naming an overridden ID carries its last override",
+ "Top content rule" in later,
+ ),
+ (
+ "an extension of an overridden ID carries its last override, before it",
+ 0 <= extra.find("Top content rule") < extra.find("Extra content rule"),
+ ),
+ (
+ "the last override carries the extension of the ID it replaces",
+ 0 <= top.find("Top content rule") < top.find("Extra content rule"),
+ ),
]
findings = [label for label, ok in owed if not ok]
findings += section_findings(
diff --git a/tools/emit_context.py b/tools/emit_context.py
index f27cf4f0..67704b49 100644
--- a/tools/emit_context.py
+++ b/tools/emit_context.py
@@ -499,7 +499,56 @@ def content(self) -> bool:
return any(r["line"].strip() and not r["heading"] for r in self.rows)
-def _topics(adopted: Iterable[Adopted]) -> list[Topic]:
+def _relate(
+ one: Adopted,
+ by_key: Mapping[tuple[str, Key], Topic],
+ replaced: dict[str, set[str]],
+) -> None:
+ """Give every topic of one file the IDs its section extends and
+ overrides, and record in `replaced` each overridden ID with the IDs the
+ overrides that replace it declare.
+
+ A section runs from its tags to the next `[ID:]`, not to the next
+ heading, so a heading with no tags of its own stays in the section
+ above it. The rows of a replaced section still count here, since an
+ override chain is read through them.
+ """
+ extends: set[str] = set()
+ overrides: set[str] = set()
+ fresh = False
+ declared: str | None = None
+ for row in one.rows:
+ if row["heading"]:
+ fresh, declared = True, None
+ continue
+ line = row["line"].strip()
+ if row["tag"]:
+ for pattern in (ID_TAG, EXTEND_TAG, OVERRIDE_TAG):
+ match = pattern.match(line)
+ if not match:
+ continue
+
+ # The first relationship under a heading opens a section.
+ if fresh:
+ extends, overrides, fresh = set(), set(), False
+ if pattern is ID_TAG:
+ declared = match.group(1)
+ elif pattern is EXTEND_TAG:
+ extends.add(match.group(1))
+ else:
+ overrides.add(match.group(1))
+ if declared:
+ replaced.setdefault(match.group(1), set()).add(declared)
+ continue
+ if line:
+ fresh = False
+ topic = by_key.get((one.path, tuple(row["path"][:2])))
+ if topic is not None:
+ topic.extends |= extends
+ topic.overrides |= overrides
+
+
+def _topics(adopted: Sequence[Adopted]) -> list[Topic]:
"""The adopted chain's topics, in chain order. One that holds no rule
gets no file, and a title with none still heads the files below it."""
topics: list[Topic] = []
@@ -518,17 +567,24 @@ def _topics(adopted: Iterable[Adopted]) -> list[Topic]:
# section before, and holds no rule of it.
if row["section"] and row["line"].strip() and not row["heading"]:
by_key[at].ids.add(row["section"])
- for row in one.rows:
- topic = by_key.get((one.path, tuple(row["path"][:2])))
- if not row["tag"] or topic is None:
- continue
- for tag, into in (
- (EXTEND_TAG, topic.extends),
- (OVERRIDE_TAG, topic.overrides),
- ):
- match = tag.match(row["line"].strip())
- if match:
- into.add(match.group(1))
+ replaced: dict[str, set[str]] = {}
+ for one in adopted:
+ _relate(one, by_key, replaced)
+
+ # An override that declares an ID of its own may be overridden in turn,
+ # and then none of its rows survive to hold the ID it replaced. The last
+ # surviving replacement stands for every ID down the chain, so a rule
+ # that names or extends the first still finds it.
+ for topic in topics:
+ stands = topic.ids | topic.overrides
+ grown = True
+ while grown:
+ grown = False
+ for old, new in replaced.items():
+ if old not in stands and new & stands:
+ stands.add(old)
+ grown = True
+ topic.overrides |= stands - topic.ids
known = {i for topic in topics if topic.content() for i in topic.ids}
known |= {i for topic in topics for i in topic.overrides}
for topic in topics:
From 2bcafb73d613747a32834bb9438d2dcdf1b66700 Mon Sep 17 00:00:00 2001
From: Branimir Georgiev <66906831+braboj@users.noreply.github.com>
Date: Sun, 15 Nov 2026 20:09:05 +0200
Subject: [PATCH 3/7] fix(emit): follow a section's own ID, and relate only
surviving rules
Two more faults in the section files, from the second review of #2496:
- A heading that named its own section's ID dropped the name, though an
ID can run over several headings. A later heading naming it now
carries the section's other headings; the visited set stops cycles
- A relationship reached rows it does not govern: the blank line between
a heading and its new `[ID:]`, and the rows of a replaced subsection.
Only a surviving rule line now takes one; a replaced section's tags
still feed the override chain
SYS-28's planted templates gain the three cases; each fails without its
fix. The root file and skills, inlined or not, stay byte-identical.
Part of #2466.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3
---
docs/tests/specs/SAIT-SMK-SYS-28-001A.md | 18 +++++++++++++++---
tests/smoke/system.py | 24 ++++++++++++++++++++++--
tools/emit_context.py | 20 ++++++++++++++------
3 files changed, 51 insertions(+), 11 deletions(-)
diff --git a/docs/tests/specs/SAIT-SMK-SYS-28-001A.md b/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
index 721a8aa9..e7f66851 100644
--- a/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
+++ b/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
@@ -57,7 +57,9 @@ on two roots written to a temporary directory that is removed afterwards)
and a planted template with rules under its title alone, declining one
base section; add a three-level override chain, each level declaring an
ID of its own, and a template whose extension runs past its heading to
- the next ID, which names and extends the chain's first ID
+ the next ID, which names and extends the chain's first ID; add a section
+ whose ID a later heading names, a heading whose ID follows a blank line,
+ and an overridden subsection that carries an extension
2. Build every root `--roots` lists on its own, as section files and with
skills inlined
3. Cut every section file at its headings, keep one copy of each block,
@@ -75,9 +77,12 @@ on two roots written to a temporary directory that is removed afterwards)
and the procedure is in a section file and not in the root file
2. Assert a section's file carries its extension after it, and the
extension's file carries the section before it, for every heading the
- extension's section runs over and for none after the next ID
+ extension's section runs over and for none after the next ID, nor for
+ a heading whose ID follows a blank line
3. Assert a file carries the rules under its template's title and every
- section those name, and the bare title gets a file of its own
+ section those name, a heading naming its own section's ID carries the
+ section's other headings, a replaced subsection's extension stays out of
+ the heading above it, and the bare title gets a file of its own
4. Assert each replaced level of the override chain is out, and a section
naming or extending its first ID carries the last override, which
carries that extension in turn
@@ -106,6 +111,13 @@ on two roots written to a temporary directory that is removed afterwards)
5. **An override chain cut short.** With an override's relationship read
only from the rows that survive, a section naming or extending the
chain's first ID lacks the last override, and the check fails
+6. **A name of its own dropped.** With a heading's own IDs taken out of the
+ IDs it names, a later heading naming its section's ID lacks the
+ section's first heading, and the check fails
+7. **Every row relating.** With a blank row or a replaced row given the
+ current relationship, a heading whose ID follows a blank line, and the
+ heading above a replaced subsection, become extensions, and the check
+ fails
## Related
diff --git a/tests/smoke/system.py b/tests/smoke/system.py
index 1ea529ff..be571e57 100644
--- a/tests/smoke/system.py
+++ b/tests/smoke/system.py
@@ -2565,14 +2565,19 @@ def check_sys_27() -> CheckResult:
"## Optional\n\n- Declined rule\n\n"
"## Render\n[ID: demo-render]\n\n- Overridden rule\n\n"
"## Target\n[ID: demo-target]\n\n- Target rule\n\n"
- "## Content\n[ID: demo-content]\n\n- Base content rule\n"
+ "## Content\n[ID: demo-content]\n\n- Base content rule\n\n"
+ "## Shared\n[ID: demo-shared]\n\n- Shared first rule\n\n"
+ "## Follow\n\n- Follow the rules of `demo-shared`\n\n"
+ "## Parent\n[ID: demo-parent]\n\n- Parent rule\n\n"
+ "### Child\n[ID: demo-child]\n[EXTEND: demo-naming]\n\n- Child rule\n"
)
SECTION_LAYER = (
"# Layer — Demo\n[ID: layer-demo]\n\n"
"The layer adds to the naming rules (`demo-naming`).\n\n"
"## Naming\n[EXTEND: demo-naming]\n\n- Prefix a layer name\n\n"
"## Render\n[OVERRIDE: demo-render]\n\n- Overriding rule\n\n"
- "## Paging\n\n- Page every list\n"
+ "## Paging\n\n- Page every list\n\n"
+ "## Child\n[ID: layer-child]\n[OVERRIDE: demo-child]\n\n- Child replaced\n"
)
SECTION_TITLE_ONLY = "# Other — Demo\n[ID: other-demo]\n\n- Rule under a bare title\n"
@@ -2593,6 +2598,7 @@ def check_sys_27() -> CheckResult:
"# More — Demo\n[ID: more-demo]\n\n"
"## First\n[EXTEND: demo-target]\n\n- First extension rule\n\n"
"## Second\n\n- Second extension rule\n\n"
+ "## Fresh\n\n[ID: more-fresh]\n\n- Fresh rule\n\n"
"## Later\n[ID: more-later]\n\n- Follow the content rules (`demo-content`)\n\n"
"## Extra\n[EXTEND: demo-content]\n\n- Extra content rule\n"
)
@@ -2761,6 +2767,8 @@ def planted_section_findings() -> list[str]:
target = emitted.get(f"{SECTIONS_DIR}/base-demo/target.md", "")
second = emitted.get(f"{SECTIONS_DIR}/stack-more/second.md", "")
later = emitted.get(f"{SECTIONS_DIR}/stack-more/later.md", "")
+ fresh = emitted.get(f"{SECTIONS_DIR}/stack-more/fresh.md", "")
+ follow = emitted.get(f"{SECTIONS_DIR}/base-demo/follow.md", "")
extra = emitted.get(f"{SECTIONS_DIR}/stack-more/extra.md", "")
top = emitted.get(f"{SECTIONS_DIR}/stack-top/content.md", "")
everything = "\n".join(emitted.values())
@@ -2795,6 +2803,18 @@ def planted_section_findings() -> list[str]:
"Target rule" in second,
),
("an extension ends at the next ID", "Target rule" not in later),
+ (
+ "a heading whose ID follows a blank line extends nothing",
+ "Target rule" not in fresh and "Fresh rule" not in target,
+ ),
+ (
+ "a heading naming its own section's ID carries its other headings",
+ "Shared first rule" in follow,
+ ),
+ (
+ "a replaced subsection's relationship stays out of its heading",
+ "Parent rule" not in base and "Child rule" not in everything,
+ ),
(
"each replaced level of an override chain is out",
"Base content rule" not in everything
diff --git a/tools/emit_context.py b/tools/emit_context.py
index 67704b49..9dbc5260 100644
--- a/tools/emit_context.py
+++ b/tools/emit_context.py
@@ -510,9 +510,12 @@ def _relate(
A section runs from its tags to the next `[ID:]`, not to the next
heading, so a heading with no tags of its own stays in the section
- above it. The rows of a replaced section still count here, since an
- override chain is read through them.
+ above it. A replaced section's tags still count, since an override
+ chain is read through them, but only a surviving rule line takes a
+ relationship: a blank line under a heading comes before its tags, and a
+ replaced subsection's rows are not its heading's.
"""
+ kept = {id(row) for _, run in one.runs for row in run}
extends: set[str] = set()
overrides: set[str] = set()
fresh = False
@@ -540,10 +543,11 @@ def _relate(
if declared:
replaced.setdefault(match.group(1), set()).add(declared)
continue
- if line:
- fresh = False
+ if not line:
+ continue
+ fresh = False
topic = by_key.get((one.path, tuple(row["path"][:2])))
- if topic is not None:
+ if topic is not None and id(row) in kept:
topic.extends |= extends
topic.overrides |= overrides
@@ -591,7 +595,11 @@ def _topics(adopted: Sequence[Adopted]) -> list[Topic]:
for row in topic.rows:
if not row["fence"]:
topic.names.update(NAMED_ID.findall(row["line"]))
- topic.names = (topic.names & known) - topic.ids
+
+ # An ID can run over several headings, so a heading that names its
+ # own section's ID still needs the others; the topic itself is
+ # already carried.
+ topic.names &= known
return topics
From d53326ad0d98286206f4d015a14a503282d4cf51 Mon Sep 17 00:00:00 2001
From: Branimir Georgiev <66906831+braboj@users.noreply.github.com>
Date: Sun, 15 Nov 2026 20:31:22 +0200
Subject: [PATCH 4/7] fix(emit): read a section's relationships before
declining or replacing
Two more faults in the section files, from the third review of #2496,
both relationship bookkeeping read after rows were filtered out:
- Declining a heading dropped its tags before the relationships were
read, so an extension that opens at a declined heading no longer
reached its adopted siblings. The extent of each section is now read
from every parsed row; only which rules are delivered is filtered. A
declined override still replaces nothing and relates nothing
- An override was recorded only against an ID its own heading declared,
so one under an untagged heading inside its title's section was lost
when a later template overrode that section. It is now recorded
against the section it sits in, declared or inherited
SYS-28's planted templates gain both cases; each fails without its fix.
The root file and skills, inlined or not, stay byte-identical.
Part of #2466.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3
---
docs/tests/specs/SAIT-SMK-SYS-28-001A.md | 16 ++++++--
tests/smoke/system.py | 35 +++++++++++++++++-
tools/emit_context.py | 47 ++++++++++++++----------
3 files changed, 72 insertions(+), 26 deletions(-)
diff --git a/docs/tests/specs/SAIT-SMK-SYS-28-001A.md b/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
index e7f66851..dc771897 100644
--- a/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
+++ b/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
@@ -59,7 +59,9 @@ on two roots written to a temporary directory that is removed afterwards)
ID of its own, and a template whose extension runs past its heading to
the next ID, which names and extends the chain's first ID; add a section
whose ID a later heading names, a heading whose ID follows a blank line,
- and an overridden subsection that carries an extension
+ and an overridden subsection that carries an extension; decline an
+ extension's first heading, and add a two-level override whose first
+ level sits under a heading inside its title's section
2. Build every root `--roots` lists on its own, as section files and with
skills inlined
3. Cut every section file at its headings, keep one copy of each block,
@@ -77,15 +79,17 @@ on two roots written to a temporary directory that is removed afterwards)
and the procedure is in a section file and not in the root file
2. Assert a section's file carries its extension after it, and the
extension's file carries the section before it, for every heading the
- extension's section runs over and for none after the next ID, nor for
- a heading whose ID follows a blank line
+ extension's section runs over, its first heading declined or not, and
+ for none after the next ID, nor for a heading whose ID follows a blank
+ line
3. Assert a file carries the rules under its template's title and every
section those name, a heading naming its own section's ID carries the
section's other headings, a replaced subsection's extension stays out of
the heading above it, and the bare title gets a file of its own
4. Assert each replaced level of the override chain is out, and a section
naming or extending its first ID carries the last override, which
- carries that extension in turn
+ carries that extension in turn, also where an override sits in a
+ section its heading inherits
5. Assert, for the planted chain and every root, that the lines held equal
the adopted lines, that two copies of a block never differ, and that a
file naming a section in backticks carries its rules
@@ -118,6 +122,10 @@ on two roots written to a temporary directory that is removed afterwards)
current relationship, a heading whose ID follows a blank line, and the
heading above a replaced subsection, become extensions, and the check
fails
+8. **Relationships read after filtering.** With a section's extent read
+ from the declined-filtered rows, or an override recorded only against
+ an ID its own heading declares, the declined heading's sibling and the
+ section naming the overridden ID lack their rules, and the check fails
## Related
diff --git a/tests/smoke/system.py b/tests/smoke/system.py
index be571e57..1f2e8b61 100644
--- a/tests/smoke/system.py
+++ b/tests/smoke/system.py
@@ -2566,6 +2566,7 @@ def check_sys_27() -> CheckResult:
"## Render\n[ID: demo-render]\n\n- Overridden rule\n\n"
"## Target\n[ID: demo-target]\n\n- Target rule\n\n"
"## Content\n[ID: demo-content]\n\n- Base content rule\n\n"
+ "## Theme\n[ID: demo-theme]\n\n- Base theme rule\n\n"
"## Shared\n[ID: demo-shared]\n\n- Shared first rule\n\n"
"## Follow\n\n- Follow the rules of `demo-shared`\n\n"
"## Parent\n[ID: demo-parent]\n\n- Parent rule\n\n"
@@ -2599,14 +2600,29 @@ def check_sys_27() -> CheckResult:
"## First\n[EXTEND: demo-target]\n\n- First extension rule\n\n"
"## Second\n\n- Second extension rule\n\n"
"## Fresh\n\n[ID: more-fresh]\n\n- Fresh rule\n\n"
- "## Later\n[ID: more-later]\n\n- Follow the content rules (`demo-content`)\n\n"
+ "## Gone\n[EXTEND: demo-naming]\n\n- Gone rule\n\n"
+ "## Kept\n\n- Kept rule\n\n"
+ "## Later\n[ID: more-later]\n\n- Follow the content rules (`demo-content`)\n"
+ "- Follow the theme rules (`demo-theme`)\n\n"
"## Extra\n[EXTEND: demo-content]\n\n- Extra content rule\n"
)
+# Two levels of override where the first sits under a heading with no ID
+# of its own, inside its title's section, which the second overrides.
+SECTION_SKIN = (
+ "# Skin — Demo\n[ID: skin-demo]\n\n"
+ "## Theme\n[OVERRIDE: demo-theme]\n\n- Skin theme rule\n"
+)
+SECTION_BRAND = (
+ "# Brand — Demo\n[ID: brand-demo]\n\n"
+ "## Skin\n[OVERRIDE: skin-demo]\n\n- Brand theme rule\n"
+)
SECTION_FILES = [
("templates/core/demo.md", SECTION_BASE),
("templates/backend/layer.md", SECTION_LAYER),
("templates/backend/mid.md", SECTION_MID),
("templates/fixture/top.md", SECTION_TOP),
+ ("templates/backend/skin.md", SECTION_SKIN),
+ ("templates/fixture/brand.md", SECTION_BRAND),
("templates/fixture/more.md", SECTION_MORE),
("templates/data/other.md", SECTION_TITLE_ONLY),
]
@@ -2615,11 +2631,13 @@ def check_sys_27() -> CheckResult:
"templates/backend/layer.md": ("backend-layer", "Layer rules"),
"templates/backend/mid.md": ("backend-mid", "Mid rules"),
"templates/fixture/top.md": ("stack-top", "Top rules"),
+ "templates/backend/skin.md": ("backend-skin", "Skin rules"),
+ "templates/fixture/brand.md": ("stack-brand", "Brand rules"),
"templates/fixture/more.md": ("stack-more", "More rules"),
"templates/data/other.md": ("base-other", "Other rules"),
}
SECTION_KINDS = {"release": "Preparing a release"}
-SECTION_DECLINED = ["templates/core/demo.md#Optional"]
+SECTION_DECLINED = ["templates/core/demo.md#Optional", "templates/fixture/more.md#Gone"]
SECTION_LEAD = "read them before the work starts"
SECTION_PATH = re.compile(r"`(" + re.escape(SECTIONS_DIR) + r"/[^`]+)`")
@@ -2768,6 +2786,7 @@ def planted_section_findings() -> list[str]:
second = emitted.get(f"{SECTIONS_DIR}/stack-more/second.md", "")
later = emitted.get(f"{SECTIONS_DIR}/stack-more/later.md", "")
fresh = emitted.get(f"{SECTIONS_DIR}/stack-more/fresh.md", "")
+ kept = emitted.get(f"{SECTIONS_DIR}/stack-more/kept.md", "")
follow = emitted.get(f"{SECTIONS_DIR}/base-demo/follow.md", "")
extra = emitted.get(f"{SECTIONS_DIR}/stack-more/extra.md", "")
top = emitted.get(f"{SECTIONS_DIR}/stack-top/content.md", "")
@@ -2803,6 +2822,18 @@ def planted_section_findings() -> list[str]:
"Target rule" in second,
),
("an extension ends at the next ID", "Target rule" not in later),
+ (
+ "a declined heading's relationship reaches its adopted siblings",
+ "Name by role" in kept
+ and "Kept rule" in base
+ and "Gone rule" not in everything,
+ ),
+ (
+ "an override under an untagged heading is replaced through its section",
+ "Brand theme rule" in later
+ and "Skin theme rule" not in everything
+ and "Base theme rule" not in everything,
+ ),
(
"a heading whose ID follows a blank line extends nothing",
"Target rule" not in fresh and "Fresh rule" not in target,
diff --git a/tools/emit_context.py b/tools/emit_context.py
index 9dbc5260..68f17d1f 100644
--- a/tools/emit_context.py
+++ b/tools/emit_context.py
@@ -331,13 +331,15 @@ def _tidy(lines: Sequence[str]) -> list[str]:
class Adopted(NamedTuple):
- """One file of the chain as the project adopts it: its `path`, its
- parsed `rows`, tag lines kept and declined ones dropped, and its `runs`,
- each a load with the rows it keeps, an overridden section dropped and a
- checked run cut to its command."""
+ """One file of the chain as the project adopts it: its `path`, every
+ parsed row in `rows`, tag lines and declined ones included, the
+ `declined` rows by identity, and its `runs`, each a load with the rows
+ it keeps, a declined or overridden section dropped and a checked run cut
+ to its command."""
path: str
rows: list[Row]
+ declined: set[int]
runs: list[tuple[str | None, list[Row]]]
@@ -346,13 +348,14 @@ def _adopt(
) -> list[Adopted]:
"""Each file of the chain as the project adopts it, in chain order."""
files = list(files)
+ every = [_blocks(text) for _, text in files]
parsed = [
- [row for row in _blocks(text) if not _declined(row, path, declined)]
- for path, text in files
+ [row for row in rows if not _declined(row, path, declined)]
+ for (path, _), rows in zip(files, every)
]
overridden = _overridden(parsed)
adopted: list[Adopted] = []
- for (path, _), parsed_rows in zip(files, parsed):
+ for (path, _), all_rows, parsed_rows in zip(files, every, parsed):
rows = [
row
for row in parsed_rows
@@ -370,7 +373,8 @@ def _adopt(
run = _checked(run)
runs.append((load, run))
i = j
- adopted.append(Adopted(path, parsed_rows, runs))
+ gone = {id(row) for row in all_rows} - {id(row) for row in parsed_rows}
+ adopted.append(Adopted(path, all_rows, gone, runs))
return adopted
@@ -510,19 +514,20 @@ def _relate(
A section runs from its tags to the next `[ID:]`, not to the next
heading, so a heading with no tags of its own stays in the section
- above it. A replaced section's tags still count, since an override
- chain is read through them, but only a surviving rule line takes a
- relationship: a blank line under a heading comes before its tags, and a
- replaced subsection's rows are not its heading's.
+ above it. Where a section runs is read from every row, declined and
+ replaced ones too, and which rules it reaches from the delivered ones:
+ only a surviving rule line takes a relationship, since a blank line
+ under a heading comes before its tags, and a replaced subsection's rows
+ are not its heading's. A declined override replaces nothing, so it
+ relates nothing.
"""
kept = {id(row) for _, run in one.runs for row in run}
extends: set[str] = set()
overrides: set[str] = set()
fresh = False
- declared: str | None = None
for row in one.rows:
if row["heading"]:
- fresh, declared = True, None
+ fresh = True
continue
line = row["line"].strip()
if row["tag"]:
@@ -534,14 +539,16 @@ def _relate(
# The first relationship under a heading opens a section.
if fresh:
extends, overrides, fresh = set(), set(), False
- if pattern is ID_TAG:
- declared = match.group(1)
- elif pattern is EXTEND_TAG:
+ if pattern is EXTEND_TAG:
extends.add(match.group(1))
- else:
+ elif pattern is OVERRIDE_TAG and id(row) not in one.declined:
overrides.add(match.group(1))
- if declared:
- replaced.setdefault(match.group(1), set()).add(declared)
+
+ # An override replaces with the section it sits in,
+ # whether its heading declares that ID or inherits it
+ # from a heading above.
+ if row["section"]:
+ replaced.setdefault(match.group(1), set()).add(row["section"])
continue
if not line:
continue
From e1248fad5257f22bc1742499678ff6b97842cb64 Mon Sep 17 00:00:00 2001
From: Branimir Georgiev <66906831+braboj@users.noreply.github.com>
Date: Sun, 15 Nov 2026 20:56:32 +0200
Subject: [PATCH 5/7] fix(emit): govern a heading by its title's override, and
check every relationship
From the fourth review of #2496: where a later template overrides a
title's ID while the title's headings keep IDs of their own, the title's
rules are removed, and the headings' files carried neither them nor
their replacement. A heading under an overridden title is now governed
by the override that replaces it, read from the unfiltered rows.
SYS-28 gains a generic property, a reading of the unfiltered chain apart
from the emitter's: every file carrying a heading must hold what each of
its relationships owes, the rules under its title, each section its
section extends and each ID its prose names, each resolved through the
overrides to what survives. Run against each earlier version of the
mode, it alone reports every omission the four reviews found.
The root file and skills, inlined or not, stay byte-identical.
Part of #2466.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3
---
docs/tests/specs/SAIT-SMK-SYS-28-001A.md | 22 +++-
tests/smoke/system.py | 145 +++++++++++++++++++++++
tools/emit_context.py | 27 ++++-
3 files changed, 187 insertions(+), 7 deletions(-)
diff --git a/docs/tests/specs/SAIT-SMK-SYS-28-001A.md b/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
index dc771897..814798d0 100644
--- a/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
+++ b/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
@@ -61,7 +61,8 @@ on two roots written to a temporary directory that is removed afterwards)
whose ID a later heading names, a heading whose ID follows a blank line,
and an overridden subsection that carries an extension; decline an
extension's first heading, and add a two-level override whose first
- level sits under a heading inside its title's section
+ level sits under a heading inside its title's section, and a title a
+ later template overrides while its headings keep IDs of their own
2. Build every root `--roots` lists on its own, as section files and with
skills inlined
3. Cut every section file at its headings, keep one copy of each block,
@@ -83,7 +84,8 @@ on two roots written to a temporary directory that is removed afterwards)
for none after the next ID, nor for a heading whose ID follows a blank
line
3. Assert a file carries the rules under its template's title and every
- section those name, a heading naming its own section's ID carries the
+ section those name, a heading under an overridden title carries the
+ override's rules, a heading naming its own section's ID carries the
section's other headings, a replaced subsection's extension stays out of
the heading above it, and the bare title gets a file of its own
4. Assert each replaced level of the override chain is out, and a section
@@ -93,10 +95,15 @@ on two roots written to a temporary directory that is removed afterwards)
5. Assert, for the planted chain and every root, that the lines held equal
the adopted lines, that two copies of a block never differ, and that a
file naming a section in backticks carries its rules
-6. Assert the root file maps each section file once, maps no other, holds
+6. Assert, by a reading of the unfiltered chain apart from the emitter's,
+ that every file carrying a heading holds what each of its relationships
+ owes: the rules under its title, each section its section extends, and
+ each ID its prose names, each resolved to the rules that survive for
+ it, its own or those of the override that replaces it, down the chain
+7. Assert the root file maps each section file once, maps no other, holds
no rule line, and says not to read the files before the work starts
-7. Assert each planted fault is reported
-8. Assert the two runs write the same files with the same bytes
+8. Assert each planted fault is reported
+9. Assert the two runs write the same files with the same bytes
### Negative controls
@@ -126,6 +133,11 @@ on two roots written to a temporary directory that is removed afterwards)
from the declined-filtered rows, or an override recorded only against
an ID its own heading declares, the declined heading's sibling and the
section naming the overridden ID lack their rules, and the check fails
+9. **The earlier emitters.** Run against each earlier version of the
+ section mode, the reading of the unfiltered chain alone reports every
+ omission later fixed: an extension past its heading, a declined first
+ heading, an override chain, a heading naming its own section's ID, and
+ an overridden title
## Related
diff --git a/tests/smoke/system.py b/tests/smoke/system.py
index 1f2e8b61..6a75e0ff 100644
--- a/tests/smoke/system.py
+++ b/tests/smoke/system.py
@@ -14,6 +14,11 @@
# so a fork's own key is read here exactly as it is resolved there.
from emit_context import EmitError
from emit_context import BUILT_LINE, MAP_HEADER, SECTIONS_DIR, section_rules
+from emit_context import EXTEND_TAG, ID_TAG, OVERRIDE_TAG
+
+# The emitter's line parser, which only reads a template; the reference
+# reading of a chain's relationships in SYS-28 is the check's own.
+from emit_context import _blocks as parse_rows
from emit_context import build as emit_build
from emit_context import build_sections as emit_sections
from emit_context import write as emit_write
@@ -2616,13 +2621,24 @@ def check_sys_27() -> CheckResult:
"# Brand — Demo\n[ID: brand-demo]\n\n"
"## Skin\n[OVERRIDE: skin-demo]\n\n- Brand theme rule\n"
)
+# A title whose ID a later template overrides, while its headings keep
+# IDs of their own and stay.
+SECTION_FACADE = (
+ "# Facade — Demo\n[ID: facade-demo]\n\nFacade title rule.\n\n"
+ "## Door\n[ID: facade-door]\n\n- Door rule\n"
+)
+SECTION_FRONT = (
+ "# Front — Demo\n[ID: front-demo]\n[OVERRIDE: facade-demo]\n\nFront title rule.\n"
+)
SECTION_FILES = [
("templates/core/demo.md", SECTION_BASE),
("templates/backend/layer.md", SECTION_LAYER),
("templates/backend/mid.md", SECTION_MID),
("templates/fixture/top.md", SECTION_TOP),
+ ("templates/backend/facade.md", SECTION_FACADE),
("templates/backend/skin.md", SECTION_SKIN),
("templates/fixture/brand.md", SECTION_BRAND),
+ ("templates/fixture/front.md", SECTION_FRONT),
("templates/fixture/more.md", SECTION_MORE),
("templates/data/other.md", SECTION_TITLE_ONLY),
]
@@ -2631,7 +2647,9 @@ def check_sys_27() -> CheckResult:
"templates/backend/layer.md": ("backend-layer", "Layer rules"),
"templates/backend/mid.md": ("backend-mid", "Mid rules"),
"templates/fixture/top.md": ("stack-top", "Top rules"),
+ "templates/backend/facade.md": ("backend-facade", "Facade rules"),
"templates/backend/skin.md": ("backend-skin", "Skin rules"),
+ "templates/fixture/front.md": ("stack-front", "Front rules"),
"templates/fixture/brand.md": ("stack-brand", "Brand rules"),
"templates/fixture/more.md": ("stack-more", "More rules"),
"templates/data/other.md": ("base-other", "Other rules"),
@@ -2715,6 +2733,126 @@ def adopted_lines(
return +lines
+class _Run:
+ """One override's section: the IDs it replaces, the sections its rows
+ sit in, and the rule lines it delivers."""
+
+ def __init__(self) -> None:
+ self.targets: set[str] = set()
+ self.sections: set[str] = set()
+ self.lines: set[str] = set()
+
+
+def relation_findings(
+ files: Sequence[tuple[str, str]],
+ declined: Iterable[str],
+ owed: Counter[str],
+ sections: Mapping[str, str],
+) -> list[str]:
+ """Each section file that lacks rules a relationship owes it.
+
+ A reference reading, apart from the emitter's: every relationship is
+ read from the unfiltered chain, the rules under a title, each section a
+ heading's section extends, and each ID its prose names, and each owes
+ the rules that survive for it, the ID's own or, where it is replaced,
+ those of the override that replaces it, followed down the chain. A file
+ carries a heading when it holds every rule the heading delivers.
+ """
+ gone_list = set(declined)
+ topics: dict[tuple[str, tuple[tuple[int, str], ...]], set[str]] = {}
+ extends_of: dict[tuple[str, tuple[tuple[int, str], ...]], set[str]] = {}
+ names_of: dict[tuple[str, tuple[tuple[int, str], ...]], set[str]] = {}
+ titles: dict[str, set[str]] = {}
+ span: dict[str, set[str]] = {}
+ runs: list[_Run] = []
+ for path, text in files:
+ extends: set[str] = set()
+ run: _Run | None = None
+ fresh = False
+ for row in parse_rows(text):
+ gone = any(f"{path}#{h}" in gone_list for _, h in row["path"])
+ line = row["line"].strip()
+ if row["heading"]:
+ fresh = True
+ if len(row["path"]) == 1 and row["section"]:
+ titles.setdefault(path, set()).add(row["section"])
+ continue
+ if row["tag"]:
+ for pattern in (ID_TAG, EXTEND_TAG, OVERRIDE_TAG):
+ match = pattern.match(line)
+ if not match:
+ continue
+ if fresh:
+ extends, run, fresh = set(), None, False
+ if pattern is EXTEND_TAG:
+ extends.add(match.group(1))
+ elif pattern is OVERRIDE_TAG and not gone:
+ if run is None:
+ run = _Run()
+ runs.append(run)
+ run.targets.add(match.group(1))
+ if row["section"]:
+ run.sections.add(row["section"])
+ continue
+ if not line:
+ continue
+ fresh = False
+ if len(row["path"]) == 1 and row["section"]:
+ titles.setdefault(path, set()).add(row["section"])
+ if run is not None and row["section"]:
+ run.sections.add(row["section"])
+ if gone or not owed[row["line"]]:
+ continue
+ key = (path, tuple(row["path"][:2]))
+ topics.setdefault(key, set()).add(row["line"])
+ extends_of.setdefault(key, set()).update(extends)
+ if not row["fence"]:
+ names_of.setdefault(key, set()).update(
+ re.findall(r"`([a-z0-9][a-z0-9-]*)`", row["line"])
+ )
+ if row["section"]:
+ span.setdefault(row["section"], set()).add(row["line"])
+ if run is not None:
+ run.lines.add(row["line"])
+
+ def survives(section: str, seen: set[str]) -> set[str]:
+ if section in seen:
+ return set()
+ seen.add(section)
+ found = set(span.get(section, ()))
+ for one in runs:
+ if section in one.targets:
+ found |= one.lines
+ for inner in sorted(one.sections):
+ found |= survives(inner, seen)
+ return found
+
+ findings: list[str] = []
+ for rel in sorted(sections):
+ lines = set(sections[rel].splitlines())
+ for key, held in topics.items():
+ if not held <= lines:
+ continue
+ path, place = key
+ heading = place[-1][1] if place else path
+ owes: dict[str, set[str]] = {}
+ if len(place) == 2:
+ owes["the rules under its title"] = topics.get((path, place[:1]), set())
+ for title in sorted(titles.get(path, ())):
+ if not span.get(title):
+ owes[f"the replacement of `{title}`"] = survives(title, set())
+ for target in sorted(extends_of.get(key, ())):
+ owes[f"`{target}`, which it extends"] = survives(target, set())
+ for target in sorted(names_of.get(key, ())):
+ owes[f"`{target}`, which it names"] = survives(target, set())
+ findings += [
+ f"{rel} carries {heading} and lacks {what}"
+ for what, needed in owes.items()
+ if not needed <= lines
+ ]
+ return findings
+
+
def section_findings(
files: Sequence[tuple[str, str]],
kinds: Mapping[str, str],
@@ -2741,6 +2879,8 @@ def section_findings(
findings += [f"no section file holds: {line}" for line in owed - held]
findings += [f"no adopted rule is: {line}" for line in held - owed]
+ findings += relation_findings(files, declined, owed, sections)
+
rules = section_rules(files, declined)
for rel in sorted(sections):
lines = set(sections[rel].splitlines())
@@ -2787,6 +2927,7 @@ def planted_section_findings() -> list[str]:
later = emitted.get(f"{SECTIONS_DIR}/stack-more/later.md", "")
fresh = emitted.get(f"{SECTIONS_DIR}/stack-more/fresh.md", "")
kept = emitted.get(f"{SECTIONS_DIR}/stack-more/kept.md", "")
+ door = emitted.get(f"{SECTIONS_DIR}/backend-facade/door.md", "")
follow = emitted.get(f"{SECTIONS_DIR}/base-demo/follow.md", "")
extra = emitted.get(f"{SECTIONS_DIR}/stack-more/extra.md", "")
top = emitted.get(f"{SECTIONS_DIR}/stack-top/content.md", "")
@@ -2834,6 +2975,10 @@ def planted_section_findings() -> list[str]:
and "Skin theme rule" not in everything
and "Base theme rule" not in everything,
),
+ (
+ "a heading under an overridden title carries the title's replacement",
+ "Front title rule." in door and "Facade title rule." not in everything,
+ ),
(
"a heading whose ID follows a blank line extends nothing",
"Target rule" not in fresh and "Fresh rule" not in target,
diff --git a/tools/emit_context.py b/tools/emit_context.py
index 68f17d1f..d612b012 100644
--- a/tools/emit_context.py
+++ b/tools/emit_context.py
@@ -486,8 +486,9 @@ class Topic:
rules under the title itself: the unit a section file is built around.
`order` is its place in the chain, `ids` the section IDs its rows sit
- in, `extends` and `overrides` the IDs its tags name, and `names` the
- adopted IDs its prose names.
+ in, `extends` and `overrides` the IDs its tags name, `names` the
+ adopted IDs its prose names, and `governed` the IDs of its template's
+ title that an override replaces.
"""
order: int
@@ -498,6 +499,7 @@ class Topic:
extends: set[str] = field(default_factory=set)
overrides: set[str] = field(default_factory=set)
names: set[str] = field(default_factory=set)
+ governed: set[str] = field(default_factory=set)
def content(self) -> bool:
return any(r["line"].strip() and not r["heading"] for r in self.rows)
@@ -582,6 +584,25 @@ def _topics(adopted: Sequence[Adopted]) -> list[Topic]:
for one in adopted:
_relate(one, by_key, replaced)
+ # The rules under a title govern every heading beneath it, read from the
+ # unfiltered rows: where a later template overrides the title's ID, the
+ # override's rules govern the headings that keep IDs of their own.
+ gone = _overridden(
+ [row for row in one.rows if id(row) not in one.declined] for one in adopted
+ )
+ for one in adopted:
+ title = {
+ row["section"]
+ for row in one.rows
+ if len(row["path"]) == 1
+ and row["section"]
+ and not row["tag"]
+ and row["line"].strip()
+ }
+ for topic in topics:
+ if topic.path == one.path and len(topic.key) == 2:
+ topic.governed = title & gone
+
# An override that declares an ID of its own may be overridden in turn,
# and then none of its rows survive to hold the ID it replaced. The last
# surviving replacement stands for every ID down the chain, so a rule
@@ -631,6 +652,8 @@ def needs(topic: Topic, whole: bool) -> list[tuple[Topic, bool]]:
and len(other.key) < len(topic.key)
and topic.key[: len(other.key)] == other.key
]
+ for i in sorted(topic.governed):
+ found += [(other, False) for other in holding.get(i, [])]
# A section is read with the one it extends or names, since a rule
# left to a reference is one the agent never reads.
From c47f868e6c9f1d7e0c0c341b72abe3d7e2b4368a Mon Sep 17 00:00:00 2001
From: Branimir Georgiev <66906831+braboj@users.noreply.github.com>
Date: Sun, 15 Nov 2026 21:36:03 +0200
Subject: [PATCH 6/7] fix(emit): carry a section its prose names by heading
From the fifth review of #2496: the templates name another section by
its heading, as the authoring rules ask, but the section files followed
only backticked IDs. Security headers kept "see Transport security" and
lost HSTS's `includeSubDomains` and one-year `max-age`.
- A heading named in the templates' own forms is now carried: its exact
text in double quotes, after "see", or a link to its anchor, matched
case and all, so plain prose names none
- It resolves in the naming template first, then anywhere in the chain,
read from the unfiltered rows and through overrides to what survives
- Every root's references resolve: 8 distinct, 17 across the 39 roots;
SYS-28 lists any that no chain template has instead of failing
SYS-28's planted templates gain the cases, and its reference reading of
the unfiltered chain follows heading references too; on the 39 roots it
reports 13 omissions without the fix. The root file and skills, inlined
or not, stay byte-identical.
Part of #2466.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3
---
.../060-section-files-load-on-demand.md | 13 +-
docs/requirements.md | 2 +-
docs/tests/specs/SAIT-SMK-SYS-28-001A.md | 12 +-
tests/smoke/system.py | 93 ++++++++++++++-
tools/emit_context.py | 111 +++++++++++++++++-
5 files changed, 217 insertions(+), 14 deletions(-)
diff --git a/docs/decisions/060-section-files-load-on-demand.md b/docs/decisions/060-section-files-load-on-demand.md
index c19ae40c..0632ef92 100644
--- a/docs/decisions/060-section-files-load-on-demand.md
+++ b/docs/decisions/060-section-files-load-on-demand.md
@@ -24,7 +24,7 @@ from the same chain (solid-ai-dev/solid-ai-benchmark#169).
450 to 1,700 words each, and nothing hands an agent one topic of one
- A topic's rules can depend on rules elsewhere: the rules under the
template's title, a section it extends, a section its prose names by
- ID, and an extension a later template adds on top of it
+ ID or by heading, and an extension a later template adds on top of it
- Template paths and section IDs are frozen for 3.x, so a delivery that
splits templates or anchors each heading changes the frozen surface
@@ -55,9 +55,14 @@ first touches it.
title alone get a file only where no topic's file carries them
2. **Carried rules** — a topic's file carries, in chain order, the rules
under its template's title, each section it extends, each section its
- prose names by ID in backticks, each extension of its own sections,
- and what each of those carries in turn. Rules carried only because they
- sit under a title do not bring that title's extensions (MUST)
+ prose names by ID in backticks or by heading, each extension of its own
+ sections, and what each of those carries in turn. A heading is named
+ by its exact text in double quotes, after "see", or as a link to its
+ anchor, and resolves in the naming template first, then anywhere in the
+ chain. Each relationship is read from the template as written and
+ resolved through the overrides to the rules that survive. Rules carried
+ only because they sit under a title do not bring that title's
+ extensions (MUST)
3. **Same rule set** — the files together hold exactly the rules the
inlined root file holds, and every copy of a rule matches its source
(MUST)
diff --git a/docs/requirements.md b/docs/requirements.md
index 996752a8..ffaaeb7d 100644
--- a/docs/requirements.md
+++ b/docs/requirements.md
@@ -70,7 +70,7 @@ Status: skeleton. Each cluster holds a few requirements until its fill
| FR-06-05 | The system shall reference a section marked `check` by its command and pass condition, never by copying the script body. | ADR-058 | SYS-26, partial, on a planted fixture |
| FR-06-06 | The system shall build byte-identical files from the same input. | ADR-058 | SYS-26 |
| FR-06-07 | The system shall build files that name no template file, since an emitted project carries no templates. | `AGENTS.md` 4.2 | SYS-27 |
-| FR-06-08 | Where the project asks for section files, the system shall build one file per heading under a template's title, carrying the rules under that title, each section it extends or names by ID, and each extension of its own, so the files together hold every adopted rule and every copy matches its source. | ADR-060 | SYS-28 |
+| FR-06-08 | Where the project asks for section files, the system shall build one file per heading under a template's title, carrying the rules under that title, each section it extends or names by ID or by heading, and each extension of its own, each resolved through overrides to the rules that survive, so the files together hold every adopted rule and every copy matches its source. | ADR-060 | SYS-28 |
| FR-06-09 | Where the project asks for section files, the system shall map each file in the root file to its topic, to be read when the work first touches it, and hold no rule in the root file. | ADR-060 | SYS-28 |
### 07. Shipped checks
diff --git a/docs/tests/specs/SAIT-SMK-SYS-28-001A.md b/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
index 814798d0..89f3ec46 100644
--- a/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
+++ b/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
@@ -62,7 +62,10 @@ on two roots written to a temporary directory that is removed afterwards)
and an overridden subsection that carries an extension; decline an
extension's first heading, and add a two-level override whose first
level sits under a heading inside its title's section, and a title a
- later template overrides while its headings keep IDs of their own
+ later template overrides while its headings keep IDs of their own; add
+ headings named in prose, quoted, after "see" and as a link, in the same
+ template and in another, one of them replaced by an override, and a
+ line of plain prose that names no heading
2. Build every root `--roots` lists on its own, as section files and with
skills inlined
3. Cut every section file at its headings, keep one copy of each block,
@@ -94,11 +97,14 @@ on two roots written to a temporary directory that is removed afterwards)
section its heading inherits
5. Assert, for the planted chain and every root, that the lines held equal
the adopted lines, that two copies of a block never differ, and that a
- file naming a section in backticks carries its rules
+ file naming a section in backticks carries its rules, and that a
+ section named by its heading is carried, resolved through overrides,
+ while plain prose names none
6. Assert, by a reading of the unfiltered chain apart from the emitter's,
that every file carrying a heading holds what each of its relationships
owes: the rules under its title, each section its section extends, and
- each ID its prose names, each resolved to the rules that survive for
+ each ID and each heading its prose names, each resolved to the rules
+ that survive for
it, its own or those of the override that replaces it, down the chain
7. Assert the root file maps each section file once, maps no other, holds
no rule line, and says not to read the files before the work starts
diff --git a/tests/smoke/system.py b/tests/smoke/system.py
index 6a75e0ff..82e69768 100644
--- a/tests/smoke/system.py
+++ b/tests/smoke/system.py
@@ -14,6 +14,7 @@
# so a fork's own key is read here exactly as it is resolved there.
from emit_context import EmitError
from emit_context import BUILT_LINE, MAP_HEADER, SECTIONS_DIR, section_rules
+from emit_context import heading_references
from emit_context import EXTEND_TAG, ID_TAG, OVERRIDE_TAG
# The emitter's line parser, which only reads a template; the reference
@@ -2575,7 +2576,8 @@ def check_sys_27() -> CheckResult:
"## Shared\n[ID: demo-shared]\n\n- Shared first rule\n\n"
"## Follow\n\n- Follow the rules of `demo-shared`\n\n"
"## Parent\n[ID: demo-parent]\n\n- Parent rule\n\n"
- "### Child\n[ID: demo-child]\n[EXTEND: demo-naming]\n\n- Child rule\n"
+ "### Child\n[ID: demo-child]\n[EXTEND: demo-naming]\n\n- Child rule\n\n"
+ "## Paths\n[ID: demo-paths]\n\n- Keep paths short (see Naming)\n"
)
SECTION_LAYER = (
"# Layer — Demo\n[ID: layer-demo]\n\n"
@@ -2609,7 +2611,10 @@ def check_sys_27() -> CheckResult:
"## Kept\n\n- Kept rule\n\n"
"## Later\n[ID: more-later]\n\n- Follow the content rules (`demo-content`)\n"
"- Follow the theme rules (`demo-theme`)\n\n"
- "## Extra\n[EXTEND: demo-content]\n\n- Extra content rule\n"
+ "## Extra\n[EXTEND: demo-content]\n\n- Extra content rule\n\n"
+ "## Refs\n[ID: more-refs]\n\n"
+ '- Follow "Target" and see Shared; keep [the theme](#theme)\n'
+ "- See the naming rules too, in plain prose\n"
)
# Two levels of override where the first sits under a heading with no ID
# of its own, inside its title's section, which the second overrides.
@@ -2765,6 +2770,30 @@ def relation_findings(
titles: dict[str, set[str]] = {}
span: dict[str, set[str]] = {}
runs: list[_Run] = []
+ headed_of: dict[tuple[str, tuple[tuple[int, str], ...]], set[str]] = {}
+ places: dict[str, list[tuple[str, tuple[tuple[int, str], ...], set[str]]]] = {}
+ for path, text in files:
+ rows = parse_rows(text)
+ for row in rows:
+ if row["heading"]:
+ where = row["path"]
+ places.setdefault(where[-1][1], []).append(
+ (
+ path,
+ tuple(where[:2]),
+ {
+ r["section"]
+ for r in rows
+ if r["path"][: len(where)] == where
+ and r["section"]
+ and not r["tag"]
+ and r["line"].strip()
+ },
+ )
+ )
+ anchors = {
+ re.sub(r"[^\w\- ]", "", text.lower()).replace(" ", "-"): text for text in places
+ }
for path, text in files:
extends: set[str] = set()
run: _Run | None = None
@@ -2810,6 +2839,20 @@ def relation_findings(
names_of.setdefault(key, set()).update(
re.findall(r"`([a-z0-9][a-z0-9-]*)`", row["line"])
)
+ said = re.findall(r'"([^"\n]+)"', row["line"]) + [
+ found.rstrip()
+ for found in re.findall(
+ r"\b[Ss]ee ([^\s\"(),.;:\]][^\"(),.;:\]]*)", row["line"]
+ )
+ ]
+ headed_of.setdefault(key, set()).update(
+ {found for found in said if found in places}
+ | {
+ anchors[found]
+ for found in re.findall(r"\]\(#([^)\s]+)\)", row["line"])
+ if found in anchors
+ }
+ )
if row["section"]:
span.setdefault(row["section"], set()).add(row["line"])
if run is not None:
@@ -2845,6 +2888,16 @@ def survives(section: str, seen: set[str]) -> set[str]:
owes[f"`{target}`, which it extends"] = survives(target, set())
for target in sorted(names_of.get(key, ())):
owes[f"`{target}`, which it names"] = survives(target, set())
+ for named in sorted(headed_of.get(key, ())):
+ at = [p for p in places[named] if p[0] == path] or places[named]
+ needed: set[str] = set()
+ for in_file, place_key, secs in at:
+ if (in_file, place_key) != key:
+ needed |= topics.get((in_file, place_key), set())
+ for sec in sorted(secs):
+ if not span.get(sec):
+ needed |= survives(sec, set())
+ owes[f'"{named}", which it names by heading'] = needed
findings += [
f"{rel} carries {heading} and lacks {what}"
for what, needed in owes.items()
@@ -2928,6 +2981,8 @@ def planted_section_findings() -> list[str]:
fresh = emitted.get(f"{SECTIONS_DIR}/stack-more/fresh.md", "")
kept = emitted.get(f"{SECTIONS_DIR}/stack-more/kept.md", "")
door = emitted.get(f"{SECTIONS_DIR}/backend-facade/door.md", "")
+ paths = emitted.get(f"{SECTIONS_DIR}/base-demo/paths.md", "")
+ refs = emitted.get(f"{SECTIONS_DIR}/stack-more/refs.md", "")
follow = emitted.get(f"{SECTIONS_DIR}/base-demo/follow.md", "")
extra = emitted.get(f"{SECTIONS_DIR}/stack-more/extra.md", "")
top = emitted.get(f"{SECTIONS_DIR}/stack-top/content.md", "")
@@ -2979,6 +3034,19 @@ def planted_section_findings() -> list[str]:
"a heading under an overridden title carries the title's replacement",
"Front title rule." in door and "Facade title rule." not in everything,
),
+ (
+ "a section named by its heading in its own template is carried",
+ "Name by role" in paths,
+ ),
+ (
+ "a heading quoted, after see, or linked in another template is carried",
+ "Target rule" in refs and "Shared first rule" in refs,
+ ),
+ (
+ "a named heading an override replaces resolves to the override",
+ "Brand theme rule" in refs,
+ ),
+ ("plain prose names no heading", "Name by role" not in refs),
(
"a heading whose ID follows a blank line extends nothing",
"Target rule" not in fresh and "Fresh rule" not in target,
@@ -3060,7 +3128,18 @@ def check_sys_28() -> CheckResult:
parse_manifest(read(os.path.join(ROOT, "templates", "manifest.yaml")))
)
names = template_names(entries)
+
+ # A reference to a heading no template of the chain has is listed, not
+ # failed: the text names a section the chain does not carry.
+ headings = {
+ row["path"][-1][1]
+ for path in template_files()
+ for row in parse_rows(read_file(path))
+ if row["heading"]
+ }
files = 0
+ resolved = 0
+ unresolved: set[str] = set()
for root in roots:
chain = [
(path, read_file(path)) for path in resolve_chain(root, core_ids, entries)
@@ -3071,7 +3150,13 @@ def check_sys_28() -> CheckResult:
f" {root}: {finding}"
for finding in section_findings(chain, kinds, emitted)
]
+ found, missed = heading_references(chain, (), headings)
+ resolved += len(found)
+ unresolved.update(f"{root}, {where}" for where in missed)
seen.count("section files emitted", files)
+ seen.count("heading references resolved, over every root", resolved)
+ seen.count("heading references no chain template has", len(unresolved), 0)
+ listed = [f" unresolved: {where}" for where in sorted(unresolved)]
# Two runs of the real tool, under different hash seeds, over roots
# whose chains extend and name sections in another template.
@@ -3100,7 +3185,7 @@ def check_sys_28() -> CheckResult:
f" emit exited {proc.returncode}: "
f"{(proc.stdout + proc.stderr).strip()}"
)
- return seen.failures() + failures, seen.notes()
+ return seen.failures() + failures, seen.notes() + listed
trees.append(emitted_tree(out))
finally:
shutil.rmtree(work, ignore_errors=True)
@@ -3111,4 +3196,4 @@ def check_sys_28() -> CheckResult:
| {k for k in set(trees[0]) & set(trees[1]) if trees[0][k] != trees[1][k]}
)
failures.append(f" two runs differ in: {', '.join(differ)}")
- return seen.failures() + failures, seen.notes()
+ return seen.failures() + failures, seen.notes() + listed
diff --git a/tools/emit_context.py b/tools/emit_context.py
index d612b012..ad39af3e 100644
--- a/tools/emit_context.py
+++ b/tools/emit_context.py
@@ -103,6 +103,14 @@
# A section ID named in a rule's prose, in backticks.
NAMED_ID = re.compile(r"`([a-z0-9][a-z0-9-]*)`")
+# A section named in a rule's prose by its heading, in the forms the
+# templates write: the heading in double quotes, "see" and the heading, or a
+# link to the heading's anchor. Only a match of a heading's whole text, case
+# and all, counts, so ordinary prose names none.
+QUOTED_HEADING = re.compile(r'"([^"\n]+)"')
+SEE_HEADING = re.compile(r"\b[Ss]ee ([^\s\"(),.;:\]][^\"(),.;:\]]*)")
+LINKED_HEADING = re.compile(r"\]\(#([^)\s]+)\)")
+
class EmitError(Exception):
"""An emission refused rather than written."""
@@ -487,8 +495,9 @@ class Topic:
`order` is its place in the chain, `ids` the section IDs its rows sit
in, `extends` and `overrides` the IDs its tags name, `names` the
- adopted IDs its prose names, and `governed` the IDs of its template's
- title that an override replaces.
+ adopted IDs its prose names, `governed` the IDs of its template's
+ title that an override replaces, and `refs` the topics its prose names
+ by heading.
"""
order: int
@@ -500,6 +509,7 @@ class Topic:
overrides: set[str] = field(default_factory=set)
names: set[str] = field(default_factory=set)
governed: set[str] = field(default_factory=set)
+ refs: list[Topic] = field(default_factory=list)
def content(self) -> bool:
return any(r["line"].strip() and not r["heading"] for r in self.rows)
@@ -628,9 +638,105 @@ def _topics(adopted: Sequence[Adopted]) -> list[Topic]:
# own section's ID still needs the others; the topic itself is
# already carried.
topic.names &= known
+
+ # A heading its prose names is read from the unfiltered rows, so a
+ # named heading whose section an override replaces resolves to the
+ # override, as a named ID does.
+ index = _heading_index(adopted)
+ for topic in topics:
+ for row in topic.rows:
+ if row["fence"] or row["heading"]:
+ continue
+ for text in _heading_refs(row["line"], index):
+ for path, key, sections in _resolve_heading(index, text, topic.path):
+ target = by_key.get((path, key))
+ if target is not None and target is not topic:
+ topic.refs.append(target)
+ topic.names |= sections & gone
return topics
+# Where a heading sits: its template's path, the key of the topic that holds
+# it, and the section IDs its rows sit in.
+HeadingPlace = tuple[str, Key, set[str]]
+
+
+def _anchor(text: str) -> str:
+ """A heading's anchor, as a Markdown renderer writes it."""
+ return re.sub(r"[^\w\- ]", "", text.lower()).replace(" ", "-")
+
+
+def _heading_index(adopted: Iterable[Adopted]) -> dict[str, list[HeadingPlace]]:
+ """Every heading of the chain by its text, read from every parsed row,
+ with each place it sits in, in chain order."""
+ index: dict[str, list[HeadingPlace]] = {}
+ for one in adopted:
+ for row in one.rows:
+ if not row["heading"]:
+ continue
+ path = row["path"]
+ sections = {
+ other["section"]
+ for other in one.rows
+ if other["path"][: len(path)] == path
+ and other["section"]
+ and not other["tag"]
+ and other["line"].strip()
+ }
+ index.setdefault(path[-1][1], []).append(
+ (one.path, tuple(path[:2]), sections)
+ )
+ return index
+
+
+def _heading_refs(line: str, headings: Collection[str]) -> list[str]:
+ """The headings a line of prose names, by their text."""
+ anchors = {_anchor(text): text for text in headings}
+ found = [m.group(1) for m in QUOTED_HEADING.finditer(line)]
+ found += [m.group(1).rstrip() for m in SEE_HEADING.finditer(line)]
+ found = [text for text in found if text in headings]
+ found += [
+ anchors[m.group(1)]
+ for m in LINKED_HEADING.finditer(line)
+ if m.group(1) in anchors
+ ]
+ return found
+
+
+def _resolve_heading(
+ index: Mapping[str, list[HeadingPlace]], text: str, path: str
+) -> list[HeadingPlace]:
+ """Where a named heading sits: in the naming template where it has one,
+ and otherwise wherever the chain has it."""
+ places = index.get(text, [])
+ return [place for place in places if place[0] == path] or places
+
+
+def heading_references(
+ files: Iterable[tuple[str, str]],
+ declined: Iterable[str] = (),
+ headings: Collection[str] = (),
+) -> tuple[list[str], list[str]]:
+ """Each adopted rule's reference to a heading, as `path: heading`, split
+ into those the chain resolves and those it does not. `headings` adds
+ texts that count as headings, such as every template's, so a reference
+ to one outside the chain is reported rather than missed."""
+ adopted = _adopt(files, set(declined))
+ index = _heading_index(adopted)
+ known = set(index) | set(headings)
+ resolved: list[str] = []
+ unresolved: list[str] = []
+ for one in adopted:
+ for _, run in one.runs:
+ for row in run:
+ if row["fence"] or row["heading"]:
+ continue
+ for text in _heading_refs(row["line"], known):
+ into = resolved if text in index else unresolved
+ into.append(f"{one.path}: {text}")
+ return resolved, unresolved
+
+
def _carried(topics: Sequence[Topic]) -> dict[int, list[Topic]]:
"""Each topic's order mapped to what its section file carries, in chain
order: the topic, the rules under its template's title, the sections it
@@ -659,6 +765,7 @@ def needs(topic: Topic, whole: bool) -> list[tuple[Topic, bool]]:
# left to a reference is one the agent never reads.
for i in sorted(topic.extends | topic.names):
found += [(other, True) for other in holding.get(i, [])]
+ found += [(other, True) for other in topic.refs]
# An extension applies on top of the section it extends, so it goes
# with that section's rules. Rules carried only because they govern
From 04764ffcf853008bf365322a24d79fb128d2d8d8 Mon Sep 17 00:00:00 2001
From: Branimir Georgiev <66906831+braboj@users.noreply.github.com>
Date: Sun, 15 Nov 2026 22:02:56 +0200
Subject: [PATCH 7/7] fix(emit): read a wrapped heading name, and keep an
override to its own rules
From the sixth review of #2496:
- A heading named in prose was read line by line, so one quoted across a
wrapped line was missed. Each paragraph and bullet outside code is now
read whole. No real root gains a reference: all 39 still resolve the
same 17
- An override under an untagged heading inherits its title's ID, and
every heading sharing that ID stood in for the replaced section, those
before the override included. An override's own rules now replace it
where they survive; the section it sits in stands in only where that
section is overridden in turn. No real root's section files change
SYS-28's planted templates gain both cases; each fails without its fix.
Its reference reading joins wrapped lines too, and gains the dual of its
missing-rules check: a file may hold no rule its own topic's
relationships do not reach. Run against the earlier emitters, the dual
reports each rule they carried too far.
The root file and skills, inlined or not, stay byte-identical.
Part of #2466.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3
---
.../060-section-files-load-on-demand.md | 10 +-
docs/tests/specs/SAIT-SMK-SYS-28-001A.md | 18 +-
tests/smoke/system.py | 239 ++++++++++++++++--
tools/emit_context.py | 50 ++--
4 files changed, 271 insertions(+), 46 deletions(-)
diff --git a/docs/decisions/060-section-files-load-on-demand.md b/docs/decisions/060-section-files-load-on-demand.md
index 0632ef92..ce48db3b 100644
--- a/docs/decisions/060-section-files-load-on-demand.md
+++ b/docs/decisions/060-section-files-load-on-demand.md
@@ -58,11 +58,11 @@ first touches it.
prose names by ID in backticks or by heading, each extension of its own
sections, and what each of those carries in turn. A heading is named
by its exact text in double quotes, after "see", or as a link to its
- anchor, and resolves in the naming template first, then anywhere in the
- chain. Each relationship is read from the template as written and
- resolved through the overrides to the rules that survive. Rules carried
- only because they sit under a title do not bring that title's
- extensions (MUST)
+ anchor, read across a wrapped line, and resolves in the naming
+ template first, then anywhere in the chain. Each relationship is read
+ from the template as written and resolved through the overrides to the
+ rules that survive. Rules carried only because they sit under a title
+ do not bring that title's extensions (MUST)
3. **Same rule set** — the files together hold exactly the rules the
inlined root file holds, and every copy of a rule matches its source
(MUST)
diff --git a/docs/tests/specs/SAIT-SMK-SYS-28-001A.md b/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
index 89f3ec46..c7e6e5c1 100644
--- a/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
+++ b/docs/tests/specs/SAIT-SMK-SYS-28-001A.md
@@ -64,8 +64,10 @@ on two roots written to a temporary directory that is removed afterwards)
level sits under a heading inside its title's section, and a title a
later template overrides while its headings keep IDs of their own; add
headings named in prose, quoted, after "see" and as a link, in the same
- template and in another, one of them replaced by an override, and a
- line of plain prose that names no heading
+ template and in another, one of them replaced by an override, one
+ quoted across a wrapped line, and a line of plain prose that names no
+ heading; add a stack that overrides a base section under an untagged
+ heading after a heading it leaves alone
2. Build every root `--roots` lists on its own, as section files and with
skills inlined
3. Cut every section file at its headings, keep one copy of each block,
@@ -99,13 +101,17 @@ on two roots written to a temporary directory that is removed afterwards)
the adopted lines, that two copies of a block never differ, and that a
file naming a section in backticks carries its rules, and that a
section named by its heading is carried, resolved through overrides,
- while plain prose names none
+ while plain prose names none, and that a section named or extended by
+ an ID an untagged override replaces carries that override and not the
+ stack's other headings
6. Assert, by a reading of the unfiltered chain apart from the emitter's,
that every file carrying a heading holds what each of its relationships
owes: the rules under its title, each section its section extends, and
each ID and each heading its prose names, each resolved to the rules
that survive for
- it, its own or those of the override that replaces it, down the chain
+ it, its own or those of the override that replaces it, down the chain;
+ and, its dual, that a file holds no rule its own topic's relationships
+ and the extensions of what they stand for do not reach
7. Assert the root file maps each section file once, maps no other, holds
no rule line, and says not to read the files before the work starts
8. Assert each planted fault is reported
@@ -143,7 +149,9 @@ on two roots written to a temporary directory that is removed afterwards)
section mode, the reading of the unfiltered chain alone reports every
omission later fixed: an extension past its heading, a declined first
heading, an override chain, a heading naming its own section's ID, and
- an overridden title
+ an overridden title. Its dual reports every rule carried too far: a
+ relationship given to a blank or replaced row, and an untagged
+ override's title section standing for it
## Related
diff --git a/tests/smoke/system.py b/tests/smoke/system.py
index 82e69768..e15aa9b1 100644
--- a/tests/smoke/system.py
+++ b/tests/smoke/system.py
@@ -19,6 +19,7 @@
# The emitter's line parser, which only reads a template; the reference
# reading of a chain's relationships in SYS-28 is the check's own.
+from emit_context import Row
from emit_context import _blocks as parse_rows
from emit_context import build as emit_build
from emit_context import build_sections as emit_sections
@@ -2577,7 +2578,9 @@ def check_sys_27() -> CheckResult:
"## Follow\n\n- Follow the rules of `demo-shared`\n\n"
"## Parent\n[ID: demo-parent]\n\n- Parent rule\n\n"
"### Child\n[ID: demo-child]\n[EXTEND: demo-naming]\n\n- Child rule\n\n"
- "## Paths\n[ID: demo-paths]\n\n- Keep paths short (see Naming)\n"
+ "## Paths\n[ID: demo-paths]\n\n- Keep paths short (see Naming)\n\n"
+ "## Error budget\n[ID: demo-budget]\n\n- Budget rule\n\n"
+ "## Venue\n[ID: demo-venue]\n\n- Base venue rule\n"
)
SECTION_LAYER = (
"# Layer — Demo\n[ID: layer-demo]\n\n"
@@ -2615,6 +2618,9 @@ def check_sys_27() -> CheckResult:
"## Refs\n[ID: more-refs]\n\n"
'- Follow "Target" and see Shared; keep [the theme](#theme)\n'
"- See the naming rules too, in plain prose\n"
+ '- Spend within the "Error\n budget" each month\n'
+ "- Hold it at the venue (`demo-venue`)\n\n"
+ "## Venue extra\n[EXTEND: demo-venue]\n\n- Venue extension rule\n"
)
# Two levels of override where the first sits under a heading with no ID
# of its own, inside its title's section, which the second overrides.
@@ -2635,6 +2641,13 @@ def check_sys_27() -> CheckResult:
SECTION_FRONT = (
"# Front — Demo\n[ID: front-demo]\n[OVERRIDE: facade-demo]\n\nFront title rule.\n"
)
+# A stack whose override of a base section sits under an untagged
+# heading, after a heading of its own it leaves alone.
+SECTION_STAGE = (
+ "# Stage — Demo\n[ID: stage-demo]\n\n"
+ "## Unrelated\n\n- Unrelated rule\n\n"
+ "## Replacement\n[OVERRIDE: demo-venue]\n\n- Replacement rule\n"
+)
SECTION_FILES = [
("templates/core/demo.md", SECTION_BASE),
("templates/backend/layer.md", SECTION_LAYER),
@@ -2644,6 +2657,7 @@ def check_sys_27() -> CheckResult:
("templates/backend/skin.md", SECTION_SKIN),
("templates/fixture/brand.md", SECTION_BRAND),
("templates/fixture/front.md", SECTION_FRONT),
+ ("templates/fixture/stage.md", SECTION_STAGE),
("templates/fixture/more.md", SECTION_MORE),
("templates/data/other.md", SECTION_TITLE_ONLY),
]
@@ -2656,6 +2670,7 @@ def check_sys_27() -> CheckResult:
"templates/backend/skin.md": ("backend-skin", "Skin rules"),
"templates/fixture/front.md": ("stack-front", "Front rules"),
"templates/fixture/brand.md": ("stack-brand", "Brand rules"),
+ "templates/fixture/stage.md": ("stack-stage", "Stage rules"),
"templates/fixture/more.md": ("stack-more", "More rules"),
"templates/data/other.md": ("base-other", "Other rules"),
}
@@ -2738,6 +2753,19 @@ def adopted_lines(
return +lines
+# A row past a template's last line, so a paragraph ending the file is read.
+_END_ROW: Row = {
+ "line": "",
+ "path": [],
+ "load": None,
+ "anchor": None,
+ "section": None,
+ "tag": False,
+ "heading": False,
+ "fence": False,
+}
+
+
class _Run:
"""One override's section: the IDs it replaces, the sections its rows
sit in, and the rule lines it delivers."""
@@ -2746,6 +2774,7 @@ def __init__(self) -> None:
self.targets: set[str] = set()
self.sections: set[str] = set()
self.lines: set[str] = set()
+ self.keys: set[tuple[str, tuple[tuple[int, str], ...]]] = set()
def relation_findings(
@@ -2753,15 +2782,20 @@ def relation_findings(
declined: Iterable[str],
owed: Counter[str],
sections: Mapping[str, str],
+ root: str = "",
) -> list[str]:
- """Each section file that lacks rules a relationship owes it.
+ """Each section file that lacks rules a relationship owes it, and each
+ that holds rules no relationship of its topic reaches.
A reference reading, apart from the emitter's: every relationship is
read from the unfiltered chain, the rules under a title, each section a
heading's section extends, and each ID its prose names, and each owes
the rules that survive for it, the ID's own or, where it is replaced,
those of the override that replaces it, followed down the chain. A file
- carries a heading when it holds every rule the heading delivers.
+ carries a heading when it holds every rule the heading delivers. The
+ dual: from the topic the root file maps a file to, following the same
+ relationships and every extension of what the topic and the sections it
+ extends or names stand for, no other heading's rules are reached.
"""
gone_list = set(declined)
topics: dict[tuple[str, tuple[tuple[int, str], ...]], set[str]] = {}
@@ -2771,6 +2805,7 @@ def relation_findings(
span: dict[str, set[str]] = {}
runs: list[_Run] = []
headed_of: dict[tuple[str, tuple[tuple[int, str], ...]], set[str]] = {}
+ key_secs: dict[tuple[str, tuple[tuple[int, str], ...]], set[str]] = {}
places: dict[str, list[tuple[str, tuple[tuple[int, str], ...], set[str]]]] = {}
for path, text in files:
rows = parse_rows(text)
@@ -2794,11 +2829,42 @@ def relation_findings(
anchors = {
re.sub(r"[^\w\- ]", "", text.lower()).replace(" ", "-"): text for text in places
}
+
+ def said(key: tuple[str, tuple[tuple[int, str], ...]], prose: str) -> None:
+ quoted = re.findall(r'"([^"]+)"', prose) + [
+ found.rstrip()
+ for found in re.findall(r"\b[Ss]ee ([^\s\"(),.;:\]][^\"(),.;:\]]*)", prose)
+ ]
+ headed_of.setdefault(key, set()).update(
+ {found for found in quoted if found in places}
+ | {
+ anchors[found]
+ for found in re.findall(r"\]\(#([^)\s]+)\)", prose)
+ if found in anchors
+ }
+ )
+
for path, text in files:
extends: set[str] = set()
run: _Run | None = None
fresh = False
- for row in parse_rows(text):
+ chunk: list[str] = []
+ chunk_key: tuple[str, tuple[tuple[int, str], ...]] | None = None
+ for row in parse_rows(text) + [_END_ROW]:
+ key = (path, tuple(row["path"][:2]))
+ delivered = (
+ bool(row["line"].strip())
+ and not (row["heading"] or row["tag"] or row["fence"])
+ and not any(f"{path}#{h}" in gone_list for _, h in row["path"])
+ and bool(owed[row["line"]])
+ )
+ starts = bool(re.match(r"^\s*(?:[-*+]|\d+\.)\s", row["line"]))
+ if chunk_key is not None and (not delivered or starts or key != chunk_key):
+ said(chunk_key, " ".join(chunk))
+ chunk, chunk_key = [], None
+ if delivered:
+ chunk.append(row["line"].strip())
+ chunk_key = key
gone = any(f"{path}#{h}" in gone_list for _, h in row["path"])
line = row["line"].strip()
if row["heading"]:
@@ -2834,25 +2900,15 @@ def relation_findings(
continue
key = (path, tuple(row["path"][:2]))
topics.setdefault(key, set()).add(row["line"])
+ if row["section"]:
+ key_secs.setdefault(key, set()).add(row["section"])
+ if run is not None:
+ run.keys.add(key)
extends_of.setdefault(key, set()).update(extends)
if not row["fence"]:
names_of.setdefault(key, set()).update(
re.findall(r"`([a-z0-9][a-z0-9-]*)`", row["line"])
)
- said = re.findall(r'"([^"\n]+)"', row["line"]) + [
- found.rstrip()
- for found in re.findall(
- r"\b[Ss]ee ([^\s\"(),.;:\]][^\"(),.;:\]]*)", row["line"]
- )
- ]
- headed_of.setdefault(key, set()).update(
- {found for found in said if found in places}
- | {
- anchors[found]
- for found in re.findall(r"\]\(#([^)\s]+)\)", row["line"])
- if found in anchors
- }
- )
if row["section"]:
span.setdefault(row["section"], set()).add(row["line"])
if run is not None:
@@ -2866,8 +2922,12 @@ def survives(section: str, seen: set[str]) -> set[str]:
for one in runs:
if section in one.targets:
found |= one.lines
+ # The section an override sits in stands for it only
+ # where that section is replaced in turn; otherwise the
+ # override's own rules are what survive.
for inner in sorted(one.sections):
- found |= survives(inner, seen)
+ if any(inner in other.targets for other in runs):
+ found |= survives(inner, seen)
return found
findings: list[str] = []
@@ -2903,6 +2963,131 @@ def survives(section: str, seen: set[str]) -> set[str]:
for what, needed in owes.items()
if not needed <= lines
]
+ return findings + _overreach(
+ sections,
+ root,
+ owed,
+ topics,
+ key_secs,
+ runs,
+ extends_of,
+ names_of,
+ headed_of,
+ titles,
+ span,
+ places,
+ )
+
+
+_Key = tuple[str, tuple[tuple[int, str], ...]]
+
+
+def _overreach(
+ sections: Mapping[str, str],
+ root: str,
+ owed: Counter[str],
+ topics: Mapping[_Key, set[str]],
+ key_secs: Mapping[_Key, set[str]],
+ runs: Sequence[_Run],
+ extends_of: Mapping[_Key, set[str]],
+ names_of: Mapping[_Key, set[str]],
+ headed_of: Mapping[_Key, set[str]],
+ titles: Mapping[str, set[str]],
+ span: Mapping[str, set[str]],
+ places: Mapping[str, list[tuple[str, tuple[tuple[int, str], ...], set[str]]]],
+) -> list[str]:
+ """Each section file holding a rule its own topic's relationships do not
+ reach, by the reference reading `relation_findings` takes."""
+
+ def holders(section: str, seen: set[str]) -> set[_Key]:
+ if section in seen:
+ return set()
+ seen.add(section)
+ found = {key for key, secs in key_secs.items() if section in secs}
+ for one in runs:
+ if section in one.targets:
+ found |= one.keys
+ for inner in sorted(one.sections):
+ if any(inner in other.targets for other in runs):
+ found |= holders(inner, seen)
+ return found
+
+ every = set(span) | {target for one in runs for target in one.targets}
+ held_by = {section: holders(section, set()) for section in sorted(every)}
+ extensions: dict[str, set[_Key]] = {}
+ for key, targets in extends_of.items():
+ for target in targets:
+ extensions.setdefault(target, set()).add(key)
+
+ def reach(owner: _Key) -> set[_Key]:
+ out = {owner}
+ done: set[tuple[_Key, bool]] = set()
+ todo = [(owner, True)]
+ while todo:
+ key, whole = todo.pop()
+ if (key, whole) in done:
+ continue
+ done.add((key, whole))
+ path, place = key
+ step: list[tuple[_Key, bool]] = []
+ if len(place) == 2:
+ if (path, place[:1]) in topics:
+ step.append(((path, place[:1]), False))
+ for title in sorted(titles.get(path, ())):
+ if not span.get(title):
+ step += [(h, False) for h in held_by.get(title, ())]
+ for target in sorted(extends_of.get(key, set()) | names_of.get(key, set())):
+ step += [(h, True) for h in held_by.get(target, ())]
+ for named in sorted(headed_of.get(key, ())):
+ at = [p for p in places[named] if p[0] == path] or places[named]
+ for in_file, place_key, secs in at:
+ if (in_file, place_key) in topics:
+ step.append(((in_file, place_key), True))
+ for sec in sorted(secs):
+ if not span.get(sec):
+ step += [(h, True) for h in held_by.get(sec, ())]
+ if whole:
+ for section, held in held_by.items():
+ if key in held:
+ step += [(e, True) for e in extensions.get(section, ())]
+ for item in step:
+ out.add(item[0])
+ todo.append(item)
+ return out
+
+ # The root file's map: each template's title, then a row per topic.
+ title_of = {key[0]: key[1][0] for key in topics if key[1]}
+ path_of = {title[1]: path for path, title in title_of.items()}
+ owners: dict[str, _Key] = {}
+ group: str | None = None
+ for line in root.splitlines():
+ if line.startswith("### "):
+ group = path_of.get(line[4:])
+ continue
+ row = re.match(r"^\| (.+) \| `([^`]+)` \|$", line)
+ if row and group:
+ cell = row.group(1).replace("\\|", "|")
+ title = title_of[group]
+ heading = (group, (title, (2, cell)))
+ owners[row.group(2)] = heading if heading in topics else (group, (title,))
+
+ findings: list[str] = []
+ for rel in sorted(sections):
+ if rel not in owners:
+ continue
+ allowed: set[str] = set()
+ for key in reach(owners[rel]):
+ allowed |= topics.get(key, set())
+ stray = sorted(
+ line
+ for line in set(sections[rel].splitlines())
+ if owed[line] and line not in allowed
+ )
+ if stray:
+ findings.append(
+ f"{rel} holds {len(stray)} rule line(s) its topic does not "
+ f"reach, such as: {stray[0].strip()}"
+ )
return findings
@@ -2932,7 +3117,9 @@ def section_findings(
findings += [f"no section file holds: {line}" for line in owed - held]
findings += [f"no adopted rule is: {line}" for line in held - owed]
- findings += relation_findings(files, declined, owed, sections)
+ findings += relation_findings(
+ files, declined, owed, sections, emitted.get("AGENTS.md", "")
+ )
rules = section_rules(files, declined)
for rel in sorted(sections):
@@ -2983,6 +3170,8 @@ def planted_section_findings() -> list[str]:
door = emitted.get(f"{SECTIONS_DIR}/backend-facade/door.md", "")
paths = emitted.get(f"{SECTIONS_DIR}/base-demo/paths.md", "")
refs = emitted.get(f"{SECTIONS_DIR}/stack-more/refs.md", "")
+ replacement = emitted.get(f"{SECTIONS_DIR}/stack-stage/replacement.md", "")
+ unrelated = emitted.get(f"{SECTIONS_DIR}/stack-stage/unrelated.md", "")
follow = emitted.get(f"{SECTIONS_DIR}/base-demo/follow.md", "")
extra = emitted.get(f"{SECTIONS_DIR}/stack-more/extra.md", "")
top = emitted.get(f"{SECTIONS_DIR}/stack-top/content.md", "")
@@ -3047,6 +3236,16 @@ def planted_section_findings() -> list[str]:
"Brand theme rule" in refs,
),
("plain prose names no heading", "Name by role" not in refs),
+ ("a heading quoted across a wrapped line is carried", "Budget rule" in refs),
+ (
+ "a section named by an overridden ID carries the override alone",
+ "Replacement rule" in refs and "Unrelated rule" not in refs,
+ ),
+ (
+ "an extension of an overridden ID goes with the override alone",
+ "Venue extension rule" in replacement
+ and "Venue extension rule" not in unrelated,
+ ),
(
"a heading whose ID follows a blank line extends nothing",
"Target rule" not in fresh and "Fresh rule" not in target,
diff --git a/tools/emit_context.py b/tools/emit_context.py
index ad39af3e..c7893ddf 100644
--- a/tools/emit_context.py
+++ b/tools/emit_context.py
@@ -613,16 +613,19 @@ def _topics(adopted: Sequence[Adopted]) -> list[Topic]:
if topic.path == one.path and len(topic.key) == 2:
topic.governed = title & gone
- # An override that declares an ID of its own may be overridden in turn,
- # and then none of its rows survive to hold the ID it replaced. The last
- # surviving replacement stands for every ID down the chain, so a rule
- # that names or extends the first still finds it.
+ # An override's section may be overridden in turn, and then none of its
+ # rows survive to hold the ID it replaced. The last surviving
+ # replacement stands for every ID down the chain, so a rule that names
+ # or extends the first still finds it. Where an override's own rules
+ # survive, they alone replace it: the section it sits in may be its
+ # template's title, whose other headings replace nothing.
+ chained = {old: new & gone for old, new in replaced.items() if new & gone}
for topic in topics:
stands = topic.ids | topic.overrides
grown = True
while grown:
grown = False
- for old, new in replaced.items():
+ for old, new in chained.items():
if old not in stands and new & stands:
stands.add(old)
grown = True
@@ -644,10 +647,8 @@ def _topics(adopted: Sequence[Adopted]) -> list[Topic]:
# override, as a named ID does.
index = _heading_index(adopted)
for topic in topics:
- for row in topic.rows:
- if row["fence"] or row["heading"]:
- continue
- for text in _heading_refs(row["line"], index):
+ for prose in _prose(topic.rows):
+ for text in _heading_refs(prose, index):
for path, key, sections in _resolve_heading(index, text, topic.path):
target = by_key.get((path, key))
if target is not None and target is not topic:
@@ -689,6 +690,26 @@ def _heading_index(adopted: Iterable[Adopted]) -> dict[str, list[HeadingPlace]]:
return index
+def _prose(rows: Iterable[Row]) -> list[str]:
+ """Each paragraph or bullet of the rows outside code, its wrapped lines
+ joined, so a heading named across a line break is read whole."""
+ chunks: list[list[str]] = []
+ open_chunk = False
+ key: object = None
+ for row in rows:
+ line = row["line"].strip()
+ prose = line and not (row["heading"] or row["tag"] or row["fence"])
+ here = tuple(row["path"][:2])
+ if not prose:
+ open_chunk = False
+ continue
+ if not open_chunk or BULLET_LINE.match(row["line"]) or here != key:
+ chunks.append([])
+ chunks[-1].append(line)
+ open_chunk, key = True, here
+ return [" ".join(chunk) for chunk in chunks]
+
+
def _heading_refs(line: str, headings: Collection[str]) -> list[str]:
"""The headings a line of prose names, by their text."""
anchors = {_anchor(text): text for text in headings}
@@ -727,13 +748,10 @@ def heading_references(
resolved: list[str] = []
unresolved: list[str] = []
for one in adopted:
- for _, run in one.runs:
- for row in run:
- if row["fence"] or row["heading"]:
- continue
- for text in _heading_refs(row["line"], known):
- into = resolved if text in index else unresolved
- into.append(f"{one.path}: {text}")
+ for prose in _prose([row for _, run in one.runs for row in run]):
+ for text in _heading_refs(prose, known):
+ into = resolved if text in index else unresolved
+ into.append(f"{one.path}: {text}")
return resolved, unresolved