Skip to content
Open
38 changes: 35 additions & 3 deletions docs/for-developers/template-builder.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ builds it; its problems carry the JSON pointer. See the known limits for what th

| Code | Severity | Meaning |
|---|---|---|
| TB9300 | error | The syntax is broken (unclosed loop, …) or the file is not a DOCX/ODT template. |
| TB9300 | error | The syntax is broken (unclosed loop, …), the file is not a DOCX/ODT template, or it exceeds an upload limit (below). |
| TB9301 | error | The copy reads a path the data does not have (`DataPath` names it as the copy writes it). |
| TB9302 | error | Filling with the data's shape fails, for example a loop over a value. |
| TB9303 | warning | No stamp: edited in an application that dropped it, or not built by the builder. |
Expand All @@ -253,6 +253,22 @@ builds it; its problems carry the JSON pointer. See the known limits for what th
| TB9306 | warning | Built from an older version of a component, or from one no longer registered in `Components`. |
| TB92xx, others | error | `CheckDefinition`: the import's and the build's own codes (TB9203: unknown data path). |

**Upload limits.** An upload comes from outside, so `Check` reads the package once within limits before anything
parses it, counting what the entries really unpack to (a ZIP can declare false sizes). Exceeding a limit is TB9300 at
the entry (`word/document.xml`) or paragraph (`content.xml, paragraph 12`), and the check stops there. The defaults fit
real templates with room to spare; raise them in `TemplateCheckOptions` if yours are larger. Cap the size of the raw
upload in the host too: `Check` reads the whole stream before it looks inside.

| Option | Default | Limits |
|---|---|---|
| `MaximumEntries` | 1,000 | entries in the package |
| `MaximumUnpackedSize` | 64 MiB | bytes all entries unpack to |
| `MaximumMarkupSize` | 8 MiB | bytes the XML entries unpack to (recognised by content, not name: what the engine parses; about half a second of checking per MiB) |
| `MaximumParagraphLength` | 20,000 | characters of text in one paragraph |

The trial fill uses witness data in which a collection answers every index (`lines[999]`) with one shared item and
loops once, so it is linear in the template, however many indexes and nested loops it has.

**Changing the data.** Adding a field is safe. Renaming or removing one is a breaking change: stored templates that read
it break. Check every stored template after such a change (for example on deploy) and show the result to the users
(yellow for warnings, red for broken). The library only checks; storing templates, keeping a changelog of data
Expand Down Expand Up @@ -556,8 +572,24 @@ Export the definitions a host stores with `TemplateJsonExportOptions.TextLanguag
the JSON and an agent can read and change them; without, the texts come from the host's catalogue and the agent only
sees the keys.

A patch that cannot be applied (malformed, a missing path, a failed `test` operation, a `move` into its own child)
changes nothing and reports TB9207 at the operation (`/1` is the second). The description and the schema are generated
A patch that cannot be applied (malformed, a missing path, a failed `test` operation, a `move` or `copy` into its own
child, or a limit below) changes nothing and reports TB9207 at the operation (`/1` is the second).

**Limits.** Everything an agent sends is input from outside. Cap it in the host as well (request size, rate), and keep
these limits, which hold whatever the host does:

| Limit | Default | Exceeded |
|---|---|---|
| `TemplateJsonImportOptions.MaximumLength` | 1,000,000 characters | TB9206 at `""` (import, check, preview); a patch that would make the definition longer: TB9207 at the operation |
| `TemplateJsonImportOptions.MaximumValues` | 100,000 JSON values (objects, arrays, strings, numbers, …) | TB9206 at `""` |
| operations in one patch | 1,000 | TB9207 at `/1000` |
| depth of a patched definition | 64 levels | TB9207 at the operation |

A patch's growth is counted per operation, so a `copy` that doubles the definition is refused before memory runs
out; a patch longer than `MaximumLength` is refused at `""`, and one that copies or removes more than 16 times
`MaximumLength` in total at the operation that crosses it. `Patch` writes the result compact (as the length is counted);
`Read` gives indented parts to read. `Preview` without data fills with the contract's witness, which, like the check's, loops once and answers every
index with one item; `Preview` with data fills with the host's data as it is. The description and the schema are generated
from one vocabulary that a test compares with the reader, so they always describe what the import accepts.

## Testing your definitions
Expand Down
76 changes: 76 additions & 0 deletions docs/superpowers/plans/2026-12-02-builder-input-limits.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Builder input limits Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Check, Preview and Patch stay fast and small on hostile input (#302).

**Architecture:** a shared-item witness list for both witnesses; limit options on check and import options; size,
depth and count guards in the patch applier.

**Tech Stack:** .NET 11/10, xUnit v3, System.Text.Json, System.IO.Compression, XmlReader.

**Spec:** `docs/superpowers/specs/2026-12-02-builder-input-limits-design.md`

## Global Constraints

- Builder API is experimental (`[TPLB001]` lines in `PublicAPI.Unshipped.txt`); core untouched.
- Limits give problems (TB9300 / TB9206 / TB9207), never exceptions.
- Defaults: entries 1,000; unpacked 64 MiB; markup 8 MiB; paragraph 20,000 chars; definition 1,000,000 chars and
100,000 values; patch 1,000 operations, depth 64.

## Review Focus

- A real template (sample, 100+ paragraphs, images) passes Check and Preview unchanged.
- Indexed paths still resolve in fills (`IndexedPathTests` stay green).
- Patch: legitimate `copy`/`move` of a section still works.
- ODT uploads hit the same limits (content.xml / styles.xml, `text:p`/`text:h`).
- A damaged ZIP is not reported as a limit (the engine's syntax error stays).

---

### Task 1: Shared-item witness

**Files:** Create `src/TriasDev.Templify.Builder/Typed/WitnessList.cs`; modify `DataContract.cs` (WitnessNode.ToData),
`Typed/DataCatalog.cs` (CreateWitness); test `tests/TriasDev.Templify.Builder.Tests/InputLimitTests.cs`.

- [ ] Tests: `Preview_DeepIndexedPath_IsFastAndSmall` (definition with `{{c0[999].c1[999].c2[999].leaf}}`, Preview
without data completes < 1 s, allocations < 100 MB, a document comes back);
`Check_IndexedPlaceholderAndNestedLoops_IsFastAndSmall` (DOCX with `{{order.lines[999].description}}` and three
nested loops over catalogue collections; Check < 1 s, < 100 MB); `Witness_IndexedItem_Resolves`.
- [ ] Run, watch the first two fail (timeout/OOM guard via allocation assertion).
- [ ] `WitnessList(object? item, int count)`: `IList`, read-only, enumerates `[item]`.
- [ ] Green, plus `IndexedPathTests`, `DataContractTests`, `TemplateCheckTests`.

### Task 2: Definition limits (TB9206)

**Files:** `Json/TemplateJsonImportOptions.cs`, `Json/TemplateJson.cs` (Import), `BuildContext.cs` (code), PublicAPI.

- [ ] Tests: just below / just above for `MaximumLength` and `MaximumValues` (Import throws TemplateBuildException with
TB9206 at `""`; CheckDefinition returns it as a problem).
- [ ] Implement; count values iteratively over the parsed `JsonElement`.

### Task 3: Patch limits (TB9207)

**Files:** `Json/JsonPatch.cs`, `Json/TemplateJson.cs` (Patch passes limits).

- [ ] Tests: `Patch_SelfCopies_AreRefused` (23 × copy `/content` → `/content/-`: not applied, TB9207, < 1 s);
`Patch_CopyIntoItsOwnSource_IsRefused`; `Patch_TooManyOperations` (1,000 ok-shaped `test` ops pass, 1,001 → TB9207
at `/1000`); `Patch_TooDeep` (TB9207, no exception); size just below/above with a small `MaximumLength`.
- [ ] Implement `JsonPatch.Apply(document, patch, maximumLength)`.

### Task 4: Check limits (TB9300)

**Files:** `TemplateCheck.cs` (options), `TemplateInspector.cs` (pre-scan), new `PackageLimits.cs`.

- [ ] Tests per limit, DOCX and ODT where it matters: entries, unpacked (zip with a large stored media entry), markup,
paragraph length (just below Ok, just above TB9300 with Location naming the entry); a damaged ZIP keeps its old
result.
- [ ] Implement a pre-scan reading every entry through a counting stream; XmlReader (DTD prohibited) for paragraph
text in `.xml` entries.

### Task 5: Property test, docs, core issue

- [ ] `Limits_RandomNestingAndIndexes_StayBounded`: seeded random definitions (loop depth 1–6, indexes 0–999) through
Preview and CheckDefinition + built upload through Check; each < 2 s and < 100 MB.
- [ ] Docs: limits table and the agent-input sentence in `docs/for-developers/template-builder.md`.
- [x] Core issue #321 for the quadratic unterminated-tag scan.
40 changes: 40 additions & 0 deletions docs/superpowers/specs/2026-12-02-builder-input-limits-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Builder: limits for Check, Preview and Patch on untrusted input (#302)

**Status:** approved without a design checkpoint (the maintainer accepts the reviewer's proposal, issue #302).

## Intent

`TemplateInspector.Check`, `TemplateJson.Preview` and `TemplateJson.Patch` are called by an agent host with input it
does not control. A few hundred bytes must not exhaust memory or keep a core busy for minutes. Every limit gives a
result with a problem, never an exception.

## Goals

- The three inputs from the issue (indexed placeholder + 3 nested loops in an upload; `c0[999].c1[999].c2[999]` in a
definition; 23 self-copies in a patch) return within 1 s and well under 100 MB.
- Limits on uploads (Check), definitions (Import and everything built on it) and patches, with documented defaults.

Non-goals: limits on the host's own data in `Preview(…, data)` (the host owns it); the core's quadratic scan of
unterminated tags (a separate core issue; the paragraph limit below bounds it for Check).

## Design

1. **Witness: one shared item per collection.** A collection in witness data is a `WitnessList`: a read-only `IList`
whose `Count` is what the highest index needs (`[999]` → 1000), whose indexer returns the one shared item, and which
*enumerates one item*. The core indexes through `IList` and loops through `IEnumerable`, so indexed paths resolve
and every loop runs once. Witness data is linear in the contract, and a trial fill or a preview without data is
linear in the template. Used by `DataContract.CreateWitness` (Preview, test kit) and `DataCatalog.CreateWitness`
(Check). Ruling: with one enumerated item there is no product of loop sizes left, so no separate fill budget.
2. **Check limits** in `TemplateCheckOptions`, counted while reading the package (declared sizes can lie):
`MaximumEntries` (1,000), `MaximumUnpackedSize` (64 MiB, all entries), `MaximumMarkupSize` (8 MiB, `.xml`/`.rels`
entries: what the engine parses), `MaximumParagraphLength` (20,000 characters of text in one paragraph). Exceeding
one is TB9300 at the entry (`word/document.xml`), the paragraph limit also names the paragraph number. The check
stops there (no validation, no fill).
3. **Definition limits** in `TemplateJsonImportOptions`: `MaximumLength` (1,000,000 characters) and `MaximumValues`
(100,000 JSON values: objects, arrays, strings, numbers, …). Exceeding one is the new code TB9206 at `""`. All JSON
functions that import (Import, CheckDefinition, Patch's check, Preview) inherit them.
4. **Patch limits**: at most 1,000 operations; the patched document's size, estimated per operation (stored length,
plus the value's length for add/replace and the copied node's serialised length for copy/move), stays within the
import's `MaximumLength`; its depth stays within 64 (the target pointer's tokens plus the value's depth); `copy`
into its own source is refused like `move`. Each is TB9207 at the operation (`/n`).
5. **Docs**: the developer docs list the limits and defaults, and tell hosts to cap agent input.
3 changes: 3 additions & 0 deletions src/TriasDev.Templify.Builder/BuildContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ internal static class DiagnosticCodes
/// <summary>A theme value the host sets on import names a token the definition's theme does not have; it is not used.</summary>
public const string UnusedThemeValue = "TB9205";

/// <summary>A JSON definition is longer or has more values than the import options allow.</summary>
public const string DefinitionTooLarge = "TB9206";

/// <summary><see cref="TemplateComposer.Page"/> was called more than once.</summary>
public const string PageAlreadySet = "TB6001";

Expand Down
10 changes: 6 additions & 4 deletions src/TriasDev.Templify.Builder/DataContract.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,9 @@ public string ToJson()
}

/// <summary>
/// Builds data in which every path of the contract exists: each collection holds one item (or as many as its highest
/// index needs, <c>items[2]</c> → three), every item with the shape of all its uses; each value is the text <c>"x"</c>.
/// Builds data in which every path of the contract exists: each collection holds one item, with the shape of all its
/// uses, which every index reads (<c>items[2]</c> is that item too); each value is the text <c>"x"</c>. A loop over
/// it runs once.
/// </summary>
/// <returns>The data, as nested dictionaries and lists.</returns>
public IReadOnlyDictionary<string, object?> CreateWitness()
Expand All @@ -139,7 +140,7 @@ public string ToJson()

// items[] (every item) or items[2] (one item): the same item shape, at least index + 1 items.
string index = segment[(bracket + 1)..^1];
node = node.Child(segment[..bracket]).Item(index.Length == 0 ? 1 : int.Parse(index, System.Globalization.CultureInfo.InvariantCulture) + 1);
node = node.Child(segment[..bracket]).Item(index.Length == 0 || !int.TryParse(index, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int at) ? 1 : Math.Min(at, int.MaxValue - 1) + 1);
}

if (entry.Usage == ContractUsage.Collection)
Expand Down Expand Up @@ -337,7 +338,8 @@ public WitnessNode Item(int count = 1)
{
if (_item != null)
{
return Enumerable.Range(0, _count).Select(_ => _item.ToData()).ToList();
// One shared item, however high the index (#302): building each anew grows as count^depth.
return new WitnessList(_item.ToData(), _count);
}

if (_children.Count > 0)
Expand Down
Loading
Loading