# Browser tree growth core

The current branch-first pipeline uses `agenda-tree-bough-growth.mjs`, `agenda-tree-bough-composition.mjs` and `agenda-tree-bough-foliage.mjs`: authored macro gestures, forward-grown child axes, then foliage pooled from their distal sites. It accepts no old crown destinations or crown-clearance objective. The browser editor is `ai-safety-agendas-boughs.html`; frozen publication and redraw inputs live in `assets/agenda-tree-kit/bough/`.

The earlier `agenda-tree-growth.mjs` is a selected, two-dimensional JavaScript adaptation of MTree's C++ generation core, also used by the preserved legacy editor. It does not run Blender. Its optional target-steering mode, documented below, belongs to that earlier routing API; the new bough pipeline calls target-free growth. Taxonomy and label layout remain separate from the growth core.

Upstream was inspected at commit **36d556111c1b0784220f2035d053688bc8def4a5**. The C++ library has its own [MIT license](https://github.com/MaximeHerpin/modular_tree/blob/36d556111c1b0784220f2035d053688bc8def4a5/m_tree/LICENSE.md), Copyright (c) 2021 MaximeHerpin. Its complete notice is preserved in `vendor/mtree/LICENSE.md`. The repository-root GPL license applies to the Blender integration; no Blender Python interface was ported.

## Functions adapted

- [`TrunkFunction::execute`](https://github.com/MaximeHerpin/modular_tree/blob/36d556111c1b0784220f2035d053688bc8def4a5/m_tree/source/tree_functions/TrunkFunction.cpp): extend an axis in short steps, inherit the previous direction, add random variation and upward attraction, normalize, and interpolate radius through a shaped progression. These operations are used by `growAxis`.
- [`BranchFunction::get_main_child_direction`, `get_origins`, `grow_node_once`](https://github.com/MaximeHerpin/modular_tree/blob/36d556111c1b0784220f2035d053688bc8def4a5/m_tree/source/tree_functions/BranchFunction.cpp): incremental heading inheritance, side origins distributed by distance along a parent, and distinct main continuation versus side-branch direction. `branchOrigins` samples a supplied parent axis by actual arc length. `forkDirection` supplies a planar side direction.
- [`PipeRadiusFunction::update_radius_rec`](https://github.com/MaximeHerpin/modular_tree/blob/36d556111c1b0784220f2035d053688bc8def4a5/m_tree/source/tree_functions/PipeRadiusFunction.cpp): terminal radii feed a bottom-up radius calculation, `r = (sum(childRadius ** exponent)) ** (1/exponent) + constantGrowth * segmentLength / 100`. `pipeRadii` implements this recurrence directly.
- [`Node` / `NodeChild`](https://github.com/MaximeHerpin/modular_tree/blob/36d556111c1b0784220f2035d053688bc8def4a5/m_tree/source/tree/Node.hpp): geometry nodes and their parent attachments are distinct from mesh vertices. The browser interface similarly keeps input topology separate from points and radius arrays.

## Deliberate browser and illustration adaptations

Coordinates are 2D and positive y points down. `unitScale` converts drawing units to growth units (default 48 drawing units per growth unit). Randomness uses one local seeded generator rather than MTree's combination of a C random generator and `std::mt19937`; identical inputs give identical browser output, but do not reproduce MTree's exact seeded shape.

When a target is supplied, growth also steers toward that target. A monotonic coordinate along source-to-target constrains every step; a smooth residual correction reaches the target exactly. This prevents backwards loops without selecting a different parent. It is an added constraint for a labelled diagram, not an upstream MTree feature. A zero-distance target produces two identical endpoints and zero length. For nonzero targets, `length` controls sampling density; the requested target fixes the end position, and the returned `length` is measured along the resulting curve.

`forkDirection` uses an exact planar rotation; upstream approximates its split angle by interpolation. `branchOrigins` generates exactly the requested number of ports instead of choosing a botanical bud count. Semantic relationships and optional construction-only splits must be decided by the caller.

`pipeWidths` adapts this project's attachment-aware Python profile to the actual `pipeRadii` recurrence. It computes subtree transport demand with `pipeRadii`, distributes each parent's authored child-flow budget in proportion to that demand, and withdraws this flow around each real attachment. It also smooths taper and retains support at near-terminal forks. It is distinct from the unnormalised `pipeRadii` recurrence: illustrated base/tip widths constrain its result. Neither width function represents research importance.

The port does not include MTree's experimental `GrowthFunction` vigor simulation, automatic branch death, gravity deformation, 3D manifold mesher, leaves, Python bindings, or Blender UI. It does not copy the upstream disabled pruning branch (`cut && false`) or its mixed global random state. Continuous 2D wood silhouettes and foliage rendering remain separate from the growth core.

## API

```js
import {
  growAxis, routeBranch, forkDirection, branchOrigins,
  pipeRadii, pipeWidths, createRng
} from './agenda-tree-growth.mjs';

const axis = growAxis({
  start: [0, 100], direction: [0, -1], target: [90, 0],
  step: 6, randomness: 0.2, upward: 0.1, seed: 'agenda-id',
  radius0: 12, radius1: 0.8
});
// { points: [[x,y], ...], radii: [...], distances: [...], length }

const points = routeBranch({
  start: [0, 100], end: [90, 0], parentTangent: [0, -1],
  seed: 'agenda-id', bend: 0.25, upward: 0.12, count: 40
});

const ports = branchOrigins(points, { count: 3, start: 0.3, end: 0.9 });
// [{ point: [x,y], direction: [dx,dy], t: normalizedArcLength }, ...]

const radii = pipeRadii([
  { id: 'fork', children: ['a', 'b'], length: 20 },
  { id: 'a', children: [], tipRadius: 2 },
  { id: 'b', children: [], tipRadius: 3 }
], { exponent: 2, constantGrowth: 0 });
// radii.fork === Math.sqrt(13)

const profiles = pipeWidths({
  parent: { points, parentId: null, width0: 24, width1: 3 },
  child: { points: [ports[0].point, [110, -20]],
    parentId: 'parent', width0: 8, width1: 0.7 }
}, { exponent: 2.5, thickness: 1 });
// { parent: [fullWidthAtEachPoint, ...], child: [...] }
```

`growAxis` defaults to at most 2,048 steps and accepts a maximum of 8,192. Invalid numeric parameters and malformed/cyclic radius topologies are rejected. `pipeRadii` uses iterative postorder evaluation so a long internode chain does not exhaust the JavaScript call stack.

## Why JavaScript here

The selected functions need only elementary vector arithmetic, a seeded random generator and tree traversal. They can run in a worker or directly for bounded previews, and their arrays feed the site's vector renderer. Porting this subset keeps geometry inspectable and does not introduce a 3D renderer or build toolchain.

A WebAssembly version of the MIT core is also feasible: compile the core plus Eigen with Emscripten and expose flat node/mesh buffers through a C interface. The present upstream CMake configuration unconditionally builds Python bindings and tests, so a browser build would need a separate target. WASM is more appropriate if the application later needs MTree's full 3D manifold mesher; it offers no necessary functionality for the current 2D branch subset. The browser pipeline has no WASM build or Blender dependency.

## Forward-grown boughs

`agenda-tree-bough-growth.mjs` adds the part that the first port left to the caller: growing successive branch stages from a carrier **before** composing foliage. Changing a recipe creates a new candidate; ordinary artwork replacement repaints the saved composition without regrowth. The taxonomy is not inferred from botanical growth.

The active upstream mechanisms are specific:

- [`BranchFunction::get_origins`, lines 213–292](https://github.com/MaximeHerpin/modular_tree/blob/36d556111c1b0784220f2035d053688bc8def4a5/m_tree/source/tree_functions/BranchFunction.cpp#L213-L292) selects branches created by the parent generation stage, spaces origins by physical distance (`1 / (branches_density + .001)`, line 219), and evaluates angle, radius and length properties at the origin's normalized position within the fertile parent interval (lines 263–270). Regular spacing **along wood** is not regular clearance between projected crowns.
- [`TreeFunction::execute_children`, lines 5–12](https://github.com/MaximeHerpin/modular_tree/blob/36d556111c1b0784220f2035d053688bc8def4a5/m_tree/source/tree_functions/base_types/TreeFunction.cpp#L5-L12) and [`BranchFunction::execute`, lines 294–300](https://github.com/MaximeHerpin/modular_tree/blob/36d556111c1b0784220f2035d053688bc8def4a5/m_tree/source/tree_functions/BranchFunction.cpp#L294-L300) create recursive generation stages. Different stage parameters produce different branching levels; the inspected code has no universal branch-order-to-length formula.
- [`Property.hpp`, lines 12–66](https://github.com/MaximeHerpin/modular_tree/blob/36d556111c1b0784220f2035d053688bc8def4a5/m_tree/source/tree_functions/base_types/Property.hpp#L12-L66) supports constant, random and shaped-curve properties. The prototype uses an original piecewise-linear knot representation to make the position-dependent profiles explicit and serializable.

`growBough` uses these stage/origin/profile mechanisms with target-free `growAxis`. Its stages select earlier stages by ID. Origins use physical `spacing` in drawing units or explicit arclength ports; length, initial radius scale and angle are evaluated at each origin. The actual parent port determines every root. No endpoint target or old crown frame is accepted. Zero heading randomness is the default, so uneven reach comes from profiles and branch topology rather than jittering label positions.

The adaptation is intentionally smaller than MTree. It uses alternating planar fork sides instead of 3D phyllotaxis. It does not implement the upstream probabilistic within-stage split loop, gravity or branch death. A rectangular bough envelope and local centerline intersection stops bound the prototype; those are illustration constraints, not upstream algorithms. They stop a branch and report why rather than moving its root or steering it to a target. A stopped branch is re-tapered over its surviving length to the configured terminal radius; this is an authoring adaptation, not preservation of the upstream unfinished radius at the cut. Thick painted-wood clearance, final self-contact review and label readability remain the composition caller's responsibility. `existingAxes` lets separately grown boughs and the fixed macro scaffold participate in the centerline check; only the local actual-parent/ancestor joint can overlap.

Distal `leafSites` are **our branch-local foliage sampling contract**, not a port of MTree leaf source. The pinned Git tree lists both `LeavesFunction.cpp` and `LeavesFunction.hpp` as zero-byte files. The Blender interface instead calls `distribute_leaves`, which attaches a Geometry Nodes group named `leaves_distribution` from `resources/geo_node/geo_nodes_2_93.blend` ([operator](https://github.com/MaximeHerpin/modular_tree/blob/36d556111c1b0784220f2035d053688bc8def4a5/python_classes/operators.py#L28-L39), [resource wrapper](https://github.com/MaximeHerpin/modular_tree/blob/36d556111c1b0784220f2035d053688bc8def4a5/python_classes/resources/node_groups.py)). None of that GPL Blender integration is copied into the browser module.

A read-only inspection of the pinned `.blend` resource found the stored `leaves_distribution` graph: `Attribute Map Range` maps the mesh `radius` attribute into `leaves_density` (radius 0 → density 1; configurable radius threshold → density 0); `Point Distribute` consumes that density with `Distance Min` 0; direction/tangent attributes feed rotation alignment; `Point Instance` receives a twig object; `Join Geometry` combines instances with wood. Density and size are group inputs. This is foliage placed on thin branch geometry, not packing closed crown silhouettes. Blender 4.3.2 preserved the old 2.93 nodes' sockets and links but marked several node types undefined, so this is inspection of serialized graph data, not a successful evaluation of the legacy modifier. The new browser leaf-site implementation does not reproduce its point-distribution sampler or copy the graph.

Each leaf site names a real axis, exact arclength position, tangent and supporting distal interval. Its radii are suggestions for composing continuous foliage. Sites sharing a first-order structural ancestor have a common `bundleId`; a bundle is not a semantic topic. The renderer can union overlapping contributions into larger masses and leave absent-shoot corridors open. Label/hit cores are assigned afterward, separately from painted mass. This API deliberately has no crown-edge-gap objective, label count, label frames or semantic parent reassignment.

```js
import { growBough, sampleBoughAxis, branchProperty } from './agenda-tree-bough-growth.mjs';

const bough = growBough({
  id: 'training-pilot', ownerId: 'training',
  parentAxis: { id: 'macro', points: [[0, 20], [0, 0], [0, -80]], widths: [30, 25, 15] },
  attachmentT: .2,
  leader: { length: 180, direction: [.3, -1], radius0: 10, upward: 0 },
  stages: [
    { id: 'limbs', start: .15, end: .95, spacing: 32,
      length: [[0, 90], [.5, 120], [1, 40]], angleDegrees: [[0, 62], [1, 30]],
      radiusScale: .55, leafBearing: true, upward: 0 },
    { id: 'shoots', parents: 'limbs', start: .45, end: .96, spacing: 22,
      length: [[0, 38], [1, 17]], angleDegrees: 38, radiusScale: .4,
      leafBearing: true, leafStart: .45, upward: 0 }
  ],
  // Optional: envelope: { bounds: [xmin, ymin, xmax, ymax] }, existingAxes: [...]
});
// { axes, leafSites, bundles, diagnostics }
// axes: id, ownerId, parentAxisId, attachmentT, order, stageId, bundleId,
//       points, widths, length, requestedLength, growthFactor, leafBearing
// leafSites: axisId, bundleId, t, point, tangent, radiusAlong, radiusAcross,
//            support: { axisId, t0, t1 }
```

The primitive is deterministic and does not mutate its inputs. Bud/site counts are checked before allocating large lists. Defaults cap it at 256 axes, 4,096 foliage sites, eight stages and 128 points per axis; oversized requests fail explicitly. Focused regression tests cover actual attachment provenance, position-dependent reach, physical density under scaling, recursive bundle membership, stopping at bounds/crossings, deterministic input preservation and bounded budgets:

```sh
node --test --test-isolation=none tests/agenda-tree-bough-growth.test.mjs
```

## Browser-callable composition recipe

`agenda-tree-bough-composition.mjs` exports `composeBoughs({macroAxes, controls, semanticNodes, width?, height?, options?})`. It consumes already-loaded arrays/objects and has no filesystem, DOM, absolute paths or saved foliage layout dependency. `semanticNodes` may be an array or ID map; each record supplies canonical `id`, `parentId`, `kind` and optional `name`. Every supplied macro axis must have a known semantic owner and actual widths.

`controls.mainBoughs` selects the agenda owners to grow from real macro ports. Each main control accepts `leader` and `stages` overrides; the initial Training/Oversight formulas are defaults, not required uniform profiles. Optional `fineBoughs` entries select exact owned carriers, ports and growth profiles for individual threads. Otherwise all canonical thread children are assigned substantial owned bearings and grown with a bounded local retry. No child can be silently omitted or attached to another semantic owner. Old recipe-specific shortening is represented explicitly by `fineLengthScale`, rather than an agenda ID inside the engine.

Optional `macroOverrides` replace explicitly selected macro gestures using authored spline anchors. Their declared parent must still be the canonical parent, roots are sampled from its actual axis, sampling has a fixed budget, and input arrays remain unchanged. These are authored large-scale controls, not forward-grown fine branches. Returned `overriddenMacroIds` tells the caller which macro paths need recompilation.

For a terminal continuation, `leader.continuation` prepares the shared basal bearing **before** descendants grow, then checks the resulting bounded axis again. This avoids the old prototype's post-growth smoothing, which could move the parent arclength under already-attached child roots. `collisionClearance` is optional: when an actual centerline crossing is detected, it retreats the stopping tip by the participating radii and requested clearance, accounting for crossing angle. It prevents a stopped tip from falsely merging into the obstacle. It does not detect every parallel near-miss; final actual-painted clearance still belongs to the composition audit.

The adapter returns `{version, seed, controls, macroAxes, axes, leafSites, structuralBundles, semanticBundles, diagnostics, overriddenMacroIds, width?, height?}`. It deliberately returns no rendered `woodPaths`: browser/CLI callers compile these same arrays using the common ribbon/junction renderer. `semanticBundles` preserve canonical topic IDs and parent IDs; `structuralBundles` describe grown branch ancestry. Labels and shared canopy paint remain a later composition stage.

```js
import { composeBoughs } from './agenda-tree-bough-composition.mjs';
const graph = composeBoughs({ macroAxes, controls, semanticNodes });
// Changing controls recomputes axes and distal sites, rather than replaying a
// saved pilot or deforming old crown frames.
```

```sh
node --test --test-isolation=none tests/agenda-tree-bough-growth.test.mjs tests/agenda-tree-bough-composition.test.mjs
```

## Browser foliage and static main-map adapter

`agenda-tree-bough-foliage.mjs` exports `composeBoughFoliage({graph, skins, semanticNodes, options})`. It pools actual distal sites into asymmetric fan patches, preserving structural group membership independently from semantic label cores. `resolveFoliagePatch` returns SVG affine matrices (and explicitly named Shapely matrices for the Python authoring path). Source SVG skins and their measured alpha contours come from `references/agenda-bough-skins.json`; `scripts/export-agenda-bough-skins.py` regenerates that cache with source SHA-256 digests after a skin replacement. Coverage is tested against the measured silhouette, including holes. A semantic owner can be supported by another patch in the same structural group, but must have an actual owned site inside that group's paint. Bounds alone never establish support.

The initial browser port matched the Python pilot's 25 source clusters, asset selections and affine matrices (maximum matrix difference `5.69e-14`). This is pooling/transform parity, not a claim that the entire illustration or labels have passed visual review. Paint is unioned across each palette family; the broad shadow is the union minus its translated union. Individual patch shadow layers would reintroduce visible badge borders. Bud counts, contours, axes and patch counts remain bounded. Label fitting, final painted contacts and readable overview composition require their own audits.

`scripts/build-agenda-bough-art.py` adapts a matched source graph, compiled wood and packed composition to the normal map artifact. It preserves canonical branch parents and IDs, the existing ground/Cooperative AI/shoggoth layers, and applies explicit goblin registration overlays. Physical construction IDs remain attached to semantic branches; complete source axes stay in the separately hashed graph. Regions carry `groupIds`, `hitClip`, `labelClip`, `labelLayout`, `focusBox` and fine-topic `focusParentId`. The optional nonzero canvas origin is exposed as `viewBox`/`fullBounds`, leaving rig coordinates unchanged.

A candidate requires explicit output paths and either `--review` or `--production`. Review mode records missing label cores and unsupported groups without silently substituting old crown positions; production rejects those failures and compositions marked `nonProduction`. The default cannot overwrite the live map; an explicit validated production invocation can. The adapter also checks the source graph digest, real parent-root bindings, actual skin coverage and canonical ownership before writing output. Tests run with the same Python environment as the asset kit:

Publication also checks branch captions using the local handwriting font's actual glyph contours on the renderer's rounded quadratic paths. Ink must remain inside its owner's exposed painted wood, and the requested font size must fit without automatic shrinking. Distinct caption phrases retain at least 0.35 times the smaller font size between their ink contours; this typography rule does not impose gaps between canopy masses. A redrawn canopy that preserves its topic label and support sites can still fail this check if it covers a branch caption. Glyph counters remain empty; letter bounding boxes are not substituted for actual ink. This is an authored world-coordinate check: browser validation still covers responsive rendering, zoom caps, font metrics and animated character clearance. The Mechanistic Interpretability caption retains its published motion-safe placement until a complete motion sweep approves any alternative.

Semantic label validation also replays the actual family paint order. A label covered by a later foreign family's foliage cannot pass because its own hidden layer contains it. Saved Alice ink is checked in the surviving visible owned paint; hit, label and focus coverage use that same visible territory. Later shading within the same family preserves ownership. Asset replacement rebuilds the union and repeats these checks without silently moving the saved labels.

```sh
python -m unittest discover -s tests -p test_agenda_bough_art.py
```
