@codeyam/codeyam-cli 0.1.0-staging.79ef713 → 0.1.0-staging.7c30edc

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 (195) hide show
  1. package/analyzer-template/.build-info.json +7 -7
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +101 -0
  4. package/analyzer-template/packages/ai/src/lib/astScopes/sharedPatterns.ts +28 -0
  5. package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +6 -0
  6. package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +176 -8
  7. package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.ts +46 -6
  8. package/analyzer-template/packages/ai/src/lib/dataStructureChunking.ts +33 -15
  9. package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +32 -5
  10. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +38 -2
  11. package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +359 -142
  12. package/analyzer-template/packages/ai/src/lib/mergeJsonTypeDefinitions.ts +5 -0
  13. package/analyzer-template/packages/ai/src/lib/promptGenerators/collapseNullableObjects.ts +118 -0
  14. package/analyzer-template/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.ts +24 -4
  15. package/analyzer-template/packages/database/src/lib/analysisBranchToDb.ts +1 -1
  16. package/analyzer-template/packages/database/src/lib/analysisToDb.ts +1 -1
  17. package/analyzer-template/packages/database/src/lib/branchToDb.ts +1 -1
  18. package/analyzer-template/packages/database/src/lib/commitBranchToDb.ts +1 -1
  19. package/analyzer-template/packages/database/src/lib/commitToDb.ts +1 -1
  20. package/analyzer-template/packages/database/src/lib/fileToDb.ts +1 -1
  21. package/analyzer-template/packages/database/src/lib/kysely/db.ts +6 -0
  22. package/analyzer-template/packages/database/src/lib/kysely/tables/labsRequestsTable.ts +52 -0
  23. package/analyzer-template/packages/database/src/lib/projectToDb.ts +1 -1
  24. package/analyzer-template/packages/database/src/lib/saveFiles.ts +1 -1
  25. package/analyzer-template/packages/database/src/lib/scenarioToDb.ts +1 -1
  26. package/analyzer-template/packages/database/src/lib/userScenarioToDb.ts +1 -1
  27. package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js +1 -1
  28. package/analyzer-template/packages/github/dist/database/src/lib/analysisBranchToDb.js.map +1 -1
  29. package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js +1 -1
  30. package/analyzer-template/packages/github/dist/database/src/lib/analysisToDb.js.map +1 -1
  31. package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js +1 -1
  32. package/analyzer-template/packages/github/dist/database/src/lib/branchToDb.js.map +1 -1
  33. package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js +1 -1
  34. package/analyzer-template/packages/github/dist/database/src/lib/commitBranchToDb.js.map +1 -1
  35. package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js +1 -1
  36. package/analyzer-template/packages/github/dist/database/src/lib/commitToDb.js.map +1 -1
  37. package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js +1 -1
  38. package/analyzer-template/packages/github/dist/database/src/lib/fileToDb.js.map +1 -1
  39. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts +2 -0
  40. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.d.ts.map +1 -1
  41. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js +3 -0
  42. package/analyzer-template/packages/github/dist/database/src/lib/kysely/db.js.map +1 -1
  43. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts +23 -0
  44. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.d.ts.map +1 -0
  45. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  46. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  47. package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js +1 -1
  48. package/analyzer-template/packages/github/dist/database/src/lib/projectToDb.js.map +1 -1
  49. package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js +1 -1
  50. package/analyzer-template/packages/github/dist/database/src/lib/saveFiles.js.map +1 -1
  51. package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js +1 -1
  52. package/analyzer-template/packages/github/dist/database/src/lib/scenarioToDb.js.map +1 -1
  53. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts +4 -0
  54. package/analyzer-template/packages/github/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  55. package/analyzer-template/packages/types/src/types/ProjectMetadata.ts +7 -1
  56. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts +4 -0
  57. package/analyzer-template/packages/utils/dist/types/src/types/ProjectMetadata.d.ts.map +1 -1
  58. package/background/src/lib/local/createLocalAnalyzer.js +1 -1
  59. package/background/src/lib/local/createLocalAnalyzer.js.map +1 -1
  60. package/codeyam-cli/src/cli.js +2 -0
  61. package/codeyam-cli/src/cli.js.map +1 -1
  62. package/codeyam-cli/src/codeyam-cli.js +18 -2
  63. package/codeyam-cli/src/codeyam-cli.js.map +1 -1
  64. package/codeyam-cli/src/commands/analyze.js +2 -0
  65. package/codeyam-cli/src/commands/analyze.js.map +1 -1
  66. package/codeyam-cli/src/commands/baseline.js +2 -0
  67. package/codeyam-cli/src/commands/baseline.js.map +1 -1
  68. package/codeyam-cli/src/commands/debug.js +2 -0
  69. package/codeyam-cli/src/commands/debug.js.map +1 -1
  70. package/codeyam-cli/src/commands/default.js +25 -19
  71. package/codeyam-cli/src/commands/default.js.map +1 -1
  72. package/codeyam-cli/src/commands/detect-universal-mocks.js +2 -0
  73. package/codeyam-cli/src/commands/detect-universal-mocks.js.map +1 -1
  74. package/codeyam-cli/src/commands/init.js +49 -257
  75. package/codeyam-cli/src/commands/init.js.map +1 -1
  76. package/codeyam-cli/src/commands/memory.js +9 -9
  77. package/codeyam-cli/src/commands/memory.js.map +1 -1
  78. package/codeyam-cli/src/commands/recapture.js +2 -0
  79. package/codeyam-cli/src/commands/recapture.js.map +1 -1
  80. package/codeyam-cli/src/commands/setup-sandbox.js +2 -0
  81. package/codeyam-cli/src/commands/setup-sandbox.js.map +1 -1
  82. package/codeyam-cli/src/commands/setup-simulations.js +284 -0
  83. package/codeyam-cli/src/commands/setup-simulations.js.map +1 -0
  84. package/codeyam-cli/src/commands/test-startup.js +2 -0
  85. package/codeyam-cli/src/commands/test-startup.js.map +1 -1
  86. package/codeyam-cli/src/commands/verify.js +2 -0
  87. package/codeyam-cli/src/commands/verify.js.map +1 -1
  88. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +127 -85
  89. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  90. package/codeyam-cli/src/utils/analyzer.js +7 -0
  91. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  92. package/codeyam-cli/src/utils/install-skills.js +41 -61
  93. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  94. package/codeyam-cli/src/utils/labsAutoCheck.js +48 -0
  95. package/codeyam-cli/src/utils/labsAutoCheck.js.map +1 -0
  96. package/codeyam-cli/src/utils/progress.js +7 -0
  97. package/codeyam-cli/src/utils/progress.js.map +1 -1
  98. package/codeyam-cli/src/utils/requireSimulations.js +10 -0
  99. package/codeyam-cli/src/utils/requireSimulations.js.map +1 -0
  100. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js +4 -4
  101. package/codeyam-cli/src/utils/ruleReflection/__tests__/contextBuilder.test.js.map +1 -1
  102. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js +95 -2
  103. package/codeyam-cli/src/utils/ruleReflection/__tests__/integration/ruleReflectionE2E.test.js.map +1 -1
  104. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js +4 -4
  105. package/codeyam-cli/src/utils/ruleReflection/__tests__/promptBuilder.test.js.map +1 -1
  106. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js +3 -3
  107. package/codeyam-cli/src/utils/ruleReflection/contextBuilder.js.map +1 -1
  108. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js +23 -23
  109. package/codeyam-cli/src/utils/rules/__tests__/ruleState.test.js.map +1 -1
  110. package/codeyam-cli/src/utils/rules/parser.js +5 -0
  111. package/codeyam-cli/src/utils/rules/parser.js.map +1 -1
  112. package/codeyam-cli/src/utils/rules/ruleState.js +10 -10
  113. package/codeyam-cli/src/utils/rules/ruleState.js.map +1 -1
  114. package/codeyam-cli/src/utils/rules/staleness.js +6 -6
  115. package/codeyam-cli/src/utils/rules/staleness.js.map +1 -1
  116. package/codeyam-cli/src/utils/serverState.js +37 -10
  117. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  118. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +19 -42
  119. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  120. package/codeyam-cli/src/webserver/app/lib/database.js +14 -3
  121. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  122. package/codeyam-cli/src/webserver/backgroundServer.js +31 -0
  123. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  124. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-CN61MOMa.js +11 -0
  125. package/codeyam-cli/src/webserver/build/client/assets/api.labs-survey-l0sNRNKZ.js +1 -0
  126. package/codeyam-cli/src/webserver/build/client/assets/api.labs-unlock-l0sNRNKZ.js +1 -0
  127. package/codeyam-cli/src/webserver/build/client/assets/globals-CuCsBc3b.css +1 -0
  128. package/codeyam-cli/src/webserver/build/client/assets/labs-CB3MGcys.js +1 -0
  129. package/codeyam-cli/src/webserver/build/client/assets/{manifest-87319d0f.js → manifest-de6ccaf4.js} +1 -1
  130. package/codeyam-cli/src/webserver/build/client/assets/memory-DCA-kLYt.js +81 -0
  131. package/codeyam-cli/src/webserver/build/client/assets/root-F7e6dvys.js +62 -0
  132. package/codeyam-cli/src/webserver/build/client/assets/settings-BejnUJ6R.js +1 -0
  133. package/codeyam-cli/src/webserver/build/server/assets/{index-9ox9LcrG.js → index-CFKHuovO.js} +1 -1
  134. package/codeyam-cli/src/webserver/build/server/assets/server-build-BQe9Dh4p.js +260 -0
  135. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  136. package/codeyam-cli/src/webserver/build-info.json +5 -5
  137. package/codeyam-cli/templates/codeyam-memory-hook.sh +14 -14
  138. package/codeyam-cli/templates/codeyam:diagnose.md +193 -515
  139. package/codeyam-cli/templates/codeyam:memory.md +9 -21
  140. package/codeyam-cli/templates/codeyam:setup.md +12 -0
  141. package/codeyam-cli/templates/rule-reflection-hook.py +64 -27
  142. package/codeyam-cli/templates/rules-instructions.md +50 -41
  143. package/package.json +1 -1
  144. package/packages/ai/src/lib/astScopes/processExpression.js +78 -1
  145. package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
  146. package/packages/ai/src/lib/astScopes/sharedPatterns.js +25 -0
  147. package/packages/ai/src/lib/astScopes/sharedPatterns.js.map +1 -1
  148. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +128 -7
  149. package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
  150. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js +40 -6
  151. package/packages/ai/src/lib/dataStructure/helpers/convertDotNotation.js.map +1 -1
  152. package/packages/ai/src/lib/dataStructureChunking.js +26 -11
  153. package/packages/ai/src/lib/dataStructureChunking.js.map +1 -1
  154. package/packages/ai/src/lib/generateEntityScenarioData.js +22 -3
  155. package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
  156. package/packages/ai/src/lib/generateExecutionFlows.js +16 -2
  157. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -1
  158. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +242 -81
  159. package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -1
  160. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js +5 -0
  161. package/packages/ai/src/lib/mergeJsonTypeDefinitions.js.map +1 -1
  162. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js +97 -0
  163. package/packages/ai/src/lib/promptGenerators/collapseNullableObjects.js.map +1 -0
  164. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js +17 -2
  165. package/packages/ai/src/lib/promptGenerators/generateEntityScenarioDataGenerator.js.map +1 -1
  166. package/packages/database/src/lib/analysisBranchToDb.js +1 -1
  167. package/packages/database/src/lib/analysisBranchToDb.js.map +1 -1
  168. package/packages/database/src/lib/analysisToDb.js +1 -1
  169. package/packages/database/src/lib/analysisToDb.js.map +1 -1
  170. package/packages/database/src/lib/branchToDb.js +1 -1
  171. package/packages/database/src/lib/branchToDb.js.map +1 -1
  172. package/packages/database/src/lib/commitBranchToDb.js +1 -1
  173. package/packages/database/src/lib/commitBranchToDb.js.map +1 -1
  174. package/packages/database/src/lib/commitToDb.js +1 -1
  175. package/packages/database/src/lib/commitToDb.js.map +1 -1
  176. package/packages/database/src/lib/fileToDb.js +1 -1
  177. package/packages/database/src/lib/fileToDb.js.map +1 -1
  178. package/packages/database/src/lib/kysely/db.js +3 -0
  179. package/packages/database/src/lib/kysely/db.js.map +1 -1
  180. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js +35 -0
  181. package/packages/database/src/lib/kysely/tables/labsRequestsTable.js.map +1 -0
  182. package/packages/database/src/lib/projectToDb.js +1 -1
  183. package/packages/database/src/lib/projectToDb.js.map +1 -1
  184. package/packages/database/src/lib/saveFiles.js +1 -1
  185. package/packages/database/src/lib/saveFiles.js.map +1 -1
  186. package/packages/database/src/lib/scenarioToDb.js +1 -1
  187. package/packages/database/src/lib/scenarioToDb.js.map +1 -1
  188. package/scripts/finalize-analyzer.cjs +8 -76
  189. package/codeyam-cli/src/webserver/build/client/assets/agent-transcripts-DfKzxuoe.js +0 -11
  190. package/codeyam-cli/src/webserver/build/client/assets/globals-Bh6jH0cL.css +0 -1
  191. package/codeyam-cli/src/webserver/build/client/assets/labs-CdVUfvji.js +0 -1
  192. package/codeyam-cli/src/webserver/build/client/assets/memory-CPIDnDEj.js +0 -76
  193. package/codeyam-cli/src/webserver/build/client/assets/root-D6oziHts.js +0 -62
  194. package/codeyam-cli/src/webserver/build/client/assets/settings-eBI36Yv5.js +0 -1
  195. package/codeyam-cli/src/webserver/build/server/assets/server-build-Cq5Vqcob.js +0 -260
@@ -13,19 +13,14 @@ This skill helps you generate and maintain Claude Rules (`.claude/rules/`) that
13
13
 
14
14
  ## Core Principle: Document Confusion, Not Information
15
15
 
16
- **Good rules** explain things that are NOT obvious from reading the code:
16
+ **Valuable rules** capture knowledge that reading the code alone wouldn't reveal:
17
17
 
18
18
  - Historical context (why code evolved this way)
19
19
  - Hidden relationships (files that must change together)
20
20
  - Gotchas that caused bugs
21
21
  - Non-obvious conventions
22
22
 
23
- **Bad rules** document things Claude can easily ascertain:
24
-
25
- - What functions do (Claude can read the code)
26
- - Type definitions (Claude can see them)
27
- - Directory structure (Claude can explore it)
28
- - Basic patterns (Claude knows common patterns)
23
+ Skip documenting things Claude can determine by reading code: function signatures, type definitions, directory structure, and common patterns.
29
24
 
30
25
  ## When to Use This Skill
31
26
 
@@ -275,7 +270,7 @@ Before generating each rule, verify it passes these tests:
275
270
 
276
271
  **2. Code-derivable check**: Read the files the rule will cover. Could the rule's content be determined by reading those files alone?
277
272
 
278
- - If YES → rule probably not needed (Claude can read the code)
273
+ - If YES → the code is its own documentation prefer keeping rules for non-derivable insights
279
274
  - If NO (historical context, edge cases, non-obvious behavior) → rule is valuable
280
275
 
281
276
  **3. Prevention check**: Would this rule have prevented one of the confusion commits you found?
@@ -301,7 +296,7 @@ This caused a bug where `entity` matched `entityCode` (siblings, not parent-chil
301
296
  - Not code-derivable: Code doesn't explain why boundary checking matters
302
297
  - Prevention: Would prevent future prefix-matching bugs
303
298
 
304
- **❌ Bad rule** (fails tests):
299
+ **Compare with a weaker alternative** (fails the checks):
305
300
 
306
301
  ```markdown
307
302
  ## Running Tests
@@ -309,9 +304,7 @@ This caused a bug where `entity` matched `entityCode` (siblings, not parent-chil
309
304
  Use `pnpm jest` to run tests. Configuration is in `jest.config.ts`.
310
305
  ```
311
306
 
312
- - No confusion evidence (no commits showing people struggled with this)
313
- - Code-derivable: Anyone can see `jest.config.ts` exists
314
- - Doesn't prevent any confusion
307
+ - No confusion evidence, code-derivable, and wouldn't prevent future mistakes
315
308
 
316
309
  ### 5B. Rule File Guidelines
317
310
 
@@ -319,17 +312,13 @@ Use `pnpm jest` to run tests. Configuration is in `jest.config.ts`.
319
312
  - Rule for `src/api/` → `.claude/rules/src/api/architecture.md`
320
313
  - Rule for testing patterns → `.claude/rules/testing-patterns.md`
321
314
 
322
- 2. **Paths must be specific**
323
- - Good: `paths: ['src/api/**/*.ts']`
324
- - Bad: `paths: ['**/*.ts']` (too broad, wastes context)
315
+ 2. **Paths must be specific** — use `paths: ['src/api/**/*.ts']` rather than `'**/*.ts'` (too broad wastes context)
325
316
 
326
317
  3. **Content should explain "why" not just "what"**
327
318
  - Focus on the reasoning, history, or gotcha
328
319
  - Be concise - every word costs context
329
320
 
330
- 4. **Timestamp must be current**
331
- - Use ISO 8601 format: `2026-01-27T15:30:00Z`
332
- - This enables the pre-commit hook enforcement
321
+ 4. **Audit dates live in `.claude/codeyam-rule-state.json`** (managed by `codeyam memory touch`). Keep rule frontmatter limited to `paths`.
333
322
 
334
323
  ### Rule Template
335
324
 
@@ -337,7 +326,6 @@ Use `pnpm jest` to run tests. Configuration is in `jest.config.ts`.
337
326
  ---
338
327
  paths:
339
328
  - 'specific/path/**/*.ts'
340
- timestamp: [CURRENT_ISO_TIMESTAMP]
341
329
  ---
342
330
 
343
331
  ## [Clear, Descriptive Title]
@@ -394,11 +382,11 @@ After generating rules based on your analysis and user answers:
394
382
  The pre-commit hook **blocks commits** when:
395
383
 
396
384
  - Code files matching a rule's `paths` are modified
397
- - The rule's `timestamp` is older than the code changes
385
+ - The rule's `lastAuditedAt` in `.claude/codeyam-rule-state.json` is older than the code changes
398
386
 
399
387
  To proceed:
400
388
 
401
389
  1. Review the flagged rule(s)
402
390
  2. Update content if needed
403
- 3. Update the `timestamp` to current time
391
+ 3. Run `codeyam memory touch` to mark rules as audited in `.claude/codeyam-rule-state.json`
404
392
  4. Stage and commit
@@ -52,6 +52,18 @@ codeyam validate-mock .codeyam/universal-mocks/{path-to-your-mock}
52
52
 
53
53
  ## Setup Workflow
54
54
 
55
+ ### Step 0: Ensure Simulation Infrastructure
56
+
57
+ Before configuring the dev server or mocks, ensure the simulation infrastructure is installed.
58
+
59
+ ```bash
60
+ codeyam setup-simulations
61
+ ```
62
+
63
+ This is **idempotent** — if already set up, each step is detected and skipped. On first run it installs analyzer dependencies, Playwright chromium, and creates baseline entities (several minutes). Subsequent runs complete in seconds.
64
+
65
+ If it fails with "No web applications found", the project doesn't support simulations — inform the user and stop.
66
+
55
67
  ### Step 1: Configure Webapp Start Command
56
68
 
57
69
  **ACTION 1:** Read configuration files:
@@ -120,6 +120,33 @@ def read_rule_content(rule_name):
120
120
  return text
121
121
 
122
122
 
123
+ def load_memory_settings():
124
+ """
125
+ Load memory settings from .codeyam/config.json.
126
+ Returns dict with safe defaults when absent or malformed.
127
+ """
128
+ defaults = {
129
+ 'conversationReflection': True,
130
+ 'ruleMaintenance': True,
131
+ 'promptModel': 'haiku',
132
+ }
133
+ try:
134
+ project_dir = os.environ.get('CLAUDE_PROJECT_DIR', os.getcwd())
135
+ config_path = os.path.join(project_dir, '.codeyam', 'config.json')
136
+ with open(config_path, 'r') as f:
137
+ config = json.load(f)
138
+ memory = config.get('memory', {})
139
+ if not isinstance(memory, dict):
140
+ return defaults
141
+ return {
142
+ 'conversationReflection': memory.get('conversationReflection', True),
143
+ 'ruleMaintenance': memory.get('ruleMaintenance', True),
144
+ 'promptModel': memory.get('promptModel', 'haiku'),
145
+ }
146
+ except (IOError, json.JSONDecodeError, KeyError):
147
+ return defaults
148
+
149
+
123
150
  def get_stale_rules():
124
151
  """
125
152
  Run `codeyam memory status` and parse the output to find stale rules.
@@ -157,8 +184,8 @@ def get_stale_rules():
157
184
  # Look for the next few lines for details
158
185
  for j in range(i + 1, min(i + 4, len(lines))):
159
186
  detail = lines[j].strip()
160
- if detail.startswith('Rule timestamp:'):
161
- rule_info['rule_timestamp'] = detail.replace('Rule timestamp:', '').strip()
187
+ if detail.startswith('Last audited:'):
188
+ rule_info['last_audited'] = detail.replace('Last audited:', '').strip()
162
189
  elif detail.startswith('Newest file:'):
163
190
  rule_info['newest_file'] = detail.replace('Newest file:', '').strip()
164
191
  elif detail.startswith('File modified:'):
@@ -286,7 +313,7 @@ def build_stale_rules_context(stale_rules):
286
313
  parts.append("For each rule, review the rule content and the diff of changes, then:")
287
314
  parts.append("1. Determine if the rule content needs updating based on the code changes")
288
315
  parts.append("2. Update the rule if needed")
289
- parts.append("3. ALWAYS update the timestamp (run `codeyam memory touch`)\n")
316
+ parts.append("3. ALWAYS run `codeyam memory touch` to mark rules as audited\n")
290
317
 
291
318
  for rule in stale_rules:
292
319
  parts.append(f"### {rule['name']}")
@@ -298,8 +325,8 @@ def build_stale_rules_context(stale_rules):
298
325
  parts.append(f" Changed file: {rule['newest_file']}")
299
326
  if rule.get('file_modified'):
300
327
  parts.append(f" File modified: {rule['file_modified']}")
301
- if rule.get('rule_timestamp'):
302
- parts.append(f" Rule timestamp: {rule['rule_timestamp']}")
328
+ if rule.get('last_audited'):
329
+ parts.append(f" Last audited: {rule['last_audited']}")
303
330
  if rule.get('diff'):
304
331
  parts.append(f" Changes:")
305
332
  for line in rule['diff'].split('\n'):
@@ -373,7 +400,7 @@ def build_interruption_context(conversation_snippets, follow_up_prompt, modified
373
400
  return '\n'.join(parts)
374
401
 
375
402
 
376
- def spawn_claude_agent(prompt, log_file, project_dir):
403
+ def spawn_claude_agent(prompt, log_file, project_dir, model='haiku'):
377
404
  """Spawn a detached claude -p agent as a background process."""
378
405
  try:
379
406
  log_fh = open(log_file, 'w')
@@ -381,7 +408,8 @@ def spawn_claude_agent(prompt, log_file, project_dir):
381
408
  env['CODEYAM_RULE_AGENT'] = '1'
382
409
  subprocess.Popen(
383
410
  ['claude', '-p', prompt,
384
- '--model', 'haiku',
411
+ '--model', model,
412
+ '--no-session-persistence',
385
413
  '--output-format', 'stream-json', '--verbose',
386
414
  '--allowedTools', 'Read,Edit,Write,Bash,Glob,Grep'],
387
415
  cwd=project_dir,
@@ -427,6 +455,8 @@ def handle_stop(hook_input):
427
455
  agent spawn) runs first. The slow `get_stale_rules()` call (~10s) runs last
428
456
  so the hook timeout doesn't kill us before the critical work is done.
429
457
  """
458
+ settings = load_memory_settings()
459
+
430
460
  session_id = hook_input.get('session_id', '')
431
461
  transcript_path = hook_input.get('transcript_path', '')
432
462
 
@@ -452,8 +482,8 @@ def handle_stop(hook_input):
452
482
  invocation_ts = datetime.now().strftime('%Y%m%d-%H%M%S')
453
483
  invocation_id = f'{session_id}-{invocation_ts}'
454
484
 
455
- # Fast: spawn conversation review agent first
456
- if len(conversation_snippets) > 0:
485
+ # Fast: spawn conversation review agent first (if enabled)
486
+ if settings['conversationReflection'] and len(conversation_snippets) > 0:
457
487
  conv_context = build_conversation_context(conversation_snippets, modified_files)
458
488
  conv_context_file = marker_dir / f'{invocation_id}-conversation.context'
459
489
  conv_context_file.write_text(conv_context)
@@ -466,26 +496,27 @@ def handle_stop(hook_input):
466
496
  NOTIFICATION_FILE=str(conv_notification_file),
467
497
  PROJECT_DIR=project_dir,
468
498
  )
469
- spawn_claude_agent(conv_prompt, conv_log_file, project_dir)
499
+ spawn_claude_agent(conv_prompt, conv_log_file, project_dir, model=settings['promptModel'])
470
500
 
471
501
  # Slow (~10s): check for stale rules last — if the hook timeout kills us
472
502
  # here, the conversation agent and marker are already handled
473
- stale_rules = get_stale_rules()
474
-
475
- if len(stale_rules) > 0:
476
- stale_context = build_stale_rules_context(stale_rules)
477
- stale_context_file = marker_dir / f'{invocation_id}-stale.context'
478
- stale_context_file.write_text(stale_context)
479
-
480
- stale_log_file = marker_dir / f'{invocation_id}-stale.log'
481
- stale_notification_file = marker_dir / 'rule-notification-stale.md'
482
- stale_prompt = load_prompt_template(
483
- 'stale-rules-prompt.txt',
484
- CONTEXT_FILE=str(stale_context_file),
485
- NOTIFICATION_FILE=str(stale_notification_file),
486
- PROJECT_DIR=project_dir,
487
- )
488
- spawn_claude_agent(stale_prompt, stale_log_file, project_dir)
503
+ if settings['ruleMaintenance']:
504
+ stale_rules = get_stale_rules()
505
+
506
+ if len(stale_rules) > 0:
507
+ stale_context = build_stale_rules_context(stale_rules)
508
+ stale_context_file = marker_dir / f'{invocation_id}-stale.context'
509
+ stale_context_file.write_text(stale_context)
510
+
511
+ stale_log_file = marker_dir / f'{invocation_id}-stale.log'
512
+ stale_notification_file = marker_dir / 'rule-notification-stale.md'
513
+ stale_prompt = load_prompt_template(
514
+ 'stale-rules-prompt.txt',
515
+ CONTEXT_FILE=str(stale_context_file),
516
+ NOTIFICATION_FILE=str(stale_notification_file),
517
+ PROJECT_DIR=project_dir,
518
+ )
519
+ spawn_claude_agent(stale_prompt, stale_log_file, project_dir, model=settings['promptModel'])
489
520
 
490
521
 
491
522
  def handle_user_prompt_submit(hook_input):
@@ -495,6 +526,12 @@ def handle_user_prompt_submit(hook_input):
495
526
  marker file is stale (transcript has lines beyond the marker). If so, spawns a
496
527
  rule-reflection agent focused on the interruption.
497
528
  """
529
+ settings = load_memory_settings()
530
+
531
+ # Interruption detection is part of conversation reflection
532
+ if not settings['conversationReflection']:
533
+ return
534
+
498
535
  session_id = hook_input.get('session_id', '')
499
536
  transcript_path = hook_input.get('transcript_path', '')
500
537
  follow_up_prompt = hook_input.get('prompt', '')
@@ -561,7 +598,7 @@ def handle_user_prompt_submit(hook_input):
561
598
  NOTIFICATION_FILE=str(notification_file),
562
599
  PROJECT_DIR=project_dir,
563
600
  )
564
- spawn_claude_agent(prompt, log_file, project_dir)
601
+ spawn_claude_agent(prompt, log_file, project_dir, model=settings['promptModel'])
565
602
 
566
603
 
567
604
  def main():
@@ -6,7 +6,27 @@ Rules provide context-specific guidance when working in files matching their `pa
6
6
 
7
7
  1. **One concept per rule** - Each rule should cover a single topic. If you're documenting two unrelated things, create two rules.
8
8
  2. **Paths must match content scope** - A rule about one specific file should have that file in `paths`, not a broad `**/*.ts` pattern.
9
- 3. **Be concise** - Every word costs context. Use bullets and tables.
9
+ 3. **Keep rules SHORT** - Most rules should be **1-4 bullets**. Only complex multi-file architectural overviews should exceed ~10 lines. Every word costs context.
10
+
11
+ ### Good vs Bad Rule Length
12
+
13
+ **Good** — a typical rule (4 bullets):
14
+
15
+ ```markdown
16
+ ---
17
+ paths:
18
+ - 'packages/ai/src/lib/generateMockData.ts'
19
+ ---
20
+
21
+ # Mock Data Generation
22
+
23
+ - Entry point: `generateMockData()` in `generateMockData.ts`
24
+ - Uses `convertDotNotation` to transform flat schema into nested objects
25
+ - Schema entry ORDER matters — `key[]` must come before `key[].property` or arrays get overwritten
26
+ - Test with exact ordering from database, not just same entries
27
+ ```
28
+
29
+ **Bad** — same info bloated to 40+ lines with unnecessary headers, restating what the code says, and paragraphs instead of bullets.
10
30
 
11
31
  ## When to Create a New Rule
12
32
 
@@ -17,23 +37,13 @@ Create a new rule when:
17
37
  - The user explains something that isn't clear from the code
18
38
  - An existing rule is covering multiple unrelated topics (split it)
19
39
 
20
- ## Before Creating: The Confusion Test
40
+ ## Before Creating: What Makes a Rule Valuable?
21
41
 
22
- Only create rules that document genuinely confusing aspects—not things Claude can figure out by reading code and will likely come up again in future sessions.
42
+ A rule earns its place when it meets these criteria:
23
43
 
24
- **Ask yourself:**
25
-
26
- 1. **Could Claude figure this out by reading the code?**
27
- - If YES → don't create the rule
28
- - If NO → proceed
29
-
30
- 2. **Does this explain "why" not just "what"?**
31
- - Good: Historical context, gotchas, non-obvious behavior, non-obvious architectural decisions
32
- - Bad: Bug fixes, Limitations (unless the user requests the limitation be noted), What functions do (unless providing a high-level architectural overview)
33
-
34
- 3. **Would this have prevented a past mistake?**
35
- - If you can point to a bug or confusion this would have prevented → create it
36
- - If it's just "nice to know" → skip it
44
+ 1. **Beyond the code** — It captures knowledge that reading the source alone wouldn't reveal (historical context, non-obvious interactions, gotchas).
45
+ 2. **Explains "why" over "what"** — Gotchas, non-obvious behavior, architectural decisions. (Function signatures, bug fixes, and limitations are already visible in code.)
46
+ 3. **Prevents real mistakes** It would have saved someone from a past confusion or bug, not just a "nice to know."
37
47
 
38
48
  ### Examples
39
49
 
@@ -44,10 +54,7 @@ Only create rules that document genuinely confusing aspects—not things Claude
44
54
  - Debugging strategies for a particular area of the repo
45
55
  - "Use `pnpm test` to run tests" (if there is more than one way to run tests and this way is preferred)
46
56
 
47
- **❌ Not worth documenting:**
48
-
49
- - "The auth module handles authentication" (obvious from reading code)
50
- - "This function takes X and returns Y" (Claude can read the signature)
57
+ Skip things like "The auth module handles authentication" or "This function takes X and returns Y" — Claude can read the code and infer these.
51
58
 
52
59
  ## Path Specificity
53
60
 
@@ -60,17 +67,25 @@ The `paths` field controls when the rule is shown. Match the scope of your conte
60
67
  | Directory | `'path/to/dir/**/*.ts'` | Rule about the queue system in `utils/queue/` |
61
68
  | Cross-cutting | Multiple specific paths | Testing rule with paths to test configs and test files |
62
69
 
63
- **Anti-pattern**: Don't use `'**/*.ts'` for a rule about one specific feature.
70
+ Match path specificity to content scope — use `'path/to/feature.ts'` for a single-feature rule, not `'**/*.ts'`.
71
+
72
+ ## File Placement
64
73
 
65
- ## File Structure
74
+ Place each rule at the **deepest common directory** shared by all its `paths` entries:
66
75
 
67
- Rules mirror the source code structure:
76
+ 1. Take all paths from the rule's frontmatter
77
+ 2. Strip filenames — keep only the directory portions
78
+ 3. Find the longest shared directory prefix
79
+ 4. Place the rule `.md` file in `.claude/rules/<that-prefix>/`
68
80
 
69
- | Source Location | Rule Location |
70
- | -------------------- | --------------------------------------- |
71
- | `src/api/auth.ts` | `.claude/rules/src/api/auth.md` |
72
- | `src/utils/queue/**` | `.claude/rules/src/utils/queue.md` |
73
- | Test configuration | `.claude/rules/testing/jest-configs.md` |
81
+ | Paths in frontmatter | Deepest common dir | Rule location |
82
+ | ---------------------------------------------------------- | ---------------------- | ---------------------------------------------- |
83
+ | `packages/ai/src/lib/foo.ts`, `packages/ai/src/lib/bar.ts` | `packages/ai/src/lib/` | `.claude/rules/packages/ai/src/lib/foo-bar.md` |
84
+ | `packages/ai/src/lib/a.ts`, `packages/ai/src/utils/b.ts` | `packages/ai/src/` | `.claude/rules/packages/ai/src/a-and-b.md` |
85
+ | `packages/ai/**`, `packages/types/**` | `packages/` | `.claude/rules/packages/ai-types.md` |
86
+ | `src/api/auth.ts` (single file) | `src/api/` | `.claude/rules/src/api/auth.md` |
87
+
88
+ Reserve the top level of `.claude/rules/` for rules whose paths genuinely span the entire repo.
74
89
 
75
90
  ## Required Frontmatter
76
91
 
@@ -79,14 +94,14 @@ Rules mirror the source code structure:
79
94
  paths:
80
95
  - 'specific/path/to/file.ts'
81
96
  - 'another/specific/path/*.ts'
82
- timestamp: 2026-01-30T00:00:00Z
83
97
  ---
84
98
  ```
85
99
 
86
- | Field | Purpose |
87
- | ----------- | ---------------------------------------------------------------- |
88
- | `paths` | Glob patterns - be specific to avoid loading rules unnecessarily |
89
- | `timestamp` | ISO 8601 - update when rule is reviewed |
100
+ | Field | Purpose |
101
+ | ------- | ---------------------------------------------------------------- |
102
+ | `paths` | Glob patterns - be specific to avoid loading rules unnecessarily |
103
+
104
+ **Note:** Audit dates live in `.claude/codeyam-rule-state.json` (managed by `codeyam memory touch`). Keep rule frontmatter limited to `paths`.
90
105
 
91
106
  ## Content Guidelines
92
107
 
@@ -95,15 +110,9 @@ timestamp: 2026-01-30T00:00:00Z
95
110
  - Good: "Run `pnpm test:api` for API tests"
96
111
  - Bad: "Make sure to run the appropriate tests"
97
112
 
98
- ### Focus on What, Not What Not
99
-
100
- - Good: "Auth tokens are stored in httpOnly cookies via `src/auth/cookies.ts`"
101
- - Bad: "WARNING: Don't store tokens in localStorage!"
102
-
103
- ### Keep Rules Short
113
+ ### Focus on What to Do
104
114
 
105
- - Target 30-50 lines
106
- - If a rule exceeds 60 lines, consider splitting it
115
+ - "Auth tokens are stored in httpOnly cookies via `src/auth/cookies.ts`" tells the reader exactly where to look and what pattern to follow.
107
116
 
108
117
  ## Categories
109
118
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codeyam/codeyam-cli",
3
- "version": "0.1.0-staging.79ef713",
3
+ "version": "0.1.0-staging.7c30edc",
4
4
  "description": "Local development CLI for CodeYam analysis",
5
5
  "type": "module",
6
6
  "bin": {
@@ -3,10 +3,66 @@ import * as crypto from 'crypto';
3
3
  import { StructuredPath } from "./paths.js";
4
4
  import { nodeToSource } from "./nodeToSource.js";
5
5
  import { methodRegistry, ArrayPushSemantics } from "./methodSemantics.js";
6
- import { isArithmeticOperator, isAssignmentOperator, isBitwiseCompoundOperator, isComparisonOperator, isDefinedType, isNumericCompoundOperator, leftOrRightType, unwrapExpression, } from "./sharedPatterns.js";
6
+ import { getComparisonOperatorString, isArithmeticOperator, isAssignmentOperator, isBitwiseCompoundOperator, isComparisonOperator, isDefinedType, isNumericCompoundOperator, leftOrRightType, unwrapExpression, } from "./sharedPatterns.js";
7
7
  import { processBindingPattern } from "./processBindings.js";
8
8
  import { extractConditionalEffectsFromTernary, findUseStateSetters, } from "./conditionalEffectsExtractor.js";
9
9
  import { detectArrayDerivedPattern } from "./arrayDerivationDetector.js";
10
+ /**
11
+ * Recursively extracts root variable names from an expression AST node.
12
+ * Used to identify which variables flow into JSX expression children,
13
+ * so we can link them to the return value schema.
14
+ *
15
+ * Examples:
16
+ * - `filteredTopPaths.map(...)` → ['filteredTopPaths']
17
+ * - `a && b` → ['a', 'b']
18
+ * - `condition ? x : y` → ['condition', 'x', 'y']
19
+ */
20
+ function extractRootVariableNames(node) {
21
+ const ignoredIdentifiers = new Set([
22
+ 'undefined',
23
+ 'null',
24
+ 'true',
25
+ 'false',
26
+ 'NaN',
27
+ 'Infinity',
28
+ ]);
29
+ if (ts.isIdentifier(node)) {
30
+ const name = node.text;
31
+ return ignoredIdentifiers.has(name) ? [] : [name];
32
+ }
33
+ if (ts.isPropertyAccessExpression(node)) {
34
+ return extractRootVariableNames(node.expression);
35
+ }
36
+ if (ts.isCallExpression(node)) {
37
+ return extractRootVariableNames(node.expression);
38
+ }
39
+ if (ts.isBinaryExpression(node)) {
40
+ return [
41
+ ...extractRootVariableNames(node.left),
42
+ ...extractRootVariableNames(node.right),
43
+ ];
44
+ }
45
+ if (ts.isPrefixUnaryExpression(node)) {
46
+ return extractRootVariableNames(node.operand);
47
+ }
48
+ if (ts.isConditionalExpression(node)) {
49
+ return [
50
+ ...extractRootVariableNames(node.condition),
51
+ ...extractRootVariableNames(node.whenTrue),
52
+ ...extractRootVariableNames(node.whenFalse),
53
+ ];
54
+ }
55
+ if (ts.isParenthesizedExpression(node)) {
56
+ return extractRootVariableNames(node.expression);
57
+ }
58
+ // Stop recursion at JSX elements and other terminal nodes
59
+ if (ts.isJsxElement(node) ||
60
+ ts.isJsxFragment(node) ||
61
+ ts.isJsxSelfClosingElement(node)) {
62
+ return [];
63
+ }
64
+ return [];
65
+ }
10
66
  /**
11
67
  * Checks if a JSX element has props that reference variables from the parent scope.
12
68
  * This is used to detect unconditionally-rendered children that should have their
@@ -966,6 +1022,8 @@ export function extractConditionalUsage(condition, context, location, options =
966
1022
  }
967
1023
  return literalValue;
968
1024
  };
1025
+ // Get the comparison operator string for the compound condition
1026
+ const comparisonOperator = getComparisonOperatorString(unwrapped.operatorToken.kind);
969
1027
  // Helper to add a condition
970
1028
  const addCondition = (path, conditionType, comparedValues, requiredValue, sourceExpr) => {
971
1029
  const usage = {
@@ -1001,6 +1059,7 @@ export function extractConditionalUsage(condition, context, location, options =
1001
1059
  comparedValues,
1002
1060
  isNegated,
1003
1061
  requiredValue,
1062
+ ...(comparisonOperator && { comparisonOperator }),
1004
1063
  ...(chainInfo.currentOrGroupId && {
1005
1064
  orGroupId: chainInfo.currentOrGroupId,
1006
1065
  }),
@@ -2456,6 +2515,15 @@ export function processExpression({ node, context, targetPath, typeHint, }) {
2456
2515
  for (const child of unwrappedNode.children) {
2457
2516
  // Process expressions in JSX children: <div>{expr}</div>
2458
2517
  if (ts.isJsxExpression(child) && child.expression) {
2518
+ // When processing return value JSX, link root variables to return value schema
2519
+ if (targetPath && targetPath.base !== '') {
2520
+ const varNames = [
2521
+ ...new Set(extractRootVariableNames(child.expression)),
2522
+ ];
2523
+ for (const varName of varNames) {
2524
+ context.addEquivalence(targetPath.withProperty(varName), StructuredPath.fromBase(varName));
2525
+ }
2526
+ }
2459
2527
  // Process the expression with StructuredPath.empty() as targetPath
2460
2528
  // to trigger type registration without imposing prefix
2461
2529
  processExpression({
@@ -2486,6 +2554,15 @@ export function processExpression({ node, context, targetPath, typeHint, }) {
2486
2554
  for (const child of unwrappedNode.children) {
2487
2555
  // Process expressions in JSX children: <>{expr}</>
2488
2556
  if (ts.isJsxExpression(child) && child.expression) {
2557
+ // When processing return value JSX, link root variables to return value schema
2558
+ if (targetPath && targetPath.base !== '') {
2559
+ const varNames = [
2560
+ ...new Set(extractRootVariableNames(child.expression)),
2561
+ ];
2562
+ for (const varName of varNames) {
2563
+ context.addEquivalence(targetPath.withProperty(varName), StructuredPath.fromBase(varName));
2564
+ }
2565
+ }
2489
2566
  // Process the expression to extract structure
2490
2567
  processExpression({
2491
2568
  node: child.expression,