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
@@ -1,352 +0,0 @@
1
- ---
2
- name: mnemonica-async-constructors
3
- description: |
4
- Async constructor patterns in mnemonica: awaitReturn, super() return-value
5
- propagation, native async class wrapping, async subtype chains, and the
6
- parent.AsyncChild() invocation pattern. Use when the user asks about async
7
- constructors, Promise return from new, await new Constructor(), async subtype
8
- chains, or mixing native async classes with mnemonica.
9
- metadata:
10
- tags: [mnemonica, async, constructors, promises, super, await, classes]
11
- ---
12
-
13
- # Async Constructors
14
-
15
- ## Basic Async define()
16
-
17
- ```typescript
18
- const AsyncType = define('AsyncType', async function (data) {
19
- await someAsyncOperation();
20
- return Object.assign(this, { data });
21
- });
22
-
23
- const instance = await new AsyncType('tada');
24
- ```
25
-
26
- ## awaitReturn Config
27
-
28
- When `awaitReturn: true` (default), `await new Constructor()` must return a value.
29
- If the constructor returns `undefined`, an error is thrown.
30
-
31
- ```typescript
32
- const AsyncType = define('AsyncType', async function () {
33
- return this; // MUST return a value
34
- }, { awaitReturn: true });
35
-
36
- const AsyncTypeNoReturn = define('AsyncTypeNoReturn', async function () {
37
- // No return needed
38
- }, { awaitReturn: false });
39
- ```
40
-
41
- ## The super() Return-Value Pattern
42
-
43
- `super()` returns whatever the parent constructor returns — including Promises.
44
- This is standard JavaScript, and mnemonica's class wrapper preserves it:
45
-
46
- ```typescript
47
- class MyAsyncClass {
48
- field = undefined;
49
- constructor() {
50
- const self = this;
51
- return new Promise((resolve) => {
52
- setTimeout(() => {
53
- self.field = 123;
54
- resolve(self);
55
- }, 100);
56
- });
57
- }
58
- }
59
-
60
- class MySubAsyncClass extends MyAsyncClass {
61
- constructor() {
62
- const promise = super(); // ← catches parent's Promise
63
- return new Promise(async (resolve) => {
64
- const item = await promise; // ← await it
65
- console.log(item.field); // 123
66
- resolve(item); // ← resolve with parent's instance
67
- });
68
- }
69
- }
70
- ```
71
-
72
- mnemonica detects class constructors via `isClass()` and uses `class extends`
73
- wrapping (`compileNewModificatorFunctionBody.ts`), so `super()` propagates the
74
- Promise into the async pipeline.
75
-
76
- ## Wrapping Native Async Classes
77
-
78
- You can pass a native async class directly to `define()`:
79
-
80
- ```typescript
81
- const First = define('First', MyAsyncClass);
82
- const Second = First.define('Second', MySubAsyncClass);
83
-
84
- const first = await new First();
85
- const second = await new first.Second(); // ← correct: invoke as method
86
- ```
87
-
88
- **Important:** `await new Second()` directly would fail `strictChain` because
89
- there is no parent instance. Always invoke async subtypes as methods on the
90
- parent instance.
91
-
92
- ## The Prototype Chain Takeover
93
-
94
- When mnemonica wraps your native class, it rewrites the prototype chain to
95
- follow mnemonica's Trie, not the native class hierarchy:
96
-
97
- ```typescript
98
- const second = await new first.Second();
99
-
100
- console.log(second instanceof Second); // true
101
- console.log(second instanceof First); // true
102
- console.log(second instanceof MyAsyncClass); // true
103
- console.log(second instanceof MySubAsyncClass); // false ← native subclass lost
104
- ```
105
-
106
- The native class is the construction vehicle; mnemonica owns the inheritance.
107
- The async behavior (field propagation, Promise resolution) still works correctly.
108
-
109
- ## Correct Async Subtype Invocation
110
-
111
- In mnemonica, async subtypes are invoked as **methods on the parent instance**:
112
-
113
- ```typescript
114
- const AsyncParent = define('AsyncParent', async function () {
115
- await sleep(50);
116
- this.parentValue = 'parent';
117
- return this;
118
- });
119
-
120
- const AsyncChild = AsyncParent.define('AsyncChild', async function () {
121
- await sleep(50);
122
- this.childValue = 'child';
123
- return this;
124
- });
125
-
126
- // ✓ Correct: invoke subtype as method on parent instance
127
- const parent = await new AsyncParent();
128
- const child = await parent.AsyncChild();
129
-
130
- console.log(child.parentValue); // 'parent'
131
- console.log(child.childValue); // 'child'
132
-
133
- // ✗ Wrong: standalone new fails strictChain
134
- const child = await new AsyncChild(); // ERROR
135
- ```
136
-
137
- ## Async Chains with Single Await
138
-
139
- ```typescript
140
- const result = await new UserTypeConstructor({
141
- email: 'async@gmail.com',
142
- password: 32123
143
- })
144
- .WithoutPassword()
145
- .WithAdditionalSign('async sign')
146
- .AsyncChain1st({ async1st: '1st' })
147
- .AsyncChain2nd({ async2nd: '2nd' })
148
- .Async2Sync2nd({ sync: 'is' })
149
- .AsyncChain3rd({ async: '3rd' });
150
- ```
151
-
152
- Each async subtype returns a Promise that resolves to the next instance. The
153
- single `await` unwraps the entire sequence.
154
-
155
- ## makeAwaiter
156
-
157
- `InstanceCreator.makeAwaiter()` wraps the construction result in a Promise,
158
- validates the instance type on resolution, and attaches subtype factories:
159
-
160
- ```typescript
161
- // After await, instance has .SubType(), .AnotherType(), etc.
162
- const instance = await new AsyncType();
163
- const chained = await instance.SubType().AnotherType();
164
- ```
165
-
166
- ## addThen
167
-
168
- `addThen()` allows sequential async subtype creation by chaining Promises:
169
-
170
- ```typescript
171
- const instance = await new AsyncType();
172
- const chained = await instance.SubType().AnotherType(); // sequential awaits
173
- ```
174
-
175
- ## Error Handling in Async Constructors
176
-
177
- When an async constructor throws, mnemonica creates an error instance that
178
- inherits from the type being constructed:
179
-
180
- ```typescript
181
- const AsyncErroredType = define('AsyncErroredType', async function () {
182
- await sleep(100);
183
- const b = {};
184
- b.c.async = null; // TypeError
185
- });
186
-
187
- try {
188
- await new AsyncErroredType();
189
- } catch (error) {
190
- console.log(error instanceof Error); // true
191
- console.log(error instanceof TypeError); // true
192
- console.log(error instanceof AsyncErroredType); // true
193
- }
194
- ```
195
-
196
- ## Summary
197
-
198
- | Pattern | Works? | Notes |
199
- |---------|--------|-------|
200
- | `define('Name', async function () { ... })` | ✅ | Standard async constructor |
201
- | `define('Name', MyAsyncClass)` | ✅ | Native async class wrapped via `class extends` |
202
- | `await new AsyncType()` | ✅ | Returns resolved instance (with `awaitReturn: true`) |
203
- | `await parent.AsyncSubType()` | ✅ | Correct subtype invocation pattern |
204
- | `await new AsyncSubType()` | ❌ | Fails `strictChain` — no parent instance |
205
- | Native `instanceof` through chain | ⚠️ | Follows mnemonica's graph, not native class hierarchy |
206
- | `super()` returning Promise | ✅ | Standard JS; mnemonica's wrapper preserves it |
207
-
208
- ---
209
-
210
- ## Symbol.hasInstance — Nominal Typing by Name
211
-
212
- Mnemonica replaces standard JS `instanceof` with **nominal typing** checked by `getTypeChecker` (`src/api/utils/index.ts:37`):
213
-
214
- ```ts
215
- const getTypeChecker = (TypeName: string) => {
216
- return (instance: object) => {
217
- if (Reflect.getPrototypeOf(instance).constructor.name === 'Promise') {
218
- return instance[SymbolConstructorName] === TypeName;
219
- }
220
- const constructors = collectConstructors(instance);
221
- return constructors[TypeName] || false;
222
- };
223
- };
224
- ```
225
-
226
- `collectConstructors` (`src/utils/collectConstructors.ts`) walks the prototype chain upward, collecting `constructor.name` values into a lookup object like `{ AsyncInitParent: true, AsyncInitChild: true, Mnemonica: true, Object: true }`. It stops at `Mnemonica`.
227
-
228
- Three places define `Symbol.hasInstance`:
229
-
230
- 1. **`TypeDescriptor.prototype`** (`src/api/types/index.ts:210`) — for `instanceof TypeName` where `TypeName` is what `define()` returned
231
- 2. **`Mnemosyne.prototype`** (`src/api/types/Mnemosyne.ts:381`) — for `instanceof` checks on the instance itself
232
- 3. **`makeSubTypeProxy`** (`src/api/types/Mnemosyne.ts:205`) — for subtype access like `parent.SubType()`
233
-
234
- ### Impact on Pre-existing Class Hierarchies
235
-
236
- When passing a pre-existing class hierarchy (`class Extended extends Base`) to `define()`:
237
-
238
- - **Top-level** `define('PreExt', Extended)`: `PreExt.prototype === Extended.prototype`. Both `instanceof PreExt` and `instanceof Extended` work.
239
- - **Sub-type** `Root.define('Sub', Extended)`: mnemonica's subtype wiring inserts the parent type (`Root`) into the instance chain **before** `Extended.prototype`. Standard JS `instanceof Extended` returns **false**, but mnemonica's `instanceof Sub` and `instanceof Root` still work because `collectConstructors` finds their names.
240
-
241
- ---
242
-
243
- ## Test Suite
244
-
245
- Tests live in `test_async/index.js` and run via `npm run test:async_init`.
246
-
247
- ### Acronyms
248
-
249
- - **WOReturn** = **W**ith**O**ut **Return** — Promise resolves to `undefined` instead of `this`
250
- - **NAR** = **N**o **A**wait **R**eturn** — `awaitReturn: false` disables the guard
251
-
252
- ### Coverage Items
253
-
254
- 1. **WOReturn guard for classes** — async class constructor returning Promise without `this` throws `WRONG_MODIFICATION_PATTERN`
255
- 2. **NAR bypass** — `awaitReturn: false` allows the same without throwing
256
- 3. **Field inheritance through mnemonica chain** — parent/child fields preserved across async constructors
257
- 4. **Pre-existing class hierarchy at top-level** — `define('Type', ExtendedClass)` preserves fields and `instanceof` against original classes
258
- 5. **Pre-existing class hierarchy as sub-type** — sub instance gets root fields + class hierarchy fields, but standard JS `instanceof` against original classes is broken (mnemonica `instanceof` still works)
259
-
260
- ### Relevant Source Files
261
-
262
- - `src/api/types/compileNewModificatorFunctionBody.ts` — wrapper class creation
263
- - `src/api/utils/index.ts` — `getTypeChecker`
264
- - `src/utils/collectConstructors.ts` — prototype chain walker
265
- - `src/api/types/Mnemosyne.ts` — `Symbol.hasInstance` on instances and sub-type proxy
266
- - `src/api/types/index.ts` — `Symbol.hasInstance` on `TypeDescriptor.prototype`
267
- - `src/api/types/InstanceCreator.ts` — async routing via `makeAwaiter`
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
-
350
- ### Related
351
-
352
- - [TC39 proposal-async-init issue #3](https://github.com/tc39/proposal-async-init/issues/3) — language-level discussion of the same problem
@@ -1,95 +0,0 @@
1
- ---
2
- name: mnemonica-code-style
3
- description: |
4
- Code style rules for mnemonica: tabs, spacing, type vs interface.
5
- Use when writing or modifying mnemonica source code, or when the user asks
6
- about formatting, indentation, spacing, or TypeScript style in mnemonica.
7
- metadata:
8
- tags: [mnemonica, style, formatting, tabs, typescript]
9
- ---
10
-
11
- # Code Style
12
-
13
- ## Indentation
14
-
15
- - **TABS ONLY** — Never use spaces for indentation
16
- - Tab width: 4
17
- - Enforced by eslint
18
-
19
- ```typescript
20
- // ✅ Correct
21
- function myFunc () {
22
- if (true) {
23
- return 42;
24
- }
25
- }
26
-
27
- // ❌ Wrong (spaces)
28
- function myFunc () {
29
- if (true) {
30
- return 42;
31
- }
32
- }
33
- ```
34
-
35
- ## Function Spacing
36
-
37
- - **Always** space before function parentheses:
38
-
39
- ```typescript
40
- function myFunc () { } // ✓ Correct
41
- function myFunc() { } // ✗ Wrong
42
-
43
- const fn = function () { }; // ✓ Correct
44
- const fn = function() { }; // ✗ Wrong
45
-
46
- class MyClass {
47
- method () { } // ✓ Correct
48
- method() { } // ✗ Wrong
49
- }
50
- ```
51
-
52
- ## Key Spacing
53
-
54
- - Align colons in object literals:
55
-
56
- ```typescript
57
- const obj = {
58
- key1 : value1,
59
- key2 : value2, // colons aligned
60
- };
61
- ```
62
-
63
- ## TypeScript Strictness
64
-
65
- - `strict: true` enabled
66
- - `noUnusedLocals: true` — unused variables cause errors
67
- - `noUnusedParameters: true` — unused parameters cause errors
68
- - `isolatedModules: true` — each file must be independently transpilable
69
- - **NO `any`** — use purpose-specific interfaces instead
70
-
71
- ## ESLint Exceptions
72
-
73
- - `@typescript-eslint/no-explicit-any`: **error** — `any` is forbidden
74
- - `@typescript-eslint/no-var-requires`: **off** — CommonJS requires allowed
75
- - `new-cap`: **off** — constructor naming not enforced
76
-
77
- ## Function Type Rules
78
-
79
- **Never use bare `Function`, `CallableFunction`, or `NewableFunction` as parameter or return types.** Define a purpose-specific interface that extends them:
80
-
81
- ```typescript
82
- // ✗ Wrong
83
- function foo (handler: Function) { }
84
-
85
- // ✓ Correct
86
- interface ConstructHandler extends CallableFunction {
87
- (this: object, ...args: unknown[]): unknown;
88
- prototype: object;
89
- }
90
- function foo (handler: ConstructHandler) { }
91
- ```
92
-
93
- Allowed exceptions (do not change without approval):
94
- - `src/types/index.ts` — central type definitions use `CallableFunction`/`NewableFunction` as base types for exported interfaces
95
- - `src/api/types/compileNewModificatorFunctionBody.ts` — `ConstructHandler`/`CreationHandler` interfaces already defined there
@@ -1,246 +0,0 @@
1
- # ⚠️ RULE #1 — NON-NEGOTIABLE: PAUSE AND ASK
2
-
3
- **This is the highest-priority rule. It overrides ALL other instructions.**
4
-
5
- ## When You MUST Stop and Ask
6
-
7
- You MUST pause BEFORE proceeding and ask the user for clarification if ANY of the following is true:
8
-
9
- 1. **Errors** — `apply_diff` fails, `write_to_file` produces unexpected results, or any tool returns an error. A successful retry does NOT cancel this rule: report the error AND how you recovered.
10
- 2. **Uncertainty** — you are not 100% certain about what change to make, how a function works, or what the user intended.
11
- 3. **Assumptions** — you find yourself filling in gaps with "probably", "likely", "I think", or "it should work".
12
- 4. **Conflicting constraints** — a tool or environment constraint conflicts with the user's stated preference. Surface the conflict verbatim; never silently satisfy the tool at the user's expense.
13
- 5. **Unrequested file creation or duplication** — you are about to create or duplicate a file the user did not explicitly request. Ask first. Never copy content when `mv`, rename, or a reference suffices.
14
-
15
- ## What To Do
16
-
17
- - STOP immediately.
18
- - Do NOT proceed with workarounds (no `sed`, no `python -c`, no console hacks, no rewriting files to bypass a tool restriction).
19
- - Do NOT make assumptions.
20
- - ASK the user a clear, specific question.
21
- - WAIT for their answer before continuing.
22
- - **Silent recovery is a violation, even when the outcome looks fine.**
23
-
24
- ## Why This Matters
25
-
26
- You work with a Computer Science Enthusiast. You are their clever and knowledgeable Assistant, developed across many spheres. Wrong assumptions waste both your time and theirs. When in doubt — ASK.
27
-
28
- ---
29
-
30
- # Files: Move, Don't Rewrite
31
-
32
- Never create a file whose content substantially duplicates an existing file.
33
- Two copies of the same document will drift apart.
34
-
35
- - To relocate a file: use `mv` (or rename) — never rewrite the full content
36
- into a new path and leave the original behind.
37
- - To share content: reference or link to the canonical file.
38
- - If a tool rejects the original path (permission error, workspace boundary):
39
- STOP and ask the user (Rule #1, clause 4). Do not work around the tool
40
- by duplicating the file elsewhere.
41
-
42
- ---
43
-
44
- # Extended Coding Rules
45
-
46
- ## CRITICAL: Full File Reading Required
47
-
48
- When asked to read a file, you MUST read the ENTIRE file, not just the first 50-100 lines.
49
-
50
- ### How to Read Full Files
51
-
52
- 1. First read with `limit: 200` and check if truncated
53
- 2. If truncated, continue with `offset: 201` until end
54
- 3. For files over 1000 lines, use multiple calls:
55
- ```typescript
56
- // Read 0-200
57
- read_file(path, 1, 200)
58
- // Read 201-400
59
- read_file(path, 201, 200)
60
- // Continue until no longer truncated
61
- ```
62
-
63
- ### NEVER Do This
64
- - ❌ Read only 50-100 lines and assume you understand
65
- - ❌ Stop reading because "it looks like enough"
66
- - ❌ Implement based on partial file content
67
-
68
- ### ALWAYS Do This
69
- - ✅ Read until file is NOT truncated
70
- - ✅ Check "Status: Showing lines X-Y of Z total lines"
71
- - ✅ If Z > Y, continue reading from Y+1
72
-
73
- ## Required Analysis Steps
74
-
75
- Before writing ANY implementation code:
76
-
77
- ### Step 1: Document Data Structures
78
- Write a brief analysis of:
79
- - What data format does each file use?
80
- - What are the key interfaces/types?
81
- - How does data flow between files?
82
-
83
- ### Step 2: Show Your Understanding
84
- Provide a summary like:
85
- ```
86
- From analyzing [file.ts]:
87
- - Data format: { key: string, items: Array<...> }
88
- - Key function: processData() expects X, returns Y
89
- - Related files: A.ts, B.ts depend on this format
90
- ```
91
-
92
- ### Step 3: Get Approval
93
- Wait for user confirmation before implementing.
94
-
95
- ### Step 4: Write Tests First
96
- Create test cases that verify your understanding:
97
- ```typescript
98
- // Test: Data format must match expected structure
99
- const data = loadData();
100
- assert(data.key !== undefined);
101
- assert(Array.isArray(data.items));
102
- ```
103
-
104
- ### Step 5: Implement
105
- Only after Steps 1-4 are complete.
106
-
107
- ## Example: ReferenceProvider Fix
108
-
109
- ❌ WRONG - Coder's Approach:
110
- - Read 50 lines of referenceProvider.ts
111
- - Assume Usages structure from memory
112
- - Implement broken marshaling
113
-
114
- ✅ CORRECT - Required Approach:
115
- 1. Read FULL referenceProvider.ts (all 300+ lines)
116
- 2. Read FULL usages.json to see actual data format
117
- 3. Read FULL Usages.ts to understand model structure
118
- 4. Document: "usages.json has { typeName: Array<Usage> } format"
119
- 5. Show mapping: "Need to convert from JSON to Mnemonica instance"
120
- 6. Write test case for conversion
121
- 7. Implement with verified understanding
122
-
123
- ## User's Direct Instructions
124
-
125
- When user says:
126
- - "Read the FULL content" → Read entire file, no shortcuts
127
- - "Analyze before implementing" → Document first, code second
128
- - "Check the data format" → Look at actual JSON/data files, don't guess
129
-
130
- ## Consequences of Not Following
131
-
132
- If you skip these steps:
133
- 1. You will make wrong assumptions
134
- 2. User will have to debug and fix your code
135
- 3. You waste user's time and energy
136
- 4. User is older and has limited energy - your shortcuts hurt them
137
-
138
- ## Remember
139
-
140
- They are not your debugger. They are a Scientist.
141
- Your job is to implement correctly the FIRST time.
142
- Read thoroughly. Analyze completely. Then code.
143
-
144
- ## Lessons Learned from Recent Refactoring
145
-
146
- ### 1. Separation of Concerns: Models vs Controllers
147
-
148
- **Pattern:** Models = Pure Data, Controllers = Actions
149
-
150
- Models should be pure data containers with only Map/array operations. File I/O and parsing actions belong in controllers.
151
-
152
- ```typescript
153
- // ✅ CORRECT - Model is pure data
154
- export const Definitions = define('Definitions', class {
155
- private map: Map<string, DefinitionEntryInstance> = new Map();
156
-
157
- get(name: string) { return this.map.get(name); }
158
- set(name: string, entry: DefinitionEntryInstance) { this.map.set(name, entry); }
159
- // Note: loadFromFile action moved to Registry
160
- });
161
-
162
- // ✅ CORRECT - Controller handles file I/O
163
- export const Registry = define('Registry', class {
164
- private async loadDefinitions(tacticaPath: string) {
165
- const content = fs.readFileSync(definitionsPath, 'utf-8');
166
- // ... populate Definitions instance
167
- }
168
- });
169
- ```
170
-
171
- ### 2. Avoid Inefficient File Operations
172
-
173
- **Pattern:** Store data during parsing, don't re-read files
174
-
175
- Never re-read an entire file just to get data that was already available during initial parsing.
176
-
177
- ```typescript
178
- // ❌ WRONG - Re-reads file every time
179
- getLineForType(typeName: string): number | undefined {
180
- const entry = this.map.get(typeName);
181
- const content = fs.readFileSync(entry.fullPath, 'utf-8'); // NO!
182
- // ... search for line number
183
- }
184
-
185
- // ✅ CORRECT - Store lineNumber during parsing
186
- export type rawTypeEntry = {
187
- name: string;
188
- fullPath: string;
189
- parent?: string;
190
- properties: Map<string, string>;
191
- lineNumber: number; // Store during parsing
192
- };
193
-
194
- // During parsing in controller:
195
- for (let i = 0; i < lines.length; i++) {
196
- if (match) {
197
- const entry = new this.typesInstance.TypeEntry({
198
- // ...
199
- lineNumber: i // Store when we know it
200
- } as rawTypeEntry);
201
- }
202
- }
203
-
204
- // Simple O(1) lookup later:
205
- getLineForType(typeName: string): number | undefined {
206
- return this.map.get(typeName)?.lineNumber;
207
- }
208
- ```
209
-
210
- ### 3. Naming: Use raw* Prefix for Data Transfer Types
211
-
212
- **Pattern:** `rawTypeEntry` for external data transfer
213
-
214
- Models should export `raw*` types that controllers use when populating them.
215
-
216
- ```typescript
217
- // In model file (Types.ts):
218
- export type rawTypeEntry = {
219
- name: string;
220
- fullPath: string;
221
- parent?: string;
222
- properties: Map<string, string>;
223
- lineNumber: number;
224
- };
225
-
226
- // In controller file (Registry.ts):
227
- import type { rawTypeEntry } from './Types';
228
-
229
- const entry = new this.typesInstance.TypeEntry({
230
- name,
231
- fullPath: typesPath,
232
- parent,
233
- properties: new Map(),
234
- lineNumber: i
235
- } as rawTypeEntry);
236
- ```
237
-
238
- ### Summary Table
239
-
240
- | Concern | Location | Example |
241
- |---------|----------|---------|
242
- | Data storage | Model | `Definitions`, `Types`, `Usages`, `Trie` |
243
- | Data operations | Model | `get()`, `set()`, `has()` |
244
- | File I/O | Controller | `Registry.loadDefinitions()` |
245
- | Parsing | Controller | `Registry.loadTypes()` |
246
- | External data types | Model exports | `rawTypeEntry`, `rawDefinitionEntry` |