@linxin666/dsh-pet 0.4.7 → 0.4.9

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 (60) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +8 -2
  3. package/README.zh.md +8 -2
  4. package/contracts/voice-pack-v1.schema.json +27 -0
  5. package/lib/client.js +144 -68
  6. package/lib/client.js.map +1 -1
  7. package/lib/index.js +160 -28
  8. package/lib/types/affinity.d.ts +26 -3
  9. package/lib/types/affinity.d.ts.map +1 -1
  10. package/lib/types/affinity.js +27 -4
  11. package/lib/types/client/PetDockEntry.d.ts +5 -0
  12. package/lib/types/client/PetDockEntry.d.ts.map +1 -1
  13. package/lib/types/client/PetDockEntry.js +1 -1
  14. package/lib/types/client/PetSprite.d.ts +11 -4
  15. package/lib/types/client/PetSprite.d.ts.map +1 -1
  16. package/lib/types/client/PetSprite.js +120 -58
  17. package/lib/types/client/index.d.ts.map +1 -1
  18. package/lib/types/client/index.js +15 -1
  19. package/lib/types/client/sequences.d.ts +9 -2
  20. package/lib/types/client/sequences.d.ts.map +1 -1
  21. package/lib/types/client/sequences.js +25 -14
  22. package/lib/types/client/spritesheet.d.ts +22 -1
  23. package/lib/types/client/spritesheet.d.ts.map +1 -1
  24. package/lib/types/client/spritesheet.js +26 -2
  25. package/lib/types/index.d.ts +1 -1
  26. package/lib/types/index.d.ts.map +1 -1
  27. package/lib/types/ledger.d.ts +10 -1
  28. package/lib/types/ledger.d.ts.map +1 -1
  29. package/lib/types/ledger.js +11 -1
  30. package/lib/types/pair-access.d.ts.map +1 -1
  31. package/lib/types/pair-access.js +26 -3
  32. package/lib/types/service.d.ts +14 -12
  33. package/lib/types/service.d.ts.map +1 -1
  34. package/lib/types/service.js +22 -17
  35. package/lib/types/voice-pack.d.ts +20 -1
  36. package/lib/types/voice-pack.d.ts.map +1 -1
  37. package/lib/types/voice-pack.js +86 -3
  38. package/package.json +24 -24
  39. package/src/affinity.test.ts +42 -0
  40. package/src/affinity.ts +46 -3
  41. package/src/client/PetDockEntry.tsx +6 -0
  42. package/src/client/PetSprite.test.tsx +304 -26
  43. package/src/client/PetSprite.tsx +123 -58
  44. package/src/client/index.test.tsx +4 -0
  45. package/src/client/index.ts +15 -1
  46. package/src/client/pet-css.test.ts +12 -0
  47. package/src/client/pet.module.css +9 -3
  48. package/src/client/sequences.test.ts +37 -1
  49. package/src/client/sequences.ts +42 -16
  50. package/src/client/spritesheet.test.ts +81 -0
  51. package/src/client/spritesheet.ts +27 -2
  52. package/src/index.ts +2 -0
  53. package/src/ledger.test.ts +19 -0
  54. package/src/ledger.ts +15 -1
  55. package/src/pair-access.ts +26 -3
  56. package/src/registry.test.ts +2 -1
  57. package/src/service.test.ts +61 -0
  58. package/src/service.ts +27 -18
  59. package/src/voice-pack.test.ts +112 -0
  60. package/src/voice-pack.ts +101 -3
package/src/index.ts CHANGED
@@ -48,6 +48,8 @@ export {
48
48
  } from './affinity.ts'
49
49
  export type {
50
50
  AffinityConfig,
51
+ AffinityRank,
52
+ AffinityRankName,
51
53
  AffinityState,
52
54
  InteractionOutcome,
53
55
  PetInteraction,
@@ -43,6 +43,25 @@ describe('PetLedger', () => {
43
43
  expect(ledger.takeDirty()).toBe(false)
44
44
  })
45
45
 
46
+ it('renames ranks from a declared ladder without touching points', () => {
47
+ const ledger = new PetLedger(emptyPersist(), {
48
+ rankLadder: [
49
+ { min: 0, name: '小煤球', nameEn: 'Little Coal Ball' },
50
+ { min: 25, name: '火星伙伴' },
51
+ ],
52
+ })
53
+ expect(ledger.affinityView(1_000_000).rank).toBe('小煤球')
54
+ expect(ledger.affinityView(1_000_000).rankEn).toBe('Little Coal Ball')
55
+ expect(ledger.snapshot.affinity.points).toBe(0)
56
+
57
+ // Re-seating on a pet switch swaps the ladder without a ledger write.
58
+ ledger.setRankLadder([{ min: 0, name: '新名字' }])
59
+ expect(ledger.affinityView(1_000_000).rank).toBe('新名字')
60
+ expect(ledger.affinityView(1_000_000).rankEn).toBeUndefined()
61
+ expect(ledger.takeDirty()).toBe(false)
62
+ expect(ledger.snapshot.affinity.points).toBe(0)
63
+ })
64
+
46
65
  it('grants and spends gameplay treats through the shared stock, capped', () => {
47
66
  const ledger = new PetLedger(emptyPersist())
48
67
  expect(ledger.grantTreats(3)).toBe(true)
package/src/ledger.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  applyTurnReward,
14
14
  defaultAffinityConfig,
15
15
  type AffinityConfig,
16
+ type AffinityRankName,
16
17
  type PetAffinityView,
17
18
  type PetInteraction,
18
19
  } from './affinity.ts'
@@ -34,6 +35,8 @@ export interface LedgerConfig {
34
35
  remarks?: PetRemarks
35
36
  /** Voice-pack fallback remark pools (global or pet voice pack). */
36
37
  voiceRemarks?: PetRemarks
38
+ /** Display-only rank ladder for the selected pet (voice.json panel.ranks). */
39
+ rankLadder?: readonly AffinityRankName[]
37
40
  }
38
41
 
39
42
  /** Result of one ledger interaction (the shape the pet RPC returns). */
@@ -56,6 +59,8 @@ export class PetLedger {
56
59
  private readonly treatConfig: TreatConfig
57
60
  /** Round-robin reaction picker; rebuilt when the selected pet changes. */
58
61
  private picker: RemarkPicker
62
+ /** Declared rank ladder; undefined keeps the built-in whale ladder. */
63
+ private rankLadder: readonly AffinityRankName[] | undefined
59
64
  private current: PetPersist
60
65
  /** Completed turns already rewarded, per session (turn numbers are per-session). */
61
66
  private rewardedTurns = new Map<string, number>()
@@ -66,6 +71,7 @@ export class PetLedger {
66
71
  this.affinityConfig = { ...defaultAffinityConfig, ...(config.affinity ?? {}) }
67
72
  this.treatConfig = { ...defaultTreatConfig, ...(config.treats ?? {}) }
68
73
  this.picker = new RemarkPicker(config.remarks, config.voiceRemarks)
74
+ this.rankLadder = config.rankLadder
69
75
  this.current = persist
70
76
  }
71
77
 
@@ -156,6 +162,14 @@ export class PetLedger {
156
162
  this.picker = new RemarkPicker(remarks, voiceRemarks)
157
163
  }
158
164
 
165
+ /**
166
+ * Swap the display-only rank ladder to the selected pet's declared one
167
+ * (called on pet selection). Undefined restores the built-in ladder.
168
+ */
169
+ setRankLadder(ladder?: readonly AffinityRankName[]): void {
170
+ this.rankLadder = ladder
171
+ }
172
+
159
173
  /**
160
174
  * Settle the treat economy (work + time output since the last settlement).
161
175
  * A zero-gain first settlement still starts the time clock (anchor write),
@@ -279,6 +293,6 @@ export class PetLedger {
279
293
 
280
294
  /** Current affinity view for the RPC snapshot. */
281
295
  affinityView(nowMs: number): PetAffinityView {
282
- return affinityViewOf(this.current.affinity, nowMs, this.affinityConfig)
296
+ return affinityViewOf(this.current.affinity, nowMs, this.affinityConfig, this.rankLadder)
283
297
  }
284
298
  }
@@ -37,9 +37,32 @@ interface LookupCtx {
37
37
  */
38
38
  export function isPairedOrLoopbackAllowed(ctx: LookupCtx, request: IncomingMessage): boolean {
39
39
  if (isLoopbackRequest(request)) return true
40
- const fromGet = typeof ctx.get === 'function' ? ctx.get('remoteWebUiPairing', false) : undefined
41
- const pairing = (isPairingAccess(fromGet) ? fromGet : ctx.remoteWebUiPairing)
42
- return pairing?.isPairedDevice(request) === true
40
+ return lookupPairing(ctx)?.isPairedDevice(request) === true
41
+ }
42
+
43
+ /**
44
+ * The pairing service, or undefined when this composition does not expose it.
45
+ *
46
+ * Two lookups exist because the fence is shared with test harnesses that hand
47
+ * over a bare object: a real cordis context resolves services through `get`, a
48
+ * harness may carry the property directly. `get(name, false)` is the
49
+ * non-strict form, so an unloaded service answers undefined rather than
50
+ * throwing. Reading an un-injected service as a PROPERTY throws instead
51
+ * (`cannot get property "remoteWebUiPairing" without inject`); a trust fence
52
+ * must answer "not paired" in that case, never leak the error into the route
53
+ * handler, where the host web server turns it into an empty-body 400 (#1942).
54
+ */
55
+ function lookupPairing(ctx: LookupCtx): PairingAccess | undefined {
56
+ if (typeof ctx.get === 'function') {
57
+ const viaGet = ctx.get('remoteWebUiPairing', false)
58
+ return isPairingAccess(viaGet) ? viaGet : undefined
59
+ }
60
+ try {
61
+ const viaProperty = ctx.remoteWebUiPairing
62
+ return isPairingAccess(viaProperty) ? viaProperty : undefined
63
+ } catch {
64
+ return undefined
65
+ }
43
66
  }
44
67
 
45
68
  function isPairingAccess(value: unknown): value is PairingAccess {
@@ -316,13 +316,14 @@ describe('loadPetRegistry', () => {
316
316
 
317
317
  // The repo checkout also resolves doro and miku (frames2d gameplay pets),
318
318
  // jyn, jyn-foxtail and jyn-loli (frames2d gameplay pets), long-niang
319
- // (sprite2d pet) and starry-doll (community sprite2d pet) from
319
+ // (sprite2d pet), starry-doll and deep-chan (community sprite2d pets) from
320
320
  // assets/; the npm files whitelist excludes them (Workshop delivery), so
321
321
  // npm installs see the atlas pets until a Workshop install lands them
322
322
  // under $DSH_HOME/pets. blue-throated-bee-eater ships bundled alongside
323
323
  // the other atlas pets.
324
324
  expect(registry.entries.map(entry => entry.id)).toEqual([
325
325
  'blue-throated-bee-eater',
326
+ 'deep-chan',
326
327
  'doro',
327
328
  'jyn',
328
329
  'jyn-foxtail',
@@ -73,6 +73,39 @@ function serviceWithPetVoicePack(id: string, remarks: Record<string, string[]>):
73
73
  return new PetService(fakeRootContext(), { registry, persistDir: tempDir() })
74
74
  }
75
75
 
76
+ /**
77
+ * A service whose global voice pack and one pet directory each declare a
78
+ * display-only rank ladder, so the merge precedence is observable end to end.
79
+ */
80
+ function serviceWithRankLadders(): PetService {
81
+ const petsDir = tempDir()
82
+ writeFileSync(join(petsDir, '.voice.json'), JSON.stringify({
83
+ voicePackVersion: 1,
84
+ panel: { ranks: [{ min: 0, name: '通用小鲸' }, { min: 25, name: '通用伙伴' }] },
85
+ }), 'utf8')
86
+ const petDir = join(petsDir, 'coalball')
87
+ mkdirSync(petDir, { recursive: true })
88
+ writeFileSync(join(petDir, 'pet.json'), JSON.stringify({
89
+ petManifestVersion: 2,
90
+ id: 'coalball',
91
+ displayName: '黑煤球',
92
+ license: 'CC0-1.0',
93
+ renderer: 'sprite2d',
94
+ sprite2d: { spritesheetPath: 'spritesheet.webp' },
95
+ }), 'utf8')
96
+ writeFileSync(join(petDir, 'spritesheet.webp'), 'webp', 'utf8')
97
+ writeFileSync(join(petDir, 'voice.json'), JSON.stringify({
98
+ voicePackVersion: 1,
99
+ panel: { ranks: [{ min: 0, name: '小煤球', nameEn: 'Little Coal Ball' }] },
100
+ }), 'utf8')
101
+ const registry = loadPetRegistry({
102
+ packageRoot: petPackageRoot(import.meta.url),
103
+ petsDir: '',
104
+ dshPetsDir: petsDir,
105
+ })
106
+ return new PetService(fakeRootContext(), { registry, persistDir: tempDir() })
107
+ }
108
+
76
109
  /** The display fields the settings surface always commits. */
77
110
  function section(petId: string): PetSettingsSection {
78
111
  return { petId, visible: true, size: 160, right: 24, bottom: 20 }
@@ -111,6 +144,34 @@ describe('PetService remark layers', () => {
111
144
  expect((await service.interact('feed')).reaction).toBe(voice.noTreats[0])
112
145
  })
113
146
 
147
+ it('uses the declared rank ladder and keeps it across switches and settings applies', async () => {
148
+ const service = serviceWithRankLadders()
149
+ const whale = service.selectedPetId()
150
+ expect(whale).not.toBe('coalball')
151
+
152
+ // A pet with no ladder of its own inherits the global one.
153
+ const whaleView = await service.state()
154
+ expect(whaleView.affinity.rank).toBe('通用小鲸')
155
+ expect(whaleView.affinity.rankEn).toBeUndefined()
156
+
157
+ // The pet's own ladder replaces the global ladder whole.
158
+ expect(await service.setPetId('coalball')).toEqual({ ok: true, petId: 'coalball' })
159
+ const petView = await service.state()
160
+ expect(petView.affinity.rank).toBe('小煤球')
161
+ expect(petView.affinity.rankEn).toBe('Little Coal Ball')
162
+
163
+ // The settings surface re-seats the pet on every change; the ladder rides
164
+ // the same resolver as the remarks, so it must survive that apply.
165
+ service.applySettingsSection(section('coalball'))
166
+ const applied = await service.state()
167
+ expect(applied.affinity.rank).toBe('小煤球')
168
+ expect(applied.affinity.rankEn).toBe('Little Coal Ball')
169
+
170
+ // Switching back restores the global ladder.
171
+ await service.setPetId(whale)
172
+ expect((await service.state()).affinity.rank).toBe('通用小鲸')
173
+ })
174
+
114
175
  it('user keeps a pet-directory voice pack remarks after the settings surface applies a section', async () => {
115
176
  const voice = { pet: ['呼……好多了'], noTreats: ['现在不困啦~'] }
116
177
  const service = serviceWithPetVoicePack('mumbler', voice)
package/src/service.ts CHANGED
@@ -15,7 +15,7 @@
15
15
  import { Context, Service } from '@deepseek-ai/cordis'
16
16
  import type { AssistantStreamFrame } from '@deepseek-ai/dsh-agent'
17
17
  import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
18
- import type { AffinityConfig, PetAffinityView, PetInteraction } from './affinity.ts'
18
+ import type { AffinityConfig, AffinityRankName, PetAffinityView, PetInteraction } from './affinity.ts'
19
19
  import { announcementFresh, MAX_ANNOUNCEMENTS, parseAnnouncement, type PetAnnouncement } from './announce.ts'
20
20
  import type { TreatConfig } from './treats.ts'
21
21
  import {
@@ -407,7 +407,7 @@ export class PetService extends Service {
407
407
  const ledgerConfig: LedgerConfig = {
408
408
  affinity: config.affinity,
409
409
  treats: config.treats,
410
- ...this.remarkLayers(selected),
410
+ ...this.voiceLayers(selected),
411
411
  }
412
412
  this.ledger = new PetLedger(persist, ledgerConfig)
413
413
  this.stateConfig = { ...defaultPetStateConfig, ...(config.state ?? {}) }
@@ -442,27 +442,36 @@ export class PetService extends Service {
442
442
  }
443
443
 
444
444
  /**
445
- * The remark layers one pet contributes to the ledger: its manifest pools
446
- * first, then the voice packs (a pet directory's voice.json over the global
447
- * `$DSH_HOME/pets/.voice.json`). Every path that seats the ledger's remark
448
- * pools resolves them here, so no call site can apply the manifest pools and
449
- * silently drop the voice layer: doing that reverted a pet whose lines a voice
450
- * pack had translated back to the built-in pools the moment the settings
451
- * surface applied.
452
- * @param entry - the pet whose remark pools apply.
453
- * @returns the layers `PetLedger.setRemarks` takes.
445
+ * The voice layers one pet contributes to the ledger: its manifest remark
446
+ * pools first, then the voice packs (a pet directory's voice.json over the
447
+ * global `$DSH_HOME/pets/.voice.json`). The voice pack's `panel.ranks`
448
+ * ladder rides the same merge, so a ladder declared by either layer applies
449
+ * with the documented precedence. Every path that seats these layers
450
+ * resolves them here, so no call site can apply the manifest pools and
451
+ * silently drop the voice layer: doing that reverted a pet whose lines a
452
+ * voice pack had translated back to the built-in pools the moment the
453
+ * settings surface applied.
454
+ * @param entry - the pet whose layers apply.
455
+ * @returns the layers `PetLedger` takes.
454
456
  */
455
- private remarkLayers(entry: PetEntry): { remarks?: PetRemarks; voiceRemarks?: PetRemarks } {
457
+ private voiceLayers(entry: PetEntry): {
458
+ remarks?: PetRemarks
459
+ voiceRemarks?: PetRemarks
460
+ rankLadder?: readonly AffinityRankName[]
461
+ } {
462
+ const voice = mergeVoicePacks(this.registry.globalVoice, entry.voice)
456
463
  return {
457
464
  remarks: entry.remarks,
458
- voiceRemarks: mergeVoicePacks(this.registry.globalVoice, entry.voice)?.remarks,
465
+ voiceRemarks: voice?.remarks,
466
+ rankLadder: voice?.panel?.ranks,
459
467
  }
460
468
  }
461
469
 
462
- /** Re-seat the ledger's remark pools from one pet's layers. */
463
- private applyRemarks(entry: PetEntry): void {
464
- const layers = this.remarkLayers(entry)
470
+ /** Re-seat the ledger's remark pools and rank ladder from one pet's layers. */
471
+ private applyVoiceLayers(entry: PetEntry): void {
472
+ const layers = this.voiceLayers(entry)
465
473
  this.ledger.setRemarks(layers.remarks, layers.voiceRemarks)
474
+ this.ledger.setRankLadder(layers.rankLadder)
466
475
  }
467
476
 
468
477
  /** RPC: current pet state snapshot. */
@@ -608,7 +617,7 @@ export class PetService extends Service {
608
617
  const entry = this.registry.byId(petId)
609
618
  if (entry === undefined) return { ok: false, error: 'unknown-pet' }
610
619
  this.ledger.setPetId(entry.id)
611
- this.applyRemarks(entry)
620
+ this.applyVoiceLayers(entry)
612
621
  this.flush()
613
622
  this.syncSettingsFromPet()
614
623
  return { ok: true, petId: entry.id }
@@ -997,7 +1006,7 @@ export class PetService extends Service {
997
1006
  const selected = typeof section.petId === 'string' ? this.registry.byId(section.petId) : undefined
998
1007
  if (selected !== undefined) {
999
1008
  this.ledger.setPetId(selected.id)
1000
- this.applyRemarks(selected)
1009
+ this.applyVoiceLayers(selected)
1001
1010
  } else if (section.petId !== undefined) {
1002
1011
  // The stored selection names a pet the registry no longer has: keep the
1003
1012
  // current selection and repair the settings document.
@@ -11,12 +11,15 @@ import {
11
11
  mergeVoicePacks,
12
12
  normalizePanel,
13
13
  normalizePool,
14
+ normalizeRankLadder,
14
15
  normalizeVoicePack,
15
16
  normalizeWhisperCategories,
16
17
  normalizeWhisperResults,
17
18
  PANEL_ACTIONS,
18
19
  PANEL_LABEL_KEYS,
19
20
  PANEL_STAT_KEYS,
21
+ RANK_LADDER_MAX,
22
+ RANK_NAME_MAX,
20
23
  VOICE_LINE_MAX,
21
24
  VOICE_PACK_KEYS,
22
25
  VOICE_PACK_V1,
@@ -186,6 +189,79 @@ describe('normalizePanel', () => {
186
189
  })
187
190
  })
188
191
 
192
+ describe('normalizeRankLadder', () => {
193
+ const valid = [
194
+ { min: 0, name: '小煤球', nameEn: 'Little Coal Ball' },
195
+ { min: 25, name: '火星伙伴', nameEn: 'Martian Buddy' },
196
+ ]
197
+
198
+ it('accepts an ascending ladder starting at 0 and trims names', () => {
199
+ const warnings: string[] = []
200
+ expect(normalizeRankLadder([
201
+ { min: 0, name: ' 小煤球 ', nameEn: ' Little Coal Ball ' },
202
+ { min: 25, name: '火星伙伴' },
203
+ ], m => warnings.push(m))).toEqual([
204
+ { min: 0, name: '小煤球', nameEn: 'Little Coal Ball' },
205
+ { min: 25, name: '火星伙伴' },
206
+ ])
207
+ expect(warnings).toEqual([])
208
+ })
209
+
210
+ it('drops the whole ladder on a structural violation', () => {
211
+ const cases: [unknown, string][] = [
212
+ [{ min: 0, name: 'A' }, 'must be an array'],
213
+ [[], '1-' + RANK_LADDER_MAX],
214
+ [[{ min: 5, name: 'A' }], 'start at min 0'],
215
+ [[{ min: 0, name: 'A' }, { min: 0, name: 'B' }], 'sorted ascending'],
216
+ [[{ min: 0, name: 'A' }, { min: 10, name: 'B' }, { min: 5, name: 'C' }], 'sorted ascending'],
217
+ [[{ min: -1, name: 'A' }], 'non-negative integer'],
218
+ [[{ min: 1.5, name: 'A' }], 'non-negative integer'],
219
+ [[{ min: 0, name: '' }], '1-' + RANK_NAME_MAX],
220
+ [[{ min: 0, name: 'x'.repeat(RANK_NAME_MAX + 1) }], '1-' + RANK_NAME_MAX],
221
+ [[{ min: 0, name: 'A', nameEn: 7 }], 'nameEn must be a string'],
222
+ [[{ min: 0, name: 'A', nameEn: 'x'.repeat(RANK_NAME_MAX + 1) }], '1-' + RANK_NAME_MAX],
223
+ [[{ min: 0, name: 'A' }, 'bad'], 'must be an object'],
224
+ ]
225
+ for (const [raw, expected] of cases) {
226
+ const warnings: string[] = []
227
+ expect(normalizeRankLadder(raw, m => warnings.push(m))).toBeUndefined()
228
+ expect(warnings.join('\n')).toContain(expected)
229
+ }
230
+ })
231
+
232
+ it('caps the ladder at sixteen entries', () => {
233
+ const entries = Array.from({ length: RANK_LADDER_MAX + 1 }, (_, index) => ({ min: index, name: 'R' + index }))
234
+ const warnings: string[] = []
235
+ expect(normalizeRankLadder(entries, m => warnings.push(m))).toBeUndefined()
236
+ expect(warnings.join('\n')).toContain('1-' + RANK_LADDER_MAX)
237
+ expect(normalizeRankLadder(entries.slice(0, RANK_LADDER_MAX))).toHaveLength(RANK_LADDER_MAX)
238
+ })
239
+
240
+ it('is read through panel.ranks without disturbing the other panel slots', () => {
241
+ const { pack, warnings } = collectWarnings({
242
+ panel: { ranks: valid, labels: { feed: '投喂' }, stats: { rank: '好感 {rank}' } },
243
+ })
244
+ expect(pack?.panel?.ranks).toEqual(valid)
245
+ expect(pack?.panel?.labels).toEqual({ feed: '投喂' })
246
+ expect(pack?.panel?.stats).toEqual({ rank: '好感 {rank}' })
247
+ expect(warnings).toEqual([])
248
+ })
249
+
250
+ it('keeps a panel that declares only a ladder', () => {
251
+ const { pack } = collectWarnings({ panel: { ranks: valid } })
252
+ expect(pack?.panel?.ranks).toEqual(valid)
253
+ })
254
+
255
+ it('drops an invalid ladder but keeps the rest of the panel', () => {
256
+ const { pack, warnings } = collectWarnings({
257
+ panel: { ranks: [{ min: 3, name: 'A' }], labels: { feed: '投喂' } },
258
+ })
259
+ expect(pack?.panel?.ranks).toBeUndefined()
260
+ expect(pack?.panel?.labels).toEqual({ feed: '投喂' })
261
+ expect(warnings.join('\n')).toContain('start at min 0')
262
+ })
263
+ })
264
+
189
265
  describe('mergeVoicePacks', () => {
190
266
  it('merges per-key with later layers winning', () => {
191
267
  const global = normalizeVoicePack({
@@ -202,6 +278,30 @@ describe('mergeVoicePacks', () => {
202
278
  expect(merged?.panel?.labels).toEqual({ feed: '宠物投喂', hide: '宠物藏' })
203
279
  })
204
280
 
281
+ it('replaces the whole rank ladder from a later layer while other panel slots merge', () => {
282
+ const global = normalizeVoicePack({
283
+ panel: {
284
+ ranks: [{ min: 0, name: '全局小鲸' }, { min: 25, name: '全局伙伴' }],
285
+ labels: { feed: '全局投喂' },
286
+ },
287
+ })
288
+ const pet = normalizeVoicePack({
289
+ panel: {
290
+ ranks: [{ min: 0, name: '小煤球', nameEn: 'Little Coal Ball' }],
291
+ labels: { hide: '宠物藏' },
292
+ },
293
+ })
294
+ const merged = mergeVoicePacks(global, pet)
295
+ expect(merged?.panel?.ranks).toEqual([{ min: 0, name: '小煤球', nameEn: 'Little Coal Ball' }])
296
+ expect(merged?.panel?.labels).toEqual({ feed: '全局投喂', hide: '宠物藏' })
297
+ })
298
+
299
+ it('keeps the global ladder for a pet that declares none', () => {
300
+ const global = normalizeVoicePack({ panel: { ranks: [{ min: 0, name: '全局小鲸' }] } })
301
+ const pet = normalizeVoicePack({ panel: { labels: { feed: '投喂' } } })
302
+ expect(mergeVoicePacks(global, pet)?.panel?.ranks).toEqual([{ min: 0, name: '全局小鲸' }])
303
+ })
304
+
205
305
  it('lets the pet pack replace whisper keys while the global stays', () => {
206
306
  const global = normalizeVoicePack({ whispers: { categories: { thinking: ['全局思考'] }, results: { pass: ['全局全绿'] } } })
207
307
  const pet = normalizeVoicePack({ whispers: { categories: { thinking: ['宠物思考'] } } })
@@ -270,6 +370,18 @@ describe('voice-pack schema file drift lock', () => {
270
370
  expect(new Set(Object.keys(stats))).toEqual(new Set(PANEL_STAT_KEYS))
271
371
  const actions = (panel.actions as { items?: { enum?: string[] } } | undefined)
272
372
  expect(actions?.items?.enum).toEqual([...PANEL_ACTIONS])
373
+ const ranks = panel.ranks as {
374
+ minItems?: number
375
+ maxItems?: number
376
+ items?: { required?: string[]; properties?: Record<string, { maxLength?: number }> }
377
+ } | undefined
378
+ expect(ranks?.minItems).toBe(1)
379
+ expect(ranks?.maxItems).toBe(RANK_LADDER_MAX)
380
+ expect(ranks?.items?.required).toEqual(['min', 'name'])
381
+ const rankProps = ranks?.items?.properties ?? {}
382
+ expect(new Set(Object.keys(rankProps))).toEqual(new Set(['min', 'name', 'nameEn']))
383
+ expect(rankProps.name?.maxLength).toBe(RANK_NAME_MAX)
384
+ expect(rankProps.nameEn?.maxLength).toBe(RANK_NAME_MAX)
273
385
  })
274
386
 
275
387
  it('keeps the schema version const in sync', () => {
package/src/voice-pack.ts CHANGED
@@ -38,6 +38,7 @@ import {
38
38
  type WhisperResult,
39
39
  } from './chatter.ts'
40
40
  import { normalizePetRemarks, type PetRemarks } from './remarks.ts'
41
+ import type { AffinityRankName } from './affinity.ts'
41
42
 
42
43
  /** Schema version this module normalizes (optional field; missing = 1). */
43
44
  export const VOICE_PACK_V1 = 1 as const
@@ -62,6 +63,11 @@ export interface PetPanelView {
62
63
  stats?: Partial<Record<PanelStatKey, string>>
63
64
  /** Actions to render in canonical order; absent = all three; [] = none. */
64
65
  actions?: PanelAction[]
66
+ /**
67
+ * Display-only affinity ladder: replaces the built-in tier names for this
68
+ * pet. Points, rewards, cooldowns and the persisted ledger are untouched.
69
+ */
70
+ ranks?: readonly AffinityRankName[]
65
71
  }
66
72
 
67
73
  /** One normalized voice pack (a pet's voice.json or the global override). */
@@ -82,6 +88,11 @@ export const VOICE_LINE_MAX = 160
82
88
  export const VOICE_LABEL_MAX = 40
83
89
  export const VOICE_STAT_MAX = 80
84
90
 
91
+ /** Hard cap on a pet-declared affinity ladder (entries). */
92
+ export const RANK_LADDER_MAX = 16
93
+ /** Longest accepted rank name in a pet-declared ladder (characters). */
94
+ export const RANK_NAME_MAX = 24
95
+
85
96
  /** Any '{token}' placeholder (no nesting, no newlines). */
86
97
  const PLACEHOLDER_PATTERN = /{[^{}]*}/g
87
98
 
@@ -200,7 +211,80 @@ export function normalizeWhisperResults(
200
211
  return Object.keys(pools).length > 0 ? pools : undefined
201
212
  }
202
213
 
203
- /** Normalize the panel block (labels / stats / actions; warn-and-drop). */
214
+ /** Validate one rank name slot of a declared ladder. */
215
+ function rankName(
216
+ raw: unknown,
217
+ index: number,
218
+ field: 'name' | 'nameEn',
219
+ onWarning: (message: string) => void,
220
+ ): string | undefined {
221
+ if (typeof raw !== 'string') {
222
+ onWarning('panel.ranks[' + index + '].' + field + ' must be a string')
223
+ return undefined
224
+ }
225
+ const trimmed = raw.trim()
226
+ if (trimmed === '' || trimmed.length > RANK_NAME_MAX) {
227
+ onWarning('panel.ranks[' + index + '].' + field + ' must be 1-' + RANK_NAME_MAX + ' characters')
228
+ return undefined
229
+ }
230
+ return trimmed
231
+ }
232
+
233
+ /**
234
+ * Normalize one pet-declared affinity ladder (`panel.ranks`). A ladder is
235
+ * all-or-nothing: it must be an array of 1-{@link RANK_LADDER_MAX} entries,
236
+ * start at min 0, sort ascending with unique minima, and carry names of
237
+ * 1-{@link RANK_NAME_MAX} characters. Any violation warns and drops the
238
+ * whole ladder, so the pet keeps the built-in names instead of a half-broken
239
+ * ladder; a bad ladder never rejects the pet.
240
+ */
241
+ export function normalizeRankLadder(
242
+ raw: unknown,
243
+ onWarning: (message: string) => void = () => {},
244
+ ): AffinityRankName[] | undefined {
245
+ if (!Array.isArray(raw)) {
246
+ onWarning('panel.ranks must be an array')
247
+ return undefined
248
+ }
249
+ if (raw.length === 0 || raw.length > RANK_LADDER_MAX) {
250
+ onWarning('panel.ranks must contain 1-' + RANK_LADDER_MAX + ' entries')
251
+ return undefined
252
+ }
253
+ const ladder: AffinityRankName[] = []
254
+ let previousMin = -1
255
+ for (let index = 0; index < raw.length; index++) {
256
+ const entry = raw[index]
257
+ if (!isRecord(entry)) {
258
+ onWarning('panel.ranks[' + index + '] must be an object')
259
+ return undefined
260
+ }
261
+ const min = entry.min
262
+ if (typeof min !== 'number' || !Number.isSafeInteger(min) || min < 0) {
263
+ onWarning('panel.ranks[' + index + '].min must be a non-negative integer')
264
+ return undefined
265
+ }
266
+ if (index === 0 && min !== 0) {
267
+ onWarning('panel.ranks must start at min 0')
268
+ return undefined
269
+ }
270
+ if (min <= previousMin) {
271
+ onWarning('panel.ranks must be sorted ascending with unique min values')
272
+ return undefined
273
+ }
274
+ previousMin = min
275
+ const defaultName = rankName(entry.name, index, 'name', onWarning)
276
+ if (defaultName === undefined) return undefined
277
+ let nameEn: string | undefined
278
+ if (entry.nameEn !== undefined) {
279
+ nameEn = rankName(entry.nameEn, index, 'nameEn', onWarning)
280
+ if (nameEn === undefined) return undefined
281
+ }
282
+ ladder.push({ min, name: defaultName, ...(nameEn === undefined ? {} : { nameEn }) })
283
+ }
284
+ return ladder
285
+ }
286
+
287
+ /** Normalize the panel block (labels / stats / actions / ranks; warn-and-drop). */
204
288
  export function normalizePanel(
205
289
  raw: unknown,
206
290
  onWarning: (message: string) => void = () => {},
@@ -265,7 +349,15 @@ export function normalizePanel(
265
349
  panel.actions = PANEL_ACTIONS.filter(action => seen.has(action))
266
350
  }
267
351
  }
268
- if (panel.labels === undefined && panel.stats === undefined && panel.actions === undefined) return undefined
352
+ const ranksRaw = raw.ranks
353
+ if (ranksRaw !== undefined) {
354
+ const ladder = normalizeRankLadder(ranksRaw, onWarning)
355
+ if (ladder !== undefined) panel.ranks = ladder
356
+ }
357
+ if (
358
+ panel.labels === undefined && panel.stats === undefined
359
+ && panel.actions === undefined && panel.ranks === undefined
360
+ ) return undefined
269
361
  return panel
270
362
  }
271
363
 
@@ -406,6 +498,7 @@ export function mergeVoicePacks(...layers: (VoicePack | undefined)[]): VoicePack
406
498
  const stats: NonNullable<PetPanelView['stats']> = {}
407
499
  let remarks: PetRemarks | undefined
408
500
  let ranks: Record<string, string> | undefined
501
+ let panelRanks: readonly AffinityRankName[] | undefined
409
502
  let actions: PanelAction[] | undefined
410
503
  let panelSeen = false
411
504
  let any = false
@@ -427,6 +520,9 @@ export function mergeVoicePacks(...layers: (VoicePack | undefined)[]): VoicePack
427
520
  if (layer.panel.labels !== undefined) Object.assign(labels, layer.panel.labels)
428
521
  if (layer.panel.stats !== undefined) Object.assign(stats, layer.panel.stats)
429
522
  if (layer.panel.actions !== undefined) actions = layer.panel.actions
523
+ // A ladder is atomic: a declaring layer replaces the previous ladder
524
+ // whole instead of merging tiers across layers.
525
+ if (layer.panel.ranks !== undefined) panelRanks = layer.panel.ranks
430
526
  }
431
527
  if (layer.remarks !== undefined) {
432
528
  remarks = { ...(remarks ?? {}), ...layer.remarks }
@@ -440,8 +536,10 @@ export function mergeVoicePacks(...layers: (VoicePack | undefined)[]): VoicePack
440
536
  ...(Object.keys(labels).length > 0 ? { labels } : {}),
441
537
  ...(Object.keys(stats).length > 0 ? { stats } : {}),
442
538
  ...(actions === undefined ? {} : { actions }),
539
+ ...(panelRanks === undefined ? {} : { ranks: panelRanks }),
443
540
  }
444
- const panelEmpty = panel.labels === undefined && panel.stats === undefined && panel.actions === undefined
541
+ const panelEmpty = panel.labels === undefined && panel.stats === undefined
542
+ && panel.actions === undefined && panel.ranks === undefined
445
543
  return {
446
544
  overrides,
447
545
  ...(panelSeen && !panelEmpty ? { panel } : {}),