Skip to content

v0.8.0

Choose a tag to compare

@github-actions github-actions released this 24 Jun 15:21
· 48 commits to master since this release

🔄 KongCode is now LaqrumCode

Same engine, new name — this is the rebranded marketplace ship. Because Claude Code identifies plugins by plugin@marketplace (no rename/alias path), existing installs need a one-time manual migration:

/plugin uninstall kongcode@kongcode-marketplace
/plugin marketplace remove kongcode-marketplace
/plugin marketplace add 42U/laqrumcode
/plugin install laqrumcode@laqrumcode-marketplace

Then restart Claude Code. MCP tools are now mcp__plugin_laqrumcode_laqrumcode__* — update any permission allowlists that referenced the old mcp__plugin_kongcode_* ids.

Moving an existing memory graph from ~/.kongcode? This release ships a content-safe migrator (copies your graph verbatim into the laqrum namespace; never rewrites your memory text):

LEGACY_BRAND=kong node scripts/migrate-legacy-graph.mjs

Old 42U/kongcode URLs 301-redirect here, so links and stars carried over.


Changed

  • Rebranded to laqrumcode — plugin id, marketplace name, MCP tool prefix (mcp__plugin_laqrumcode_laqrumcode__*), runtime paths (~/.laqrumcode), and SurrealDB namespace (laqrum). Existing installs must reinstall under the new id (see release notes).

Added

  • scripts/migrate-legacy-graph.mjs — content-safe migrator to import a pre-rebrand memory graph into the laqrum namespace (verbatim content copy + surgical structural-id fixups; LEGACY_BRAND/NEW_BRAND parameterized).

Hardened — enterprise 1M-install readiness pass (branch harden-1m-and-rename)

A 118-agent review (fan-out → triage → 3-lens adversarial verify) of the whole
engine for ~1M independent single-host installs surfaced 36 confirmed defects
(+ K0); 15 were refuted (one — orchestrator_metrics retention — because the
proposed hard-DELETE would have violated the Tier-0 NEVER-DELETE directive). All
confirmed defects are fixed below; full suite green (1318 tests). Frame: 1M users
= 1M local daemons, so the bar is deterministic correctness + per-host
resource/cost discipline, not server sharding. No content-table hard-deletes were
added; all new indexes are non-UNIQUE / IF NOT EXISTS (boot-safe).

  • K0 — drain pipeline unbroken. pending_work.status SCHEMAFULL enum was
    missing the committing transient that batch-2a's C1 CAS writes, so
    commit_work_results failed deterministically and NO work item could commit.
    Enum fixed; added test/schema-status-enum-drift.test.ts (non-mocked static
    guard for the whole code-vs-schema status-enum class — the mocked
    commit-claim-guard test couldn't see it).
  • Concurrency (CRITICAL/HIGH): K3 concept dedup race sealed via deterministic
    concept:⟨sha256(lowercased content)⟩ record id (no risky UNIQUE migration);
    K15 stale-recovery no longer reverts an in-flight committing row (clock reset
    at the CAS + pre-write ownership re-assert); K41 commit CAS made idempotent
    across a withRetry re-fire via committing_token; K31 causal_graduate claims
    chains at fetch time (RETURN BEFORE) so concurrent drains can't double-synthesize
    skills; K10 auto-drain lock no longer steals a live child's lock by age / unlinks
    a sibling's lock; K21 utility-cache running-average replaced with commutative
    util_sum/count accumulators; K9 consolidate mutual-archive guarded; K42
    createSoul idempotent.
  • Scalability hot path (CRITICAL/HIGH): K4 tagBoostedConcepts, K19/K20
    consolidate + concept-dedup, K18 reflection membership, K14 PreCompact reads —
    all converted off full linear cosine/WITH NOINDEX scans to HNSW-KNN /
    index-served bounded reads; K2/K23 retrieval-eval bounded + batched + moved off
    the Stop critical path; K6 deadline now cancels the inner pipeline (AbortSignal
    honored); K13 cross-encoder rankAll got a timeout + circuit breaker; K28
    graduation aggregations no longer run twice per prompt; K8/K29/K33 added missing
    created_at/timestamp/importance indexes + turn_score retention.
  • Resilience / resource (HIGH/MED/LOW): K1 dead session-reaper wired +
    hard sessions-Map cap; K48 _observedFilePaths cap + bounded scan; K11
    daemon close() drains in-flight RPCs before disposing the store; K12 RPC + embed
    backpressure; K5 ingest embed-failure degrades to an un-embedded (heal-able) row
    instead of dropping the turn; K16 concept backfill keys off content (not the
    dead name column); K17 embedding_cache periodic prune + pruned_at reset; K51
    memory backfill embeds the original short target; K32/K38/K39 added connect /
    readiness / download timeouts; K34 ACAN training uses transferable buffers; K40
    rerank all-dropped floor; K47 drain-log fd closed on spawn failure; K50 relay
    process-level rejection handlers; K35 UI search bounded.

Hardened — round 2/3 (loop-until-dry): regressions in the round-1 fixes + missed defects

A second adversarial review (regression audit of the fix commit + missed-issues
sweep) found 19 more confirmed defects — proof that one pass wasn't enough.
Most were regressions the round-1 fixes themselves introduced; two were genuinely
missed; three filings were refuted by running the real SurrealDB binary. All 19
fixed; full suite green (1407 tests).

  • Missed CRITICAL — Windows was entirely non-functional (R6): the MCP client
    spoke only Unix sockets (existsSync gate) while the daemon binds TCP on win32,
    so memory was dead on 100% of Windows installs and LAQRUMCODE_DAEMON_TRANSPORT=tcp
    was a no-op. Client is now transport-aware (TCP on win32 / env opt-in, fixed port
    18764), with a real meta.handshake readiness probe; dup-daemon protection preserved.
  • Missed HIGH — ReDoS on the shared event loop (R4/R16): the path-extraction
    regexes ([\w./~-]+\.ext) had catastrophic backtracking (~6s stall per
    PostToolUse/PreCompact on dot-heavy tool output). Replaced with one shared
    tokenizing extractor; K48's length cap alone didn't bound backtracking.
  • Regressions in round-1 fixes: R1 K21's deterministic-id muc UPSERT collided
    with the retained muc_mid_idx UNIQUE on legacy rows (froze utility writeback on
    upgrade) → removed the now-redundant UNIQUE + migration folds legacy rows; R2 K13's
    rerank breaker used a submit-time clock (tripped on queue depth) → single serial
    FIFO with dequeue-time clock; R5/R14/R15 K39's download used a wall-clock abort that
    killed healthy slow downloads + leaked/​hung on write errors → stream.pipeline()
    rewrite (connect-phase timeout only); R7 K1's cap evicted FIFO not LRU → recency
    bump; R8 K31 stranded the graduation backlog on a failed synthesis → bounded claim +
    un-stamp recovery; R9 K15's ownership re-assert was TOCTOU → markTerminal gates the
    terminal stamp on committing_token at write time; R10 K6 left staging/access-bump
    unguarded on abort; R11 K3's hash id broke on all-digit prefixes → constant letter
    prefix; R12 K16 healed concepts to a searchTerms-stripped vector → concept
    embedding_target; R3 K2's detached eval wasn't drained on shutdown → daemon
    pending-task registry awaited in gracefulCleanup.
  • Coverage gaps (R19/R20/R22/R23): added the real-behavior tests whose absence let
    the round-1 fixes ship under-verified (the mocked-test-blindspot class that hid K0).

Hardened — round 4/5 (convergence): regressions in the round-3 fixes + 1 pre-existing

A third review round (regression audit of the round-2/3 commit + whole-campaign
completeness critic) found 6 more (trend: 36 → 19 → 6, converging); all fixed,
full suite green (1451 tests).

  • S1 (pre-existing, HIGH): a failed schema apply left isAvailable() returning
    true (it checked only socket connectivity), so the daemon served writes for its
    whole lifetime WITHOUT the pending_work UNIQUE seal the dedup/committing_token
    CAS relies on. Added a schemaApplied gate (isAvailable = isConnected && schemaApplied), a bounded schema-apply retry, and a reconnect-path re-arm so a
    degraded store self-heals.
  • S6 (Windows multi-user isolation): R6's TCP path bound a flat shared loopback
    port, so a 2nd OS user on a Windows host adopted the 1st user's daemon + graph.
    Port is now derived per-user (username/SID hash offset, symmetric client/daemon),
    plus a 0600 per-user handshake token (loopback TCP isn't user-isolated like the
    Unix socket).
  • Regressions in the round-3 fixes: S3 — R4/R16's replacement left a quadratic
    suffix-strip regex and pre-compact lost its size cap → non-backtracking reverse
    scan (0.1ms vs 4.2s @64kb) + restored 64KB cap; S7 — R4/R16 silently dropped
    Windows backslash paths → backslash added to the token splitter; S4 — R9's guarded
    terminal stamp mis-reported a retry-idempotent success as skipped → self-token
    confirmation SELECT + stripped the contradictory skipped from the success
    envelope (a pre-existing ambiguity); S5 — R8's graduation un-stamp missed the
    stale-recovery path → stale-recovery now un-stamps won_chain_ids.

Hardened — round 6/7 (convergence): regressions in the round-5 fixes

A fourth review round found 4 more (trend: 36 → 19 → 6 → 4), all regressions
in the two most complex round-5 fixes (S1 schema-gate, S6 Windows transport),
fixed by hand; full suite green (1451 tests).

  • T1: S1's schemaApplied gate could latch a healthy daemon to
    isAvailable()===false permanently (a transient schema-reapply timeout behind
    the reconnect early-return) — worse than the bug it fixed. Made schemaApplied
    monotonic (the schema persists in the DB and is idempotent; reconnect only
    re-applies when never-applied) and only clears the zombie flag when usable.
  • T2: S6 enforced the handshake token on every connection but the co-located
    UDS client never sent it → self-lockout when LAQRUMCODE_DAEMON_PORT is set on
    Linux/macOS. Client now attaches its own 0600 token whenever readable.
  • T3: S6's per-user port window [18764, 28763] overlapped the managed-SurrealDB
    port 18765 → ~1/10000 usernames wedged. Window moved to [28765, 32764], provably
    disjoint from SurrealDB and below the ephemeral floor; the test now guards it.
  • T4: S3's pre-compact 64KB cap head-sliced (dropped the actively-edited recent
    file from the FILES: resume summary) → tail-slice (recency-biased).

Hardened — round 8/9 (convergence floor): 1 LOW regression + 1 stale doc

A fifth review round found only 1 LOW + 1 doc (trend: 36 → 19 → 6 → 4 → 1; no
CRITICAL/HIGH/MEDIUM remain). Both fixed; full suite green (1456 tests).

  • U1 (LOW): T3's daemon IPC window [28765, 32764] overlapped the read-only UI
    server window (uiPort = 28900 + uid%10000) → ~1/4000 TCP-transport users got a
    working daemon whose web UI silently failed to bind (non-fatal: the IPC server
    wins the port, the UI skips). Moved the UI base to 33000 (exported UI_PORT_BASE,
    above the IPC ceiling 32765); test/fix-u1-ui-daemon-port-disjoint.test.ts now
    guards the two windows' disjointness so it can't recur.
  • U2 (doc): T3 left a stale JSDoc still describing the old [18764, 28763] window
    — corrected to the real [28765, 32764].

Hardened — round 10/11: V1 (half-applied UI-port move) + flaky-test root cause

A sixth review round found 1 HIGH (V1); fixing it surfaced a pre-existing flaky
test whose root cause is also fixed. Full suite green (1460+ tests).

  • V1 (HIGH, half-applied U1): the round-9 UI-port move (28900→33000) updated
    src/ui-server.ts but NOT the user-facing launcher scripts/open-ui.mjs (nor
    the skill doc), which kept a duplicated 28900 literal → on the default config
    the daemon bound :3X000 while node scripts/open-ui.mjs opened :29900, so
    the web UI was unreachable for ~100% of default installs (and would hand the
    daemon bearer token via ?token= to whatever held the stale port). Fixed at the
    root: the launcher now imports uiPort() from dist/ui-server.js (single
    source of truth — no duplicated formula), docs corrected, and
    test/fix-v1-open-ui-port-parity.test.ts forbids re-introducing a literal. This
    closes the port-derivation-duplication class (R6→S6→T3→U1→V1).

Hardened — round 12: withRetry now retries transaction conflicts (K21 class)

Verifying V1 surfaced an intermittently-failing real-DB test
(duplicate-row-fix "two parallel claims") — root cause: SurrealStore.withRetry
retried only connection-level faults (isRetryableSurrealError), NOT a
transaction write conflict, which SurrealDB itself flags as "...can be
retried". So under genuine multi-session concurrency a CAS
(claimSessionForCleanup, updateUtilityCache, the commit CAS — the K21-noted
gap) could surface a conflict error instead of cleanly losing. withRetry now
retries transaction conflicts with bounded backoff (≤3, ~135ms) and no
reconnect
(the socket is healthy; the conflicted tx already rolled back, so
re-running a CAS is safe). The previously-flaky test now passes 10/10;
test/fix-withretry-tx-conflict.test.ts is a CI-safe unit guard (the real-DB
test skips in CI). Full suite green (1463 tests).

Hardened — round 13 (live verification): memory_utility_cache.memory_id type

Restarting the daemon onto the final build (mandatory live-verification gate)
surfaced a runtime error the whole test suite missed: updateUtilityCache
logged Couldn't coerce ... Expected record<memory>|record<concept>|record<turn> but found artifact:... on every artifact (and skill) retrieval. retrieval-quality.ts
caches utility for ANY scored record id (memory/concept/turn/artifact/skill
— all recall scopes), but memory_utility_cache.memory_id was typed as only the
3-table union, so artifact/skill utility writebacks were silently rejected and
those proven-utility signals were lost. Same schema-narrower-than-code class as
K0; invisible to CI (swallowed runtime error on the live hook path only).

  • Widened to DEFINE FIELD OVERWRITE memory_id ON memory_utility_cache TYPE option<record> (any record table — matches the field's documented "keyed by
    any retrieved-record id" intent). OVERWRITE because IF NOT EXISTS no-ops a
    type change; widening can't invalidate an existing value so the re-validation
    is safe. Verified live: the DB now accepts artifact:/skill: memory_id
    rows, daemon re-applies schema green on the populated DB, no coercion errors.
  • Also confirmed live this restart: schema applies cleanly on ~10.8K/3.5K/8.6K
    rows; R1's REMOVE INDEX muc_mid_idx is gone (direct DB query: indexes []);
    the K13 timeout-breaker + K40 all-dropped floor degrade gracefully under
    CPU-slow rerank.

Hardened — round 14: concept.superseded_by + close the polymorphic-record class

The live artifact-coerce catch prompted a systematic sweep of EVERY record<…>
schema field type vs. the code that writes it — which found a third instance of
the same class. concept.superseded_by was typed record<memory>, but the
extraction dedup path (commit.ts, target.kind==="concept") supersedes a
concept WITH a concept id → Couldn't coerce ... found concept:... (swallowed at
:decay), so the back-pointer silently never set (the supersedes edge +
superseded_at still landed). A concept is legitimately superseded by EITHER a
correction memory (the supersede tool) OR a newer concept, so the field is now
option<record> (OVERWRITE), verified live (TYPE none | record).

  • The class (K0 enum → memory_idconcept.superseded_by) is now closed and
    guarded: test/fix-schema-polymorphic-record-fields.test.ts asserts the two
    polymorphic fields stay open record and the three self-referential
    superseded_by fields stay intentionally table-typed. The remaining
    record<…> fields were swept and verified consistent with their writers.

Hardened — Phase 2 (post deletion-policy): G3 graphExpand read-path liveness gate

After the GRAPH DELETION — QA-GATED policy change, a deletion-lens enterprise review
(adversarial, every proposed delete gated) refused 10 of 11 deletion designs for real
blast-radius gaps — confirming bulk graph-deletion is unsafe and must roll out individually
through the graph-delete-qa gate. But it surfaced one unambiguous zero-deletion bug:

  • G3 — graphExpand had no read-path liveness filter (surreal.ts), so a superseded/
    archived/pruned (dead) node with an edge from a live seed resurfaced as a live retrieval
    neighbor
    — dead knowledge re-entering context every turn. Added a NONE-tolerant
    union-of-dead-markers WHERE to both the forward and reverse traversals, mirroring the
    per-table predicates vectorSearch already uses. Verified live: the WHERE-on-graph-path
    parses + executes, one seed narrowed 11 neighbors → 1 (10 dead nodes dropped); NONE-tolerant by
    construction so no live node is over-filtered. test/fix-g3-graphexpand-liveness.test.ts guards
    it. (Sibling tool paths what-is-missing / cluster-scan share the class — same-class follow-ups.)

The actual GC deletes (orphaned-edge sweep, dedup-merge, tiered retention, junk purge, privacy
erasure) remain a gated, incremental roadmap behind a future gcHardDelete keystone — not bulk.

Hardened — Phase 2 Round 1: the gcHardDelete keystone (src/engine/gc.ts)

Built the single audited content-DELETE choke point that every GC delete must flow through —
deletes nothing itself; it is the gate. Five REAL primitives (no stubs):

  1. snapshot — in-process SELECT of target rows + all incident edges across all 26 relation
    tables
    → re-importable file under ~/.laqrumcode/cache/gc-backups/; a write failure ABORTS.
  2. genuinely-dead — refuses to delete a correction (category='correction' / [CORRECTION]).
  3. blast-radius — co-deletes every incident edge + NULLs the complete scalar back-pointer
    set (4× superseded_by, resolved_by, causal_chain.trigger/outcome_memory, and the
    memory_utility_cache/retrieval_outcome/compaction_checkpoint .memory_id refs).
  4. after-verify — throws (never claims success) unless targets are gone, zero edge across the
    26 tables references a deleted id, and zero scalar back-pointer dangles.
  5. audit — a maintenance_runs row per op. Record-ids are interpolated as validated Thing
    tokens (IN [id, …]), never IN $stringArray (which this engine silently no-ops).
  • D4 lint evolved, not loosened: CONTENT_TABLES + the literal regex are unchanged; a content
    DELETE is permitted ONLY inside gc.ts with a same-line // GATED-GC: marker, and a new
    DELETE ${expr} dynamic-table detector forces the keystone's own deletes under the gate. Added
    D5 (the keystone body must retain its snapshot + after-verify). Adversarial review found +
    fixed two gaps before commit: GAP-1 (5 missed back-pointers → would dangle, now reconciled +
    after-verified) and GAP-2 (function-wide marker scope → tightened to same-line so no ad-hoc
    DELETE inside gc.ts is auto-laundered). Full suite green (1483). A 2.3 GB master DB snapshot was
    taken first as the disaster net.

Hardened — Phase 2 Round 2: orphaned-edge sweep (gcSweepOrphanedEdges) — FIRST real GC delete

The graph carried 309 dangling edges — relation rows whose in/out endpoint record was
hard-deleted long ago (residue of pre-v0.7.93 DELETE-based concept GC + bulk imports). Added
gcSweepOrphanedEdges (reusable; also the trailing sweep after a future node delete): detects via
in.id IS NONE OR out.id IS NONE (absent endpoint — a SOFT-tagged endpoint still exists and is
read-filtered by G3, never deleted), snapshots the danglers, deletes per table, and after-verifies
(throws unless every table's orphan count is 0 AND its both-endpoints-live count did not DROP).

  • Detector proven before deleting (read-only): per-table orphan + both-live == total
    (exhaustive + disjoint, zero false positives); sampled endpoints confirmed absent.
  • Executed on the live DB with per-action sign-off: removed exactly 309 (related_to 97,
    derived_from 90, relevant_to 90, broader 20, performed 11, owns 1); independent global re-count
    0; reversible 38 K snapshot (309 CREATE statements) written first. fix-g2-orphaned-edge- sweep.test.ts guards the contract. Edge tables aren't content-bearing (lint-legal), but the sweep
    still runs the full snapshot + after-verify QA gate.

Hardened — Phase 2 Round 2b: GC wired into daemon maintenance + G10B embedding_cache purge

Made the GC self-maintaining in the daemon's own maintenance cycle (the 1M-right path — every
install cleans its own graph on boot + every 6h, no ad-hoc scripts):

  • G10B — purgeStaleEmbedCache now hard-deletes pruned rows. embedding_cache is telemetry
    (D4 DELETE-OK), and a pruned row is truly dead (l2Get filters pruned_at IS NONE; l2Put
    recomputes on miss). Live-verified end-to-end: the boot purge drained 16,384+ pruned rows →
    pruned = 0 (embedding_cache 29,775 → 13,266, −55%), usable cache untouched (13,237 preserved).
  • gcSweepOrphanedEdges wired into the maintenance job list (Group 2 + the 6h re-arm) — a cheap
    no-op now that the keystone co-deletes incident edges and the D4 lint blocks ad-hoc deletes.

Bug caught by LIVE verification (the gate the subagents' "live probe" missed): the first cut used
a LET $x = (SELECT … LIMIT $batch); FOR $row IN $x { UPDATE/DELETE … } form via queryMulti. The
daemon log proved it parse-errors on this SurrealDB (Unexpected token LIMIT, expected Eof — a
write statement inside FOR combined with a LIMIT-in-LET subquery). Worse, the pre-existing
Phase-1 soft-tag used the identical form and was the first statement
, so its error silently skipped
the whole purge — the embedding_cache prune had been broken before G10B too (the swallow.warn ate
it). Both phases rewritten to the proven keystone idiom: SELECT id … LIMIT N (queryFirst) →
DELETE/UPDATE … WHERE id IN [<validated Things>] (queryExec). fix-g10b-embed-cache-purge.test.ts

  • the K17-maint guards in fix-db4-queue-conn.test.ts updated to the new shape. Full suite green.

Hardened — Phase 3 (enterprise readiness) Wave 1: 8 audited gaps across security/observability/ops/cross-platform

A 6-dimension enterprise-readiness audit (adversarially verified, lean-1M) found 16 real gaps;
Wave 1 fixes the CRITICAL + HIGH ones, each adversarially reviewed + the integration gated live:

  • E2 (CRITICAL, security) — TCP daemon auth bypass. The S6 handshake token gated only identity,
    not data access: dispatchLine dispatched every method with no per-socket auth state, so a
    co-located process on the shared loopback port (Windows / LAQRUMCODE_DAEMON_TRANSPORT=tcp) could
    send tool.*/hook.* as its first line and read/write another OS user's graph. Added a per-socket
    authed flag (set only on a token-matching meta.handshake); dispatchLine now rejects any
    non-meta.* method on an unauthed socket with UNAUTHORIZED (−32006) when a token is enforced.
    UDS (0600) path unchanged. The mcp-client treats −32006 as reconnect+re-handshake+retry so a bare
    TCP reconnect self-heals. 8 tests over a real TCP socket.
  • E1 (HIGH, observability) — maintenance failures were structurally invisible. maintenance_runs
    had no status/error and recorded success-only; nothing read it. Added status/error fields, a
    runJob() wrapper that ALWAYS records (ok/error) in a finally, wired the maintenance.ts jobs
    through it, and a memory_health diagnostic that surfaces any job whose latest run errored (or is
    overdue). Live-verified: an injected error row flipped memory_health to red with an
    actionable message. Added purgeOldMaintenanceRuns + a ran_at index so the new audit trail
    itself stays bounded (no new unbounded growth).
  • E6 / E7 (HIGH, scale) — monologue + turn_archive grew unbounded; added count-gated retention
    routed through the gcHardDelete keystone (both are content tables).
  • E3 (CRITICAL, ops)scripts/backup-jsonl.mjs + restore-jsonl.mjs imported surrealdb from a
    hardcoded dev path → disaster recovery crashed on 100% of installs; changed to the bare specifier.
    E16: restored access_stats to both scripts' table lists.
  • E5 (HIGH, cross-platform) — managed-SurrealDB port was flat 18765 for all Windows OS users
    (collision → 2nd user wedged); now per-user (username-hash offset). E14: cred file written
    0600 atomically + ~/.laqrumcode dir 0700.
  • E9 (HIGH, cross-platform) — auto-drain was POSIX-only (which/spawn); made findClaudeBin
    Windows-aware (where, .cmd/.exe, %APPDATA%\npm) + shell on win32.

Full suite green (1546; sole failure is the pre-existing environmental R6 real-daemon-TCP-spawn
timeout). Wave 2 (E8 stale-daemon-restart, E10 EADDRINUSE, E11/E12 maintenance backoff + drain
liveness, E13 sweep cadence, E17 hot-table indexes, E20 skill path) follows.

Hardened — Phase 3 Wave 2: remaining 7 audited gaps (lifecycle / maintenance-perf / drain / skill)

Closes the rest of the 16-gap audit:

  • E8 (HIGH) — stale daemon after upgrade. A busy single-host daemon only exited at the
    last-client-disconnect, so it ran old dist/ indefinitely after npm upgrade. Added a bounded
    supersede grace window (supersedeGraceMs, 3min default): once flagged superseded by a newer
    client it drains in-flight RPCs (via the audited K11 close() path) and exits even with clients
    attached, so a fresh daemon spawns. Graceful last-disconnect path still wins if it fires first
    (single shared supersedeFired guard; can't double-exit or thrash).
  • E10 (MEDIUM) — TCP EADDRINUSE recovery. The TCP listen path now probes the occupant with an
    unauthenticated meta.health and throws a distinguishable TcpPortInUseError{kind}
    laqrumcode-daemon → defer to the live sibling (exit 0), foreign → clear diagnostic + exit 1
    (was an opaque bind crash; UDS path unchanged).
  • E11 (LOW) — maintenance failure backoff. shouldRunMaintenance now reads the E1 status field
    and skips a job whose latest run errored within a 30min cooldown — a permanently-failing job no
    longer hot-loops every boot.
  • E13 (MEDIUM) — orphan-sweep cadence. Throttled gcSweepOrphanedEdges to weekly (with a
    zero-orphan heartbeat row to gate on) instead of ~56 full edge-table scans every 6h; force
    (post-delete trailing sweep) + dryRun bypass the throttle.
  • E17 (MEDIUM) — hot-table indexes. Added the composite/endpoint indexes the archiveOldTurns +
    garbageCollectConcepts predicates need (turn pruned_at,timestamp; retrieval_outcome
    memory_table,memory_id; concept-edge endpoints) so they aren't full scans on a large graph.
  • E12 (MEDIUM) — drain liveness. Auto-drain now writes a maintenance_runs row (job=autoDrain,
    ok/error) per attempt, so E1's memory_health diagnostic surfaces a chronically-failing drainer.
  • E20 (LOW) — backup skill. laqrumcode-backup-native de-hardcoded (runtime-resolved surreal
    binary, version de-pinned, Verify section corrected to the real batched-INSERT export format).

Full suite green (1577; sole failure is the pre-existing environmental R6 TCP-spawn timeout). All 16
audited enterprise-readiness gaps are now addressed.

Hardened — Phase 3 Wave 3: storage-substrate self-healing (the dimension the audit missed)

A completeness critic found the prior audit treated SurrealDB as a reliable black box — the real
remaining gap was self-healing of the storage substrate itself. Three "never silently corrupts /
never needs a human" blockers, closed (each surfaced via E1's maintenance_runs/memory_health):

  • C1 (CRITICAL) — managed SurrealDB child was never supervised. spawnManagedSurreal had no
    exit/error handler, so a dead/OOM-killed/crash-looping child = permanent silent failure with no
    recovery. Added a supervisor: on unexpected child exit it respawns with bounded exponential
    backoff
    (500ms→8s); ≥5 exits in 60s trips a crash-loop cap that stops respawning and latches
    degraded (no fork-bomb, no port race — one child at a time, idempotent).
  • C2 (CRITICAL) — corrupt-KV / persistent-failure now detect-and-surface, never auto-destroy. When
    the cap trips, it writes a surrealSupervisor error row (→ memory_health RED) + logs the data-dir
    and a surreal import … recovery command. It never auto-quarantines or deletes the data dir — at
    1M installs a false-positive must not wipe a user's graph; recovery stays a human decision. The win:
    no more silent permanent failure (transient death self-heals via C1; true corruption is loud).
  • C3 (CRITICAL) — embedding dimension is validated at the write boundary. A wrong-width vector
    (mis-set EMBED_MODEL_PATH, partial GGUF) used to poison ALL vector search (cosine throws DB-wide;
    manual repair-vector-dim.mjs-only fix). Now a non-1024 result is rejected before any write
    (cache/L2/resolve), the row stays un-embedded for backfill to heal, and an embedDimGuard error row
    surfaces it. Never rejects a valid 1024-dim vector.
  • H1/H2/H3 (HIGH, unbounded-disk class) — daemon.log + auto-drain.log now size-rotate at open;
    a gc-backups retention sweep (age+count+size cap, 24h floor) runs in the 6h cycle; memory_health
    gained a free-disk RED below threshold + M3 fix (store-amplification check reads the managed
    dataDir so it actually runs on managed installs).

Full suite green (1607; sole failure is the pre-existing environmental R6 TCP-spawn timeout). Per the
critic's verdict these three workstreams close the "self-heals / never needs a human" gap; remaining
scale-hardening (H4/H5, M1/M2/M4) follows.

Hardened — Phase 3 Wave 4: final scale-hardening (closes every audit + completeness-critic gap)

  • H4 (HIGH) — daemon-side hook-handler deadline. http-api.ts dispatched await handler(...) with
    no timeout, so under DB degradation an orphaned handler held Node's single event loop ~120s after the
    proxy already failed open, starving other sessions. Now wrapped in raceWithDeadline
    (~50s — above the 45s inner transform, below the 55s proxy budget): a wedged handler returns a fast
    fail-open {} and frees the loop. The user-turn fail-open boundary (the proxy's job) is unchanged.
  • H5 (HIGH) — connection ceiling. server.maxConnections (512) + explicit backlog + a persistent
    EMFILE/ENFILE handler that pauses-and-resumes accepting instead of crash-looping; applied after bind
    so the E10 EADDRINUSE path is untouched.
  • M2 (MEDIUM) — fair, retryable backpressure. Embed-queue-full now throws a retryable EmbedBusyError
    (→ client backs off + retries instead of failing the turn); dispatchLine passes through retryable codes
    rather than flattening to HANDLER_ERROR; a per-socket in-flight sub-cap (maxInFlight/4) stops one
    session starving all others. Global K12 cap unchanged.
  • M1 (MEDIUM) — adaptive embedding backfill. Backfill batch scales with the unembedded backlog
    (bounded ceiling) so a post-restore 100k backlog drains in hours/days, not months; steady-state stays a
    small trickle.
  • M4 (MEDIUM) — compaction_checkpoint retention + created_at index (purgeOldCompactionCheckpoints,
    wired into the 6h cycle).

Full suite green (1627; sole failure is the pre-existing environmental R6 real-daemon-TCP-spawn timeout —
needs a real Windows/TCP env to validate). All 16 audit gaps + all completeness-critic CRITICAL/HIGH/
MEDIUM gaps are now closed.
Residual: LOW tier L1–L4 (non-transactional schema apply [well-mitigated by
idempotent DEFINEs + retry], per-session in-memory counter race [benign], client fd-leak window [slow],
graduation_event retention [rare]) — documented scale-hardening follow-ups.

Hardened — Phase 3 Wave 5: second-pass critic gaps (auth DoS, upgrade self-heal, hook fd)

A second completeness pass re-verified the 4 CRITICAL fixes correct as-shipped (tested, dist==src,
reranker degrades, cold-start sound) and found 3 new material gaps — all fixed here:

  • E2-META-DoS (HIGH) — the E2 auth gate exempted ALL meta.*, but meta.shutdown /
    meta.requestSupersede do no token check, so on TCP a cross-OS-user could kill/supersede another
    user's daemon (availability DoS; not a data breach). Tightened the pre-auth exemption to EXACTLY
    {meta.handshake, meta.health} (typed Set<IpcMethod> so a future meta method is gated-by-default).
    Lifecycle meta ops now fall under the token gate on TCP; UDS + the probeTcpOccupant health path
    unchanged.
  • SCHEMA-UPGRADE-WEDGE (MEDIUM) — a <0.7.70→current upgrade with legacy data could be REJECTED by
    the pending_work.status ASSERT / UNIQUE indexes → daemon wedged needing a human. Added an in-band,
    data-preserving normalize (LET+IF, zero-cost on clean installs) that moves out-of-enum/NULL queue rows
    to the benign terminal 'failed' bucket before the ASSERT (using the live 5-value enum incl.
    committing — caught + recorded a latent enum-drift in predeploy-dedup.mjs); and applySchemaWithRetry
    now breaks the futile retry on a UNIQUE violation and surfaces a LOUD memory_health RED naming the
    exact recovery command — it does NOT auto-dedup content (that delete must route through the
    gcHardDelete keystone). No content destroyed.
  • HTTP-HOOK-FD-ASYMMETRY (MEDIUM) — mirrored H5 onto the HTTP hook server (maxConnections + an
    EMFILE/ENFILE accept-pause) so an fd-exhaustion event degrades instead of crashing the daemon;
    the H4 deadline + fail-open boundary unchanged.

Full suite green (1650; sole failure is the pre-existing environmental R6 TCP-spawn timeout).