>>> LOGIN: ADMIN_ROOT
>>> PASSWORD: ***********
>>> DECRYPTING SCHEMATIC... [COMPLETE]
STATUS: PRODUCTION / HARDENED
ARCHETYPE: Universal Resource-Contention Guard & Lock-Free State Manager
MISSION: Eliminate deadlocks and blocking via ephemeral localized state duplication.
CHANGELOG (v2.2 → v5.1.0): queueing replaces outright rejection at the concurrent-clone cap • weighted TieLedger + coinflip queue ordering • secureModule() one-line whole-module wrapping • scope provenance IDs (ResourceID:ScopeID:CloneID) • restored in-clone set() with out-of-scope guarding • construction-time input validation • graceful shutdown() draining • a clone's successful writes merge back onto the primary resource (mergeShadow) instead of being discarded when the clone drops.
CHANGELOG (v5.1.0 → v5.2.0): opt-in RetryLedger (per-scope retry-on-timeout) • opt-in NoCloneLedger (per-scope queue-only, never clone).
CHANGELOG (v5.2.0 → v5.3.0): every operation now receives a third argument, signal: AbortSignal, that fires on timeout or external cancellation • a timed-out primary/clone's lock/slot is held until the abandoned operation actually settles instead of releasing on the losing race, closing a real overlap window • withScope(..., { signal }) lets a caller cancel one specific active or queued call, rejecting with the new OperationCancelledError (never retried) • TieLedger takes an optional agingRate so a low-weight scope can't starve forever • manager.getMetrics() observability snapshot • manager.shutdown() now returns a Promise that resolves once every in-flight operation has settled, with an optional { force: true }.
>>> LAUNCH INTERACTIVE CONSOLE — drive withScope(), the triple-axis guards, TieLedger, and the retry/cancel path by hand.
ONE LINE FIX ALL.
Grug have many functions. Grug tired of writing locks for every function. Grug wrap whole box of functions in autoGuard. Now only functions named antiLock_* get shield — unless Grug say guardAll: true, then every function protected. For entire file at once, Grug use secureModule(rawModule, config) — one call, whole imported file safe, no per-function naming needed. Friend import Grug's code, friend get safe code without doing anything. Magic.
SUBJECT: Transparent Contention-Guarding Proxy.
The autoGuard function acts as a universal higher-order wrapper via JavaScript Proxies. By default it guards only antiLock_-prefixed exports; passing guardAll: true extends the Proxy trap to every function on the target. secureModule(rawModule, config) is the zero-configuration entry point built on top of it: it instantiates a private ScopedResourceManager wired to a TieLedger, sets guardAll: true internally, and returns a fully-guarded module in one call. This isolates the entire configuration surface to the producer module, requiring zero boilerplate from the consumer.
MAKE FAKE ROOM FOR FRIEND.
Grug using workbench. Friend want use workbench too. Instead of make friend wait (boring) or fight (bad), Grug snap fingers. Make clone of workbench just for friend. Friend do work on clone — and if friend finish the work properly, whatever friend built gets carried back to the real workbench before the clone poofs. Clone only poofs empty-handed if friend's work went wrong (crash or ran out of time). Nobody wait. Nobody fight. Nobody's work vanishes for no reason.
SUBJECT: Phase-Lock Avoidance via Ephemeral MVCC.
The core architectural invariant is the total absence of blocking locks on a busy-but-not-saturated scope. If a resource scope is actively locked (activeLocks.has(scopeKey)) and clone capacity remains, the manager immediately triggers shadowClone() to generate an isolated, deep-copied ephemeral view of just that scope. Secondary operations occur purely on this disposable reference. On successful completion, the clone's dirty (written) keys are reconciled onto the primary resource via mergeShadow() — last-writer-wins per key against whatever else touched that key meanwhile — before the clone reference is dropped in a finally block; a clone whose operation throws or times out is dropped unmerged, so a half-finished write never reaches the primary. Only once both the primary lock and every clone slot are exhausted does a caller wait — and even then it waits in an explicit, ordered queue (Module 6) rather than being rejected.
STAY IN YOUR YARD.
Clone only copy YOUR yard, not whole world. If your name is "user:alice", you get clone of "user:alice" — and you can read AND write inside it, just like real thing, and it goes back to the real yard when you're done. But if you try touch "user:bob" inside clone, either to look or to change, clone yell at you and crash. Keeps Grug from accidentally messing up things that aren't his, and keeps a write from silently vanishing into nowhere when clone poofs.
SUBJECT: Scope-Bounded Deep Cloning & Strict Invariants.
Unlike traditional full-table cloning, ChainedHashTable.shadowClone utilizes explicit namespace rules (e.g., scopeKey or scopeKey:*) rather than arbitrary hash bucket co-location. The generated Shadow object exposes both get() and set(), and both route through _assertInScope() before touching entries. Any attempt to read or write a key outside the locked namespace triggers a catastrophic RuntimeInvariantError, preventing silent data reconciliation failures where an out-of-scope write would otherwise vanish when the clone is dropped. Underlying values are duplicated with structuredClone() (falling back to a JSON round-trip on older runtimes), itself wrapped so an unclonable value fails as a RuntimeInvariantError at the clone site instead of a bare engine exception downstream.
THREE RULES OF CAVE.
1. Rate: Don't knock on door too fast (Throttle).
2. Time: Don't stay inside too long (Timeout).
3. Space: Don't make too many clones or cave get crowded (Max Clones).
Break rule? You get kicked out. No infinite waiting.
SUBJECT: Independent Multi-Axis Resource Bounding.
System stability relies on bounding three orthogonal vectors of exhaustion:
1. Rate: StrictThrottler enforces a fixed-window request limit.
2. Duration: Promise.race() pairs the operation with a strict millisecond timeout budget.
3. Memory: maxConcurrentClones caps the instantiation of ephemeral shadows. Losing control of any single axis results in catastrophic unbounded scaling; this architecture guards all three.
NOBODY TURNED AWAY, EVERYONE GETS A NUMBER.
Old way: cave full of clones (20 max), new friend show up, Grug say "NO, go away" (EphemeralMemoryExhaustedError). Rude. New way: friend get a number and wait in line. When clone finishes and poofs, next number in line goes. If two friends tied for next spot, Grug flip coin — unless Grug wrote down ahead of time that some jobs (like SaveData) always cut the line over others (like ReadData). Line only breaks if it gets TOO long (maxQueueSize) — then Grug finally says no, but tells friend exactly why (QueueOverflowError), never just silently drops them.
SUBJECT: Bounded FIFO Admission Control with Weighted Tie-Breaking.
Once both the primary lock and every clone slot for a scope are exhausted, _enqueue() pushes the request onto _pendingQueue with an enqueueTime and returns an unsettled Promise. _processQueue() re-sorts the queue on every drain using the manager's _queueComparator — FIFO by default, or a TieLedger.getComparator() when supplied. TieLedger orders by a caller-supplied priorityWeights map keyed by scopeKey; equal (or absent) weights fall through to coinflipComparator, a Math.random() - 0.5 shuffle. The deprecated EphemeralMemoryExhaustedError reject-at-capacity path from v2.2 has been fully replaced by this admission queue; the only remaining rejection is QueueOverflowError, thrown synchronously at maxQueueSize so back-pressure is explicit rather than silent.
NO SECRET BROKEN THINGS.
When thing break, it MUST scream. No returning 'null' and pretending everything okay. But screaming crash program. So Grug put scream in a box (explicitTry). You open box, check if it has data or a scream inside. Safe to hold. Even setup time now screams properly — bad settings (like negative timeout, or empty name) caught the moment cave built, not later when friend already mid-task. And when Grug close cave for the night (shutdown()), nobody left waiting in line forever wondering — every friend still in queue gets told "cave closed" right then, loud and clear.
SUBJECT: Typed Exceptions & Result Envelope Pattern.
The module rejects silent failures (boolean flags, magic nulls) in favor of a strict typed error taxonomy (RuntimeInvariantError, ThrottlingExhaustedError, TimeoutExceededError, OperationCancelledError, QueueOverflowError). To prevent untamed exception bubbling, the boundary function explicitTry captures these errors into a structured Result object ({ok, data, error}), forcing the consumer into explicit error-handling paths. The pact now extends to two lifecycle edges that v2.2 left implicit: (1) construction — every ScopedResourceManager option (maxRequests, windowMs, maxQueueSize, resourceId, queueComparator) is validated in the constructor, failing at instantiation rather than deep inside a later call; and (2) shutdown — shutdown(reason, {force}) synchronously drains _pendingQueue (rejecting every waiting task with a RuntimeInvariantError and flipping _shutDown so subsequent withScope() calls fail loudly), then returns a Promise that only resolves once every in-flight primary/clone has also settled — see Module 8 for why that distinction matters.
SOME JOBS GET SECOND CHANCE. SOME JOBS NEVER CLONE.
Sometimes friend's job run out of time (TimeoutExceededError) but Grug thinks cave was just busy for a moment, not really broken. For THOSE jobs — the ones Grug write down in RetryLedger — Grug let friend try again, up to a number Grug picked, before finally giving up. Off by default: retrying broken thing can make broken thing MORE broken, so Grug only turn it on when Grug sure timeout was bad luck, not bad job.
Other jobs need to see EVERY change in order, one after another, no fake copies. Grug write those down in NoCloneLedger. Even when clone room is empty, those jobs wait in line for real workbench — never get a fake one.
SUBJECT: Per-Scope Opt-In Policy Ledgers.
RetryLedger.getMaxRetries(scopeKey) maps a scope to an extra-attempt budget (0 for any unlisted scope — off by default). withScope()'s outer loop catches only TimeoutExceededError; if the scope's budget isn't exhausted, it re-runs the entire dispatch — fresh throttle check, fresh primary/clone/queue admission decision — rather than blindly re-invoking the same branch. Any other thrown error, including the new OperationCancelledError, propagates immediately and is never retried.
NoCloneLedger.isQueueOnly(scopeKey) is consulted in _dispatch() before the clone-capacity check: a listed scope skips the clone path entirely and always falls through to the queue, even with slots free. This exists for operations that need strict linearizability on their scope — a snapshot-at-clone-time view would let them silently miss a write that happened between clone and merge.
GRUG CANNOT KILL WHAT GRUG STARTED.
Grug learn hard truth: once friend start job, Grug cannot reach in and stop friend's hands. Even after Grug yell "TIME UP" and walk away, friend might keep hammering in the dark, unseen, on the SAME workbench Grug just handed to someone new. Very bad — two friends hammering same wood, one of them invisible. So now: Grug does NOT hand workbench to next friend until first friend's hands actually stop moving, even if that's long after "TIME UP" was yelled. Grug also gives every friend a little bell (signal) that rings the moment their time is up — smart friend hears bell, drops hammer immediately, so workbench frees up fast instead of Grug waiting for friend to finish anyway.
Friend outside can also ring a SPECIFIC bell to cancel just ONE job, whether it's still in line or already hammering — different scream than "you were too slow" (OperationCancelledError, not TimeoutExceededError), so Grug never accidentally gives a cancelled job a second try.
Line-cutting weights don't fade with waiting — until now: Grug can tell TieLedger to add a little more cutting-power to a job for every tick it waits, so a cheap job doesn't wait behind expensive jobs FOREVER. And Grug can peek at the whole cave any time (getMetrics()) without touching anything, and closing the cave now waits for every hammering friend to actually finish, not just tells them to stop.
SUBJECT: Cooperative Cancellation & the Zombie-Overlap Fix.
Prior versions released activeLocks/activeClones the instant a Promise.race() lost to its timeout. Since JS has no preemption, the losing operation() call keeps executing in the background — meaning a brand-new caller could begin mutating the primary resource concurrently with an operation the manager itself had already abandoned. As of v5.3.0, release is wired to the abandoned call's own eventual settle (via a `.then` on the execution promise, tracked in _inFlight), not to the race outcome — closing that overlap window at the cost of a scope staying "busy" past timeoutMs if its operation ignores cancellation.
Every operation's third argument is now an AbortSignal, fired by an internal AbortController the instant its attempt times out — an operation checking signal.aborted can exit immediately instead of running pointlessly, closing that window itself. withScope()'s new {signal} option merges a caller-supplied external AbortSignal into the same race: it cancels a still-queued task immediately (spliced out of _pendingQueue) or an active one cooperatively, rejecting with OperationCancelledError — deliberately a distinct class from TimeoutExceededError so a configured RetryLedger can never mistake an explicit cancellation for a transient fault.
TieLedger's comparator now accepts an agingRate: effective priority becomes weight + waitedMs * agingRate, guaranteeing eventual dequeue for a low-weight scope regardless of sustained higher-weight traffic (0, the default, reproduces the prior static-weight behavior exactly). getMetrics() exposes a point-in-time { queueLength, activeClones, maxConcurrentClones, lockedScopes, inFlight, shutDown } snapshot. shutdown(reason, { force }) now returns a Promise resolved via Promise.allSettled() over every tracked in-flight settle-promise — "shut down" means truly idle — with force: true additionally calling abort() on every live controller first.
>>> RENDERING MERMAID.JS LOGIC MATRICES...
One pass through the retry loop in Diagram 4. signal is a per-attempt AbortController.signal, fired by this diagram's own timeout branch, then merged against any caller-supplied external signal (Diagram 5).
Wraps Diagram 1's single-attempt dispatch. Distinguishes a transient timeout (retryable, per-scope, via RetryLedger) from an explicit cancellation (never retried, regardless of ledger config).
The fix at the center of Diagram 1's "Settle" node: a timed-out call's lock/slot is no longer released the instant the race is lost. Concrete timeline for an un-cooperative 60ms operation racing a 10ms timeout.
>>> shadowClone.js v5.3.0 — VERSION export verified. Regression suite: npm test (57/57 PASS).
>>> END OF FILE.
>>> ARCHITECTURE IS DEPLOYED. UNAUTHORIZED MODIFICATIONS WILL BE LOGGED.