physics: bundles join their cluster; depth runs over the logical graph

Owner-approved brief (orchestrator, physics arc): two laws.

1. IMP-NODE CLUSTER ASSIGNMENT. Imp nodes were unclustered (the partition
   runs over stored propositions only) — no centroid pull, outside the
   painted hulls, bundles sitting on the periphery pointing outward.
   Now: a derived imp node's cluster is a function of its derivation —
   MAJORITY among its PREMISES' birth sessions (owner: premises, NOT the
   conclusion), ties to the chain's OWN birth (its provenance's first
   point — the asserting session; deterministic, coincides with the
   unanimous common case). Imp nodes are always re-derived, never
   birthed, so the assignment must be exactly this.

   Seam chosen: core/session-clusters.ts exports impClusterKey + a
   shared attachImpToCommunities that mutates a communities list's
   members IN PLACE. graphSnapshot attaches AFTER the hull filter (a
   2-proposition community + its bundle never resurrects a hull — the
   filter counts propositions); settleGraphLayout attaches to the
   unfiltered partition (settle pulls every community; hulls are a
   canvas-only concern). Both cluster-membership consumers — the sim's
   centroid pull and buildRegions' rasterization — read it through the
   members lists that went through the one helper, so the resting
   ledger and the live sim agree on where bundles belong.

2. DEPTHS OVER THE LOGICAL GRAPH. inferenceDepths ran Tarjan over the
   DRAWN edges (premise→imp→conclusion), inflating every multi-premise
   conclusion one hop (depth(imp)+1 instead of depth(premises)+1) and
   ranking the geometry point itself. Now:
   - deriveView additionally emits logicalEdges — every chain contracted
     to direct premise→conclusion arrows over PROPOSITION ids only
     (per-premise, deduped — a conclusion's rank is max over premises,
     which a single arbitrary premise edge could not express).
   - GraphSnapshot carries logicalEdges; createGraphSimulation /
     incrementalLayout accept a logicalEdges option: the depth
     machinery (orphan detection AND the rank pass) reads it, springs
     keep the drawn edges. Absent = edges (legacy behavior).
   - Imp nodes join the ORPHAN-EXEMPTION mask explicitly — never pinned
     to a level, keep the full regular forces (gravity, cluster pull,
     springs), settle naturally between premise and conclusion levels;
     the rank map is computed over propositions only, so arg_ ids are
     absent from it by construction.
   Wiring: settle + canvas (CanvasData.logicalEdges → buildSim) +
   replay-layout all pass the logical set.

   EXTRA FIX (in-slice discovery, one line, graph-server domain):
   server/graph.ts graphClusters — the practice picker's /api/graph/
   clusters — partitioned snap.NODES (the canvas image, imp nodes riding
   it since chains-primary), leaking arg_ ids into nodeIds: pickable ids
   that silently vanish inside chainsForSelection while nodeCount lied.
   Now partitions snap.propositions — same purity law as the chain
   table's 767a559 fix.

Tests (+13): impClusterKey pins (unanimous; cross-session majority; tie
→ chain's own birth, not the conclusion's); attach pins (members gain
the imp id, sorted; single-premise attaches nothing — no node exists;
dangling mints nothing; home absent from the list stays unattached);
snapshot pins (imp id rides cluster members to both consumers; the hull
filter counts propositions); logical-depth pins (multi-premise
conclusion at premises'+1 NOT +2; imp absent from the rank map);
depth-force exemption pin (rows pin crisply, arg_x floats unpinned —
old behavior stamped it onto the conclusion's row); deriveView logical
arrows (per-premise, deduped, proposition ids only).
This commit is contained in:
amosblomqvist
2026-09-30 04:30:25 +03:00
parent 719f7f9934
commit af666aaa3f
12 changed files with 330 additions and 15 deletions
+5
View File
@@ -314,6 +314,11 @@ export interface GraphSnapshot {
/** DERIVED untyped arrows: premise → imp → conclusion. A lossy image
* of the stored chains — rebuilt after every change, never stored. */
edges: GraphEdge[];
/** DERIVED LOGICAL arrows: every chain contracted to direct premise→
* conclusion over PROPOSITION ids only (the imp hop collapsed). The
* depth pass consumes these — inference depth is a property of
* propositions, never of the geometry point (owner, 2026-09-30). */
logicalEdges: GraphEdge[];
/** The STORED reasoning chains (merged by (premises, conclusion) at
* read): the chain table's and the practice pipeline's input — they
* read the truth, never the derived fan-out. */
+24 -3
View File
@@ -56,7 +56,7 @@ import type {
GraphSnapshot,
} from "./contracts.ts";
import { MIN_CLUSTER_SIZE } from "./clusters.ts";
import { birthSessionOf, birthSessionPartition } from "./session-clusters.ts";
import { attachImpToCommunities, birthSessionOf, birthSessionPartition } from "./session-clusters.ts";
import { formatChainLine } from "./practice.ts";
import type { ChatStore, GraphStore } from "./ports.ts";
@@ -316,14 +316,27 @@ export function getGraph(graphStore: Pick<GraphStore, "readNodes" | "readChains"
* regular citizens (half link distance — layout.ts). Dangling chains
* (a member node missing) drop here — the deletion cascades should
* prevent them; this is the honest belt. */
export function deriveView(graph: DerivedGraph): { nodes: GraphNode[]; edges: GraphEdge[] } {
export function deriveView(graph: DerivedGraph): { nodes: GraphNode[]; edges: GraphEdge[]; logicalEdges: GraphEdge[] } {
const names: Record<string, { name: string }> = {};
for (const node of graph.nodes) names[node.id] = { name: node.name };
const live = new Set(graph.nodes.map((node) => node.id));
const impNodes: GraphNode[] = [];
const edges: GraphEdge[] = [];
// The LOGICAL edge set (owner, 2026-09-30): every chain contracted to
// direct premise→conclusion arrows over PROPOSITION ids only —
// what inference semantics (the depth pass) consumes. The drawn edges
// are the canvas image; these are the meaning.
const logicalEdges: GraphEdge[] = [];
const logicalSeen = new Set<string>();
const emitLogical = (from: string, to: string): void => {
const key = from + "\u0000" + to;
if (logicalSeen.has(key)) return;
logicalSeen.add(key);
logicalEdges.push({ from, to });
};
for (const chain of graph.chains) {
if (!live.has(chain.conclusion) || !chain.premises.every((premise) => live.has(premise))) continue;
for (const premise of chain.premises) emitLogical(premise, chain.conclusion);
// Single premise: the argument IS a plain arrow — no geometry
// point needed (the 1-in/1-out collapse; rendering arc, owner).
if (chain.premises.length === 1) {
@@ -341,7 +354,7 @@ export function deriveView(graph: DerivedGraph): { nodes: GraphNode[]; edges: Gr
for (const premise of chain.premises) edges.push({ from: premise, to: chain.id });
edges.push({ from: chain.id, to: chain.conclusion });
}
return { nodes: [...graph.nodes, ...impNodes], edges };
return { nodes: [...graph.nodes, ...impNodes], edges, logicalEdges };
}
// ─── the /api/graph payload ──────────────────────────────────────────────────
@@ -411,6 +424,13 @@ export function graphSnapshot(deps: GraphDeps): GraphSnapshot {
label: sessions[community.id] ?? fileSources[community.id] ?? null,
members: community.members,
}));
// IMP-NODE CLUSTER ASSIGNMENT (owner, 2026-09-30): majority among the
// premises' birth sessions, ties to the chain's own birth — attached
// AFTER the hull filter so a two-proposition community + its bundle
// never resurrects a hull (the filter counts propositions). Both
// cluster-membership consumers — the sim's centroid pull and the
// canvas's region rasterization — read it through this one list.
attachImpToCommunities(clusters, graph.nodes, graph.chains);
// Resting layout (Option A): the positions ledger, when the settle has
// ever run. Absent on a fresh graph — the view falls back to its own
@@ -421,6 +441,7 @@ export function graphSnapshot(deps: GraphDeps): GraphSnapshot {
nodes,
propositions: graph.nodes,
edges: view.edges,
logicalEdges: view.logicalEdges,
chains: graph.chains,
sessions,
fileSources,
+11 -2
View File
@@ -1,6 +1,6 @@
import type { GraphChain, GraphNode, Position } from "./contracts.ts";
import { incrementalLayout } from "./layout.ts";
import { birthSessionPartition } from "./session-clusters.ts";
import { attachImpToCommunities, birthSessionPartition } from "./session-clusters.ts";
import { deriveView, getGraph } from "./graph.ts";
/**
@@ -39,6 +39,15 @@ export function settleGraphLayout(graphStore: {
// PROPOSITIONS ONLY (owner, 2026-09-30): implication nodes never
// partition; the stored world clusters, its image follows.
const communities = birthSessionPartition(graph.nodes);
const next = incrementalLayout(view.nodes, view.edges, previous, { clusters: communities });
// The SAME imp-node assignment the snapshot renders (majority among
// premises' births — core/session-clusters.ts): the resting ledger and
// the live sim must agree on where bundles belong, or the first live
// tick would fight the settle. Unfiltered here (settle pulls every
// community, hulls are a canvas-only concern).
attachImpToCommunities(communities, graph.nodes, graph.chains);
const next = incrementalLayout(view.nodes, view.edges, previous, {
clusters: communities,
logicalEdges: view.logicalEdges,
});
graphStore.writePositions(Object.fromEntries(next));
}
+24 -3
View File
@@ -177,6 +177,11 @@ export interface SimOptions {
velocityDecay?: number;
/** Inference-depth anchoring (see DepthAnchor). Off by default. */
depthAnchor?: DepthAnchor;
/** The LOGICAL edge list (proposition→conclusion, imp hops
* contracted) for the depth machinery — orphan detection AND the
* rank pass (owner, 2026-09-30). Absent = `edges` (legacy
* behavior). Springs ALWAYS run over `edges` — the drawn arrows. */
logicalEdges?: ReadonlyArray<LayoutEdge>;
/** Cluster centroid pull (the "virtual node" without the node):
* members of each cluster accelerate toward their own cluster's
* centroid. Two O(n) passes per tick — cheaper than a real virtual
@@ -288,11 +293,14 @@ export function createGraphSimulation(
// depth force and keep the REGULAR view's forces instead (full center
// gravity + full cluster pull, unprojected).
const mode = options.depthAnchor?.mode ?? "off";
// The depth machinery reads the LOGICAL edge list when supplied —
// structure is inference over propositions, not the drawn geometry.
const depthEdges = options.logicalEdges ?? edges;
let orphan: Uint8Array | null = null;
if (mode !== "off") {
const connected = new Set<string>();
const valid = new Set(nodes.map((n) => n.id));
for (const e of edges) {
for (const e of depthEdges) {
// Self-loops and dangling endpoints are not a structure (same
// guards as inferenceDepths).
if (e.from === e.to || !valid.has(e.from) || !valid.has(e.to)) continue;
@@ -301,7 +309,12 @@ export function createGraphSimulation(
}
orphan = new Uint8Array(nodes.length);
nodes.forEach((n, i) => {
if (!connected.has(n.id)) orphan![i] = 1;
// IMP EXEMPTION joins the mask (owner, 2026-09-30): depth is a
// property of inference over PROPOSITIONS; an implication node
// is pure geometry — never pinned to a level, keeps the full
// regular forces (gravity, cluster pull, springs), and settles
// naturally between premise and conclusion levels.
if (!connected.has(n.id) || n.id.startsWith(IMP_ID_PREFIX)) orphan![i] = 1;
});
}
const g = options.gravity;
@@ -402,7 +415,12 @@ export function createGraphSimulation(
// organic sag.
const da = options.depthAnchor;
if (da && da.mode !== "off" && da.strength > 0) {
const depths = inferenceDepths(nodes, edges);
// Propositions only: imp ids are absent from the rank map by
// construction (belt under the orphan-mask exemption).
const depths = inferenceDepths(
nodes.filter((n) => !n.id.startsWith(IMP_ID_PREFIX)),
depthEdges,
);
const strength = da.strength;
const spacing = da.spacing;
const c = da.center ?? { x: 0, y: 0 };
@@ -460,6 +478,8 @@ export interface IncrementalLayoutOptions {
/** Inference-depth anchoring (see DepthAnchor). `center` defaults to
* the anchored core's centroid. */
depthAnchor?: DepthAnchor;
/** The LOGICAL edge list for the depth pass (see SimOptions). */
logicalEdges?: ReadonlyArray<LayoutEdge>;
}
/**
@@ -598,6 +618,7 @@ export function incrementalLayout(
options.depthAnchor && options.depthAnchor.mode !== "off"
? { ...options.depthAnchor, center: options.depthAnchor.center ?? { x: cx, y: cy } }
: options.depthAnchor,
logicalEdges: options.logicalEdges,
});
const dMode = options.depthAnchor?.mode ?? "off";
const dCenter = options.depthAnchor?.center ?? { x: cx, y: cy };
+57 -3
View File
@@ -32,7 +32,7 @@
* core barrel — the shell reads clusters from the snapshot; only the
* server-side derivations (snapshot, settle) and tests import this.
*/
import type { GraphNode } from "./contracts.ts";
import type { GraphChain, GraphNode } from "./contracts.ts";
/** One birth-session cluster: the session id + the SORTED member node
* ids born in it. The shape is deliberately the { members } contract
@@ -47,7 +47,7 @@ export interface BirthSessionCluster {
/** A node's birth session: its first surviving provenance point's chatId.
* null when the node carries no provenance at all (legacy data). */
export function birthSessionOf(node: GraphNode): string | null {
export function birthSessionOf(node: Pick<GraphNode, "provenance">): string | null {
return node.provenance[0]?.chatId ?? null;
}
@@ -73,4 +73,58 @@ export function birthSessionPartition(nodes: readonly GraphNode[]): BirthSession
return [...members.entries()]
.map(([id, list]) => ({ id, members: [...list].sort() }))
.sort((a, b) => b.members.length - a.members.length || (a.id < b.id ? -1 : 1));
}
}
/** The cluster key a derived implication node takes: MAJORITY among its
* PREMISES' birth sessions (owner, 2026-09-30 — premises, NOT the
* conclusion), ties to the chain's OWN birth (its provenance's first
* point, the asserting session — deterministic, and it coincides with
* the unanimous common case anyway). Imp nodes are always re-derived,
* never birthed, so their cluster must be a function of the derivation
* — this is that function. */
export function impClusterKey(
chain: Pick<GraphChain, "premises" | "provenance">,
birthOf: (nodeId: string) => string | null,
): string | null {
const counts = new Map<string, number>();
for (const premise of chain.premises) {
const birth = birthOf(premise);
if (birth !== null) counts.set(birth, (counts.get(birth) ?? 0) + 1);
}
const own = chain.provenance[0]?.chatId ?? null;
if (counts.size === 0) return own;
let max = 0;
for (const n of counts.values()) if (n > max) max = n;
const winners: string[] = [];
for (const [key, n] of counts) if (n === max) winners.push(key);
if (winners.length === 1) return winners[0]!;
// Tie → the chain's own birth; if even that is missing, the
// alphabetically-first winner (last-resort determinism).
return own ?? winners.sort()[0]!;
}
/** Attach derived imp nodes to communities IN PLACE (the shared seam for
* both consumers of cluster membership — the sim's centroid pull and
* the canvas's region rasterization both read members lists that went
* through here). Only MULTI-premise fully-live chains mint imp nodes
* (single-premise chains collapsed to direct arrows, rendering arc
* 2026-09-30); dangling chains mint nothing. A chain whose home
* community is absent from the list stays unclustered — like its
* premises when the hull filter drops them. */
export function attachImpToCommunities(
communities: Array<{ id: string; members: string[] }>,
propositions: ReadonlyArray<Pick<GraphNode, "id" | "provenance">>,
chains: ReadonlyArray<Pick<GraphChain, "id" | "premises" | "conclusion" | "provenance">>,
): void {
const birthById = new Map(propositions.map((node) => [node.id, birthSessionOf(node)]));
const live = new Set(propositions.map((node) => node.id));
for (const chain of chains) {
if (chain.premises.length < 2) continue;
if (!live.has(chain.conclusion) || !chain.premises.every((p) => live.has(p))) continue;
const key = impClusterKey(chain, (id) => birthById.get(id) ?? null);
const community = key === null ? undefined : communities.find((c) => c.id === key);
if (!community) continue;
community.members.push(chain.id);
}
for (const community of communities) community.members.sort();
}
+4 -1
View File
@@ -33,7 +33,10 @@ export function graphView(): GraphSnapshot {
* honest, never guessed. A corrupt/empty graph is an empty list. */
export function graphClusters(): GraphClusterGroup[] {
const snap = graphSnapshot(stores);
return birthSessionPartition(snap.nodes).map((group) => ({
// PROPOSITIONS ONLY: snap.nodes is the canvas image (imp nodes ride
// it); the picker offers propositions — an arg_ id in nodeIds would
// silently vanish inside chainsForSelection and lie about nodeCount.
return birthSessionPartition(snap.propositions).map((group) => ({
key: group.id,
kind: group.id in snap.sessions ? "chat" : "notes",
label: snap.sessions[group.id] ?? snap.fileSources[group.id] ?? null,