From 45c3ffd853eee77f96118f6393f02a00287309ba Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 22 Sep 2026 23:52:47 +0000 Subject: [PATCH] Port resolveQuests, progression and nextContinuations: every family runs The last three families the port had vendored but never run. All 12 test fixtures now pass, covering every vector against the v0.14.0 pin. - ResolveQuests fires quest stage onComplete and outcome effects whose completeWhen/reachedWhen holds, once each (recorded in QuestFired), to a fixpoint, in ordinal quest-id then array order. Unconditioned effects never auto-fire, and QuestStages is never written. - Progression: LevelForXp, PointsEarned, AvailablePoints, EffectiveSkill, SkillCap, RecomputeSkills and the guarded InvestSkillPoint, with an optional skills registry for per-skill max. - NextContinuations returns a pending cutscene first, then forced routing (a routed character whose winning offer reads its active_dialogue__ flag at the top level, visited set ignored), else discovery with the visited filter. ClearActiveDialogue and ClearPendingCutscene consume them. Mutants on once-only firing, the cap guard, the cap clamp and the forced-offer flag test each turn the suite red. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Wc6JEuMmSXJEJSRYwGjn1f --- Parlance.Tests/ConformanceTests.cs | 85 +++++++++++ README.md | 7 +- Runtime/Runtime.cs | 217 +++++++++++++++++++++++++++++ 3 files changed, 306 insertions(+), 3 deletions(-) diff --git a/Parlance.Tests/ConformanceTests.cs b/Parlance.Tests/ConformanceTests.cs index 21675c9..e36a14c 100644 --- a/Parlance.Tests/ConformanceTests.cs +++ b/Parlance.Tests/ConformanceTests.cs @@ -244,6 +244,91 @@ public void ResolveCharacterDialogue() } } + [Test] + public void NextContinuations() + { + var vectors = Load("nextContinuations.json"); + Assert.NotNull(vectors); + foreach (var vObj in vectors) + { + var v = (Dictionary)vObj; + var state = State.FromDict((Dictionary)v["state"]); + var project = (Dictionary)v["project"]; + var visited = v.ContainsKey("visited") ? (List)v["visited"] : new List(); + + // Compared by id, as the reference harness does. + var got = new List(); + foreach (var c in Runtime.NextContinuations(state, project, visited, (string)v["currentDialogueId"])) + { + if ((string)c["kind"] == "cutscene") + { + got.Add(new Dictionary { { "kind", "cutscene" }, { "cutscene", ((Dictionary)c["cutscene"])["id"] } }); + } + else + { + got.Add(new Dictionary + { + { "kind", "dialogue" }, + { "characterId", c["characterId"] }, + { "dialogue", ((Dictionary)c["dialogue"])["id"] }, + { "queued", c["queued"] } + }); + } + } + AssertDeepEqual(v["expected"], got, (string)v["description"]); + } + } + + [Test] + public void ResolveQuests() + { + var vectors = Load("resolve_quests.json"); + Assert.NotNull(vectors); + foreach (var vObj in vectors) + { + var v = (Dictionary)vObj; + var state = State.FromDict((Dictionary)v["state"]); + var project = (Dictionary)v["project"]; + + var result = Runtime.ResolveQuests(state, project); + var firings = new List(); + foreach (Dictionary f in (List)result["firings"]) + { + firings.Add(new Dictionary { { "quest", f["quest"] }, { "kind", f["kind"] }, { "id", f["id"] } }); + } + var got = new Dictionary + { + { "state", ((State)result["state"]).ToDict() }, + { "firings", firings } + }; + AssertDeepEqual(v["expected"], got, (string)v["description"]); + } + } + + // progression.json mixes five functions; the vector's `fn` picks one. + [Test] + public void Progression() + { + var vectors = Load("progression.json"); + Assert.NotNull(vectors); + foreach (var vObj in vectors) + { + var v = (Dictionary)vObj; + var config = (Dictionary)v["config"]; + string fn = (string)v["fn"]; + object got = fn switch + { + "levelForXp" => Runtime.LevelForXp(Convert.ToSingle(v["xp"]), config), + "pointsEarned" => Runtime.PointsEarned(Convert.ToSingle(v["xp"]), config), + "availablePoints" => Runtime.AvailablePoints(State.FromDict((Dictionary)v["state"]), config), + "investSkillPoint" => Runtime.InvestSkillPoint(State.FromDict((Dictionary)v["state"]), (string)v["skillId"], config).ToDict(), + "recomputeSkills" => Runtime.RecomputeSkills(State.FromDict((Dictionary)v["state"]), config).ToDict(), + _ => throw new InvalidOperationException($"unknown progression fn '{fn}'") + }; + AssertDeepEqual(v["expected"], got, $"{fn}: {v["description"]}"); + } + } + private Func RngFrom(object spec) { List values = spec is List l ? l : new List { spec }; diff --git a/README.md b/README.md index 422688f..7b6053e 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,10 @@ This package reads that JSON and runs it in Unity: dialogues, conditions, effect | parlance-unity | Parlance spec | Families | |---|---|---| -| `main` (unreleased) | v0.14.0 — pinned to [`f4a25b0`](conformance/PIN) | 8 of 11 | +| `main` (unreleased) | v0.14.0 — pinned to [`f4a25b0`](conformance/PIN) | 11 of 11 | [`conformance/PIN`](conformance/PIN) is the authoritative record of which upstream ref the vectors came from. -Not ported yet: `resolveQuests`, `progression` and `nextContinuations`. Their vectors are vendored but no test runs them. - ## Install Install this package via the Unity Package Manager (UPM). @@ -72,6 +70,9 @@ var nextNodeId = outcome.GetValueOrDefault("nextNodeId"); // null on a terminal - **`onEnter` effects are not applied for you.** `StepDialogue` returns them; firing them is the caller's job, on first arrival only. Applying them on every render double-counts on a rewind. - **A node with no choices is not necessarily over.** If it has `next`, call `AdvanceNode` — that's a listen-only beat. Treating it as the end silently truncates ambient chains. - **Passive checks never roll.** Show or hide a passive-check choice with `PassiveCheckPasses` (`skill + Σbonus >= difficulty`), so a check modifier means the same thing in both modes. +- **Run `ResolveQuests` after every state change.** It fires quest stage `onComplete` and outcome `effects` whose condition holds, once each, and records them in `QuestFired`. It never advances a stage for you. +- **Levelling is derived, not stored.** `Xp` is total-earned; `LevelForXp`, `PointsEarned` and `AvailablePoints` derive from it. `InvestSkillPoint` is a guarded player action, not an effect; call `RecomputeSkills` on load so checks read preset + invested skill. +- **When a scene ends, ask `NextContinuations`.** A pending cutscene comes first, then any character routed with `set_active_dialogue`, otherwise each character's best offer. Consume them with `ClearPendingCutscene` / `ClearActiveDialogue`. - **Which dialogue a character opens is `ResolveCharacterDialogue`.** It ranks the dialogues whose `offer` names that character (priority tier, then condition specificity, then id); pass your visited set so non-replayable dialogues are not offered twice. ## Verify it yourself diff --git a/Runtime/Runtime.cs b/Runtime/Runtime.cs index e0a4ca1..bd86317 100644 --- a/Runtime/Runtime.cs +++ b/Runtime/Runtime.cs @@ -700,6 +700,223 @@ private static bool BetterOffer(Dictionary a, Dictionary "active_dialogue__" + characterId; + + // Clears a character's forced-dialogue flag once its forced dialogue is consumed. + public static State ClearActiveDialogue(string characterId, State state) + { + var next = state.Copy(); + next.Flags[ActiveDialogueFlag(characterId)] = false; + return next; + } + + public static State ClearPendingCutscene(State state) + { + var next = state.Copy(); + next.PendingCutscene = null; + return next; + } + + // What to offer when the current scene ends. Each entry is + // { kind: "cutscene", cutscene } or { kind: "dialogue", characterId, dialogue, queued }. + // A pending cutscene comes first. Then forced routing: characters whose + // active_dialogue__ flag is set and whose winning offer reads that flag + // (queued, visited ignored); if any, only those. Otherwise discovery: + // each character's best eligible offer with the visited filter. The + // current dialogue is excluded and ids are de-duplicated. + public static List> NextContinuations(State state, Dictionary project, IEnumerable visited, string currentDialogueId) + { + var seen = new HashSet { currentDialogueId }; + var dialogues = project.TryGetValue("dialogues", out var dObj) && dObj is Dictionary dd ? dd : new Dictionary(); + var characters = project.TryGetValue("characters", out var cObj) && cObj is Dictionary cd ? cd : new Dictionary(); + + var pending = new List>(); + if (state.PendingCutscene != null + && project.TryGetValue("cutscenes", out var csObj) && csObj is Dictionary cutscenes + && cutscenes.TryGetValue(state.PendingCutscene, out var cutscene) && cutscene is Dictionary) + { + pending.Add(new Dictionary { { "kind", "cutscene" }, { "cutscene", cutscene } }); + } + + var forced = new List>(); + foreach (var chObj in characters.Values) + { + if (!(chObj is Dictionary character)) continue; + string charId = character.TryGetValue("id", out var cid) ? cid?.ToString() ?? "" : ""; + string flag = ActiveDialogueFlag(charId); + if (!(state.Flags.TryGetValue(flag, out var set) && set)) continue; + var resolved = ResolveCharacterDialogue(state, character, project)?.ToString(); + if (resolved == null || !(dialogues.TryGetValue(resolved, out var dlgObj) && dlgObj is Dictionary dialogue)) continue; + var offer = dialogue.TryGetValue("offer", out var oObj) ? oObj as Dictionary : null; + object when = null; + offer?.TryGetValue("when", out when); + if (!ConditionReadsFlag(when, flag)) continue; + if (seen.Add(resolved)) + { + forced.Add(new Dictionary { { "kind", "dialogue" }, { "characterId", charId }, { "dialogue", dialogue }, { "queued", true } }); + } + } + if (forced.Count > 0) return pending.Concat(forced).ToList(); + + var discovered = new List>(); + foreach (var chObj in characters.Values) + { + if (!(chObj is Dictionary character)) continue; + string charId = character.TryGetValue("id", out var cid) ? cid?.ToString() ?? "" : ""; + var resolved = ResolveCharacterDialogue(state, character, project, visited ?? new List())?.ToString(); + if (resolved == null || !(dialogues.TryGetValue(resolved, out var dlgObj) && dlgObj is Dictionary dialogue)) continue; + if (seen.Add(resolved)) + { + discovered.Add(new Dictionary { { "kind", "dialogue" }, { "characterId", charId }, { "dialogue", dialogue }, { "queued", false } }); + } + } + return pending.Concat(discovered).ToList(); + } + + // Does this gate require `flag` to be true, as a top-level conjunct + // (an `all` flattened)? The test for a forced offer. + private static bool ConditionReadsFlag(object conditionObj, string flag) + { + if (!(conditionObj is Dictionary c)) return false; + string type = c.TryGetValue("type", out var t) ? t as string : null; + if (type == "all") + { + return c.TryGetValue("of", out var ofObj) && ofObj is IEnumerable of && of.Any(x => ConditionReadsFlag(x, flag)); + } + return type == "flag" + && c.TryGetValue("flag", out var f) && f as string == flag + && c.TryGetValue("value", out var v) && v is bool b && b; + } + + // ---------------------------------------------------------- resolveQuests -- + + public static string QuestFiredKey(string questId, string kind, string id) => $"{questId}/{kind}/{id}"; + + // Fires quest stage onComplete / outcome effects whose completeWhen / + // reachedWhen holds, once each (recorded in QuestFired), to a fixpoint. + // Order: quests by ordinal id, then stages, then outcomes in array + // order. Effects with no condition never auto-fire; QuestStages is + // never written. Returns { state, firings: [{ quest, kind, id, effects }] }. + public static Dictionary ResolveQuests(State state, Dictionary project) + { + var quests = project.TryGetValue("quests", out var qObj) && qObj is Dictionary qd ? qd : new Dictionary(); + var questIds = quests.Keys.ToList(); + questIds.Sort(string.CompareOrdinal); + + var current = state; + var firings = new List(); + bool changed = true; + while (changed) + { + changed = false; + foreach (var qid in questIds) + { + if (!(quests[qid] is Dictionary quest)) continue; + foreach (var item in Items(quest, "stages")) + { + var next = TryFire(current, project, qid, "stage", item, "completeWhen", "onComplete", firings); + if (next != null) { current = next; changed = true; } + } + foreach (var item in Items(quest, "outcomes")) + { + var next = TryFire(current, project, qid, "outcome", item, "reachedWhen", "effects", firings); + if (next != null) { current = next; changed = true; } + } + } + } + return new Dictionary { { "state", current }, { "firings", firings } }; + } + + private static IEnumerable> Items(Dictionary quest, string key) + { + return quest.TryGetValue(key, out var obj) && obj is IEnumerable list + ? list.OfType>() + : Enumerable.Empty>(); + } + + // One item's firing attempt: the new state if it fired, else null. + private static State TryFire(State state, Dictionary project, string questId, string kind, Dictionary item, string whenKey, string effectsKey, List firings) + { + if (!(item.TryGetValue(effectsKey, out var effObj) && effObj is List effects && effects.Count > 0)) return null; + if (!item.TryGetValue(whenKey, out var when)) return null; + string id = item.TryGetValue("id", out var idObj) ? idObj?.ToString() ?? "" : ""; + string key = QuestFiredKey(questId, kind, id); + if (state.QuestFired.Contains(key)) return null; + if (!Evaluate(when as Dictionary, state, project)) return null; + // Effects are non-empty, so ApplyEffects has already copied. + var next = ApplyEffects(effects, state, project); + next.QuestFired.Add(key); + firings.Add(new Dictionary { { "quest", questId }, { "kind", kind }, { "id", id }, { "effects", effects } }); + return next; + } + + // ------------------------------------------------------------ progression -- + // Xp is total-earned and monotonic; levels and points derive from it. + // `config` is progression.json; `skills` is the optional skills + // registry (id -> skill) for per-skill `max` caps. + + public static int LevelForXp(float xp, Dictionary config) + { + int level = 0; + if (config.TryGetValue("xpThresholds", out var tObj) && tObj is List thresholds) + { + for (int i = 0; i < thresholds.Count; i++) + { + if (xp >= Convert.ToSingle(thresholds[i])) level = i; + else break; + } + } + return level; + } + + public static float PointsEarned(float xp, Dictionary config) + { + float perLevel = config.TryGetValue("pointsPerLevel", out var p) ? Convert.ToSingle(p) : 0f; + return LevelForXp(xp, config) * perLevel; + } + + public static float SkillCap(string skillId, Dictionary config, Dictionary skills = null) + { + if (skills != null && skills.TryGetValue(skillId, out var sObj) && sObj is Dictionary skill && skill.TryGetValue("max", out var max)) + return Convert.ToSingle(max); + return config.TryGetValue("maxSkill", out var m) ? Convert.ToSingle(m) : 0f; + } + + public static float EffectiveSkill(string skillId, State state, Dictionary config, Dictionary skills = null) + { + float preset = config.TryGetValue("startingSkills", out var ssObj) && ssObj is Dictionary ss && ss.TryGetValue(skillId, out var pv) ? Convert.ToSingle(pv) : 0f; + float invested = state.SkillPointsSpent.TryGetValue(skillId, out var iv) ? iv : 0f; + return Math.Min(preset + invested, SkillCap(skillId, config, skills)); + } + + public static float AvailablePoints(State state, Dictionary config) + { + return PointsEarned(state.Xp, config) - state.SkillPointsSpent.Values.Sum(); + } + + // Skills = EffectiveSkill for every preset or invested skill; others untouched. + public static State RecomputeSkills(State state, Dictionary config, Dictionary skills = null) + { + var next = state.Copy(); + var ids = new HashSet(state.SkillPointsSpent.Keys); + if (config.TryGetValue("startingSkills", out var ssObj) && ssObj is Dictionary ss) ids.UnionWith(ss.Keys); + foreach (var id in ids) next.Skills[id] = EffectiveSkill(id, state, config, skills); + return next; + } + + // Spends one point. A player action, not an effect: a no-op unless a + // point is available and the skill is below its ceiling. + public static State InvestSkillPoint(State state, string skillId, Dictionary config, Dictionary skills = null) + { + if (AvailablePoints(state, config) <= 0) return state; + if (EffectiveSkill(skillId, state, config, skills) >= SkillCap(skillId, config, skills)) return state; + var next = state.Copy(); + next.SkillPointsSpent[skillId] = (next.SkillPointsSpent.TryGetValue(skillId, out var v) ? v : 0f) + 1f; + return RecomputeSkills(next, config, skills); + } + // ------------------------------------------------------ speaker / portrait -- public static object EffectiveSpeakerId(Dictionary dialogue, Dictionary node)