# Integrating algorithms

> This section covers the two ways protocols connect to work.

Page: PAG · Patterns
Canonical: https://banes-lab.com/pag/patterns#algorithm-integration

This section is stop 30 of 102 in the learning route. Previous: [04 - Algorithm examples](https://banes-lab.com/pag/patterns/algorithm-examples.md). Next: [17 - Detect, log, fix](https://banes-lab.com/disciplined-methodology/build/detect-log-fix.md). It builds on [03 - Genesis stages](https://banes-lab.com/pag/patterns/genesis-stages.md).

This section covers the two ways protocols connect to work. Instantiation takes a request to a chain of nodes, in the order shown in [E1·d instantiation order](https://banes-lab.com/pag/patterns#algorithm-integration-panel-d) and written in [E1·a instantiation](https://banes-lab.com/pag/patterns#algorithm-integration-panel-a): the transition the request asks for is named, the protocol is chosen by fit, its placeholders are bound to the task's nouns, and its chain is expanded into tagged nodes, each with a contract and a gate. Distillation takes repeated behaviour to one shared base, and it is a document type of its own. It is an epistemology walked on the reasoning axis, gated on evidence that the base is universal, invariant, foundational, enforceable and load-reducing, the five properties named in [E1·c boundary principles](https://banes-lab.com/pag/patterns#algorithm-integration-panel-c). A distillation is incomplete until the old pattern is proven gone, as shown in [E1·e distillation order](https://banes-lab.com/pag/patterns#algorithm-integration-panel-e), and [E1·b distillation](https://banes-lab.com/pag/patterns#algorithm-integration-panel-b) is the grammar's own template for it.

### Instantiate and distil

A base promoted from one instance, or from a resemblance, carries that instance's accidents into everything that extends it. A base is raised from two classes whose names rhyme, three later classes are forced to extend it, and each one overrides most of what it inherited because the shared half was the name. A base is a promise that every future instance shares one behaviour, and a promise made from one instance or from a naming resemblance has nothing to be checked against.

For this reason a shared base has to be earned by behaviour shown in more than one place, and a resemblance between names earns nothing. The classes are signed from their behaviour and the five principles decide, rather than a base being raised from what the names have in common. In practice, instantiation names the transition first, chooses the protocol whose use-when fits it and records the reason, binds each placeholder to a noun the task owns, and expands the chain into nodes whose contracts read the previous output and whose gates carry three to five checks with evidence. Distillation starts only after what exists has been measured and the candidates ranked by worth. Every class is signed from its behaviour, each of the five boundary principles is proven with the evidence that shows it, the base is composed within its size limit, each target is migrated reversibly starting from the simplest, and the whole scope is scanned for the old pattern before anything is declared complete.

To check this, name for a base the second instance that justified it, the behavioural signature each class was signed with, and the evidence behind each of the five principles. A base with one instance, a signature based on names, or an unproven principle is a base its next class overrides more than it inherits. Distillation decides whether a shared base is justified, and when a shape earns a template at all is described in [core templates](https://banes-lab.com/pag/templates/templates-core.md).

The transition comes first because the protocol is selected by it, as described in [from intent to structure](https://banes-lab.com/pag/patterns/intent-to-structure.md), and instantiation ends when no placeholder survives.

Distillation measures before it proposes, because a missing adoption of an existing base looks like a missing [abstraction](https://banes-lab.com/records/arch/abstraction.md) until the registry has been read. A class's signature covers initialisation, lifecycle, [error handling](https://banes-lab.com/records/arch/error-handling.md), state and dependencies. The base consists of concrete responsibilities plus abstract hooks, which is the [template method pattern](https://banes-lab.com/records/arch/template-method-pattern.md), and a single stray occurrence outside the approved locations is a refutation whose result line routes back to composition. The last gate measures the reduction rather than asserting it, so the [single source of truth](https://banes-lab.com/records/arch/single-source-of-truth.md) for which bases exist is the registry, never the memory of the model or the developer that did the distilling.

E1·a instantiation

```pag
# instantiation · from a request to a gated node chain

# STEP 1: the transition · what state of the tree the request asks for
Request:    "route each incoming request to the handler that owns it"
Transition: <a registry that resolves a handler by a request's type>

# STEP 2: the protocol · by semantic fit against each use-when, with the reason
Chosen:     <resolve-through-a-registry>
Reason:     "keyed resolution is justified · handlers vary, the key does not"
Chain:      ANALYZE → FIND → CREATE → LINK → VERIFY

# STEP 3: the nouns · the task's own, so no placeholder survives
<candidates> = the handlers declared in {project.handler_registry}
<key>        = <request>.<type>

# STEP 4: the nodes · one per verb, tagged with its stage, each contract reading the prior output
# NODE 1 — ANALYZE THE REQUESTS   [epistemic · analysis · logic · yields: set]
@genesis: difference
CONTRACT:
input:     <queue>
transform: READ_RESOURCE <queue> INTO <incoming>; EXTRACT_FACTS <type> FROM <incoming> INTO <keys>
output:    <keys>, one per request
HANDOFF GATE:
[check] <incoming> read from <queue> (evidence: the read returned requests)
[check] a <key> resolved for every <request> (evidence: the two counts match) over: <incoming> measured: <keyed> / <requests>
[check] no <request> carries an unknown <type> (evidence: every key in the declared set)
result: pass → NODE 2 | unknown type → REPAIR (owner: NODE 1) | unknown → BLOCKED

# NODE 2 — FIND THE HANDLER       [epistemic · ontology · set-theory · yields: set]
@genesis: existence
CONTRACT:
input:     <keys> from NODE 1
transform: FOR EACH <key> IN <keys>: FIND <handler> IN <candidates> WHERE <handler>.<owns> == <key> INTO <matched>
output:    <matched>
HANDOFF GATE:
[check] exactly one <handler> per <request> (evidence: the two counts match, no duplicates) over: <keys> measured: <matched> / <keys>
[check] every <handler> in <matched> is declared in {project.handler_registry} (evidence: a lookup per handler)
[check] an unmatched <request> reported, never dropped (evidence: the report names each)
result: pass → NODE 3 | duplicate handler → REPAIR (owner: NODE 2) | unknown → BLOCKED

# NODE 3 — CREATE THE ROUTE       [epistemic · formalisation · computation · yields: procedure]
@genesis: structure
CONTRACT:
input:     <matched> from NODE 2
transform: COMPOSE_ARTIFACT <route> FROM <matched> USING <the route shape here>
output:    <route>
HANDOFF GATE:
[check] <route> names its <handler> and its <key> (evidence: both fields non-empty)
[check] one <route> per <matched> entry (evidence: the two counts match) over: <matched> measured: <routed> / <entries>
[check] <route> conforms to <the route shape here> (evidence: VALIDATE_ARTIFACT passed)
result: pass → NODE 4 | nonconforming → REPAIR (owner: NODE 3) | unknown → BLOCKED

# NODE 4 — LINK THE ROUTE         [epistemic · reasoning · graph · yields: edge-list]
@genesis: relation
CONTRACT:
input:     <route> from NODE 3
transform: LINK <route> TO <the dispatch table>
output:    the dispatch entry
HANDOFF GATE:
[check] <route> resolves from <the dispatch table> (evidence: a lookup returns it)
[check] no earlier <route> for <key> remains (evidence: one entry per key) over: dispatch entries measured: <one per key> / <keys>
[check] nothing else in <the dispatch table> changed (evidence: a diff of the entries)
result: pass → NODE 5 | stale entry → REPAIR (owner: NODE 4) | unknown → BLOCKED

# NODE 5 — VERIFY THE DISPATCH    [evaluative · verification · logic · yields: boolean]
@genesis: constraint
CONTRACT:
input:     the dispatch entry from NODE 4
transform: EXECUTE_TOOL <route> WITH <request> INTO <response>; PERSIST_ARTIFACT <response> TO <outbox>; EXECUTE_TOOL {toolchain.verify_command} INTO <verdict>; VALIDATE_ARTIFACT <verdict> AGAINST <green on one full run>
output:    <verdict>
HANDOFF GATE:
[check] <response> persisted (evidence: a read of <outbox> returns it)
[check] <response>.<handled-by> equals <matched>.<handler> (evidence: the two values) over: <requests> measured: <handled by the matched handler> / <requests>
[check] <verdict> green on one full run (evidence: the run's own output)
refuse: <outbox> changed since it was read before PERSIST_ARTIFACT
standing: moved-set <the files changed since NODE 4>
result: pass → TERMINATE | wrong handler → REPAIR (owner: NODE 2) | unknown → BLOCKED
```

E1·b distillation

```pag
---
name: {task_name}
type: DISTILLATION
version: 1.0.0
---

THIS DISTILLATION DISTILLS repeated behavioural evidence into one justified shared abstraction, and is incomplete until the old pattern is proven gone.

%% META %%:
priority: BEHAVIORAL_EVIDENCE > BOUNDARY_PRINCIPLES > TASK
trust: procedural_scan = TRUSTED, naming_similarity = UNTRUSTED, prior_knowledge = UNTRUSTED
objective: {task_description}
jurisdiction: {task_description} across the role families {convention.role_taxonomy} names | external: every family the scope does not name
recursion_limit: 3

# NODE 1 — ORIENT   [epistemic · ontology · set-theory · yields: set]
@purpose: "load the registry and rule sources, probe capabilities, and measure the existing baseline before proposing any base"
@genesis: existence
CONTRACT:
input:     {task_description}
transform: READ_RESOURCE {project.architecture_registry} INTO registry; READ_RESOURCE {project.rule_sources} INTO rules; EXECUTE_TOOL <capability probes> WITH timeout: <bound> INTO capability; EXTRACT_FACTS <existing bases, implementation counts, hierarchy depth> FROM registry INTO baseline; FOR EACH role IN {convention.role_taxonomy}: ANALYZE_CONTENT <its classes> AGAINST <the expected base> INTO gap
constraints: compare against existing bases before proposing a new one; a missing adoption is not a missing abstraction
output:    baseline_bundle
DECLARE baseline_bundle: object
SET baseline_bundle = {registry: registry, rules: rules, capability: capability, baseline: baseline, gap: <adoption versus abstraction per role>}
HANDOFF GATE (evidence-bearing):
rule_id: "ORIENT"   yields: boolean
[check] the registry and rule sources are loaded with provenance (evidence: baseline_bundle.registry and rules)
[check] the existing architecture is measured (evidence: baseline_bundle.baseline) over: existing bases measured: <measured> / <bases>
[check] the compliance gap distinguishes adoption from abstraction (evidence: baseline_bundle.gap)
refuse: a probe that would mutate the tree before EXECUTE_TOOL
result: pass → NODE 2 | context unavailable → BLOCKED | unknown → BLOCKED

# NODE 2 — INTENT   [conative · teleology · optimisation · yields: ranking]
@purpose: "score every candidate anti-pattern by worth and gate on the highest-worth one and its highest-worth remediation before any composition"
@genesis: difference
@mandatory
CONTRACT:
input:     baseline_bundle from NODE 1
transform: EXTRACT_FACTS candidate anti-patterns FROM baseline_bundle.gap INTO candidates; FOR EACH candidate IN candidates: CALCULATE_METRIC impact minus effort FROM candidate INTO candidate.worth; FILTER candidates WHERE <not already covered by an existing base>; RANK candidates BY worth
constraints: the verdict create-base, prefer-composition, prefer-utility or reject-abstraction is a worth decision, never a reflex
output:    selected
DECLARE selected: object
SET selected = <the argmax admissible candidate with its remediation verdict, or a redirect to adopting an existing base>
HANDOFF GATE (tel-priority injection-gate):
rule_id: "INTENT"   yields: boolean over ranking
[check] every candidate carries impact, effort and an admissibility verdict (evidence: candidates) over: candidates measured: <scored> / <candidates>
[check] the selected candidate is the argmax of impact minus effort among admissible ones (evidence: the ranking's first entry)
[check] no candidate already covered by an existing base is selected (evidence: the coverage filter)
result: pass → NODE 3 | none admissible → REPAIR (owner: NODE 1) | unknown → BLOCKED

# NODE 3 — SIGN   [epistemic · analysis · graph · yields: edge-list + boolean]
@purpose: "sign each class's behaviour from evidence, surface repeated structure and inconsistency, and reason to the boundary verdict"
@genesis: relation
CONTRACT:
input:     selected from NODE 2
transform: FOR EACH class IN <the selected role family>: EXTRACT_FACTS <initialization, lifecycle, error handling, state, dependencies, orchestration> FROM class INTO signature; ANALYZE_CONTENT signatures FOR <repeated structure with occurrence counts and competing implementations> INTO patterns; ANALYZE_CONTENT patterns AGAINST <universal, invariant, foundational, enforcing, load-reducing, and domain coverage> INTO verdict
constraints: a base needs behavioural evidence, never naming similarity; without sufficient boundary principles the verdict is composition, utility or a local refactor
output:    boundary_verdict
DECLARE boundary_verdict: object
SET boundary_verdict = {signatures: signatures, patterns: patterns, verdict: verdict}
HANDOFF GATE (evidence-bearing):
rule_id: "SIGN"   yields: boolean
[check] every class in the family is signed from evidence, not names (evidence: signatures) over: the family measured: <signed> / <classes>
[check] repeated structure and inconsistency are surfaced with counts (evidence: patterns)
[check] a base verdict rests on sufficient boundary principles and coverage (evidence: boundary_verdict.verdict)
result: pass → NODE 4 | insufficient boundary → REPAIR (owner: NODE 2) | unknown → BLOCKED

# NODE 4 — COMPOSE AND MIGRATE   [epistemic · formalisation · computation · yields: procedure]
@purpose: "split concrete from abstract, design the template-method lifecycle, compose the base within limits, and migrate targets simple-first and reversibly"
@genesis: structure
CONTRACT:
input:     boundary_verdict from NODE 3
transform: COMPOSE_ARTIFACT base FROM boundary_verdict USING <concrete constructor, initialize, destroy, handle-error and dependency setup; abstract on-initialize, on-destroy, on-error, configure and execute-core; guard then shared then hook then error policy>; ORDER targets BY ascending complexity then dependency; FOR EACH target IN targets: PERSIST_ARTIFACT <a checkpoint> TO <the checkpoint store>; PERSIST_ARTIFACT <the migrated target> TO target; EXECUTE_TOOL {toolchain.verify.execute} WITH timeout: <bound> INTO removal
constraints: a base over {limits.max_lines} is split; a failed migration restores its checkpoint; a base whose boundary collapsed or that blew the effort budget is inadmissible
preserves: every behaviour signed at NODE 3
output:    migration
DECLARE migration: object
SET migration = {base: base, targets: <each with checkpoint, outcome and removal verdict>, admissible: <boundary still sufficient, size within limit, effort within budget, every target reversible>}
HANDOFF GATE (evidence-bearing):
rule_id: "COMPOSE"   yields: boolean
[check] concrete and abstract responsibilities are split and the lifecycle is defined (evidence: base)
[check] the base is within {limits.max_lines} with a compliant name and location (evidence: the base's size and path)
[check] every target migrated or restored from its checkpoint (evidence: migration.targets) over: targets measured: <migrated> / <targets>
[check] the base is admissible (evidence: migration.admissible)
refuse: a target whose checkpoint cannot be read back before PERSIST_ARTIFACT
result: pass → NODE 5 | inadmissible → REPAIR (owner: NODE 3) | unknown → BLOCKED

# NODE 5 — ELIMINATE   [evaluative · verification · logic + probability · yields: number]
@purpose: "prove the old pattern is eliminated across the whole scope from real source, and migrate any straggler reversibly"
@genesis: constraint
@mandatory
CONTRACT:
input:     migration from NODE 4
transform: SEARCH_CONTENT <the whole scope> FOR <the old pattern> INTO occurrences; FILTER occurrences WHERE <outside the approved base locations>; CALCULATE_METRIC completeness FROM occurrences INTO completeness; ANALYZE_CONTENT occurrences FOR <a stray occurrence that would refute elimination> INTO refuter
constraints: the scan reads real source, never the migration log; a stray occurrence refutes back to NODE 4, bounded by recursion_limit
output:    elimination
DECLARE elimination: object
SET elimination = {occurrences: occurrences, completeness: completeness, refuter: refuter}
HANDOFF GATE (ver-stop gate):
rule_id: "ELIMINATE"   yields: boolean
[check] the scan ran over the whole scope from real source (evidence: the scanned file set) over: the scope measured: <scanned> / <files>
[check] only approved base-location occurrences remain (evidence: elimination.occurrences)
[check] a refuter is named and completeness meets its threshold (evidence: elimination.refuter and completeness)
standing: moved-set <the files changed since NODE 4>
result: pass → NODE 6 | stray occurrence → REPAIR (owner: NODE 4) | unknown → BLOCKED

# NODE 6 — TERMINATE   [evaluative · termination · set-theory · yields: artifact]
@purpose: "regenerate the registry to the new truth, persist measured ROI deduplicated, and stop only on saturation and completion and verification"
@genesis: emergence
@mandatory
CONTRACT:
input:     elimination from NODE 5
transform: EXECUTE_TOOL {project.registry_regenerate} WITH timeout: <bound> INTO regenerated; READ_RESOURCE {project.architecture_registry} INTO registry_after; CALCULATE_METRIC <duplication, code, adoption, lines saved, load> FROM {baseline_bundle, migration, registry_after} INTO roi; COMPOSE_ARTIFACT report FROM {migration, elimination, roi} USING <the success or blocked shape>; PERSIST_ARTIFACT report TO <{task_name} report>; REPORT_RESULT report TO <the parties whose next work it creates>
constraints: ROI is measured, never asserted; the registry reflects the new base and the migrated implementations; a self-assessed done is not ter-stop
output:    report
freshness: fingerprint(registry_after) + fingerprint(this document)
HANDOFF GATE (ter-stop gate):
rule_id: "TERMINATE"   yields: boolean
[check] the registry is regenerated and reflects the new truth (evidence: registry_after names the base and the migrated implementations) over: migrated implementations measured: <represented> / <migrated>
[check] ROI is computed from measurements and history is persisted deduplicated (evidence: roi and the history read back)
[check] success only when saturation and completion and verification all hold (evidence: the termination set)
refuse: a report destination that changed since it was read before PERSIST_ARTIFACT
result: pass → TERMINATE | registry stale → REPAIR (owner: NODE 6) | unknown → BLOCKED

# CROSS-NODE INVARIANTS
INVARIANT measure-before-propose: the existing baseline is measured before any base is proposed over: every distillation binds: the distiller objector: [check] the existing architecture is measured at NODE 1
INVARIANT worth-before-base: the selected candidate is the highest-worth admissible one over: candidates binds: the distiller objector: [check] the selected candidate is the argmax at NODE 2
INVARIANT evidence-not-names: a base rests on behavioural evidence, never on naming similarity over: every base binds: the distiller objector: [check] every class is signed from evidence at NODE 3
INVARIANT reversible-migration: every target migrates through a checkpoint and restores on failure over: targets binds: the distiller objector: [check] every target migrated or restored at NODE 4
INVARIANT gone-means-scanned: elimination is proven over the whole scope from real source over: the scope binds: the distiller objector: [check] the scan ran over the whole scope at NODE 5
INVARIANT roi-measured: ROI is a measurement over the regenerated registry, never an assertion over: every report binds: the distiller objector: [check] ROI is computed from measurements at NODE 6

REPORT:
subject: NODE 6
verdict: pass | fail | unknown
domain: declared <files in scope> measured <scanned>
populations: targets migrated <n>, targets restored <n>, occurrences remaining <n>
refusals: <n> [<reason>]
unresolved: <n> [<reason>]
completion: saturated <bool> complete <bool> verified <bool>

```

E1·c boundary principles

```pag
# the boundary principles · a base is justified only when every one holds, with the evidence that shows it
universal       every instance in the family is an instance of the shared behaviour
invariant       the shared half does not vary across them
foundational    other behaviour composes from it
enforceable     a check can hold it
load-reducing   it removes work rather than adding a layer

# otherwise the verdict is compose, a utility, or a local refactor · never a base
```

E1·d instantiation order

```mermaid
flowchart LR
request["A request"]
transition["The transition it asks for"]
protocol["The protocol that fits, with its reason"]
nouns["Placeholders bound to the task's nouns"]
nodes["Nodes · tagged, contracted, gated"]
request --> transition --> protocol --> nouns --> nodes
```

E1·e distillation order

```mermaid
flowchart TB
measure["Measure what exists"]
worth["Rank candidates by worth"]
sign["Sign each class from behaviour"]
boundary{"Universal, invariant, foundational, enforceable, load-reducing?"}
base["Compose the base · migrate reversibly"]
gone{"Old pattern gone from the whole scope?"}
registry["Regenerate the registry · measure the reduction"]
other["Compose, a utility, or a local refactor"]
measure --> worth --> sign --> boundary
boundary -- all five --> base --> gone
boundary -- any fails --> other
gone -- no --> base
gone -- yes --> registry
```

## Links to

- [Core templates](https://banes-lab.com/pag/templates/templates-core.md)
- [From intent to structure](https://banes-lab.com/pag/patterns/intent-to-structure.md)
- [Abstraction](https://banes-lab.com/records/arch/abstraction.md)
- [Error Handling](https://banes-lab.com/records/arch/error-handling.md)
- [Template Method Pattern](https://banes-lab.com/records/arch/template-method-pattern.md)
- [Single Source of Truth](https://banes-lab.com/records/arch/single-source-of-truth.md)
