npt-connector / src /lib /npt /engine.ts
Z User
948fdb38-2859-43f9-9d47-7323c94c2ba1
346ca6c
Raw History Blame Contribute Delete
9.19 kB
import type {
CognitiveNode,
Connection,
ExecutionStage,
LedgerEntry,
NodeConfig,
} from "./types";
// ---------------------------------------------------------------------------
// SHA-256 via Web Crypto (works in Node 18+ runtime of Next.js route handlers)
// ---------------------------------------------------------------------------
export async function sha256(text: string): Promise<string> {
const data = new TextEncoder().encode(text);
const digest = await crypto.subtle.digest("SHA-256", data);
return bufferToHex(digest);
}
function bufferToHex(buf: ArrayBuffer): string {
const bytes = new Uint8Array(buf);
let out = "";
for (const b of bytes) out += b.toString(16).padStart(2, "0");
return out;
}
export function shortHash(h: string, len = 10): string {
if (!h) return "∅";
return h.slice(0, len) + "…" + h.slice(-4);
}
// ---------------------------------------------------------------------------
// Pipeline command parsing
// PIPE sense attend | trn evaluate | surgery audit
// => stages: [{node:"sense", op:"attend"}, {node:"trn", op:"evaluate"}, {node:"surgery", op:"audit"}]
// Also supports direct single commands: trn evaluate
// ---------------------------------------------------------------------------
export interface ParsedStage {
node: string;
operation: string;
}
export interface ParseResult {
ok: boolean;
stages: ParsedStage[];
error?: string;
}
export function parsePipeline(input: string): ParseResult {
const raw = input.trim();
if (!raw) return { ok: false, stages: [], error: "empty input" };
let body = raw;
const isPipe = /^pipe\b/i.test(body);
if (isPipe) body = body.slice(4).trim();
const segments = body
.split("|")
.map((s) => s.trim())
.filter(Boolean);
if (segments.length === 0)
return { ok: false, stages: [], error: "no stages provided" };
const stages: ParsedStage[] = [];
for (const seg of segments) {
const parts = seg.split(/\s+/);
const node = parts[0]?.toLowerCase();
const operation = parts.slice(1).join(" ").toLowerCase() || "route";
if (!node) return { ok: false, stages: [], error: `bad segment "${seg}"` };
stages.push({ node, operation });
}
return { ok: true, stages };
}
// ---------------------------------------------------------------------------
// Execution simulation — routing, latency, allostatic load, Hebbian update
// ---------------------------------------------------------------------------
export interface EngineDeps {
nodes: Map<string, CognitiveNode>;
connections: Connection[];
configs: Record<string, NodeConfig>;
}
export interface ExecutionResult {
trace: ExecutionStage[];
totalLatencyMs: number;
finalLoad: number;
outcome: "success" | "partial" | "failed";
attributionPath: string;
}
export function executePipeline(
parsed: ParsedStage[],
deps: EngineDeps
): ExecutionResult {
const { nodes, connections, configs } = deps;
const trace: ExecutionStage[] = [];
let totalLatency = 0;
let load = 0.35;
let failedCount = 0;
let throttledCount = 0;
const path: string[] = [];
parsed.forEach((stage, idx) => {
const node = nodes.get(stage.node);
if (!node) {
trace.push({
index: idx,
node: stage.node,
operation: stage.operation,
latencyMs: 0,
allostaticDelta: 0,
weightBefore: 0,
weightAfter: 0,
status: "failed",
note: `unknown node "${stage.node}" — route rejected`,
});
failedCount++;
return;
}
const cfg = configs[node.id];
const baseLatency = node.latencyMs;
// jitter influenced by allostatic load & priority
const loadPenalty = node.allostaticLoad * 6;
const jitter = (Math.sin(idx * 13.37 + node.latencyMs) * 0.5 + 0.5) * 4;
const latency = Math.max(1, Math.round(baseLatency + loadPenalty + jitter));
totalLatency += latency;
// glutamate budget throttle check
const budget = cfg?.glutamateBudget ?? node.glutamateBudget;
const overBudget = budget < 35;
const status: ExecutionStage["status"] = overBudget
? "throttled"
: "routed";
if (overBudget) throttledCount++;
const delta = 0.012 + Math.random() * 0.02;
load = Math.min(0.98, load + delta + node.allostaticLoad * 0.05);
// Hebbian reinforcement on the inbound connection from previous node
let weightBefore = 0;
let weightAfter = 0;
if (idx > 0) {
const prev = parsed[idx - 1].node;
const conn = connections.find(
(c) => c.source === prev && c.target === stage.node
);
if (conn) {
weightBefore = conn.weight;
const reward = status === "routed" ? 0.02 : -0.01;
conn.weight = Math.max(0.05, Math.min(0.99, conn.weight + reward));
conn.coactivations += status === "routed" ? 1 : 0;
weightAfter = conn.weight;
path.push(`${prev}→${stage.node}:${weightAfter.toFixed(2)}`);
}
}
path.push(stage.node);
trace.push({
index: idx,
node: stage.node,
operation: stage.operation,
latencyMs: latency,
allostaticDelta: Number(delta.toFixed(3)),
weightBefore: Number(weightBefore.toFixed(3)),
weightAfter: Number(weightAfter.toFixed(3)),
status,
note:
status === "throttled"
? `glutamate budget ${budget}/100 — pathway throttled`
: `routed via ${node.category} · op=${stage.operation}`,
});
});
let outcome: ExecutionResult["outcome"] = "success";
if (failedCount > 0 && failedCount < parsed.length) outcome = "partial";
else if (failedCount >= parsed.length) outcome = "failed";
else if (throttledCount > 0) outcome = "partial";
return {
trace,
totalLatencyMs: totalLatency,
finalLoad: Number(load.toFixed(3)),
outcome,
attributionPath: path.join(" › "),
};
}
// ---------------------------------------------------------------------------
// Ledger block construction with SHA-256 chain
// ---------------------------------------------------------------------------
export async function buildLedgerEntry(params: {
block: number;
prevHash: string;
command: string;
trace: ExecutionStage[];
outcome: LedgerEntry["outcome"];
totalLatencyMs: number;
finalLoad: number;
attribution: string;
operator: string;
}): Promise<LedgerEntry> {
const {
block,
prevHash,
command,
trace,
outcome,
totalLatencyMs,
finalLoad,
attribution,
operator,
} = params;
const timestamp = new Date().toISOString();
// attribution chain: merkle-ish concatenation of pathway edges + outcome
const attributionChain = trace
.map((s) => `${s.node}:${s.operation}:${s.status}`)
.join("|");
const attributionHash = await sha256(attributionChain + "|" + attribution);
const payload = JSON.stringify({
block,
timestamp,
command,
outcome,
totalLatencyMs,
finalLoad,
attribution,
prevHash,
});
const signature = await sha256(payload + "::" + attributionHash);
const id = `npt-${block.toString().padStart(6, "0")}`;
return {
id,
block,
timestamp,
command,
stages: trace,
outcome,
totalLatencyMs,
finalLoad,
signature,
prevHash,
attribution: attributionHash,
verified: true,
operator,
};
}
// ---------------------------------------------------------------------------
// Seeded genesis ledger entries (mock history so the table is populated)
// ---------------------------------------------------------------------------
const SEED_COMMANDS = [
"PIPE sense attend | trn evaluate | surgery audit",
"PIPE vision perceive | aware focus | recall retrieve",
"PIPE audio perceive | trn filter | decide arbitrate",
"PIPE aware predict | infer posterior | reason deduce",
"PIPE decide arbitrate | plan sequence | motor execute",
"PIPE recall retrieve | memory consolidate | ltm store",
"PIPE surgery audit | ethics evaluate | audit verify",
"PIPE router dispatch | gateway bridge | ledger append",
];
export async function seedLedger(
nodes: Map<string, CognitiveNode>,
connections: Connection[],
configs: Record<string, NodeConfig>
): Promise<LedgerEntry[]> {
const entries: LedgerEntry[] = [];
let prevHash = "0000000000000000000000000000000000000000000000000000000000000000";
const operators = ["operator.root", "operator.aux", "operator.safety", "auto.scheduler"];
const baseTime = Date.now() - 1000 * 60 * 60 * 6;
for (let i = 0; i < SEED_COMMANDS.length; i++) {
const parsed = parsePipeline(SEED_COMMANDS[i]).stages;
const res = executePipeline(parsed, { nodes, connections, configs });
const entry = await buildLedgerEntry({
block: i + 1,
prevHash,
command: SEED_COMMANDS[i],
trace: res.trace,
outcome: res.outcome,
totalLatencyMs: res.totalLatencyMs,
finalLoad: res.finalLoad,
attribution: res.attributionPath,
operator: operators[i % operators.length],
});
// backdate timestamp
entry.timestamp = new Date(baseTime + i * 1000 * 60 * 37).toISOString();
entries.push(entry);
prevHash = entry.signature;
}
return entries;
}