Unit Tests
Relevant Source Files
- src/cli/adopt.ts
- src/engine/dependency.ts
- src/engine/index.ts
- src/engine/mastery.ts
- src/engine/sm2.ts
- src/storage/atomic-write.ts
- src/storage/cache.ts
- src/storage/frontmatter.ts
- src/storage/loader.ts
- src/storage/lock.ts
- src/storage/memory.ts
- src/storage/pattern-matcher.ts
- src/storage/roadmap-parser.ts
- src/storage/walker.ts
- src/types.ts
- test/engine-dependency.test.ts
- test/engine-mastery.test.ts
- test/engine-sm2.test.ts
- test/storage-atomic-write.test.ts
- test/storage-cache.test.ts
- test/storage-frontmatter.test.ts
- test/storage-loader.test.ts
- test/storage-lock.test.ts
- test/storage-memory.test.ts
- test/storage-pattern-matcher.test.ts
- test/storage-roadmap-parser.test.ts
- test/storage-walker.test.ts
- test/types-difficulty.test.ts
The PALEE unit test suite ensures the mathematical correctness of core algorithms, defensive file-safety protocols in the storage layer, and strict domain model typing. Unit tests are executed directly from TypeScript source using tsx and the native Node.js test runner (node:test), ensuring high speed and complete test isolation.
1. Engine Core Tests
Engine tests verify spaced repetition scheduling, graph algorithms, and pedagogical mastery computation on pure in-memory data structures decoupled from the filesystem.
SuperMemo SM-2 Spaced Repetition (test/engine-sm2.test.ts)
Tests in test/engine-sm2.test.ts (15 tests) verify the processReview function and scheduling arithmetic:
- State Transitions: Validates that quality ratings
trigger a lapse, resetting repetitionto 0,interval_daysto 1, and incrementinglapses. - Interval Progression: Verifies the expanding interval progression (Repetition 1
1 day, Repetition 2 6 days, Repetition ). - Ease Factor Clamping: Confirms that
ease_factoris adjusted via, is strictly clamped to , and is rounded to 4 decimal places. - Calendar Due Dates: Validates
computeDueDatecalculation in the local timezone across month and year boundaries.
Dependency Graph & Cycle Detection (test/engine-dependency.test.ts)
Tests in test/engine-dependency.test.ts (7 tests) exercise graph validation and traversal over the canonical depends_on field:
- 3-Color DFS Cycle Detection: Verifies that
detectCyclecorrectly flags simple circular dependencies () as well as complex multi-node cycles ( ). - Frontier Readiness Filtering: Validates
getReadyTopics, confirming that topics are only marked ready when all declared prerequisites reach or exceedMASTERY_THRESHOLD(0.70). - Missing Dependency Diagnostics: Ensures
validateDependencyGraphemits structured error descriptors containing missing topic IDs when unadopted notes are referenced independs_on.
Alias unioning is no longer tested here — the engine reads depends_on only. The storage-boundary canonicalization (legacy dependencies unioned into depends_on, deduplicated, array and comma-string forms) is covered in test/storage-loader.test.ts (loadTopics unions and dedupes depends_on and dependencies when both keys are present) and test/storage-roadmap-parser.test.ts (normalizes dependency aliases at the parse boundary).
Four-Pillar Pedagogical Mastery (test/engine-mastery.test.ts)
Tests in test/engine-mastery.test.ts (11 tests) verify the multi-dimensional mastery engine:
- Formula Invariant: Confirms
mastery = round((c + p + d + 2f) / 5, 4)with 40% Feynman weighting. - Mastery Threshold: Asserts that
MASTERY_THRESHOLD = 0.70serves as the authoritative threshold for dependency satisfaction. - Score Normalization & Clamping: Verifies that out-of-range scores (
< 0.0or> 1.0),NaN,null, or undefined inputs are safely clamped within[0.0, 1.0]. - Archive Topic Exclusion: Ensures archived topics (
archived: true) are excluded from active readiness calculations.
2. Storage Layer & Safety Tests
Storage tests enforce PALEE's "File-Safety Contract," guaranteeing non-destructive updates, concurrency control, and crash tolerance across local vaults.
File Locking & Mutex (test/storage-lock.test.ts)
Tests in test/storage-lock.test.ts (11 tests) verify the cross-process lock directory mutex:
- Atomic Acquisition: Confirms
mkdirSyncon.palee/locks/<hash>.lockdirprovides mutual exclusion, throwingECONFLICTon concurrent collision. - Descriptor & Heartbeat: Validates that lock descriptors record PID, hostname, and timestamp, refreshed every 15 seconds via
utimesSync. - Stale Lock Quarantine Takeover: Simulates abandoned locks by artificially aging
mtime, verifying automatic takeover after 60s on Windows or 120s on POSIX systems. - Symlink Canonicalization: Ensures symbolic links resolve to their canonical physical paths prior to lock hash computation.
Atomic Writes & OCC (test/storage-atomic-write.test.ts)
Tests in test/storage-atomic-write.test.ts (10 tests) verify safe filesystem writes:
- Optimistic Concurrency Control (OCC): Verifies that passing a stale SHA-256 fingerprint triggers an
ECONFLICTerror, preventing lost updates from external editors. - Atomic Swap & Temp Cleanup: Confirms writes flush to unique
.tmp.*files and execute atomicrenameSync. If write failure occurs, temporary files are cleanly unlinked.
Frontmatter Preservation via CST (test/storage-frontmatter.test.ts)
Tests in test/storage-frontmatter.test.ts (11 tests) exercise the YAML Document API:
- Comment & Custom Key Preservation: Verifies that updating PALEE keys (
palee_id,topic_mastery,due_at) preserves user-authored YAML comments, custom tags, and Obsidian properties. - Byte-for-Byte Body Integrity: Asserts that the Markdown document body remains identical byte-for-byte after frontmatter modifications.
- Fingerprinting: Verifies SHA-256 content hashing for OCC synchronization.
Vault Topic Loader (test/storage-loader.test.ts)
Tests in test/storage-loader.test.ts (13 tests) verify batch vault loading and the storage-boundary dependency canonicalization:
- Extraction & Normalization: Parses frontmatter blocks, converts numeric strings, and clamps invalid values.
- Fallback Title Hierarchy: Verifies title resolution order in
loadTopics: frontmattertitle→ base filename. - Pre-Scanned Performance: Confirms that providing a pre-scanned file list bypasses redundant filesystem scans.
- Dependency Canonicalization (
normalizeDependencies, 5 parameterized cases): Unions and dedupesdepends_on+ legacydependenciesin canonical-first order, supports comma-separated strings, preserves wikilinks, trims whitespace/drops empty entries, ignores unsupported values. - Union at Load (3 cases):
loadTopicsunions both keys when both are present, supports comma-separated string dependencies, and drops null/empty YAML list entries without coercing to"null".
Roadmap ingestion exercises the same boundary in test/storage-roadmap-parser.test.ts (normalizes dependency aliases at the parse boundary).
Working Memory & Session Recovery (test/storage-memory.test.ts)
Tests in test/storage-memory.test.ts (10 tests) verify the active study context system:
- Session Identification: Verifies session ID generation format
S-YYYYMMDDTHHMMSS-xxxxand draft checkpointsDRAFT-S-xxxxxxxx. - Hot Context Truncation: Validates that
.palee/hot.mdtruncates note text toMAX_HOT_WORDS = 250words to preserve context efficiency. - Catalog Regeneration: Ensures
.palee/index.mdaccurately regenerates topic lists, recent sessions, and draft links.
Pattern & Glob Matching (test/storage-pattern-matcher.test.ts)
Tests in test/storage-pattern-matcher.test.ts (14 tests) verify pattern matching utilities:
- Glob Support: Validates single
*, recursive**/*.md, character class[...], and wildcard?matching. - Cross-Platform Path Normalization: Automatically normalizes Windows
\backslashes to canonical/slashes. - Obsidian Tag Matching: Extracts and matches exact
#tagand nested#category/subcategorytag hierarchies.
Multi-Format Roadmap Parser (test/storage-roadmap-parser.test.ts)
Tests in test/storage-roadmap-parser.test.ts (8 tests) exercise curriculum ingestion:
- Format Flexibility: Parses roadmaps from pure
.yaml/.ymlfiles, Markdown frontmatter headers, and embedded```yamlcodeblocks. - Syntax & Schema Diagnostics: Validates topic node requirements and provides clear error diagnostics on missing required fields.
Vault Traversal (test/storage-walker.test.ts)
Tests in test/storage-walker.test.ts (11 tests) verify recursive file discovery:
- Markdown Discovery: Recursively traverses nested vault folders to locate
.mdfiles. - Exclusion Filters: Automatically ignores
.obsidian,.trash,.git,node_modules, and hidden dot-directories. - Symlink Safety: Skips circular symlinks to prevent infinite directory recursion.
In-Memory File Cache (test/storage-cache.test.ts)
Tests in test/storage-cache.test.ts (9 tests) verify caching and invalidation logic:
- Unsettled Horizon (2000ms): Mitigates filesystem buffer lag by using SHA-256 content hashes within the 2-second edit window, falling back to fast
mtimechecks outside the window. - Cache Invalidation: Invalidates cache entries on size mismatch or explicit deletion.
3. Data Model & Domain Type Tests
Difficulty Coercion & Types (test/types-difficulty.test.ts)
Tests in test/types-difficulty.test.ts (9 tests) enforce type contracts:
- Difficulty Coercion: Verifies
normalizeDifficultycoerces case-insensitive strings ("BEGINNER", " Advanced ") and numeric thresholds (values ≤ 1 →beginner, values ≤ 3 →intermediate, and values > 3 →advanced, including numbers like 0 or 6), safely defaulting unrecognized strings tointermediate. - Discriminated Union Session Types: Verifies type discrimination between
CompletedSessionandDraftSessionbased on session state and properties.
Code Entity Association Matrix
| System Component | Primary Functions / Classes | Test File | Test Count |
|---|---|---|---|
| Spaced Repetition | processReview, computeDueDate | test/engine-sm2.test.ts | 15 |
| Dependency Graph | detectCycle, getReadyTopics, validateDependencyGraph | test/engine-dependency.test.ts | 8 |
| Pedagogical Mastery | computeTopicMastery, MASTERY_THRESHOLD | test/engine-mastery.test.ts | 11 |
| File Locking | Lock class, acquireLock, releaseLock | test/storage-lock.test.ts | 11 |
| Atomic Writes | atomicWrite, isConflictError | test/storage-atomic-write.test.ts | 10 |
| Frontmatter CST | parseFrontmatter, updateFrontmatter, computeFingerprint | test/storage-frontmatter.test.ts | 11 |
| Vault Loader | loadTopics | test/storage-loader.test.ts | 5 |
| Working Memory | startSession, saveDraft, endSession | test/storage-memory.test.ts | 10 |
| Pattern Matcher | matchesGlob, matchesTag | test/storage-pattern-matcher.test.ts | 14 |
| Roadmap Parser | parseRoadmap | test/storage-roadmap-parser.test.ts | 8 |
| Vault Walker | walkVault | test/storage-walker.test.ts | 11 |
| File Cache | FileCache, UNSETTLED_HORIZON | test/storage-cache.test.ts | 9 |
| Domain Types | normalizeDifficulty, Difficulty, Session | test/types-difficulty.test.ts | 9 |
