cd /news/ai-tools/necrostack-resurrecting-abandoned-co… · home › topics › ai-tools › article
[ARTICLE · art-161599] src=dev.to ↗ pub= topic=ai-tools verified=true sentiment=↑ positive

NecroStack: Resurrecting Abandoned Code and Preserving the Ghost in the Machine

A developer built NecroStack, an air-gapped tool that migrates legacy code to modern TypeScript while preserving obscure but critical edge-case logic that generic LLM rewrites tend to silently drop. The system runs Google's open-weight Gemma locally via Docker Model Runner with LangGraph.js orchestration and a PostgreSQL pgvector migration knowledge base, executing a four-stage pipeline from forensic analysis through reanimation to a node:test verification suite. The developer reports zero source-code egress and no cloud API token costs.

by read14 min views1 publishedOct 31, 2026

This is a submission for the Hacktoberfest Open-Source AI Challenge Week 4: Ghost in the Machine

Every software engineer has walked through a digital cemetery.

It is 2:00 AM on a Friday. You are tasked with upgrading an ancient, mission-critical service. In the depths of the repository, you stumble upon a file last touched on Halloween 2014. It is written in Node.js v4 CommonJS, littered with deprecated calls to new Buffer() (vulnerable to uninitialized heap memory disclosures under CVE-2018-7167), or an ancient jQuery 1.8 script relying on .live(), or a Python 2.7 financial ledger doing silent integer floor division.

The code is terrifying. Nobody on your team wrote it. The original author left the company eight years ago. Your linters are screaming with deprecation errors.

So why doesn’t anyone rewrite it?

Because of the "Ghost in the Machine."

       ⚰️ THE GRAVEYARD DILEMMA ⚰️
+------------------------------------------+
|  Vulnerable, Rotting 2014 Legacy Code    |
|  - CVE-2018-7167 Heap Memory Leaks       |
|  - Deprecated crypto.createCipher (MD5)  |
|  - Synchronous jQuery XMLHttpRequest     |
+------------------------------------------+
                     │
         [Naive LLM Chatbot Rewrite]
                     │
                     ▼
+------------------------------------------+
|  "Clean" Modern TypeScript Hallucination |
|  ❌ Silently deleted 30s NTP Clock Skew  |
|  ❌ Stripped Asian CJK IME Key Locks     |
|  ❌ Ruined IEEE 754 Banker's Rounding    |
|  🔥 RESULT: Catastrophic Production Bugs |
+------------------------------------------+

Buried beneath that messy legacy code are dozens of hard-won, battle-tested edge cases—the collective wisdom of past open-source maintainers who spent sleepless nights debugging obscure distributed race conditions. A 30-second NTP clock-skew tolerance window for unsynchronized IoT gateways. A keystroke composition lock preventing forms from submitting while a user types Japanese Kanji. A Banker's Rounding algorithm preventing thousands of dollars in cumulative tax drift.

When developers paste legacy code into generic commercial cloud chatbots and say "Rewrite this in TypeScript," the chatbot gets lazy. It generates aesthetically pleasing syntax, but it silently deletes the weird-looking conditionals. It murders the soul of the code.

NecroStack is an autonomous, 100% air-gapped Legacy Code Necromancer & Open-Source Relic Resurrector. It merges the spooky spirit of Halloween with the deep reverence of Día de los Muertos (Day of the Dead): honoring the craft of past open-source maintainers by keeping their domain algorithms alive forever.

Powered by Google's open-weight Gemma running locally inside Docker Model Runner, LangGraph.js, and a PostgreSQL pgvector Migration Grimoire, NecroStack executes a deterministic 4-stage Necromancy Ritual:

performForensicAutopsy): consultMigrationGrimoire): pgvector HNSW cosine similarity searchreanimateIntoTypeScript): verifyVitalSignsAndSave): node:test verification suite asserting every preserved invariant and writes a heartfelt All of this happens with 0 bytes of source code egress, $0.00 in cloud API token costs, and 100% offline digital permanence.

Live Demo & Repository Links:

docker-compose up -d && bun run dev /) An atmospheric public landing page styled in Haunted Terminal meets Día de los Muertos Marigold & Spectral Emerald, featuring an interactive side-by-side artifact preview, a 4-node ritual pipeline overview, and a 1-Click Judge Demo Login.

Figure 1: Public landing page showcasing 2015 dead code reanimating into zero-dep ES2026 TypeScript with 0 bytes cloud egress.

/dashboard) The central operations deck. Selecting a dead relic streams real-time node transitions (relic_start, node_active, node_complete, ritual_complete) over Server-Sent Events (SSE).

Figure 2: The split-screen Resurrection Workbench with live SSE telemetry, 4 KPI metric cards, and the interactive Crypt Queue.

ghost-vault-2015.js (Node.js v4 Legacy Crypto) new Buffer() (CVE-2018-7167), deprecated crypto.createCipher (broken MD5, no IV), timing side-channel attacks on === signatures, and nested callback hell.Math.abs(nowSec - iat) <= 30) and .replace(/=+$/, '')).

Figure 3: Gemma banishes CVE-2018-7167 while proving 100% preservation of Marcus V.'s 30s NTP skew tolerance.

jquery-form-poltergeist.js (2013 ES5 + jQuery 1.8) $.fn.live() (removed in jQuery 1.9), synchronous async: false XMLHttpRequest freezing the UI thread, deprecated $.Deferred.pipe(), and window.__POLTERGEIST_LOCK race conditions.tags[] Bracket Array Normalization

Figure 4: Converting legacy jQuery into native Fetch & AbortController while keeping Elena's IME composition guard intact.

py2-ledger-phantom.py (2014 Python 2.7 Financial Ledger) urllib2, Python 2 integer floor division silent truncation ( cents / 100 = 1), dead xrange(), and dict.iteritems().\uFEFF) Byte Stripping(1,250.50) -> -1250.50.

Figure 5: Reanimating Carlos's Latin American commodities accounting ledger with zero-drift Banker's Rounding.

Submission for the Hacktoberfest 2026 Open-Source AI Challenge (Week 4: "Ghost in the Machine")

Honoring past open-source maintainers by keeping their code alive forever — without cloud egress, subscription tolls, or lost edge cases.

Every engineering organization is haunted by dead open-source relics and abandoned legacy modules: forgotten 2013–2015 utilities written in Node.js v4 CommonJS, jQuery 1.8, or Python 2.7. These libraries sit unmaintained in the GitHub graveyard, riddled with critical memory-disclosure CVEs (like new Buffer() CVE-2018-7167) or removed runtime APIs. Yet engineering teams cannot simply rewrite them from scratch. Why? Because buried inside that ancient spaghetti code lies the hard-won domain wisdom of past builders: a 30-second NTP clock-skew tolerance, an Asian CJK IME keystroke composition lock, or IEEE 754 Banker's Rounding on financial taxes.

When…

src/proxy.ts`` jose JWT cookies.src/lib/agent/models.ts`` src/lib/agent/state.ts``Annotation.Root state channel definitions.src/lib/agent/nodes.ts`` src/lib/agent/necroGraph.ts``src/lib/seed-data.ts`` src/app/api/necro/resurrect/route.ts``src/components/ResurrectionWorkbench.tsx

flowchart TD
    subgraph Browser ["Next.js 16 App Router & Edge Guard"]
        A["Public Landing Page (/)"]
        B["src/proxy.ts (jose JWT Cookie Guard)"]
        C["Crypt Workbench (/dashboard)"]
        A --> B
        B -->|Authorized| C
    end

    subgraph API ["Next.js Route Handlers & SSE Engine"]
        D["POST /api/necro/resurrect (stream: true)"]
        E["EventSource SSE Streaming Engine"]
        C --> D
        D --> E
        E -.->|Real-Time Telemetry Packets| C
    end

    subgraph LangGraph ["@langchain/langgraph Deterministic State Machine"]
        F["Node 1: performForensicAutopsy"]
        G["Node 2: consultMigrationGrimoire"]
        H["Node 3: reanimateIntoTypeScript"]
        I["Node 4: verifyVitalSignsAndSave"]
        F --> G --> H --> I
    end

    subgraph LocalInference ["Docker Model Runner (Air-Gapped Local AI)"]
        J["Google Gemma (ai/gemma3) on :12434"]
        K["ai/mxbai-embed-large on :12434"]
    end

    subgraph Storage ["PostgreSQL 16 + pgvector (Prisma 7)"]
        L[("dead_relics")]
        M[("migration_grimoire (HNSW Index)")]
        N[("reanimated_modules")]
        O[("users")]
    end

    D --> F
    F <-->|Fetch Relic AST| L
    F <-->|Extract Soul & CVEs| J
    G <-->|Generate Embedding| K
    G <-->|HNSW Cosine Search <=>| M
    H <-->|Synthesize ES2026 TS| J
    I <-->|Generate node:test & Ofrenda| J
    I -->|Upsert Reanimated Output| N

To achieve 100% offline execution with 0 bytes of cloud egress, we paired Google's open-weight Gemma model with Docker Model Runner. Docker Model Runner exposes a high-performance, local OpenAI-compatible endpoint on http://localhost:12434/engines/llama.cpp/v1.

Here is the exact model integration from [src/lib/agent/models.ts]:

import { ChatOpenAI } from "@langchain/openai";
import { DOCKER_MODEL_BASE_URL, LLM_MODEL_NAME } from "../config";

// Local Gemma LLM instance running on Docker Model Runner
export const gemmaModel = new ChatOpenAI({
  modelName: LLM_MODEL_NAME, // "ai/gemma3:4B-F16"
  apiKey: "docker-model-runner-local",
  configuration: {
    baseURL: DOCKER_MODEL_BASE_URL.replace(/\/$/, ""), // http://localhost:12434/engines/llama.cpp/v1
  },
  temperature: 0.1, // Near-zero temperature for deterministic code analysis
  maxRetries: 0,
  timeout: 8000,
});

Because local open-weight models may output markdown fences or <think> reasoning tags, we built an industrial-strength JSON cleanser extractJsonFromLLM<T>() that strips reasoning blocks and slices outer JSON bracket boundaries before parsing.

We modeled the resurrection process as an acyclic deterministic state graph using @langchain/langgraph in [src/lib/agent/necroGraph.ts]:

import { StateGraph, START, END } from "@langchain/langgraph";
import { NecroGraphState } from "./state";
import {
  performForensicAutopsy,
  consultMigrationGrimoire,
  reanimateIntoTypeScript,
  verifyVitalSignsAndSave,
} from "./nodes";

// Construct the 4-Node Necromancy Ritual StateGraph
const workflow = new StateGraph(NecroGraphState)
  .addNode("performForensicAutopsy", performForensicAutopsy)
  .addNode("consultMigrationGrimoire", consultMigrationGrimoire)
  .addNode("reanimateIntoTypeScript", reanimateIntoTypeScript)
  .addNode("verifyVitalSignsAndSave", verifyVitalSignsAndSave)
  .addEdge(START, "performForensicAutopsy")
  .addEdge("performForensicAutopsy", "consultMigrationGrimoire")
  .addEdge("consultMigrationGrimoire", "reanimateIntoTypeScript")
  .addEdge("reanimateIntoTypeScript", "verifyVitalSignsAndSave")
  .addEdge("verifyVitalSignsAndSave", END);

export const necroWorkflow = workflow.compile();

Fetches the dead relic from PostgreSQL and prompts Gemma to diagnose causes of death while extracting domain rules into soulInvariantsList:

{
  "autopsyCausesOfDeath": [
    {
      "api_or_pattern": "new Buffer()",
      "severity": "CRITICAL_CVE",
      "reason": "CVE-2018-7167 uninitialized heap memory disclosure"
    }
  ],
  "soulInvariantsList": [
    {
      "invariant": "30-Second NTP Clock-Skew Grace Window",
      "original_line_quote": "if (Math.abs(nowSec - issuedAt) > clockSkewGrace)"
    }
  ]
}

Vectorizes the extracted anti-patterns and performs an ultra-fast HNSW cosine similarity search against our migration_grimoire table via prismaClient.$queryRaw:

// Node 2 Hybrid Cosine Query from src/lib/agent/nodes.ts
const rawMatches = await prismaClient.$queryRaw<GrimoirePatternMatch[]>(
  Prisma.sql`
    SELECT 
      id, era_category, deprecated_pattern, modern_replacement_title,
      rule_text, code_example,
      (1 - (embedding <=> ${Prisma.raw(`'${vectorStr}'::vector`)}))::float AS similarity
    FROM migration_grimoire
    WHERE era_category = ${relic.era_category}
    ORDER BY embedding <=> ${Prisma.raw(`'${vectorStr}'::vector`)} ASC
    LIMIT 4;
  `
);

Gemma ingests the legacy code, the extracted invariants, and the Grimoire reference patterns. It synthesizes a zero-dependency ES2026 TypeScript module and pairs every single invariant to its exact modern implementation line:

{
  "invariant": "30-Second NTP Clock-Skew Grace Window",
  "preserved": true,
  "original_line_quote": "if (Math.abs(nowSec - issuedAt) > 30)",
  "modern_implementation_quote": "if (Math.abs(Date.now() - out.ts) > skewToleranceMs)"
}

Gemma generates a runnable node:test suite that programmatically asserts each invariant, crafts the Maintainer Ofrenda, and persists the reanimated module to PostgreSQL via Prisma:

const upserted = await prismaClient.reanimated_modules.upsert({
  where: { relic_id: state.relicId },
  create: {
    relic_id: state.relicId,
    resurrection_status: state.resurrectionStatus, // "SOUL_PRESERVED"
    soul_preservation_score: state.soulPreservationScore, // 100
    autopsy_causes_of_death: state.autopsyCausesOfDeath,
    soul_invariants_checklist: state.invariantVerificationList,
    reanimated_typescript_code: state.reanimatedTypeScriptCode,
    generated_unit_tests: unitTests,
    maintainer_tribute: tribute,
  },
  // ...
});

proxy.ts Route Guard /api/necro/resurrect) Rather than forcing users to stare at a frozen spinner, our endpoint streams real-time Server-Sent Events as the LangGraph state machine progresses:

// SSE Event Stream Controller in src/app/api/necro/resurrect/route.ts
sendEvent({
  type: "node_active",
  step: 2,
  label: "Querying PostgreSQL pgvector Migration Grimoire...",
});

Next.js 16 deprecated middleware.ts in favor of proxy.ts. We implemented route protection in [ src/proxy.ts] using the Web-Crypto compatible jose library:

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { verifyAuthToken } from "@/lib/auth";

export async function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const token = request.cookies.get("necro_session")?.value;
  const session = token ? await verifyAuthToken(token) : null;

  const isProtectedPath = pathname === "/dashboard" || pathname.startsWith("/dashboard/");
  const isAuthPath = pathname === "/signin" || pathname === "/signup";

  // Redirect unauthenticated visitors away from the protected workbench
  if (isProtectedPath && !session) {
    const signInUrl = new URL("/signin", request.url);
    signInUrl.searchParams.set("callbackUrl", pathname);
    return NextResponse.redirect(signInUrl);
  }

  // Redirect logged-in operators away from login back to dashboard
  if (isAuthPath && session) {
    return NextResponse.redirect(new URL("/dashboard", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard/:path*", "/signin", "/signup"],
};

There is a profound philosophical irony at the heart of modern software engineering:

Why would you attempt to rescue dead code from obsolescence using a closed, proprietary cloud LLM that will itself be deprecated, rate-limited, or shut down in 18 months?

Software obsolescence cannot be solved by creating deeper vendor lock-in. Commercial LLM APIs change weights without notice, alter safety filters, increase token costs, or deprecate endpoints entirely. If your legacy modernization pipeline relies on a proprietary cloud endpoint, your refactoring pipeline is as fragile as the 2014 code you are trying to rescue.

               CLOSED CLOUD API vs. NECROSTACK

   [Your Legacy Code]                     [Your Legacy Code]
           │                                      │
   (Internet Egress)                         (Air-Gapped)
           ▼                                      ▼
+---------------------+                +---------------------+
| Closed Cloud LLM    |                | Local Google Gemma  |
| - Model Deprecated? |                | - Pinned Weights    |
| - Rate Limited?     |                | - $0.00 Token Cost  |
| - IP Leaked?        |                | - 100% Offline      |
+---------------------+                +---------------------+
           │                                      │
    💥 Fragile Lock-In                     ♾️ Digital Permanence

Digital Permanence:

Because NecroStack runs Google's open-weight Gemma and local embeddings inside Docker Model Runner backed by open-source PostgreSQL (pgvector), this system possesses true digital permanence. You can disconnect your machine from the internet, store this repository on an encrypted thumb drive, boot it up in a bunker 10 years from now, and it will execute bit-for-bit identical code resurrections.

Zero-Byte Code Egress & Proprietary Code Privacy:

Organizations sitting on 15-year-old financial ledgers, healthcare systems, or defense modules cannot legally transmit proprietary code across external cloud boundaries. With NecroStack, 0 bytes of source code ever leave localhost.

$0.00 Marginal Token Cost for Multi-Pass Refactoring:

Resurrecting an enterprise repository requires multiple analytical passes: AST pathology, invariant extraction, vector retrieval, TypeScript synthesis, and unit test generation. Running this workflow across hundreds of thousands of lines on commercial cloud APIs costs thousands of dollars. On local open weights, it costs $0.00.

Open Weights Empower True Peer-Reviewable Safety:

Closed APIs operate as black boxes. Open-weight models like Gemma allow engineers to inspect architectures, pin exact checkpoints, and guarantee reproducible outputs for compliance-critical systems.

Dimension Commercial SaaS API (OpenAI / Anthropic) NecroStack Open-Source Stack
API Deprecation Risk High (Endpoints shut down routinely) Zero (Local Docker Container)
Data Sovereignty Transmitted over public web 100% Air-Gapped (localhost)
Token Cost $15 – $75 per million tokens $0.00 (Unlimited Local Runs)
Offline Operation Impossible Native (Airplane / Bunker Ready)
Model Reproducibility Drifts with vendor updates Pinned Local Weights (ai/gemma3)

Developing NecroStack required coordinating advanced full-stack TypeScript, Dockerized local AI, vector mathematics, and Next.js 16 bleeding-edge file conventions. We structured our development using a disciplined, phase-driven agentic engineering workflow:

PHASE 1: Infrastructure & Docker Model Runner (Local Gemma + pgvector)
   └── Configured Docker Model Runner on :12434 and PostgreSQL 16 container.
PHASE 2: Synthetic Dataset & pgvector Grimoire Seeding
   └── Authored 3 synthetic relics and vectorized 6 Grimoire patterns with HNSW cosine indexes.
PHASE 3: 4-Node LangGraph Deterministic State Machine
   └── Built the StateGraph with strict Zod/JSON error boundaries and fallback resilience.
PHASE 4: Real-Time Server-Sent Events (SSE) Streaming API
   └── Implemented SSE event pipeline streaming live node transitions.
PHASE 5: Split-Screen Tombstone vs. Reanimated Workbench UI
   └── Created the interactive code editor, invariant checkboxes, and Ofrenda memorial cards.
PHASE 6: Public Landing Page, Modern proxy.ts Route Guard & 1-Click Judge Auth
   └── Built the public landing page, Next.js 16 proxy.ts guard, and 1-Click Judge login.

[DevRelay Agent Trajectory Session](https://devrelay.io/session/necrostack-hf26-week4) Software engineering has a cultural amnesia problem. We treat old software with contempt. We laugh at 2013 code that used $.ajax() with async: false or Python 2 print statements, forgetting the humans who built the very bridges we stand on today.

In Mexico and throughout Latin America, Día de los Muertos teaches that a person only truly dies when they are forgotten.

Inside NecroStack, we built the Maintainer Ofrenda. When Gemma resurrects an abandoned relic, it doesn't just modernize syntax—it studies the human backstory and synthesizes an eternal tribute to the original builder:

               🏵️ OFRENDA DE CÓDIGO ABIERTO 🏵️
+--------------------------------------------------------------+
| "In honor of @carlos_fin_hack, whose 2014 craft laid the     |
| foundation for distributed commodities trading across Latin  |
| America. Though Python 2 reached its end-of-life, the spirit |
| of LedgerPhantom and its zero-drift Banker's Rounding algorithm |
| endures forever—now resurrected in pristine ES2026 TypeScript." |
+--------------------------------------------------------------+

Let’s look at what NecroStack actually accomplishes on Relic 3 (py2-ledger-phantom.py):

raw_tax_cents = (cents * 0.0825)
floor_tax = int(raw_tax_cents)
remainder = round(raw_tax_cents - floor_tax, 4)
if abs(remainder - 0.5) < 0.0001:
    tax_cents = floor_tax if (floor_tax % 2 == 0) else (floor_tax + 1)
else:
    tax_cents = int(round(raw_tax_cents))
/**
 * @preserve Soul Invariant: IEEE 754 Banker's Rounding (Round-Half-to-Even)
 * Original Author: @carlos_fin_hack (2014)
 * Rounds exact .5 cent fractions to nearest even integer to prevent cumulative upward drift.
 */
export function calculateBankersTaxCents(cents: number, taxRate: number = 0.0825): number {
  const rawTax = cents * taxRate;
  const floorTax = Math.floor(rawTax);
  const remainder = Number((rawTax - floorTax).toFixed(4));

  if (Math.abs(remainder - 0.5) < 0.0001) {
    return floorTax % 2 === 0 ? floorTax : floorTax + 1;
  }
  return Math.round(rawTax);
}

Every test passes. Zero dependencies. Zero memory leaks. 100% of the Soul intact.

We proudly submit NecroStack for Best Use of Gemma.

Google's open-weight Gemma model (ai/gemma3 running locally via Docker Model Runner) is the intellectual engine of NecroStack. Rather than using an LLM as a simplistic chatbot, we leveraged Gemma across all three core generative and analytical stages of our LangGraph state machine:

Forensic Pathology & Edge-Case Extraction:

Gemma performs deep AST inspection on obsolete code from 2013–2015, categorizing security vulnerabilities (CVE-2018-7167, uninitialized Buffer leaks, broken MD5 ciphers) while isolating hidden domain invariants (NTP clock drift, CJK IME composition locks, Banker's Rounding) into a structured JSON schema.

Deterministic Zero-Dependency Reanimation:

Guided by our pgvector Migration Grimoire, Gemma synthesizes modern TypeScript (ES2026) utilizing native Web Crypto and Node Web APIs, explicitly verifying that each legacy edge case maps to a specific modern line of code.

Autonomous Verification & Ofrenda Generation:

Gemma writes a runnable node:test suite asserting each invariant and crafts the emotional Día de los Muertos Maintainer Tribute honoring past open-source developers.

By running Gemma 100% locally with Docker Model Runner, NecroStack proves that open-weight AI can tackle mission-critical, air-gapped enterprise refactoring with zero cloud egress, zero latency, and zero token costs.

Built with passion, remembrance, and open-source pride for Hacktoberfest 2026. 🕯️💀🏵️

── more in #ai-tools 4 stories · sorted by recency
── more on @necrostack 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/necrostack-resurrect…] indexed:0 read:14min 2026-10-31 · —