# M2S — Master Implementation Specification
## Music-to-Style Engine עבור Korg Pa600
### גרסת Master — v2.0.0 — 25.09.2026

> **סטטוס:** Specification Baseline  
> **Target ראשוני:** Korg Pa600 Standard  
> **Target OS Profile:** Pa600 / OS 2.1.1  
> **Production Principle:** `Evidence → Model → Deterministic Engine → Native Artifact → Validation → Hardware QA`
>
> המסמך הזה מחליף את גרסת `M2S_Master_Implementation_Spec_Revised.md`.
> הוא משמר את הכיוון והמטרות של המסמך המקורי, אך מוסיף חוזים פורמליים, גבולות, מדיניות כשל, אבטחה, reproducibility, provenance, versioning, test gates, packaging safety, audio/MIDI separation, editor/LLM isolation ו־release management.

---

# 0. Executive Summary

M2S הוא מנוע עצמאי שמקבל:

```text
Reference Audio / MIDI
+
User Korg Pa600 SET
```

ומפיק:

```text
Native Korg STY
+
Optional Minimal SET
+
Optional Complete SET Package
+
Validation / Provenance Report
```

ה־Pa600 אינו חוליה בייצור.

```text
Production:
Input → M2S → STY / SET

QA:
STY / SET → Pa600 → Observe → PASS / FAIL
```

המשמעות:

- משתמש הקצה אינו חייב Pa600 כדי לבצע production run.
- Pa600 נדרש רק ל־Hardware Compatibility Certification.
- כל פעולה לפני Writer חייבת להיות ניתנת להרצה ללא חומרה.
- כל מה שאפשר לבדוק סטטית נבדק אוטומטית.
- כל מה שדורש חומרה נכנס ל־Hardware Test Suite נפרד.

עקרון־על:

```text
Korg Evidence
↓
Korg Codec / Resource Model
↓
Internal Music Model
↓
Deterministic Style Compiler
↓
Native STY Writer
↓
Static Validation
↓
Optional SET Packager
↓
Hardware QA
```

AI הוא שכבת עזר מאוחרת:

```text
Audio/MIDI Intelligence
LLM Planner
FX Estimator
```

ולא מקור האמת של הפורמט.

---

# 1. מטרת המוצר

## 1.1 מטרת Core

להפוך מקור מוזיקלי לקונסטרוקציה של Style עבור Pa600 תוך שימוש ב־SET שהמשתמש סיפק:

```text
Song
+
User SET
↓
M2S
↓
Rhythmic Structure
↓
Korg-compatible Mapping
↓
Native Style
```

## 1.2 סוגי Input

M2S יתמוך בשלושה מסלולים:

```text
A. Audio + SET
B. MIDI + SET
C. Existing Korg Style / SET → analysis/edit/rebuild
```

המסלול C חשוב ל־Reverse Engineering ול־Editor.

## 1.3 סוגי Output

### Native STY

```text
generated_style.sty
```

### Diagnostic MIDI

```text
generated_style_diagnostic.mid
```

נועד לבדיקה אנושית/מוזיקלית בלבד ואינו תחליף ל־STY.

### Minimal SET

```text
generated.SET/
```

מכיל רק את המשאבים שהוכחו כנדרשים.

### Complete SET

חבילה רחבה יותר כאשר המשתמש מבקש אריזה מלאה.

### Report

```text
m2s_report.json
m2s_report.html
```

יכלול:

```text
inputs
versions
hashes
detected structure
mapping decisions
warnings
confidence
validation
hardware status
```

---

# 2. גבולות המערכת

## 2.1 Target ראשון

```text
Device: Korg Pa600 Standard
OS Profile: 2.1.1
```

אין לפתח בשלב ראשון במקביל עבור:

```text
Pa600QT
Pa700
Pa1000
Pa4X
Pa5X
```

לכל דגם עתידי יהיה Profile נפרד.

## 2.2 Unsupported Does Not Mean Corrupt

אם קובץ/SET מגיע מדגם או OS שאינו נתמך:

```text
status = UNSUPPORTED_PROFILE
```

ולא:

```text
guess_target_format
```

במצב כזה המערכת יכולה:

```text
inspect
read
report
preserve
```

אבל לא להפיק Native artifact שאינו מוסמך.

---

# 3. מקור האמת

M2S משתמשת בהיררכיית Evidence:

```text
LEVEL 1 — VERIFIED
```

הוכח:

- בקובץ אמיתי;
- בניסוי Variable Isolation;
- ובמידת הצורך על Pa600 חומרה.

```text
LEVEL 2 — DOCUMENTED
```

מופיע בתיעוד Korg אך עדיין לא הוכח במימוש שלנו.

```text
LEVEL 3 — EXPERIMENTAL
```

השערה Reverse Engineering, inference, benchmark זמני או behavior שלא אומת.

## 3.1 כלל

אסור:

```text
EXPERIMENTAL → silently treat as VERIFIED
```

מותר:

```text
EXPERIMENTAL → preserve + expose warning
```

---

# 4. Five-Pass Quality Review

הגרסה הזו נבדקה בחמישה מסלולי ביקורת נפרדים.

## Pass 1 — Requirements Completeness

בדיקת:

```text
Input
Output
Scope
MVP
Failure states
Acceptance criteria
```

תיקון עיקרי:

```text
נוספו Input/Output contracts ו־failure model.
```

## Pass 2 — Korg Format Integrity

בדיקת:

```text
Style Elements
CVs
Style Tracks
SMF
NTT
Style Performance
KMP/KSF
SET
```

תיקון עיקרי:

```text
Style Pattern ≠ Style Performance
CASM ≠ Korg Pa600 model
SMF ≠ complete STY representation
```

## Pass 3 — Internal Model Integrity

בדיקת:

```text
time
ticks
events
groove
pattern identity
mapping
resources
```

תיקון עיקרי:

```text
Absolute time is canonical.
Seconds are an input/output boundary.
MIDI and Audio paths converge only after normalization.
```

## Pass 4 — Failure, Safety and QA

בדיקת:

```text
corruption
bad input
partial analysis
unknown fields
SET collisions
worker failures
rollback
```

תיקון עיקרי:

```text
No silent fallback.
No destructive write.
Every stage is resumable or safely restartable.
```

## Pass 5 — Production Readiness

בדיקת:

```text
versioning
provenance
licenses
observability
security
release
support
migration
```

תיקון עיקרי:

```text
Schema versions, model registry, artifact manifests,
retention policy, license registry and release certification
are now mandatory.
```

---

# 5. Product Principles

## Principle 1 — Evidence over Guessing

```text
Known > Unknown
Verified > Documented > Experimental
```

## Principle 2 — Model before Bytes

```text
Binary
↓
Codec
↓
Domain Model
↓
Writer
```

## Principle 3 — Unknown Data Must Survive

```text
Known → interpret
Unknown → preserve
```

## Principle 4 — Deterministic Core

אותו input/configuration/model version צריך להפיק אותו semantic artifact כאשר backend deterministic.

## Principle 5 — Hardware QA Is Separate

```text
Production != Hardware QA
```

## Principle 6 — No Silent Decisions

כל החלטה שמשנה musical semantics או resource references חייבת להיות:

```text
explicit
logged
reproducible
undoable
```

## Principle 7 — User Data Is Not Disposable

אין למחוק או להחליף User resources ללא policy מפורשת.

---

# 6. Architecture Overview

```text
                         ┌─────────────────────────────┐
                         │           WEB UI             │
                         │ Upload / Analyze / Edit      │
                         │ Review / Export / LLM        │
                         └──────────────┬──────────────┘
                                        │
                                   API Gateway
                                        │
                                   Job Service
                                        │
                                 ┌──────▼──────┐
                                 │ Orchestrator│
                                 └──────┬──────┘
                                        │
          ┌─────────────────────────────┼─────────────────────────────┐
          │                             │                             │
          ▼                             ▼                             ▼
   Korg Resource Engine          Audio Engine                  Music Engine
          │                             │                             │
          │                        Decode/Normalize              Beat
          │                        Separation                     Downbeat
          │                        Drum ADT                      Bars
          │                                                     Patterns
          │                                                     Groove
          │                                                     Structure
          └───────────────┬──────────────┬────────────────────────────┘
                          │              │
                          ▼              ▼
                    Mapping Engine   FX Estimator
                          │
                          ▼
                  Internal Style Model
                          │
                    ┌─────┴─────┐
                    ▼           ▼
              Native STY      SET Packager
                    │           │
                    └─────┬─────┘
                          ▼
                  Static Validator
                          │
                    ┌─────┴─────┐
                    ▼           ▼
                 STY/SET     Report
                          │
                          ▼
                    Hardware QA
```

LLM אינו יושב בתוך Binary Layer.

```text
User Intent
↓
LLM Planner
↓
Action Schema
↓
Permission/Domain Validator
↓
Deterministic Engine
```

---

# 7. Repository Structure

```text
m2s/
│
├── README.md
├── pyproject.toml
├── .gitignore
├── .env.example
├── LICENSE
├── THIRD_PARTY_NOTICES.md
│
├── docs/
│   ├── architecture.md
│   ├── korg-format.md
│   ├── korg-evidence.md
│   ├── smf-interoperability.md
│   ├── set-format.md
│   ├── security.md
│   ├── privacy.md
│   ├── licensing.md
│   ├── test-protocol.md
│   ├── hardware-protocol.md
│   ├── decisions.md
│   ├── evidence.md
│   ├── release-process.md
│   ├── schema-versioning.md
│   └── operations.md
│
├── src/
│   └── m2s/
│       │
│       ├── api/
│       ├── cli/
│       ├── models/
│       ├── schemas/
│       ├── versioning/
│       ├── provenance/
│       ├── security/
│       ├── jobs/
│       ├── observability/
│       │
│       ├── korg/
│       │   ├── parser/
│       │   ├── writer/
│       │   ├── profiles/
│       │   ├── validator/
│       │   ├── resource_graph/
│       │   └── evidence/
│       │
│       ├── midi/
│       │   ├── parser/
│       │   ├── writer/
│       │   ├── normalization/
│       │   └── validation/
│       │
│       ├── audio/
│       │   ├── io/
│       │   ├── normalization/
│       │   ├── separation/
│       │   ├── transcription/
│       │   ├── onset/
│       │   └── quality/
│       │
│       ├── music/
│       │   ├── time/
│       │   ├── tempo/
│       │   ├── beat/
│       │   ├── quantization/
│       │   ├── patterns/
│       │   ├── groove/
│       │   ├── structure/
│       │   └── similarity/
│       │
│       ├── mapping/
│       │
│       ├── style/
│       │   ├── compiler/
│       │   ├── templates/
│       │   └── policies/
│       │
│       ├── packaging/
│       │
│       ├── fx/
│       │
│       ├── ai/
│       │   ├── planners/
│       │   ├── registry/
│       │   └── validators/
│       │
│       └── editor/
│
├── tests/
│   ├── unit/
│   ├── integration/
│   ├── regression/
│   ├── property/
│   ├── security/
│   ├── golden/
│   ├── fixtures/
│   ├── audio/
│   └── hardware/
│
├── scripts/
│   ├── inspect_sty.py
│   ├── diff_sty.py
│   ├── inspect_set.py
│   ├── diff_set.py
│   ├── inspect_smf.py
│   ├── validate_sty.py
│   ├── validate_set.py
│   ├── validate_manifest.py
│   └── hash_resource.py
│
└── data/
    ├── raw/
    ├── extracted/
    ├── generated/
    ├── golden/
    ├── manifests/
    ├── benchmarks/
    └── qa/
```

---

# 8. Development Environment

## 8.1 Initial stack

```text
Python 3.11 / 3.12
Git
VS Code
pytest
Ruff
Pydantic
NumPy
SciPy
Mido
librosa
FFmpeg
```

## 8.2 AI stack

לא להתקין עד P2.

ה־AI backend חייב להיות adapter.

## 8.3 Environment Lock

Production חייב להשתמש ב:

```text
pyproject.toml
lock file
Python version
OS/container version
model manifest
```

כל Release מקבל environment fingerprint.

---

# 9. Coding Standards

חובה:

```text
type hints
docstrings for public APIs
structured logging
exceptions with domain-specific error types
tests for public behavior
```

禁止:

```text
print() במקום logging
silent except
bare except
global mutable state
magic constants
undocumented binary offsets
```

---

# 10. Versioning

שלוש שכבות:

```text
Application Version
Internal Schema Version
Korg Profile Version
```

לדוגמה:

```text
M2S = 2.0.0
Schema = 1.4
Profile = Pa600-2.1.1
```

## 10.1 Schema compatibility

Reader רשאי לקרוא:

```text
same major
supported minor range
```

Writer חייב לכתוב:

```text
current schema
```

Migration functions:

```python
migrate_schema_v1_to_v2(...)
```

---

# 11. Formal Input Contract

## 11.1 Audio

Supported baseline:

```text
WAV
FLAC
MP3
```

Input checks:

```text
file size
decode success
sample rate
channel count
duration
clipping
silence
```

## 11.2 MIDI

Accept:

```text
SMF Format 0
SMF Format 1
```

Internal representation is normalized to one canonical model.

## 11.3 SET

Accept only:

```text
Pa600-compatible SET structure
```

or report:

```text
UNSUPPORTED
PARTIAL
CORRUPTED
```

---

# 12. Formal Output Contract

Every successful build produces:

```text
artifact/
├── style.sty
├── report.json
├── manifest.json
└── diagnostics/
```

Optional:

```text
style.mid
style.set/
preview.wav
mapping.csv
```

The output is not published unless all required validators pass.

---

# 13. Job State Machine

```text
CREATED
↓
UPLOADING
↓
VALIDATING_INPUT
↓
PARSING_SET
↓
ANALYZING_SOURCE
↓
EXTRACTING_STRUCTURE
↓
MAPPING
↓
COMPILING
↓
PACKAGING
↓
STATIC_VALIDATION
↓
READY
```

Terminal states:

```text
COMPLETED
FAILED
CANCELLED
REVIEW_REQUIRED
UNSUPPORTED
```

No stage can silently jump over a required blocking validator.

---

# 14. Stage Contract

כל Stage מחזיר:

```python
StageResult(
    status,
    artifacts,
    warnings,
    errors,
    metrics,
    provenance,
    next_actions
)
```

Status:

```text
PASS
PASS_WITH_WARNINGS
REVIEW_REQUIRED
FAIL
UNSUPPORTED
```

---

# 15. Artifact Dependency Graph

דוגמה:

```text
source_audio
     │
     ▼
normalized_audio
     │
     ▼
drum_stem
     │
     ▼
raw_events
     │
     ▼
canonical_patterns
     │
     ▼
style_model
     │
     ├─────────────► diagnostic_mid
     │
     ▼
sty
     │
     ▼
set
```

אם artifact parent משתנה:

```text
invalidate descendants
```

אין להשתמש ב־artifact ישן לאחר שינוי source/config בלי validation מחדש.

---

# 16. Caching

Cache key:

```text
SHA256(
    input hashes
    + stage version
    + config hash
    + model hash
    + schema version
    + profile version
)
```

אסור:

```text
cache by filename only
```

---

# 17. Provenance

כל artifact יכיל:

```json
{
  "artifact_id": "...",
  "parent_ids": [],
  "input_sha256": [],
  "engine_version": "...",
  "schema_version": "...",
  "profile": "Pa600-2.1.1",
  "backend": "...",
  "backend_version": "...",
  "model_hash": "...",
  "configuration_hash": "...",
  "seed": 1234,
  "created_at": "..."
}
```

---

# 18. Security

## 18.1 File ingestion

חובה:

```text
path traversal protection
symlink rejection
archive bomb limits
maximum file count
maximum extraction bytes
maximum filename length
extension validation
magic-byte validation where applicable
temporary workspace isolation
atomic publish
```

## 18.2 Parser safety

Parser לא יקצה memory על סמך field לא־מאומת בלי upper bound.

כל parser חייב לטפל ב:

```text
EOF
truncated header
malformed length
integer overflow
invalid offset
recursive references
duplicate IDs
unknown chunks
```

## 18.3 No destructive operations

אין:

```text
overwrite source
delete user SET
replace user slot without policy
```

---

# 19. Privacy / Data Retention

ל־web deployment יש policy מפורשת:

```text
upload
processing
artifact retention
automatic deletion
user deletion
backup deletion
```

ברירת מחדל מומלצת:

```text
Raw user audio/SET → temporary retention only
Generated artifacts → user-controlled retention
Diagnostics → minimal retention
```

אם יש cloud LLM:

```text
explicit opt-in
provider disclosure
data handling policy
```

---

# 20. Licensing / Third-Party Models

כל backend מקבל record:

```text
name
version
license
source URL
model license
redistribution policy
commercial-use status
notice requirement
```

קובץ:

```text
THIRD_PARTY_NOTICES.md
```

אין לשלב מודל או library ב־production בלי בדיקת רישיון.

---

# 21. P0 — Korg Reverse Engineering

## P0 Objective

להוכיח:

```text
Can M2S safely inspect real Pa600 resources?
```

ולא:

```text
Can AI guess what bytes mean?
```

---

# 22. Golden Corpus Policy

הקורפוס צריך להכיל, ככל שאפשר:

```text
Real STY
Matching SET
Pa600-exported SMF
OS version
device variant
```

Categories:

```text
A — Drum-centered
B — Multi-track
C — Multi-CV
D — Performance/FX
E — Custom PCM
F — unusual lengths/meters
G — empty/minimal
H — user-edited
```

אין להשתמש בקובצי Korg/third-party שאין זכויות לשמור ולהפיץ כ־test assets.

לכל fixture:

```text
fixture_id
source
license/permission
sha256
device
os
notes
expected capabilities
```

---

# 23. Variable Isolation Protocol

כל ניסוי:

```text
Original A
↓
One change
↓
Modified B
↓
Binary diff
↓
Semantic diff
↓
Hardware observation where required
```

דוגמאות:

```text
one note
one velocity
one tempo
one track volume
one program
one CC
one element
one CV
one FX parameter
one PCM resource
```

---

# 24. Evidence Registry

קובץ:

```text
docs/evidence.md
```

Record:

```yaml
id: E-0001
claim: "Field X represents tempo"
source:
  - fixture: style_001
  - experiment: exp_004
status: EXPERIMENTAL
confidence: low
write_policy: PRESERVE_ONLY
next_test: "Change tempo only"
```

כאשר הוכח:

```text
status: VERIFIED
```

---

# 25. Binary Diff Tooling

`diff_sty.py` חייב להציג:

```text
offset
before
after
width
candidate field
confidence
```

ולא רק:

```text
0x0034 differs
```

בשלב ראשון אין parser interpretation אוטומטי בלי evidence.

---

# 26. STY Parser Architecture

```text
File bytes
↓
Reader
↓
Container/chunk detection
↓
Known-field decoder
↓
Unknown-region collector
↓
Semantic model
↓
Validation
```

API:

```python
parse_sty(path) -> StyleDocument
```

---

# 27. Unknown Data Preservation

Model:

```python
UnknownRegion(
    offset=...,
    length=...,
    raw_bytes=...,
    parent_context=...,
    evidence_level="EXPERIMENTAL",
)
```

Rule:

```text
Known → decode
Unknown → preserve
Unverified → preserve-only
```

Writer אינו רשאי “לנקות” unknown bytes.

---

# 28. Reader / Writer Modes

## Read-only

```text
parse
inspect
diff
validate
```

## Safe Writer

כותב רק fields עם:

```text
write_policy = VERIFIED_WRITE
```

## Experimental Writer

אסור לשימוש production.

רק:

```text
research
fixtures
developer mode
```

---

# 29. Korg Profile

```python
class Pa600Profile:
    device = "Korg Pa600"
    variant = "Standard"
    os = "2.1.1"
```

Profile includes:

```text
style elements
CV limits
style track roles
style SMF channel mapping
SMF rules
marker rules
style settings rules
resource folders
PCM capability
FX capability
NTT capability
version notes
```

---

# 30. Style Structure

Pa600 documentation identifies:

```text
3 Intros
4 Variations
4 Fills
1 Break
3 Endings
```

Style track structure:

```text
8 Style Tracks
```

Chord Variation structure:

```text
Variation → up to 6 CV
Other Style Elements → up to 2 CV
```

Total:

```text
46 patterns / CV instances
```

Implementation must derive exact usable limits from the active Profile and never use a global “6 CV” constant for all elements.

---

# 31. Style Pattern vs Style Performance

Internal model:

```text
StyleDocument
├── PatternData
├── StylePerformance
├── ResourceReferences
├── UnknownData
└── Provenance
```

## PatternData

```text
Style Elements
CVs
Tracks
events
pattern length
track length
header data
```

## StylePerformance

```text
tempo
track settings
volume
pan
EQ
FX
wrap-around
mute/control settings
other verified performance settings
```

The exact field list is Profile-specific.

---

# 32. Chord Variation Model

```python
ChordVariation(
    element_type,
    element_index,
    cv_index,
    cv_length,
    track_patterns,
    header,
    unknown_data
)
```

Must preserve:

```text
CV length
Track pattern length
```

as different concepts.

---

# 33. Track Pattern Model

```python
TrackPattern(
    role,
    midi_channel,
    events,
    loop_length,
    source_length,
    playback_policy
)
```

For MVP:

```text
DRUM
PERCUSSION
```

But model has room for:

```text
BASS
ACC1
ACC2
ACC3
ACC4
ACC5
```

---

# 34. MIDI Canonical Model

Source of truth:

```text
absolute_tick
```

Events:

```text
NoteOn
NoteOff
CC
ProgramChange
PitchBend
Aftertouch where relevant
Meta
SysEx
```

Not every event is guaranteed to be valid for every Korg Style context.

---

# 35. MIDI Time Representation

Never use floating seconds as canonical music position.

Canonical:

```text
integer ticks
+
tempo map
+
time signature map
```

Audio path is converted into:

```text
beat position
```

only after tempo/beat estimation.

Seconds are retained as evidence metadata:

```text
onset_sec
```

---

# 36. MIDI Serialization

```text
absolute events
↓
deterministic ordering
↓
delta-time conversion
↓
SMF encoding
```

Ordering tie-breaker must be deterministic.

Example policy:

```text
Meta
Program/Bank
CC
NoteOff
NoteOn
```

The actual ordering must be validated against the target interoperability requirement; do not assume that all orderings are semantically equivalent.

---

# 37. SMF Interoperability Layer

Important:

```text
SMF != STY
```

SMF is an interoperability/debugging representation.

Pa600 Style import uses:

```text
SMF Format 0
```

and Korg documents marker-based Style/CV organization.

Marker policy must be encoded by Profile, not as scattered constants.

Known examples include forms such as:

```text
v1cv1
i1cv1
f1cv1
e1cv1
```

and Break markers must be verified against the exact Profile corpus.

SMF export is therefore:

```text
interoperability probe
+
musical inspection tool
```

not a full substitute for binary STY understanding.

---

# 38. SMF Import/Export Test

Every supported marker must have:

```text
valid fixture
invalid fixture
parser test
writer test
hardware import test where required
```

Invalid:

```text
capital letters
extra suffix
wrong numbering
unsupported element
unsupported CV
```

must produce a clear validation error.

---

# 39. Hardware Echo Test

Strongest interoperability test:

```text
M2S generated STY
↓
Pa600 load
↓
save/export
↓
retrieve resulting artifact
↓
parse
↓
compare semantic model
```

This detects:

```text
firmware canonicalization
lost fields
unsupported fields
unexpected normalization
```

Byte-for-byte equality is not required.

Semantic equality is.

---

# 40. KMP / KSF Resource Strategy

M2S treats:

```text
KMP
KSF
Sound
DrumKit
PCM
```

as resources with references.

Do not assume exact binary layout without evidence.

Semantic layer:

```text
sample identity
sample format
mapping
zones
velocity behavior
loop metadata
```

Binary layer:

```text
preserve / parse / write according to evidence
```

---

# 41. KSF Model

```python
SampleResource(
    id=...,
    original_ksf_ref=...,
    raw_bytes=...,
    sample_rate=...,
    bit_depth=...,
    channels=...,
    loop_start=...,
    loop_end=...,
    normalized_audio_ref=...,
)
```

Never discard original KSF.

Normalized WAV is derived data only.

---

# 42. Resource Identity

Resource identity ≠ slot.

Example:

```text
Resource ID = logical identity
Slot = current placement
Content Hash = content identity
Reference = relationship
```

This distinction is mandatory for SET remapping.

---

# 43. SET Resource Graph

```text
SET
├── STYLE
├── SOUND
├── PAD
├── PERFORM
├── SONGBOOK
├── PCM
└── GLOBAL
```

The graph stores:

```text
resource
reference
slot
path
dependency
owner
content hash
```

---

# 44. SET Parser

Output:

```python
SetDocument(
    root,
    resources,
    dependency_graph,
    unknown_files,
    warnings,
    provenance
)
```

Parser must be able to identify:

```text
valid
partial
corrupted
unsupported
```

without silently repairing.

---

# 45. SET Repair vs SET Interpretation

These are different operations.

```text
Interpret:
read exactly what exists
```

```text
Repair:
modify input
```

MVP does not auto-repair user SET.

A future `repair-set` command must:

```text
create copy
produce diff
record every modification
```

---

# 46. P1 — Native Writer

Writer pipeline:

```text
Internal Style Model
↓
Profile validation
↓
Field serialization
↓
Unknown-region placement
↓
Length/reference rebuild where verified
↓
Container assembly
↓
Static validation
↓
Output
```

---

# 47. Template/Patch Bootstrap

Early POC may use:

```text
known-good STY
↓
targeted field patch
↓
parse
↓
validate
```

But only when:

```text
field write policy = VERIFIED_WRITE
```

It must never evolve into:

```text
unknown bytes guessing engine
```

---

# 48. Native Writer Safety Rules

Writer MUST fail instead of producing:

```text
invalid pointer
invalid length
unresolved resource
unsupported required field
```

Output:

```text
FAIL
```

not:

```text
best effort artifact
```

unless user explicitly requested research mode.

---

# 49. Semantic Round Trip

```text
STY A
↓
Parser
↓
Model A
↓
Writer
↓
STY B
↓
Parser
↓
Model B
```

Compare:

```text
semantic(Model A)
==
semantic(Model B)
```

Also compare:

```text
preserved unknown regions
```

where appropriate.

---

# 50. Canonical Semantic Comparison

Comparison ignores:

```text
byte offsets that may legally move
non-semantic padding
verified writer normalization
```

Comparison MUST NOT ignore:

```text
notes
velocity
timing
length
track identity
CV identity
resource references
style settings
verified performance data
```

---

# 51. P1 Hardware QA

Minimum certification:

```text
Load
Select Style
Variation 1
Variation 2
Intro 1
Fill 1
Ending 1
Tempo
Drums
Percussion
Save
Reload
```

Extended certification:

```text
Variation 3
Variation 4
Fill 2–4
Break
Intro 2–3
Ending 2–3
```

---

# 52. Hardware QA Environment

Do not test destructive SET loads on irreplaceable user memory.

Prepare:

```text
QA Pa600
documented OS
backup
known reset/recovery procedure
known test card/USB
operator checklist
recording method
```

Each test records:

```text
test_id
input_hash
output_hash
profile
OS
date
operator
steps
observations
pass/fail
```

---

# 53. P2 — MIDI Path

MIDI should be the first end-to-end music path because it removes AI uncertainty.

```text
MIDI
↓
SMF parser
↓
Canonical MIDI
↓
Track classification
↓
Beat/Bar normalization
↓
Pattern model
```

This should be implemented before relying on Audio → ADT.

---

# 54. MIDI Track Role Classification

For a source MIDI:

```text
Track metadata
+
channel
+
program
+
note distribution
+
drum channel conventions
+
human override
```

produce:

```text
DRUM
PERCUSSION
BASS
KEYBOARD
GUITAR
BRASS
OTHER
```

MVP consumes:

```text
DRUM
PERCUSSION
```

---

# 55. MIDI Input Quality

Detect:

```text
format
PPQN
tempo map
time signature map
empty tracks
duplicate notes
note overlaps
invalid velocities
```

Do not silently quantize source MIDI before saving the original normalized event model.

---

# 56. P2 — Audio Path

```text
Audio
↓
Decode
↓
Validation
↓
Normalization
↓
Source Separation
↓
Drum Stem
↓
ADT
↓
Raw Drum Events
```

---

# 57. Source Separation Interface

```python
class ISourceSeparator:
    def separate(
        self,
        audio_path,
        output_dir,
        config
    ) -> SeparationResult:
        ...
```

Backend abstraction is mandatory.

No hard coupling to one model.

---

# 58. Separation Backend Registry

Each backend record:

```text
backend_id
version
model_id
model_hash
license
supported_platforms
input requirements
output stem names
quality benchmark
```

Demucs may be retained as an adapter/baseline, but it is not an architectural dependency.

---

# 59. Audio Normalization

Preserve original.

Create derived:

```text
analysis_audio.wav
```

Metadata:

```text
original_sample_rate
target_sample_rate
channels
gain policy
peak
duration
```

Do not destructively normalize the source.

---

# 60. Drum Stem Quality

Check:

```text
clipping
silence
RMS / loudness range
duration mismatch
channel mismatch
separation confidence
```

If below calibrated quality threshold:

```text
REVIEW_REQUIRED
```

Do not fabricate certainty.

---

# 61. Drum ADT Interface

```python
class IDrumTranscriber:
    def transcribe(
        self,
        drum_stem_path,
        config
    ) -> DrumTranscriptionResult:
        ...
```

Baseline backend may use Omnizart.

Backend is accepted only after evaluation on project corpus.

---

# 62. Raw Drum Event Model

```python
RawDrumEvent(
    id,
    onset_sec,
    instrument,
    velocity,
    raw_score,
    calibrated_confidence,
    source_frame,
    source_bar=None,
    source_beat=None
)
```

MVP semantic classes:

```text
KICK
SNARE_HEAD
SNARE_RIM
HH_CLOSED
HH_OPEN
TOM_LOW
TOM_MID
TOM_HIGH
CRASH
RIDE
RIDE_BELL
CLAP
PERCUSSION
OTHER
```

---

# 63. Event De-duplication

ADT may generate duplicate close events.

Rule must be configurable:

```text
instrument
minimum onset separation
confidence
velocity merge policy
```

Never merge two events solely because they are close in time.

---

# 64. Velocity Model

Velocity is semantic dynamic information.

Internal domain:

```text
source_velocity
normalized_velocity
target_velocity
velocity_curve_id
```

Mapping must preserve expressive contour.

---

# 65. Confidence Propagation

Confidence flow:

```text
Event confidence
↓
Pattern confidence
↓
Structure confidence
↓
Mapping confidence
↓
Artifact readiness
```

One global confidence number is insufficient.

---

# 66. P3 — Tempo and Time

## Tempo

Detect:

```text
BPM
confidence
half/double-time alternatives
tempo changes
```

## Time Signature

Detect:

```text
meter
confidence
change points
```

## Downbeat

```text
beat
↓
downbeat
↓
bar
```

---

# 67. Time Ambiguity Resolver

Handle:

```text
90 BPM vs 180 BPM
3/4 vs 6/8
pickup bar
late downbeat
syncopated groove
swing
```

The system may preserve multiple candidates:

```text
TempoHypothesis[]
```

and select only after scoring against musical consistency.

---

# 68. Pickup / Anacrusis

A song can start before bar 1.

Model:

```text
pickup_length
bar_zero_offset
```

Never force first detected onset to beat 1.

---

# 69. Tempo Changes

For Audio:

```text
piecewise tempo map
```

For MIDI:

```text
read existing tempo events
```

When compiling a Korg Style, the system must distinguish:

```text
reference-song tempo map
```

from:

```text
style default tempo
```

Default style tempo can be configurable independently.

---

# 70. P3 — Canonical Pattern

Raw timing is normalized into:

```text
bar-relative beat positions
+
subdivision
+
instrument class
+
dynamic envelope
```

Canonical Pattern does NOT contain:

```text
Korg note
Korg sample
SET slot
```

---

# 71. Pattern Identity vs Groove

Pattern identity:

```text
what is played
```

Groove:

```text
how it is timed and dynamically shaped
```

Separate:

```text
PatternIdentity
GrooveTemplate
```

---

# 72. Groove Representation

Prefer normalized values:

```text
beat fraction offset
subdivision phase
velocity bias
```

rather than permanently storing:

```text
+17 ms
```

because BPM changes.

---

# 73. Swing

Swing can be represented as:

```text
ratio
target subdivision
confidence
```

Example:

```text
8th-note swing ratio
```

is different from:

```text
16th-note swing ratio
```

Do not use one global swing number.

---

# 74. Quantization Policy

Quantization modes:

```text
NONE
ADAPTIVE
GRID
MANUAL
```

Grid candidates:

```text
1/4
1/8
1/16
triplet
custom
```

Never destroy original timing; quantized timing is derived.

---

# 75. Humanization

Humanization is optional.

Represent separately:

```text
humanization_amount
timing_distribution
velocity_distribution
seed
```

Core output must be deterministic.

---

# 76. Pattern Fingerprint

Minimum:

```text
kick positions
snare positions
hat positions
other percussion positions
velocity histogram
density
syncopation
accent structure
bar-ending activity
silence windows
```

---

# 77. Pattern Similarity

Weighted distance:

```text
position
instrument
density
accent
velocity structure
syncopation
```

Microtiming has lower weight than structural identity.

Weights are versioned configuration.

---

# 78. Pattern Clustering

Pipeline:

```text
bars
↓
fingerprints
↓
similarity matrix
↓
clusters
↓
stable representatives
```

Cluster count is not fixed to four merely because Pa600 has four Variations.

First discover musical groups.

Then assign selected clusters to Style Elements.

---

# 79. Variation Assignment

Candidate score:

```text
stability
musicality
density
uniqueness
coverage
confidence
```

No global “best style” ranking.

The purpose is structural assignment:

```text
Var1
Var2
Var3
Var4
```

---

# 80. Fill Detection

Fill score:

```text
structural_change
density_change
instrument_change
boundary_activity
last_beat_activity
local_context
```

A fill candidate must also satisfy:

```text
position at phrase boundary
```

unless explicitly overridden.

---

# 81. Intro / Ending Detection

Each result:

```text
DETECTED
DERIVED
SYNTHESIZED
USER_CREATED
```

The UI must expose the origin.

Never claim:

```text
"Original Intro recovered"
```

when it was derived.

---

# 82. Repetition and Coverage

The engine must avoid choosing one bar and calling it the whole Style.

It should report:

```text
covered source duration
covered bars
uncovered bars
ambiguous bars
discarded bars
```

---

# 83. Structural Review UI

Before compiling:

```text
Source timeline
├── Intro candidate
├── Variation candidates
├── Fill candidates
├── Ending candidate
└── Unassigned
```

User can reassign bars.

---

# 84. P4 — Semantic Remapping

Internal note taxonomy:

```text
KICK
SNARE
HAT
TOM
CYMBAL
RIDE
PERCUSSION
```

Then resolve against:

```text
user DrumKit
user Sound
target Profile
```

---

# 85. Drum Sample Classification

Each candidate:

```text
sample_id
semantic_role
confidence
evidence
user_override
```

---

# 86. Human Review

Display:

```text
Detected Role
Sample
Confidence
Candidate Target
```

Actions:

```text
accept
change role
choose target
mute
exclude
```

---

# 87. Resolver

```text
Semantic Role
↓
Compatible DrumKit / Sound
↓
Available Key
↓
Target Note
↓
Velocity policy
```

---

# 88. Velocity Layers

The model stores:

```text
Predicted target layer
```

only as analysis/UI metadata.

The MIDI representation stores:

```text
target_note
velocity
```

The DrumKit is responsible for runtime Velocity behavior.

---

# 89. Mapping Fallback

Strict order:

```text
1. Exact semantic match
2. Profile-approved compatible match
3. User-selected target
4. Mute + warning
```

No arbitrary mapping.

---

# 90. Example

```text
RIDE_BELL
↓
exact target exists
→ use
```

If absent:

```text
compatible candidate?
→ show user
```

If user declines:

```text
mute + warning
```

---

# 91. Korg-specific Drum Controls

Features such as:

```text
Snare Designation
Kick Designation
Drum Mapping
```

are represented as control/semantic settings where verified.

They are not confused with the note-to-sample mapping table.

---

# 92. P5 — Native Style Compiler

Inputs:

```text
Pattern Model
Groove Model
Structure
Target Mapping
User SET References
Profile
```

Output:

```text
InternalStyleModel
```

before bytes are produced.

---

# 93. Compiler Pipeline

```text
Source musical model
↓
Structural selection
↓
Element/CV assignment
↓
Track assignment
↓
Korg-specific controls
↓
Resource references
↓
Performance settings
↓
Binary writer
```

---

# 94. No Raw Byte Editing From User/LLM

Editor and LLM can only change:

```text
Domain Model
```

Binary is generated later.

---

# 95. Static Validator

Must check:

```text
profile
structure
fields
ranges
lengths
pointers
references
tracks
events
CVs
style settings
resource graph
unknown regions
```

---

# 96. Range Validation

At minimum:

```text
MIDI note: 0–127
velocity: 1–127
CC: 0–127
program: valid MIDI range
non-negative lengths
valid tick positions
```

Profile-specific constraints override generic MIDI constraints.

---

# 97. Orphan Detection

Find:

```text
orphan resource
dangling reference
duplicate slot
duplicate logical identity with collision
missing dependency
circular dependency where unsupported
```

---

# 98. Output Modes

## Production

Only:

```text
VERIFIED_WRITE
```

## Research

May include:

```text
EXPERIMENTAL
```

but every artifact must be visibly marked:

```text
RESEARCH_ONLY
```

and cannot be exported as production-certified output.

---

# 99. Diagnostic MIDI

Produce an optional MIDI version for:

```text
timeline inspection
pattern listening
manual edit
debugging
```

This file must include:

```text
M2S markers
source mapping metadata
target track names where appropriate
```

but does not claim to reproduce all STY semantics.

---

# 100. P6 — SET Packager

The packager operates on:

```text
Resource Graph
```

not on flat files.

---

# 101. Resource Graph Example

```text
Generated Style
│
├── Drum Track
│    └── DrumKit Ref
│         └── PCM/Sample resources
│
└── Optional accompaniment tracks
     └── Sound refs
           └── Multisample refs
                └── KMP/KSF
```

---

# 102. Slot Allocation

When resource exists and is compatible:

```text
REUSE
```

When absent:

```text
ALLOCATE_NEW
```

When conflict:

```text
MANUAL_REVIEW
```

Default is never to overwrite an unrelated user resource.

---

# 103. Slot Mapping Table

Before writing SET:

```text
logical_resource
old_slot
new_slot
content_hash
references_changed
```

must be generated.

---

# 104. Collision Policies

Supported:

```text
reuse
allocate-new
replace
skip
manual-review
```

Production default:

```text
reuse
allocate-new
manual-review
```

`replace` requires explicit user policy.

---

# 105. Canonical Hashing

Domains:

```text
SampleContentHash
MultisampleHash
SoundDefinitionHash
DrumKitDefinitionHash
StylePatternHash
StylePerformanceHash
```

Do not hash filenames as identity.

---

# 106. Sample Hash Normalization

Sample content hash policy must document:

```text
raw bytes or canonical decoded PCM
endianness
metadata inclusion
loop metadata inclusion
channel order
```

These are different hashes for different purposes.

---

# 107. Minimal SET

Default export:

```text
Minimal SET
```

contains only proven dependencies.

Advantages:

```text
less collision risk
smaller artifact
easier QA
```

---

# 108. Complete SET

Optional.

Requires:

```text
explicit packaging scope
dependency scan
slot allocation
conflict report
```

No unrelated user resource should be silently replaced.

---

# 109. SET Integrity Test

Before export:

```text
all required refs resolved
all slots legal
all folder structure legal
all required files present
no unexpected overwrite
```

---

# 110. Clean-Environment Test

```text
Generated SET
↓
source SET removed
↓
temporary workspace removed
↓
load on clean QA setup
```

The generated package must not rely on hidden local resources.

---

# 111. P7 — Web Backend

```text
Client
↓
FastAPI
↓
Job Service
↓
Queue
↓
Worker
↓
M2S Engine
```

Heavy processing is not performed as a giant blocking web request.

---

# 112. Worker Architecture

Workers can be specialized:

```text
CPU worker
GPU worker
Packaging worker
Validation worker
```

Queue is abstract.

Possible implementations:

```text
Celery
RQ
Arq
equivalent
```

Choice is deployment-dependent.

---

# 113. Job Idempotency

Each stage gets:

```text
job_id
stage_id
input_hash
config_hash
```

Retry must not:

```text
duplicate resources
double-apply changes
overwrite artifacts
```

---

# 114. Progress Reporting

Example:

```json
{
  "stage": "transcription",
  "progress": 62,
  "status": "processing"
}
```

Progress must describe real work where measurable.

Do not show fake percentage.

---

# 115. Cancellation

User can:

```text
cancel job
```

Cancellation must:

```text
stop future stages
cleanup temp files
preserve immutable logs
mark artifacts incomplete
```

---

# 116. Resume

A failed job can resume from the last valid immutable artifact when:

```text
input hash unchanged
configuration hash unchanged
engine version compatible
schema compatible
```

Otherwise re-run from invalidated parent.

---

# 117. Web UI — First Version

Use:

```text
Streamlit or Gradio
```

screen:

```text
[Upload SET]
[Upload Song]

[Analyze]

Stage:
███████░░░ 70%

Preview
Warnings
Mapping Review

[Download STY]
[Download Minimal SET]
```

---

# 118. Final UI — Later

```text
React
+
FastAPI
```

Views:

```text
Upload
Analysis
Structure
Pattern Editor
Mapping
Style Editor
Validation
Export
Chat/LLM
```

---

# 119. Music Editor

The editor works on:

```text
Internal Music Model
Internal Style Model
```

Never on raw bytes.

---

# 120. Editor Functions

```text
move note
delete note
add note
change velocity
change grid
change swing
copy bar
duplicate pattern
change element
change CV
split pattern
merge pattern
mute event
change mapping
```

---

# 121. Structure Editor

Example:

```text
Bars 1–4    → Intro 1
Bars 5–8    → Variation 1
Bars 9–12   → Variation 2
Bars 13–14  → Fill 1
Bars 15–22  → Variation 1
Bars 23–24  → Ending 1
```

---

# 122. Undo / Redo

Every user edit produces:

```text
operation_id
parent_model_hash
new_model_hash
inverse operation
timestamp
```

Undo should operate on semantic operations.

---

# 123. P9 — LLM

LLM is optional.

The deterministic engine must operate without it.

LLM responsibilities:

```text
interpret user intent
plan valid domain actions
explain warnings
suggest edits
```

LLM must NOT:

```text
write STY bytes
write SET bytes
invent undocumented Korg structures
```

---

# 124. Action Registry

Example:

```text
modify_velocity
move_note
delete_note
add_note
quantize
set_swing
change_element
change_cv
regenerate_fill
set_tempo
change_mapping
```

---

# 125. LLM Action Schema

```json
{
  "schema_version": "1",
  "action": "modify_velocity",
  "target": {
    "instrument": "SNARE_HEAD",
    "element": "Fill1"
  },
  "parameters": {
    "mode": "relative",
    "amount": 0.15
  }
}
```

---

# 126. LLM Validation

```text
Natural language
↓
LLM
↓
JSON Schema
↓
Action Registry
↓
Permission Check
↓
Domain Validation
↓
Deterministic Engine
↓
Post-validation
```

Any invalid action:

```text
REJECT
```

No fuzzy execution.

---

# 127. LLM Security

Never include unnecessary user files in the LLM prompt.

Do not allow prompt text to control:

```text
filesystem paths
shell commands
binary offsets
worker commands
```

LLM receives semantic context only.

---

# 128. LLM Determinism

Where reproducibility matters:

```text
model ID
provider
temperature policy
system prompt version
tool schema version
input context hash
```

are recorded.

---

# 129. Idempotent Editing

Represent:

```text
base value
desired modification
```

rather than repeatedly mutating the already-rendered result.

Example:

```text
base_velocity = 90
modifier = +15%
```

---

# 130. P10 — FX

Phase 2.

Pipeline:

```text
Reference Mix
+
Drum Stem
↓
FX Estimator
↓
Abstract FX Profile
↓
Korg-compatible renderer
↓
Style Performance / FX data
```

FX is:

```text
Estimated
```

unless explicitly verified.

---

# 131. FX Non-Goal

Do not claim:

```text
exact original DSP chain reconstruction
```

from a finished mix unless evidence supports it.

---

# 132. Third-Party AI Backends

## Omnizart

Possible baseline for:

```text
drum transcription
beat transcription
```

but it is not considered certified until benchmarked in the M2S environment.

## Basic Pitch

Possible adapter for:

```text
pitched/melodic transcription
```

not default Drum ADT.

## Demucs

Possible legacy/baseline separator adapter.

The original `facebookresearch/demucs` repository is archived, so it is not treated as a permanent dependency.

---

# 133. Model Registry

Every AI model has:

```text
model_id
version
weights_hash
backend_version
license
input preprocessing
output schema
benchmark
known limitations
```

---

# 134. Benchmark Protocol

No model is promoted from:

```text
EXPERIMENTAL
```

to:

```text
APPROVED
```

without:

```text
reproducible benchmark
golden dataset
metrics
failure analysis
license review
environment test
```

---

# 135. Test Pyramid

```text
                    Hardware QA
                 ───────────────
                  Integration
             ─────────────────────
                Regression/Golden
           ─────────────────────────
               Property/Fuzz
         ─────────────────────────────
                    Unit
```

---

# 136. Unit Tests

Examples:

```text
parse_varlen
serialize_varlen
parse_note
normalize_velocity
quantize_position
hash_sample
resolve_mapping
validate_range
```

---

# 137. Integration Tests

Examples:

```text
KSF → Sample Model
KMP → Multisample Model
SET → Resource Graph
SMF → MIDI Model
STY → Style Model
Style Model → STY
```

---

# 138. Golden Regression

Every known-good fixture:

```text
parse
validate
semantic snapshot compare
```

Unexpected semantic delta blocks merge.

---

# 139. Round-Trip Tests

```text
parse
→ write
→ parse
→ compare
```

Required for every supported writer feature.

---

# 140. Fuzz / Property Tests

Test:

```text
truncated input
invalid offset
invalid length
unknown data
malformed varlen
extreme event count
duplicate references
random byte mutation
```

Acceptance:

```text
No crash
No memory abuse
No silent destructive output
```

---

# 141. Security Tests

Test:

```text
path traversal
symlinks
archive bombs
oversized input
zip slip
malicious filename
invalid UTF-8
resource exhaustion
```

---

# 142. Audio Tests

Test:

```text
silence
mono
stereo
clipped
very short
very long
tempo changes
swing
triplets
dense drums
sparse drums
electronic drums
acoustic drums
```

---

# 143. MIDI Tests

Test:

```text
Format 0
Format 1
multiple tempo events
time signatures
empty tracks
drum channel
overlapping notes
CC11
CC0/32
Program Change
SysEx
```

---

# 144. Hardware Certification Levels

## H0

```text
Load
```

## H1

```text
Load + basic playback
```

## H2

```text
All MVP Style Elements
```

## H3

```text
Save + Reload + Echo Test
```

## H4

```text
Minimal SET clean environment
```

Release certification requires defined H-level per feature.

---

# 145. Hardware Evidence

Hardware evidence must include:

```text
photo/video where useful
OS version
fixture hash
artifact hash
test sequence
result
```

A verbal “it loaded” is insufficient certification evidence.

---

# 146. Quality Metrics — Audio

```text
Precision
Recall
F1
Onset Error
Velocity MAE
False Positive Rate
Calibration Error
```

Report per-class metrics:

```text
Kick
Snare
HH
Tom
Cymbal
Percussion
```

not only one aggregate number.

---

# 147. Quality Metrics — Structure

```text
BPM error
beat accuracy
downbeat accuracy
bar boundary accuracy
pattern cluster purity / NMI or equivalent
fill detection precision/recall
coverage
```

---

# 148. Quality Metrics — Korg

```text
parse success
semantic round-trip success
hardware load success
hardware playback success
save/reload success
dependency integrity
```

---

# 149. Acceptance Threshold Policy

Do not invent numeric thresholds without corpus evidence.

Before Release Candidate:

```text
measure baseline
define target
freeze threshold
record threshold in release manifest
```

Threshold changes require:

```text
decision log
benchmark rerun
release note
```

---

# 150. Error Model

Domain error classes:

```text
InputError
FormatError
UnsupportedProfileError
EvidenceError
ModelError
MappingError
ResourceConflictError
SerializationError
ValidationError
HardwareValidationError
SecurityError
LicenseError
CancelledError
```

---

# 151. Error Severity

```text
BLOCKING
WARNING
INFO
```

Blocking error examples:

```text
unresolved required reference
invalid STY structure
unsupported target profile
corrupted source
unverified required binary field
```

---

# 152. Warning Examples

```text
derived intro
derived ending
low-confidence snare
unsupported optional FX
experimental transcription backend
```

Warnings must not be hidden.

---

# 153. Report Contract

```json
{
  "job_id": "...",
  "status": "PASS_WITH_WARNINGS",
  "profile": "Pa600-2.1.1",
  "artifacts": [],
  "warnings": [],
  "errors": [],
  "metrics": {},
  "provenance": {},
  "hardware": {
    "status": "NOT_RUN"
  }
}
```

---

# 154. User-facing Quality States

Show:

```text
READY
READY WITH WARNINGS
REVIEW REQUIRED
FAILED
UNSUPPORTED
```

Never:

```text
AI certainty 97%
```

without explaining what the confidence means.

---

# 155. CLI

Initial commands:

```bash
m2s inspect-sty file.sty
m2s inspect-set file.set
m2s inspect-smf file.mid
m2s diff-sty a.sty b.sty
m2s diff-set a.set b.set
m2s validate-sty file.sty
m2s validate-set file.set
m2s build-sty config.json
m2s build-set config.json
m2s report job.json
```

---

# 156. CLI Exit Codes

```text
0 = PASS
1 = FAIL
2 = USAGE ERROR
3 = UNSUPPORTED
4 = REVIEW REQUIRED
5 = SECURITY BLOCK
```

---

# 157. Logging

Structured logs:

```json
{
  "timestamp": "...",
  "job_id": "...",
  "stage": "...",
  "event": "...",
  "severity": "INFO"
}
```

Do not log:

```text
user secrets
credentials
full copyrighted audio
unnecessary personal data
```

---

# 158. Observability

Production tracks:

```text
job duration
stage duration
failure rate
retry rate
queue depth
GPU/CPU usage
memory
artifact size
cache hit rate
quality metrics
```

---

# 159. Operations

Minimum production services:

```text
API
Queue
Workers
Artifact Storage
Metadata DB
Monitoring
```

Optional:

```text
GPU workers
Object storage
distributed tracing
```

---

# 160. Database Model

Minimum entities:

```text
User
Job
InputArtifact
DerivedArtifact
StyleModel
Resource
Action
ValidationRun
HardwareRun
Release
```

Relationships are by immutable IDs.

---

# 161. Artifact Storage

Artifacts are immutable.

Publishing:

```text
write temp
→ fsync/verify where applicable
→ hash
→ validate
→ atomic rename/publish
```

Never publish before validation.

---

# 162. Backup / Recovery

Production must have:

```text
backup policy
restore test
artifact integrity check
database backup
configuration backup
model registry backup
```

---

# 163. Release Process

Release stages:

```text
Development
↓
Internal
↓
QA
↓
Release Candidate
↓
Certified
```

---

# 164. Release Candidate Gate

All must pass:

```text
unit
integration
regression
property/fuzz
security
benchmark
license
documentation
hardware
```

for the relevant feature scope.

---

# 165. Regression Policy

A change is blocked when it causes:

```text
previously PASS golden → FAIL
previously verified field → unknown
previously safe SET → conflict
hardware pass → load failure
semantic round-trip → mismatch
```

unless a signed Decision Record approves the change.

---

# 166. Feature Flags

Experimental features are behind:

```text
feature flag
```

Examples:

```text
experimental_transcriber
experimental_ntt
experimental_fx
experimental_writer_field_X
```

Production default:

```text
OFF
```

---

# 167. Configuration

All meaningful behavior must be configurable.

Example:

```yaml
profile: Pa600-2.1.1
quantization:
  mode: adaptive
  grid: 1/16
mapping:
  fallback: manual-review
output:
  minimal_set: true
audio:
  separator_backend: approved_backend
```

---

# 168. No Hidden Magic Constants

Bad:

```python
if score > 0.85:
```

Good:

```python
if score >= config.transcription.snare_threshold:
```

Configuration is versioned.

---

# 169. P0 Gates

## Gate P0-A

```text
Environment PASS
```

## Gate P0-B

```text
Real SET inspect PASS
```

## Gate P0-C

```text
Real KMP/KSF inspect PASS
```

## Gate P0-D

```text
Real STY parse PASS
```

---

# 170. P1 Gates

## Gate P1-A

```text
Model snapshot PASS
```

## Gate P1-B

```text
Semantic round-trip PASS
```

## Gate P1-C

```text
Native STY validation PASS
```

## Gate P1-D

```text
Pa600 H1 PASS
```

---

# 171. P2 Gates

## Gate P2-A

```text
MIDI path → canonical events PASS
```

## Gate P2-B

```text
Audio decode/normalize PASS
```

## Gate P2-C

```text
Separation quality PASS
```

## Gate P2-D

```text
Drum ADT benchmark PASS
```

---

# 172. P3 Gates

```text
Tempo PASS
Beat PASS
Downbeat PASS
Bar PASS
Pattern clustering PASS
Groove model PASS
Structure coverage PASS
```

---

# 173. P4 Gates

```text
Mapping candidate resolution PASS
No unresolved required drum roles
User review UI PASS
Velocity semantics PASS
Fallback policy PASS
```

---

# 174. P5 Gates

```text
Style compiler PASS
Static validator PASS
Semantic round-trip PASS
MVP hardware PASS
```

---

# 175. P6 Gates

```text
Dependency graph PASS
Slot allocation PASS
Conflict report PASS
Minimal SET PASS
Clean environment PASS
```

---

# 176. P7 Gates

```text
Upload PASS
Job lifecycle PASS
Retry PASS
Cancel PASS
Artifact download PASS
```

---

# 177. P8 Gates

```text
Editor semantic edits PASS
Undo PASS
Validation after edit PASS
Recompile PASS
```

---

# 178. P9 Gates

```text
LLM schema PASS
Action validator PASS
Permission PASS
Audit PASS
Undo PASS
```

---

# 179. P10 Gates

```text
FX estimator benchmark PASS
Renderer PASS
Static validation PASS
Hardware validation where applicable
```

---

# 180. MASTER GO / NO-GO

The most important hardware Go/No-Go:

```text
Generated STY
↓
Pa600
↓
Load
↓
Play
↓
Save
↓
Reload
↓
Echo/Export
↓
Semantic comparison
```

If it fails:

```text
STOP
DIAGNOSE
FIX
RETEST
```

No “continue anyway” for a broken core.

---

# 181. MVP Definition

Input:

```text
Song MIDI OR Audio
+
Pa600 Standard SET
```

Output:

```text
Drum/Percussion Native STY
```

Minimum Style Elements:

```text
Variation 1
Variation 2
Fill 1
Intro 1
Ending 1
```

MVP MUST support:

```text
drum/percussion event extraction
beat/bar normalization
pattern identity
groove representation
semantic mapping
native writer
static validation
hardware QA
```

MVP MAY defer:

```text
Bass
ACC1–5
advanced NTT generation
full complete SET merge
LLM
FX
```

---

# 182. MVP Is Not Allowed To Cheat

MVP is not considered complete if it:

```text
guesses unknown binary fields
hardcodes all drum notes
silently mutates samples
requires Pa600 for generation
uses SMF as STY substitute
skips semantic validation
skips hardware QA
```

---

# 183. Full Product Definition

```text
User
↓
Upload Song + SET
↓
M2S
↓
Parse
↓
Analyze
↓
Extract
↓
Cluster
↓
Map
↓
Edit
↓
Compile
↓
Validate
↓
Package
↓
Export
```

Optional:

```text
LLM
FX
Advanced accompaniment
```

---

# 184. Day 1 — Exact Work Order

Do exactly:

```text
1. Create repository.
2. Create Python environment.
3. Configure pytest.
4. Configure Ruff.
5. Configure logging.
6. Obtain one real Pa600 SET with proper authorization.
7. Obtain one real STY.
8. Export same Style from Pa600 as SMF.
9. Record Pa600 OS version.
10. Hash all source files.
11. Create manifest.
12. Write inspect_sty.py.
13. Write inspect_set.py.
14. Write inspect_smf.py.
15. Record file sizes.
16. Generate hex dumps.
17. List SMF tracks.
18. List SMF markers.
19. Commit.
```

Do not start with AI.

---

# 185. First Golden Pair

Best first pair:

```text
Real STY
+
Pa600-exported SMF
```

Why:

```text
STY gives binary ground truth.
SMF gives an interoperability/semantic probe.
```

But:

```text
STY ≠ SMF
```

and their models must remain separate.

---

# 186. First 20 Engineering Tickets

```text
P0-001 bootstrap repository
P0-002 environment lock
P0-003 manifest schema
P0-004 SHA256 tooling
P0-005 binary inspector
P0-006 SET inspector
P0-007 SMF inspector
P0-008 diff tool
P0-009 evidence registry
P0-010 STY reader skeleton
P0-011 unknown-region model
P0-012 style document model
P0-013 CV model
P0-014 track model
P0-015 semantic comparator
P0-016 writer skeleton
P0-017 golden round-trip test
P0-018 static validator skeleton
P0-019 hardware checklist
P0-020 Gate P0-D
```

---

# 187. What the Non-Programmer Needs to Learn

## Level 1

```text
Python variables
if
for
functions
classes
dict/list
JSON
files
exceptions
```

## Level 2

```text
typing
Pydantic
modules
packages
logging
pytest
Git
```

## Level 3

```text
bytes
hex
struct
offset
length
endianness
checksum
```

## Level 4

```text
MIDI
ticks
PPQN
tempo
SMF
```

## Level 5

```text
audio
spectrogram
onset
beat
downbeat
BPM
```

## Level 6

```text
model
inference
confidence
calibration
benchmark
```

## Level 7

```text
HTTP
API
jobs
worker
upload
storage
```

---

# 188. AI-Assisted Coding Rules

AI may write code.

AI may not define facts.

Workflow:

```text
One task
↓
Small change
↓
Tests
↓
Inspection
↓
Commit
```

---

# 189. Prompt Pattern for Coding

Use:

```text
Task:
single function/module

Constraints:
do not infer undocumented Korg behavior

Tests:
add pytest

Output:
list files changed
explain assumptions
```

---

# 190. What AI Must Never Do

```text
invent Korg format
guess unknown offsets
guess checksums
silently change resource IDs
overwrite samples
rewrite SET destructively
directly edit raw STY bytes
execute shell commands from user text
treat experimental behavior as verified
```

---

# 191. Decision Log

Every significant choice:

```text
D-001
Question:
...

Evidence:
...

Status:
EXPERIMENTAL / DOCUMENTED / VERIFIED

Decision:
...

Reason:
...

Impact:
...

Next test:
...
```

---

# 192. Documentation Integrity

Every factual Korg claim used by code should point to:

```text
official manual
official specification
fixture
experiment
```

No unsupported sentence is allowed to become a hardcoded rule.

---

# 193. Korg Claim Registry

Create:

```text
docs/korg-evidence.md
```

Example:

```text
Claim:
Pa600 Style contains 8 Style Tracks.

Source:
Korg Technical Specifications.

Status:
DOCUMENTED.

Code impact:
Profile only.

Hardware proof:
pending.
```

---

# 194. Research vs Production

Two modes:

```text
PRODUCTION
```

Only verified writer fields.

```text
RESEARCH
```

Allows:

```text
experiments
unknown fields
candidate offsets
diagnostics
```

Research output cannot be mislabeled production-certified.

---

# 195. Quality Report Example

```text
M2S BUILD REPORT

Profile: Pa600-2.1.1

Input:
Audio SHA256: ...

SET:
SHA256: ...

Structure:
Bars: 32
Tempo: 98.2 ± 0.6 BPM

Patterns:
Variation 1: PASS
Variation 2: PASS
Fill 1: REVIEW

Mapping:
Kick: PASS
Snare: PASS
HH: PASS
Ride Bell: USER REVIEW

Output:
STY: STATIC PASS
SET: NOT BUILT

Hardware:
NOT RUN

Overall:
READY WITH WARNINGS
```

---

# 196. Release Manifest

Every release includes:

```json
{
  "application_version": "2.0.0",
  "schema_version": "1.x",
  "profiles": ["Pa600-2.1.1"],
  "models": [],
  "tests": {},
  "hardware_certification": {},
  "licenses": []
}
```

---

# 197. Definition of Done — Format Core

PASS only if:

```text
Real STY parses
Unknown data preserved
Supported fields round-trip
Writer emits valid structure
Validator detects corrupted output
No parser crashes on fuzz corpus
```

---

# 198. Definition of Done — Musical Core

PASS only if:

```text
MIDI and Audio converge to same internal event model
Tempo is explicit
Bar boundaries are explicit
Pattern identity is independent of groove
Variations are structurally distinct
Fill detection is reviewable
```

---

# 199. Definition of Done — Mapping

PASS only if:

```text
semantic roles exist
candidate targets are visible
fallbacks are deterministic
velocity semantics preserved
unresolved roles are explicit
```

---

# 200. Definition of Done — Native Style

PASS only if:

```text
Internal model validates
STY writes
Semantic round-trip passes
Pa600 loads
Required elements play
Save/reload passes
```

---

# 201. Definition of Done — SET

PASS only if:

```text
dependency graph resolves
slot allocation resolves
conflicts are reported
Minimal SET loads independently
source SET is not required
```

---

# 202. Definition of Done — Web

PASS only if:

```text
job starts
progress works
failure is visible
cancel works
retry is safe
artifacts are downloadable
```

---

# 203. Definition of Done — LLM

PASS only if:

```text
LLM actions validate
permissions work
domain engine performs actions
audit exists
undo exists
LLM cannot access raw binary writer
```

---

# 204. Definition of Done — Product

PASS only if:

```text
User uploads SET + Song
↓
M2S completes pipeline
↓
Native STY produced
↓
Static validation PASS
↓
Hardware certification PASS for release scope
```

---

# 205. Master Stop Rule

At every Gate:

```text
PASS
```

or:

```text
FAIL
↓
diagnose
↓
fix
↓
retest
```

There is no:

```text
probably works
```

and no:

```text
we will fix it later
```

for release-blocking functions.

---

# 206. Exceptions to Stop Rule

Only non-blocking experimental work may continue in parallel when:

```text
core Gate is already PASS
```

Example:

```text
experimental FX
```

may proceed while:

```text
certified Drum core
```

remains stable.

No experimental work may modify certified writer code without regression.

---

# 207. Project Backlog Order

Mandatory order:

```text
0. Bootstrap
1. Evidence
2. Korg parsing
3. Korg model
4. Native writer
5. Static validator
6. Hardware QA
7. MIDI pipeline
8. Audio pipeline
9. Pattern intelligence
10. Mapping
11. Native generation
12. SET packaging
13. Web
14. Editor
15. LLM
16. FX
17. Production hardening
```

---

# 208. Future Expansion

After Pa600 certification:

```text
Pa600Profile
Pa700Profile
Pa1000Profile
Pa4XProfile
...
```

Do not fork the engine.

Use:

```text
shared domain model
+
profile-specific codec
+
profile-specific validator
+
profile-specific capability matrix
```

---

# 209. Capability Matrix

Every Profile declares:

```text
supported style elements
supported CV counts
supported tracks
supported FX
supported PCM
supported SMF
supported writer fields
```

The compiler asks:

```python
profile.supports(feature)
```

rather than testing model name everywhere.

---

# 210. Maintainability Rule

Never write:

```python
if device == "Pa600":
```

deep inside arbitrary business logic.

Prefer:

```python
profile.capabilities
profile.rules
profile.codec
```

---

# 211. Performance Targets

Before production define:

```text
max upload size
max audio duration
max SET size
max concurrent jobs
CPU/GPU requirements
memory budget
```

Benchmarks must record:

```text
median
p95
failure rate
```

not only average.

---

# 212. Cost Control

For web deployment:

```text
CPU job
GPU job
LLM call
storage
bandwidth
```

are measured separately.

Cache deterministic stages.

Do not rerun expensive separation after an unrelated mapping edit.

---

# 213. Change Impact Analysis

Every code change declares:

```text
affected domains
```

Examples:

```text
Korg writer change
→ run Korg regression + hardware

ADT model change
→ run Audio benchmark + Pattern regression where relevant

Editor change
→ run Model/Writer regression
```

---

# 214. Golden Snapshot Policy

Store expected semantic snapshots in a stable format:

```json
{
  "style_elements": [],
  "cvs": [],
  "tracks": [],
  "performance": {},
  "resources": []
}
```

Do not snapshot only raw bytes.

---

# 215. Hardware Corpus Strategy

Use a small controlled set:

```text
H-001 Basic Drum Style
H-002 Multi-CV Style
H-003 Multi-Element Style
H-004 Custom PCM Style
H-005 Performance/FX Style
```

Each has known expected outcomes.

---

# 216. Recovery Procedure

If generated SET damages QA state:

```text
1. Stop test.
2. Restore backup.
3. record artifact hash.
4. preserve logs.
5. mark regression.
6. reproduce on isolated QA device.
```

Never continue blindly.

---

# 217. User Overrides

Every automated decision can have override where safe:

```text
tempo
bar boundaries
pattern assignment
instrument classification
mapping
velocity curve
intro/ending origin
```

User override becomes provenance:

```text
source = USER
```

and supersedes model suggestion.

---

# 218. Provenance Source Types

```text
SOURCE
MODEL
RULE
USER
DERIVED
HARDWARE_VERIFIED
```

Example:

```text
snare mapping:
source = USER
previous suggestion = MODEL
```

---

# 219. Explainability

For any warning:

```text
What happened?
Why?
Confidence?
What can user change?
```

Example:

```text
Ride Bell not found.
Closest compatible candidate: Ride Bow.
Automatic substitution disabled by policy.
Action: choose target or mute.
```

---

# 220. No Hidden Musical Mutation

When compiler changes:

```text
quantization
velocity
timing
note mapping
```

record:

```text
before
after
reason
policy
actor
```

---

# 221. Music Preservation

The system always keeps:

```text
original events
canonical events
compiled events
```

as separate layers.

Never overwrite source data.

---

# 222. Compiler Layers

```text
Raw Musical Evidence
↓
Normalized Musical Model
↓
Musical Interpretation
↓
Target Compilation
↓
Korg Binary
```

Each layer can be inspected independently.

---

# 223. Preview Strategy

Before final export:

```text
Pattern preview
Mapping preview
Structure preview
Diagnostic MIDI
```

Optional audio preview can use:

```text
generic drum kit
or
verified user DrumKit rendering
```

and must state which one was used.

---

# 224. Preview Must Not Pretend to Be Hardware

UI label:

```text
Software Preview
```

vs:

```text
Pa600 Hardware Verified
```

These are distinct states.

---

# 225. User-Facing Export Page

Show:

```text
STY
[Download]

Minimal SET
[Download]

Complete SET
[Download if available]

Diagnostic MIDI
[Download]

Report
[Download]
```

Also:

```text
Hardware verified: YES/NO
Warnings: N
Experimental components: N
```

---

# 226. Complete Product Architecture — Final

```text
                  ┌────────────────────┐
                  │      WEB / CLI     │
                  └─────────┬──────────┘
                            │
                       Job Service
                            │
                     M2S Orchestrator
                            │
          ┌─────────────────┼───────────────────┐
          │                 │                   │
          ▼                 ▼                   ▼
      KORG CORE         MUSIC CORE          AI ADAPTERS
          │                 │                   │
     Parser/Writer     MIDI/Audio         Separation
     Profiles          Time/Beat          ADT
     Resource Graph    Pattern/Groove     LLM
     Validator         Structure          FX
          │                 │                   │
          └─────────────────┼───────────────────┘
                            ▼
                  Internal Style Model
                            │
                            ▼
                    Native STY Compiler
                            │
                     ┌──────┴──────┐
                     ▼             ▼
                    STY        SET Packager
                     │             │
                     └──────┬──────┘
                            ▼
                     Static Validator
                            │
                            ▼
                       QA / Report
                            │
                       Pa600 QA only
```

---

# 227. Final Product Contract

The production product promises:

```text
We will only claim what has been verified.
```

Therefore:

```text
Native STY
```

means:

```text
written through the supported Korg codec
+
static validation
+
required hardware certification
```

and not:

```text
SMF renamed to STY
```

or:

```text
binary guessed from a single sample
```

---

# 228. First Release Scope

Release 0.1:

```text
Pa600 Standard 2.1.1
Drum/Percussion only
MIDI input first
Audio input second
Variation 1–2
Fill 1
Intro 1
Ending 1
Native STY
Static validation
Hardware certification
```

Release 0.2:

```text
Variation 3–4
Fill 2–4
Break
Intro 2–3
Ending 2–3
```

Release 0.3:

```text
Bass
```

Release 0.4+:

```text
ACC1–ACC5
advanced NTT
advanced resource compilation
```

Later:

```text
Web
Editor
LLM
FX
additional Profiles
```

---

# 229. Final Project Sequence

```text
PHASE 0
Environment
        ↓
P0
Evidence / Reverse Engineering
        ↓
P0 Gate
        ↓
P1
Native Parser / Model / Writer
        ↓
P1 Gate
        ↓
Hardware H1/H2
        ↓
P2
MIDI first
        ↓
P2 MIDI Gate
        ↓
P2 Audio / Separation / ADT
        ↓
P2 Audio Gate
        ↓
P3
Pattern / Groove / Structure
        ↓
P3 Gate
        ↓
P4
Smart Mapping
        ↓
P4 Gate
        ↓
P5
Native Style Compiler
        ↓
P5 Gate
        ↓
P6
SET Packager
        ↓
P6 Gate
        ↓
P7
Web
        ↓
P8
Editor
        ↓
P9
LLM
        ↓
P10
FX
        ↓
Production Certification
```

---

# 230. Final Checklist

## Format

```text
[ ] Pa600 profile frozen
[ ] Evidence registry exists
[ ] STY reader works
[ ] Unknown preservation works
[ ] KMP/KSF strategy works
[ ] SET graph works
[ ] Native writer works
[ ] semantic round-trip works
```

## MIDI

```text
[ ] SMF 0/1 input
[ ] tick model
[ ] tempo map
[ ] time signatures
[ ] track classification
[ ] canonical event model
```

## Audio

```text
[ ] decoder
[ ] normalization
[ ] separation adapter
[ ] ADT adapter
[ ] calibration
[ ] event deduplication
```

## Music

```text
[ ] beat
[ ] downbeat
[ ] bars
[ ] pickup
[ ] half/double tempo
[ ] canonical patterns
[ ] groove
[ ] similarity
[ ] variation selection
[ ] fill
[ ] intro/ending
```

## Mapping

```text
[ ] semantic taxonomy
[ ] user review
[ ] target resolver
[ ] velocity policy
[ ] fallback policy
[ ] warnings
```

## Packaging

```text
[ ] dependency graph
[ ] slot allocator
[ ] canonical hashes
[ ] conflicts
[ ] minimal SET
[ ] clean environment test
```

## Product

```text
[ ] jobs
[ ] queue
[ ] retries
[ ] cancellation
[ ] caching
[ ] logs
[ ] security
[ ] privacy
[ ] licenses
[ ] provenance
```

## QA

```text
[ ] unit
[ ] integration
[ ] golden
[ ] semantic round-trip
[ ] fuzz
[ ] security
[ ] audio benchmark
[ ] structure benchmark
[ ] hardware certification
[ ] release manifest
```

---

# 231. Final Rule

When uncertain:

```text
DO NOT GUESS.
```

Instead:

```text
PRESERVE
↓
LABEL UNKNOWN
↓
CREATE EXPERIMENT
↓
COLLECT EVIDENCE
↓
UPDATE REGISTRY
↓
IMPLEMENT
↓
REGRESS
↓
HARDWARE VERIFY
```

---

# 232. Source / Evidence Notes

The specification's Korg-specific baseline should be checked against the exact Pa600 documentation and project fixtures before each implementation release.

Primary documentation used for the baseline:

1. KORG — Pa600 User Manual v2.1  
   https://cdn.korg.com/us/support/download/files/dde158cb091b2cc543ff4036ca6703f1.pdf

2. KORG — Pa600 technical specifications / Quick Guide  
   https://cdn.korg.com/us/support/download/files/3b5090db94307ca19ba68eb6e8a348ce.pdf

3. KORG — Pa600 support / OS downloads  
   https://www.korg.com/us/support/download/product/0/90/

4. KORG — Arranger / Style tutorial material  
   https://www.korg.com/tw/features/arrangers/tutorials/

5. Spotify — Basic Pitch  
   https://github.com/spotify/basic-pitch

6. Music and Culture Technology Lab — Omnizart  
   https://github.com/Music-and-Culture-Technology-Lab/omnizart

7. facebookresearch — Demucs repository status  
   https://github.com/facebookresearch/demucs

8. Yamaha documentation is used only to identify/exclude Yamaha-specific CASM/SFF terminology from the Korg Pa600 model. It is not a source of Korg binary behavior.

---

# 233. Important Verified/Documented Korg Baseline

For the initial Pa600 profile, the specification uses the following documented capabilities as design anchors:

```text
8 Style Tracks
15 Style Elements
up to 46 Style patterns / Chord Variations
4 Variations
3 Intros
4 Fills
1 Break
3 Endings
96 MB PCM User Memory
4 Stereo Master FX
125 Effect types
```

These values describe the target device's documented capabilities; they are not by themselves proof of every binary field layout.

---

# 234. Final Status

```text
Specification Version: 2.0.0
Target Profile: Pa600 Standard / OS 2.1.1
Core Philosophy: Evidence-driven deterministic compiler
MVP Focus: Drum/Percussion Native STY
Hardware Role: QA only
AI Role: Optional adapter / planner
Production Requirement: PASS at every release gate
```

---

# 235. One Sentence To Remember

> **M2S אינו “AI שמייצר STY”; M2S הוא Compiler דטרמיניסטי לפורמט Korg, שעליו מונחות שכבות AI לניתוח, הצעה ועריכה.**

---

---

# 236. Non-Functional Requirements

M2S הוא לא רק אוסף פונקציות. עליו לעמוד בדרישות מערכת.

## NFR-01 Correctness

לא לייצר Native artifact כאשר יש שדה חובה לא מאומת או reference לא פתור.

## NFR-02 Reproducibility

אותו:

```text
input hash
+
configuration hash
+
engine version
+
model version/hash
+
profile
+
schema
```

מייצר אותו semantic result ככל שהbackend מאפשר deterministic execution.

## NFR-03 Safety

אין:

```text
destructive overwrite
silent mutation
unsafe parser allocation
hidden dependency
```

## NFR-04 Auditability

כל שינוי משמעותי ניתן לקשר ל:

```text
user action
rule
model
experiment
```

## NFR-05 Explainability

כל warning משמעותי מסביר:

```text
what
why
confidence
next action
```

## NFR-06 Maintainability

Korg-specific behavior נמצא בתוך:

```text
Profile
Codec
Validator
Resource Graph
```

ולא מפוזר בין UI/AI/business logic.

## NFR-07 Portability

ה־Core אינו תלוי ב:

```text
Windows-only path behavior
one GPU vendor
one AI provider
one web framework
```

## NFR-08 Performance

כל stage מקבל benchmark עצמאי.

מודדים:

```text
p50
p95
failure rate
memory peak
```

## NFR-09 Recoverability

Job שנכשל יוכל להמשיך רק מארטיפקט parent מאומת ותואם version/configuration.

## NFR-10 Privacy

Raw user media אינו נשמר מעבר למדיניות retention המוצהרת.

---

# 237. Explicit Support Boundaries

## Supported in v0.1

```text
Pa600 Standard
OS Profile 2.1.1
Drum
Percussion
Variation 1–2
Fill 1
Intro 1
Ending 1
MIDI input
Native STY output
```

## Supported experimentally in v0.1

```text
Audio input
Source Separation
ADT
Groove estimation
```

## Not release-blocking in v0.1

```text
Bass
ACC1–ACC5
advanced NTT
Complete SET merge
LLM
FX
```

## Unsupported

```text
unknown device profile
unverified Korg binary format
corrupted mandatory resources
unresolved mandatory references
```

---

# 238. Capability Negotiation

לפני build:

```python
plan = compiler.plan(
    input_model,
    profile,
    requested_features,
)
```

ה־plan מחזיר:

```text
supported
unsupported
experimental
requires_user_review
```

אין להתחיל build ואז לגלות באמצע ש־feature אינו נתמך, אלא אם אי-הוודאות עצמה היא תוצאת הניתוח.

---

# 239. Compilation Plan

ה־Compiler מייצר Plan לפני Writer:

```text
CompilePlan
├── target_profile
├── style_elements
├── tracks
├── cv allocation
├── resource allocations
├── mapping decisions
├── transformations
├── unsupported items
└── validation requirements
```

המשתמש/QA יכול לבדוק Plan לפני יצירת artifact.

---

# 240. Plan vs Artifact

חשוב להפריד:

```text
Plan
```

מ:

```text
Artifact
```

Plan יכול להיכשל לפני Writer.

Artifact נחשב קיים רק לאחר Writer + Validator.

---

# 241. Transactional Build

Build:

```text
create temp workspace
↓
compile
↓
validate
↓
hash
↓
publish atomically
```

כשל באמצע:

```text
discard incomplete artifact
```

אין להציג קובץ חלקי כ־downloadable production output.

---

# 242. Resource Allocation Transaction

SET build:

```text
calculate allocations
↓
validate conflicts
↓
build copy
↓
rewrite references
↓
validate
↓
publish
```

אין לשנות את source SET בזמן planning.

---

# 243. User SET Protection

Source SET הוא:

```text
READ_ONLY
```

מבחינת M2S.

כל output הוא:

```text
NEW_ARTIFACT
```

אין in-place editing.

---

# 244. Backup Policy

כל hardware QA run על SET must have:

```text
pre-test backup
post-test backup
artifact hash
```

במקרה של SET conflict או unexpected erase:

```text
STOP TEST
RESTORE
LOG
```

---

# 245. Style Content vs Slot Placement

המערכת חייבת להפריד:

```text
Style semantic content
```

מ:

```text
User bank/slot
```

לכן אותו Style יכול להיות:

```text
logical_style_id = STY-123
slot = U01-03
```

או:

```text
slot = U05-12
```

בלי לשנות את זהותו הלוגית.

---

# 246. Resource Identity vs Filename

אין להשתמש בשם קובץ כ־identity.

לדוגמה:

```text
SNARE.KSF
```

אינו בהכרח אותו Resource כמו:

```text
SNARE.KSF
```

ב־SET אחר.

Identity דורשת:

```text
content
mapping
context
source lineage
```

בהתאם לסוג resource.

---

# 247. Musical Semantic Model

M2S מגדיר שכבה ניטרלית מ־Korg:

```text
MusicalEvent
Pattern
Groove
Section
InstrumentRole
```

ואז:

```text
Korg Compiler
```

ממיר אותה ל־Pa600.

המטרה היא לאפשר בעתיד:

```text
same musical model
→ Pa600
→ Pa700
→ another target
```

בלי לשכתב את Audio/Pattern engine.

---

# 248. Chord Context Model

ל־Advanced Accompaniment עתידי:

```python
ChordContext(
    root,
    chord_quality,
    inversion,
    bass_note,
    source_label
)
```

זה אינו CASM.

ה־Korg compiler ימפה Chord Context ל־NTT/Chord Table behavior רק לאחר Evidence.

---

# 249. Unsupported Chord Behavior

אם בעתיד Track דורש chord-aware transformation שלא הוכח:

```text
UNSUPPORTED_REQUIRED_TRANSFORMATION
```

ולא:

```text
approximate silently
```

---

# 250. Audio-to-MIDI Reconciliation

כאשר Audio ו־MIDI זמינים יחד:

```text
MIDI = explicit structural evidence
Audio = acoustic evidence
```

המערכת יכולה להשוות:

```text
MIDI kick
vs
Audio kick
```

ולזהות:

```text
missing MIDI events
extra MIDI events
timing disagreement
velocity disagreement
```

אך לא משנה אוטומטית מקור בלי policy.

---

# 251. Source Priority Policy

Default:

```text
User-authored MIDI
>
high-confidence direct MIDI events
>
calibrated ADT
>
low-confidence ADT
```

Audio evidence can still override via:

```text
explicit reconciliation policy
```

העדיפות היא policy versioned ולא hardcoded.

---

# 252. Human-in-the-Loop Thresholds

כאשר confidence נמצא בטווח:

```text
review_low ≤ confidence < auto_accept
```

המערכת מבקשת:

```text
user review
```

לא:

```text
auto-accept
```

---

# 253. Review Queue

Items requiring human review:

```text
low confidence event
ambiguous instrument
uncertain downbeat
ambiguous tempo
unresolved target key
resource conflict
unsupported style feature
```

כל item כולל:

```text
reason
candidates
evidence
recommended action
```

---

# 254. User Override Priority

כאשר user override קיים:

```text
USER
>
POLICY
>
MODEL
>
DEFAULT
```

User override itself must pass domain validation.

---

# 255. Model Drift Monitoring

After deployment:

```text
model version changes
dataset changes
backend changes
OS changes
```

trigger:

```text
benchmark rerun
```

No silent backend upgrade in a certified environment.

---

# 256. Dependency Pinning

Production freezes:

```text
Python
libraries
AI backend
model weights
system packages
FFmpeg
```

An unpinned update invalidates certification until regression passes.

---

# 257. Environment Manifest

Every release records:

```text
OS
Python
package lock hash
container hash if used
FFmpeg version
CPU/GPU
model hashes
profile version
```

---

# 258. Data Lineage

Every generated note can be traced conceptually to:

```text
source event(s)
↓
normalization
↓
pattern operation
↓
mapping operation
↓
rendered Korg event
```

Not necessarily stored per note forever, but enough lineage must exist for debugging and audit.

---

# 259. Debug Bundle

When a production job fails, support can export a sanitized bundle:

```text
job metadata
config
schema
profile
logs
error
artifact hashes
optional redacted model snapshot
```

without automatically including the user's complete source media.

---

# 260. Release Certification Matrix

| Layer | Required |
|---|---|
| Python/bootstrap | PASS |
| Korg parser | PASS |
| Korg semantic model | PASS |
| Writer | PASS |
| Static validator | PASS |
| Golden regression | PASS |
| Fuzz/security | PASS |
| MIDI pipeline | PASS |
| Audio pipeline | Scope-dependent |
| Mapping | PASS for supported roles |
| Native STY | PASS |
| SET package | PASS if shipped |
| Web | PASS if shipped |
| Editor | PASS if shipped |
| LLM | PASS if shipped |
| FX | PASS if shipped |
| Hardware | Required for shipped Korg features |

A release cannot be “partially certified” without explicitly stating the certified scope.

---

# 261. Master Acceptance Matrix

## A. Input

```text
valid SET → PASS
invalid SET → clean FAIL
valid MIDI → PASS
valid Audio → PASS
unsupported profile → UNSUPPORTED
```

## B. Format

```text
STY parse → PASS
unknown preservation → PASS
semantic round-trip → PASS
```

## C. Music

```text
beat/bar → PASS
pattern → PASS
structure → PASS
```

## D. Mapping

```text
exact mapping → PASS
fallback → deterministic
unresolved → review
```

## E. Output

```text
STY static validation → PASS
SET validation → PASS
```

## F. Hardware

```text
load → PASS
playback → PASS
save → PASS
reload → PASS
echo test → PASS
```

---

# 262. Final Certification Rule

A feature is:

```text
CERTIFIED
```

only when:

```text
implementation
+
tests
+
evidence
+
documentation
+
required hardware validation
```

all exist.

A feature without one of these is:

```text
DOCUMENTED
EXPERIMENTAL
or UNSUPPORTED
```

but not CERTIFIED.

---

# 263. Change Log from Previous Master

The previous specification already established the essential architecture:

```text
Korg format first
Internal Model
Native Writer
Audio intelligence
Pattern intelligence
Smart remapping
SET packaging
Web
LLM
FX
```

The present version adds and closes the following gaps:

```text
1. Formal Input/Output contract
2. Explicit unsupported-state behavior
3. Five-pass review record
4. Non-functional requirements
5. Versioned capability negotiation
6. Compile Plan before artifact creation
7. Transactional/atomic builds
8. Source SET read-only policy
9. Artifact dependency invalidation
10. Job resume/cancel/retry semantics
11. Audio/MIDI reconciliation policy
12. Human review thresholds
13. User override precedence
14. Model drift controls
15. Dependency pinning
16. Environment manifest
17. Data lineage
18. Debug bundle policy
19. Release certification matrix
20. Master acceptance matrix
21. Hardware Echo Test
22. Explicit distinction between SMF and STY
23. Explicit distinction between Style semantics and slot placement
24. Resource identity vs filename
25. Chord Context abstraction without importing Yamaha CASM
```

---

# 264. Final Audit Result

Five review passes completed:

```text
PASS 1 — Requirements completeness       PASS
PASS 2 — Korg/SMF model integrity        PASS
PASS 3 — Internal model integrity        PASS
PASS 4 — Failure/security/QA coverage    PASS
PASS 5 — Production/release readiness   PASS
```

Important limitation:

```text
"PASS" here means the specification review is internally consistent
and the required controls are defined.

It does NOT mean the undocumented Korg binary format has already
been reverse-engineered or hardware-certified.
```

That distinction is mandatory.

---

# 265. Final Go/No-Go Summary

```text
CAN WE START CODING?
→ YES

CAN WE CLAIM NATIVE STY WORKS?
→ NO, not before Gate P1 + Hardware

CAN WE CLAIM AUDIO TRANSCRIPTION IS RELIABLE?
→ NO, not before calibrated benchmark

CAN WE CLAIM SET PACKAGING IS SAFE?
→ NO, not before dependency + conflict + clean-environment tests

CAN WE ADD LLM NOW?
→ Not to the production core

CAN WE ADD FX NOW?
→ Only as isolated experimental work
```

---

# 266. Final Operating Rule

If a statement in the code cannot be answered with:

```text
"Where is the evidence?"
```

then it does not become a production rule yet.


