Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions coverage.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
ℹ file | line % | branch % | funcs % | uncovered lines
ℹ ----------------------------------------------------------
ℹ src | | | |
ℹ lru.js | 100.00 | 99.37 | 100.00 |
ℹ lru.js | 100.00 | 99.35 | 100.00 |
ℹ ----------------------------------------------------------
ℹ all files | 100.00 | 99.37 | 100.00 |
ℹ all files | 100.00 | 99.35 | 100.00 |
ℹ ----------------------------------------------------------
ℹ end of coverage report
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
schema: spec-driven
created: 2026-11-24
skip_specs: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Design

## Context

`src/lru.js` implements the `LRU` class as a doubly-linked list (`first`/`last` pointers) plus an `items` hash map (`Object.create(null)`). Two patterns are duplicated (see proposal.md - Why):

1. **Insertion block** — byte-identical in `setWithEvicted()` (lines 362-376) and `set()` (lines 410-424): create the item, wire first/last, set `this.last`.
2. **Traversal-and-skip-expired** — near-identical in `keys()`, `entries()`, `values()`, `toJSON()`: walk `first`→`last`, skip expired via `#isExpired`, collect.

Constraints (AGENTS.md §3.2, §6.1, §7.1): tabs/double-quotes/semicolons; 100% line coverage; O(1) get/set/delete; traversal must access items directly (never call `get()`, which moves items and deletes expired entries mid-iteration).

## Goals / Non-Goals

**Goals:**
- Single source of truth for the insertion block via `#insertItem(key, value)`.
- Single source of truth for the live-item traversal via `#forEachLive(callback)`.
- Byte-for-byte behavioral equivalence; 100% line coverage preserved.

**Non-Goals:**
- No change to the update-existing-key branch (already near-identical, not the flagged duplication).
- No change to the `keys`-array overloads of `entries()`/`values()`.
- No change to `forEach()`, `cleanup()`, `sizeByTTL()`, `keysByTTL()`, `valuesByTTL()` — distinct semantics.
- No public API change.

## Decisions

### D1: `#insertItem(key, value)` returns the created item

The helper performs the full insertion: `item = this.items[key] = { expiry, key, prev: this.last, next: null, value }`, then `if (++this.size === 1) this.first = item; else this.last.next = item;`, then `this.last = item;`, and returns `item`.

- **Why return the item?** Both callers already assign the result to a local `item` and the surrounding code is identical; returning keeps the call sites a one-liner and preserves the exact `prev: this.last` capture-before-reassignment ordering.
- **Eviction stays in the caller.** `set()` calls `this.evict()` (fires onEvict); `setWithEvicted()` calls `this.#evictItem()` and captures the evicted item for its return value. Only the post-eviction insertion is shared. This preserves the divergent eviction semantics while removing the duplicated block.
- **Alternative considered:** a single `#setInternal(key, value, { silent })` that also handles eviction. Rejected — it would couple the two eviction paths and risk changing onEvict firing behavior; the flagged duplication is only the insertion block.

### D2: `#forEachLive(callback)` for traversal

A private helper that walks `for (let x = this.first; x !== null; x = x.next)`, skips expired items via `#isExpired(x)`, and invokes `callback(item)` per live item. `keys()`, `entries()`, `values()`, `toJSON()` each call it with a collector callback.

- **Why a callback rather than a returned array?** The four methods collect different shapes (`x.key`, `[x.key, x.value]`, `x.value`, `{key,value,expiry}`). A callback keeps the traversal logic shared while letting each caller decide what to collect.
- **Why not a generator?** A generator would add allocation/iteration overhead to the hot path; a plain callback loop preserves the current O(1)-amortized, allocation-light traversal.
- **Direct item access (AGENTS.md §7.1):** the helper reads `x.key`/`x.value`/`x.expiry` directly and uses `#isExpired` — it never calls `get()`, so LRU order is not mutated and expired items are not deleted mid-iteration.
- **Alternative considered:** a shared `#collectLive(selector)` returning an array. Rejected — `toJSON()` builds objects and `entries()` builds pairs; a selector callback is the minimal shared surface.

### D3: Helper placement

Place `#insertItem` and `#forEachLive` adjacent to the related private helpers (`#unlink`, `#removeItem`, `#evictItem`) to keep private infrastructure grouped.

## Risks / Trade-offs

- [Ordering bug in `#insertItem`] → The `prev: this.last` capture and `++this.size === 1` first-wiring must execute in the exact original order; verified by the full 173-test suite and 100% coverage.
- [Coverage gap on new helpers] → Both helpers are exercised transitively by every existing set/keys/entries/values/toJSON test, so 100% line coverage is maintained without new tests.
- [Behavior drift] → Pure refactor; no observable change. The existing suite is the regression guard.
- [Callback allocation in `#forEachLive`] → Negligible; the callback is a small closure per call, matching the current per-method allocation profile.

## Migration Plan

Single-file change to `src/lru.js`. No migration, no data changes, no deploy steps. Rollback is a `git revert` of the commit.

## Open Questions

None.
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Proposal

## Why

A code-quality audit (issue #547, rule QUAL-003, low severity) found two copy-paste patterns in `src/lru.js` that are a maintenance hazard: the insertion block in `setWithEvicted()` is byte-identical to the one in `set()`, and the "walk the linked list, skip expired, collect" pattern is near-duplicated across `keys()`, `entries()`, `values()`, and `toJSON()`. Keeping multiple copies in sync risks silent divergence that could break LRU ordering or TTL handling. Extracting shared helpers gives each pattern a single source of truth.

## What Changes

- Extract the duplicated post-eviction insertion block into a private helper `#insertItem(key, value)` that creates the item, wires the first/last pointers, sets `this.last`, and returns the item. Both `set()` and `setWithEvicted()` call it after their own eviction handling.
- Extract the shared "walk list, skip expired, collect" traversal into a private helper `#forEachLive(callback)` and rewrite `keys()`, `entries()`, `values()`, and `toJSON()` to use it.
- No public API changes. No behavior changes. No breaking changes.

## Capabilities

### New Capabilities

None. This is a pure internal refactor with no spec-level behavior change.

### Modified Capabilities

None. No requirement changes. The change opts out of specs via `skip_specs: true` in `.openspec.yaml` because behavior is unchanged — specs describe behavior, and nothing observable changes.

## Impact

- **Code:** `src/lru.js` only. Two new private methods (`#insertItem`, `#forEachLive`); call-site updates in `set()`, `setWithEvicted()`, `keys()`, `entries()`, `values()`, `toJSON()`.
- **API:** None. Public surface unchanged.
- **Dependencies:** None.
- **Tests:** Existing 173 tests must continue to pass; 100% line coverage must be maintained. No new tests required (behavior is unchanged), but coverage of the new helpers is exercised transitively by the existing suite.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Tasks

## 1. Shared insertion helper

- [ ] 1.1 Add private method `#insertItem(key, value)` to `src/lru.js` that creates the item (`this.items[key] = { expiry, key, prev: this.last, next: null, value }`), wires first/last (`if (++this.size === 1) this.first = item; else this.last.next = item;`), sets `this.last = item`, and returns `item`. Verify by reading the new method and confirming it matches the original insertion block byte-for-byte.
- [ ] 1.2 Replace the inline insertion block in `setWithEvicted()` with a call to `#insertItem(key, value)` (after the `#evictItem()` eviction handling). Verify `npm run test` passes.
- [ ] 1.3 Replace the inline insertion block in `set()` with a call to `#insertItem(key, value)` (after the `this.evict()` eviction handling). Verify `npm run test` passes.

## 2. Shared traversal helper

- [ ] 2.1 Add private method `#forEachLive(callback)` to `src/lru.js` that walks `for (let x = this.first; x !== null; x = x.next)`, skips expired items via `#isExpired(x)`, and invokes `callback(x)` per live item. Verify by reading the new method.
- [ ] 2.2 Rewrite `keys()`, `entries()`, `values()`, and `toJSON()` to use `#forEachLive` for the no-`keys`-argument traversal branch. Verify `npm run test` passes and output is unchanged.

## 3. Verification

- [ ] 3.1 Run `npm run lint` and confirm no errors.
- [ ] 3.2 Run `npm run coverage` and confirm 100% line coverage is maintained.
- [ ] 3.3 Run `npm run test` and confirm all 173 tests pass.

## Workflow follow-up

- Archive the change after the project's review requirements are satisfied.
- Verify the archived result.
32 changes: 32 additions & 0 deletions openspec/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
schema: spec-driven

# Project context (optional)
# Add only constraints that should guide OpenSpec artifacts and workflows.
# Include constraints an agent cannot infer by reading the code.
# Keep general project documentation and discoverable codebase facts out.
# Example:
# context: |
# Designs and tasks must cover Windows, macOS, and Linux
# Write all artifacts in Spanish

# Per-artifact rules (optional)
# Add custom rules for specific artifacts.
# Example:
# rules:
# proposal:
# - Keep proposals under 500 words
# - Always state what is out of scope
# tasks:
# - Break tasks into chunks of max 2 hours

# Per-operation guidance (optional)
# Add advisory guidance for how apply and archive work should be conducted.
# This is separate from artifact rules above.
# Example:
# operations:
# apply:
# guidance:
# - Keep test summaries concise
# archive:
# guidance:
# - Summarize the archive outcome before finishing
Empty file added openspec/specs/.gitkeep
Empty file.
111 changes: 57 additions & 54 deletions src/lru.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,7 @@ export class LRU {
entries(keys) {
if (keys === undefined) {
const result = [];
for (let x = this.first; x !== null; x = x.next) {
if (!this.#isExpired(x)) {
result.push([x.key, x.value]);
}
}
this.#forEachLive((x) => result.push([x.key, x.value]));

return result;
}
Expand Down Expand Up @@ -289,6 +285,51 @@ export class LRU {
return item;
}

/**
* Creates and links a new item at the most recently used position.
* Wires the first/last pointers and returns the created item.
*
* @param {string} key - The key to store.
* @param {*} value - The value to store.
* @returns {Object} The created and linked item.
* @private
*/
#insertItem(key, value) {
const item = (this.items[key] = {
expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
key: key,
prev: this.last,
next: null,
value,
});

if (++this.size === 1) {
this.first = item;
} else {
this.last.next = item;
}

this.last = item;

return item;
}

/**
* Invokes a callback for each live (non-expired) item in LRU order.
* Accesses items directly without calling get(), so LRU order is not
* mutated and expired items are not deleted mid-iteration.
*
* @param {function(Object): void} callback - Function to call for each live item.
* @private
*/
#forEachLive(callback) {
for (let x = this.first; x !== null; x = x.next) {
if (!this.#isExpired(x)) {
callback(x);
}
}
}

/**
* Efficiently moves an item to the end of the LRU list (most recently used position).
* This is an internal optimization method that avoids the overhead of the full set() operation
Expand Down Expand Up @@ -318,11 +359,7 @@ export class LRU {
*/
keys() {
const result = [];
for (let x = this.first; x !== null; x = x.next) {
if (!this.#isExpired(x)) {
result.push(x.key);
}
}
this.#forEachLive((x) => result.push(x.key));

return result;
}
Expand Down Expand Up @@ -359,21 +396,7 @@ export class LRU {
};
}

item = this.items[key] = {
expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
key: key,
prev: this.last,
next: null,
value,
};

if (++this.size === 1) {
this.first = item;
} else {
this.last.next = item;
}

this.last = item;
item = this.#insertItem(key, value);
}

this.#stats.sets++;
Expand Down Expand Up @@ -407,21 +430,7 @@ export class LRU {
this.evict();
}

item = this.items[key] = {
expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
key: key,
prev: this.last,
next: null,
value,
};

if (++this.size === 1) {
this.first = item;
} else {
this.last.next = item;
}

this.last = item;
item = this.#insertItem(key, value);
}

this.#stats.sets++;
Expand All @@ -440,11 +449,7 @@ export class LRU {
values(keys) {
if (keys === undefined) {
const result = [];
for (let x = this.first; x !== null; x = x.next) {
if (!this.#isExpired(x)) {
result.push(x.value);
}
}
this.#forEachLive((x) => result.push(x.value));

return result;
}
Expand Down Expand Up @@ -590,15 +595,13 @@ export class LRU {
*/
toJSON() {
const result = [];
for (let x = this.first; x !== null; x = x.next) {
if (!this.#isExpired(x)) {
result.push({
key: x.key,
value: x.value,
expiry: x.expiry,
});
}
}
this.#forEachLive((x) => {
result.push({
key: x.key,
value: x.value,
expiry: x.expiry,
});
});

return result;
}
Expand Down
Loading