# Graft Strategy Implementation & Authoring Guidance

This document serves as the **authoritative architectural contract and guide** for implementing and maintaining graft strategies in the `ibgib` sync engine.

---

## 🚨 Critical Principles & Invariants

When implementing any `GraftStrategy` (implementing `GraftStrategy` or extending `GraftMergeStrategyBase_V1`):

### 1. The `GraftTimelinesResult` Payload Contract is Complete and Accretive
`SyncSagaCoordinator` relies strictly on the returned `GraftTimelinesResult` to transfer, persist, and register all new, replayed, and referenced domain objects into the destination space:

```typescript
export interface GraftTimelinesResult {
    /**
     * DNA ibgibs created specifically during this graft (e.g. from mut8/rel8 transforms).
     */
    dnasCreatedInGraft: IbGib_V1[];
    /**
     * DNA ibgibs replayed from the orphan branch.
     */
    dnasReplayed: IbGib_V1[];
    /**
     * Intermediate non-DNA timeline frames created during multi-pass evolves.
     */
    intermediateIbGibsCreatedInGraft: IbGib_V1[];
    /**
     * Non-timeline "stone" ibgibs, binary payloads (BinIbGib_V1), comment stones (CommentIbGib_V1),
     * DNA stones, ancestor stones, and ancillary graph nodes created or newly referenced from the orphan branch.
     */
    ancillaryIbGibsCreated: IbGib_V1[];
    /**
     * Final produced ibgib tip in the timeline. Must have graft info rel8d.
     */
    newGraftTip: IbGib_V1;
    /**
     * The GraftInfoIbGib_V1 created and rel8d to newGraftTip.
     */
    graftInfoCreated: GraftInfoIbGib_V1;
}
```

> [!CAUTION]
> **No Dangling References**: If a graft strategy attaches or references an object (such as a `CommentIbGib_V1` or `BinIbGib_V1` from the orphan branch) on `newGraftTip`, you **MUST** include that object and its dependency graph (its DNAs, ancestors, and stones) in `ancillaryIbGibsCreated`!
>
> If you omit referenced nodes from `ancillaryIbGibsCreated`, `SyncSagaCoordinator.executeLocalCommit` will NOT transfer or register them into the local space, causing dangling pointer corruption in the destination space.

---

### 2. Monotonic Timeline Counters (`highestDataN`)
In `ibgib` timelines, each frame has a monotonic counter `data.n`:
- `metaspace.registerNewIbGib` checks whether incoming `data.n` is strictly greater than `n_existingLatest` in that space.
- If `incoming.data.n <= n_existingLatest`, the space logs:
  `incoming ibGib ... is NOT NEWER than existing latest ... multiple branches for the same timeline? ignoring incoming ibGibAddr`
  and **drops the registration**!

> [!IMPORTANT]
> **Always Use `Math.max` for Timeline Advance**:
> When reconciling two diverging branches where `baseItem` has `n = N_base` and `orphanItem` has `n = N_orphan`, you must compute:
> ```typescript
> const highestDataN = Math.max(baseItem.data?.n ?? 0, orphanItem.data?.n ?? 0);
> ```
> And ensure the new graft frame starts from `highestDataN + 1`. Never use `Math.min`, or the graft frame will be rejected by the space as an older/equal frame!

---

### 3. Self-Contained Branch Spaces (No Cross-Space Fallback Crutches)
Each branch space (e.g. `b2s~code-1~main`, `b2s~code-1~feature`) must be completely self-contained.
- Calling `getDependencyGraph({ ibGib, space })` on a grafted tip within a single branch space **MUST succeed completely** without requiring fallbacks to metaspace or scanning sibling spaces on disk.
- Never use fallback lookups in `getIbGibWithMetaspaceFallback` or similar functions to paper over missing objects in a space; if an object is missing, fix the graft strategy to properly populate `ancillaryIbGibsCreated`.

---

### 4. Resolving Base vs. Orphan Branches
Graft strategies should extend `GraftMergeStrategyBase_V1` and call `this.resolveBaseAndOrphan(...)` to honor the requested `GraftPreference`:
- `GraftPreference.receiver`: Receiver's branch is `baseTip`, sender's branch is `orphanTip`.
- `GraftPreference.sender`: Sender's branch is `baseTip`, receiver's branch is `orphanTip`.
- `GraftPreference.timestamp`: Branch with the later timestamp is `baseTip`.

---

## 🛠️ Step-by-Step Checklist for Writing / Modifying a Graft Strategy

1. **Extract LCA & Divergent Branches**:
   - Locate `latestCommonFrameAddr` in both `timelineAddrsA` and `timelineAddrsB`.
   - Slice addresses since LCA and fetch from `ibGibReadCache` (falling back to `space`).
2. **Resolve Base and Orphan**:
   - Use `this.resolveBaseAndOrphan(...)`.
3. **Compute Highest `n`**:
   - `highestDataN = Math.max(baseTip.data?.n ?? 0, orphanTip.data?.n ?? 0)`.
4. **Merge Payloads & Domain Rel8ns**:
   - Merge text/binary content (e.g. via 3-way line diff).
   - Union domain relations like `rel8ns.comment` across `baseTip` and `orphanTip`.
5. **Collect Ancillary Dependency Graph**:
   - For any orphan nodes newly referenced on the merged item (e.g., comments, binary stones), gather the full sub-graph into `ancillaryIbGibsCreated`.
6. **Evolve & Attach Graft Info**:
   - Create `GraftInfoIbGib_V1` with `createGraftInfo(...)`.
   - Perform `rel8` to attach `[GRAFT_INFO_REL8N_NAME]: [graftInfoAddr]`.
   - Ensure the final resulting tip is `newGraftTip`.
7. **Return `GraftTimelinesResult`**:
   - Populate all 6 fields accurately.
8. **Verify with In-Memory `getDependencyGraph`**:
   - Verify that `getDependencyGraph({ ibGib: newGraftTip, space })` resolves all nodes strictly within `space`.
