@gotcos/glasses-server 6.92.0 → 6.93.0

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/.env.example +30 -1
  2. package/CHANGELOG.md +57 -29
  3. package/README.md +58 -0
  4. package/docs/active-query-jobs.md +1 -1
  5. package/docs/test-plan-6.71.7.md +1 -1
  6. package/managed-runtime-contract.json +2 -0
  7. package/package.json +2 -1
  8. package/server/lib/ask-session-id.ts +2 -1
  9. package/server/lib/embedding-eviction.ts +60 -2
  10. package/server/lib/fuzzy-correct.ts +1 -1
  11. package/server/lib/hallucination-filter.ts +1 -1
  12. package/server/lib/imported-library-rows.ts +4 -2
  13. package/server/lib/live-cos-ask.ts +3 -2
  14. package/server/lib/mac-live-voices.ts +57 -0
  15. package/server/lib/mac-recording-asr.ts +16 -8
  16. package/server/lib/mac-speaker-projection.ts +211 -0
  17. package/server/lib/mac-stream-diarizer.ts +185 -0
  18. package/server/lib/mac-voice-assignment.ts +361 -0
  19. package/server/lib/mac-voice-labels.ts +70 -8
  20. package/server/lib/mac-window-replay.ts +271 -0
  21. package/server/lib/mac-window-voices.ts +390 -0
  22. package/server/lib/meeting-actions.ts +1 -1
  23. package/server/lib/meeting-ask-owner.ts +4 -4
  24. package/server/lib/meeting-ask-transcript-sources.ts +41 -3
  25. package/server/lib/meeting-audio-archive.ts +4 -0
  26. package/server/lib/meeting-batch-transcribe.ts +7 -1
  27. package/server/lib/meeting-context-keys.ts +6 -3
  28. package/server/lib/meeting-corrections.ts +4 -4
  29. package/server/lib/meeting-fact-check.ts +3 -3
  30. package/server/lib/meeting-parse.ts +1 -1
  31. package/server/lib/meeting-relabel-enrolment.ts +8 -8
  32. package/server/lib/meeting-relabel.ts +3 -3
  33. package/server/lib/meeting-scribe-content.ts +1 -1
  34. package/server/lib/meeting-speaker-review.ts +8 -8
  35. package/server/lib/meeting-store.ts +19 -9
  36. package/server/lib/nemotron-final.ts +114 -9
  37. package/server/lib/nemotron-live.ts +58 -6
  38. package/server/lib/phone-recording.ts +114 -0
  39. package/server/lib/prompt-tail-guard.ts +1 -1
  40. package/server/lib/speaker-embeddings.ts +154 -28
  41. package/server/lib/speaker-name.ts +1 -1
  42. package/server/lib/stranded-session-actions.ts +7 -2
  43. package/server/lib/training-audio-provenance.ts +3 -2
  44. package/server/lib/transcript-cleanup-context.ts +3 -3
  45. package/server/lib/transcript-cleanup-model.ts +1 -1
  46. package/server/lib/transcript-cleanup-spans.ts +10 -10
  47. package/server/lib/transcript-cleanup-text.ts +4 -4
  48. package/server/lib/transcript-cleanup.ts +1 -1
  49. package/server/lib/unsaved-audio-quarantine.ts +10 -1
  50. package/server/lib/voice-directory.ts +1 -1
  51. package/server/lib/voice-evidence-guard.ts +2 -1
  52. package/server/lib/voice-profile-store.ts +11 -5
  53. package/server/lib/whisper-local.ts +1 -1
  54. package/server/routes/health.ts +8 -0
  55. package/server/routes/meeting.ts +189 -19
  56. package/server/routes/meetings.ts +9 -5
  57. package/server/routes/transcribe-stream.ts +140 -15
  58. package/server/routes/voice.ts +12 -4
  59. package/server/scripts/mac-voice-assignment-6930-mutation-gate.mjs +225 -0
  60. package/server/scripts/mac-window-voices-6930-mutation-gate.mjs +193 -0
@@ -0,0 +1,225 @@
1
+ #!/usr/bin/env node
2
+ // 6.93.0 mutation gate: assigning a Mac recording `Voice N` to an existing voice profile (lib/mac-voice-assignment.ts and
3
+ // its hook in the relabel route of routes/meeting.ts). Engine copied unchanged from mac-window-voices-6930-mutation-gate.mjs;
4
+ // mutations run only in a disposable copy of the checkout.
5
+ //
6
+ // What it proves, in order:
7
+ // 0. The target suites are GREEN unmutated. A gate over a red suite reads every mutant as killed and proves nothing.
8
+ // 1. Each target string appears EXACTLY ONCE in its file, so the mutation is unambiguous.
9
+ // 2. The mutated file differs from the original, so the edit landed.
10
+ // 3. A NAMED test fails ("FAIL server/x.test.ts > name"); a build error or a harness failure is not a kill.
11
+ // 4. The file is restored byte for byte (compared) before the next mutant.
12
+ // Usage: node server/scripts/mac-voice-assignment-6930-mutation-gate.mjs [--list] [name…]
13
+ import { mkdtempSync, cpSync, readFileSync, writeFileSync, symlinkSync, rmSync } from 'node:fs'
14
+ import { tmpdir } from 'node:os'
15
+ import { resolve, join, dirname, basename } from 'node:path'
16
+ import { fileURLToPath } from 'node:url'
17
+ import { spawnSync } from 'node:child_process'
18
+
19
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..')
20
+ const LIB_T = ['server/lib/mac-voice-assignment.test.ts']
21
+ const ROUTE_T = ['server/routes/meeting-mac-assign-route.test.ts']
22
+ const G2_T = ['server/routes/meeting-relabel-route.test.ts']
23
+ const EV_T = ['server/lib/embedding-eviction.test.ts', 'server/lib/embedding-eviction-integration.test.ts']
24
+ const SE_T = ['server/lib/speaker-embeddings-enroll.test.ts']
25
+ const TP_T = ['server/lib/training-audio-provenance.test.ts']
26
+ const MERGE_T = ['server/lib/voice-profile-merge.test.ts']
27
+ const VS_T = ['server/routes/voice-safety.test.ts']
28
+ const ALL = [...LIB_T, ...ROUTE_T, ...G2_T, ...EV_T, ...SE_T, ...TP_T, ...MERGE_T, ...VS_T]
29
+ const A = 'server/lib/mac-voice-assignment.ts', M = 'server/routes/meeting.ts'
30
+ const VP = 'server/lib/voice-profile-store.ts', VR = 'server/routes/voice.ts'
31
+ const EV = 'server/lib/embedding-eviction.ts', SE = 'server/lib/speaker-embeddings.ts', TP = 'server/lib/training-audio-provenance.ts'
32
+ const m = (name, file, edits, tests) => ({ name, file, edits: typeof edits[0] === 'string' ? [edits] : edits, tests })
33
+
34
+ const mutations = [
35
+ // ── Library guards: each refusal stands on its own, not only behind the route's ──
36
+ m('guard-not-mac', A, [" if (!isMacCaptureSidecar(sidecar, sessionId)) return none('not_mac_capture')\n", ''], [...LIB_T, ...ROUTE_T]),
37
+ m('guard-voice-label', A, [" if (!isVoiceLabel(from)) return none('not_a_voice_label')\n", ''], [...LIB_T, ...ROUTE_T]),
38
+ m('guard-placeholder-target', A, [" if (isPlaceholderLabel(to)) return none('unknown_profile')\n", ''], [...LIB_T, ...ROUTE_T]),
39
+ m('guard-unknown-profile', A, [" if (!profile) return none('unknown_profile')\n", ''], [...LIB_T, ...ROUTE_T]),
40
+ m('profile-name-case-insensitive', A, ['.find(p => p.name === to) } catch', '.find(p => p.name.toLowerCase() === to.toLowerCase()) } catch'], [...LIB_T, ...ROUTE_T]),
41
+ m('guard-embeddings-switch', A, [" if (!chunkEmbeddingsEnabled()) return none('disabled')\n", ''], LIB_T),
42
+ m('guard-model-present', A, [" if (!isEmbeddingAvailable()) return none('store_unavailable')\n", ''], [...LIB_T, ...ROUTE_T]),
43
+ m('guard-index-mapping', A, [" if (!rawIndices) return none('no_index_mapping')\n", ''], LIB_T),
44
+ // ── B3: the wearer profile is never a target ──
45
+ m('guard-owner', A, [" if (input.ownerLabel && sameName(to, input.ownerLabel)) return none('owner_profile')\n", ''], [...LIB_T, ...ROUTE_T]),
46
+ m('owner-match-case-sensitive', A, ["a.normalize('NFKC').trim().toLowerCase() === b.normalize('NFKC').trim().toLowerCase()", "a === b"], [...LIB_T, ...ROUTE_T]),
47
+ m('route-owner-label-not-passed', M, ['sidecar: parsedForAssign, ownerLabel })', 'sidecar: parsedForAssign })'], ROUTE_T),
48
+ m('route-owner-not-409', M, [" if (macAssign.report.skipped === 'owner_profile') {", ' if (false) {'], ROUTE_T),
49
+ m('guard-no-stored-voice', A, [" if (!stored) return none('no_stored_voice')\n", ''], LIB_T),
50
+ // ── B2: capacity (a Mac-assigned sample can only use free slots or replace its own kind) ──
51
+ m('guard-profile-full', A, [" if (capacity <= 0) return none('profile_full')\n", ''], ROUTE_T),
52
+ m('capacity-ignores-replaceable', A, ['Math.max(0, MAX_EMBEDDINGS_PER_SPEAKER - profile.embeddings.length) + macCount)', 'Math.max(0, MAX_EMBEDDINGS_PER_SPEAKER - profile.embeddings.length))'], ROUTE_T),
53
+ m('selection-not-trimmed-to-room', A, ['Math.min(MAX_ENROL_PER_CORRECTION, capacity)).slice(0, capacity)', 'Math.min(MAX_ENROL_PER_CORRECTION, capacity))'], ROUTE_T),
54
+ m('selection-ignores-mac-cap', A, ['Math.min(MAX_ENROL_PER_CORRECTION, capacity)).slice(0, capacity)', 'MAX_ENROL_PER_CORRECTION)'], ROUTE_T),
55
+ // ── Which audio ──
56
+ m('mixed-chunk-used-whole', A, ['if (turns.length === 0 || turns.every(t => t.speaker === from)) {', 'if (true) {'], ROUTE_T),
57
+ m('other-voices-turns-sliced', A, ['const usable = turns.filter(t => t.speaker === from\n', 'const usable = turns.filter(t => true\n'], ROUTE_T),
58
+ m('slice-min-ignored', A, ['>= MAC_ASSIGN_MIN_SLICE_SEC)', '>= 0)'], ROUTE_T),
59
+ m('slice-min-off-by-one', A, ['export const MAC_ASSIGN_MIN_SLICE_SEC = 3.0', 'export const MAC_ASSIGN_MIN_SLICE_SEC = 2.0'], ROUTE_T),
60
+ m('slice-inset-removed', A, ['export const MAC_ASSIGN_SLICE_INSET_SEC = 0.15', 'export const MAC_ASSIGN_SLICE_INSET_SEC = 0'], ROUTE_T),
61
+ m('slice-start-inset-removed', A, ['slice: { startSec: (t.startSec as number) + MAC_ASSIGN_SLICE_INSET_SEC,', 'slice: { startSec: (t.startSec as number),'], ROUTE_T),
62
+ m('slice-end-inset-removed', A, ['endSec: (t.endSec as number) - MAC_ASSIGN_SLICE_INSET_SEC }', 'endSec: (t.endSec as number) }'], ROUTE_T),
63
+ m('final-segments-ignored', A, ['const list = Array.isArray(final) && final.length > 0 ? final : Array.isArray(live) ? live : []', 'const list = Array.isArray(live) ? live : []'], ROUTE_T),
64
+ m('short-chunk-not-skipped', A, [' if (sec < VOICEPRINT_MIN_AUDIO_SEC) { report.shortSkipped += 1; continue }\n', ''], ROUTE_T),
65
+ m('unit-cap-ignored', A, ['const picked = spread(units, MAC_ASSIGN_MAX_UNITS)', 'const picked = units'], ROUTE_T),
66
+ m('spread-takes-the-first', A, ['out.push(items[Math.floor((k * items.length) / max)])', 'out.push(items[k])'], ROUTE_T),
67
+ m('missing-audio-not-counted', A, [' if (!path) { report.missingAudio += 1; continue }\n', ' if (!path) continue\n'], [...LIB_T, ...ROUTE_T]),
68
+ m('audio-gone-reads-as-unusable', A, ["report.skipped = units.length === 0 ? 'no_usable_audio' : 'audio_not_retained'", "report.skipped = 'no_usable_audio'"], [...LIB_T, ...ROUTE_T]),
69
+ m('wrong-sample-rate-accepted', A, [' if (!pcm || pcm.sampleRate !== SAMPLE_RATE) continue\n', ' if (!pcm) continue\n'], ROUTE_T),
70
+ // ── The same gates a glasses rename uses ──
71
+ m('coherence-gate-skipped', A, ['greedyDiversitySelect(cluster.members.map(m => embeddings[m]), Math.min(', 'greedyDiversitySelect(embeddings, Math.min('], ROUTE_T),
72
+ m('coherence-skips-not-reported', A, ['report.clusterSkipped = embeddings.length - cluster.members.length', 'report.clusterSkipped = 0'], ROUTE_T),
73
+ m('no-cluster-still-enrols', A, [" if (cluster.members.length === 0) { report.skipped = 'no_usable_audio'; return { report, selected: [], stats } }\n", ''], ROUTE_T),
74
+ m('diversity-cap-ignored', A, ['Math.min(MAX_ENROL_PER_CORRECTION, capacity)).slice(0, capacity)', 'Infinity).slice(0, capacity)'], ROUTE_T),
75
+ // ── B1: similarity, counts and the three gates ──
76
+ m('below-floor-never-flagged', A, ['report.belowFloor = report.similarity < MERGE_SIMILARITY_FLOOR', 'report.belowFloor = false'], ROUTE_T),
77
+ m('below-floor-wrong-way', A, ['report.belowFloor = report.similarity < MERGE_SIMILARITY_FLOOR', 'report.belowFloor = report.similarity > MERGE_SIMILARITY_FLOOR'], ROUTE_T),
78
+ m('similarity-not-reported', A, ['report.similarity = Math.round(rawCosineSimilarity(voice, stored) * 1000) / 1000', 'report.similarity = null'], ROUTE_T),
79
+ m('floor-not-the-merge-floor', A, ['belowFloor: false, floor: MERGE_SIMILARITY_FLOOR,', 'belowFloor: false, floor: 0.5,'], ROUTE_T),
80
+ m('gate-below-floor-dropped', A, [" if (report.belowFloor) report.gates.push('below_floor')\n", ''], [...LIB_T, ...ROUTE_T]),
81
+ m('gate-mixed-dropped', A, [" if (report.groupSize < embeddings.length * MAC_ASSIGN_MIXED_FRACTION) report.gates.push('mixed_voice')\n", ''], [...LIB_T, ...ROUTE_T]),
82
+ m('gate-mixed-edge-inclusive', A, ['report.groupSize < embeddings.length * MAC_ASSIGN_MIXED_FRACTION', 'report.groupSize <= embeddings.length * MAC_ASSIGN_MIXED_FRACTION'], LIB_T),
83
+ m('gate-mixed-fraction-half', A, ['export const MAC_ASSIGN_MIXED_FRACTION = 2 / 3', 'export const MAC_ASSIGN_MIXED_FRACTION = 1 / 2'], [...LIB_T, ...ROUTE_T]),
84
+ m('gate-too-little-dropped', A, [" if (report.groupSize < MAC_ASSIGN_MIN_UNITS && report.groupSec < MAC_ASSIGN_MIN_SINGLE_SEC) report.gates.push('too_little_audio')\n", ''], [...LIB_T, ...ROUTE_T]),
85
+ m('gate-too-little-or', A, ['report.groupSize < MAC_ASSIGN_MIN_UNITS && report.groupSec < MAC_ASSIGN_MIN_SINGLE_SEC', 'report.groupSize < MAC_ASSIGN_MIN_UNITS || report.groupSec < MAC_ASSIGN_MIN_SINGLE_SEC'], [...LIB_T, ...ROUTE_T]),
86
+ m('gate-single-seconds-lowered', A, ['export const MAC_ASSIGN_MIN_SINGLE_SEC = 6', 'export const MAC_ASSIGN_MIN_SINGLE_SEC = 5'], LIB_T),
87
+ m('gate-min-units-one', A, ['export const MAC_ASSIGN_MIN_UNITS = 2', 'export const MAC_ASSIGN_MIN_UNITS = 1'], [...LIB_T, ...ROUTE_T]),
88
+ m('group-size-not-reported', A, [' report.groupSize = cluster.members.length\n', ''], [...LIB_T, ...ROUTE_T]),
89
+ m('group-seconds-wrong', A, ['report.groupSec = Math.round(cluster.members.reduce((sum, m) => sum + secs[m], 0) * 10) / 10', 'report.groupSec = Math.round(secs.reduce((sum, v) => sum + v, 0) * 10) / 10'], LIB_T),
90
+ // ── The route: gates refuse unless forced; force is not wider than that ──
91
+ m('route-gates-never-refuse', M, [' if (macAssign && macAssign.report.gates.length > 0 && req.body?.force !== true) {', ' if (false) {'], ROUTE_T),
92
+ m('route-force-ignored', M, [' if (macAssign && macAssign.report.gates.length > 0 && req.body?.force !== true) {', ' if (macAssign && macAssign.report.gates.length > 0) {'], ROUTE_T),
93
+ m('route-gate-reason-not-first', M, [' const gate = macAssign.report.gates[0]\n', ' const gate = macAssign.report.gates[macAssign.report.gates.length - 1]\n'], ROUTE_T),
94
+ m('route-force-skips-pending-correction', M, [' if (stalled.length > 0 && (req.body?.force !== true || macAssign)) {', ' if (stalled.length > 0 && req.body?.force !== true) {'], ROUTE_T),
95
+ // ── B4: capture, interleave, deadline, yield, vector reuse ──
96
+ m('route-capture-pre-check-dropped', M, [' if (captureActive()) {\n res.status(409).json({ error: \'A meeting is being recorded right now.', ' if (false) {\n res.status(409).json({ error: \'A meeting is being recorded right now.'], ROUTE_T),
97
+ m('route-capture-post-check-dropped', M, [' if (macAssign && captureActive()) {', ' if (false) {'], ROUTE_T),
98
+ m('route-capture-ignored-by-default-probe', M, ['(() => getTranscriptionSessionLiveness().live > 0)', '(() => false)'], ROUTE_T),
99
+ m('route-in-flight-not-guarded', M, [' if (macAssignInFlight.has(sessionId)) {', ' if (false) {'], ROUTE_T),
100
+ m('route-in-flight-never-released', M, [' } finally {\n macAssignInFlight.delete(sessionId)\n }', ' } finally {\n }'], ROUTE_T),
101
+ m('route-meeting-bytes-not-rechecked', M, [' if (sidecarAfter !== sidecarRaw || revisionAfter) {', ' if (revisionAfter) {'], ROUTE_T),
102
+ m('route-revision-not-rechecked', M, [' if (sidecarAfter !== sidecarRaw || revisionAfter) {', ' if (sidecarAfter !== sidecarRaw) {'], ROUTE_T),
103
+ m('plan-does-not-yield', A, [' await yieldToLoop()\n', ''], [...LIB_T, ...ROUTE_T]),
104
+ m('plan-deadline-ignored', A, [' if (now() >= deadline) {', ' if (false) {'], LIB_T),
105
+ m('plan-deadline-not-a-refusal', A, [" report.skipped = 'deadline'\n", ''], LIB_T),
106
+ m('env-deadline-unbounded', A, ['raw >= 1000 && raw <= 25_000', 'raw >= 0'], LIB_T),
107
+ m('vectors-not-reused', A, [' const hit = cacheGet(key)\n', ' const hit = undefined as ReturnType<typeof cacheGet>\n'], [...LIB_T, ...ROUTE_T]),
108
+ m('vector-key-ignores-file', A, ['|${info.size}|${Math.round(info.mtimeMs)}|${info.ino}|${Math.round(info.ctimeMs)}`', '`'], LIB_T),
109
+ m('vector-key-ignores-mtime', A, ['|${Math.round(info.mtimeMs)}|${info.ino}', '|${info.ino}'], LIB_T),
110
+ m('vector-key-ignores-inode', A, ['|${info.ino}|${Math.round(info.ctimeMs)}`', '|${Math.round(info.ctimeMs)}`'], LIB_T),
111
+ m('vector-key-ignores-ctime', A, ['|${info.ino}|${Math.round(info.ctimeMs)}`', '|${info.ino}`'], LIB_T),
112
+ m('vector-key-ignores-slice', A, ["${unit.slice ? `${unit.slice.startSec.toFixed(3)}-${unit.slice.endSec.toFixed(3)}` : 'whole'}", "whole"], LIB_T),
113
+ m('apply-writes-per-sample', A, ['const result = enrollEmbeddingsBatch(plan.report.person, plan.selected.map(embedding => ({ embedding, source })))', 'const result = plan.selected.map(embedding => enrollEmbeddingsBatch(plan.report.person, [{ embedding, source }])).reduce((a, r) => ({ enrolled: a.enrolled + r.enrolled, declined: a.declined + r.declined, persisted: a.persisted && r.persisted }), { enrolled: 0, declined: 0, persisted: true })'], LIB_T),
114
+ // ── Commit ──
115
+ m('commit-ignores-refusal', A, [" if (plan.report.skipped !== null || plan.selected.length === 0) return { ...plan.report, enrolled: 0 }\n", ''], LIB_T),
116
+ m('commit-source-tag', A, ['const source = `${MAC_ASSIGN_SOURCE}:${sessionId}`', 'const source = `correction:${sessionId}`'], [...LIB_T, ...ROUTE_T]),
117
+ m('commit-source-tag-unstamped', A, ['const source = `${MAC_ASSIGN_SOURCE}:${sessionId}`', 'const source = MAC_ASSIGN_SOURCE'], [...LIB_T, ...ROUTE_T]),
118
+ m('commit-store-failure-swallowed', A, [" if (!result.persisted) return { ...plan.report, enrolled: 0, skipped: 'store_unavailable' }\n", ''], [...LIB_T, ...ROUTE_T]),
119
+ m('commit-counts-everything', A, [' return { ...plan.report, enrolled: result.enrolled }', ' return { ...plan.report, enrolled: plan.selected.length }'], ROUTE_T),
120
+ m('plan-creates-profile-flag', A, ['person, enrolled: 0, attempted: 0, created: false,', 'person, enrolled: 0, attempted: 0, created: true as unknown as false,'], ROUTE_T),
121
+ // ── The relabel route ──
122
+ m('route-flag-always-on', M, [' if (req.body?.assignVoiceProfile === true) {', ' if (true) {'], [...ROUTE_T, ...G2_T]),
123
+ m('route-flag-ignored', M, [' if (req.body?.assignVoiceProfile === true) {', ' if (false) {'], ROUTE_T),
124
+ m('route-mac-only', M, [' if (!isMacCaptureSidecar(parsedForAssign, sessionId)) {\n', ' if (false) {\n'], ROUTE_T),
125
+ m('route-voice-label-only', M, [' if (!isVoiceLabel(from)) {\n res.status(400).json({ error: \'Only an unnamed Voice N', ' if (false) {\n res.status(400).json({ error: \'Only an unnamed Voice N'], ROUTE_T),
126
+ m('route-unknown-profile-404', M, [" if (macAssign.report.skipped === 'unknown_profile') {", ' if (false) {'], ROUTE_T),
127
+ m('route-nothing-to-enrol-refusal', M, [' if (macAssign && macAssign.report.skipped !== null) {', ' if (false) {'], ROUTE_T),
128
+ m('route-preview-hides-enrolment', M, [' ...(macAssign ? { enrolment: macAssign.report } : {}),\n', ''], ROUTE_T),
129
+ m('route-preview-message', M, [' ? `, and adding up to ${macAssign.report.enrolled} voice sample(s) to ${to}\'s profile`', ' ? ``'], ROUTE_T),
130
+ m('route-preview-hides-refusal-reason', M, [' : `. Assigning is not possible: ${macAssignSkipText(macAssign.report.skipped)}. You can still rename the speaker in the transcript without adding any voice samples`', ' : \'\''], ROUTE_T),
131
+ m('route-apply-uses-glasses-path', M, [' const enrolment = macAssign\n ? commitMacVoiceAssignment(sessionId, macAssign)\n : enrolNamedVoice(', ' const enrolment = false\n ? commitMacVoiceAssignment(sessionId, macAssign!)\n : enrolNamedVoice('], ROUTE_T),
132
+ m('route-plan-uses-renamed-sidecar', M, ['macAssign = await planMacVoiceAssignment({ sessionId, from, to, changed: plan.value.changed, sidecar: parsedForAssign, ownerLabel })', 'macAssign = await planMacVoiceAssignment({ sessionId, from, to, changed: [], sidecar: parsedForAssign, ownerLabel })'], ROUTE_T),
133
+ // ── B2 policy (embedding-eviction.ts) ──
134
+ m('mac-assign-not-assisted', EV, [" case MAC_ASSIGN_SOURCE:\n", ''], [...EV_T, ...SE_T, ...ROUTE_T]),
135
+ m('mac-assign-vouches', EV, ["return head === 'manual' || head === 'fireflies' || head === 'g2-enrollment'", "return head === 'manual' || head === 'fireflies' || head === 'g2-enrollment' || head === 'mac-assign'"], EV_T),
136
+ m('mac-assign-is-a-correction', EV, ["return String(source ?? '').trim().toLowerCase().startsWith('correction')", "return String(source ?? '').trim().toLowerCase().startsWith('correction') || isMacAssign(source)"], EV_T),
137
+ m('mac-assign-evicts-others', EV, [" if (macIdx.length > 0) {\n return {\n index: macIdx[0],", " if (false) {\n return {\n index: macIdx[0],"], [...EV_T, ...SE_T, ...ROUTE_T]),
138
+ m('mac-assign-refusal-evicts-index-zero', EV, ["return { index: -1, tier: 'assisted', reason: 'profile is full and holds no Mac-assigned sample to replace, refusing the Mac-assigned sample', refuse: true }", "return { index: 0, tier: 'assisted', reason: 'profile is full and holds no Mac-assigned sample to replace, refusing the Mac-assigned sample' }"], [...EV_T, ...SE_T, ...ROUTE_T]),
139
+ m('mac-assign-outlives-auto', EV, [" if (macIdx.length > 0) {\n return {\n index: macIdx[0],\n tier: 'assisted',\n reason: `dropping the oldest Mac-assigned sample", " if (false) {\n return {\n index: macIdx[0],\n tier: 'assisted',\n reason: `dropping the oldest Mac-assigned sample"], [...EV_T, ...SE_T]),
140
+ m('mac-assign-evicted-only-within-assisted', EV, [[
141
+ " if (macIdx.length > 0) {\n return {\n index: macIdx[0],\n tier: 'assisted',\n reason: `dropping the oldest Mac-assigned sample (${String(sources[macIdx[0]])}) before any other kind, it is the weakest evidence`,\n }\n }\n", ''],
142
+ [" const idx = sources.findIndex(s => provenanceTier(s) === tier)", " const idx = tier === 'assisted' && macIdx.length > 0 ? macIdx[0] : sources.findIndex(s => provenanceTier(s) === tier)"]], [...EV_T, ...SE_T]),
143
+ // ── 6.93.0 polish: the cap is min(10, the profile's other samples), at plan time, at write time and in a merge ──
144
+ m('cap-is-flat-ten', EV, ['return Math.min(MAC_ASSIGN_PROFILE_CAP, Math.max(0, sampleCount - macCount))', 'return MAC_ASSIGN_PROFILE_CAP'], [...EV_T, ...SE_T, ...LIB_T, ...ROUTE_T, ...MERGE_T]),
145
+ m('cap-counts-mac-as-other', EV, ['return Math.min(MAC_ASSIGN_PROFILE_CAP, Math.max(0, sampleCount - macCount))', 'return Math.min(MAC_ASSIGN_PROFILE_CAP, sampleCount)'], [...EV_T, ...SE_T, ...LIB_T, ...ROUTE_T, ...MERGE_T]),
146
+ m('plan-capacity-flat-ten', A, ['Math.min(macAssignCapFor(profile.embeddings.length, macCount), Math.max(0,', 'Math.min(10, Math.max(0,'], ROUTE_T),
147
+ m('store-guard-flat-ten', SE, ['macCount >= macAssignCapFor(profile.embeddings.length, macCount)', 'macCount >= 10'], [...SE_T, ...LIB_T]),
148
+ m('store-guard-not-for-mac-incoming', SE, ['const macAtCap = isMacAssign(source) && macCount >= macAssignCapFor(profile.embeddings.length, macCount)', 'const macAtCap = false'], [...SE_T, ...LIB_T]),
149
+ m('merge-mac-not-trimmed', VP, ['const trimmed = new Set(macKept.slice(0, Math.max(0, macKept.length - macAllowed)))', 'const trimmed = new Set<number>()'], MERGE_T),
150
+ m('merge-trims-newest-mac', VP, ['const trimmed = new Set(macKept.slice(0, Math.max(0, macKept.length - macAllowed)))', 'const trimmed = new Set(macKept.slice(macAllowed))'], MERGE_T),
151
+ m('merge-mac-cap-flat-ten', VP, ['macAssignCapFor(kept.length, macKept.length)', 'Math.min(10, kept.length)'], MERGE_T),
152
+ m('merge-mac-ranked-as-assisted', VP, ['isMacAssign(sources[i]) ? -1 : EVICTION_ORDER', 'false ? -1 : EVICTION_ORDER'], MERGE_T),
153
+ m('profiles-listing-mac-assign-uncollapsed', VR, [": source.startsWith('mac-assign:') ? 'mac-assign' : source", ': source'], VS_T),
154
+ m('route-finalizing-post-check-dropped', M, [' const finalizingAfter = finalizingRefusal(sessionId)\n', ' const finalizingAfter = null as ReturnType<typeof finalizingRefusal>\n'], ROUTE_T),
155
+ m('deattribute-retracts-nothing', M, ['retracted = retractEmbeddingsBySource(from, s => isSampleFromSession(s, sessionId)).removed', 'retracted = 0'], ROUTE_T),
156
+ m('deattribute-retracts-every-sample', M, ['retracted = retractEmbeddingsBySource(from, s => isSampleFromSession(s, sessionId)).removed', 'retracted = retractEmbeddingsBySource(from, () => true).removed'], ROUTE_T),
157
+ m('mac-assign-cap-changed', EV, ['export const MAC_ASSIGN_PROFILE_CAP = 10', 'export const MAC_ASSIGN_PROFILE_CAP = 20'], [...EV_T, ...SE_T, ...ROUTE_T]),
158
+ m('mac-assign-not-retractable', TP, ["['auto:', 'correction:', 'g2-training:', 'ext-group:', 'mac-assign:']", "['auto:', 'correction:', 'g2-training:', 'ext-group:']"], [...TP_T, ...ROUTE_T]),
159
+ // ── 6.93.0 final: a merge never leaves an empty profile; a correction at quota runs before the Mac step ──
160
+ m('merge-allows-empty-profile', SE, ["if (wouldBe.mergedFrom.length > 0 && wouldBe.samplesAfter === 0) {", 'if (false) {'], MERGE_T),
161
+ m('merge-empty-refusal-not-409', VR, [' if (report.refusal) {\n', ' if (false) {\n'], VS_T),
162
+ m('correction-quota-after-mac-step', EV, ['if (isCorrection(incomingSource) && correctionIdx.length >= correctionQuota(cap)) {', 'if (isCorrection(incomingSource) && correctionIdx.length >= correctionQuota(cap) && macIdx.length === 0) {'], [...EV_T, ...SE_T]),
163
+ // ── B2/B4/W8: the real store code ──
164
+ m('batch-writes-per-sample', SE, [' appendEmbedding(profile, Array.from(item.embedding), item.source)\n added++\n', ' appendEmbedding(profile, Array.from(item.embedding), item.source)\n added++\n writeProfileStore(store)\n'], SE_T),
165
+ m('batch-dedup-dropped', SE, [' if (profile.embeddings.some(existing => rawCosineSimilarity(item.embedding, new Float32Array(existing)) > 0.95)) { declined++; continue }\n', ''], SE_T),
166
+ m('batch-room-not-made', SE, [' const room = makeRoomForSample(name, profile, item.source)\n if (!room.ok) { declined++; continue }\n', ''], SE_T),
167
+ m('batch-write-failure-swallowed', SE, [" if (!writeProfileStore(store)) throw new Error('the store refused the write')\n } catch (err: unknown) {\n restoreProfileFromDisk(name)\n return { enrolled: 0, declined: items.length", " writeProfileStore(store)\n } catch (err: unknown) {\n restoreProfileFromDisk(name)\n return { enrolled: 0, declined: items.length"], SE_T),
168
+ m('batch-failure-memory-kept', SE, [" } catch (err: unknown) {\n restoreProfileFromDisk(name)\n return { enrolled: 0, declined: items.length", " } catch (err: unknown) {\n return { enrolled: 0, declined: items.length"], SE_T),
169
+ m('batch-failure-counts-enrolled', SE, ["return { enrolled: 0, declined: items.length, persisted: false, error: `Profile store write failed: ${errMsg(err)}` }\n }\n rebuildSpeakerInManager", "return { enrolled: added, declined: items.length, persisted: false, error: `Profile store write failed: ${errMsg(err)}` }\n }\n rebuildSpeakerInManager"], SE_T),
170
+ m('mac-cap-not-enforced', SE, ['if (profile.embeddings.length < MAX_EMBEDDINGS_PER_SPEAKER && !macAtCap) return { ok: true }', 'if (profile.embeddings.length < MAX_EMBEDDINGS_PER_SPEAKER) return { ok: true }'], SE_T),
171
+ m('refusal-falls-back-to-oldest', SE, [" if (choice?.refuse) {\n", " if (false) {\n"], SE_T),
172
+ m('persist-swallows-write-error', SE, [" restoreProfileFromDisk(name)\n throw err instanceof Error ? err : new Error(errMsg(err))\n", " restoreProfileFromDisk(name)\n"], SE_T),
173
+ m('persist-ignores-refused-write', SE, [" if (!writeProfileStore(store)) throw new Error('the store refused the write')\n } catch (err: unknown) {\n console.error('[speaker] Profile persist error:', errMsg(err))", " writeProfileStore(store)\n } catch (err: unknown) {\n console.error('[speaker] Profile persist error:', errMsg(err))"], SE_T),
174
+ m('persist-failure-memory-kept', SE, [" console.error('[speaker] Profile persist error:', errMsg(err))\n restoreProfileFromDisk(name)\n", " console.error('[speaker] Profile persist error:', errMsg(err))\n"], SE_T),
175
+ m('enroll-reports-success-after-failed-write', SE, [" try {\n persistProfile(name, embedding, source)\n } catch (err: unknown) {\n return { success: false, dim: extractor.dim, error: `Profile store write failed: ${errMsg(err)}` }\n }\n const updatedStore", " try {\n persistProfile(name, embedding, source)\n } catch (err: unknown) {\n }\n const updatedStore"], SE_T),
176
+ m('enroll-reports-success-after-failed-write-new', SE, [" // Persist to disk with provenance\n try {\n persistProfile(name, embedding, source)\n } catch (err: unknown) {\n return { success: false, dim: extractor.dim, error: `Profile store write failed: ${errMsg(err)}` }\n }", " // Persist to disk with provenance\n try {\n persistProfile(name, embedding, source)\n } catch (err: unknown) {\n }"], SE_T),
177
+ m('restore-leaves-phantom-speaker', SE, [" else if (manager?.contains(name)) manager.remove(name)\n", ''], SE_T),
178
+ ]
179
+
180
+ const args = process.argv.slice(2)
181
+ if (args.includes('--list')) { for (const { name } of mutations) console.log(name); process.exit(0) }
182
+ const selected = args.length ? mutations.filter(({ name }) => args.includes(name)) : mutations
183
+ if (args.length && selected.length !== args.length) throw new Error('Unknown mutation name in: ' + args.join(' '))
184
+ if (new Set(mutations.map(x => x.name)).size !== mutations.length) throw new Error('Duplicate mutation name')
185
+
186
+ // Record exactly which code this run proved (QA R-N1): the commit, and whether the tree matched it.
187
+ const rev = spawnSync('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).stdout.trim()
188
+ const modified = spawnSync('git', ['-C', root, 'status', '--porcelain', '--untracked-files=no'], { encoding: 'utf8' }).stdout.split('\n').filter(Boolean).length
189
+ console.log(`commit ${rev || 'unknown'} (${modified ? `${modified} modified files: NOT the committed code` : 'clean tree'})`)
190
+ const scratch = mkdtempSync(join(tmpdir(), "mac-voice-assignment-6930-mutations-"))
191
+ try {
192
+ const skip = new Set(['data', 'models', 'certs', 'node_modules'])
193
+ cpSync(join(root, 'server'), join(scratch, 'server'), { recursive: true, filter: src => !(skip.has(basename(src)) && dirname(src) === join(root, 'server')) })
194
+ for (const dir of ['shared', 'work-task-runtime', 'bin', 'docs', 'memory-runtime']) cpSync(join(root, dir), join(scratch, dir), { recursive: true })
195
+ for (const file of ['vitest.config.ts', 'package.json', 'managed-runtime-contract.json']) cpSync(join(root, file), join(scratch, file))
196
+ symlinkSync(join(root, 'node_modules'), join(scratch, 'node_modules'), 'dir')
197
+ const run = tests => spawnSync(process.execPath, [join(root, 'node_modules/vitest/vitest.mjs'), 'run', '--maxWorkers=1', ...tests], {
198
+ cwd: scratch, env: { PATH: process.env.PATH, HOME: scratch, TMPDIR: process.env.TMPDIR, COS_DATA_DIR: join(scratch, 'data'), COS_PROFILE_PATH: join(scratch, 'data', 'profile.json') },
199
+ encoding: 'utf8', timeout: 300000,
200
+ })
201
+ const baseline = run(ALL)
202
+ if (baseline.status !== 0) throw new Error('Baseline failed; a gate over a red suite proves nothing:\n' + baseline.stdout + '\n' + baseline.stderr)
203
+ const totals = /Tests\s+(\d+) passed/.exec(baseline.stdout)
204
+ console.log(`baseline PASS (${totals ? totals[1] : '?'} tests in ${ALL.length} files)`)
205
+ let killed = 0
206
+ for (const { name, file, edits, tests } of selected) {
207
+ const target = join(scratch, file), original = readFileSync(target, 'utf8')
208
+ let mutated = original
209
+ for (const [find, replacement] of edits) {
210
+ if (mutated.split(find).length !== 2) throw new Error(`Mutation ${name} does not match exactly once in ${file}: ${find.slice(0, 80)}`)
211
+ mutated = mutated.replace(find, () => replacement)
212
+ }
213
+ if (mutated === original) throw new Error(`Mutation ${name} did not change ${file}`)
214
+ writeFileSync(target, mutated)
215
+ let result
216
+ try { result = run(tests) } finally { writeFileSync(target, original) }
217
+ if (readFileSync(target, 'utf8') !== original) throw new Error(`Restore failed for ${file} after ${name}`)
218
+ const output = result.stdout + '\n' + result.stderr
219
+ const killers = [...new Set([...output.matchAll(/FAIL\s+(server\/\S+\.test\.ts > [^\n]+)/g)].map(x => x[1].trim()))]
220
+ if (result.status === 0 || result.error || !killers.length) { console.log(`${name} SURVIVED or harness failed\n${output.slice(-3000)}`); process.exitCode = 1; continue }
221
+ killed += 1
222
+ console.log(`${name} KILLED by ${killers.slice(0, 2).join(' | ')}${killers.length > 2 ? ` (+${killers.length - 2} more)` : ''}`)
223
+ }
224
+ console.log(`${killed} of ${selected.length} Mac voice assignment 6.93.0 mutations killed`)
225
+ } finally { rmSync(scratch, { recursive: true, force: true }) }
@@ -0,0 +1,193 @@
1
+ #!/usr/bin/env node
2
+ // 6.93.0 mutation gate: live Mac window replay (lib/mac-window-voices.ts, lib/mac-window-replay.ts), its hook in
3
+ // lib/nemotron-live.ts and the Mac chunk route. Engine copied unchanged from mac-voices-6900-mutation-gate.mjs;
4
+ // mutations run only in a disposable copy of the checkout.
5
+ //
6
+ // What it proves, in order:
7
+ // 0. The target suites are GREEN unmutated. A gate over a red suite reads every mutant as killed and proves nothing.
8
+ // 1. Each target string appears EXACTLY ONCE in its file, so the mutation is unambiguous.
9
+ // 2. The mutated file differs from the original, so the edit landed.
10
+ // 3. A NAMED test fails ("FAIL server/x.test.ts > name"); a build error or a harness failure is not a kill.
11
+ // 4. The file is restored byte for byte (compared) before the next mutant.
12
+ // Usage: node server/scripts/mac-window-voices-6930-mutation-gate.mjs [--list] [name…]
13
+ import { mkdtempSync, cpSync, readFileSync, writeFileSync, symlinkSync, rmSync } from 'node:fs'
14
+ import { tmpdir } from 'node:os'
15
+ import { resolve, join, dirname, basename } from 'node:path'
16
+ import { fileURLToPath } from 'node:url'
17
+ import { spawnSync } from 'node:child_process'
18
+
19
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..')
20
+ const UNIT_T = ['server/lib/mac-window-voices.test.ts']
21
+ const REPLAY_T = ['server/lib/mac-window-replay.test.ts']
22
+ const LABELS_T = ['server/lib/mac-voice-labels.test.ts']
23
+ const LIVE_T = ['server/lib/nemotron-live.test.ts']
24
+ const FINAL_T = ['server/lib/nemotron-final-mac-voices.test.ts']
25
+ const MAC_T = ['server/routes/mac-recording.test.ts']
26
+ const ALL = [...UNIT_T, ...REPLAY_T, ...LABELS_T, ...LIVE_T, ...FINAL_T, ...MAC_T]
27
+ const W = 'server/lib/mac-window-voices.ts', RP = 'server/lib/mac-window-replay.ts', L = 'server/lib/nemotron-live.ts', TS = 'server/routes/transcribe-stream.ts'
28
+ const VL = 'server/lib/mac-voice-labels.ts', NF = 'server/lib/nemotron-final.ts'
29
+ const m = (name, file, edits, tests) => ({ name, file, edits: typeof edits[0] === 'string' ? [edits] : edits, tests })
30
+
31
+ const mutations = [
32
+ // ── Switch (QA B1: with every switch off a Mac recording is 6.92.0) ──
33
+ // Default ON (Miles 2026-10-26): unset is the window; only an explicit off (0, false, no) or COS_MAC_VOICE_LABELS off is 6.92.0.
34
+ m('live-default-off', VL, [" }\n return 'window'\n}", " }\n return 'off'\n}"], [...LABELS_T, ...UNIT_T, ...REPLAY_T, ...MAC_T]),
35
+ m('live-default-anchors', VL, [" }\n return 'window'\n}", " }\n return 'anchors'\n}"], [...LABELS_T, ...UNIT_T, ...MAC_T]),
36
+ m('anchors-unselectable', VL, [" if (raw === 'anchors') return 'anchors'\n", ''], [...LABELS_T, ...UNIT_T]),
37
+ m('explicit-off-ignored', VL, [" if (OFF_WORDS.includes(raw)) return 'off'\n", ''], [...LABELS_T, ...UNIT_T, ...MAC_T]),
38
+ // Every spelling of off is its own guard (6.93.0 added none, disable, disabled, never).
39
+ ...['0', 'false', 'off', 'no', 'none', 'disable', 'disabled', 'never'].map(word => {
40
+ const list = ['0', 'false', 'off', 'no', 'none', 'disable', 'disabled', 'never']
41
+ const quote = items => '[' + items.map(x => `'${x}'`).join(', ') + ']'
42
+ return m(`off-word-${word}-dropped`, VL, [`export const OFF_WORDS: readonly string[] = ${quote(list)}`, `export const OFF_WORDS: readonly string[] = ${quote(list.filter(x => x !== word))}`], LABELS_T)
43
+ }),
44
+ // ── W9: an unrecognised value is window and says so once ──
45
+ m('unrecognised-not-warned', VL, [' warn(`[mac-voices] mac_live_voices_unrecognised', ' void(`[mac-voices] mac_live_voices_unrecognised'], LABELS_T),
46
+ m('unrecognised-warned-every-time', VL, ["raw !== 'window' && !warnedUnrecognised.has(raw)) {", "raw !== 'window') {"], LABELS_T),
47
+ m('window-value-warned', VL, ["if (raw !== '' && raw !== 'window' && !warnedUnrecognised", "if (raw !== '' && !warnedUnrecognised"], LABELS_T),
48
+ m('empty-value-warned', VL, ["if (raw !== '' && raw !== 'window' && !warnedUnrecognised", "if (raw !== 'window' && !warnedUnrecognised"], LABELS_T),
49
+ m('anchors-value-warned', VL, [" if (raw === 'anchors') return 'anchors'\n if (raw !==", " if (raw !=="], LABELS_T),
50
+ m('explicit-off-case-sensitive', VL, ["const raw = String(env.COS_MAC_LIVE_VOICES ?? '').trim().toLowerCase()", "const raw = String(env.COS_MAC_LIVE_VOICES ?? '').trim()"], LABELS_T),
51
+ m('voice-labels-off-not-master', VL, [" if (!macVoiceLabelsEnabled(env)) return 'off'\n const raw", ' const raw'], [...LABELS_T, ...UNIT_T, ...MAC_T]),
52
+ m('voice-shape-unchecked', VL, ['return Array.isArray(segments) && segments.some(', 'return segments.some('], LABELS_T),
53
+ m('anchors-run-when-off', TS, ["macLiveVoicesMode() === 'anchors' ? {", "macLiveVoicesMode() !== 'window' ? {"], MAC_T),
54
+ m('anchors-run-in-window-mode', TS, ["macLiveVoicesMode() === 'anchors' ? {", "macLiveVoicesMode() !== 'off' ? {"], MAC_T),
55
+ m('projection-when-off', TS, ["labels.diarizer?.engine === 'nemotron' && macLiveVoicesMode() !== 'off'", "labels.diarizer?.engine === 'nemotron'"], MAC_T),
56
+ m('g2-takes-window', TS, ['const macWindowOn = MAC_CAPTURE_ID.test(sessionId) && macWindowVoicesEnabled()', 'const macWindowOn = macWindowVoicesEnabled()'], MAC_T),
57
+ m('final-restricts-without-live-voices', NF, ['const liveMap = liveNumbers.length ? mapChannelsToLiveVoices(timeline.windows, activity) : null', 'const liveMap = mapChannelsToLiveVoices(timeline.windows, activity)'], [...FINAL_T, ...MAC_T]),
58
+ m('final-leaves-unproven-ext', NF, ['channels = found.channels.filter(channel => !liveMap || liveMap.has(channel) || unproven.includes(channel))', 'channels = found.channels.filter(channel => !liveMap || liveMap.has(channel))'], FINAL_T),
59
+ m('final-numbers-contradicted-channel', NF, ['return channels.filter(channel => !claims.has(channel))', 'return channels'], FINAL_T),
60
+ m('final-number-collides-with-live', NF, ['let next = Math.max(...liveNumbers)', 'let next = 0'], FINAL_T),
61
+ // ── Carry across the boundary ──
62
+ m('carry-min-ignored', W, ['if (c.count < MAC_WINDOW_CARRY_MIN_FRAMES || ', 'if ('], UNIT_T),
63
+ m('carry-agreement-ignored', W, [' || c.count / exclusiveInOverlap.get(c.slot)! < MAC_WINDOW_CARRY_AGREEMENT) continue', ') continue'], UNIT_T),
64
+ m('carry-not-one-to-one', W, ['if (slotTrack.has(c.slot) || usedTracks.has(c.track)) continue', 'if (slotTrack.has(c.slot)) continue'], UNIT_T),
65
+ // The denominator counts untracked exclusive frames too (they are why a slot of mixed history is not carried).
66
+ m('untracked-not-in-denominator', W, [
67
+ [' exclusiveInOverlap.set(slot, (exclusiveInOverlap.get(slot) ?? 0) + 1)\n const track = codes[i]\n if (track < 0) continue\n', ' const track = codes[i]\n if (track < 0) continue\n exclusiveInOverlap.set(slot, (exclusiveInOverlap.get(slot) ?? 0) + 1)\n'],
68
+ ], UNIT_T),
69
+ // ── The current chunk must agree (QA W1) ──
70
+ m('agreement-skipped', W, ['if (chunkAgreesWithSlot(window, start, length, slot, input.chunkAlone)) continue', 'if (true) continue'], UNIT_T),
71
+ m('agreement-without-a-view', W, ['if (!alone || alone.probs.length !== alone.frames * NEMOTRON_CHANNELS) return false', 'if (!alone) return true\n if (alone.probs.length !== alone.frames * NEMOTRON_CHANNELS) return false'], UNIT_T),
72
+ m('agreement-coverage-ignored', W, ['if (covered === 0 || covered < own * MAC_WINDOW_AGREE_COVERAGE) return false', 'if (covered === 0) return false'], UNIT_T),
73
+ m('agreement-purity-ignored', W, ['return Math.max(...perChannel.values()) / covered >= MAC_WINDOW_AGREE_PURITY', 'return true'], UNIT_T),
74
+ m('withheld-slot-still-coded-tracked', W, ['slotTrack.delete(slot)\n withheld++', 'withheld++'], UNIT_T),
75
+ m('silent-carried-slot-counted-as-disagreement', W, [' if ((exclusiveNew.get(slot) ?? 0) === 0) { slotTrack.delete(slot); continue }\n', ''], UNIT_T),
76
+ // ── Repeated window timeouts stop the window for the capture (QA R3) ──
77
+ m('disable-threshold-off-by-one', RP, ['timeouts >= MAC_WINDOW_BACKOFF_TIMEOUTS && !windowDisabled.has(sessionId)', 'timeouts > MAC_WINDOW_BACKOFF_TIMEOUTS && !windowDisabled.has(sessionId)'], [...REPLAY_T, ...MAC_T]),
78
+ m('backoff-window-of-one', RP, ['.slice(-MAC_WINDOW_BACKOFF_OF_LAST)', '.slice(-1)'], REPLAY_T),
79
+ m('backoff-window-unbounded', RP, ['.slice(-MAC_WINDOW_BACKOFF_OF_LAST)', '.slice(-1000)'], REPLAY_T),
80
+ m('backoff-counts-non-timeout', RP, ['const timeouts = recent.filter(Boolean).length', 'const timeouts = recent.length'], REPLAY_T),
81
+ m('timeout-not-counted', RP, [' noteWindowRun(input.sessionId, !outcome.ok && outcome.reason === \'timeout\', log)\n', ''], [...REPLAY_T, ...MAC_T]),
82
+ m('disable-logged-every-time', RP, ['timeouts >= MAC_WINDOW_BACKOFF_TIMEOUTS && !windowDisabled.has(sessionId)', 'timeouts >= MAC_WINDOW_BACKOFF_TIMEOUTS'], REPLAY_T),
83
+ m('route-ignores-disabled-window', TS, [' && !macWindowDisabledFor(sessionId)\n', '\n'], MAC_T),
84
+ // ── A re-run over the pass's own output reads the live label, not its own (QA R-N2) ──
85
+ m('rerun-reads-speaker', NF, ["return typeof chunk?.originalSpeaker === 'string' ? chunk.originalSpeaker : chunk?.speaker", 'return chunk?.speaker'], FINAL_T),
86
+ m('rerun-numbers-read-speaker', NF, ['entries.flatMap(entry => [liveLabelOf(entry.chunk), ', 'entries.flatMap(entry => [entry.chunk?.speaker, '], FINAL_T),
87
+ m('agreement-view-dropped', RP, ['crossed = cross(outcome.run, solo.ok ? solo.run : null, plan)', 'crossed = cross(outcome.run, null, plan)'], [...REPLAY_T, ...MAC_T]),
88
+ m('agreement-run-unconditional', RP, ['if (crossed.stats.carried > 0) {', 'if (true) {'], REPLAY_T),
89
+ m('agreement-run-failure-allowed', RP, ['crossed = cross(outcome.run, solo.ok ? solo.run : null, plan)', 'crossed = cross(outcome.run, solo.ok ? solo.run : soloOf(outcome.run, plan), plan)\n function soloOf(run, p) { const before = p.chunks.slice(0, -1).reduce((n, c) => n + c.samples, 0); const f0 = Math.floor(before / 160); const n = run.frames - f0; return { frames: n, probs: run.probs.slice(f0 * 8, (f0 + n) * 8) } }'], REPLAY_T),
90
+ // ── New tracks, eviction, cap ──
91
+ m('new-track-despite-overlap', W, ['if (slotTrack.has(slot) || votes.has(slot) || n < MAC_WINDOW_NEW_TRACK_FRAMES) continue', 'if (slotTrack.has(slot) || n < MAC_WINDOW_NEW_TRACK_FRAMES) continue'], UNIT_T),
92
+ m('new-track-any-length', W, ['if (slotTrack.has(slot) || votes.has(slot) || n < MAC_WINDOW_NEW_TRACK_FRAMES) continue', 'if (slotTrack.has(slot) || votes.has(slot)) continue'], UNIT_T),
93
+ m('track-cap-ignored', W, [' if (id >= MAC_WINDOW_MAX_TRACKS) { capped++; continue }\n', ''], UNIT_T),
94
+ m('no-eviction', W, ['state.tracks = state.tracks.filter(t => referenced.has(t.id))', 'state.tracks = state.tracks'], UNIT_T),
95
+ m('eviction-drops-referenced', W, ['state.tracks = state.tracks.filter(t => referenced.has(t.id))', 'state.tracks = state.tracks.filter(t => t.voice !== null)'], UNIT_T),
96
+ m('max-voice-ignored', W, [' if (state.voices >= MAX_VOICE) { t.proofs.pop(); continue }\n', ''], UNIT_T),
97
+ // ── Proof and numbering ──
98
+ m('one-proof-confirms', W, [' if (t.proofs.length >= MAC_WINDOW_PROOFS) {', ' if (t.proofs.length >= 1) {'], [...UNIT_T, ...MAC_T]),
99
+ m('duplicate-audio-proof', W, ['if (t.proofs.some(p => p.chunk === current.chunk || p.audioSha256 === audioSha256)) continue', 'if (t.proofs.some(p => p.chunk === current.chunk)) continue'], UNIT_T),
100
+ m('proof-purity-ignored', W, ['if (ex < MAC_WINDOW_PROOF_FRAMES || purity < MAC_WINDOW_PROOF_PURITY || t.voice !== null) continue', 'if (ex < MAC_WINDOW_PROOF_FRAMES || t.voice !== null) continue'], UNIT_T),
101
+ m('proof-any-length', W, ['if (ex < MAC_WINDOW_PROOF_FRAMES || purity < MAC_WINDOW_PROOF_PURITY || t.voice !== null) continue', 'if (purity < MAC_WINDOW_PROOF_PURITY || t.voice !== null) continue'], UNIT_T),
102
+ // ── Untrusted input ──
103
+ m('geometry-unchecked', W, [' if (window.frames !== macWindowFrameCount(sample)) return null\n', ''], UNIT_T),
104
+ m('geometry-tail-fft-wrong', W, ['export const MAC_WINDOW_FFT_SAMPLES = 512', 'export const MAC_WINDOW_FFT_SAMPLES = 500'], UNIT_T),
105
+ m('geometry-tail-window-wrong', W, ['export const MAC_WINDOW_FRAME_SAMPLES = 400', 'export const MAC_WINDOW_FRAME_SAMPLES = 399'], UNIT_T),
106
+ m('geometry-hop-wrong', W, ['Math.round(MAC_AUDIO.sampleRate * NEMOTRON_FRAME_SEC)', 'Math.round(MAC_AUDIO.sampleRate * NEMOTRON_FRAME_SEC) + 1'], UNIT_T),
107
+ m('window-ceiling-wrong', W, ['MAC_AUDIO.sampleRate * (MAC_AUDIO.maxChunkMs / 1000)', 'MAC_AUDIO.sampleRate * (MAC_AUDIO.maxChunkMs / 1000) - 1'], UNIT_T),
108
+ m('values-unchecked', W, [' for (const v of window.probs) if (!Number.isFinite(v) || v < 0 || v > 1) return null\n', ''], UNIT_T),
109
+ m('invalid-state-accepted', W, ['if (!validMacWindowVoices(input.state) || !SHA.test(audioSha256)', 'if (!SHA.test(audioSha256)'], UNIT_T),
110
+ m('voice-above-highwater', W, ['if (!isIndex(t.voice) || t.voice < 1 || t.voice > s.voices || voices.has(t.voice)', 'if (!isIndex(t.voice) || t.voice < 1 || voices.has(t.voice)'], UNIT_T),
111
+ m('duplicate-voice-accepted', W, ['|| t.voice > s.voices || voices.has(t.voice) ||', '|| t.voice > s.voices ||'], UNIT_T),
112
+ m('unproven-number-accepted', W, [' } else if (t.proofs.length >= MAC_WINDOW_PROOFS) return false\n', ' }\n'], UNIT_T),
113
+ m('recent-order-unchecked', W, ['if (!r || !isIndex(r.chunk) || r.chunk <= last) return false', 'if (!r || !isIndex(r.chunk)) return false'], UNIT_T),
114
+ m('frame-codes-unchecked', W, ['codes.some(c => c < UNTRACKED || (c >= 0 && !ids.has(c)))', 'codes.some(c => c < UNTRACKED)'], UNIT_T),
115
+ m('frame-length-cap-ignored', W, ['frames.length > 64_000 || ', ''], UNIT_T),
116
+ // ── Plan and bounds ──
117
+ m('plan-bridges-gap', W, ['if (!isIndex(n) || n === 0 || total + n > MAC_WINDOW_MAX_SAMPLES) break', 'if (!isIndex(n) || n === 0 || total + n > MAC_WINDOW_MAX_SAMPLES) continue'], UNIT_T),
118
+ m('plan-sample-cap-ignored', W, ['if (!isIndex(n) || n === 0 || total + n > MAC_WINDOW_MAX_SAMPLES) break', 'if (!isIndex(n) || n === 0) break'], UNIT_T),
119
+ m('recent-unbounded', W, [' .slice(-(MAC_WINDOW_MAX_CHUNKS - 1))\n', ''], [...UNIT_T, ...MAC_T]),
120
+ // ── Timeouts and fallback (QA W4) ──
121
+ m('window-budget-per-chunk', RP, ['const timeoutMs = liveBudgetForAudioSec(windowSec)', 'const timeoutMs = 1500'], [...REPLAY_T, ...MAC_T]),
122
+ m('timeout-no-fallback', RP, ["return outcome.reason === 'timeout' ? fallback('timeout', outcome.ms) : outcome", 'return outcome'], [...REPLAY_T, ...MAC_T]),
123
+ m('other-failures-fall-back', RP, ["return outcome.reason === 'timeout' ? fallback('timeout', outcome.ms) : outcome", "return fallback('timeout', outcome.ms)"], REPLAY_T),
124
+ m('geometry-no-fallback', RP, ["let crossed = cross(outcome.run, null, plan)\n if (!crossed) return fallback('geometry', undefined)", "let crossed = cross(outcome.run, null, plan)\n if (!crossed) return { ok: false, reason: 'bad_output' } as LiveDiarizeOutcome"], REPLAY_T),
125
+ m('window-timeout-trips-breaker', L, ["if (RUN_FAILURES.has(reason) && !(reason === 'timeout' && options.timeoutTripsBreaker === false)) {", 'if (RUN_FAILURES.has(reason)) {'], LIVE_T),
126
+ m('window-exempt-from-all-failures', L, ["if (RUN_FAILURES.has(reason) && !(reason === 'timeout' && options.timeoutTripsBreaker === false)) {", 'if (RUN_FAILURES.has(reason) && options.timeoutTripsBreaker !== false) {'], LIVE_T),
127
+ m('timeout-option-ignored', L, ['timeoutMs: options.timeoutMs ?? this.budget(),', 'timeoutMs: this.budget(),'], LIVE_T),
128
+ m('budget-not-scaled', L, ['Math.max(LIVE_BUDGET_MS, Math.ceil(LIVE_BUDGET_MS * (Number.isFinite(audioSec) ? audioSec : 0) / LIVE_BUDGET_REFERENCE_AUDIO_SEC))', 'LIVE_BUDGET_MS'], LIVE_T),
129
+ m('window-tripping-diarize-call', TS, ['diarizeWindow: (wavPath, timeoutMs) => nemotronLive.diarize(wavPath, { timeoutMs, timeoutTripsBreaker: false }),', 'diarizeWindow: (wavPath, timeoutMs) => nemotronLive.diarize(wavPath, { timeoutMs }),'], MAC_T),
130
+ // ── Telemetry (QA W8) ──
131
+ m('withheld-state-not-noted', TS, [' if (macWindowWithheld) noteMacWindowWithheld(sessionId, macWindowWithheld)\n', ''], MAC_T),
132
+ m('withheld-noted-every-chunk', RP, [' if (seenWithheld.has(key)) return\n', ''], REPLAY_T),
133
+ m('window-line-not-logged', RP, [' log(`[mac-window] chunk #${input.chunkIndex} window ${plan.chunks.length} chunks', ' void (`[mac-window] chunk #${input.chunkIndex} window ${plan.chunks.length} chunks'], REPLAY_T),
134
+ // ── I/O half and route ──
135
+ m('restart-after-voice-labels', RP, [" return chunks.some(chunkShowsVoiceLabel) ? 'earlier_voice_labels' : null\n", ' return null\n'], [...REPLAY_T, ...MAC_T]),
136
+ m('corrupt-state-accepted', RP, ["return validMacWindowVoices(saved) ? null : 'corrupt_state'", 'return null'], [...REPLAY_T, ...MAC_T]),
137
+ m('corrupt-state-restarted', RP, [
138
+ [' if (macWindowWithheldReason(saved, chunks)) return null\n', " if (macWindowWithheldReason(saved, chunks) === 'earlier_voice_labels') return null\n"],
139
+ ['return saved === undefined ? emptyMacWindowVoices() : saved as MacWindowVoiceState', 'return saved === undefined || !validMacWindowVoices(saved) ? emptyMacWindowVoices() : saved as MacWindowVoiceState'],
140
+ ], [...REPLAY_T, ...MAC_T]),
141
+ m('window-wav-kept', RP, [' let cleaned = false\n const cleanup = () => {\n if (cleaned) return\n cleaned = true\n', ' let cleaned = false\n const cleanup = () => {\n if (cleaned || true) return\n cleaned = true\n'], [...REPLAY_T, ...MAC_T]),
142
+ m('channel-label-dropped', L, [' if (label && isVoiceLabel(label)) names.set(track.channel, { speaker: label, similarity: 0 })\n } else if (input.anonymousVoice', ' } else if (input.anonymousVoice'], MAC_T),
143
+ m('voice-overwrites-name', L, [' if (current && isRealLabel(current.speaker)) continue\n const label = input.anonymousChannel(track.channel)', ' const label = input.anonymousChannel(track.channel)'], MAC_T),
144
+ m('window-state-not-committed', TS, [' if (macWindowNext !== undefined) session.macWindowVoices = macWindowNext\n', ''], MAC_T),
145
+ m('window-state-not-persisted', TS, [' ...(session.macWindowVoices !== undefined ? { macWindowVoices: session.macWindowVoices } : {}),\n', ''], MAC_T),
146
+ ]
147
+
148
+ const args = process.argv.slice(2)
149
+ if (args.includes('--list')) { for (const { name } of mutations) console.log(name); process.exit(0) }
150
+ const selected = args.length ? mutations.filter(({ name }) => args.includes(name)) : mutations
151
+ if (args.length && selected.length !== args.length) throw new Error('Unknown mutation name in: ' + args.join(' '))
152
+ if (new Set(mutations.map(x => x.name)).size !== mutations.length) throw new Error('Duplicate mutation name')
153
+
154
+ // Record exactly which code this run proved (QA R-N1): the commit, and whether the tree matched it.
155
+ const rev = spawnSync('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).stdout.trim()
156
+ const modified = spawnSync('git', ['-C', root, 'status', '--porcelain', '--untracked-files=no'], { encoding: 'utf8' }).stdout.split('\n').filter(Boolean).length
157
+ console.log(`commit ${rev || 'unknown'} (${modified ? `${modified} modified files: NOT the committed code` : 'clean tree'})`)
158
+ const scratch = mkdtempSync(join(tmpdir(), 'mac-window-voices-6930-mutations-'))
159
+ try {
160
+ const skip = new Set(['data', 'models', 'certs', 'node_modules'])
161
+ cpSync(join(root, 'server'), join(scratch, 'server'), { recursive: true, filter: src => !(skip.has(basename(src)) && dirname(src) === join(root, 'server')) })
162
+ for (const dir of ['shared', 'work-task-runtime', 'bin', 'docs', 'memory-runtime']) cpSync(join(root, dir), join(scratch, dir), { recursive: true })
163
+ for (const file of ['vitest.config.ts', 'package.json', 'managed-runtime-contract.json']) cpSync(join(root, file), join(scratch, file))
164
+ symlinkSync(join(root, 'node_modules'), join(scratch, 'node_modules'), 'dir')
165
+ const run = tests => spawnSync(process.execPath, [join(root, 'node_modules/vitest/vitest.mjs'), 'run', '--maxWorkers=1', ...tests], {
166
+ cwd: scratch, env: { PATH: process.env.PATH, HOME: scratch, TMPDIR: process.env.TMPDIR, COS_DATA_DIR: join(scratch, 'data'), COS_PROFILE_PATH: join(scratch, 'data', 'profile.json') },
167
+ encoding: 'utf8', timeout: 300000,
168
+ })
169
+ const baseline = run(ALL)
170
+ if (baseline.status !== 0) throw new Error('Baseline failed; a gate over a red suite proves nothing:\n' + baseline.stdout + '\n' + baseline.stderr)
171
+ const totals = /Tests\s+(\d+) passed/.exec(baseline.stdout)
172
+ console.log(`baseline PASS (${totals ? totals[1] : '?'} tests in ${ALL.length} files)`)
173
+ let killed = 0
174
+ for (const { name, file, edits, tests } of selected) {
175
+ const target = join(scratch, file), original = readFileSync(target, 'utf8')
176
+ let mutated = original
177
+ for (const [find, replacement] of edits) {
178
+ if (mutated.split(find).length !== 2) throw new Error(`Mutation ${name} does not match exactly once in ${file}: ${find.slice(0, 80)}`)
179
+ mutated = mutated.replace(find, () => replacement)
180
+ }
181
+ if (mutated === original) throw new Error(`Mutation ${name} did not change ${file}`)
182
+ writeFileSync(target, mutated)
183
+ let result
184
+ try { result = run(tests) } finally { writeFileSync(target, original) }
185
+ if (readFileSync(target, 'utf8') !== original) throw new Error(`Restore failed for ${file} after ${name}`)
186
+ const output = result.stdout + '\n' + result.stderr
187
+ const killers = [...new Set([...output.matchAll(/FAIL\s+(server\/\S+\.test\.ts > [^\n]+)/g)].map(x => x[1].trim()))]
188
+ if (result.status === 0 || result.error || !killers.length) { console.log(`${name} SURVIVED or harness failed\n${output.slice(-3000)}`); process.exitCode = 1; continue }
189
+ killed += 1
190
+ console.log(`${name} KILLED by ${killers.slice(0, 2).join(' | ')}${killers.length > 2 ? ` (+${killers.length - 2} more)` : ''}`)
191
+ }
192
+ console.log(`${killed} of ${selected.length} Mac window replay 6.93.0 mutations killed`)
193
+ } finally { rmSync(scratch, { recursive: true, force: true }) }