Repository navigation
release: v3.5.0 - #88
Merged
Merged
Conversation
`.ts`/`.mts` modules previously failed to import bare specifiers (e.g.
`import { self } from "@cldmv/slothlet/runtime"`) or relative paths.
The TS branch loaded transpiled output via `data:` URLs, which Node's
ESM resolver cannot anchor bare-specifier or relative-path resolution
against.
Write transpiled output to `<projectRoot>/.slothlet-cache/<pid>-<id>/<hash>.mjs`
and import via `pathToFileURL`, mirroring the working `.mjs` branch.
The cache lives outside `node_modules/` so Node's `READ_PACKAGE_SCOPE`
walk doesn't halt at a `node_modules` segment, which keeps self-reference
resolution working in monorepo / dev-checkout scenarios.
Cache lifecycle:
- `shutdown()` removes the current instance's dir.
- First TS load per project root per process passively sweeps sibling
dirs whose `<pid>` prefix no longer matches a live process (probed
via `process.kill(pid, 0)` — signal 0, nothing is killed). Survives
SIGKILL, OOM, and forgotten shutdown calls.
… guards
Brings the suite to 100% across statements, branches, functions, lines.
- typescript-helpers-coverage: exercises `createDataUrl`, `findPackageRoot`
(statSync-throws, directory startPath, walks-to-root), `writeTransformedToCache`
(cache-dedup short-circuit, tmpdir fallback), and the sweep's PID
classification (dead → removed, live → kept, EPERM PID 1 → kept).
- loader-ts-cache-coverage: combined `slothlet()` initial load + `api.add({moduleID})`
+ `api.reload(apiPath)` in a single `it` so v8 captures all four arms of
`if (moduleID)` / `if (cacheBust)` in #buildTypescriptModuleUrl in the
same coverage snapshot.
- metadata-key-validation-coverage: covers pre-existing prototype-pollution
guards on the `metadata.set` path (`__proto__` segment, empty-string key
early return, deep-nested walk true-arm).
- changelog/v3/v3.4.2.md: new release notes covering root cause, fix, cache location rationale (outside `node_modules/`), and the orphan sweep behavior. - TYPESCRIPT.md: replace the "self constant" section with a unified "Runtime Imports" section covering all three exports (`self`, `context`, `instanceID`); update Limitations to describe `.slothlet-cache/` and the sweep. - MODULE-STRUCTURE.md: new "Runtime Imports from .ts / .mts" subsection. - CONTEXT-PROPAGATION.md: new TypeScript example alongside ESM/CJS. - README.md: promote v3.4.2 to "Latest", trim Recent Releases to 4 per rule; broaden the cross-module-access feature line and example to list all three runtime exports.
The loader supports .mts symmetrically to .ts (`isTypeScript = endsWith(".ts") || endsWith(".mts")`)
but no test asserted .mts files actually load through the file:// cache path
or that `self.*` works across a .mts → .ts call.
Adds `api_tests/api_test_typescript_runtime/baz.mts` which imports `self`
and `instanceID` from `@cldmv/slothlet/runtime` and chains into `bar.ts`,
plus two new test cases (fast and eager modes) in the existing regression
suite. Updates the v3.4.2 changelog to document `.mts` coverage.
Adds `slothlet typegen`, a CLI and programmatic export that generates a
.d.ts file describing a Slothlet API directory. Designed for fast-mode
users who want editor-time type-checking and autocomplete on `self.*`
without opting into strict mode at runtime.
Three argument shapes for the CLI:
- positional: `slothlet typegen <dir> <output> <interfaceName>`
- flags: `--dir/-d`, `--output/-o`, `--interface-name/-n`
- fallback: `slothlet.typegen.{dir,output,interfaceName}` in package.json
Resolution order per option: flag → positional → package.json. Missing
fields fall through; if still unset, exits non-zero with a clear error.
Programmatic equivalent:
import { generateTypes } from "@cldmv/slothlet/typegen";
await generateTypes({ dir, output, interfaceName });
Internally loads the API in eager + fast TS mode, walks the structure,
extracts type info via the TS compiler API, writes the .d.ts, and
shuts the loaded instance down. Runtime is unaffected — Slothlet does
not invoke the generator implicitly.
Package wiring:
- `"bin": { "slothlet": "./bin/slothlet.mjs" }`
- `"./typegen"` exports entry (slothlet-dev → src, default → dist)
- `bin/` added to `files` so the CLI ships explicitly
Tests: 21 new tests across programmatic and CLI surfaces — happy paths
in fast/eager modes for both .ts and .mts, validation (missing options,
unknown flags, flag-without-value, unparseable package.json), and the
flag/positional/package.json precedence chain.
Docs: docs/changelog/v3/v3.5.0.md (renamed from v3.4.2.md and expanded
for the CLI), README "What's New" updated to v3.5.0, TYPESCRIPT.md gets
a "Generating Types On Demand" section.
Prior to this fix, the `self` proxy in @cldmv/slothlet/runtime had no
`set` trap. JS would default-set on the proxy's empty `{}` target while
`get` routed reads to the live API — so writes were silently lost (even
from the writer's perspective):
self.myVar = "hello"; // appears to succeed
self.myVar // → undefined
Add a `set` trap to the dispatcher and to both async + live runtime
self proxies. Each forwards the assignment through `ctx.self`
(boundApi), whose existing set trap lands the value on
`slothlet.api[prop]` so subsequent reads find it.
Stage 1 of a multi-stage change tracking a known issue. This commit
just stops the silent loss; ownership rules, wrap-on-set via
UnifiedWrapper, collision checks, and reload survival follow in
subsequent commits on this branch.
Stage 2 of the wrap-on-set work. Routes top-level `self.X = …` writes through a new `apiManager.setOwnedProperty()` that validates the caller owns the target path before persisting. Ownership model: - An `api.slothlet.api.add()`-mounted module owns its `endpoint` subtree. A function in that module may write under that subtree but NOT to siblings or to root keys it does not own. - Base-loaded modules (no api.add cache entry) effectively own the whole tree — they can write anywhere, matching today's "this is the user's API" intuition. - External code (no `currentWrapper` in ALS context) is unconstrained. The owned-root is looked up via `apiCacheManager.get(callerModuleID).endpoint`, which is the module's actual mount point — not the function-level wrapper apiPath. Falling back to the wrapper apiPath would over-restrict (a function couldn't write to its own siblings). Wires the slothlet ref through the context store (`store.slothlet = this` in slothlet.load()) so the runtime self set traps can reach `apiManager` synchronously. Adds `LOOSE_SET_NOT_OWNED` error code and translations across all 12 language files. Stage 2 covers TOP-LEVEL writes that fire the runtime self set trap. Deep-path writes like `self.X.foo = …` flow through the wrapper at `self.X` and will be addressed in Stage 3 alongside wrap-on-set.
When the value assigned via `self.X = …` is callable or object-shaped,
construct a UnifiedWrapper around it (matching the wrap pattern that
api.slothlet.api.add() uses). Primitives stay verbatim — no need to
proxy a number or string.
Also wires `slothlet` into child stores created by
`api.slothlet.run() / .scope()` so the runtime self set traps reach
apiManager from inside those callbacks.
Limitation acknowledged: hook / permission / lifecycle integration on
synthetic wrappers is incomplete. Calling a wrapped function set this
way returns the right result, but `hook.on("after:X")` interception
isn't reliably wired without the metadata-registration pass that
api.slothlet.api.add() does. For full lifecycle behavior, use
api.slothlet.api.add(). Documented in the test fileheader and
deferred to a follow-up.
Stage 4 (operationHistory replay on reload) and Stage 5 (docs +
changelog) follow.
Each `setOwnedProperty` call now records a `setOwnedProperty`
operation in `apiManager.state.operationHistory` AND a separate
`apiManager.state.ownedSets` Map keyed by full apiPath. The Map
carries the raw value plus owner metadata (moduleID,
wrapper apiPath, sourceFolder) needed to re-validate and re-wrap
on replay.
A new `apiManager.replayOwnedSets()` walks the Map and re-applies
each entry via `setOwnedProperty(..., { skipOwnershipCheck: true })`
— the original validation already succeeded; the original caller
wrapper is gone after reload.
Wired into all three reload entry points:
- apiManager._reloadByModuleID — calls replayOwnedSets at the end
- apiManager._reloadByApiPath — calls replayOwnedSets at the end
- slothlet.reload (full instance reload) — saves ownedSets before
load() destroys the apiManager, replays via setOwnedProperty after
the new manager is in place
Reload semantics: post-init runtime sets via self.X = … are the
authoritative state. If a module's init re-sets the same path
during reload, the replay overwrites it. This matches users'
expectation that explicit runtime sets are sticky.
- changelog/v3/v3.5.0.md: third feature section (after the TS-loader fix and typegen CLI) covering the four-stage self.X = … work — persist, owner-scoped writes, wrap-on-set, reload survival. Calls out the LOOSE_SET_NOT_OWNED error code and the deferred deep-path / hook-integration scope. Tests section updated with the four new runtime suites + the new fixture. - CONTEXT-PROPAGATION.md: new "Writable self.X = …" subsection with example showing both an allowed (under-own-namespace) write and a denied (sibling) write. Notes the wrap-on-set limitation around hook integration. - README.md: third bullet in v3.5.0 What's New.
Brings coverage back to 100% across statements, branches, functions, lines. - Added a live-mode test in self-assign-persist (covers runtime-livebindings.mjs set trap). - Added `overwriteOwnMount` fixture function + test to exercise the ownership-validation success arm (`isUnderOwn=true`) in apiManager.setOwnedProperty — previously only the throw path was tested. - Wrapped the defensive `parts.length === 0` guard and the `?? ownedRoot` callerApiPath fallback in `/* v8 ignore */`; these are reachable only via direct programmatic calls with null inputs, which the runtime self set trap's `String(prop)` coercion forecloses. - Mirrored the existing get-trap ignore convention on the set-trap no-ctx guard in both async + live runtime modules.
Four small fixes from review:
1. JSDoc on `ApiManager.setOwnedProperty` documents the `options` param
(with `skipOwnershipCheck?: boolean`) so the generated `.d.mts` exposes
the option to TS consumers instead of typing it as `{}`.
2. `setOwnedProperty` JSDoc no longer claims "Stage 2 … no UnifiedWrapper
yet": the function performs wrap-on-set for functions/objects and
records each write to `state.ownedSets` for reload replay. Rewrote
the description and `@param value` line to match current behavior.
3. Shutdown comment in `src/slothlet.mjs` now references the actual cache
layout `<projectRoot>/.slothlet-cache/<pid>-<instanceID>/` instead of
the stale `node_modules/.cache/slothlet/<instanceID>/` path that
predates the move out of `node_modules` (READ_PACKAGE_SCOPE issue).
4. README.md and docs/MODULE-STRUCTURE.md now point at v3.5.0 for the
`.ts`/`.mts` bare-specifier loader fix. No v3.4.2 tag exists — the
branch was renamed from release/3.4.2 to release/3.5.0 when typegen
and `self.X = …` work was bundled in. CONTEXT-PROPAGATION.md already
said v3.5.0.
Also moved an inline comment above the `callerApiPath` value in the
LOOSE_SET_NOT_OWNED throw so the i18n placeholder analyzer can parse
the key cleanly.
1. setOwnedProperty no longer pushes to state.operationHistory. The replay loop in src/slothlet.mjs:744 handles only add/remove/permission ops — setOwnedProperty entries were never consumed but kept being pushed (and re-pushed on every reload via replayOwnedSets), causing unbounded growth. Reload survival uses state.ownedSets, which is keyed by apiPath and idempotent. 2. setOwnedProperty JSDoc says the runtime self set trap covers `self.X = …` (top-level) only — deep-path writes like `self.X.Y = …` go through the wrapper at `self.X` and never reach this method. Previous wording incorrectly implied `self.X.Y = …` flowed here. 3. writeTransformedToCache JSDoc no longer implies the cache file fixes relative imports between user TS modules. The fix solves bare specifiers only — relative imports would resolve against the cache directory rather than the source dir. In practice slothlet loads each .ts/.mts file independently and wires them via `self.*`, so relative cross-module imports aren't needed.
1. Doc wording on the .ts/.mts loader fix is narrowed to bare-specifier (package) imports — relative imports between user TS modules (`import './sibling.ts'`) are explicitly noted as unsupported via the cache path. README.md, docs/MODULE-STRUCTURE.md, and the v3.5.0 changelog (5 passages) were claiming relative imports worked too, but the cache file at `.slothlet-cache/<pid>-<inst>/<hash>.mjs` isn't co-located with the source so relative resolution would fail. 2. v3.5.0 changelog "Reload survival" section no longer says each set is also recorded in `state.operationHistory` — that push was removed in commit 5b2a09a (replay never consumed it; it would have grown unbounded). Only `state.ownedSets` is the record now; the changelog updated to call out the explicit reason for the separate Map. 3. Comment in api-manager.mjs setOwnedProperty no longer claims ownership falls back to the wrapper's apiPath on cache miss. The actual fallback (set right below the comment block) is `"."` (root), matching the base-load policy already documented two lines below.
`findPackageRoot` returned `startPath` unnormalized — when a caller passed a relative `originalPath` to the public `writeTransformedToCache` helper, the walk could return a relative dir (e.g. `"."`). That propagated to a relative `cacheDir` / `cachePath`; `mkdir`, `writeFile`, and `pathToFileURL` then all silently resolved against the process cwd. It happened to work as long as cwd stayed stable between the write and the import, but it was fragile (a `process.chdir` would break it) and contradicted the JSDoc's "Absolute path to the package root" claim. `findPackageRoot` now runs `path.resolve(startPath)` before walking, so it always returns an absolute path regardless of the caller's input. Every downstream consumer (cache dir, cache file, file:// URL) is now cwd-independent. The copilot report predicted `pathToFileURL` would throw `ERR_INVALID_ARG_VALUE` on a relative path — that is not accurate for current Node (it resolves against cwd instead) — but the underlying normalization gap and JSDoc mismatch were real. New test passes a relative `originalPath` and asserts the resulting `cacheDir` and file:// URL are absolute.
1. `isProcessAlive` JSDoc clarified to document the deliberate fail-safe policy: only a confirmed ESRCH means dead; every other error code (EPERM and anything unexpected) is treated as alive so the cache sweep never deletes a dir whose owner might still be running. The implementation was already correct — copilot's suggested `err.code === "EPERM"` would have inverted the policy and made the sweep delete dirs on unexpected errors. Doc-only change. 2. `typescript-helpers-coverage` EPERM test no longer hardcodes that PID 1's cache dir is kept. It now probes `process.kill(1, 0)` (mirroring isProcessAlive) and asserts keep/remove against the computed result, so the test is correct on platforms where PID 1 isn't a POSIX-style unsignalable init process. 3. `typegen-cli` runCli appends `--conditions=slothlet-dev` to any inherited NODE_OPTIONS instead of replacing it, so coverage / runtime flags set by the test runner survive into the child. 4. `typescript-cache-key-collision` test uses `fileURLToPath` instead of `new URL(url).pathname` for portable file:// URL → path conversion (the latter mangles Windows drive paths).
The `@type` annotation on `ApiManager.state` listed only addHistory, initialConfig, and operationHistory — it omitted `ownedSets`, the Map that tracks `self.X = …` writes for reload survival. The generated `.d.mts` therefore under-described the type. Added `ownedSets` with its full entry shape. Also corrected the accompanying comment: it claimed the stored ownership info was "needed to re-validate on replay", but `replayOwnedSets()` does not re-validate ownership — the info is used to reconstruct the caller so wrap-on-set re-wraps with the same identity. Comment now states that accurately.
Stage 1 of removing apiCacheManager. `setOwnedProperty` resolved a caller module's ownership root by reading `apiCacheManager.get(id).endpoint`. That coupling is now severed: - OwnershipManager gains a `moduleEndpoints` Map (moduleID → mount endpoint) with `setModuleEndpoint()` / `getModuleEndpoint()`, cleared in `unregister()` and `clear()`. - `addApiComponent` and the base load in slothlet.mjs record the endpoint on the ownership handler alongside the existing subtree registration (base module → "."). - `setOwnedProperty` reads the endpoint from the ownership handler. apiCacheManager is untouched and still functional — this only relocates the one ownership-root lookup so later stages can remove the cache. No behavior change: 244 self-assign + ownership tests pass.
…, scope isolation, cache cleanup
Four related defects where slothlet did not behave as designed:
1. **Reload re-execution incomplete.** The operation-history "remove" replay
in `reload()` did a bare `deletePath(this.api, …)` — pruning only the
`api` tree and leaving `boundApi`, the apiCacheManager entry, ownership
and metadata behind. It now routes through
`removeApiComponent(apiPath, { recordHistory: false })` for the same full
cleanup a live remove performs.
2. **Stale / orphaned apiCacheManager entries.** `removeApiComponent`'s
apiPath branch never deleted the cache entry (only the moduleID branch
did). New `#sweepOrphanedCaches()` runs after a removal and drops cache
entries whose mount endpoint no longer resolves in the live tree —
handling apiPath/moduleID removal uniformly and preserving partial
removals. Caching for fast targeted reload stays; it is now invalidated.
3. **`self.X = …` survived a reload.** A reload rebuilds from disk + history;
a runtime write is not part of that history. The `ownedSets` /
`replayOwnedSets()` machinery (and the `skipOwnershipCheck` option) is
removed — `setOwnedProperty` still applies the live write but it is not
recorded or replayed. Module-init writes still reappear, because the
module body re-executes during the rebuild.
4. **`full`-isolation `.run()`/`.scope()` was unsound.** `full` isolation
`deepClone`'d `self` — `deepClone` of the live `boundApi` Proxy tree
produced a non-proxy copy and broke concurrent live-mode `.run()`. It now
uses a recursive, memoized copy-on-write `self` view: reads pass through
to the live instance, writes (top-level and deep-path) land on a
per-scope overlay discarded on exit. `partial` mode is unchanged —
`self` stays shared and writes persist, by design.
`setOwnedProperty`'s ownership-root lookup was moved off apiCacheManager onto
the ownership handler's `moduleEndpoints` map in an earlier commit.
Tests: `self-assign-replay` rewritten to assert `self.X = …` does NOT survive
a reload; new `api-cache-invalidation` suite (orphan cleanup on
remove-by-path / remove-by-id / reload-after-remove / partial removal); new
`scope-self-sandbox` suite (full-isolation copy-on-write `self`). All other
self-assign + per-request-context tests unchanged and passing. Coverage 100%.
core-reload-full only asserted the visible `api` tree after a full reload. It now also verifies — via the `diag` namespace (enabled with `diagnostics: true`) — that a reload's replayed `remove` performs the same full cleanup a live remove does: - no orphaned `apiCacheManager` entry survives for the removed module (`diag.caches.getAllModuleIDs()` count is stable across the reload); - the removed path is no longer owned (`diag.owner.get(path)` is null) while a kept path still is. This closes the gap where a shallow remove-replay could prune `api` while leaving `boundApi` / cache / ownership remnants behind.
The v3.5.0 changelog, README, and CONTEXT-PROPAGATION.md were written during the self-assignment work and still described the reload-survival mechanism (`ownedSets` / `replayOwnedSets`) that the subsequent reload/ scope/cache fix removed. Corrected: - `self.X = …` writes persist for the instance lifetime but do NOT survive a reload (a reload rebuilds from disk + operation history). - `.run()`/`.scope()` `full` isolation gives `self` a copy-on-write view, not a `deepClone`; `partial` shares `self` (writes persist). - changelog: Overview now lists all four 3.5.0 changes (adds the reload / scope-isolation / API-cache-cleanup fixes); the `self.X = …` section drops the "reload survival" stage and the stale `apiCacheManager.get().endpoint` ownership-lookup detail; Test Coverage section lists the new suites.
The self set-trap comments in runtime-livebindings.mjs and runtime-asynclocalstorage.mjs still described full-isolation ctx.self as utilities.deepClone(parent.self). That mechanism was replaced by the makeCopyOnWriteSelf copy-on-write view: reads pass through to the live tree, writes land in a per-scope overlay — there is no clone. The makeCopyOnWriteSelf JSDoc in api_builder.mjs separately overclaimed that reads always see current live state; object-valued children are memoized, so a child view stays pinned to the object resolved at first access. Reported by Copilot as three items. The two runtime-comment items were VALID — the comments were factually stale. The api_builder item was PARTIAL: the staleness is real, but the suggested fix (rebuild the memoized child view when the underlying object is swapped) would discard in-scope deep-path writes, since the overlay lives on that memoized view. The memoization is load-bearing for self.X.Y = ... read-back. Comment-only changes, no behavior change. The runtime comments now describe the copy-on-write view. The api_builder JSDoc now states that primitive/top-level reads re-resolve on every access while object children are memoized — and that pinning the view across a mid-scope swap is intentional, because following the swap would drop in-scope writes.
Three Copilot review items, all VALID. runtime-livebindings.mjs / runtime-asynclocalstorage.mjs — the self set trap routed every assignment through apiManager.setOwnedProperty(String(prop), ...). A Symbol property key (self[sym] = value, valid JS) was coerced by String(prop) to a "Symbol(...)" string and set as THAT string key — the symbol-keyed property the assignment targeted was never written, and the symbol read-back returned undefined. Both runtimes are fixed with a typeof prop === "symbol" fast-path that writes straight to ctx.self (the copy-on-write set trap under isolation, or boundApi); apiPath ownership validation does not apply to symbols, which are never apiPaths. typescript.mjs — writeTransformedToCache hashed originalPath exactly as passed. A relative path made the content-hash — and therefore the cache file's file:// URL and Node's ESM module identity — depend on process.cwd(), so the same source referenced from two CWDs cached twice and resolved to two distinct module instances. findPackageRoot already resolved internally; the hash was the one remaining CWD-dependent input. Fixed by resolving originalPath to an absolute path once and using it for both findPackageRoot and the hash. Copilot's diagnosis and suggested fixes for all three items were accurate. Tests: a writeSymbolKey fixture in the api_test_self_assign owner module and a new self-assign-symbol-key suite exercise the symbol fast-path under both the live and async runtimes; a new case in typescript-cache-key-collision asserts a relative and an absolute reference to the same source share one cache file.
The async context proxy's set trap has a defensive guard, if (!ctx || !ctx.context) { throw RUNTIME_NO_ACTIVE_CONTEXT_CONTEXT }, for the no-active-context case. This adds a behavior test for it (writing to context outside an ALS context throws).
v8's parallel-worker coverage merge miscounts this if (...) { throw }: the throw consequent and the if-evaluation receive inconsistent hit counts across workers, so the v8-to-istanbul synthetic else-arm resolves to a phantom -1. The text/summary reporter counts that as an uncovered branch, holding the suite at 99.97% even though statement coverage confirms both arms execute.
The guard is annotated /* v8 ignore next 3 */, mirroring the already-ignored self set-trap guard a few lines above in the same file. The self and context set-trap guards are the same defensive pattern; only the self one had been ignored. This is the consistency fix, not a coverage workaround.
Shinrai
approved these changes
May 18, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
🚀 What's Changed
💥 Breaking Changes
No breaking changes
✨ Features
🐛 Bug Fixes
self.X = …instead of silently dropping it (385ed1e)🔧 Other Changes
👥 Contributors
Avg: 100.0% ·
e1b27bb· Node lts/*