mnemonica 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/.ai/ONBOARDING.md +1 -1
  2. package/.ai/PROTOTYPE-CHAIN.md +12 -2
  3. package/.ai/rules-async-constructors.md +81 -1
  4. package/.ai/rules-define-patterns.md +39 -0
  5. package/AGENTS.md +14 -1
  6. package/CONTRIBUTING.md +4 -18
  7. package/FOR_HUMANS.md +103 -11
  8. package/README.md +42 -7
  9. package/SKILL.md +7 -2
  10. package/build/api/errors/index.js +7 -5
  11. package/build/api/index.d.ts +1 -0
  12. package/build/api/index.js +2 -1
  13. package/build/api/types/InstanceCreator.js +16 -5
  14. package/build/api/types/Mnemosyne.d.ts +3 -14
  15. package/build/api/types/Mnemosyne.js +21 -8
  16. package/build/api/types/Props.js +1 -2
  17. package/build/api/types/TypeProxy.d.ts +1 -1
  18. package/build/api/types/TypeProxy.js +9 -9
  19. package/build/api/types/compileNewModificatorFunctionBody.js +3 -5
  20. package/build/api/types/index.d.ts +5 -0
  21. package/build/api/types/index.js +70 -31
  22. package/build/api/utils/index.d.ts +1 -0
  23. package/build/api/utils/index.js +13 -3
  24. package/build/descriptors/types/index.js +46 -2
  25. package/build/index.d.ts +6 -2
  26. package/build/index.js +18 -3
  27. package/build/types/index.d.ts +22 -4
  28. package/build/types/index.js +1 -1
  29. package/build/utils/parent.js +35 -5
  30. package/docs/async-constructors.md +1 -1
  31. package/docs/empathy-in-ai.md +2 -3
  32. package/docs/prototype-chain.md +4 -0
  33. package/docs/typed-lookup.md +19 -2
  34. package/package.json +8 -8
  35. package/src/api/errors/index.ts +10 -4
  36. package/src/api/index.ts +2 -8
  37. package/src/api/types/InstanceCreator.ts +28 -6
  38. package/src/api/types/Mnemosyne.ts +34 -15
  39. package/src/api/types/Props.ts +4 -4
  40. package/src/api/types/TypeProxy.ts +10 -9
  41. package/src/api/types/compileNewModificatorFunctionBody.ts +12 -4
  42. package/src/api/types/index.ts +122 -65
  43. package/src/api/utils/index.ts +27 -9
  44. package/src/descriptors/types/index.ts +81 -3
  45. package/src/index.ts +66 -0
  46. package/src/types/index.ts +105 -10
  47. package/src/utils/parent.ts +48 -4
package/.ai/ONBOARDING.md CHANGED
@@ -106,7 +106,7 @@ require user approval first.
106
106
 
107
107
  ```
108
108
  src/
109
- ├── index.ts # Main exports: define, lookup, apply, call, bind
109
+ ├── index.ts # Main exports: define, lazy, lookup, apply, call, bind
110
110
  ├── types/index.ts # TypeScript type definitions
111
111
  ├── constants/ # Symbols and default options
112
112
  ├── descriptors/ # Type collection and error definitions
@@ -21,7 +21,7 @@ superadmin
21
21
  └── root Mnemosyne Proxy
22
22
  └── Mnemonica instance
23
23
  └── Mnemonica.prototype
24
- └── uranus
24
+ └── ancestor
25
25
  ```
26
26
 
27
27
  `SuperAdminMemory`, `AdminMemory`, and `UserMemory` are the **memory layers**. Only `UserMemory`’s parent is the real `Mnemosyne` constructor result wrapped in a Proxy. The deeper memory layers are plain objects that play the same role.
@@ -86,6 +86,16 @@ This is why the same constructor function can be reused across multiple type def
86
86
 
87
87
  `getProps(instance)` walks the prototype chain from the instance until it finds the first object with a `WeakMap` entry. That is always the instance’s own memory layer. `parent(instance)` reads `__parent__` from that props object; it is the `existentInstance` passed to `InstanceCreator`.
88
88
 
89
+ ## Why the memory layer is the `WeakMap` key
90
+
91
+ **Why not key props on `ModificatorType.prototype`?** It would save one hop in the walk, but that object is user-facing: it receives the captured user-prototype descriptors during construction and is reachable via `instance.constructor.prototype`. The memory layer is created fresh per construction, is never handed out as a value, and its only own property (`constructor`) is a non-configurable getter. Keying the props by an object identity that userland cannot forge or pollute keeps the metadata lookup deterministic no matter what user code does to instances or prototypes.
92
+
93
+ **This is not a security boundary.** JavaScript within a realm offers none: a determined user with `Reflect` can reach the memory layer (`Reflect.getPrototypeOf(instance.constructor.prototype)`) and even change its prototype. The design goal is determinism under *accidental* interference — the `WeakMap` entry is keyed by identity rather than by any name or property another library could collide with, and the `constructor` getter cannot be redefined. (This was historically nicknamed "MITM resistance": forgery and pollution of the metadata lookup are structurally deflected; deliberate reflection is not. Security tooling would rightly not count this as a defense.)
94
+
95
+ **Do not re-add keying by instance or creator.** Props were historically keyed by the `InstanceCreator` context, then by the instance itself. Both writes were proven unread (sentinel experiment: both suites green with garbage stored in the entry) and removed. The memory layer is the only props key; `setProps` additions are keyed by the props object itself.
96
+
97
+ **The `_getProps` guard.** The chain walk stops with `undefined` as soon as the next level’s `constructor` differs from the original object’s; the memory layer’s own getter keeps constructors aligned across its level, so the walk survives it. Consequence: `getProps(Object.create(instance))` resolves to the parent instance’s props — derived objects share the nearest ancestor’s memory layer.
98
+
89
99
  ## `_setSelf` and async construction
90
100
 
91
101
  `_setSelf(instance)` is called at the end of successful construction. It adds one more getter to the props object:
@@ -94,7 +104,7 @@ This is why the same constructor function can be reused across multiple type def
94
104
  __self__: () => instance
95
105
  ```
96
106
 
97
- Then it stores the props object in the `WeakMap` keyed by the instance itself. This solves the async-constructor problem.
107
+ This is what solves the async-constructor problem: the props object is already reachable from the instance through the prototype-chain walk, so the `__self__` getter can serve as a completion marker.
98
108
 
99
109
  When a constructor returns a Promise, the initial value of `new Constructor()` is that Promise. `makeAwaiter` waits for resolution, then checks:
100
110
 
@@ -266,7 +266,87 @@ Tests live in `test_async/index.js` and run via `npm run test:async_init`.
266
266
  - `src/api/types/index.ts` — `Symbol.hasInstance` on `TypeDescriptor.prototype`
267
267
  - `src/api/types/InstanceCreator.ts` — async routing via `makeAwaiter`
268
268
 
269
+ ### Historical examples (from the unshipped `test_async` suite)
270
+
271
+ `test_async/index.js` is a historical record and is **not part of the
272
+ published package**. The scenarios it covered are preserved here.
273
+
274
+ Async class constructors that resolve `this` keep fields and chain identity:
275
+
276
+ ```js
277
+ const AsyncInitParent = define('AsyncInitParent', class {
278
+ parentField = 'parent-field';
279
+ constructor () {
280
+ return new Promise((resolve) => {
281
+ setTimeout(() => resolve(this), 10);
282
+ });
283
+ }
284
+ });
285
+
286
+ const AsyncInitChild = AsyncInitParent.define('AsyncInitChild', class {
287
+ childField = 'child-field';
288
+ constructor () {
289
+ return new Promise((resolve) => {
290
+ setTimeout(() => resolve(this), 10);
291
+ });
292
+ }
293
+ });
294
+
295
+ const parent = await new AsyncInitParent();
296
+ const child = await parent.AsyncInitChild();
297
+ child.parentField; // 'parent-field' — inherited through the async chain
298
+ child.childField; // 'child-field'
299
+ ```
300
+
301
+ An async constructor that resolves `undefined` throws by default;
302
+ `awaitReturn: false` disables the guard:
303
+
304
+ ```js
305
+ const AsyncInitWOReturn = define('AsyncInitWOReturn', class {
306
+ constructor () {
307
+ return new Promise((resolve) => {
308
+ setTimeout(() => resolve(), 10); // resolves undefined → throws
309
+ });
310
+ }
311
+ });
312
+
313
+ define('AsyncInitWOReturnNAR', class {
314
+ constructor () {
315
+ return new Promise((resolve) => {
316
+ setTimeout(() => resolve(), 10);
317
+ });
318
+ }
319
+ }, { awaitReturn: false }); // resolves undefined → no throw
320
+ ```
321
+
322
+ A pre-existing class hierarchy can serve as the construct handler, at the
323
+ top level or as a subtype:
324
+
325
+ ```js
326
+ class AsyncInitBaseClass {
327
+ baseField = 'base-field';
328
+ }
329
+
330
+ class AsyncInitExtendedClass extends AsyncInitBaseClass {
331
+ extField = 'ext-field';
332
+ constructor () {
333
+ super();
334
+ return new Promise((resolve) => {
335
+ setTimeout(() => resolve(this), 10);
336
+ });
337
+ }
338
+ }
339
+
340
+ // top level: instanceof works against BOTH the mnemonica type
341
+ // and the original classes
342
+ const AsyncInitPreExtended = define('AsyncInitPreExtended', AsyncInitExtendedClass);
343
+
344
+ // as a subtype of a root type (AsyncInitRooted, defined as above):
345
+ // fields are inherited and mnemonica instanceof works, but plain JS
346
+ // instanceof against the original classes is broken
347
+ const AsyncInitRootedSub = AsyncInitRooted.define('AsyncInitRootedSub', AsyncInitExtendedClass);
348
+ ```
349
+
269
350
  ### Related
270
351
 
271
- - [`test_async/index.js`](../test_async/index.js) — test suite covering async initialization scenarios
272
352
  - [TC39 proposal-async-init issue #3](https://github.com/tc39/proposal-async-init/issues/3) — language-level discussion of the same problem
@@ -63,6 +63,45 @@ define('Parent.Child', function (this: Child, data: Data) {
63
63
  });
64
64
  ```
65
65
 
66
+ ## Lazy definitions
67
+
68
+ Use `.lazy()` when the constructor must be resolved through a getter — for
69
+ example, to break a circular dependency or to defer constructor selection until
70
+ definition time. `.define()` no longer accepts an anonymous function as its
71
+ first argument; that form has moved to `.lazy()`.
72
+
73
+ ### Unnamed (name from returned constructor)
74
+ ```typescript
75
+ const LazyType = define('RootType', function () {})
76
+ .lazy(() => function LazySubType(this: LazySubType, data: LazyData) {
77
+ Object.assign(this, data);
78
+ });
79
+ ```
80
+
81
+ ### Named (explicit type name)
82
+ ```typescript
83
+ const NamedLazy = RootType.lazy('NamedLazy', () => function (data: NamedData) {
84
+ Object.assign(this, data);
85
+ });
86
+ ```
87
+
88
+ ### Free-function form
89
+ ```typescript
90
+ import { lazy } from 'mnemonica';
91
+
92
+ const LazyRoot = lazy('LazyRoot', () => class LazyRoot {
93
+ field: string;
94
+ constructor(field: string) {
95
+ this.field = field;
96
+ }
97
+ });
98
+ ```
99
+
100
+ The getter is called once at definition time. The returned constructor is
101
+ registered exactly like a constructor passed directly to `define()`, and the
102
+ resulting type supports `.define()`, `.lazy()`, `.lookup()`, and subtype
103
+ chaining.
104
+
66
105
  ## Export root constructors only when needed; never export subtypes
67
106
 
68
107
  Subtypes live on the parent constructor and on parent instances. Exporting a subtype splits the Trie and usually loses the parent part of the chain.
package/AGENTS.md CHANGED
@@ -229,7 +229,7 @@ The library makes heavy use of JavaScript Proxies:
229
229
 
230
230
  ### Internal Instance Properties
231
231
 
232
- Stored in a `WeakMap` keyed by the instance, not as own properties on the instance itself. Access via `getProps(instance)`. For the full property list (9 entries, with meanings) see the **Internal instance properties** table in [`README.md`](./README.md) — that table is the canonical reference.
232
+ Stored in a `WeakMap` keyed by the instance's **Mnemosyne memory layer** — the prototype object created per construction in `createInstanceModificator` — not as own properties on the instance itself. `_getProps` reaches it by walking the prototype chain from the instance. Access via `getProps(instance)`. For the full property list (9 entries, with meanings) see the **Internal instance properties** table in [`README.md`](./README.md) — that table is the canonical reference.
233
233
 
234
234
  `setProps(instance, values)` is the mutating counterpart; rarely needed and considered advanced.
235
235
 
@@ -308,6 +308,19 @@ If a comment becomes technically inaccurate after a change, update it rather tha
308
308
 
309
309
  See [`.ai/rules-testing.md`](./.ai/rules-testing.md) for full coverage requirements and patterns. 100% required on both Mocha and Jest. Must run `npm run test:cov` before completing any task.
310
310
 
311
+ ## Before Saying a Task Is Done
312
+
313
+ When a task uses a TODO list, the list is part of the deliverable:
314
+
315
+ 1. **Before reporting completion, update the TODO list** so every item is
316
+ marked done (struck through). A stale `in_progress` item reads as
317
+ unfinished work even when the work itself is complete.
318
+ 2. **Only mark items done that are verified** — tests green, coverage at
319
+ 100% on both suites, `lint:md` clean where docs changed. Never mark an
320
+ item done just to tidy the list.
321
+ 3. **When the task concludes, wipe the TODO list.** A concluded task leaves
322
+ no list behind; the next task starts fresh.
323
+
311
324
  ## Common Patterns
312
325
 
313
326
  ### Adding Types
package/CONTRIBUTING.md CHANGED
@@ -116,21 +116,7 @@ links and broken anchors across all Markdown files in the repo.
116
116
 
117
117
  ## Releasing
118
118
 
119
- ### 1. Update the changelog
120
-
121
- In `CHANGELOG.md`, move everything under `## [Unreleased]` into a
122
- new versioned section:
123
-
124
- ```markdown
125
- ## [1.0.1] - 2026-05-22
126
-
127
- ### Fixed
128
- - ...
129
- ```
130
-
131
- Leave a fresh empty `## [Unreleased]` block at the top for the next cycle.
132
-
133
- ### 2. Bump the version
119
+ ### 1. Bump the version
134
120
 
135
121
  ```bash
136
122
  npm version patch # 1.0.0 → 1.0.1
@@ -140,7 +126,7 @@ npm version patch # 1.0.0 → 1.0.1
140
126
  `npm version` updates `package.json` and creates a git commit + tag
141
127
  (`v1.0.1`) automatically. Do not edit `package.json` by hand for this.
142
128
 
143
- ### 3. Verify
129
+ ### 2. Verify
144
130
 
145
131
  ```bash
146
132
  npm run verify # build + lint:check
@@ -150,14 +136,14 @@ npm run lint:md # no dead links or broken anchors
150
136
 
151
137
  All three must pass before publishing.
152
138
 
153
- ### 4. Inspect the tarball
139
+ ### 3. Inspect the tarball
154
140
 
155
141
  ```bash
156
142
  npm pack --dry-run
157
143
  ```
158
144
 
159
145
  The tarball must include: `build/`, `module/`, `src/`, `docs/`, `.ai/`,
160
- `examples/`, `README.md`, `FOR_HUMANS.md`, `AGENTS.md`, `SKILL.md`,
146
+ `README.md`, `FOR_HUMANS.md`, `AGENTS.md`, `SKILL.md`,
161
147
  `CONTRIBUTING.md`, `LICENSE`.
162
148
 
163
149
  It must **not** include: `test/`, `test-jest/`, `test-ts/`, `test_async/`,
package/FOR_HUMANS.md CHANGED
@@ -122,7 +122,7 @@ The key inversion: `new` is called on the **parent instance** (`alice`), not on
122
122
  - **Curious about the theory?** Read [`README.md`](./README.md) — the HoTT framing, the Trie observation, the pipeline pattern, the AI-agent angle.
123
123
  - **Want examples you can run?** See the [Examples](#examples) section below.
124
124
  - **Going deeper on philosophy?** Read [`docs/purpose.md`](./docs/purpose.md).
125
- - **Background reading:** [Inheritance in JavaScript: Factory of Constructors with Prototype Chain](https://github.com/mythographica/stash/blob/master/inheritance.md) · [Architecture of Prototype Inheritance in JavaScript](https://dev.to/wentout/architecture-of-prototype-inheritance-in-javascript-ce6) · [Dead Simple type checker for JavaScript](https://dev.to/wentout/dead-simple-type-checker-for-javascript-4l40)
125
+ - **Background reading:** [Inheritance in JavaScript: Factory of Constructors with Prototype Chain](https://github.com/mythographica/stash/blob/master/inheritance.md) · [Architecture of Prototype Inheritance in JavaScript](https://github.com/mythographica/stash/blob/master/inheritance_architecture.md) · [Dead Simple type checker for JavaScript](https://github.com/mythographica/typologica)
126
126
 
127
127
  ---
128
128
 
@@ -493,10 +493,11 @@ const AsyncTypeNoReturn = define('AsyncType', async function () {
493
493
  | I want to... | Use |
494
494
  |---|---|
495
495
  | Define a type | `define('Name', ctor)` |
496
+ | Define a type lazily | `lazy('Name', () => ctor)` or `Type.lazy(() => ctor)` |
496
497
  | Create from instance | `new instance.SubType(args)` |
497
- | Look up a type | `lookup('Name')` or `lookup('Name')` |
498
+ | Look up a type | `lookup('Name')` or `Type.lookup('Path')` |
498
499
  | Read construction history | `getProps(instance)` |
499
- | Get parent instance | `utils.parent(instance)` or `utils.parent(instance, 'TypeName')` |
500
+ | Get parent instance | `utils.parent(instance)`, `utils.parent(instance, 'TypeName')` or `utils.parent(instance, 'Root.Parent')` |
500
501
  | Flatten to plain object | `utils.extract(instance)` |
501
502
  | Add lifecycle hooks | `type.registerHook('postCreation', cb)` |
502
503
  | Use classes (requires Tactica) | see [`docs/decorate.md`](./docs/decorate.md) |
@@ -517,10 +518,44 @@ const MyType = define('MyType', function (data) {
517
518
  ```
518
519
 
519
520
  **Parameters:**
520
- - `typeName` (string): Name of the type (optional if using factory function)
521
+ - `typeName` (string): Name of the type (optional if using factory function). Must be non-empty, start with an uppercase letter, and must not be one of the reserved names `Mnemonica` or `Mnemosyne`. May be a nested path (`'Parent.Child'`) to define a subtype under an existing type.
521
522
  - `constructHandler` (Function): Constructor function
522
523
  - `config` (object, optional): Configuration options
523
524
 
525
+ #### `lazy(typeName?, getter, config?)`
526
+
527
+ Defines a type whose constructor is resolved through a zero-arg getter. Useful
528
+ for breaking circular dependencies or deferring constructor selection until
529
+ definition time. The resulting type behaves like a type created with `define()`.
530
+
531
+ ```js
532
+ const { lazy } = require('mnemonica');
533
+
534
+ // unnamed: type name is taken from the returned constructor's .name
535
+ const LazyType = lazy(() => function LazyType(data) {
536
+ Object.assign(this, data);
537
+ });
538
+
539
+ // named: explicit type name
540
+ const NamedType = lazy('NamedType', () => function (data) {
541
+ Object.assign(this, data);
542
+ });
543
+
544
+ // chainable on constructors and collections
545
+ const SubType = MyType.lazy('SubType', () => function (data) {
546
+ this.extra = data;
547
+ });
548
+ ```
549
+
550
+ **Parameters:**
551
+ - `typeName` (string, optional): Name of the type. If omitted, the name is taken from the getter's returned constructor.
552
+ - `getter` (Function): Zero-arg function returning the constructor.
553
+ - `config` (object, optional): Configuration options
554
+
555
+ **Note:** the getter is invoked **once at definition time** (to determine the
556
+ type name, class mode, and prototype) and then again on every construction.
557
+ Keep it free of side effects that must not run at `define()` time.
558
+
524
559
  #### `lookup(typeNestedPath)`
525
560
 
526
561
  Looks up a type by its nested path.
@@ -531,6 +566,11 @@ const SomeType = lookup('SomeType');
531
566
  const SomeNestedType = lookup('SomeType.SomeNestedType');
532
567
  ```
533
568
 
569
+ Path segments may be separated by `.`, `/`, or `:`, and whitespace inside the
570
+ path is ignored — `lookup('A/B')`, `lookup('A:B')`, and `lookup(' A . B ')`
571
+ all resolve like `lookup('A.B')`. The same path forms work everywhere a
572
+ nested type path is accepted (`define()`, `utils.parent()`, hooks, etc.).
573
+
534
574
  #### `lookup(typeNestedPath)`
535
575
 
536
576
  Type-safe lookup function. Requires a `TypeRegistry` augmentation — hand-written for small projects or generated by [`@mnemonica/tactica`](https://www.npmjs.com/package/@mnemonica/tactica). See [`docs/typed-lookup.md`](./docs/typed-lookup.md) for both paths side by side.
@@ -619,6 +659,7 @@ For advanced TypeScript usage, the following types are exported from `mnemonica`
619
659
  | Type | Description | Usage |
620
660
  |------|-------------|-------|
621
661
  | `IDEF<T>` | Base constructor function type | `define('Name', fn: IDEF<MyType>)` |
662
+ | `LazyDef<T>` | Zero-arg getter returning a constructor | `lazy('Name', fn: LazyDef<MyType>)` |
622
663
  | `MnemonicaInstance` | Optional helper interface | Can be used when attaching the legacy instance methods to your own prototype |
623
664
  | `TypeClass` | Base type constructor | `const MyType: TypeClass = define(...)` |
624
665
  | `DecoratedClass<T>` | Decorated class type | `@decorate() class MyClass {}` (see [`docs/decorate.md`](./docs/decorate.md)) |
@@ -732,6 +773,11 @@ myCollection.registerHook('preCreation', (opts) => {
732
773
  const FoundType = myCollection.lookup('MyType');
733
774
  ```
734
775
 
776
+ Only known option keys are applied to a collection: unknown keys are
777
+ silently dropped, and a value whose type does not match the option's default
778
+ falls back to that default. Note that `asClass` is a per-`define()` option —
779
+ it is not part of the collection-level defaults and is ignored here.
780
+
735
781
  #### `getProps(instance)` / `setProps(instance, values)`
736
782
 
737
783
  Get or set internal properties of an instance.
@@ -742,10 +788,12 @@ const { getProps, setProps } = require('mnemonica');
742
788
  const props = getProps(instance);
743
789
  console.log(props.__type__, props.__args__);
744
790
 
745
- // Set properties
746
- setProps(instance, { __timestamp__: Date.now() });
791
+ // Set custom properties
792
+ setProps(instance, { myFlag: true });
747
793
  ```
748
794
 
795
+ `setProps` only accepts non-reserved names: the internal `__…__` properties (`__type__`, `__args__`, `__timestamp__`, etc.) are filtered out and cannot be overwritten. Also note that `getProps` returns the *live* internal object when no custom properties are set — mutating the result mutates the instance's construction record. Once `setProps` has been used, `getProps` returns a merged copy instead.
796
+
749
797
  ---
750
798
 
751
799
  ### Instance Methods
@@ -792,13 +840,26 @@ const pickedArray = utils.pick(instance, ['email', 'password']);
792
840
 
793
841
  #### `utils.parent(instance, constructorName?)`
794
842
 
795
- Gets the parent instance. If `constructorName` is provided, walks up the chain.
843
+ Gets the parent instance. If `constructorName` is provided, walks up the chain
844
+ and returns the nearest ancestor with that constructor name. The instance itself
845
+ is never a candidate — only ancestors are searched.
846
+
847
+ A **dotted path** (`'GrandParent.Parent'`) requires the segments to match
848
+ contiguously upwards: each leading segment must be the direct parent of the
849
+ instance matched by the next one. The return value is the instance matched by
850
+ the **last** segment. This disambiguates lineages where the same type name
851
+ appears more than once (possible with `strictChain: false` re-construction).
852
+ If no contiguous match exists, the result is `undefined`.
853
+
796
854
  The structural return type is `object | undefined`; a specific nominal parent
797
855
  type requires a `TypeRegistry` augmentation (see [`docs/typed-lookup.md`](./docs/typed-lookup.md)).
798
856
 
799
857
  ```ts
800
858
  const immediateParent = utils.parent(instance);
801
859
  const specificParent = utils.parent(instance, 'UserType'); // object | undefined
860
+ // lineage request → route → page → response:
861
+ const route = utils.parent(response, 'RequestData.RouteData'); // route instance
862
+ const nearest = utils.parent(response, 'RouteData'); // page's parent, as before
802
863
  ```
803
864
 
804
865
  #### `utils.clone(instance)`
@@ -891,7 +952,7 @@ explicit `<T>` cast is required for ordinary use.
891
952
  | `utils.fork(instance)` | `(this: object, ...args: unknown[]) => T` |
892
953
  | `utils.parent(instance, path?)` | `object \| undefined` |
893
954
  | `utils.sibling(instance)` | `SiblingAccessor` |
894
- | `utils.merge(A, B, ...args)` | `InstanceResult<Merge<B, A>, constructorOptions>` |
955
+ | `utils.merge(A, B, ...args)` | `InstanceResult<Merge<B, A>>` |
895
956
  | `utils.parse(instance)` | `Parsed<T>` |
896
957
  | `utils.toJSON(instance)` | `string` |
897
958
  | `utils.collectConstructors(instance, flat?)` | `(CallableFunction \| string)[]` |
@@ -948,7 +1009,7 @@ interface HookData {
948
1009
  args: unknown[]; // Arguments passed to constructor
949
1010
  existentInstance: object; // Parent instance
950
1011
  inheritedInstance: object; // New instance (postCreation only)
951
- throwModificationError(error: Error): void; // Throw error from hook
1012
+ throwModificationError(error: Error): void; // Throw error from hook (not available in preCreation)
952
1013
  }
953
1014
  ```
954
1015
 
@@ -961,6 +1022,13 @@ MyType.registerHook('postCreation', (hookData) => {
961
1022
 
962
1023
  **Note:** In preCreation hooks, `existentInstance` refers to the parent; in postCreation hooks, it refers to the instance used for inheritance.
963
1024
 
1025
+ **Error wrapping boundaries.** `preCreation` hooks do not receive
1026
+ `throwModificationError` — throw normally to abort construction; the error
1027
+ propagates unwrapped. The same is true for errors thrown by a lazy type's
1028
+ getter at setup and by a custom `ModificationConstructor` during prototype
1029
+ wiring: they propagate as-is. Only failures of the user constructor body are
1030
+ wrapped into mnemonica errored instances (when `blockErrors` is `true`).
1031
+
964
1032
  ---
965
1033
 
966
1034
  ### Error Handling
@@ -1014,6 +1082,10 @@ const { defineStackCleaner } = require('mnemonica');
1014
1082
  defineStackCleaner(/node_modules\/some-package/);
1015
1083
  ```
1016
1084
 
1085
+ Multiple cleaners may be registered; a stack line is removed if **any** of
1086
+ them matches. If cleaning would remove every line, the original stack is
1087
+ kept instead.
1088
+
1017
1089
  ---
1018
1090
 
1019
1091
  ### Symbols & Constants
@@ -1057,6 +1129,26 @@ define('SomeType', function () {}, {
1057
1129
  | `asClass` | `boolean` | `auto` | Force class mode detection. Usually auto-detected from constructor syntax. |
1058
1130
  | `ModificationConstructor` | `Function` | - | Custom constructor function for internal instance modification. |
1059
1131
 
1132
+ ### What `strictChain` actually guards
1133
+
1134
+ `strictChain` is checked at two independent points, and re-constructing a
1135
+ predecessor type on a deeper instance (`apply(deepInstance, AncestorType)`)
1136
+ requires **both** of them to be off:
1137
+
1138
+ 1. **Subtype resolution** checks the config of the **entity's type**: may this
1139
+ instance construct a subtype that is not its own direct subtype? With
1140
+ `strictChain: false`, the search walks up the parent chain and a subtype
1141
+ registered on any ancestor type becomes constructible
1142
+ (`Mnemosyne.prepareSubtypeForConstruction` → `findSubTypeFromParent`).
1143
+ 2. **Construction validation** checks the config of the **target type**: must
1144
+ the new instance's parent be an instance of the type's declared parent
1145
+ kind? With `strictChain: false`, a parent of a different kind is accepted
1146
+ (`InstanceCreator.postProcessing`).
1147
+
1148
+ This is how one lineage can end up carrying the same type name more than
1149
+ once — which is exactly the case `utils.parent(instance, 'A.B')` dotted
1150
+ paths were made for.
1151
+
1060
1152
  ### Instance Method Opt-In
1061
1153
 
1062
1154
  Starting from v1.0.6 instance methods are **not** exposed on instances by default. Use the standalone `utils` export or attach the methods to your constructor's prototype before calling `define()`:
@@ -1272,8 +1364,8 @@ rules live in [AGENTS.md](AGENTS.md).
1272
1364
 
1273
1365
  **Related reading:**
1274
1366
  - [Inheritance in JavaScript: Factory of Constructors with Prototype Chain](https://github.com/mythographica/stash/blob/master/inheritance.md)
1275
- - [Architecture of Prototype Inheritance in JavaScript](https://dev.to/wentout/architecture-of-prototype-inheritance-in-javascript-ce6)
1276
- - [Dead Simple type checker for JavaScript](https://dev.to/wentout/dead-simple-type-checker-for-javascript-4l40)
1367
+ - [Architecture of Prototype Inheritance in JavaScript](https://github.com/mythographica/stash/blob/master/inheritance_architecture.md)
1368
+ - [Dead Simple type checker for JavaScript](https://github.com/mythographica/typologica)
1277
1369
 
1278
1370
  ---
1279
1371
 
package/README.md CHANGED
@@ -203,13 +203,13 @@ These terms are used throughout the codebase and documentation with precise mean
203
203
  | **Trie node** | A type definition created by `define()`. Has a name, a constructor handler, a prototype, and a Map of subtypes. |
204
204
  | **Trie edge** | A parent-child relationship between two nodes. Created by `ParentType.define('ChildType', ...)`. |
205
205
  | **Trie path** | A sequence of edges from the root to a specific node. `UserType → AdminType → SuperAdminType` is a path. |
206
- | **Construction context** | The 9-tuple stored per instance: `__type__`, `__parent__`, `__args__`, `__timestamp__`, `__creator__`, `__collection__`, `__subtypes__`, `__proto_proto__`, `__stack__`. Readable via `getProps(instance)`. |
206
+ | **Construction context** | The construction record stored per instance (10 props): `__type__`, `__parent__`, `__args__`, `__timestamp__`, `__creator__`, `__collection__`, `__subtypes__`, `__proto_proto__`, `__stack__`, `__self__`. Readable via `getProps(instance)`. |
207
207
  | **Instance-level inheritance** | The mechanism where `new alice.Employee()` creates a prototype chain whose immediate parent is the **specific instance** `alice`, not a shared `Employee.prototype`. |
208
208
  | **Nominal type** | A type whose identity is determined by its constructor function reference, not by its property shape. Two types with identical fields but different constructors are different types. |
209
209
  | **Mnemosyne** | The prototype object inserted between `ModificatorType.prototype` and the parent instance. Stores internal construction context. User-facing instance methods (`extract`, `pick`, `parent`, etc.) are available through standalone `utils.*` or by explicit prototype attachment. |
210
210
  | **TypeProxy** | The constructor-like object returned by `define()`. Wraps the raw constructor with `.define()`, `.lookup()`, `.registerHook()` methods. |
211
211
  | **ModificatorType** | The actual constructor function used for `new` calls. Its prototype is linked to Mnemosyne, which is linked to the parent instance. |
212
- | **WeakMap key** | Internal properties are stored in a `WeakMap` keyed by the **Mnemosyne object**, not the instance itself. This keeps instance enumeration clean and shares metadata across instances of the same type. |
212
+ | **WeakMap key** | Internal properties are stored in a `WeakMap` keyed by the **Mnemosyne object**, not the instance itself. This keeps instance enumeration clean; a fresh Mnemosyne object is created per construction, so metadata is strictly per-instance. |
213
213
 
214
214
  For the full construction pipeline from `define()` through `TypeProxy` → `InstanceCreator` → `Mnemosyne` → instance, see [`.ai/theory-of-operations.md`](./.ai/theory-of-operations.md).
215
215
 
@@ -314,6 +314,7 @@ This is the primitive that is currently missing in the Node.js ecosystem for bui
314
314
  | Function | Purpose | Source |
315
315
  |---|---|---|
316
316
  | `define(name, ctor, config?)` | Create a type at module scope or as a subtype | [`src/index.ts`](./src/index.ts) |
317
+ | `lazy(name?, getter, config?)` | Create a type from a zero-arg getter that returns the constructor | [`src/index.ts`](./src/index.ts) |
317
318
  | `lookup(path)` | Type-safe runtime lookup — requires `TypeRegistry` augmentation (by hand or via [`@mnemonica/tactica`](https://www.npmjs.com/package/@mnemonica/tactica); see [`docs/typed-lookup.md`](./docs/typed-lookup.md)) | [`src/index.ts`](./src/index.ts) |
318
319
  | `lookup(path)` | Untyped runtime lookup | [`src/index.ts`](./src/index.ts) |
319
320
  | `apply(parent, Ctor, args)` / `call(...)` / `bind(...)` | Apply a constructor to a parent instance | [`src/index.ts`](./src/index.ts) |
@@ -323,6 +324,39 @@ This is the primitive that is currently missing in the Node.js ecosystem for bui
323
324
  | `registerHook(Ctor, type, cb)` | Register hook on a specific constructor | [`src/index.ts`](./src/index.ts) |
324
325
  | `defaultTypes` | The default collection — has its own `.registerHook()` for collection-wide hooks | [`src/index.ts`](./src/index.ts) |
325
326
 
327
+ ### Lazy type definitions
328
+
329
+ In addition to `define()`, mnemonica provides `.lazy()` for cases where the
330
+ constructor must be resolved through a getter — for example, to break a
331
+ circular dependency or to defer constructor selection until definition time.
332
+
333
+ ```typescript
334
+ const User = define('User', function (data: { name: string }) {
335
+ this.name = data.name;
336
+ });
337
+
338
+ // unnamed: type name is taken from the returned constructor's .name
339
+ const Admin = User.lazy(() => class Admin {
340
+ role: string;
341
+ constructor(role: string) {
342
+ this.role = role;
343
+ }
344
+ });
345
+
346
+ // named: explicit type name
347
+ const Guest = User.lazy('Guest', () => function (this: Guest, token: string) {
348
+ this.token = token;
349
+ });
350
+
351
+ const admin = new user.Admin('root');
352
+ ```
353
+
354
+ `.lazy()` is chainable on constructors and collections, available as a free
355
+ `lazy(...)` export, and supports an explicit-source form
356
+ `lazy(source, name?, getter, config?)`. The resulting type participates in the
357
+ same registry, `.lookup()`, and subtype chaining as a type created with
358
+ `.define()`.
359
+
326
360
  ### Instance methods
327
361
 
328
362
  Starting from v1.0.6 these convenience methods are **no longer auto-injected** on every instance. Use the standalone utilities from `utils`:
@@ -385,6 +419,7 @@ Hook data shape: `hooksOpts<P, T>` in [`src/types/index.ts`](./src/types/index.t
385
419
  | `__subtypes__` | Map of available subtypes for this instance |
386
420
  | `__proto_proto__` | The prototype object used during construction |
387
421
  | `__stack__` | Construction stack trace (only if `submitStack: true`) |
422
+ | `__self__` | The instance this record belongs to — installed separately after construction, because the instance does not exist yet when the other props are written. When repeated `getPrototypeOf` hops have lost track of where you are in the chain, `__self__` tells you. Also used as the async completion marker (`makeAwaiter`) and the fork self-call detector |
388
423
 
389
424
  Full shape in [`src/types/index.ts`](./src/types/index.ts) (`InstanceInternalProps`).
390
425
 
@@ -402,16 +437,16 @@ new instance.SubType(args)
402
437
  InstanceCreator ← validates parent, resolves TypeDef
403
438
  │
404
439
  ▼
405
- preCreation hooks ← may throw → creationError hooks fire instead
440
+ preCreation hooks ← may throw → construction aborts, the error propagates (no creationError hooks)
406
441
  │
407
442
  ▼
408
- Object.create(existentInstance) ← prototype IS the parent instance
443
+ Mnemosyne memory layer created, proto-linked to the parent instance
409
444
  │
410
445
  ▼
411
- constructHandler.call(newObj, args) ← user constructor runs
446
+ WeakMap.set(memoryLayer, internalProps) ← __type__, __parent__, __args__, __timestamp__, ...
412
447
  │
413
448
  ▼
414
- WeakMap.set(newObj, internalProps) ← __type__, __parent__, __args__, __timestamp__, ...
449
+ constructHandler.call(newObj, args) ← user constructor runs
415
450
  │
416
451
  ▼
417
452
  postCreation hooks
@@ -420,7 +455,7 @@ new instance.SubType(args)
420
455
  return newObj
421
456
  ```
422
457
 
423
- `preCreation` fires before `Object.create`; `postCreation` fires after the WeakMap is written. If the user constructor throws, `creationError` fires and the instance is not returned. The object carries none of the internal props as own properties — they live in the WeakMap, readable via `getProps`.
458
+ `preCreation` fires before the memory layer is created; `postCreation` fires after the user constructor runs. If the user constructor throws, `creationError` fires and the instance is not returned. The object carries none of the internal props as own properties — they live in the WeakMap, readable via `getProps`.
424
459
 
425
460
  See [`src/api/types/InstanceCreator.ts`](./src/api/types/InstanceCreator.ts) and [`src/api/types/TypeProxy.ts`](./src/api/types/TypeProxy.ts).
426
461
 
package/SKILL.md CHANGED
@@ -40,13 +40,18 @@ When the task involves adding or modifying a type definition:
40
40
  - Free `lookup()` on a builder project? Use the one-line `RegistryOf` bridge — see [docs/typed-lookup.md](./docs/typed-lookup.md).
41
41
  - Using tactica / `@decorate()`? Does `.tactica/types.ts` need updating? Is `lookup('MyType')` properly typed? See [tactica-deep-dive.md](./docs/tactica-deep-dive.md)
42
42
 
43
- 3. **Test both success and error paths**
43
+ 3. **If the constructor needs a getter**, use `.lazy()`
44
+ - `.define()` no longer accepts an anonymous first-argument function.
45
+ - Use `Type.lazy('Name', () => Constructor)` or the free `lazy(...)` export.
46
+ - See [rules-define-patterns.md](.ai/rules-define-patterns.md)
47
+
48
+ 4. **Test both success and error paths**
44
49
  - Mocha test in `test/` for runtime behavior
45
50
  - Jest test in `test-jest/` for type coverage
46
51
  - Error path: test `ALREADY_DECLARED`, `WRONG_MODIFICATION_PATTERN`
47
52
  - See [rules-testing.md](.ai/rules-testing.md)
48
53
 
49
- 4. **Run coverage before completing**
54
+ 5. **Run coverage before completing**
50
55
  - `npm run test:cov` (Mocha + build)
51
56
  - `npm run test:jest:cov` (Jest on TypeScript source)
52
57