mnemonica 1.2.3 → 1.2.7

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 (43) hide show
  1. package/FOR_HUMANS.md +160 -125
  2. package/README.md +70 -249
  3. package/build/api/types/index.js +18 -12
  4. package/build/index.js +6 -2
  5. package/docs/UTILS.md +97 -8
  6. package/docs/decorate.md +1 -1
  7. package/docs/empathy-in-ai.md +20 -10
  8. package/docs/prototype-chain.md +8 -7
  9. package/docs/typed-lookup.md +195 -5
  10. package/docs/typeomatica.md +8 -345
  11. package/package.json +6 -10
  12. package/src/api/types/index.ts +33 -20
  13. package/src/index.ts +12 -1
  14. package/.ai/AGENTS.md +0 -151
  15. package/.ai/ARCHITECT.md +0 -110
  16. package/.ai/DEBUG.md +0 -178
  17. package/.ai/ONBOARDING.md +0 -189
  18. package/.ai/PROTOTYPE-CHAIN.md +0 -155
  19. package/.ai/mode-ask.md +0 -121
  20. package/.ai/mode-orchestrator.md +0 -141
  21. package/.ai/performance-vs-security.md +0 -395
  22. package/.ai/rules-async-constructors.md +0 -352
  23. package/.ai/rules-code-style.md +0 -95
  24. package/.ai/rules-coding.md +0 -246
  25. package/.ai/rules-context-condensing.md +0 -50
  26. package/.ai/rules-contributing.md +0 -227
  27. package/.ai/rules-define-patterns.md +0 -159
  28. package/.ai/rules-ecosystem.md +0 -140
  29. package/.ai/rules-error-system.md +0 -66
  30. package/.ai/rules-hooks.md +0 -46
  31. package/.ai/rules-instance-methods.md +0 -93
  32. package/.ai/rules-philosophy.md +0 -231
  33. package/.ai/rules-reminders.md +0 -19
  34. package/.ai/rules-testing.md +0 -66
  35. package/.ai/rules-type-system.md +0 -124
  36. package/.ai/theory-of-operations.md +0 -224
  37. package/AGENTS.md +0 -345
  38. package/CONTRIBUTING.md +0 -150
  39. package/SKILL.md +0 -114
  40. package/docs/ai-learning-trajectory.md +0 -141
  41. package/docs/purpose.md +0 -707
  42. package/docs/tactica-deep-dive.md +0 -629
  43. package/docs/tactica-pattern.md +0 -146
package/FOR_HUMANS.md CHANGED
@@ -36,7 +36,7 @@ define(name, ctor) → TypeProxy → new instance.SubType()
36
36
  > Status API is stable for the documented surface: advanced topics are also covered
37
37
  > If you're looking for the deeper theory (Homotopy Type Theory, runtime Tries, AI-agent pipelines), see [`README.md`](./README.md). This document is the welcoming entry — practical, example-driven, aimed at developers who want to use the library.
38
38
  > **For type-safe `lookup()`:** read [`docs/typed-lookup.md`](./docs/typed-lookup.md) — the `TypeRegistry` augmentation pattern, hand-written or generated by [`@mnemonica/tactica`](https://www.npmjs.com/package/@mnemonica/tactica). Runtime behaviour is identical either way.
39
- > [`SKILL.md`](./SKILL.md) is a usage quick reference only (not for contributors).
39
+ > [`SKILL.md`](https://github.com/wentout/mnemonica/blob/master/SKILL.md) is a usage quick reference only (not for contributors).
40
40
 
41
41
  ---
42
42
 
@@ -50,14 +50,15 @@ The key inversion: subtypes are instantiated *from parent instances*, not from c
50
50
 
51
51
  **Why it matters:** in any system where data transformation order matters — HTTP pipelines, ETL flows, AI agent chains — the construction history *is* the business logic. mnemonica makes that history first-class.
52
52
 
53
- ### One runtime, two type-system paths
53
+ ### One runtime, three type-system paths
54
54
 
55
- Mnemonica has one runtime behavior, but TypeScript cannot see the type graph created by runtime `define()` calls. To solve this, there are two compile-time paths:
55
+ Mnemonica has one runtime behavior, but TypeScript cannot see the type graph created by runtime `define()` calls. To solve this, there are three compile-time paths:
56
56
 
57
57
  1. **Builder mode** — chain `.define()` on the `mnemonica` object or on `createTypesCollection()`. The returned object carries a local type registry, so `.lookup()` is typed without any global augmentation.
58
- 2. **Augmented mode** — use the free `define()` / `lookup()` exports and augment the global `TypeRegistry` by hand or with `@mnemonica/tactica`.
58
+ 2. **Registry bridge** — merge the builder's local registry into the global `TypeRegistry` with one hand-written line (`interface TypeRegistry extends RegistryOf<typeof App> {}`), so the free `lookup()` is typed too.
59
+ 3. **Augmented mode** — use the free `define()` / `lookup()` exports and `@decorate()`, with the global `TypeRegistry` populated by `@mnemonica/tactica` or written by hand.
59
60
 
60
- There is also a one-line middle path: the `RegistryOf` bridge merges a builder's local registry into the global `TypeRegistry` by hand. At runtime all paths are identical — the only difference is where TypeScript looks up the types. See [`docs/typed-lookup.md`](./docs/typed-lookup.md) for details.
61
+ At runtime all paths are identical — the only difference is where TypeScript looks up the types. See [`docs/typed-lookup.md`](./docs/typed-lookup.md) for details.
61
62
 
62
63
  ---
63
64
 
@@ -83,7 +84,7 @@ Concrete benefits:
83
84
  ## A 30-second example
84
85
 
85
86
  ```javascript
86
- const { define, getProps } = require('mnemonica');
87
+ const { define, getProps, utils } = require('mnemonica');
87
88
 
88
89
  // Define a base type
89
90
  const Person = define('Person', function (data) {
@@ -121,7 +122,7 @@ The key inversion: `new` is called on the **parent instance** (`alice`), not on
121
122
  - **Looking for a specific function?** Jump to the [API Reference](#api-reference).
122
123
  - **Curious about the theory?** Read [`README.md`](./README.md) — the HoTT framing, the Trie observation, the pipeline pattern, the AI-agent angle.
123
124
  - **Want examples you can run?** See the [Examples](#examples) section below.
124
- - **Going deeper on philosophy?** Read [`docs/purpose.md`](./docs/purpose.md).
125
+ - **Going deeper on philosophy?** Read [`.ai/purpose.md`](https://github.com/wentout/mnemonica/blob/master/.ai/purpose.md).
125
126
  - **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
127
 
127
128
  ---
@@ -132,6 +133,7 @@ The key inversion: `new` is called on the **parent instance** (`alice`), not on
132
133
  - [Quick Start](#quick-start)
133
134
  - [For AI Agents](#for-ai-agents)
134
135
  - [Core Concepts](#core-concepts)
136
+ - [Formal definitions](#formal-definitions)
135
137
  - [Trie Observation](#trie-observation)
136
138
  - [Pipeline Pattern](#pipeline-pattern)
137
139
  - [TypeScript Support](#typescript-support)
@@ -221,23 +223,7 @@ import { define, lookup } from 'mnemonica/module';
221
223
 
222
224
  ## For AI Agents
223
225
 
224
- > **Before editing code, load the docs that match your change type.** The wrong context produces broken code — the right context is a short read.
225
-
226
- | Change type | Read before starting |
227
- |---|---|
228
- | Any `src/` change | [`AGENTS.md`](./AGENTS.md) + [`.ai/ONBOARDING.md`](./.ai/ONBOARDING.md) |
229
- | Involves `define()` / type graph | + [`.ai/rules-define-patterns.md`](./.ai/rules-define-patterns.md) |
230
- | Involves hooks | + [`.ai/rules-hooks.md`](./.ai/rules-hooks.md) |
231
- | Involves async constructors | + [`.ai/rules-async-constructors.md`](./.ai/rules-async-constructors.md) |
232
- | Involves TypeScript types | + [`.ai/rules-type-system.md`](./.ai/rules-type-system.md) |
233
- | Involves proxy internals | + [`.ai/PROTOTYPE-CHAIN.md`](./.ai/PROTOTYPE-CHAIN.md) |
234
- | Uses tactica / `lookup` | + [`docs/tactica-deep-dive.md`](./docs/tactica-deep-dive.md) |
235
- | Docs-only change | README section you're touching only |
236
- | Unfamiliar with the codebase | [`.ai/ONBOARDING.md`](./.ai/ONBOARDING.md) first — one file, five minutes |
237
-
238
- **`AGENTS.md` + `.ai/ONBOARDING.md` are the always-required baseline for any `src/` edit.** Everything else is opt-in by change type.
239
-
240
- AI agent integration guidance (introspection patterns, type discovery, safe construction) lives in [`AGENTS.md`](AGENTS.md). It is kept separate from the user-facing API reference.
226
+ Contributors editing the library itself — human or AI — should read [`AGENTS.md`](https://github.com/wentout/mnemonica/blob/master/AGENTS.md). It is the canonical contributor guide and is not duplicated here.
241
227
 
242
228
  ---
243
229
 
@@ -245,7 +231,7 @@ AI agent integration guidance (introspection patterns, type discovery, safe cons
245
231
 
246
232
  ### Factory of Constructors
247
233
 
248
- Define types using constructors, factory functions, or classes:
234
+ Define types using constructor functions or classes:
249
235
 
250
236
  ```js
251
237
  // Using a constructor function
@@ -253,26 +239,45 @@ const SomeType = define('SomeType', function (opts) {
253
239
  Object.assign(this, opts);
254
240
  });
255
241
 
256
- // Using a factory function
257
- const AnotherType = define(() => {
258
- const AnotherTypeConstructor = function (opts) {
259
- Object.assign(this, opts);
260
- };
261
- AnotherTypeConstructor.prototype.description = 'SomeType Constructor';
262
- return AnotherTypeConstructor;
242
+ // A named function as the only argument also works —
243
+ // the type name is taken from fn.name
244
+ const AnotherType = define(function AnotherType(opts) {
245
+ Object.assign(this, opts);
263
246
  });
247
+ ```
248
+
249
+ Note what does **not** work: passing an *anonymous* function as the first
250
+ argument. `define(() => { ... return MyClass; })` throws
251
+ `TYPENAME_MUST_BE_A_STRING` — there is no name to register the type under.
252
+ For the deferred / factory case, where the constructor must be resolved
253
+ through a getter (to break a circular dependency, or to defer constructor
254
+ selection), use `.lazy()`:
264
255
 
265
- // Using a class
266
- const ClassType = define(() => {
267
- class MyClass {
268
- constructor(opts) {
269
- Object.assign(this, opts);
270
- }
256
+ ```js
257
+ // unnamed: the type name is taken from the returned constructor's .name
258
+ const ClassType = SomeType.lazy(() => class ClassType {
259
+ constructor(opts) {
260
+ Object.assign(this, opts);
271
261
  }
272
- return MyClass;
262
+ });
263
+
264
+ // named: explicit type name
265
+ const GuestType = SomeType.lazy('GuestType', () => function (opts) {
266
+ Object.assign(this, opts);
267
+ });
268
+
269
+ // also available as a free export
270
+ const { lazy } = require('mnemonica');
271
+ const StandaloneType = lazy(() => function StandaloneType(opts) {
272
+ Object.assign(this, opts);
273
273
  });
274
274
  ```
275
275
 
276
+ The resulting type behaves exactly like one created with `define()` — same
277
+ registry, same `.lookup()`, same subtype chaining. See
278
+ [`lazy(typeName?, getter, config?)`](#lazytypename-getter-config) in the API
279
+ reference.
280
+
276
281
  ### Nested Type Definition
277
282
 
278
283
  ```js
@@ -321,6 +326,27 @@ const extracted = extract(subInstance);
321
326
 
322
327
  ---
323
328
 
329
+ ## Formal definitions
330
+
331
+ These terms are used throughout the codebase and documentation with precise meanings.
332
+
333
+ | Term | Definition |
334
+ |---|---|
335
+ | **Trie node** | A type definition created by `define()`. Has a name, a constructor handler, a prototype, and a Map of subtypes. |
336
+ | **Trie edge** | A parent-child relationship between two nodes. Created by `ParentType.define('ChildType', ...)`. |
337
+ | **Trie path** | A sequence of edges from the root to a specific node. `UserType → AdminType → SuperAdminType` is a path. |
338
+ | **Construction context** | The construction record stored per instance (9 internal props + `__self__` installed after construction): `__type__`, `__parent__`, `__args__`, `__timestamp__`, `__creator__`, `__collection__`, `__subtypes__`, `__proto_proto__`, `__stack__`, `__self__`. Readable via `getProps(instance)`. |
339
+ | **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`. |
340
+ | **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. |
341
+ | **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. |
342
+ | **TypeProxy** | The constructor-like object returned by `define()`. Wraps the raw constructor with `.define()`, `.lazy()`, `.decorate()`, `.lookup()`, `.registerHook()` methods. |
343
+ | **ModificatorType** | The actual constructor function used for `new` calls. Its prototype is linked to Mnemosyne, which is linked to the parent instance. |
344
+ | **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. |
345
+
346
+ For the exact shape of the prototype chain, layer by layer, see [`.ai/PROTOTYPE-CHAIN.md`](https://github.com/wentout/mnemonica/blob/master/.ai/PROTOTYPE-CHAIN.md).
347
+
348
+ ---
349
+
324
350
  ## Trie Observation
325
351
 
326
352
  A Trie is a tree where each node is reached by a sequence of keys — you look up data by walking a path, not by hashing a key. The JavaScript prototype chain is exactly this structure: each `new` narrows the search space one step further.
@@ -378,15 +404,18 @@ const route = new req.RouteData(matchedRoute);
378
404
  const page = new route.PageData(await route.handler(route));
379
405
  const res = new page.ResponseData(200);
380
406
 
381
- getProps(res).__parent__.__parent__.__parent__; // the original RequestData instance
407
+ getProps(getProps(getProps(res).__parent__).__parent__).__parent__; // the original RequestData instance
408
+ // (internal props live in a WeakMap, reachable via getProps() — each hop up the chain needs its own call)
382
409
  ```
383
410
 
384
411
  At any point in the chain, the full history is available without any additional bookkeeping. Add a `preCreation` hook on `RouteData` to measure routing latency. Add a `postCreation` hook on `ResponseData` to log the full request/response pair including every intermediate state — all from a single callback:
385
412
 
386
413
  ```javascript
387
- ResponseData.registerHook('postCreation', ({ type, existentInstance }) => {
388
- const reqData = getProps(existentInstance).__parent__.__parent__.__parent__;
389
- log({ url: reqData.url, status: existentInstance.status });
414
+ ResponseData.registerHook('postCreation', ({ type, existentInstance, inheritedInstance }) => {
415
+ // existentInstance is the parent (the PageData instance) — two hops up to RequestData.
416
+ // Internal props live in a WeakMap, so each hop needs its own getProps() call.
417
+ const reqData = getProps(getProps(existentInstance).__parent__).__parent__;
418
+ log({ url: reqData.url, status: inheritedInstance.status });
390
419
  });
391
420
  ```
392
421
 
@@ -432,7 +461,7 @@ The most commonly used types for TypeScript projects:
432
461
  ```typescript
433
462
  import {
434
463
  IDEF, // Base constructor function type
435
- MnemonicaInstance, // Instance methods interface (extract, pick, parent, fork, etc.)
464
+ LazyDef, // Zero-arg getter returning a constructor (for lazy())
436
465
  constructorOptions, // Type config options (strictChain, blockErrors, etc.)
437
466
  hooksTypes, // 'preCreation' | 'postCreation' | 'creationError'
438
467
  hook, // Hook callback type
@@ -440,7 +469,7 @@ import {
440
469
  } from 'mnemonica';
441
470
  ```
442
471
 
443
- Additional types available: `Constructor`, `Props`, `SiblingAccessor`, `IDefinitorInstance`, `DecoratedClass`, `TypeDef`, `CollectionDef`, `hooksOpts`, `ApplyFunction`, `CallFunction`, `BindFunction`, `CreateTypesCollectionFunction`, `TypesCollection`, `HideInstanceMethodsOptions`, `IsHidingMethods`, `Proto`, `SubtypesMap`, `TypeAbsorber`. See [`src/types/index.ts`](./src/types/index.ts) for full definitions.
472
+ Additional types available: `Constructor`, `TypeConstructor`, `TypeConstructorBase`, `Proto`, `ProtoFlat`, `InstanceResult`, `Merge`, `IDefinitorInstance`, `DecoratedClass`, `hooksOpts`, `TypesCollection`, `TypeLookup`, `LookupResult`, `RegistryOf`, `MnemonicaModule`, `TypeAbsorber`, and the `TypeRegistry` interface (for augmentation). See [`src/types/index.ts`](./src/types/index.ts) for full definitions.
444
473
 
445
474
  ### Generic Type Patterns
446
475
 
@@ -518,7 +547,7 @@ const MyType = define('MyType', function (data) {
518
547
  ```
519
548
 
520
549
  **Parameters:**
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.
550
+ - `typeName` (string): Name of the type. 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. (Alternatively, pass a *named* function as the only argument — the name is then taken from `fn.name`; an anonymous first-argument function throws `TYPENAME_MUST_BE_A_STRING`.)
522
551
  - `constructHandler` (Function): Constructor function
523
552
  - `config` (object, optional): Configuration options
524
553
 
@@ -571,9 +600,10 @@ path is ignored — `lookup('A/B')`, `lookup('A:B')`, and `lookup(' A . B ')`
571
600
  all resolve like `lookup('A.B')`. The same path forms work everywhere a
572
601
  nested type path is accepted (`define()`, `utils.parent()`, hooks, etc.).
573
602
 
574
- #### `lookup(typeNestedPath)`
575
-
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.
603
+ **Type-safe lookup.** Without a `TypeRegistry` augmentation, `lookup()`
604
+ returns `TypeClass | undefined`. With an augmentation — hand-written for
605
+ small projects or generated by [`@mnemonica/tactica`](https://www.npmjs.com/package/@mnemonica/tactica)
606
+ — augmented paths return properly typed constructors:
577
607
 
578
608
  ```typescript
579
609
  import { lookup } from 'mnemonica';
@@ -592,7 +622,7 @@ To enable type safety, generate types with tactica:
592
622
  npx tactica
593
623
  ```
594
624
 
595
- Then include the generated types in your project. See [`docs/typed-lookup.md`](./docs/typed-lookup.md) for details.
625
+ Then include the generated types in your project. See [`docs/typed-lookup.md`](./docs/typed-lookup.md) for both paths side by side.
596
626
 
597
627
  #### `apply(entity, Constructor, args?)`
598
628
 
@@ -660,20 +690,17 @@ For advanced TypeScript usage, the following types are exported from `mnemonica`
660
690
  |------|-------------|-------|
661
691
  | `IDEF<T>` | Base constructor function type | `define('Name', fn: IDEF<MyType>)` |
662
692
  | `LazyDef<T>` | Zero-arg getter returning a constructor | `lazy('Name', fn: LazyDef<MyType>)` |
663
- | `MnemonicaInstance` | Optional helper interface | Can be used when attaching the legacy instance methods to your own prototype |
693
+ | `TypeConstructor<T>` | Registry-stored constructor type | What an augmented `TypeRegistry` maps paths to |
664
694
  | `TypeClass` | Base type constructor | `const MyType: TypeClass = define(...)` |
665
695
  | `DecoratedClass<T>` | Decorated class type | `@decorate() class MyClass {}` (see [`docs/decorate.md`](./docs/decorate.md)) |
666
696
  | `IDefinitorInstance<N, S>` | Constructor with subtypes | Returned by `define()` with `.define()` method |
667
- | `ConstructorFunction<T>` | Constructor with prototype | Generic constructor function signature |
668
697
  | `constructorOptions` | Configuration options | `{ strictChain: true, blockErrors: true }` |
669
698
  | `hooksTypes` | Hook type literals | `'preCreation' \| 'postCreation' \| 'creationError'` |
670
699
  | `hook` | Hook callback type | `(opts: hooksOpts) => void` |
671
700
  | `hooksOpts` | Hook options object | Passed to hook callbacks |
672
- | `TypeDef` | Type definition structure | `instance.__type__` structure |
673
- | `CollectionDef` | Types collection | `instance.__collection__` structure |
674
- | `ApplyFunction` | apply() function type | `apply<E, T, S>(entity, Ctor, args) => S` |
675
- | `CallFunction` | call() function type | `call<E, T, S>(entity, Ctor, ...args) => S` |
676
- | `BindFunction` | bind() function type | `bind<E, T, S>(entity, Ctor) => (...args) => S` |
701
+ | `TypesCollection` | Types collection interface | What `createTypesCollection()` returns |
702
+ | `RegistryOf<T>` | Registry extractor | The one-line bridge: `interface TypeRegistry extends RegistryOf<typeof App> {}` |
703
+ | `TypeRegistry` | Global registry interface | Augmented by hand, by the bridge, or by tactica |
677
704
 
678
705
  These types enable complete type safety when defining and using mnemonica types in TypeScript projects.
679
706
 
@@ -926,19 +953,24 @@ const sibling = siblingAccessor.OtherType;
926
953
 
927
954
  ### Instance Properties (via `getProps`)
928
955
 
929
- All instances have non-enumerable internal properties:
956
+ Internal properties are stored in a `WeakMap` keyed by the instance's
957
+ Mnemosyne memory layer — not as own properties on the instance itself — and
958
+ are read via `getProps(instance)`:
930
959
 
931
- | Property | Type | Description |
932
- |----------|------|-------------|
933
- | `.__args__` | `unknown[]` | Arguments used for instance creation |
934
- | `.__type__` | `TypeDef` | Type definition object |
935
- | `.__parent__` | `object` | Parent instance reference |
936
- | `.__subtypes__` | `Map<string, object>` | Map of available subtypes |
937
- | `.__collection__` | `CollectionDef` | Types collection where type was defined |
938
- | `.__stack__` | `string` | Stack trace (if `submitStack: true` in config) |
939
- | `.__creator__` | `InstanceCreatorContext` | Instance creator reference |
940
- | `.__timestamp__` | `number` | Creation timestamp (ms since epoch) |
941
- | `.__self__` | `object` | Self reference to the instance |
960
+ | Property | Meaning |
961
+ |---|---|
962
+ | `__type__` | The `TypeDef` for this instance's type |
963
+ | `__parent__` | The parent instance this was constructed from |
964
+ | `__args__` | The arguments passed to the constructor |
965
+ | `__timestamp__` | Construction time (ms since epoch) |
966
+ | `__creator__` | The `InstanceCreatorContext` of the immediate creator (may differ from `__type__` in chained construction) |
967
+ | `__collection__` | The types collection (usually `defaultTypes`) |
968
+ | `__subtypes__` | Map of available subtypes for this instance |
969
+ | `__proto_proto__` | The prototype object used during construction |
970
+ | `__stack__` | Construction stack trace (only if `submitStack: true`) |
971
+ | `__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 |
972
+
973
+ Full shape in [`src/types/index.ts`](./src/types/index.ts) (`InstanceInternalProps`).
942
974
 
943
975
  ---
944
976
 
@@ -964,7 +996,7 @@ explicit `<T>` cast is required for ordinary use.
964
996
  | `utils.merge(A, B, ...args)` | `InstanceResult<Merge<B, A>>` |
965
997
  | `utils.parse(instance)` | `Parsed<T>` |
966
998
  | `utils.toJSON(instance)` | `string` |
967
- | `utils.collectConstructors(instance, flat?)` | `(CallableFunction \| string)[]` |
999
+ | `utils.collectConstructors(instance, asSequence?)` | `string[]` when `asSequence: true`, otherwise a `{ [name]: true }` lookup object |
968
1000
 
969
1001
  For the full type-level explanation, helper types, and examples, see
970
1002
  [`docs/UTILS.md`](./docs/UTILS.md).
@@ -979,6 +1011,50 @@ For the full type-level explanation, helper types, and examples, see
979
1011
  - `'postCreation'` - Called after instance creation
980
1012
  - `'creationError'` - Called when instance creation throws an error
981
1013
 
1014
+ #### Construction sequence
1015
+
1016
+ When `new instance.SubType(args)` fires:
1017
+
1018
+ ```
1019
+ new instance.SubType(args)
1020
+ │
1021
+ ▼
1022
+ TypeProxy.construct ← proxy trap intercepts the new call
1023
+ │
1024
+ ▼
1025
+ InstanceCreator ← validates parent, resolves TypeDef
1026
+ │
1027
+ ▼
1028
+ preCreation hooks ← may throw → construction aborts, the error propagates (no creationError hooks)
1029
+ │
1030
+ ▼
1031
+ Mnemosyne memory layer created, proto-linked to the parent instance
1032
+ │
1033
+ ▼
1034
+ WeakMap.set(memoryLayer, internalProps) ← __type__, __parent__, __args__, __timestamp__, ...
1035
+ │
1036
+ ▼
1037
+ constructHandler.call(newObj, args) ← user constructor runs
1038
+ │
1039
+ ▼
1040
+ postCreation hooks
1041
+ │
1042
+ ▼
1043
+ return newObj
1044
+ ```
1045
+
1046
+ `preCreation` fires before the memory layer is created; `postCreation` fires
1047
+ after the user constructor runs. `creationError` fires when construction
1048
+ produced an **errored instance** — the `blockErrors: true` path, where a
1049
+ failure of the user constructor body is wrapped so that
1050
+ `inheritedInstance instanceof Error` (see
1051
+ [`src/api/types/InstanceCreator.ts`](./src/api/types/InstanceCreator.ts)).
1052
+ With `blockErrors: false` such a failure propagates unwrapped instead. The
1053
+ object carries none of the internal props as own properties — they live in
1054
+ the WeakMap, readable via `getProps`.
1055
+
1056
+ See [`src/api/types/InstanceCreator.ts`](./src/api/types/InstanceCreator.ts) and [`src/api/types/TypeProxy.ts`](./src/api/types/TypeProxy.ts).
1057
+
982
1058
  #### `type.registerHook(hookType, callback)`
983
1059
 
984
1060
  Register a hook on a specific type.
@@ -1017,7 +1093,7 @@ interface HookData {
1017
1093
  type: TypeDef; // The type being constructed
1018
1094
  args: unknown[]; // Arguments passed to constructor
1019
1095
  existentInstance: object; // Parent instance
1020
- inheritedInstance: object; // New instance (postCreation only)
1096
+ inheritedInstance: object; // New instance (postCreation and creationError)
1021
1097
  throwModificationError(error: Error): void; // Throw error from hook (not available in preCreation)
1022
1098
  }
1023
1099
  ```
@@ -1029,7 +1105,7 @@ MyType.registerHook('postCreation', (hookData) => {
1029
1105
  });
1030
1106
  ```
1031
1107
 
1032
- **Note:** In preCreation hooks, `existentInstance` refers to the parent; in postCreation hooks, it refers to the instance used for inheritance.
1108
+ **Note:** In both preCreation and postCreation hooks, `existentInstance` is the parent instance — the instance the new one is constructed from. The new instance itself is available in postCreation (and creationError) hooks as `inheritedInstance`.
1033
1109
 
1034
1110
  **Error wrapping boundaries.** `preCreation` hooks do not receive
1035
1111
  `throwModificationError` — throw normally to abort construction; the error
@@ -1061,7 +1137,6 @@ errors.WRONG_ARGUMENTS_USED
1061
1137
  errors.WRONG_HOOK_TYPE
1062
1138
  errors.MISSING_HOOK_CALLBACK
1063
1139
  errors.MISSING_CALLBACK_ARGUMENT
1064
- errors.FLOW_CHECKER_REDEFINITION
1065
1140
  errors.OPTIONS_ERROR
1066
1141
  errors.WRONG_STACK_CLEANER
1067
1142
  ```
@@ -1221,7 +1296,7 @@ For complete documentation including integration patterns, error handling, and a
1221
1296
 
1222
1297
  > **AI agent guidance.** Patterns for type introspection, safe property
1223
1298
  > access, type discovery, instance traversal, and safe construction live
1224
- > in [AGENTS.md](AGENTS.md). They are not duplicated here.
1299
+ > in [AGENTS.md](https://github.com/wentout/mnemonica/blob/master/AGENTS.md). They are not duplicated here.
1225
1300
 
1226
1301
  ---
1227
1302
 
@@ -1315,65 +1390,25 @@ const merged = merge(instanceA, instanceB, 'args');
1315
1390
 
1316
1391
  ## Roadmap
1317
1392
 
1318
- Items below are designed but **not yet shipped**. They are documented here
1319
- so consumers can avoid relying on them prematurely.
1320
-
1321
- ### Nested `lookup()` — resolved as unnecessary
1393
+ ### Nested `lookup()` — designed, not yet shipped
1322
1394
 
1323
1395
  A type-safe `.lookup()` method on constructors (e.g.
1324
- `Scene2D.lookup('GraphNode2D')`) was considered so that the returned
1325
- constructor would preserve the parent type in the prototype chain.
1326
-
1327
- However, this is unnecessary overhead:
1328
-
1329
- - mnemonica subtypes are constructed from **parent instances**, not from
1330
- parent constructors. The chain is created by `new scene.GraphNode2D(...)`,
1331
- not by a constructor looked up in isolation.
1332
- - Tactica-generated declaration merging already types those instance-level
1333
- subtype constructors. Starting from `lookup('Scene2D')` gives a fully
1334
- typed root constructor; after `const scene = new Scene2D(...)`,
1335
- `scene.GraphNode2D` is typed and produces the correct chained instance.
1336
-
1337
- If `lookup('Something')` returns `TypeClass | undefined` instead of a typed
1338
- constructor, it means one of three things:
1339
-
1340
- 1. No `TypeRegistry` augmentation is in scope (the `.tactica` declarations
1341
- are not imported or included in `tsconfig.json`).
1342
- 2. The augmentation is in scope, but does not declare `'Something'`.
1343
- 3. `'Something'` was never defined at runtime.
1344
-
1345
- How nested `.lookup()` could have been implemented if it were needed:
1346
-
1347
- 1. Encode the type's dotted path in `TypeConstructor` itself:
1348
-
1349
- ```typescript
1350
- interface TypeConstructor<Instance, Path extends string = string> {
1351
- lookup<const K extends keyof NestedTypeRegistry[Path]>(
1352
- name: K
1353
- ): NestedTypeRegistry[Path][K];
1354
- }
1355
- ```
1356
-
1357
- 2. Or parse the full path with template literal types and consult a
1358
- `NestedTypeRegistry` mapping parent paths to their child constructors:
1359
-
1360
- ```typescript
1361
- type ParentPath<P extends string> =
1362
- P extends `${infer Head}.${string}` ? Head : never;
1363
- ```
1364
-
1365
- Both approaches require either changing `TypeConstructor` to carry a `Path`
1366
- generic or maintaining a second registry. Since the root-constructor +
1367
- instance-level subtype pattern already gives the same result with no core
1368
- changes, this item is intentionally not implemented.
1396
+ `Scene2D.lookup('GraphNode2D')`), preserving the parent type in the returned
1397
+ constructor, is designed but **not yet shipped**. The runtime method already
1398
+ exists — it resolves relative first, then falls back to the collection root
1399
+ — what is missing is the type-level machinery. Until it lands, start from a
1400
+ typed root constructor (`lookup('Scene2D')` with a `TypeRegistry`
1401
+ augmentation) and construct subtypes from instances: `scene.GraphNode2D` is
1402
+ typed by the augmentation and produces the correctly chained instance. See
1403
+ [`docs/typed-lookup.md`](./docs/typed-lookup.md).
1369
1404
 
1370
1405
  ---
1371
1406
 
1372
1407
  ## Contributing
1373
1408
 
1374
- See [CONTRIBUTING.md](CONTRIBUTING.md) for branch model, commit style, and
1409
+ See [CONTRIBUTING.md](https://github.com/wentout/mnemonica/blob/master/CONTRIBUTING.md) for branch model, commit style, and
1375
1410
  the local build/test loop. Repository conventions, code style, and agent
1376
- rules live in [AGENTS.md](AGENTS.md).
1411
+ rules live in [AGENTS.md](https://github.com/wentout/mnemonica/blob/master/AGENTS.md).
1377
1412
 
1378
1413
  **Related reading:**
1379
1414
  - [Inheritance in JavaScript: Factory of Constructors with Prototype Chain](https://github.com/mythographica/stash/blob/master/inheritance.md)