Add /graph G6: plan-boundary topology optimizer

A restricted optimizer pass now reviews the graph at plan boundaries —
right after initial planning and piggybacked on each replan version
boundary, never mid-execution. An optimizer subagent may emit four ops
over Waiting/Ready nodes only: remove_dep (delete a false dependency,
restoring parallelism — the highest-value edit), reorder (pending
priority for the serial scheduler), merge (fold two tiny nodes; specs
concatenate, deps union, dependents re-point, absorbed self-deps drop),
and split (2-3 focused replacements inheriting the original's deps and
dependents). The optimizer changes graph DATA only; the executor stays
pure deterministic Rust. KIGI_GRAPH_OPTIMIZER=0 disables it entirely.

apply_optimization enforces the contract twice: per-op checks
(pending-only targets, known ids, terminal node untouchable, dead-node
deps rejected as DeadDep, merge/split targets with non-pending
dependents rejected with the true reason instead of tripping the
immutable invariant later), then FINAL invariants — every non-pending
node byte-identical in the result, the gn-final gate rebuilt over all
survivors, node cap, whole-graph acyclicity, and a BIDIRECTIONAL status
re-derivation for pending nodes (adversarial review caught the critical
hole: a merge grafting unsatisfied deps onto a Ready node would
otherwise dispatch it ahead of its new prerequisites, since
recompute_ready is promote-only). Applied passes bump plan_version,
freeze an immutable baseline, and consume a slot of the SHARED replan
cap; an explicit {"ops": []} is a respected free no-op; any failure
degrades to keeping the current plan. Plumbing reuses a new shared
artifact-pass runner (stale-artifact delete, size cap, missing-file
fail-closed) extracted from the replanner.

Tests: remove_dep parallelism restore + loud no-such-dep, immutable and
terminal-node rejections across all four ops, merge/split dependent
rewiring incl. final-gate rebuild and intra-split dep resolution,
result-cycle rejection, dead-dep splits, Ready-demote-on-merge, and
three e2e flows — false-dep removal proven ACTUALLY parallel by the
held-reply fan-out gate, OPTIMIZER=0 spawning zero passes, and the
shared-cap guard. kigi-shell 4959 lib tests green; clippy clean.
This commit is contained in:
2026-07-20 20:21:49 -04:00
parent db05ed0751
commit 02cf5deebd
19 changed files with 1123 additions and 0 deletions
@@ -1929,6 +1929,14 @@ impl Config {
.unwrap_or(3)
.clamp(1, 8)
}
/// Graph topology optimizer master switch (`KIGI_GRAPH_OPTIMIZER`;
/// default on, `0` disables). Runs at plan boundaries only.
pub(crate) fn resolve_graph_optimizer_enabled(&self) -> bool {
!matches!(
std::env::var("KIGI_GRAPH_OPTIMIZER").ok().as_deref(),
Some("0") | Some("false")
)
}
/// Max replan passes per graph (`KIGI_GRAPH_REPLAN_CAP`); 0 turns
/// dynamic replanning off. Past the cap, discoveries drain to
/// history only — the graph must still converge. Clamped to [0, 10].