Add profile and save persistence, wired into the three autoloads

scripts/profiles/: SaveIO handles real file I/O in user://saves (one
file per profile_id, atomic write via temp-file-then-rename, backup
copy before each overwrite, corrupted-main falls back to backup,
schema-invalid content is rejected like corruption). SaveMigration
and SaveFactory are pure; SaveMigration refuses a schema_version it
doesn't recognize (older or newer) rather than guessing. ProgressUpdates
is pure and wires ReviewScheduler/DifficultyManager onto a save's
skills dict, including per-session overdue-review marking.

The three autoloads (SaveManager, ProfileManager, ProgressManager)
stay thin: in-memory current-profile state and orchestration only,
no logic of their own, so the actual behavior lives in the tested
pure/file-IO modules above rather than in untestable glue.

26 new headless tests, including the failure modes called out in the
launch prompt: a truncated .tmp file never corrupts the readable
save, a corrupted main file falls back to its backup, two profiles
never mix (down through the real autoload layer, not just SaveIO),
and an unknown future schema_version is rejected outright.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Denis Defolie
2026-10-11 17:12:50 +02:00
parent 2fe455f5d1
commit ebabe91821
22 changed files with 696 additions and 6 deletions
+60
View File
@@ -0,0 +1,60 @@
class_name ProgressUpdates
extends RefCounted
## Fonctions pures qui appliquent une tentative d'exercice ou un debut de
## seance a une sauvegarde (dictionnaire conforme a save.schema.json), en
## s'appuyant sur ReviewScheduler et DifficultyManager (scripts/pedagogy/).
## ProgressManager (autoload) est seul responsable d'appeler ces fonctions et
## de persister le resultat via SaveManager ; l'ecriture sur disque reste
## groupee en fin de mission (docs/specs/decisions.md, point 7).
## attempt : {"skill": String, "success": bool, "hint_used": bool,
## "exercise_type": String}.
static func record_attempt(save_data: Dictionary, attempt: Dictionary) -> Dictionary:
var updated: Dictionary = save_data.duplicate(true)
var skills: Dictionary = updated["skills"]
var skill_id: String = attempt["skill"]
var skill_state: Dictionary = (
skills[skill_id] if skills.has(skill_id) else ReviewScheduler.initial_state()
)
var current_session: int = updated["session_count"]
skills[skill_id] = ReviewScheduler.record_attempt(skill_state, attempt, current_session)
updated["skills"] = skills
return updated
## A appeler une fois en debut de seance, avant toute tentative : incremente
## session_count et bascule en "a_reviser" les competences "acquise" dont le
## delai de revision est depasse sans nouvelle pratique.
static func start_session(save_data: Dictionary) -> Dictionary:
var updated: Dictionary = save_data.duplicate(true)
updated["session_count"] = int(updated["session_count"]) + 1
var current_session: int = updated["session_count"]
var skills: Dictionary = updated["skills"]
var updated_skills: Dictionary = {}
for skill_id: String in skills:
updated_skills[skill_id] = ReviewScheduler.mark_overdue_as_review(
skills[skill_id], current_session
)
updated["skills"] = updated_skills
return updated
static func next_difficulty_for_skill(
save_data: Dictionary, skill_id: String, current_difficulty: int
) -> int:
var skills: Dictionary = save_data["skills"]
if not skills.has(skill_id):
return current_difficulty
var recent: Array[bool] = skills[skill_id]["recent_results"]
return DifficultyManager.next_difficulty(current_difficulty, recent)
static func unlock_region(save_data: Dictionary, region_id: String) -> Dictionary:
var updated: Dictionary = save_data.duplicate(true)
var regions: Array = updated["unlocked_regions"]
if not regions.has(region_id):
regions.append(region_id)
updated["unlocked_regions"] = regions
return updated
+1
View File
@@ -0,0 +1 @@
uid://ql1hepqsa81w
+17
View File
@@ -0,0 +1,17 @@
class_name SaveFactory
extends RefCounted
## Construit une nouvelle sauvegarde vide pour un profil, conforme a
## data/schemas/save.schema.json. Code pur.
static func new_save(profile_id: String, display_name: String, school_level: String) -> Dictionary:
return {
"schema_version": SaveMigration.CURRENT_SCHEMA_VERSION,
"profile_id": profile_id,
"display_name": display_name,
"school_level": school_level,
"session_count": 0,
"unlocked_regions": [],
"skills": {},
"rewards": {"stars": 0, "items": []},
}
+1
View File
@@ -0,0 +1 @@
uid://bmeoyopvvcljr
+115
View File
@@ -0,0 +1,115 @@
class_name SaveIO
extends RefCounted
## Lecture/ecriture des sauvegardes par profil dans user://saves, avec
## ecriture atomique (fichier temporaire puis remplacement), copie de secours
## en cas de corruption du fichier principal, et migration de schema a la
## lecture. Pas pur (touche le systeme de fichiers), mais sans dependance a
## l'arbre de scenes : testable en headless avec de vrais chemins user://.
## Un profil ne lit et n'ecrit jamais que son propre fichier (nomme par
## profile_id) : deux profils ne peuvent pas se melanger.
const SAVE_DIR := "user://saves"
static func write(profile_id: String, data: Dictionary) -> bool:
DirAccess.make_dir_recursive_absolute(SAVE_DIR)
var tmp_path := _tmp_path(profile_id)
var tmp_file := FileAccess.open(tmp_path, FileAccess.WRITE)
if tmp_file == null:
return false
tmp_file.store_string(JSON.stringify(data))
tmp_file.close()
var main_path := _save_path(profile_id)
if FileAccess.file_exists(main_path):
_copy_file(main_path, _backup_path(profile_id))
var dir := DirAccess.open(SAVE_DIR)
if dir == null:
return false
return dir.rename(tmp_path, main_path) == OK
## Lit la sauvegarde d'un profil, deja migree vers le schema courant et
## validee contre `schema`. Retourne null si le fichier principal est absent,
## corrompu ou invalide ET que la copie de secours l'est aussi (ou n'existe
## pas).
static func read(profile_id: String, schema: Dictionary) -> Variant:
var from_main: Variant = _try_read(_save_path(profile_id), schema)
if from_main != null:
return from_main
return _try_read(_backup_path(profile_id), schema)
static func delete(profile_id: String) -> void:
var dir := DirAccess.open(SAVE_DIR)
if dir == null:
return
for path in [_save_path(profile_id), _backup_path(profile_id), _tmp_path(profile_id)]:
if FileAccess.file_exists(path):
dir.remove(path.get_file())
static func list_profile_ids() -> Array[String]:
var ids: Array[String] = []
var dir := DirAccess.open(SAVE_DIR)
if dir == null:
return ids
dir.list_dir_begin()
var entry := dir.get_next()
while entry != "":
if entry.ends_with(".json") and not entry.ends_with(".backup.json"):
ids.append(entry.get_basename())
entry = dir.get_next()
return ids
static func _try_read(path: String, schema: Dictionary) -> Variant:
var parsed: Variant = _read_raw_json(path)
if typeof(parsed) != TYPE_DICTIONARY:
return null
var migrated: Dictionary = SaveMigration.migrate(parsed)
if migrated.is_empty():
return null
var errors: Array[String] = SchemaValidator.validate(migrated, schema)
if not errors.is_empty():
return null
return migrated
static func _read_raw_json(path: String) -> Variant:
if not FileAccess.file_exists(path):
return null
var file := FileAccess.open(path, FileAccess.READ)
if file == null:
return null
var text := file.get_as_text()
if text.strip_edges().is_empty():
return null
return JSON.parse_string(text)
static func _copy_file(from_path: String, to_path: String) -> void:
var source := FileAccess.open(from_path, FileAccess.READ)
if source == null:
return
var bytes := source.get_buffer(source.get_length())
source.close()
var dest := FileAccess.open(to_path, FileAccess.WRITE)
if dest == null:
return
dest.store_buffer(bytes)
dest.close()
static func _save_path(profile_id: String) -> String:
return "%s/%s.json" % [SAVE_DIR, profile_id]
static func _tmp_path(profile_id: String) -> String:
return "%s/%s.json.tmp" % [SAVE_DIR, profile_id]
static func _backup_path(profile_id: String) -> String:
return "%s/%s.backup.json" % [SAVE_DIR, profile_id]
+1
View File
@@ -0,0 +1 @@
uid://cnsull4s5riep
+30
View File
@@ -0,0 +1,30 @@
class_name SaveMigration
extends RefCounted
## Migration des sauvegardes entre versions de schema. Code pur. Une seule
## version existe pour l'instant (1) ; chaque montee de version future ajoute
## une etape a la chaine ci-dessous, sans jamais reecrire les etapes passees.
const CURRENT_SCHEMA_VERSION := 1
## Retourne un dictionnaire vide si la version est absente, invalide, ou plus
## recente que ce que cette version du moteur sait lire : refuser plutot que
## de deviner et corrompre la progression de l'enfant.
static func migrate(data: Dictionary) -> Dictionary:
if not data.has("schema_version"):
return {}
var version: Variant = data["schema_version"]
if typeof(version) != TYPE_INT and typeof(version) != TYPE_FLOAT:
return {}
var version_int: int = int(version)
if version_int < 1 or version_int > CURRENT_SCHEMA_VERSION:
return {}
var migrated: Dictionary = data.duplicate(true)
# Chaine de montees de version, a completer quand CURRENT_SCHEMA_VERSION
# augmentera :
# if version_int == 1:
# migrated = _migrate_v1_to_v2(migrated)
# version_int = 2
migrated["schema_version"] = CURRENT_SCHEMA_VERSION
return migrated
+1
View File
@@ -0,0 +1 @@
uid://ct1yblqd7jxtw