mnemonica 1.2.0 → 1.2.3

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 (53) hide show
  1. package/.ai/ONBOARDING.md +1 -1
  2. package/.ai/PROTOTYPE-CHAIN.md +15 -3
  3. package/.ai/rules-async-constructors.md +81 -1
  4. package/.ai/rules-define-patterns.md +39 -0
  5. package/.ai/rules-error-system.md +10 -0
  6. package/.ai/rules-instance-methods.md +1 -1
  7. package/AGENTS.md +14 -1
  8. package/CONTRIBUTING.md +4 -18
  9. package/FOR_HUMANS.md +128 -23
  10. package/README.md +44 -9
  11. package/SKILL.md +7 -2
  12. package/build/api/errors/exceptionConstructor.js +20 -47
  13. package/build/api/errors/index.js +7 -5
  14. package/build/api/errors/throwModificationError.js +26 -61
  15. package/build/api/index.d.ts +1 -0
  16. package/build/api/index.js +2 -1
  17. package/build/api/types/InstanceCreator.js +20 -5
  18. package/build/api/types/Mnemosyne.d.ts +3 -14
  19. package/build/api/types/Mnemosyne.js +21 -8
  20. package/build/api/types/Props.js +24 -11
  21. package/build/api/types/TypeProxy.d.ts +1 -1
  22. package/build/api/types/TypeProxy.js +9 -9
  23. package/build/api/types/compileNewModificatorFunctionBody.js +3 -5
  24. package/build/api/types/index.d.ts +5 -0
  25. package/build/api/types/index.js +70 -31
  26. package/build/api/utils/index.d.ts +1 -0
  27. package/build/api/utils/index.js +13 -3
  28. package/build/descriptors/types/index.js +46 -2
  29. package/build/index.d.ts +6 -2
  30. package/build/index.js +18 -3
  31. package/build/types/index.d.ts +31 -8
  32. package/build/types/index.js +1 -1
  33. package/build/utils/parent.js +35 -5
  34. package/docs/async-constructors.md +3 -1
  35. package/docs/empathy-in-ai.md +2 -3
  36. package/docs/prototype-chain.md +4 -0
  37. package/docs/typed-lookup.md +19 -2
  38. package/package.json +8 -8
  39. package/src/api/errors/exceptionConstructor.ts +40 -83
  40. package/src/api/errors/index.ts +10 -4
  41. package/src/api/errors/throwModificationError.ts +64 -104
  42. package/src/api/index.ts +2 -8
  43. package/src/api/types/InstanceCreator.ts +42 -6
  44. package/src/api/types/Mnemosyne.ts +34 -15
  45. package/src/api/types/Props.ts +57 -22
  46. package/src/api/types/TypeProxy.ts +10 -9
  47. package/src/api/types/compileNewModificatorFunctionBody.ts +12 -4
  48. package/src/api/types/index.ts +122 -65
  49. package/src/api/utils/index.ts +27 -9
  50. package/src/descriptors/types/index.ts +81 -3
  51. package/src/index.ts +66 -0
  52. package/src/types/index.ts +120 -15
  53. 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.
@@ -84,7 +84,19 @@ This is why the same constructor function can be reused across multiple type def
84
84
  - `__proto_proto__`
85
85
  - `__stack__`
86
86
 
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`.
87
+ `getProps(instance)` first checks for a record keyed by the object itself (see the error-props note below), then walks the prototype chain from the instance until it finds the first object with a `WeakMap` entry. For instances 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
+
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. For instances the memory layer is the only props key; `setProps` additions are keyed by the props object itself.
96
+
97
+ **Error props use a second key-space.** Error instances carry their data (`args`, `originalError`, `instance`, `exceptionReason`, `reasons`, `surplus`) in a record keyed by the error object itself, stored in a *separate* `WeakMap` (`__object_props__` in `Props.ts`) that `_getProps` consults before the chain walk. The two key-spaces must never share one map: memory layer objects are themselves keys in `__props__`, so a shared map would make `_getProps(memoryLayer)` return the layer's own record when the caller meant to reach the parent layer's one (this exact regression once silently bypassed the `prepareSubtypeForConstruction` early-exit and cost a coverage branch). `setProps` on an object with no chain record (plain objects, `Error` objects) creates such an object-keyed record on demand; on primitives it returns `false`.
98
+
99
+ **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.
88
100
 
89
101
  ## `_setSelf` and async construction
90
102
 
@@ -94,7 +106,7 @@ This is why the same constructor function can be reused across multiple type def
94
106
  __self__: () => instance
95
107
  ```
96
108
 
97
- Then it stores the props object in the `WeakMap` keyed by the instance itself. This solves the async-constructor problem.
109
+ 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
110
 
99
111
  When a constructor returns a Promise, the initial value of `new Constructor()` is that Promise. `makeAwaiter` waits for resolution, then checks:
100
112
 
@@ -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.
@@ -17,6 +17,16 @@ All errors extend from `BASE_MNEMONICA_ERROR` which provides:
17
17
  - Additional stack prepending
18
18
  - BaseStack preservation
19
19
 
20
+ ## Error Data Lives in Props, Not on the Error Object
21
+
22
+ Mnemonica errors are plain `Error` objects: only `.message` and `.stack` are
23
+ own properties. All mnemonica-specific data (`args`, `originalError`,
24
+ `instance`, `exceptionReason`, `reasons`, `surplus`, `error`) is stored in the
25
+ external props storage — read it with `getProps(error)`, write it with
26
+ `setProps(error, …)` (see `.ai/PROTOTYPE-CHAIN.md` for the two key-spaces).
27
+ Never read `error.originalError` etc. directly, and never add those fields back
28
+ onto the error object.
29
+
20
30
  ## constructError Factory
21
31
 
22
32
  ```typescript
@@ -30,7 +30,7 @@ utils.parent(instance, 'UserType');
30
30
  utils.fork(instance)(newArgs);
31
31
  utils.clone(instance);
32
32
  utils.sibling(instance);
33
- utils.exception(instance, new Error('oops'));
33
+ new utils.exception(instance, new Error('oops')); // must be called with `new`
34
34
  ```
35
35
 
36
36
  All utilities infer their type parameter from the instance argument.
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,14 @@ 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. Repeated `setProps` calls accumulate: earlier values are kept, new values override per key. 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
+
797
+ `setProps` also works on objects with no mnemonica record at all (plain objects, `Error` objects): a record keyed by the object itself is created on demand, and `getProps` finds it directly. This is how library errors carry their data. On primitives (`setProps(5, …)`) it returns `false`.
798
+
749
799
  ---
750
800
 
751
801
  ### Instance Methods
@@ -759,7 +809,7 @@ utils.extract(instance);
759
809
  utils.pick(instance, 'key');
760
810
  utils.parent(instance, 'ParentType');
761
811
  utils.fork(instance)(newArgs);
762
- utils.exception(instance, error);
812
+ new utils.exception(instance, error); // must be called with `new`
763
813
  utils.sibling(instance);
764
814
  utils.clone(instance);
765
815
  ```
@@ -792,13 +842,26 @@ const pickedArray = utils.pick(instance, ['email', 'password']);
792
842
 
793
843
  #### `utils.parent(instance, constructorName?)`
794
844
 
795
- Gets the parent instance. If `constructorName` is provided, walks up the chain.
845
+ Gets the parent instance. If `constructorName` is provided, walks up the chain
846
+ and returns the nearest ancestor with that constructor name. The instance itself
847
+ is never a candidate — only ancestors are searched.
848
+
849
+ A **dotted path** (`'GrandParent.Parent'`) requires the segments to match
850
+ contiguously upwards: each leading segment must be the direct parent of the
851
+ instance matched by the next one. The return value is the instance matched by
852
+ the **last** segment. This disambiguates lineages where the same type name
853
+ appears more than once (possible with `strictChain: false` re-construction).
854
+ If no contiguous match exists, the result is `undefined`.
855
+
796
856
  The structural return type is `object | undefined`; a specific nominal parent
797
857
  type requires a `TypeRegistry` augmentation (see [`docs/typed-lookup.md`](./docs/typed-lookup.md)).
798
858
 
799
859
  ```ts
800
860
  const immediateParent = utils.parent(instance);
801
861
  const specificParent = utils.parent(instance, 'UserType'); // object | undefined
862
+ // lineage request → route → page → response:
863
+ const route = utils.parent(response, 'RequestData.RouteData'); // route instance
864
+ const nearest = utils.parent(response, 'RouteData'); // page's parent, as before
802
865
  ```
803
866
 
804
867
  #### `utils.clone(instance)`
@@ -834,13 +897,20 @@ const dagInstance = forkFn.call(instanceB, 'args');
834
897
 
835
898
  #### `utils.exception(instance, error, ...args)`
836
899
 
837
- Creates an exception instance from the given instance.
900
+ Creates an exception instance from the given instance. Must be called with
901
+ `new` (it throws `WRONG_INSTANCE_INVOCATION` otherwise).
838
902
 
839
903
  ```ts
840
- const error = utils.exception(someInstance, new Error('Something went wrong'));
904
+ const error = new utils.exception(someInstance, new Error('Something went wrong'));
841
905
  throw error;
842
906
  ```
843
907
 
908
+ The resulting error is a plain `Error` — data lives in its props, read via
909
+ `getProps(error)`: `args`, `originalError`, `instance`. Only `.message` and
910
+ `.stack` (merged lifecycle trace) sit on the error object itself. No bound
911
+ methods either: use `utils.extract(getProps(error).instance)` /
912
+ `utils.parse(getProps(error).instance)` for properties and structural info.
913
+
844
914
  #### `utils.sibling(instance)`
845
915
 
846
916
  Access sibling types from the same collection. Returns a callable/proxy object
@@ -891,7 +961,7 @@ explicit `<T>` cast is required for ordinary use.
891
961
  | `utils.fork(instance)` | `(this: object, ...args: unknown[]) => T` |
892
962
  | `utils.parent(instance, path?)` | `object \| undefined` |
893
963
  | `utils.sibling(instance)` | `SiblingAccessor` |
894
- | `utils.merge(A, B, ...args)` | `InstanceResult<Merge<B, A>, constructorOptions>` |
964
+ | `utils.merge(A, B, ...args)` | `InstanceResult<Merge<B, A>>` |
895
965
  | `utils.parse(instance)` | `Parsed<T>` |
896
966
  | `utils.toJSON(instance)` | `string` |
897
967
  | `utils.collectConstructors(instance, flat?)` | `(CallableFunction \| string)[]` |
@@ -948,7 +1018,7 @@ interface HookData {
948
1018
  args: unknown[]; // Arguments passed to constructor
949
1019
  existentInstance: object; // Parent instance
950
1020
  inheritedInstance: object; // New instance (postCreation only)
951
- throwModificationError(error: Error): void; // Throw error from hook
1021
+ throwModificationError(error: Error): void; // Throw error from hook (not available in preCreation)
952
1022
  }
953
1023
  ```
954
1024
 
@@ -961,6 +1031,13 @@ MyType.registerHook('postCreation', (hookData) => {
961
1031
 
962
1032
  **Note:** In preCreation hooks, `existentInstance` refers to the parent; in postCreation hooks, it refers to the instance used for inheritance.
963
1033
 
1034
+ **Error wrapping boundaries.** `preCreation` hooks do not receive
1035
+ `throwModificationError` — throw normally to abort construction; the error
1036
+ propagates unwrapped. The same is true for errors thrown by a lazy type's
1037
+ getter at setup and by a custom `ModificationConstructor` during prototype
1038
+ wiring: they propagate as-is. Only failures of the user constructor body are
1039
+ wrapped into mnemonica errored instances (when `blockErrors` is `true`).
1040
+
964
1041
  ---
965
1042
 
966
1043
  ### Error Handling
@@ -991,18 +1068,22 @@ errors.WRONG_STACK_CLEANER
991
1068
 
992
1069
  #### Exception Instances
993
1070
 
994
- When creating exceptions using `utils.exception()`:
1071
+ When creating exceptions using `utils.exception()` (must be called with `new`):
995
1072
 
996
1073
  ```js
997
- const { utils } = require('mnemonica');
998
- const error = utils.exception(instance, new Error('Original error'));
1074
+ const { utils, getProps } = require('mnemonica');
1075
+ const error = new utils.exception(instance, new Error('Original error'));
999
1076
 
1000
- // Properties:
1001
- error.originalError // The original error
1002
- error.exceptionReason // { methodName, ... }
1003
- error.BaseStack // Base stack trace
1004
- error.parse() // Parse the exception structure
1005
- error.extract() // Extract properties from the exception
1077
+ // The error object itself is a plain Error: .message and .stack
1078
+ // (merged lifecycle trace) only. Everything else lives in props:
1079
+ const errorProps = getProps(error);
1080
+ errorProps.args // Extra arguments passed to the exception call
1081
+ errorProps.originalError // The original error
1082
+ errorProps.instance // The mnemonica instance the error was made from
1083
+
1084
+ // Errors carry no bound methods — use the utils on the props instance:
1085
+ utils.extract(errorProps.instance) // Extract properties from the instance
1086
+ utils.parse(errorProps.instance) // Parse the instance structure
1006
1087
  ```
1007
1088
 
1008
1089
  #### Stack Cleaning
@@ -1014,6 +1095,10 @@ const { defineStackCleaner } = require('mnemonica');
1014
1095
  defineStackCleaner(/node_modules\/some-package/);
1015
1096
  ```
1016
1097
 
1098
+ Multiple cleaners may be registered; a stack line is removed if **any** of
1099
+ them matches. If cleaning would remove every line, the original stack is
1100
+ kept instead.
1101
+
1017
1102
  ---
1018
1103
 
1019
1104
  ### Symbols & Constants
@@ -1057,6 +1142,26 @@ define('SomeType', function () {}, {
1057
1142
  | `asClass` | `boolean` | `auto` | Force class mode detection. Usually auto-detected from constructor syntax. |
1058
1143
  | `ModificationConstructor` | `Function` | - | Custom constructor function for internal instance modification. |
1059
1144
 
1145
+ ### What `strictChain` actually guards
1146
+
1147
+ `strictChain` is checked at two independent points, and re-constructing a
1148
+ predecessor type on a deeper instance (`apply(deepInstance, AncestorType)`)
1149
+ requires **both** of them to be off:
1150
+
1151
+ 1. **Subtype resolution** checks the config of the **entity's type**: may this
1152
+ instance construct a subtype that is not its own direct subtype? With
1153
+ `strictChain: false`, the search walks up the parent chain and a subtype
1154
+ registered on any ancestor type becomes constructible
1155
+ (`Mnemosyne.prepareSubtypeForConstruction` → `findSubTypeFromParent`).
1156
+ 2. **Construction validation** checks the config of the **target type**: must
1157
+ the new instance's parent be an instance of the type's declared parent
1158
+ kind? With `strictChain: false`, a parent of a different kind is accepted
1159
+ (`InstanceCreator.postProcessing`).
1160
+
1161
+ This is how one lineage can end up carrying the same type name more than
1162
+ once — which is exactly the case `utils.parent(instance, 'A.B')` dotted
1163
+ paths were made for.
1164
+
1060
1165
  ### Instance Method Opt-In
1061
1166
 
1062
1167
  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 +1377,8 @@ rules live in [AGENTS.md](AGENTS.md).
1272
1377
 
1273
1378
  **Related reading:**
1274
1379
  - [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)
1380
+ - [Architecture of Prototype Inheritance in JavaScript](https://github.com/mythographica/stash/blob/master/inheritance_architecture.md)
1381
+ - [Dead Simple type checker for JavaScript](https://github.com/mythographica/typologica)
1277
1382
 
1278
1383
  ---
1279
1384