Skip to content

BUG: attempts to use host as conditional of lib.optionalAttrs in sub … - #413

Closed
kalyanoliveira wants to merge 2 commits into
denful:mainfrom
kalyanoliveira:push-asuhdglkajsf
Closed

kalyanoliveira wants to merge 2 commits into
denful:mainfrom
kalyanoliveira:push-asuhdglkajsf

Conversation

@kalyanoliveira

@kalyanoliveira kalyanoliveira commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

This is my first time trying to write a test case for den.

The edited bug.nix contains what I believe to be a bug.

Only what I BELIEVE to be a bug, though. I need someone to verify that I have not had any skill issues.

@kalyanoliveira

Copy link
Copy Markdown
Contributor Author

Of course, feel free to close once a decision about this has been made: this should not be merged.

den.schema.host.options.foo._.sub.enable = lib.mkEnableOption "asdf";
};

# enables that "enable" in the schema

@kalyanoliveira kalyanoliveira Apr 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I meant to say #enables that "enable" option on the host

@kalyanoliveira

Copy link
Copy Markdown
Contributor Author

Here's what claude had to say about this in relation to #410 and #408

Bug: bare function aspects in provides/_ sub-aspects are called as module functions

Problem

When a sub-aspect defined via provides (or the _ alias) is a bare parametric function, Den incorrectly calls it as a NixOS module function instead of dispatching it as a parametric aspect. This causes the error:

error: attribute 'host' missing
at lib/modules.nix:727
  config._module.args.${name}

Minimal reproduction

den.aspects.foo = { host, ... }: {
  includes = lib.optionals (host.foo._.sub.enable == true) [
    den.aspects.foo._.sub
  ];
};

den.aspects.foo._.sub = { host, ... }: {
  nixos = lib.optionalAttrs (host.hostName != "whatever") {
    networking.networkmanager.enable = true;
  };
};

Root cause

PR #410 fixed bare function aspects in includes by wrapping them as { includes = [fn]; } at the coercedProviderType level. However, sub-aspects defined via provides/_ go through providerType directly, which still has the old merge behavior in providerFnType. The merge override in providerFnType wraps the merged result in { __functor = _: ...; } to make it look like an aspect, but when the result is itself a bare function (a curriedProviderFnType — i.e. a parametric function taking { host, ... } rather than the static { class, aspect-chain }), it is later called with NixOS module arguments instead of being dispatched parametrically.

Relationship to #408 and #410

Issue #408 identified that bare function aspects were being called as module functions. PR #410 fixed this for top-level includes entries by coercing bare functions to { includes = [fn]; }. This case is the same bug one level deeper: in provides/_ sub-aspects, the same coercion is needed but was not applied.

Workaround

Wrap the sub-aspect explicitly with den.lib.parametric:

den.aspects.foo._.sub = den.lib.parametric {
  includes = [
    ({ host, ... }: {
      nixos = lib.optionalAttrs (host.hostName != "whatever") {
        networking.networkmanager.enable = true;
      };
    })
  ];
};

Fix

The same coercion applied to top-level includes in #410 needs to be applied to provides/_ sub-aspects — specifically, bare parametric functions (matching curriedProviderFnType) appearing as values in a provides attrset should be wrapped as { includes = [fn]; } rather than being left as bare functions that the merge machinery will later mistake for module functions.

@sini

sini commented Apr 9, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the detailed investigation I'll take a look today.

@sini

sini commented Apr 9, 2026

Copy link
Copy Markdown
Collaborator

I've also been letting claude try different permutations of fixes to try and find a novel solution that isn't just a band aid around this one edge-case that also doesn't break any existing signatures. I ran out out of max-tier tokens twice so waiting for my window to refresh again.

Every time I get a fix that passes for this edge case it sneaks in somewhere else and breaks or causes infinite recursion, but I'm confident that a solution exists. :)

I've got one that works, but re-introduces the duplication on perHost-perUser bug. Very close to a working solution.

@kalyanoliveira

Copy link
Copy Markdown
Contributor Author

yeah I have been playing around with claude on https://github.com/kalyanoliveira/den on branch fix/provides-perHost-identity, but the furthest I got was passing all test cases but the one of #408

sini added a commit to sini/den that referenced this pull request Apr 9, 2026
When a parametric aspect includes a provider sub-aspect that is also
a bare function (e.g. den.aspects.foo._.sub = { host, ... }: { ... }),
the sub-aspect's function was never called with the parametric context.

Root cause: providerFnType.merge wraps bare functions as
{ __functor = _: fn; }, placing them in the aspect's __functor rather
than includes. When the parent aspect's function returns
{ includes = [foo._.sub]; }, the sub-aspect appears as a leaf in
deepRecurse's mapIncludes and reaches resolve uncalled.

Fix: applyDeep in parametric.applyIncludes resolves sub-includes of
successful takeFn results one level deep. When take.atLeast calls
a provider function that returns { includes = [sub-aspect]; }, the
nested sub-aspect also receives parametric context before entering
the static pipeline.

Guards prevent double-resolution: results carrying meta (from
withIdentity/withOwn) or __functor (deferred deepRecurse wrappers)
are returned as-is since their includes are already processed.

Fixes denful#413
sini pushed a commit to sini/den that referenced this pull request Apr 9, 2026
Demonstrates that using host as a conditional inside a provider
sub-aspect function fails — the sub-aspect's parametric context
is never applied.

ref: denful#413
sini added a commit to sini/den that referenced this pull request Apr 9, 2026
When a parametric aspect includes a provider sub-aspect that is also
a bare function (e.g. den.aspects.foo._.sub = { host, ... }: { ... }),
the sub-aspect's function was never called with the parametric context.

Root cause: providerFnType.merge wraps bare functions as
{ __functor = _: fn; }, placing them in the aspect's __functor rather
than includes. When the parent aspect's function returns
{ includes = [foo._.sub]; }, the sub-aspect appears as a leaf in
deepRecurse's mapIncludes and reaches resolve uncalled.

Fix: applyDeep in parametric.applyIncludes resolves sub-includes of
successful takeFn results one level deep. When take.atLeast calls
a provider function that returns { includes = [sub-aspect]; }, the
nested sub-aspect also receives parametric context before entering
the static pipeline.

Guards prevent double-resolution: results carrying meta (from
withIdentity/withOwn) or __functor (deferred deepRecurse wrappers)
are returned as-is since their includes are already processed.

Fixes denful#413
@sini

sini commented Apr 9, 2026

Copy link
Copy Markdown
Collaborator

@kalyanoliveira

yeah I have been playing around with claude on https://github.com/kalyanoliveira/den on branch fix/provides-perHost-identity, but the furthest I got was passing all test cases but the one of #408

As I post that, I've got a fix that passes for everything. I'll push it shortly. I've taken your test out of the bogus template and put it into our templates/ci/modules/features/deadbugs module and tagged the commit with you as author. :-) I'll open a separate PR with it and tag you in it.

sini added a commit to sini/den that referenced this pull request Apr 9, 2026
When a parametric aspect includes a provider sub-aspect that is also
a bare function (e.g. den.aspects.foo._.sub = { host, ... }: { ... }),
the sub-aspect's function was never called with the parametric context.

Root cause: providerFnType.merge wraps bare functions as
{ __functor = _: fn; }, placing them in the aspect's __functor rather
than includes. When the parent aspect's function returns
{ includes = [foo._.sub]; }, the sub-aspect appears as a leaf in
deepRecurse's mapIncludes and reaches resolve uncalled.

Fix: applyDeep in parametric.applyIncludes resolves sub-includes of
successful takeFn results one level deep. When take.atLeast calls
a provider function that returns { includes = [sub-aspect]; }, the
nested sub-aspect also receives parametric context before entering
the static pipeline.

Guards prevent double-resolution: results carrying meta (from
withIdentity/withOwn) or __functor (deferred deepRecurse wrappers)
are returned as-is since their includes are already processed.

Fixes denful#413
sini pushed a commit to sini/den that referenced this pull request Apr 9, 2026
sini added a commit to sini/den that referenced this pull request Apr 9, 2026
…#413)

When a parametric aspect includes a provider sub-aspect that is also
a bare function (e.g. den.aspects.foo._.sub = { host, ... }: { ... }),
the sub-aspect's function was never called with the parametric context.

Root cause: providerFnType.merge wraps bare functions as
{ __functor = _: fn; }, placing them in the aspect's __functor rather
than includes. When the parent aspect's function returns
{ includes = [foo._.sub]; }, the sub-aspect appears as a leaf in
deepRecurse's mapIncludes and reaches resolve uncalled.

Fix: applyDeep in parametric.applyIncludes resolves sub-includes of
successful takeFn results one level deep. When take.atLeast calls
a provider function that returns { includes = [sub-aspect]; }, the
nested sub-aspect also receives parametric context before entering
the static pipeline.

Guards prevent double-resolution: results carrying meta (from
withIdentity/withOwn) or __functor (deferred deepRecurse wrappers)
are returned as-is since their includes are already processed.

Fixes denful#413
sini pushed a commit to sini/den that referenced this pull request Apr 9, 2026
sini added a commit to sini/den that referenced this pull request Apr 9, 2026
…#413)

When a parametric aspect includes a provider sub-aspect that is also
a bare function (e.g. den.aspects.foo._.sub = { host, ... }: { ... }),
the sub-aspect's function was never called with the parametric context.

Root cause: providerFnType.merge wraps bare functions as
{ __functor = _: fn; }, placing them in the aspect's __functor rather
than includes. When the parent aspect's function returns
{ includes = [foo._.sub]; }, the sub-aspect appears as a leaf in
deepRecurse's mapIncludes and reaches resolve uncalled.

Fix: applyDeep in parametric.applyIncludes resolves sub-includes of
successful takeFn results one level deep. When take.atLeast calls
a provider function that returns { includes = [sub-aspect]; }, the
nested sub-aspect also receives parametric context before entering
the static pipeline.

Guards prevent double-resolution: results carrying meta (from
withIdentity/withOwn) or __functor (deferred deepRecurse wrappers)
are returned as-is since their includes are already processed.

Fixes denful#413
@sini

sini commented Apr 9, 2026

Copy link
Copy Markdown
Collaborator

This should be fixed with #419 -- we can re-open if needed.

@sini sini closed this Apr 9, 2026
vic pushed a commit that referenced this pull request Apr 9, 2026
Fixes #413

### Problem

Provider sub-aspects defined as bare context functions don't receive `{
host }` during resolution:

```nix
den.aspects.foo._.sub = { host, ... }: {
  nixos = lib.optionalAttrs (host.hostName != "whatever") {
    networking.networkmanager.enable = true;
  };
};
```

When a parent function returns `{ includes = [foo._.sub] }`, the
sub-aspect is resolved by the adapter system which only passes `{ class,
aspect-chain }` — the `{ host }` context from the pipeline never reaches
nested includes of function results.

### Fix

`applyDeep` in `parametric.applyIncludes` — when `takeFn` succeeds and
returns a bare result with sub-includes (no `meta`, no `__functor`),
also apply `takeFn` to those sub-includes. This propagates context to
provider sub-aspects nested inside function results without
double-applying to parametric wrappers or `deepRecurse` outputs.

The key discriminator: bare provider results carry only `includes` (+
`name` from `carryAttrs`). Results from `withOwn`/`withIdentity` have
`meta`; deferred `deepRecurse` wrappers have `__functor`. Neither should
be re-resolved.

### Test coverage

- `deadbugs/issue-413-provider-bare-function.nix` — reproduces the
original report
- `deadbugs/issue-413-provider-sub-aspect-function.nix` — variant with
`lib.optionalAttrs` guard
- `provides-parametric.nix` — provider sub-aspects with parametric
context in various configurations

cc: @kalyanoliveira for the report

---------

Co-authored-by: horyzon <[email protected]>
sini added a commit to sini/den that referenced this pull request Apr 11, 2026
Extends has-aspect.nix with the complete Groups A-J test matrix from
the design spec §7.3:

- Group A: sanity / transitive chains
- Group B: parametric contexts, including the denful#423 and denful#413 regression
  shapes as explicit lock-ins
- Group C: factory-function aspects (§8.1 resolved as Outcome A —
  factory-path identity is stable; tested via direct factory reference
  in includes since invoked instances become anonymous aspects)
- Group D: provider sub-aspects + identity disambiguation
- Group E: mutual-provider / provides chains (to-users, per-user,
  to-hosts)
- Group F: substituteAspect, composition at different levels (NOT
  nested-reaching per filterIncludes.tag semantics), oneOfAspects
  integration
- Group G: multi-class users (primary, forClass, forAnyClass, unknown
  class)
- Group H: extensibility contract (den.schema.conf owns the option)
- Group I: error cases — bad ref throws
- Group J: real-world call from inside a deferred nixos module body,
  validating the cycle-safety guarantee for the primary intended use
  case (uses outer let-binding closure capture since the `host`
  specialArg from nix/lib/types.nix:30 lives on the den host submodule
  and does not propagate into OS-level deferred nixos modules)

hasAspect reads config.resolved which is the output of the ctxApply +
parametric resolution pipeline. Every aspect-shape recent regressions
(denful#408, denful#413, denful#423, denful#429) lived in has a corresponding test here, so a
future regression in parametric.nix or aspects/types.nix that affects
any of these shapes fails a hasAspect test before it reaches user code.

Two tests in Groups B and D are XFAILed against current behavior:
function-bodied provider sub-aspects (`foo._.sub = { host, ... }: ...`)
lose their `foo` provider prefix in the resolved tree (aspectPath
becomes ["sub"] instead of ["foo","sub"]). The class config still
materializes correctly — see deadbugs/issue-413 — but hasAspect lookup
misses because the reference's path differs from the resolved tree's
path. Test bodies document the gap and are wired to flip to `expected
= true` once the parametric pipeline preserves provider prefix on
function-bodied sub-aspects.
sini added a commit to sini/den that referenced this pull request Apr 12, 2026
Extends the smoke suite with the complete regression-class matrix,
organized by aspect shape:

- Group A: sanity / transitive chains
- Group B: parametric contexts, incl. denful#423 static-sub-in-parametric-
  parent and denful#413 bare-function-sub-aspect shapes as explicit
  regression lock-ins
- Group C: factory-function aspects — direct factory reference in
  includes (factory-path identity is stable; inline invocation
  produces a differently-named sibling, tested here as a caveat)
- Group D: provider sub-aspects + identity disambiguation
- Group E: mutual-provider / provides chains (to-users, per-user,
  to-hosts)
- Group F: substituteAspect, composition at different levels (NOT
  nested-reaching per filterIncludes.tag semantics), oneOfAspects
  integration
- Group G: multi-class users (primary, forClass, forAnyClass,
  unknown class)
- Group H: extensibility contract — den.schema.conf owns the option
- Group I: error cases — bad ref throws
- Group J: real-world call from inside a deferred nixos module body,
  validating the cycle-safety guarantee for the primary intended
  use case

hasAspect reads config.resolved — the output of the ctxApply +
parametric resolution pipeline. Every aspect-shape that recently
produced a regression (denful#408, denful#413, denful#423, denful#429) has a lock-in test
here, so a future regression in parametric.nix or aspects/types.nix
that affects any of those shapes fails a hasAspect test before it
reaches user code.
sini added a commit to sini/den that referenced this pull request Apr 13, 2026
Extends the smoke suite with the complete regression-class matrix,
organized by aspect shape:

- Group A: sanity / transitive chains
- Group B: parametric contexts, incl. denful#423 static-sub-in-parametric-
  parent and denful#413 bare-function-sub-aspect shapes as explicit
  regression lock-ins
- Group C: factory-function aspects — direct factory reference in
  includes (factory-path identity is stable; inline invocation
  produces a differently-named sibling, tested here as a caveat)
- Group D: provider sub-aspects + identity disambiguation
- Group E: mutual-provider / provides chains (to-users, per-user,
  to-hosts)
- Group F: substituteAspect, composition at different levels (NOT
  nested-reaching per filterIncludes.tag semantics), oneOfAspects
  integration
- Group G: multi-class users (primary, forClass, forAnyClass,
  unknown class)
- Group H: extensibility contract — den.schema.conf owns the option
- Group I: error cases — bad ref throws
- Group J: real-world call from inside a deferred nixos module body,
  validating the cycle-safety guarantee for the primary intended
  use case

hasAspect reads config.resolved — the output of the ctxApply +
parametric resolution pipeline. Every aspect-shape that recently
produced a regression (denful#408, denful#413, denful#423, denful#429) has a lock-in test
here, so a future regression in parametric.nix or aspects/types.nix
that affects any of those shapes fails a hasAspect test before it
reaches user code.
sini added a commit that referenced this pull request Apr 13, 2026
# feat: `entity.hasAspect <ref>` query method

## What this does

Adds a `.hasAspect` method on context entities (`host`, `user`, `home`,
and any custom entity kind that imports `den.schema.conf`). It answers
"is this aspect structurally present in my resolved tree?" from inside
class-config module bodies:

```nix
den.aspects.impermanence.nixos = { config, host, ... }: lib.mkMerge [
  (lib.mkIf (host.hasAspect <zfs-root>)   { /* zfs impermanence */ })
  (lib.mkIf (host.hasAspect <btrfs-root>) { /* btrfs impermanence */ })
];
```

There are two variants for when the bare form isn't enough:

```nix
host.hasAspect.forClass "nixos" <facter>
user.hasAspect.forAnyClass <agenix-rekey>
```

Identity is compared by `aspectPath` (`meta.provider ++ [name]`), so
provider sub-aspects like `foo._.sub` keep their full path. Refs can be
plain aspect values (`den.aspects.facter`) or `<angle-bracket>` sugar,
they're the same thing after `__findFile` resolves.

Alongside `hasAspect`, this ships a companion `oneOfAspects` adapter.
That's the structural-decision primitive for "prefer A over B when both
are present", which is the thing you actually want when you're tempted
to use `hasAspect` to decide includes (see the guardrails section
below).

## Why

Real patterns that users hit:

- `<impermanence>` config depends on whether `<zfs-root>` or
  `<btrfs-root>` is also configured on the host
- A secrets forward wants to pick `<agenix-rekey>` when present and
  fall back to `<sops-nix>` otherwise
- Library aspects want to gate opt-in behavior on companion aspects

Today these get worked around with `config.*` lookups, hand-maintained
`lib.elem` checks, or structural hacks. `hasAspect` is the first-class
primitive for the read side. `oneOfAspects` is the first-class primitive
for the write side.

## Commits

Each commit is independently reviewable and builds green on its own.

### `fix(parametric): preserve meta on materialized parametric results`

Opened as it's own PR #440 

### `feat(adapters): add collectPaths terminal adapter`

New public terminal adapter. Walks a resolved tree via `filterIncludes`
and returns `{ paths = [ [providerSeg..., name], ... ]; }`, depth-first,
not deduplicated. Tombstones are skipped via the `meta.excluded` check.

Ships with two small helpers exported from the same file: `pathKey`
(slash-joined path key) and `toPathSet` (list of paths to attrset-as-set
for O(1) lookups). Both are used by `hasAspect` and `oneOfAspects`, so
exporting them keeps the two consumers from duplicating the same
one-liners.

### `feat(adapters): add oneOfAspects structural-decision adapter`

`meta.adapter` that keeps the first structurally-present candidate and
tombstones the rest via `excludeAspect`:

```nix
den.aspects.secrets-bundle = {
  includes = [ <agenix-rekey> <sops-nix> ];
  meta.adapter = den.lib.aspects.adapters.oneOfAspects [
    <agenix-rekey>  # preferred
    <sops-nix>      # fallback
  ];
};
```

Complements `excludeAspect` and `substituteAspect`. The three together
cover include-this / exclude-this / swap-this-for-that. Internally it
walks the parent subtree with the raw collector (bypassing
`filterIncludes` so it doesn't re-enter itself), finds which candidates
are present, and folds `excludeAspect` over the losers. No code
duplication with `collectPaths` thanks to the shared helpers from the
previous commit.

### `feat(aspects): add has-aspect library primitives`

New file `nix/lib/aspects/has-aspect.nix` exporting:

- `hasAspectIn { tree; class; ref }` for any resolved tree, not just
  entity contexts
- `collectPathSet { tree; class }` for an attrset-as-set of visible
  paths
- `mkEntityHasAspect { tree; primaryClass; classes }` which builds the
  functor-plus-attrs value attached to entities. Per-class path sets
  are thunk-cached, so repeated calls share one traversal per class

`refKey` validates that its input has both `name` and `meta` before
reaching for `aspectPath`, throwing loudly rather than silently
producing an `<anon>` path key.

### `feat(context): add entity.hasAspect method via den.schema.conf`

The wiring. `modules/context/has-aspect.nix` is a flake-level module
that self-wires into `den.schema.conf` via
`config.den.schema.conf.imports`. Every entity type that imports `conf`
(host, user, home, and any user-defined kind) inherits `.hasAspect`
automatically. Zero changes to `nix/lib/types.nix`.

Class-protocol: prefers `classes` (list), falls back to `[ class ]`,
throws otherwise. Entities without a matching `den.ctx.<kind>` (so no
`config.resolved`) produce a call-time throw. The fallback value
preserves the functor-plus-attrs shape so `forClass` / `forAnyClass`
attribute access doesn't leak a cryptic error before reaching the real
one.

### `test(has-aspect): full regression-class coverage for entity method`

31 tests organized by aspect-construction shape. Every shape that's
produced a recent regression (`#408`, `#413`, `#423`, `#429`) has a
lock-in test. A future regression in `parametric.nix` or
`aspects/types.nix` that breaks any of these shapes trips a `has-aspect`
test before it reaches user code.

Groups cover basic and transitive chains, parametric contexts including
the static and bare-function sub-aspect shapes, factory functions,
provider sub-aspects and identity disambiguation, mutual-provider and
provides chains, `meta.adapter` composition, multi-class users, the
extensibility contract, error cases, and the primary intended use case
(calling `hasAspect` from inside a deferred `nixos` module body).

### `docs(example): add hasAspect + oneOfAspects worked examples`

User-facing pedagogical file in `templates/example/`. Three sections:
reading structure via `host.hasAspect` from a class-config body, writing
structure via `oneOfAspects` as a `meta.adapter`, and an anti-pattern
section explaining why `hasAspect` can't decide an aspect's `includes`
list with a pointer at the adapter library.

## Design guardrails

`hasAspect` is a read-only query on frozen structure. You call it from
inside class-config module bodies (`nixos = ...`, `homeManager = ...`)
or from lazy positions in aspect functor bodies. It's cycle-safe by
construction because by the time deferred class modules evaluate, the
aspect tree has already been resolved and frozen.

What it is not for: deciding an aspect's `includes` list. That's cyclic.
The tree you want to query depends on the decision you want `hasAspect`
to inform. Users who need that reach for `meta.adapter` composed via
`oneOfAspects`, `excludeAspect`, `substituteAspect`, or `filter` /
`filterIncludes`. Those run during the tree walk with full structural
visibility, so they can't cycle. The template example file has an
explicit anti-pattern section with the failing shape and the correct
rewrite.

Two tools, two jobs:

| Need | Tool | When it runs |
|---|---|---|
| Read "is X in my tree?" from module config | `hasAspect` | After the
tree is frozen, inside lazy class-module bodies |
| Decide tree structure based on "is X present?" | `meta.adapter` +
`oneOfAspects` / friends | During the tree walk, with full structural
visibility |

## Test plan

- [x] `just ci` passes 331/331 at branch tip
- [x] Each commit builds and passes tests on its own
- [x] `just fmt` is idempotent across the tree
- [x] The parametric fix doesn't regress `deadbugs/issue-413-*`,
      `deadbugs/issue-423-*`, or `issue-408` tests
- [x] Full regression-class matrix covers every aspect shape that's
      produced a recent bug

## Migration

None. Purely additive.

- `hasAspect` is a new option name, no conflict.
- No signature changes in `parametric.nix`, `resolve.nix`,
`ctx-apply.nix`, `types.nix`, or the other core library files.
- `adapters.nix` gains new exports (`collectPaths`, `oneOfAspects`,
`pathKey`, `toPathSet`). Nothing is renamed or removed.
- `nix/lib/aspects/default.nix` re-exports the new lib functions under
`den.lib.aspects.*` at their canonical paths.
- `modules/context/has-aspect.nix` is a new file, picked up by the
existing `import-tree` flake setup.
- Zero changes to `nix/lib/types.nix`.

## Follow-ups

- Docs pass on when to make aspects non-parametric. Users often reach
for `perHost` / `perUser` wrappers when the aspect has no actual ctx
dependence, which makes structural tooling less reliable than it could
be. Docs-only, separate PR.
- Conditional-include wrapper `onlyIf guard target`. A small adapter
sitting next to `oneOfAspects` that lets users write `includes = [
(onlyIf <zfs-root> <zfs-impermanence>) ]` for "include target iff guard
is structurally present." Same cycle-avoidance trick (decision runs in
the wrapper's own meta.adapter, walks the subtree with the raw
`collectPathsInner` collector so it doesn't re-enter itself). Reuses
every helper this PR exports. Rough spec is written up, scoped as its
own follow-up PR.
sini added a commit to sini/den that referenced this pull request Apr 13, 2026
, denful#437, meta carryover

Add bare function include handling to resolveDeep — wraps lambdas in
minimal aspect envelopes so they participate in recursive resolution.

Regression tests cover:
- Provider sub-aspect with bare parametric includes (denful#413/denful#423)
- Static sub inside parametric parent preserves owned config (denful#426)
- Factory function not incorrectly coerced (denful#437)
- meta.provider survives deep resolution
- 3-level deep parametric nesting
sini added a commit to sini/den that referenced this pull request Apr 14, 2026
, denful#437, meta carryover

Add bare function include handling to resolveDeep — wraps lambdas in
minimal aspect envelopes so they participate in recursive resolution.

Regression tests cover:
- Provider sub-aspect with bare parametric includes (denful#413/denful#423)
- Static sub inside parametric parent preserves owned config (denful#426)
- Factory function not incorrectly coerced (denful#437)
- meta.provider survives deep resolution
- 3-level deep parametric nesting
sini added a commit to sini/den that referenced this pull request Apr 14, 2026
, denful#437, meta carryover

Add bare function include handling to resolveDeep — wraps lambdas in
minimal aspect envelopes so they participate in recursive resolution.

Regression tests cover:
- Provider sub-aspect with bare parametric includes (denful#413/denful#423)
- Static sub inside parametric parent preserves owned config (denful#426)
- Factory function not incorrectly coerced (denful#437)
- meta.provider survives deep resolution
- 3-level deep parametric nesting
sini added a commit to sini/den that referenced this pull request Apr 14, 2026
, denful#437, meta carryover

Add bare function include handling to resolveDeep — wraps lambdas in
minimal aspect envelopes so they participate in recursive resolution.

Regression tests cover:
- Provider sub-aspect with bare parametric includes (denful#413/denful#423)
- Static sub inside parametric parent preserves owned config (denful#426)
- Factory function not incorrectly coerced (denful#437)
- meta.provider survives deep resolution
- 3-level deep parametric nesting
sini added a commit to sini/den that referenced this pull request Apr 14, 2026
, denful#437, meta carryover

Add bare function include handling to resolveDeep — wraps lambdas in
minimal aspect envelopes so they participate in recursive resolution.

Regression tests cover:
- Provider sub-aspect with bare parametric includes (denful#413/denful#423)
- Static sub inside parametric parent preserves owned config (denful#426)
- Factory function not incorrectly coerced (denful#437)
- meta.provider survives deep resolution
- 3-level deep parametric nesting
sini added a commit to sini/den that referenced this pull request Apr 17, 2026
- Move tests from batteries/, context/, perf/, home-manager/ subdirs
  to flat features/ directory
- Add fx-specific test suites: fx-aspect, fx-constraints, fx-handlers,
  fx-resolve, fx-trace, fx-e2e, fx-full-pipeline, fx-identity,
  fx-includeIf, fx-integration, fx-flag, fx-ctx-apply, fx-ctx-parametric,
  fx-effectful-resolve, fx-parametric-meta, fx-regressions,
  fx-adapter-integration
- Update existing tests for constraint terminology and provides. alias
- Add fxPipeline=false for legacy adapter tests
- Add regression reproductions for issues denful#413, denful#423, denful#426, denful#437
@sini sini mentioned this pull request Apr 17, 2026
5 tasks done
vic added a commit that referenced this pull request Apr 17, 2026
## Summary

Replace den's legacy recursive tree-walking resolution with an
effects-based pipeline. Aspects compile into effectful computations via
`aspectToEffect` — the tree structure emerges from effect composition,
not explicit recursion. All resolution strategy (constraint checking,
dedup, tracing, context dispatch) lives in handlers.

- **`aspectToEffect` compiler** — single function compiles any aspect
into a computation that emits `emit-class`, `register-constraint`,
`emit-include`, and `resolve-complete` effects
- **Handler-owned recursion** — `emit-include` handler checks
constraints and recurses via effectful resume; `into-transition` handler
processes context transitions with `scope.stateful`
- **Constraint system** — `meta.handleWith` / `meta.excludes` replace fx
usage of `meta.adapter`; scoped constraints via includes-chain ancestry;
`exclude`, `substitute`, `filterBy` constructors with subtree/global
variants
- **Includes chain provenance** — `chain-push`/`chain-pop` effects
replace `__parent` string tracking; observable by any handler for
diagrams, scope visualization, composable analysis
- **Module wiring** — `{ lib, den }` only, no `init` function, barrel
`default.nix`; nix-effects accessed as `den.lib.fx`
- **`den.fxPipeline` option** — defaults to `true`; legacy tests using
`resolve.withAdapter` run with `fxPipeline = false`

### Pipeline architecture

```
nix/lib/aspects/fx/
  aspect.nix        — aspectToEffect compiler
  pipeline.nix      — mkPipeline, defaultHandlers, fxResolve
  identity.nix      — path/identity utilities, collectPathsHandler, pathSetHandler
  constraints.nix   — exclude, substitute, filterBy constructors
  includes.nix      — includeIf conditional inclusion
  trace.nix         — structuredTraceHandler, tracingHandler
  handlers/
    include.nix     — emit-include handler (owns recursion)
    transition.nix  — into-transition handler (scope.stateful)
    ctx.nix         — constantHandler, ctxSeenHandler
    tree.nix        — constraintRegistryHandler, chainHandler, classCollectorHandler
```

### Effect protocol

| Effect | Handler responsibility |
|---|---|
| `emit-class` | Accumulate modules by class |
| `emit-include` | Check constraints, recurse via `aspectToEffect` |
| `register-constraint` | Store in registry with scope/ownerChain |
| `check-constraint` | Query registry, first-registered-wins |
| `chain-push` / `chain-pop` | Track includes-path stack |
| `into-transition` | Walk context transitions with scoped handlers |
| `ctx-seen` | Dedup context stages |
| `resolve-complete` | Emit trace entries, accumulate paths |
| `get-path-set` | Return accumulated path set for `includeIf` guards |
| `<arg-name>` | `constantHandler` resumes with context value |

### Compatibility shims

The type system operates at declaration time and cannot be gated on
`config.den.fxPipeline` without circular evaluation:

- `aspect-chain` in `constantHandler` — provider functions from
`providerFnType.merge` create `{ class, aspect-chain }` functors
- `options.nix` uses legacy `ctxApply` — `config.resolved` can't access
`config.den` without circularity
- Legacy adapter tests run with `fxPipeline = false`

### Also in this PR

- `refactor: replace _. alias with provides.` across all
aspect/output/template modules
- `feat: ci-fast recipe` using nix-eval-jobs for parallel test eval
- Test restructuring: `batteries/`, `context/`, `perf/`, `home-manager/`
subdirs flattened to `features/`
- Regression reproductions for issues #413, #423, #426, #437
- Consolidated design spec at `docs/design/fx-pipeline-spec.md`

## Test plan

- [x] `nix develop -c just ci ""` — 488/488 pass
- [x] `nix develop -c just ci-fast` — parallel eval, 488/488 pass
- [x] `nix flake check` — templates, packages, devShells all pass
- [x] Checkmate `system-agnostic` tests — 15/15 pass
- [x] Legacy tests with `fxPipeline = false` verify backward
compatibility

---------

Co-authored-by: Victor Borja <[email protected]>
charlesfire pushed a commit to charlesfire/den that referenced this pull request May 16, 2026
Replace den's legacy recursive tree-walking resolution with an
effects-based pipeline. Aspects compile into effectful computations via
`aspectToEffect` — the tree structure emerges from effect composition,
not explicit recursion. All resolution strategy (constraint checking,
dedup, tracing, context dispatch) lives in handlers.

- **`aspectToEffect` compiler** — single function compiles any aspect
into a computation that emits `emit-class`, `register-constraint`,
`emit-include`, and `resolve-complete` effects
- **Handler-owned recursion** — `emit-include` handler checks
constraints and recurses via effectful resume; `into-transition` handler
processes context transitions with `scope.stateful`
- **Constraint system** — `meta.handleWith` / `meta.excludes` replace fx
usage of `meta.adapter`; scoped constraints via includes-chain ancestry;
`exclude`, `substitute`, `filterBy` constructors with subtree/global
variants
- **Includes chain provenance** — `chain-push`/`chain-pop` effects
replace `__parent` string tracking; observable by any handler for
diagrams, scope visualization, composable analysis
- **Module wiring** — `{ lib, den }` only, no `init` function, barrel
`default.nix`; nix-effects accessed as `den.lib.fx`
- **`den.fxPipeline` option** — defaults to `true`; legacy tests using
`resolve.withAdapter` run with `fxPipeline = false`

```
nix/lib/aspects/fx/
  aspect.nix        — aspectToEffect compiler
  pipeline.nix      — mkPipeline, defaultHandlers, fxResolve
  identity.nix      — path/identity utilities, collectPathsHandler, pathSetHandler
  constraints.nix   — exclude, substitute, filterBy constructors
  includes.nix      — includeIf conditional inclusion
  trace.nix         — structuredTraceHandler, tracingHandler
  handlers/
    include.nix     — emit-include handler (owns recursion)
    transition.nix  — into-transition handler (scope.stateful)
    ctx.nix         — constantHandler, ctxSeenHandler
    tree.nix        — constraintRegistryHandler, chainHandler, classCollectorHandler
```

| Effect | Handler responsibility |
|---|---|
| `emit-class` | Accumulate modules by class |
| `emit-include` | Check constraints, recurse via `aspectToEffect` |
| `register-constraint` | Store in registry with scope/ownerChain |
| `check-constraint` | Query registry, first-registered-wins |
| `chain-push` / `chain-pop` | Track includes-path stack |
| `into-transition` | Walk context transitions with scoped handlers |
| `ctx-seen` | Dedup context stages |
| `resolve-complete` | Emit trace entries, accumulate paths |
| `get-path-set` | Return accumulated path set for `includeIf` guards |
| `<arg-name>` | `constantHandler` resumes with context value |

The type system operates at declaration time and cannot be gated on
`config.den.fxPipeline` without circular evaluation:

- `aspect-chain` in `constantHandler` — provider functions from
`providerFnType.merge` create `{ class, aspect-chain }` functors
- `options.nix` uses legacy `ctxApply` — `config.resolved` can't access
`config.den` without circularity
- Legacy adapter tests run with `fxPipeline = false`

- `refactor: replace _. alias with provides.` across all
aspect/output/template modules
- `feat: ci-fast recipe` using nix-eval-jobs for parallel test eval
- Test restructuring: `batteries/`, `context/`, `perf/`, `home-manager/`
subdirs flattened to `features/`
- Regression reproductions for issues denful#413, denful#423, denful#426, denful#437
- Consolidated design spec at `docs/design/fx-pipeline-spec.md`

- [x] `nix develop -c just ci ""` — 488/488 pass
- [x] `nix develop -c just ci-fast` — parallel eval, 488/488 pass
- [x] `nix flake check` — templates, packages, devShells all pass
- [x] Checkmate `system-agnostic` tests — 15/15 pass
- [x] Legacy tests with `fxPipeline = false` verify backward
compatibility

---------

Co-authored-by: Victor Borja <[email protected]>
charlesfire pushed a commit to charlesfire/den that referenced this pull request May 16, 2026
Replace den's legacy recursive tree-walking resolution with an
effects-based pipeline. Aspects compile into effectful computations via
`aspectToEffect` — the tree structure emerges from effect composition,
not explicit recursion. All resolution strategy (constraint checking,
dedup, tracing, context dispatch) lives in handlers.

- **`aspectToEffect` compiler** — single function compiles any aspect
into a computation that emits `emit-class`, `register-constraint`,
`emit-include`, and `resolve-complete` effects
- **Handler-owned recursion** — `emit-include` handler checks
constraints and recurses via effectful resume; `into-transition` handler
processes context transitions with `scope.stateful`
- **Constraint system** — `meta.handleWith` / `meta.excludes` replace fx
usage of `meta.adapter`; scoped constraints via includes-chain ancestry;
`exclude`, `substitute`, `filterBy` constructors with subtree/global
variants
- **Includes chain provenance** — `chain-push`/`chain-pop` effects
replace `__parent` string tracking; observable by any handler for
diagrams, scope visualization, composable analysis
- **Module wiring** — `{ lib, den }` only, no `init` function, barrel
`default.nix`; nix-effects accessed as `den.lib.fx`
- **`den.fxPipeline` option** — defaults to `true`; legacy tests using
`resolve.withAdapter` run with `fxPipeline = false`

```
nix/lib/aspects/fx/
  aspect.nix        — aspectToEffect compiler
  pipeline.nix      — mkPipeline, defaultHandlers, fxResolve
  identity.nix      — path/identity utilities, collectPathsHandler, pathSetHandler
  constraints.nix   — exclude, substitute, filterBy constructors
  includes.nix      — includeIf conditional inclusion
  trace.nix         — structuredTraceHandler, tracingHandler
  handlers/
    include.nix     — emit-include handler (owns recursion)
    transition.nix  — into-transition handler (scope.stateful)
    ctx.nix         — constantHandler, ctxSeenHandler
    tree.nix        — constraintRegistryHandler, chainHandler, classCollectorHandler
```

| Effect | Handler responsibility |
|---|---|
| `emit-class` | Accumulate modules by class |
| `emit-include` | Check constraints, recurse via `aspectToEffect` |
| `register-constraint` | Store in registry with scope/ownerChain |
| `check-constraint` | Query registry, first-registered-wins |
| `chain-push` / `chain-pop` | Track includes-path stack |
| `into-transition` | Walk context transitions with scoped handlers |
| `ctx-seen` | Dedup context stages |
| `resolve-complete` | Emit trace entries, accumulate paths |
| `get-path-set` | Return accumulated path set for `includeIf` guards |
| `<arg-name>` | `constantHandler` resumes with context value |

The type system operates at declaration time and cannot be gated on
`config.den.fxPipeline` without circular evaluation:

- `aspect-chain` in `constantHandler` — provider functions from
`providerFnType.merge` create `{ class, aspect-chain }` functors
- `options.nix` uses legacy `ctxApply` — `config.resolved` can't access
`config.den` without circularity
- Legacy adapter tests run with `fxPipeline = false`

- `refactor: replace _. alias with provides.` across all
aspect/output/template modules
- `feat: ci-fast recipe` using nix-eval-jobs for parallel test eval
- Test restructuring: `batteries/`, `context/`, `perf/`, `home-manager/`
subdirs flattened to `features/`
- Regression reproductions for issues denful#413, denful#423, denful#426, denful#437
- Consolidated design spec at `docs/design/fx-pipeline-spec.md`

- [x] `nix develop -c just ci ""` — 488/488 pass
- [x] `nix develop -c just ci-fast` — parallel eval, 488/488 pass
- [x] `nix flake check` — templates, packages, devShells all pass
- [x] Checkmate `system-agnostic` tests — 15/15 pass
- [x] Legacy tests with `fxPipeline = false` verify backward
compatibility

---------

Co-authored-by: Victor Borja <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants