Repository navigation
feat(lifecycle): add stackRoutines, decoupled entirely from collisionMode (#365) - #366
Conversation
…cWrapper reads their child keys syncWrapper() decided whether a colliding key already existed on the existing side via Object.prototype.hasOwnProperty against Object.keys(existingWrapper) — which, for an untouched lazy wrapper, reflects only what's been materialized so far, not its full eventual key set. An api.slothlet.api.add() collision against a same-named sibling that had never been touched therefore took the "key doesn't exist yet" fast path (a bare Object.defineProperty) and installed the incoming value directly, without ever reading or materializing the existing module — so its file was never even loaded, its lifecycle events never fired, and "merge" mode's documented "keep existing" contract was silently violated with no way to recover the discarded module afterward. Force-materializing both the existing and incoming wrapper (mirroring setValueAtPath's identical parent-materialization guard) before computing existingChildKeys/nextChildKeys makes every collision mode's existing/already-there check accurate regardless of which side is still lazy. This also fixes replace mode's shadow-recording (_recordReplaceShadows), which reads the same incomplete key list. This is a core lazy-mode correctness defect independent of the stackable-routines feature (#341) that originally surfaced it — discovered while investigating why a routine contributor could be silently dropped on collision (see #362).
…ests it was masking (#367) Config#normalizeCollision only ever produces { initial, api }, but two independent call sites fed their config-driven collision-mode fallback "addApi" as collisionContext, which matches neither key: - src/lib/helpers/modes-utils.mjs's getOwnershipCollisionMode() - src/lib/builders/api-assignment.mjs's own identical inline fallback, which decides the REAL file-vs-folder merge outcome for a same-name collision within one module directory (not just ownership tracking) Both silently fell back to a hardcoded "merge" regardless of the instance's actually-configured collision.api default. Renamed to "api" at both source sites (api-manager.mjs's addApiComponent, api-cache-manager.mjs's reload rebuild). Root-caused via api-assignment.mjs: TEST_DIRS.API_TEST has a deliberate, already-documented file-vs-folder collision fixture (math.mjs vs math/, both exporting add) whose header comment says the root file wins "under default slothlet collision resolution". Under GENUINE replace mode — already directly tested and passing elsewhere (collision-config.test.vitest.mjs's "replace mode: should replace with last loaded (folder or file)") — the folder (loaded last) correctly wins instead. core-reload-selective.test.vitest.mjs configures collision: { api: "replace" } and uses this fixture throughout; its hardcoded +1000-offset expectations (1005/1002/1020/1006) were only ever correct because the addApi bug silently suppressed replace mode from ever reaching this decision point. The file's own "should reload base API module" test already independently documents and correctly expects the folder-wins outcome for the base module (unaffected by the addApi bug, since "initial" context was never mismatched) — confirming the +1000 expectations elsewhere in the same file were inconsistent with the author's own established intent, not a deliberate design choice. Updated to the correct plain-sum values and added the `await` genuine lazy-folder materialization requires. core-reload-path-multicache.test.vitest.mjs's "Child Caches Under Parent Path" block hit the same fixture via TEST_DIRS.API_TEST_COLLISIONS (math.mjs vs math/, non-overlapping exports) but its own assertions expect BOTH sides' exports to coexist ("math has all exports from both") — a merge, not replace, semantic; genuine replace mode discards the entire losing side, not just overlapping keys, which is incompatible with that expectation. Switched its config from replace to merge to match its own documented intent (nothing else in that block depends on replace specifically). Also had to extend modes-processor.mjs's ModesProcessor#resolveOwnershipCollisionMode (added in #365/#366): clamping was previously applied only to the per-call override, not to getOwnershipCollisionMode()'s own fallback result — once fixed, that fallback could ALSO now correctly resolve to "error"/"skip"/"warn" (previously impossible, since it always returned "merge"), reintroducing the exact "leaf-level registration throws mid-build" hazard the original clamp existed to prevent (rule-12-comprehensive.test.vitest.mjs regressed with an OWNERSHIP_CONFLICT error preempting the intended top-level "path already exists" error). Now clamps the fully-resolved value (override or fallback) uniformly to replace/merge-replace, defaulting everything else to merge. Also adds i18n-pack-resolution.test.vitest.mjs to SOLO_RUN_PATTERNS — it writes into node_modules/@cldmv/slothlet-i18n's own pack directory and races under full parallel workers (ENOENT / non-deterministic), passing cleanly in isolation; this is a shared-mutable-state test that belongs in the solo phase like the other entries already there, not a flaky test to shrug off. Full suite green: 382 files, 13,530 tests, 0 failures.
…ation can't be narrowed Addresses PR review feedback on the force-materialization added for #364: both narrowing options considered (skip for "replace", or derive keys from __childFilePathsPreMaterialize instead of materializing) are unsafe — every collision mode reaching syncWrapper needs accurate keys from both sides, and the metadata map only ever holds keys copied in from a prior merge step, not a lazy wrapper's own undiscovered children.
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical and moderate findings remain.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Adds stackRoutines as an independent lifecycle option while improving collision ownership, context propagation, and lazy materialization.
Changes:
- Adds ownership-aware routine stacking.
- Corrects collision handling and merge ownership tracking.
- Updates tests, documentation, generated API references, and fixtures.
File summaries
| File | Summary |
|---|---|
tests/vitests/suites/ownership/ownership-merge-current-owner.test.vitest.mjs |
Tests merge ownership precedence. |
tests/vitests/suites/lifecycle/routines.test.vitest.mjs |
Updates lifecycle routine coverage. |
tests/vitests/suites/lifecycle/routines-stack-flag.test.vitest.mjs |
Tests stackRoutines behavior. |
tests/vitests/suites/core/core-reload-selective.test.vitest.mjs |
Updates selective reload expectations. |
tests/vitests/suites/core/core-reload-path-multicache.test.vitest.mjs |
Covers reload collision semantics. |
tests/vitests/suites/api-manager/api-manager-lazy-collision-materialization.test.vitest.mjs |
Tests lazy collision materialization. |
tests/vitests/run-all-vitest.mjs |
Adjusts test orchestration. |
src/slothlet.mjs |
Documents the new option. |
src/lib/modes/eager.mjs |
Propagates eager collision overrides. |
src/lib/helpers/config.mjs |
Normalizes stackRoutines. |
src/lib/handlers/routine-manager.mjs |
Filters routine contributors by ownership. |
src/lib/handlers/ownership.mjs |
Tracks collision winners. |
src/lib/handlers/api-manager.mjs |
Handles API collision context and lazy materialization. |
src/lib/handlers/api-cache-manager.mjs |
Corrects reload collision context. |
src/lib/builders/modes-processor.mjs |
Resolves collision modes and ownership registration. |
src/lib/builders/builder.mjs |
Passes collision modes to builders. |
docs/LIFECYCLE.md |
Documents lifecycle stacking behavior. |
docs/generated/API.md |
Updates generated API documentation. |
docs/generated/api_tests/api_test_collisions.md |
Documents the collision fixture. |
docs/CONFIGURATION.md |
Documents configuration behavior. |
api_tests/api_test_collisions/lazybase/sub/test-func.mjs |
Adds a lazy collision fixture. |
Review details
Suppressed comments (6)
src/lib/builders/modes-processor.mjs:81
- Clamping
skip/warntomergehere does not discard the rejected contributor:processFiles()still callsownership.register()afterassignToApiPath()can skip a file/folder collision, andaddApiComponent()can later reject the mount atsetValueAtPath(). That leaves the skipped module in ownership/raw state; with the defaultstackRoutines: falseit can becomegetCurrentOwner()(especially when the instance default isskip/warn), and withstackRoutines: trueit is invoked even though its value never reached the live API. Only register/capture contributors after the collision is accepted, or roll back all ownership and routine state when the add is rejected.
#resolveOwnershipCollisionMode(collisionModeOverride, collisionContext) {
const resolved =
collisionModeOverride || this.slothlet.helpers.modesUtils.getOwnershipCollisionMode(this.slothlet.config, collisionContext);
return resolved === "replace" || resolved === "merge-replace" ? resolved : "merge";
src/lib/builders/modes-processor.mjs:1087
- This registration uses the per-call override, but the immediately preceding
assignToApiPath()for the same category only receivescollisionContextand derives its collision mode from config. ThusforceOverwrite: truecan make ownership reportreplacewhile an internal collision in the newly built API was composed withcollision.api(for examplemerge), causingstackRoutines: falseto select a function that is not live. Pass the same effective mode into the assignment path, or keep it out of both decisions.
collisionMode: this.#resolveOwnershipCollisionMode(collisionModeOverride, collisionContext),
src/lib/handlers/api-manager.mjs:1842
- Changing the outer runtime build to
collisionContext: "api"does not cover deferred lazy builds.createLazySubdirectoryWrapper()later callsprocessFiles()with"initial", and itsassignToApiPath()calls derive the collision mode from that context; whencollision.initialandcollision.apidiffer, file/folder or default/named-export collisions inside an API-added lazy subtree use the initial policy on first materialization. Propagate the API context (and per-call override) through lazy materialization as well.
collisionContext: "api",
src/lib/handlers/ownership.mjs:122
- This predicate only looks at the incoming value. If a live routine function collides with an incoming primitive under
merge, the composition path keeps the existing function, but this registration still pushes the primitive on top.#isCurrentOwner()then filters out the live routine as a loser whenstackRoutinesis false. Precedence needs to be derived from the actual merge outcome (including the existing value), not just `typeof value === "function".
const isMergeLeafLoser =
Boolean(currentOwner) && currentOwner.moduleID !== moduleID && collisionMode === "merge" && typeof value === "function";
src/lib/modes/eager.mjs:121
- The override is passed only to the root
processFiles()call. Its eager recursive calls atmodes-processor.mjs:1478,1497, and1530omit the positionalcollisionModeOverride, soapi.add(..., { forceOverwrite: true })can replace the live nested value while ownership for nested leaves is still registered with the configured mode. WithstackRoutines: false, routines can then invoke the old module even though the new implementation won the live collision. Thread this override through every recursive call.
collisionMode,
src/slothlet.mjs:1434
- The new option is absent from the committed public declaration:
types/index.d.mtsimportsSlothletOptionsfromtypes/src/slothlet.d.mts, whereautoRoutinesis immediately followed bytracking. TypeScript consumers using the documentedstackRoutinesoption will therefore get an excess-property error. Regenerate and commit the declarations (and source map) with this property.
* @property {boolean} [stackRoutines=false] - Whether two or more modules' contributions colliding at the exact same composed api path all run, or only the single contribution that actually owns that path (per `collisionMode`) runs (#365). `false` by default, matching ordinary (non-routine) collision behavior everywhere else in the framework. Deliberately independent of `collisionMode` — a module that loses a collision, under any mode, does not run via the routine system unless this is explicitly `true`. The root cascade is unaffected either way — it always runs every matching contribution anywhere in the tree, at their own distinct api paths; this only governs what happens when two or more contributions land on the identical path. See [LIFECYCLE.md](docs/LIFECYCLE.md#stackroutines).
- Files reviewed: 19/21 changed files
- Comments generated: 5
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
…ests it was masking (#367) Config#normalizeCollision only ever produces { initial, api }, but two independent call sites fed their config-driven collision-mode fallback "addApi" as collisionContext, which matches neither key: - src/lib/helpers/modes-utils.mjs's getOwnershipCollisionMode() - src/lib/builders/api-assignment.mjs's own identical inline fallback, which decides the REAL file-vs-folder merge outcome for a same-name collision within one module directory (not just ownership tracking) Both silently fell back to a hardcoded "merge" regardless of the instance's actually-configured collision.api default. Renamed to "api" at both source sites (api-manager.mjs's addApiComponent, api-cache-manager.mjs's reload rebuild). Root-caused via api-assignment.mjs: TEST_DIRS.API_TEST has a deliberate, already-documented file-vs-folder collision fixture (math.mjs vs math/, both exporting add) whose header comment says the root file wins "under default slothlet collision resolution". Under GENUINE replace mode — already directly tested and passing elsewhere (collision-config.test.vitest.mjs's "replace mode: should replace with last loaded (folder or file)") — the folder (loaded last) correctly wins instead. core-reload-selective.test.vitest.mjs configures collision: { api: "replace" } and uses this fixture throughout; its hardcoded +1000-offset expectations (1005/1002/1020/1006) were only ever correct because the addApi bug silently suppressed replace mode from ever reaching this decision point. The file's own "should reload base API module" test already independently documents and correctly expects the folder-wins outcome for the base module (unaffected by the addApi bug, since "initial" context was never mismatched) — confirming the +1000 expectations elsewhere in the same file were inconsistent with the author's own established intent, not a deliberate design choice. Updated to the correct plain-sum values and added the `await` genuine lazy-folder materialization requires. core-reload-path-multicache.test.vitest.mjs's "Child Caches Under Parent Path" block hit the same fixture via TEST_DIRS.API_TEST_COLLISIONS (math.mjs vs math/, non-overlapping exports) but its own assertions expect BOTH sides' exports to coexist ("math has all exports from both") — a merge, not replace, semantic; genuine replace mode discards the entire losing side, not just overlapping keys, which is incompatible with that expectation. Switched its config from replace to merge to match its own documented intent (nothing else in that block depends on replace specifically). Also had to extend modes-processor.mjs's ModesProcessor#resolveOwnershipCollisionMode (added in #365/#366): clamping was previously applied only to the per-call override, not to getOwnershipCollisionMode()'s own fallback result — once fixed, that fallback could ALSO now correctly resolve to "error"/"skip"/"warn" (previously impossible, since it always returned "merge"), reintroducing the exact "leaf-level registration throws mid-build" hazard the original clamp existed to prevent (rule-12-comprehensive.test.vitest.mjs regressed with an OWNERSHIP_CONFLICT error preempting the intended top-level "path already exists" error). Now clamps the fully-resolved value (override or fallback) uniformly to replace/merge-replace, defaulting everything else to merge. Also adds i18n-pack-resolution.test.vitest.mjs to SOLO_RUN_PATTERNS — it writes into node_modules/@cldmv/slothlet-i18n's own pack directory and races under full parallel workers (ENOENT / non-deterministic), passing cleanly in isolation; this is a shared-mutable-state test that belongs in the solo phase like the other entries already there, not a flaky test to shrug off. Full suite green: 382 files, 13,530 tests, 0 failures.
cf2e793 to
408ee30
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved moderate issues remain in collision propagation, ownership tracking, public typing, and documentation.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (11)
docs/CONFIGURATION.md:474
- This configuration guide repeats that the root cascade is unaffected by
stackRoutines, butrunCascade()filters same-path entries through#contributorsFor()when the flag isfalse. A contributor that loses a same-path collision will not run in that cascade; only contributions at distinct paths remain unaffected. Please correct this statement to match the runtime behavior.
Deliberately independent of `collisionMode`: stacking is not a side effect of `merge`, `replace`, or any other mode — a module that loses a collision, under any collision mode, does not run via the routine system unless `stackRoutines: true` is set. The root cascade is unaffected either way — it always runs every matching contribution at its own distinct api path; this only governs what happens when two or more contributions land on the identical path.
docs/LIFECYCLE.md:446
- The implementation now sends
runCascade()through#contributorsFor(), which applies the same-path ownership filter, and the new regression test expects a collided loser to be omitted from the root cascade by default. This sentence says the root cascade is unaffected and always runs every matching contribution, which contradicts that behavior and can mislead users aboutstackRoutines. Clarify that contributors at distinct paths are always included, while identical-path groups use the ownership/stack filter.
The root cascade (`self.<name>()` / `api.slothlet.<name>()`) is unaffected by this flag either way — it always runs every matching contribution anywhere in the tree, at their own distinct api paths; `stackRoutines` only governs what happens when two or more contributions land on the identical path.
src/lib/builders/builder.mjs:196
- The new override is passed only to the root
processFiles()call. The eager transparent/regular recursive calls (modes-processor.mjs:1478-1511) and the lazy transparent call (:1530-1543) omit the finalcollisionModeOverrideargument, so nested leaves fromapi.add(..., { forceOverwrite: true })fall back to the instance config while root leaves usereplace. That leaves ownership precedence inconsistent within one mounted module; thread the override through every recursive call.
collisionMode,
src/lib/builders/modes-processor.mjs:446
- The per-call override is used for the ownership entry here, but the actual eager file/folder composition still derives
modes_eagerCollisionModefromconfigand callsassignToApiPath()withoutcollisionModeOverride(modes-processor.mjs:1350-1446). For example, anapi.add()withforceOverwrite: truecan record the incoming leaf as areplacewinner while the eager module's internal file/folder collision was merged usingcollision.api, making ownership disagree with the live tree.
collisionMode: this.#resolveOwnershipCollisionMode(collisionModeOverride, collisionContext),
src/lib/builders/modes-processor.mjs:74
- The
collisionContextcontract here includes runtime"api", but lazy subdirectory materialization still callsprocessFileswith a hard-coded"initial"context. Thus a wrapper created byapi.add()can resolve nested collisions withconfig.collision.initialinstead ofconfig.collision.apiwhen those defaults differ. Preserve the originating context in the lazy wrapper and use it during materialization.
* @param {string} collisionContext - `"initial"` or `"api"`.
src/lib/handlers/api-manager.mjs:1859
- Changing the add path to the normalized
"api"context does not reach lazy descendants:createLazySubdirectoryWrapper()invokes its materializationprocessFiles()with hard-coded"initial"(modes-processor.mjs:1974). Whencollision.initialandcollision.apidiffer, a nested file/folder collision in a lazyapi.add()is therefore composed using the initial policy while the mount was registered using the API policy, so the live winner and ownership can disagree. Preserve the originating collision context in the lazy materializer.
collisionContext: "api",
src/lib/handlers/ownership.mjs:122
- This predicate is reversed for function/namespace merges.
api-assignment.mjskeeps the existing wrapper only when it is callable; when the existing value is a namespace and the incoming value is callable, the incoming wrapper is explicitly installed. Conversely, an existing callable must remain current when the incoming value is an object. Checking onlytypeof value === "function"therefore produces the wrong current owner in one of these two orders, causing the default routine filter to suppress the callable that is actually live.
const isMergeLeafLoser =
Boolean(currentOwner) && currentOwner.moduleID !== moduleID && collisionMode === "merge" && typeof value === "function";
src/lib/handlers/ownership.mjs:196
api.add()allows a per-callcollisionModeto override the normalized instance mode, so the genericimpl:createdregistration can put an incoming function on top using (for example)replacewhile the later authoritative registration carriesmerge. This correction handles onlyreplace/merge-replace, leaving that incoming function as the current owner even though merge keeps the existing value;stackRoutines: falsethen invokes the wrong contributor. The duplicate-registration path also needs to restore merge ordering when the authoritative mode ismerge.
if ((collisionMode === "replace" || collisionMode === "merge-replace") && typeof existingEntry.value === "function") {
const index = stack.indexOf(existingEntry);
if (index !== -1 && index !== stack.length - 1) {
stack.splice(index, 1);
stack.push(existingEntry);
}
src/lib/helpers/config.mjs:632
- The runtime normalizer adds
stackRoutines, but the package's public declaration attypes/src/slothlet.d.mtsstill hasroutinesandautoRoutineswith nostackRoutinesproperty. Becausepackage.jsonexports that file as thetypesentry, TypeScript consumers cannot pass the new option without an excess-property error. Add the option to the declaration and regenerate the corresponding declaration output.
stackRoutines: config.stackRoutines === true,
src/slothlet.mjs:1434
- This new API documentation says the root cascade is unaffected by
stackRoutines, butrunCascade()obtains entries through#contributorsFor(), which applies the same ownership filter used by direct path calls. WithstackRoutines: false, a same-path loser is therefore excluded from the root cascade; only contributors at distinct paths are always retained. Update this statement and the generated declaration/docs to match the implementation.
* @property {boolean} [stackRoutines=false] - Whether two or more modules' contributions colliding at the exact same composed api path all run, or only the single contribution that actually owns that path (per `collisionMode`) runs (#365). `false` by default, matching ordinary (non-routine) collision behavior everywhere else in the framework. Deliberately independent of `collisionMode` — a module that loses a collision, under any mode, does not run via the routine system unless this is explicitly `true`. The root cascade is unaffected either way — it always runs every matching contribution anywhere in the tree, at their own distinct api paths; this only governs what happens when two or more contributions land on the identical path. See [LIFECYCLE.md](docs/LIFECYCLE.md#stackroutines).
src/slothlet.mjs:1434
- This documents
stackRoutinesin the runtime JSDoc, but the shippedSlothletOptionsdeclaration intypes/src/slothlet.d.mtsstill has nostackRoutinesproperty. Becausetypes/index.d.mtsexposes that declaration, TypeScript consumers configuring the new option can receive an excess-property error. Add the option to the public declaration and regenerate any derived type docs.
* @property {boolean} [stackRoutines=false] - Whether two or more modules' contributions colliding at the exact same composed api path all run, or only the single contribution that actually owns that path (per `collisionMode`) runs (#365). `false` by default, matching ordinary (non-routine) collision behavior everywhere else in the framework. Deliberately independent of `collisionMode` — a module that loses a collision, under any mode, does not run via the routine system unless this is explicitly `true`. The root cascade is unaffected either way — it always runs every matching contribution anywhere in the tree, at their own distinct api paths; this only governs what happens when two or more contributions land on the identical path. See [LIFECYCLE.md](docs/LIFECYCLE.md#stackroutines).
- Files reviewed: 19/21 changed files
- Comments generated: 2
- Review effort level: Lite
…able impl as unmaterialized A lazy wrapper whose real content is itself a function (e.g. a self-named single-file folder) had its state.materialized flag wrongly reset to false right after legitimately materializing, because the check used `typeof impl !== "function"` as a materialized signal. A later access would then re-run the materializer, double-firing _onWrapperMaterialized() and corrupting the global unmaterialized-lazy-wrapper count. Only "impl is still null/undefined" means unmaterialized; a callable impl is exactly as materialized as any other content type. Surfaced by PR #364 review; new regression fixture api_tests/api_test_collisions/lazyfuncbase/sub/sub.mjs and test.
… last-registered register() always pushed a newly-allowed collision entry onto pathToModule's stack, and getCurrentOwner()/getCurrentValue()/ownsPath() all read the stack's top — last-registered-wins. Correct for replace/merge-replace (the incoming module does win the real composed tree under those modes), but wrong for a leaf (function) "merge" collision: merge mode's real tree composition (syncWrapper()) keeps the EXISTING function at a colliding leaf, never the incoming one, so ownership's "current owner" disagreed with what's actually live for every leaf merge collision. Scoped deliberately to `typeof value === "function"`: a container/ namespace merge (two modules' namespaces combining their distinct children under the same path) has no single winner to prefer — both genuinely coexist as children — so last-registered-wins stays correct there and is left untouched (verified against api-manager-remove-ownership-restore's restore-to-first-owner container-merge scenario, which regressed under an earlier, unscoped version of this fix and is now green again). Part of #365 (finding 2): a standing gap independent of the stackable- routines feature and of laziness — it predates both.
…Mode (#365) Routine contributor stacking at a shared api path was an implicit side effect of raw impl:created event capture, independent of what collision resolution actually decided — any collision, under ANY collisionMode (replace, skip, error, ...), caused every raw contributor to run via the routine system regardless of which one actually won on the real composed tree. Nothing before #341 ever stacked functions at a shared api path; #341 should not have made that automatic/implicit either. Adds `stackRoutines` (boolean, default false, independent of collisionMode) as its own explicit opt-in. RoutineManager now narrows to whichever contributor is ownership's currently-recognized owner of an exact api path unless stackRoutines is true, in both #contributorsFor (routine matching / rebuildStacks groups) and runPath (the installed stacked callable's own direct lookup, a separate this.raw read that bypassed #matches entirely). This surfaced and required three supporting fixes to make ownership accurate enough to narrow correctly: - OwnershipManager#register(): a genuine LEAF (function) "merge" collision now keeps the EXISTING module as current owner (matching what syncWrapper's real tree composition already does), not the last-registered one — scoped to functions only; a container/ namespace merge has no single winner and is left untouched. - OwnershipManager#register(): a later, more-authoritative registration for the same (moduleID, apiPath) pair (e.g. modes-processor's own collisionMode-aware registration, arriving after the framework's generic impl:created listener already registered it with the instance's default mode) can now correct an earlier call's stack position for "replace"/"merge-replace". - modes-processor.mjs: per-leaf ownership.register() calls now prefer the real per-call collisionMode override (e.g. from api.add()'s forceOverwrite) over the instance-default config fallback, scoped to "replace"/"merge-replace" only — "error"/"skip"/"warn" are deliberately left alone so a leaf-level rejection can't abort a build partway through with some leaves already registered; the existing top-level setValueAtPath check already rejects those collisions cleanly, once, before anything is merged into the live tree. A related "addApi" vs "api" collisionContext string mismatch in getOwnershipCollisionMode()'s config lookup was found but NOT fixed — changing it broke reload/replace-mode scenarios elsewhere in a way not yet root-caused; left as-is with a note for follow-up. Existing #341 tests that relied on the old implicit stacking now pass stackRoutines: true explicitly. Full suite green (13,474+ tests, excluding two confirmed pre-existing flakes unrelated to this change: i18n-pack-resolution's node_modules pack-staging race, and api-manager-reload-coverage under full-suite memory pressure — both pass cleanly in isolation).
…ests it was masking (#367) Config#normalizeCollision only ever produces { initial, api }, but two independent call sites fed their config-driven collision-mode fallback "addApi" as collisionContext, which matches neither key: - src/lib/helpers/modes-utils.mjs's getOwnershipCollisionMode() - src/lib/builders/api-assignment.mjs's own identical inline fallback, which decides the REAL file-vs-folder merge outcome for a same-name collision within one module directory (not just ownership tracking) Both silently fell back to a hardcoded "merge" regardless of the instance's actually-configured collision.api default. Renamed to "api" at both source sites (api-manager.mjs's addApiComponent, api-cache-manager.mjs's reload rebuild). Root-caused via api-assignment.mjs: TEST_DIRS.API_TEST has a deliberate, already-documented file-vs-folder collision fixture (math.mjs vs math/, both exporting add) whose header comment says the root file wins "under default slothlet collision resolution". Under GENUINE replace mode — already directly tested and passing elsewhere (collision-config.test.vitest.mjs's "replace mode: should replace with last loaded (folder or file)") — the folder (loaded last) correctly wins instead. core-reload-selective.test.vitest.mjs configures collision: { api: "replace" } and uses this fixture throughout; its hardcoded +1000-offset expectations (1005/1002/1020/1006) were only ever correct because the addApi bug silently suppressed replace mode from ever reaching this decision point. The file's own "should reload base API module" test already independently documents and correctly expects the folder-wins outcome for the base module (unaffected by the addApi bug, since "initial" context was never mismatched) — confirming the +1000 expectations elsewhere in the same file were inconsistent with the author's own established intent, not a deliberate design choice. Updated to the correct plain-sum values and added the `await` genuine lazy-folder materialization requires. core-reload-path-multicache.test.vitest.mjs's "Child Caches Under Parent Path" block hit the same fixture via TEST_DIRS.API_TEST_COLLISIONS (math.mjs vs math/, non-overlapping exports) but its own assertions expect BOTH sides' exports to coexist ("math has all exports from both") — a merge, not replace, semantic; genuine replace mode discards the entire losing side, not just overlapping keys, which is incompatible with that expectation. Switched its config from replace to merge to match its own documented intent (nothing else in that block depends on replace specifically). Also had to extend modes-processor.mjs's ModesProcessor#resolveOwnershipCollisionMode (added in #365/#366): clamping was previously applied only to the per-call override, not to getOwnershipCollisionMode()'s own fallback result — once fixed, that fallback could ALSO now correctly resolve to "error"/"skip"/"warn" (previously impossible, since it always returned "merge"), reintroducing the exact "leaf-level registration throws mid-build" hazard the original clamp existed to prevent (rule-12-comprehensive.test.vitest.mjs regressed with an OWNERSHIP_CONFLICT error preempting the intended top-level "path already exists" error). Now clamps the fully-resolved value (override or fallback) uniformly to replace/merge-replace, defaulting everything else to merge. Also adds i18n-pack-resolution.test.vitest.mjs to SOLO_RUN_PATTERNS — it writes into node_modules/@cldmv/slothlet-i18n's own pack directory and races under full parallel workers (ENOENT / non-deterministic), passing cleanly in isolation; this is a shared-mutable-state test that belongs in the solo phase like the other entries already there, not a flaky test to shrug off. Full suite green: 382 files, 13,530 tests, 0 failures.
…ther source changes types/src/slothlet.d.mts (and the other declaration files for files this PR touches) were stale: stackRoutines was documented in src/slothlet.mjs's JSDoc but absent from the committed public declaration, so TypeScript consumers configuring the new option would get an excess-property error. Regenerated via `npm run build:types` and scoped to only the declaration files whose source this PR actually changed — reverted unrelated regen drift in files this PR didn't touch (that's a version-bump-time concern, not this PR's).
…isionContext into nested/lazy processing Two gaps in ownership bookkeeping for api.add()'s per-call collision-mode override, both flagged in PR #366 review: - processFiles()'s three recursive subdirectory calls dropped collisionModeOverride entirely, so only the top level of a mounted tree respected an api.add({forceOverwrite: true})-style override; every nested leaf silently fell back to the instance's configured default for its ownership registration. - createLazySubdirectoryWrapper() hardcoded "initial" as the collision context its later materialization resolves internal collisions with, regardless of whether the lazy subtree was actually mounted via api.add() (collision context "api"). A repo whose collision.initial and collision.api defaults differ would silently use the wrong one once the subtree materialized. Both are ownership/registration-bookkeeping fixes — the live composed api tree's actual values were already correct; what could disagree was which mode/context ownership recorded for stackRoutines' current-owner checks. Full modes-processor/collision/lazy/ownership/routine regression suite (67 files, 2452 tests) green.
408ee30 to
9183ee4
Compare
|
Addressing the suppressed-comment findings across both reviews (5179696002, 5181071251). No thread ids exist for these (suppressed, not posted threads), so responding here. Fixed in
Fixed in
Not a bug — docs are accurate as written: Needs a design decision, not fixed here (three related gaps in the new
Flagging these three to the PR author for a decision on scope (fix now vs. track as a follow-up) rather than guessing. |
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical and moderate findings affect async materialization, collision propagation, ownership ordering, and routine filtering.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (7)
api_tests/api_test_collisions/lazyfuncbase/sub/sub.mjs:20
- This new documented fixture is absent from
docs/generated/api_tests/api_test_collisions.md, while the neighboringlazybasefixture is listed there. Since this file adds@module/@memberofdocumentation and the generated API artifact is committed, regenerate or update that artifact so the newlazyfuncbase.subsurface is not missing from the published fixture docs.
* @module api_test_collisions.lazyfuncbase.sub
* @memberof module:api_test_collisions.lazyfuncbase
docs/LIFECYCLE.md:446
- The implementation applies the
stackRoutinesownership filter before grouping contributors for the root cascade, so an exact-path loser is omitted when the flag is false and included when it is true. This statement says the root cascade is unaffected and always runs every contribution, which contradicts that behavior and the collision test coverage. Clarify that only contributions at distinct paths are unaffected; identical-path collisions follow the same flag.
The root cascade (`self.<name>()` / `api.slothlet.<name>()`) is unaffected by this flag either way — it always runs every matching contribution anywhere in the tree, at their own distinct api paths; `stackRoutines` only governs what happens when two or more contributions land on the identical path.
src/lib/builders/modes-processor.mjs:81
#resolveOwnershipCollisionMode()turnsskip/warn(and every other non-replace mode) intomerge, but the real collision has already rejected the incoming path. The genericimpl:createdownership registration therefore returns null, then the later explicit registration records the skipped/warned module and makes it current; withstackRoutines: false, a skipped/warned routine can run even though its value is absent from the API. Keep those modes out of ownership (or preserve them soregister()rejects them) instead of coercing them tomerge.
return resolved === "replace" || resolved === "merge-replace" ? resolved : "merge";
src/lib/builders/modes-processor.mjs:1628
modes_initialCollisionModehonors the per-call override, but thisassignToApiPathcall does not receive it, and the assignment helper currently resolves collision detection fromconfig.collision[collisionContext]. Thus a directory containing a file/folder collision added withforceOverwrite: truecan still be merged undercollision.api: "merge", sonewApialready has the wrong winner beforesetValueAtPathapplies replace. Thread the override through every collision-detecting assignment and make the assignment helper honor it.
{
useCollisionDetection: true,
config: this.slothlet.config,
collisionContext
}
src/lib/handlers/api-manager.mjs:894
- This new check regresses valid
null(andundefined) exports.syncWrapper()has just force-materialized both wrappers, andUnifiedWrapper._materialize()marks a legitimate null export as materialized even though__impl === null; this assignment resets that state to false, so the next access rematerializes the wrapper and can double-fire materialization/lifecycle bookkeeping. Preserve the materialized state or use a separate unmaterialized sentinel instead of treating null/undefined as absence.
const hasImpl = existingWrapper.____slothletInternal.impl !== null && existingWrapper.____slothletInternal.impl !== undefined;
src/lib/handlers/ownership.mjs:191
- The first
impl:createdregistration usesconfig.collision.apibefore this context-aware duplicate registration runs. With{ initial: "merge", api: "replace" }, a second initial module is first pushed as replace, then this later merge registration leaves it on top because only replace modes trigger repositioning; the live merge tree still keeps the existing function.getCurrentOwner()and default routine filtering consequently select the wrong contributor. The duplicate correction must also handle the resolved merge mode, or the initial listener must receive the originating context.
if ((collisionMode === "replace" || collisionMode === "merge-replace") && typeof existingEntry.value === "function") {
src/lib/handlers/routine-manager.mjs:228
- When
stackRoutinesis true this returns every historicalrawentry, even when ownership has since removed that module. Removing a merge loser does not emitimpl:removedbecause it was never the live property, so its raw contribution remains and the existing stacked callable/root cascade can continue invoking the removed module. Filter enabled-mode entries byownership.getPathOwnership(entry.apiPath)so only current co-owners are retained.
if (this.slothlet.config?.stackRoutines) return entries;
return entries.filter((entry) => this.#isCurrentOwner(entry));
- Files reviewed: 28/39 changed files
- Comments generated: 4
- Review effort level: Lite
…ollisionModeOverride into assignToApiPath Two more findings from PR #366's review, against commit 9183ee4: - syncWrapper's final bookkeeping still inferred existingWrapper's materialized state from its impl's content/type. The earlier #364-review fix corrected this for a callable impl but the same class of bug applied to any other falsy-by-check impl (e.g. a legitimate null/undefined export) — the underlying flaw was re-deriving "materialized" from content at all. Replaced with an explicit flag set only in the one branch that genuinely needs existingWrapper marked unmaterialized (impl explicitly cleared to null, pending a future re-materialization); every other path now keeps whatever _materialize()/___setImpl() already correctly set. New regression test + api_tests/api_test_collisions/lazynullbase fixture (a self-named single-file lazy folder whose export is null). - assignToApiPath()'s collision-detection branch derived its mode purely from config.collision[collisionContext], ignoring any per-call override (api.add()'s forceOverwrite). modes-processor.mjs's lazy-subdirectory file/folder-collision call site already resolved the correct override-aware mode (modes_initialCollisionMode) for its OWN ownership registration and the lazy wrapper's later materialization, but never passed it to this assignToApiPath call — so the actual composed value for an internal collision inside a forceOverwrite-mounted directory could disagree with the mount's own top-level decision. Added a collisionModeOverride option to assignToApiPath, threaded through. Regression: 116 files / 4221 tests green across both rounds.
…via the tree revertSpeculativeState() (the state-only variant buildAPI()'s outer catch uses when there's no concrete api-tree reference left to walk) restored/dropped raw fn entries but never invalidated the wrappers those speculative entries came from. A candidate build that constructs several wrappers before an unrelated later failure aborts the whole attempt left every already-materializing wrapper free to re-apply its result after the rollback. Track each raw entry's originating UnifiedWrapper (resolved from impl:created's first per-construction emit, keyed by moduleID:apiPath) in a new rawWrappers map, and invalidate the wrapper for any path whose raw fn actually changed during the aborted build attempt.
…e existing owner is callable isMergeLoss only flagged the INCOMING side when both the incoming and existing values were functions. api-assignment.mjs's merge resolution has no branch that reassigns the slot to a plain object/namespace when the existing owner is already callable — the generic wrapper merge loop runs instead, merging the incoming object's children onto the existing callable and leaving that wrapper's own identity (and targetApi[key]) untouched. The incoming object registration was never flagged a loss in that shape, so #currentEntry()'s "last non-loss wins" scan handed callers the no-longer-live namespace instead of the still-live callable.
…ontained export needs hasUnshippableReference() warned about #-prefixed internal references in self-contained type stubs but never actually resolved them: the package's own imports map already points the production types condition for #factories/*/#handlers/* at types/stub/lib/<dir>/*.d.mts, but this generator never wrote those files, so a consumer importing e.g. @cldmv/slothlet/modes/eager (which imports #factories/component-base) hit a real TS2307. Comment-strip declaration text before scanning it for references (two of the warning's 15 hits were plain prose inside @example/JSDoc blocks matching the same regex, not real imports) and recursively emit a self-contained stub for every #factories/*/#handlers/* target a self-contained stub transitively references, so the imports map resolves to a real file. Only a genuine relative (./,../) reference, or a #-prefixed one with no source file on disk, still warns. Extends tests/validate-typestubs.mjs to type-check ./modes/eager under the production condition, proving the closure resolves.
|
Addressing the 4 suppressed findings from the review at
All four verified red-then-green against a temporary revert of each fix, plus the full builders/handlers/ownership/config/api-manager/unified-wrapper suites (70+ files, 2260+ tests) and both type-stub validators ( Requesting a fresh review. |
There was a problem hiding this comment.
🟡 Changes recommended
Critical ownership and overlapping routine-stack issues, plus a moderate wrapper-retention issue, remain unresolved.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (1)
src/lib/handlers/routine-manager.mjs:472
- This rollback removes the raw entry but leaves the rejected wrapper in
rawWrappers. Each rejectedapi.add()can use a fresh auto-generated module ID, so repeated skip/warn rejections retain invalidated wrappers (and their Slothlet references) indefinitely in this strongMap, causing unbounded memory growth. Remove the correspondingrawWrapperskey as part of this rollback.
} else if (idx !== -1) {
this.raw.splice(idx, 1);
}
- Files reviewed: 64/76 changed files
- Comments generated: 2
- Review effort level: Lite
…gistration too #assignWithRoutineRevert only reverted RoutineManager's speculative raw capture. Wrapper construction fires impl:created unconditionally, and the generic subscriber in src/slothlet.mjs reacts by registering ownership using the instance's default mode, clamped to "replace"/"merge-replace" only — so that registration always succeeds even when assignToApiPath() is about to reject the same candidate as skip/warn, or a later throw aborts it outright. Confirmed concretely: on a shared-moduleID skip collision, the winning entry's filePath/value got overwritten by the rejected candidate's, even though the live tree's value was correct. OwnershipManager gets a single-pair snapshotPathEntry(), reusing the existing restoreEntry()/removePath() primitives, wired into #assignWithRoutineRevert alongside the existing RoutineManager revert.
|
Fixed in |
There was a problem hiding this comment.
🟡 Changes recommended
One critical, six moderate, and one nit finding remain unresolved.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (6)
src/lib/handlers/api-manager.mjs:2926
- The path-form
api.remove()deletes the entire subtree, but this callback only prunes the exact(normalizedPath, moduleID)entry. Descendant routine captures such asauth.initializetherefore remain inRoutineManager.raw; the rebuild added after every removal then continues to include them in the root cascade whenstackRoutinesis enabled, even though their subtree was removed. Prune all raw entries (and wrapper bookkeeping) whose paths are at or below the removed path before rebuilding.
this.slothlet.handlers.routineManager?.onImplRemoved?.({ apiPath: normalizedPath, moduleID: moduleIDKey });
src/lib/handlers/api-manager.mjs:1008
- This invalidates the candidate wrapper before walking its children.
UnifiedWrapper#___invalidate()deletes the wrapper's child properties but does not invalidate those child wrappers, soObject.entries(api)is then empty and nested in-flight lazy/background materializations remain live. When one completes it can emitimpl:changedand repopulateRoutineManager.rawfor a candidate that was rejected; traverse the raw wrapper's children first (or make invalidation recursive), then invalidate the parent.
resolveWrapper(api)?.___invalidate();
for (const [key, value] of Object.entries(api)) {
const skipProps = ["__metadata", "__type", "_materialize", "_impl", "____slothletInternal"];
if (skipProps.includes(key)) continue;
src/lib/handlers/routine-manager.mjs:398
- This removes the wrapper references from
rawWrapperswithout invalidating the wrappers themselves. A removed merge-loser is not present in the live API tree, sodeletePath()cannot invalidate its detached lazy wrapper; if background materialization is already in flight, it can still emitimpl:changedafter this prune andonImplCreated()will recapture the removed module intoraw, makingstackRoutines: trueinvoke it again. Invalidate each removed module wrapper before dropping the map entry, while handling shared container wrappers safely.
pruneModule(moduleID) {
this.raw = this.raw.filter((e) => e.moduleID !== moduleID);
const prefix = `${moduleID}:`;
for (const key of this.rawWrappers.keys()) {
if (key.startsWith(prefix)) this.rawWrappers.delete(key);
}
src/lib/handlers/routine-manager.mjs:607
- When a prior
(apiPath, moduleID)contribution was deleted during the candidate build, this restoration appends it rather than putting it back at its original position.raworder is the documented registration/mount order used bystackRoutines: true; a re-add/rollback such asA, Bwhere A is temporarily re-touched as non-function restores the sequence asB, A, changing which contributor runs first. Snapshot the original raw index (or otherwise preserve ordering) and restore at that position.
if (prior) {
const idx = this.raw.findIndex((e) => e.apiPath === path && e.moduleID === moduleID);
if (idx !== -1) this.raw[idx] = { apiPath: path, moduleID, fn: prior };
else this.raw.push({ apiPath: path, moduleID, fn: prior });
src/lib/handlers/routine-manager.mjs:470
- This single-path rollback has the same ordering loss as the module rollback below: when the candidate deleted the prior raw entry,
push()moves that contribution to the end of the global registration sequence. WithstackRoutines: true, a rejected internal re-touch can therefore change contributor execution order even though the candidate never mounted. Preserve the prior entry's array index in the snapshot and restore it in place.
revertRawEntry(apiPath, moduleID, priorFn) {
const idx = this.raw.findIndex((e) => e.apiPath === apiPath && e.moduleID === moduleID);
if (priorFn !== undefined) {
if (idx !== -1) this.raw[idx] = { apiPath, moduleID, fn: priorFn };
else this.raw.push({ apiPath, moduleID, fn: priorFn });
} else if (idx !== -1) {
src/lib/handlers/routine-manager.mjs:524
- When the candidate's non-function re-touch removed an existing raw entry, this fallback also appends the restored contribution and loses its original registration position. That changes
stackRoutinesexecution order after a rejected subtree build; restoring the function value is not sufficient. Carry the original array index inpriorEntriesand splice the entry back into that slot.
// Only updating an EXISTING entry silently no-ops here, leaving the prior, genuinely
// pre-candidate contribution unrestored even though this revert path was reached
// specifically to bring it back (#372 review, suppressed finding).
if (idx !== -1) this.raw[idx] = { apiPath: revertPath, moduleID, fn: prior };
else this.raw.push({ apiPath: revertPath, moduleID, fn: prior });
- Files reviewed: 64/76 changed files
- Comments generated: 1
- Review effort level: Lite
…subtree cleanup Four related gaps surfaced by the same review round: - revertRawEntry/revertSpeculativeSubtree/revertSpeculativeState restored a deleted raw entry via push(), moving it to the end of the array instead of its original registration position — silently reordering stackRoutines: true's execution order after a rejected re-touch. snapshotRawEntry/snapshotRawEntries now also capture each entry's index, and restore re-inserts at that position via splice(). - invalidateSpeculativeWrappers() invalidated the parent wrapper BEFORE walking its children, but ___invalidate() deletes a wrapper's own child properties as part of invalidating it — so the recursive walk then found nothing to enumerate and never reached a single nested wrapper. Reordered to walk children first, invalidate the parent last. - pruneModule() dropped rawWrappers entries without invalidating them first, leaking a merge-loser's wrapper (and any in-flight background materialization on it) indefinitely. - The scoped api.remove(apiPath, moduleID) deletes the whole live subtree, but impl:removed only ever fires for the exact path removed — descendant routine captures (e.g. "auth.initialize" under a removed "auth") survived in RoutineManager.raw indefinitely. New pruneSubtree(apiPath, moduleID) prunes the exact path and every descendant, wired into the scoped-removal "delete" branch.
|
Addressing the 6 suppressed findings from the review at
All four verified red→green with targeted tests. Full handlers/builders/ownership/config/lifecycle/api-manager/core suite (95 files, ~3017 tests) green. |
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical and moderate findings must be addressed before approval.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (1)
src/lib/builders/modes-processor.mjs:225
- This new
modes_effectiveCollisionModeis documented as applying to every internal collision, but the normalprocessModuleForAPI()call below does not receive it (it only passescollisionContextaround lines 499-508). As a result,api.add(..., { forceOverwrite: true })still uses the configured mode for a function default versus colliding named export and can retain the default property instead of replacing it. Thread this value into the flatten processor and use it for that collision decision, with a regression test for the function-default/named-export case.
// The effective per-call collision mode for every collision-detecting assignToApiPath() call
// this invocation makes: the caller's own override (e.g. api.add()'s forceOverwrite) when
// supplied, otherwise the context-appropriate config default. Threading the SAME resolved
// value into every call (not just one) keeps every internal collision within this module's
// own build agreeing with the mount's own top-level decision (#365/#366 review — see #373).
// Third || arm ("replace") unreachable — collision config always supplies an initial/api value.
/* v8 ignore next 2 */
const modes_effectiveCollisionMode =
collisionModeOverride ||
(collisionContext === "initial" ? this.slothlet.config.collision?.initial : this.slothlet.config.collision?.api) ||
"replace";
- Files reviewed: 64/76 changed files
- Comments generated: 1
- Review effort level: Lite
…ort merge
processModuleForAPI()'s function-default-vs-named-export collision
decision re-derived its mode straight from config.collision, ignoring
any per-call override (e.g. api.add({ forceOverwrite: true })) the
caller resolved. Every other collision decision in the same build
already prefers the override first; this was the one call chain
modes-processor.mjs never threaded it into, since the decision itself
lives in a separate file (processors/flatten.mjs).
|
Addressing the suppressed finding from the review at
Verified red→green with a targeted unit test. Processors/builders/config suite (24 files, 608 tests) green; the broader handlers/ownership/lifecycle/api-manager/core suite (95 files, ~3017 tests) verified green in the prior round and unaffected by this change (only |
There was a problem hiding this comment.
🟡 Changes recommended
One or more issues must be addressed before approval.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (6)
docs/LIFECYCLE.md:406
- The root cascade description says it runs every matching contribution anywhere, but the default
stackRoutines: falsefilters contributors that collide at the same exact path to the current owner, just like a direct call. Add that same-path qualification here; only distinct-path groups are unconditional, while all same-path contributors run together when stacking is enabled.
Slothlet also generates a **root cascade** for each configured routine — `self.<name>()`, mirrored at `api.slothlet.<name>()` (a dotted or `^`-prefixed name is reachable via bracket notation, e.g. `api.slothlet["admin.initialize"]`) — that runs every matching contribution anywhere, grouped by exact path, the groups ordered per the routine's `order`:
- **`order: "mount"`** (default for `startup`/`manual`) — groups run in first-appearance registration order.
src/lib/handlers/ownership.mjs:256
- This checks for any historical non-loss function, so an older winner can incorrectly demote the module that is currently live. For example,
Aregisters withmerge,Bsupersedes it withreplace, thenBis re-registered undermerge:Aremains non-loss, this setsB.isMergeLoss = true, andgetCurrentOwner()/non-stacked routines switch back toAeven thoughBis still the live value. Base the correction on the current non-loss entry (and only mark this entry a loss when that current entry belongs to another module).
existingEntry.isMergeLoss = stack.some(
(entry) => entry !== existingEntry && !entry.isMergeLoss && typeof entry.value === "function"
);
src/lib/handlers/routine-manager.mjs:429
- This prefix scan treats
:as a delimiter even though it is valid in module IDs. For example,pruneModule("a")also matches the wrapper key for module IDa:b, so removing one module can invalidate/delete another module's wrapper while its raw entry remains. Filter by a structured module ID or by the raw entries' exactmoduleIDinstead of a string prefix.
const prefix = `${moduleID}:`;
for (const key of this.rawWrappers.keys()) {
if (!key.startsWith(prefix)) continue;
src/lib/handlers/routine-manager.mjs:524
- When a speculative re-touch replaces an existing
(moduleID, apiPath)entry,onImplCreatedhas already replacedrawWrapperswith the candidate wrapper. This rollback restores only the prior function and array position; the caller invalidates the candidate, but the original wrapper is no longer tracked. A detached or in-flight prior wrapper can therefore re-emit a stale contribution after removal. Snapshot and restore the prior wrapper mapping along with the raw entry (including the state-wide rollback path).
revertRawEntry(apiPath, moduleID, priorEntry) {
const idx = this.raw.findIndex((e) => e.apiPath === apiPath && e.moduleID === moduleID);
if (priorEntry !== undefined) {
const entry = { apiPath, moduleID, fn: priorEntry.fn };
if (idx !== -1) this.raw[idx] = entry;
// The candidate's own touch deleted this pair outright (onImplCreated's non-function
// guard) rather than overwriting it — re-insert at its ORIGINAL position instead of
// appending, or a rejected re-touch would silently move this contributor to the end of
// `raw`, changing `stackRoutines: true`'s registration-order execution (#372/#373 review,
// suppressed finding). Clamp to the current length in case other entries were removed
// in the interim.
else this.raw.splice(Math.min(priorEntry.index, this.raw.length), 0, entry);
src/lib/handlers/routine-manager.mjs:217
- The phrase "a path ownership has no record for at all" is grammatically incorrect and obscures the intended condition. Please change it to "a path with no ownership record at all".
* `OwnershipManager#getCurrentOwner()`. Conservative by design: a path ownership has no record
* for at all is never excluded (ownership tracking doesn't reach every construction path, and
* an untracked path was never a collision in the first place) — this only ever EXCLUDES an
types/src/lib/handlers/routine-manager.d.mts:117
- The generated
runCascade()declaration repeats that colliding contributors run together without stating thestackRoutinesgate. With the public defaultfalse, only the current owner at an identical path runs, so this consumer-facing JSDoc is inaccurate. Regenerate it after correcting the source documentation.
- Files reviewed: 66/78 changed files
- Comments generated: 1
- Review effort level: Lite
RoutineManager.rawWrappers was keyed by a single `${moduleID}:${apiPath}`
string. Since ':' is a valid character in a user-supplied moduleID,
pruneModule("a")'s own prefix scan ("a:") could also match a DIFFERENT
module's own key (moduleID "a:b"'s "a:b:sub.path"), wrongly
invalidating/dropping that unrelated module's tracked wrapper.
Restructured to a nested moduleID -> apiPath -> wrapper map, which
eliminates the ambiguity entirely and simplifies pruneModule() (no more
string parsing).
Also fixes revertRawEntry/revertSpeculativeSubtree/revertSpeculativeState
losing track of a pair's ORIGINAL wrapper on restore: onImplCreated
overwrites rawWrappers with a candidate's own wrapper the moment it
re-touches an existing (apiPath, moduleID) pair, and reverting only
restored raw's fn/position, not rawWrappers' tracking — leaving a
genuinely-still-relevant prior wrapper untracked after the candidate's
own was correctly invalidated. snapshotRawEntry/snapshotRawEntries now
also capture the prior wrapper; every restore path puts it back.
Two documentation accuracy fixes from the same review round:
- routine-manager.mjs's runCascade() JSDoc (and generated .d.mts) said
the root cascade "runs every matching contribution anywhere" without
qualifying that same-path contributors are still gated by
stackRoutines; docs/LIFECYCLE.md had the identical gap in its earlier
root-cascade introduction (both now match the accurate wording
already used elsewhere in the same doc).
- Fixed a comment typo ("has no record for at all" -> "with no
ownership record at all").
Regenerated types/ via a full `npm run build` (the prior npm run
build:types-only attempt picked up a stale dist/, degrading an
unrelated declaration to `any` — confirmed and discarded).
Declined one suggested fix from this same review round: the
ownership.mjs duplicate-registration "merge" correction based on
"any historical non-loss function" was flagged as able to demote a
still-live winner, but the suggested fix (base it on the CURRENT
#currentEntry() winner instead) breaks an already-established,
already-tested invariant from an earlier round of this same PR
(tests/vitests/suites/ownership/ownership-merge-current-owner.test.vitest.mjs,
"a later 'merge' registration for the same pair demotes it, correcting
an earlier call's wrong 'replace' guess") — confirmed via direct
regression before reverting the attempted change.
|
Addressing the 6 suppressed findings from the review at
All 4 code fixes verified red→green. Full handlers/ownership/lifecycle/config/builders/api-manager/core/processors suite (102 files, ~3085 tests) green. Regenerated |
There was a problem hiding this comment.
🔵 Needs a closer look
Rejected wrapper candidates can leave descendant state and routines active until full-subtree rollback is implemented.
Review details
Suppressed comments (1)
src/lib/builders/modes-processor.mjs:153
- This helper only snapshots/reverts the exact
(apiPath, moduleID)pair, but constructing a wrapper with an object implementation eagerly creates child wrappers and emitsimpl:createdfor paths such asapiPath.initializebeforeassignToApiPath()decides the parent collision. If that parent is rejected byskip/warn,constructedWrapper?.___invalidate()clears only the parent; the child ownership/raw entries and child wrappers remain, so an unmounted candidate's routines can still run (and later materialization can re-register them). Revert the entire candidate subtree and invalidate its descendants on both rejection paths.
if (!assigned) {
this.slothlet.handlers.routineManager?.revertRawEntry(apiPath, moduleID, priorFn);
this.#revertOwnershipEntry(apiPath, moduleID, priorOwnershipEntry);
constructedWrapper?.___invalidate();
- Files reviewed: 69/84 changed files
- Comments generated: 0 new
- Review effort level: Lite
…t just its own pair #assignWithRoutineRevert only snapshotted/reverted the exact (apiPath, moduleID) pair. An eager wrapper constructed from an OBJECT initialImpl adopts child properties synchronously at construction (___adoptImplChildren, called whenever initialImpl isn't null and child adoption isn't deferred) — firing impl:created for descendant paths (e.g. "apiPath.initialize") before assignToApiPath()'s parent-level collision decision is known. A rejected parent only had its own pair reverted; descendant raw/ownership entries and their wrappers survived, so an unmounted candidate's descendant routines could still run. Snapshot the whole module's raw/ownership state fresh before each candidate's own construction (cheap - a filter over already-in-memory state), and on rejection/throw walk the actual constructed wrapper's subtree via RoutineManager/OwnershipManager's existing revertSpeculativeSubtree() plus ApiManager#invalidateSpeculativeWrappers() - reusing the same primitives already used for outer-level api.add() rejections, instead of duplicating single-pair logic. Falls back to the single-pair revert only when no wrapper was constructed for a branch (a raw-value assignment). Verified via full regression (builders/ownership/config/lifecycle/ handlers/api-manager/core, 95 files, ~3019 tests, zero regressions). A hand-crafted end-to-end repro isolating the exact eager-child-adoption trigger proved elusive within reasonable effort; this is verified at the mechanism level (each reused primitive already has its own dedicated tests from earlier rounds) plus code-review correctness against the reviewer's own described scenario.
|
Addressing the suppressed finding from the review at
Verified via full regression (95 files, ~3019 tests, zero regressions) plus code-review correctness against the described scenario — a hand-crafted end-to-end repro isolating the exact eager-child-adoption trigger proved elusive within reasonable effort, so this is verified at the mechanism level (each reused primitive already has its own dedicated tests from earlier rounds), matching the same standard applied to a similarly hard-to-isolate |
…d-callable writes RoutineManager#rebuildStacks() installs its stacked callable directly onto the live tree (target[key] = ...), guarding only its OWN raw capture via recording = false. The generic impl:created/impl:changed subscribers that feed OwnershipManager had no equivalent guard, so every rebuild's write was misattributed to whatever module owns the CONTAINER (e.g. the base module) and registered as if it were that module's own contribution — polluting the ownership stack with a phantom entry on every single rebuildStacks() call. A later removal's restore-to-prior-owner logic could then pick that phantom entry instead of the real one, leaving a stale stacked callable (or nothing useful) where a genuine value should have been restored. Mirrors RoutineManager#onImplCreated's own existing fn.__slothletRoutineStack check. Declined two related suggested fixes from the same review round after confirming, via direct regression, that each conflicts with an already-established, already-tested design decision from an earlier round of this PR: - Making rebuildStacks() run every routine that matches an overlapping apiPath (instead of last-registered-routine-wins) breaks routines.test.vitest.mjs's "distinct routines sharing an exact composed apiPath" test, which explicitly asserts exactly one contributor runs and cross-invocation between independently configured routines must never happen. - The stale-stack-after-last-contributor-removed symptom traces to this same root cause (ownership's own restore logic picking the phantom stacked-callable entry instead of the genuine prior owner); isolated testing of rebuildStacks()'s own "skip paths outside current groups" logic confirms it is already correct once ownership's bookkeeping isn't corrupted. Verified via full regression (lifecycle/ownership/config/handlers/ builders/api-manager/core, 95 files, ~3019 tests; one core-reload-full timeout reproduced as a resource-pressure flake, confirmed passing 64/64 in isolation).
…rialization deletePath() cleared a removed wrapper's impl/children/materialized state but never set the invalid flag ___materialize() itself checks (before starting and again after its awaited work resolves). A backgroundMaterialize: true wrapper mid-materialization when its path is removed could apply its stale result afterward, and if the same moduleID is re-added before that resolves, the re-add's own clearUnregistered() call would let the stale impl:changed through and pollute ownership/routine state.
🚀 What's Changed
💥 Breaking Changes
No breaking changes
✨ Features
🐛 Bug Fixes
📦 Dependencies
No dependency updates
🔧 Other Changes
👥 Contributors