@cachly-dev/mcp-server 0.9.22 → 0.9.24

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.
@@ -606,3 +606,269 @@ describe('Brain E2E: learn → CKG → recall', () => {
606
606
  expect(lastAttempt.outcome).toBe('failure');
607
607
  });
608
608
  });
609
+
610
+ // ── Extended Brain Flow Scenarios ─────────────────────────────────────────────
611
+
612
+ describe('Brain Flow: advanced scenarios', () => {
613
+ let redis: MockRedis;
614
+ beforeEach(() => { redis = new MockRedis(); });
615
+
616
+ describe('recall_count and lesson update flow', () => {
617
+ it('partial outcome can later be upgraded to success', async () => {
618
+ await storeLessonInRedis(redis, {
619
+ topic: 'fix:timeout',
620
+ outcome: 'partial',
621
+ what_worked: 'increase timeout to 15s',
622
+ severity: 'major',
623
+ commands: [],
624
+ tags: [],
625
+ file_paths: [],
626
+ });
627
+ // Upgrade to success
628
+ await storeLessonInRedis(redis, {
629
+ topic: 'fix:timeout',
630
+ outcome: 'success',
631
+ what_worked: 'increase timeout to 30s + add retry logic',
632
+ severity: 'major',
633
+ commands: ['--timeout 30s', '--retry 3'],
634
+ tags: ['reliability'],
635
+ file_paths: [],
636
+ });
637
+
638
+ const best = JSON.parse((await redis.get('cachly:lesson:best:fix:timeout'))!) as LessonObj;
639
+ expect(best.outcome).toBe('success');
640
+ expect(best.what_worked).toContain('retry logic');
641
+
642
+ const history = await redis.lrange('cachly:lessons:fix:timeout', 0, -1);
643
+ expect(history).toHaveLength(2);
644
+ });
645
+
646
+ it('lesson version is always 3', async () => {
647
+ await storeLessonInRedis(redis, {
648
+ topic: 'deploy:mcp',
649
+ outcome: 'success',
650
+ what_worked: 'npm publish --access public',
651
+ severity: 'minor',
652
+ commands: [],
653
+ tags: [],
654
+ file_paths: [],
655
+ });
656
+ const lesson = JSON.parse((await redis.get('cachly:lesson:best:deploy:mcp'))!) as LessonObj;
657
+ expect(lesson.version).toBe(3);
658
+ });
659
+
660
+ it('verified_at is set for success/partial outcomes', async () => {
661
+ await storeLessonInRedis(redis, {
662
+ topic: 'infra:ssl',
663
+ outcome: 'success',
664
+ what_worked: 'certbot renew',
665
+ severity: 'critical',
666
+ commands: [],
667
+ tags: [],
668
+ file_paths: [],
669
+ });
670
+ const lesson = JSON.parse((await redis.get('cachly:lesson:best:infra:ssl'))!) as LessonObj;
671
+ expect(lesson.verified_at).toBeDefined();
672
+ expect(new Date(lesson.verified_at!).getTime()).toBeLessThanOrEqual(Date.now());
673
+ });
674
+
675
+ it('verified_at is NOT set for failure outcomes', async () => {
676
+ await storeLessonInRedis(redis, {
677
+ topic: 'infra:ssl',
678
+ outcome: 'failure',
679
+ what_worked: '',
680
+ severity: 'critical',
681
+ commands: [],
682
+ tags: [],
683
+ file_paths: [],
684
+ });
685
+ const lesson = JSON.parse((await redis.get('cachly:lesson:best:infra:ssl'))!) as LessonObj;
686
+ expect(lesson.verified_at).toBeUndefined();
687
+ });
688
+ });
689
+
690
+ describe('multi-topic lesson management', () => {
691
+ it('different topics do not interfere with each other', async () => {
692
+ const topics = [
693
+ { topic: 'deploy:api', what_worked: 'docker compose up api' },
694
+ { topic: 'deploy:web', what_worked: 'rsync + docker build web' },
695
+ { topic: 'deploy:mcp', what_worked: 'npm publish mcp server' },
696
+ { topic: 'infra:nginx', what_worked: 'nginx -t && systemctl reload' },
697
+ { topic: 'fix:memory', what_worked: 'increase heap to 4G' },
698
+ ];
699
+
700
+ for (const t of topics) {
701
+ await storeLessonInRedis(redis, { ...t, outcome: 'success', severity: 'minor', commands: [], tags: [], file_paths: [] });
702
+ }
703
+
704
+ for (const t of topics) {
705
+ const raw = await redis.get(`cachly:lesson:best:${t.topic}`);
706
+ expect(raw, `lesson for ${t.topic} should exist`).not.toBeNull();
707
+ const lesson = JSON.parse(raw!) as LessonObj;
708
+ expect(lesson.what_worked).toBe(t.what_worked);
709
+ }
710
+ });
711
+
712
+ it('all topics are reachable via scanStream', async () => {
713
+ const topics = ['alpha:test', 'beta:test', 'gamma:test', 'delta:test'];
714
+ for (const t of topics) {
715
+ await storeLessonInRedis(redis, { topic: t, outcome: 'success', what_worked: 'x', severity: 'minor', commands: [], tags: [], file_paths: [] });
716
+ }
717
+
718
+ const keys: string[] = [];
719
+ await new Promise<void>((resolve, reject) => {
720
+ const stream = redis.scanStream({ match: 'cachly:lesson:best:*', count: 100 });
721
+ stream.on('data', (batch: string[]) => keys.push(...batch));
722
+ stream.on('end', resolve);
723
+ stream.on('error', reject);
724
+ });
725
+
726
+ expect(keys).toHaveLength(4);
727
+ for (const t of topics) {
728
+ expect(keys.some(k => k.endsWith(t))).toBe(true);
729
+ }
730
+ });
731
+
732
+ it('pipeline fetches all lessons in a single batch', async () => {
733
+ const topics = ['a:1', 'b:2', 'c:3'];
734
+ for (const t of topics) {
735
+ await storeLessonInRedis(redis, { topic: t, outcome: 'success', what_worked: 'fix', severity: 'minor', commands: [], tags: [], file_paths: [] });
736
+ }
737
+
738
+ const keys = topics.map(t => `cachly:lesson:best:${t}`);
739
+ const pipeline = redis.pipeline();
740
+ for (const k of keys) pipeline.get(k);
741
+ const results = await pipeline.exec();
742
+
743
+ expect(results).toHaveLength(3);
744
+ for (const [err, val] of results) {
745
+ expect(err).toBeNull();
746
+ expect(val).not.toBeNull();
747
+ const lesson = JSON.parse(val as string) as LessonObj;
748
+ expect(lesson.outcome).toBe('success');
749
+ }
750
+ });
751
+ });
752
+
753
+ describe('BM25 recency boost integration', () => {
754
+ it('newer lesson with same content ranks higher than older', async () => {
755
+ // Seed two similar lessons — same keywords, different age
756
+ const oldTs = new Date(Date.now() - 30 * 86400000).toISOString(); // 30 days ago
757
+
758
+ // Store "old" lesson manually with backdated timestamp
759
+ const oldLesson: LessonObj = {
760
+ topic: 'deploy:old',
761
+ outcome: 'success',
762
+ what_worked: 'docker compose deploy redis service restart',
763
+ what_failed: undefined,
764
+ context: undefined,
765
+ severity: 'minor',
766
+ commands: [],
767
+ tags: [],
768
+ file_paths: [],
769
+ recall_count: 0,
770
+ ts: oldTs,
771
+ verified_at: oldTs,
772
+ confidence: 1.0,
773
+ audit_trail: [{ ts: oldTs, action: 'created' }],
774
+ version: 3,
775
+ };
776
+ await redis.rpush('cachly:lessons:deploy:old', JSON.stringify(oldLesson));
777
+ await redis.set('cachly:lesson:best:deploy:old', JSON.stringify(oldLesson));
778
+
779
+ // Store "new" lesson with current timestamp (similar content, different service)
780
+ await storeLessonInRedis(redis, {
781
+ topic: 'deploy:new',
782
+ outcome: 'success',
783
+ what_worked: 'docker compose deploy redis service restart',
784
+ severity: 'minor',
785
+ commands: [],
786
+ tags: [],
787
+ file_paths: [],
788
+ });
789
+
790
+ const results = await keywordSearch(
791
+ redis as unknown as Redis,
792
+ ['cachly:lesson:best:*'],
793
+ 'docker compose redis restart',
794
+ 5,
795
+ );
796
+
797
+ // Both should match; newer should rank higher or equal
798
+ expect(results.length).toBe(2);
799
+ const newIdx = results.findIndex(r => r.key.includes('deploy:new'));
800
+ const oldIdx = results.findIndex(r => r.key.includes('deploy:old'));
801
+ expect(newIdx).toBeLessThanOrEqual(oldIdx); // new ≤ old (higher rank = lower index)
802
+ });
803
+
804
+ it('lesson with matching topic-keyword gets higher BM25 score', async () => {
805
+ await storeLessonInRedis(redis, {
806
+ topic: 'fix:ssl-certificate',
807
+ outcome: 'success',
808
+ what_worked: 'renew SSL certificate via certbot on Nginx',
809
+ severity: 'critical',
810
+ commands: ['certbot renew'],
811
+ tags: ['ssl', 'nginx'],
812
+ file_paths: [],
813
+ });
814
+ await storeLessonInRedis(redis, {
815
+ topic: 'deploy:api',
816
+ outcome: 'success',
817
+ what_worked: 'docker compose up -d api',
818
+ severity: 'minor',
819
+ commands: [],
820
+ tags: [],
821
+ file_paths: [],
822
+ });
823
+
824
+ const results = await keywordSearch(
825
+ redis as unknown as Redis,
826
+ ['cachly:lesson:best:*'],
827
+ 'ssl certificate nginx renew',
828
+ 5,
829
+ );
830
+
831
+ expect(results.length).toBeGreaterThan(0);
832
+ expect(results[0].content.toLowerCase()).toContain('ssl');
833
+ });
834
+ });
835
+
836
+ describe('CKG multi-edge scenarios', () => {
837
+ it('same node can have multiple typed edges to different targets', async () => {
838
+ const r = redis as unknown as Redis;
839
+ await ckgUpsertNode(r, 'api-service', 'backend', 'concept');
840
+ await ckgUpdateEdge(r, 'api-service', 'depends_on', 'postgres', true);
841
+ await ckgUpdateEdge(r, 'api-service', 'depends_on', 'redis', true);
842
+ await ckgUpdateEdge(r, 'api-service', 'deployed_with', 'docker', true);
843
+
844
+ const fromIdx = await redis.smembers('cachly:ckg:idx:from:api-service');
845
+ expect(fromIdx).toHaveLength(3);
846
+ expect(fromIdx.some(k => k.includes('postgres'))).toBe(true);
847
+ expect(fromIdx.some(k => k.includes('redis'))).toBe(true);
848
+ expect(fromIdx.some(k => k.includes('docker'))).toBe(true);
849
+ });
850
+
851
+ it('same edge accumulates confidence across multiple successes', async () => {
852
+ const r = redis as unknown as Redis;
853
+ for (let i = 0; i < 10; i++) {
854
+ await ckgUpdateEdge(r, 'problem', 'solved_by', 'solution', true);
855
+ }
856
+ const edge = JSON.parse((await redis.get('cachly:ckg:edge:problem:solved_by:solution'))!);
857
+ // After 10 successes: (10+1)/(10+2) = 11/12 ≈ 0.9167
858
+ expect(edge.confidence).toBeGreaterThan(0.9);
859
+ expect(edge.trials).toBe(10);
860
+ expect(edge.successes).toBe(10);
861
+ });
862
+
863
+ it('mixed success/failure converges to true rate', async () => {
864
+ const r = redis as unknown as Redis;
865
+ // 6 success, 4 failure = 60% actual rate
866
+ for (let i = 0; i < 6; i++) await ckgUpdateEdge(r, 'X', 'leads_to', 'Y', true);
867
+ for (let i = 0; i < 4; i++) await ckgUpdateEdge(r, 'X', 'leads_to', 'Y', false);
868
+ const edge = JSON.parse((await redis.get('cachly:ckg:edge:X:leads_to:Y'))!);
869
+ // Beta(6+1, 10+2) = 7/12 ≈ 0.583 — close to 60%
870
+ expect(edge.confidence).toBeGreaterThan(0.5);
871
+ expect(edge.confidence).toBeLessThan(0.75);
872
+ });
873
+ });
874
+ });
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Tests for confidence.ts
3
+ *
4
+ * Covers:
5
+ * calculateConfidence – decay model (fresh / aging / warn / stale)
6
+ * confidenceBadge – emoji + human label
7
+ * simpleHash – determinism, uniqueness, fixed length
8
+ * STRUCTURED_TEMPLATES – required fields, hints
9
+ * Constants – sensible defaults and relationships
10
+ *
11
+ * Run: npx vitest run src/__tests__/confidence.test.ts
12
+ */
13
+
14
+ import { describe, it, expect } from 'vitest';
15
+ import {
16
+ calculateConfidence,
17
+ confidenceBadge,
18
+ STRUCTURED_TEMPLATES,
19
+ CONFIDENCE_WARN_DAYS,
20
+ CONFIDENCE_STALE_DAYS,
21
+ CONFIDENCE_WARN_VALUE,
22
+ CONFIDENCE_STALE_VALUE,
23
+ simpleHash,
24
+ } from '../confidence.js';
25
+
26
+ // ── Constant sanity ───────────────────────────────────────────────────────────
27
+
28
+ describe('Confidence constants', () => {
29
+ it('CONFIDENCE_WARN_DAYS < CONFIDENCE_STALE_DAYS', () => {
30
+ expect(CONFIDENCE_WARN_DAYS).toBeLessThan(CONFIDENCE_STALE_DAYS);
31
+ });
32
+
33
+ it('CONFIDENCE_WARN_VALUE > CONFIDENCE_STALE_VALUE', () => {
34
+ expect(CONFIDENCE_WARN_VALUE).toBeGreaterThan(CONFIDENCE_STALE_VALUE);
35
+ });
36
+
37
+ it('CONFIDENCE_WARN_VALUE < 1.0 and > 0', () => {
38
+ expect(CONFIDENCE_WARN_VALUE).toBeLessThan(1.0);
39
+ expect(CONFIDENCE_WARN_VALUE).toBeGreaterThan(0);
40
+ });
41
+
42
+ it('CONFIDENCE_STALE_VALUE < 1.0 and > 0', () => {
43
+ expect(CONFIDENCE_STALE_VALUE).toBeLessThan(1.0);
44
+ expect(CONFIDENCE_STALE_VALUE).toBeGreaterThan(0);
45
+ });
46
+
47
+ it('defaults to 5 warn days and 10 stale days (when env vars absent)', () => {
48
+ // These may be overridden via env, but assert sensible defaults
49
+ expect(CONFIDENCE_WARN_DAYS).toBeGreaterThanOrEqual(1);
50
+ expect(CONFIDENCE_STALE_DAYS).toBeGreaterThanOrEqual(CONFIDENCE_WARN_DAYS + 1);
51
+ });
52
+ });
53
+
54
+ // ── calculateConfidence ───────────────────────────────────────────────────────
55
+
56
+ describe('calculateConfidence', () => {
57
+ /** Returns an ISO timestamp that is `days` old from now. */
58
+ function tsAgo(days: number): string {
59
+ return new Date(Date.now() - days * 86400000).toISOString();
60
+ }
61
+
62
+ it('returns 1.0 for brand-new lesson (age ≈ 0)', () => {
63
+ const c = calculateConfidence({ ts: new Date().toISOString() });
64
+ expect(c).toBeCloseTo(1.0, 2);
65
+ });
66
+
67
+ it('prefers verified_at over ts', () => {
68
+ // ts is very old, but verified_at is recent → should NOT be stale
69
+ const c = calculateConfidence({
70
+ ts: tsAgo(365),
71
+ verified_at: tsAgo(0),
72
+ });
73
+ expect(c).toBeCloseTo(1.0, 2);
74
+ });
75
+
76
+ it('returns exactly CONFIDENCE_WARN_VALUE at exactly CONFIDENCE_WARN_DAYS', () => {
77
+ const c = calculateConfidence({ ts: tsAgo(CONFIDENCE_WARN_DAYS) });
78
+ // At exactly the warn threshold the function returns CONFIDENCE_WARN_VALUE
79
+ expect(c).toBeCloseTo(CONFIDENCE_WARN_VALUE, 3);
80
+ });
81
+
82
+ it('returns exactly CONFIDENCE_STALE_VALUE at exactly CONFIDENCE_STALE_DAYS', () => {
83
+ const c = calculateConfidence({ ts: tsAgo(CONFIDENCE_STALE_DAYS) });
84
+ expect(c).toBe(CONFIDENCE_STALE_VALUE);
85
+ });
86
+
87
+ it('caps at CONFIDENCE_STALE_VALUE for very old lessons', () => {
88
+ const c = calculateConfidence({ ts: tsAgo(365) });
89
+ expect(c).toBe(CONFIDENCE_STALE_VALUE);
90
+ });
91
+
92
+ it('linearly decreases between 0 and CONFIDENCE_WARN_DAYS', () => {
93
+ const midDays = CONFIDENCE_WARN_DAYS / 2;
94
+ const c = calculateConfidence({ ts: tsAgo(midDays) });
95
+ // at half-way to warn: 1.0 - (0.5 * (1.0 - CONFIDENCE_WARN_VALUE))
96
+ const expected = 1.0 - 0.5 * (1.0 - CONFIDENCE_WARN_VALUE);
97
+ expect(c).toBeCloseTo(expected, 3);
98
+ });
99
+
100
+ it('is monotonically decreasing with age', () => {
101
+ const c0 = calculateConfidence({ ts: tsAgo(0) });
102
+ const c1 = calculateConfidence({ ts: tsAgo(CONFIDENCE_WARN_DAYS * 0.3) });
103
+ const c2 = calculateConfidence({ ts: tsAgo(CONFIDENCE_WARN_DAYS * 0.7) });
104
+ const c3 = calculateConfidence({ ts: tsAgo(CONFIDENCE_WARN_DAYS) });
105
+ const c4 = calculateConfidence({ ts: tsAgo(CONFIDENCE_STALE_DAYS) });
106
+ expect(c0).toBeGreaterThanOrEqual(c1);
107
+ expect(c1).toBeGreaterThan(c2);
108
+ expect(c2).toBeGreaterThan(c3);
109
+ expect(c3).toBeGreaterThan(c4);
110
+ });
111
+
112
+ it('value between WARN and STALE ages equals CONFIDENCE_WARN_VALUE', () => {
113
+ const betweenDays = (CONFIDENCE_WARN_DAYS + CONFIDENCE_STALE_DAYS) / 2;
114
+ const c = calculateConfidence({ ts: tsAgo(betweenDays) });
115
+ expect(c).toBe(CONFIDENCE_WARN_VALUE);
116
+ });
117
+
118
+ it('ignores recall_count (not used in calculation)', () => {
119
+ const ts = new Date().toISOString();
120
+ const c1 = calculateConfidence({ ts, recall_count: 0 });
121
+ const c2 = calculateConfidence({ ts, recall_count: 100 });
122
+ expect(c1).toBeCloseTo(c2, 5);
123
+ });
124
+ });
125
+
126
+ // ── confidenceBadge ───────────────────────────────────────────────────────────
127
+
128
+ describe('confidenceBadge', () => {
129
+ it('returns ✅ for confidence >= 0.9 (fresh)', () => {
130
+ expect(confidenceBadge(1.0, 0)).toBe('✅');
131
+ expect(confidenceBadge(0.9, 1)).toBe('✅');
132
+ expect(confidenceBadge(0.95, 2)).toBe('✅');
133
+ });
134
+
135
+ it('returns ⚠️ prefix for warn range [0.7, 0.9)', () => {
136
+ const badge = confidenceBadge(0.7, 6);
137
+ expect(badge).toMatch(/^⚠️/);
138
+ expect(badge).toContain('6d old');
139
+ expect(badge).toContain('70%');
140
+ expect(badge).toContain('verify before applying');
141
+ });
142
+
143
+ it('⚠️ badge rounds age to nearest day', () => {
144
+ const badge = confidenceBadge(0.75, 4.6);
145
+ expect(badge).toContain('5d old'); // Math.round(4.6) = 5
146
+ });
147
+
148
+ it('returns 🔴 STALE prefix for confidence < 0.7', () => {
149
+ const badge = confidenceBadge(0.5, 12);
150
+ expect(badge).toMatch(/^🔴 STALE/);
151
+ expect(badge).toContain('12d old');
152
+ expect(badge).toContain('50%');
153
+ expect(badge).toContain('likely outdated');
154
+ });
155
+
156
+ it('🔴 badge for exactly 0.0 confidence', () => {
157
+ const badge = confidenceBadge(0.0, 99);
158
+ expect(badge).toMatch(/^🔴 STALE/);
159
+ expect(badge).toContain('0%');
160
+ });
161
+
162
+ it('edge: confidence exactly 0.7 returns ⚠️ (not 🔴)', () => {
163
+ const badge = confidenceBadge(0.7, 5);
164
+ expect(badge).toMatch(/^⚠️/);
165
+ });
166
+
167
+ it('edge: confidence exactly 0.9 returns ✅ (not ⚠️)', () => {
168
+ expect(confidenceBadge(0.9, 1)).toBe('✅');
169
+ });
170
+ });
171
+
172
+ // ── simpleHash ────────────────────────────────────────────────────────────────
173
+
174
+ describe('simpleHash', () => {
175
+ it('returns exactly 12 characters', () => {
176
+ expect(simpleHash('hello world')).toHaveLength(12);
177
+ expect(simpleHash('')).toHaveLength(12);
178
+ expect(simpleHash('x'.repeat(10000))).toHaveLength(12);
179
+ });
180
+
181
+ it('returns only hex characters [0-9a-f]', () => {
182
+ const hash = simpleHash('test input 123');
183
+ expect(hash).toMatch(/^[0-9a-f]{12}$/);
184
+ });
185
+
186
+ it('is deterministic — same input always yields same hash', () => {
187
+ const input = 'docker compose up -d --build api';
188
+ const h1 = simpleHash(input);
189
+ const h2 = simpleHash(input);
190
+ const h3 = simpleHash(input);
191
+ expect(h1).toBe(h2);
192
+ expect(h2).toBe(h3);
193
+ });
194
+
195
+ it('different inputs yield different hashes (collision resistance)', () => {
196
+ const inputs = [
197
+ 'deploy:api',
198
+ 'deploy:web',
199
+ 'fix:redis-timeout',
200
+ 'infra:clickhouse',
201
+ '',
202
+ 'a',
203
+ ' ',
204
+ '0',
205
+ ];
206
+ const hashes = inputs.map(simpleHash);
207
+ const unique = new Set(hashes);
208
+ expect(unique.size).toBe(inputs.length);
209
+ });
210
+
211
+ it('is sensitive to character order', () => {
212
+ expect(simpleHash('abc')).not.toBe(simpleHash('cba'));
213
+ expect(simpleHash('ab')).not.toBe(simpleHash('ba'));
214
+ });
215
+
216
+ it('is sensitive to whitespace differences', () => {
217
+ expect(simpleHash('hello world')).not.toBe(simpleHash('helloworld'));
218
+ expect(simpleHash('hello world')).not.toBe(simpleHash('hello world'));
219
+ });
220
+
221
+ it('works with unicode input', () => {
222
+ const h1 = simpleHash('日本語テスト');
223
+ const h2 = simpleHash('中文测试');
224
+ expect(h1).toHaveLength(12);
225
+ expect(h2).toHaveLength(12);
226
+ expect(h1).not.toBe(h2);
227
+ });
228
+
229
+ it('works with newlines and special chars', () => {
230
+ const h = simpleHash('line1\nline2\ttab\r\n');
231
+ expect(h).toHaveLength(12);
232
+ expect(h).toMatch(/^[0-9a-f]{12}$/);
233
+ });
234
+ });
235
+
236
+ // ── STRUCTURED_TEMPLATES ──────────────────────────────────────────────────────
237
+
238
+ describe('STRUCTURED_TEMPLATES', () => {
239
+ it('contains all expected category keys', () => {
240
+ const expected = ['deploy', 'bash', 'infra', 'pricing', 'stripe'];
241
+ for (const key of expected) {
242
+ expect(STRUCTURED_TEMPLATES, `Missing key: "${key}"`).toHaveProperty(key);
243
+ }
244
+ });
245
+
246
+ it('every entry has a non-empty hint string', () => {
247
+ for (const [key, tmpl] of Object.entries(STRUCTURED_TEMPLATES)) {
248
+ expect(typeof tmpl.hint, `hint for "${key}" is not a string`).toBe('string');
249
+ expect(tmpl.hint.length, `hint for "${key}" is empty`).toBeGreaterThan(0);
250
+ }
251
+ });
252
+
253
+ it('every entry has a required array', () => {
254
+ for (const [key, tmpl] of Object.entries(STRUCTURED_TEMPLATES)) {
255
+ expect(Array.isArray(tmpl.required), `required for "${key}" is not an array`).toBe(true);
256
+ }
257
+ });
258
+
259
+ it('deploy / bash / infra require commands[]', () => {
260
+ for (const key of ['deploy', 'bash', 'infra']) {
261
+ expect(STRUCTURED_TEMPLATES[key].required, `${key} should require commands`).toContain('commands');
262
+ }
263
+ });
264
+
265
+ it('pricing / stripe have empty required list (free-form)', () => {
266
+ expect(STRUCTURED_TEMPLATES['pricing'].required).toHaveLength(0);
267
+ expect(STRUCTURED_TEMPLATES['stripe'].required).toHaveLength(0);
268
+ });
269
+
270
+ it('hints mention the category key', () => {
271
+ for (const [key, tmpl] of Object.entries(STRUCTURED_TEMPLATES)) {
272
+ expect(tmpl.hint.toLowerCase(), `hint for "${key}" should mention the key`).toContain(key);
273
+ }
274
+ });
275
+
276
+ it('is a plain object (not prototype-polluted)', () => {
277
+ expect(Object.getPrototypeOf(STRUCTURED_TEMPLATES)).toBe(Object.prototype);
278
+ });
279
+
280
+ it('all category keys are valid topic prefixes (lowercase, no special chars)', () => {
281
+ for (const key of Object.keys(STRUCTURED_TEMPLATES)) {
282
+ expect(key).toMatch(/^[a-z][a-z0-9_-]*$/);
283
+ }
284
+ });
285
+ });