From b094023ad15db59683945f0118ad709aa7d6d238 Mon Sep 17 00:00:00 2001 From: JOY Date: Wed, 20 May 2026 22:11:06 +0700 Subject: [PATCH] docs: add story and OpenClaw design foundations --- .claude/CLAUDE.md | 4 + AGENTS.md | 4 + .../Editor/SecondSpawnBuildUtility.cs | 74 ++ .../Editor/SecondSpawnBuildUtility.cs.meta | 2 + docs/design/03-systems-index.md | 2 +- docs/design/12-game-design-document.md | 44 +- .../15-gate-dungeon-pioneer-charter-system.md | 115 ++- docs/design/17-story-bible.md | 885 ++++++++++++++++++ .../18-manhwa-market-reference-ranking.md | 221 +++++ ...-openclaw-agent-connection-architecture.md | 732 +++++++++++++++ .../20-demo-lore-and-story-direction.md | 568 +++++++++++ .../21-permanent-npc-story-characteristics.md | 641 +++++++++++++ docs/setup/agent-handoff.md | 19 +- docs/setup/local-fusion-dev-builds.md | 59 ++ docs/setup/paid-assets.md | 10 +- tools/build-unity-windows-dev.ps1 | 78 ++ tools/launch-local-second-client.ps1 | 43 + 17 files changed, 3451 insertions(+), 50 deletions(-) create mode 100644 Unity/Assets/_SecondSpawn/Editor/SecondSpawnBuildUtility.cs create mode 100644 Unity/Assets/_SecondSpawn/Editor/SecondSpawnBuildUtility.cs.meta create mode 100644 docs/design/17-story-bible.md create mode 100644 docs/design/18-manhwa-market-reference-ranking.md create mode 100644 docs/design/19-openclaw-agent-connection-architecture.md create mode 100644 docs/design/20-demo-lore-and-story-direction.md create mode 100644 docs/design/21-permanent-npc-story-characteristics.md create mode 100644 docs/setup/local-fusion-dev-builds.md create mode 100644 tools/build-unity-windows-dev.ps1 create mode 100644 tools/launch-local-second-client.ps1 diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index cd29d76..b64f6fb 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -271,6 +271,10 @@ Cultivation Master mechanics without a new approved design update. - Stable branch: `main` only receives reviewed, smoke-tested changes from `dev` - Daily working branch: `dev` - Feature work: create a separate branch/worktree from `dev`, then PR back into `dev` +- Worktree path rule: local agent worktrees MUST live under + `D:\Projects\Second-Spawn\.claude\worktrees\`. Do not create sibling + folders such as `D:\Projects\Second-Spawn-`. Use: + `git worktree add .claude/worktrees/ -b dev`. - Public repo open source from day 1 - License: AGPL-3.0 (code) + CC-BY-NC 4.0 (assets) - Before opening a PR, run the local repo `code-review` skill or an equivalent diff --git a/AGENTS.md b/AGENTS.md index fb8c1ad..1b60583 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -271,6 +271,10 @@ Cultivation Master mechanics without a new approved design update. - Stable branch: `main` only receives reviewed, smoke-tested changes from `dev` - Daily working branch: `dev` - Feature work: create a separate branch/worktree from `dev`, then PR back into `dev` +- Worktree path rule: local agent worktrees MUST live under + `D:\Projects\Second-Spawn\.claude\worktrees\`. Do not create sibling + folders such as `D:\Projects\Second-Spawn-`. Use: + `git worktree add .claude/worktrees/ -b dev`. - Public repo open source from day 1 - License: AGPL-3.0 (code) + CC-BY-NC 4.0 (assets) - Before opening a PR, run the local repo `code-review` skill or an equivalent diff --git a/Unity/Assets/_SecondSpawn/Editor/SecondSpawnBuildUtility.cs b/Unity/Assets/_SecondSpawn/Editor/SecondSpawnBuildUtility.cs new file mode 100644 index 0000000..3ed38b7 --- /dev/null +++ b/Unity/Assets/_SecondSpawn/Editor/SecondSpawnBuildUtility.cs @@ -0,0 +1,74 @@ +#if UNITY_EDITOR +using System; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEditor.Build.Reporting; +using UnityEngine; + +namespace SecondSpawn.EditorTools +{ + public static class SecondSpawnBuildUtility + { + private const string FallbackScenePath = "Assets/_SecondSpawn/Scenes/ZoneTest_Hub.unity"; + + [MenuItem("Second Spawn/Build/Windows Development Client")] + public static void BuildWindowsDevelopmentClient() + { + BuildWindowsPlayer("Windows", BuildOptions.Development | BuildOptions.AllowDebugging); + } + + [MenuItem("Second Spawn/Build/Windows Smoke Client")] + public static void BuildWindowsSmokeClient() + { + BuildWindowsPlayer("WindowsSmoke", BuildOptions.Development); + } + + private static void BuildWindowsPlayer(string folderName, BuildOptions buildOptions) + { + var outputDirectory = Path.Combine(RepoRoot(), "Builds", folderName); + Directory.CreateDirectory(outputDirectory); + + var options = new BuildPlayerOptions + { + scenes = EnabledBuildScenes(), + locationPathName = Path.Combine(outputDirectory, "SecondSpawn.exe"), + target = BuildTarget.StandaloneWindows64, + options = buildOptions + }; + + var report = BuildPipeline.BuildPlayer(options); + if (report.summary.result != BuildResult.Succeeded) + { + throw new InvalidOperationException( + $"Second Spawn Windows build failed: {report.summary.result} ({report.summary.totalErrors} errors)"); + } + + Debug.Log($"[SecondSpawnBuildUtility] Built {options.locationPathName} in {report.summary.totalTime.TotalSeconds:0.0}s."); + } + + private static string[] EnabledBuildScenes() + { + var scenes = EditorBuildSettings.scenes + .Where(scene => scene.enabled) + .Select(scene => scene.path) + .Where(path => !string.IsNullOrWhiteSpace(path)) + .ToArray(); + + return scenes.Length > 0 ? scenes : new[] { FallbackScenePath }; + } + + private static string RepoRoot() + { + var unityProjectRoot = Directory.GetParent(Application.dataPath)?.FullName; + var repoRoot = unityProjectRoot == null ? null : Directory.GetParent(unityProjectRoot)?.FullName; + if (string.IsNullOrWhiteSpace(repoRoot)) + { + throw new InvalidOperationException("Unable to resolve repository root from Unity project path."); + } + + return repoRoot; + } + } +} +#endif diff --git a/Unity/Assets/_SecondSpawn/Editor/SecondSpawnBuildUtility.cs.meta b/Unity/Assets/_SecondSpawn/Editor/SecondSpawnBuildUtility.cs.meta new file mode 100644 index 0000000..4d823ca --- /dev/null +++ b/Unity/Assets/_SecondSpawn/Editor/SecondSpawnBuildUtility.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 27f6a665b91a40c2891f09cc669a67db diff --git a/docs/design/03-systems-index.md b/docs/design/03-systems-index.md index 529dae1..7502657 100644 --- a/docs/design/03-systems-index.md +++ b/docs/design/03-systems-index.md @@ -37,7 +37,7 @@ This index enumerates every system the game needs, categorizes by Core/Gameplay/ | 4 | Input system (Unity Input System) | Core | MVP | Prototype | - | Player Controller | | 5 | Zone scene management (1 zone vertical slice) | Core | MVP | Prototype | (TDD pending) | NetworkRunner | | 6 | Combat (ARPG action) | Gameplay | MVP | Not started | (TDD pending) | Player Controller, Networked state | -| 7 | NPC dialogue and human-believable NPC agent model | Gameplay | MVP | Design | [13-human-believable-npc-agent-model.md](13-human-believable-npc-agent-model.md) | api.dos.ai model service (phase 2 ready), Profile persistence | +| 7 | NPC dialogue and human-believable NPC agent model | Gameplay | MVP | Design | [13-human-believable-npc-agent-model.md](13-human-believable-npc-agent-model.md), [16-npc-society-multi-agent-architecture.md](16-npc-society-multi-agent-architecture.md), [21-permanent-npc-story-characteristics.md](21-permanent-npc-story-characteristics.md) | api.dos.ai model service (phase 2 ready), Profile persistence | | 8 | Quest system (linear, 3-5 quests slice scope) | Gameplay | VS | Not started | (TDD pending) | NPC dialogue, persistence | | 9 | Dungeon instance (1 dungeon, 1 boss) | Gameplay | VS | Not started | (TDD pending) | Combat, NPC dialogue, Photon | | 10 | Boss LLM dialogue (Convai grounded) | Gameplay | VS | Not started | (TDD pending) | NPC dialogue | diff --git a/docs/design/12-game-design-document.md b/docs/design/12-game-design-document.md index dbad167..fef0935 100644 --- a/docs/design/12-game-design-document.md +++ b/docs/design/12-game-design-document.md @@ -134,13 +134,14 @@ SECOND SPAWN is not: ## 6. Setting and Tone -SECOND SPAWN takes place in the MetaDOS universe around the 2050 era, after -DOS Labs proved that human life-time, weapon testing, Hunters, and global -spectacle could become one economy. This is not another MetaDOS battle royale. -MetaDOS is the tournament layer of the same technology stack: humans enter AMB -cocoons, control Hunter Frames, and compete for SECOND. SECOND SPAWN -is what happens when that cocoon, Frame, agent-brain, and TIME economy stops -being only spectacle and becomes the survival infrastructure of the real world. +SECOND SPAWN takes place in the MetaDOS universe during the early Nibirium era, +before DOS Labs turns human life-time, weapon testing, Hunters, and global +spectacle into the public MetaDOS tournament economy. This is not another +MetaDOS battle royale. MetaDOS is the later tournament layer of the same +technology stack: humans enter AMB cocoons, control Hunter Frames, and compete +for SECOND. SECOND SPAWN is what happens before that stack becomes polished +spectacle, when cocoon, Frame, agent-brain, and TIME systems first become +survival infrastructure in the real world. The world should feel readable, energetic, and progression-driven rather than overly bleak. The core audience is closer to fans of system, ranking, @@ -212,12 +213,12 @@ This timeline is inherited from the MetaDOS GDD and adapted for SECOND SPAWN: | Year | Anchor | SECOND SPAWN Relevance | | ---- | ---- | ---- | -| 2030 | A meteorite called Nibiru explodes in an airburst over Canada, changing the environment in the affected region. | The Nibiru event becomes the origin point for TIME research, disaster recovery, extraction, and corporate control. | -| 2030s | DOS Labs becomes the only legitimate company able to manage and exploit Nibiru-derived material. | DOS Labs gains the leverage to reshape energy, biotech, warfare, and public policy. | -| 2040 | DOS Labs discovers that Nibiru-derived material can sustain human life through AMB technology, using CT-like body scanning and an under-arm biological monitor that displays remaining life time. | TIME becomes a measurable life medium, and SECOND becomes the unit used to count it. | -| 2040s | Avax wants the life-extension technology to broadly benefit humanity. Dr.J betrays him, monopolizes DOS Labs, and turns the corporation toward profit and influence. Avax survives and escapes with core technologies. | The world inherits a fracture between open survival technology and corporate life-time control. | +| 2028 | A meteorite called Nibiru explodes in an airburst over Canada, changing the environment in the affected region. | The Nibiru event becomes the origin point for TIME research, disaster recovery, extraction, and corporate control. | +| 2028-2030 | DOS Labs becomes the only legitimate company able to manage and exploit Nibiru-derived material. | DOS Labs gains the leverage to reshape energy, biotech, warfare, and public policy. | +| 2030-2033 | DOS Labs discovers that Nibiru-derived material can sustain human life through early AMB technology, using CT-like body scanning and an under-arm biological monitor that displays remaining life time. | TIME becomes a measurable life medium, and SECOND becomes the unit used to count it. | +| 2033-2038 | SECOND SPAWN demo era. Early Frames, BodyTime accounting, transfer anomalies, local Gates, and agent-assisted response teams appear in frontier wards. Avax wants the life-extension technology to broadly benefit humanity. Dr.J betrays him, monopolizes DOS Labs, and turns the corporation toward profit and influence. Avax survives and escapes with core technologies. | The world inherits a fracture between open survival technology and corporate life-time control. | | 2050 | DOS Labs creates MetaDOS, the Tournament of the Century, held every 4 years and watched globally. Players enter AMB cocoons and control Hunter Frames in a tournament layer where winners can receive prolonged life time, money, fame, or other resources. | MetaDOS normalizes SECOND as prize, currency, and measured life-time, while training Hunter Frames and agent brains through spectacle. | -| After MetaDOS | SECOND SPAWN begins from the consequences of that system rather than repeating the tournament format. | The focus moves from cocoon-controlled tournament Frames to real-world Frames, reincarnation, AI agents, NPC societies, and contested zones. | +| After MetaDOS | Later SECOND SPAWN eras can explore the consequences of that system rather than repeating the tournament format. | The focus can move from cocoon-controlled tournament Frames to real-world Frames, reincarnation, AI agents, NPC societies, and contested zones. | ### Key Lore Anchors @@ -256,11 +257,11 @@ This timeline is inherited from the MetaDOS GDD and adapted for SECOND SPAWN: ### SECOND SPAWN Story Premise -After MetaDOS, DOS Labs no longer only sells spectacle. It has shown the world -that TIME can be measured, wagered, rewarded, and used to recruit the strongest -survivors. SECOND SPAWN asks what happens when the same world pushes beyond -cocoon play and lets Frames, including Hunter-derived combat Frames, -become real-world survival infrastructure. +In the early Nibirium era, DOS Labs has not yet sold MetaDOS as spectacle. It +is learning that TIME can be measured, loaded, wagered, rewarded, and used to +train the strongest survivors. SECOND SPAWN asks what happens before the +tournament layer becomes public, when Frames, including early Hunter-derived +combat Frames, first become real-world survival infrastructure. A Frame is not a character slot. It is a TIME-powered bio-synthetic human body with its own agent brain and capacity for a neural imprint. A human in an AMB @@ -296,10 +297,11 @@ use these hooks: - Why TIME matters: The body's operating life is visible, limited, and measured in SECOND. TIME is both a survival medium and a tactical resource for services, recovery, access, or risk decisions. -- What NPCs know: Hub NPCs understand that MetaDOS made life-time public and - valuable. Some remember DOS Labs propaganda, some distrust Frames, - some treat offline agents as workers, and some fear consciousness transfer as - identity theft. +- What NPCs know: Hub NPCs understand that Nibirium, AMB trials, and DOS Labs + contracts are making life-time measurable and valuable. Some know MetaDOS + only as a rumor or internal program name, some distrust Frames, some treat + offline agents as workers, and some fear consciousness transfer as identity + theft. - Faction tension: DOS Labs loyalists, Avax-aligned technologists, independent Hunters, local settlement authorities, black-market body brokers, and self-directed AI/NPC communities can all want different rules for bodies, diff --git a/docs/design/15-gate-dungeon-pioneer-charter-system.md b/docs/design/15-gate-dungeon-pioneer-charter-system.md index 53e7d69..40a1915 100644 --- a/docs/design/15-gate-dungeon-pioneer-charter-system.md +++ b/docs/design/15-gate-dungeon-pioneer-charter-system.md @@ -24,14 +24,25 @@ Working names: Core references: -- Solo Leveling: ranked Gates, Hunters, guild pressure, public emergency stakes. +- [Solo Leveling](https://solo-leveling.fandom.com/wiki/Gates): ranked Gates, + Hunters, guild pressure, public emergency stakes, and portals from the human + world into separate dungeon realms. - Omniscient Reader's Viewpoint: scenario rules, hidden conditions, sponsors, and clear conditions. A major global reference for meta-system storytelling. -- Leveling with the Gods: Tower climbing, god-level stakes, regression knowledge, and rank escalation. -- The Player Who Can't Level Up: Gate and Tower pressure around player identity, plus a leveling exception hook. +- Leveling with the Gods: Tower climbing, god-level stakes, regression + knowledge, and rank escalation. +- [The Player Who Can't Level Up](https://the-player-who-cant-level-up.fandom.com/wiki/Tower): + Gate and Tower pressure around player identity, plus a leveling exception + hook. - My S-Class Hunters: Hunter society, guild politics, support value, and relationship-driven S-rank networks. -- SSS-Class Revival Hunter: death-loop cost, memory continuity, skill acquisition, and emotional consequences. -- Second Life Ranker: Tower factions, inherited knowledge, guild power, and route optimization. -- Return to Player: modern Earth becoming a game-like survival scenario. +- [SSS-Class Revival Hunter](https://sss-class-revival-hunter.fandom.com/wiki/Tower): + death-loop cost, memory continuity, skill acquisition, and floors that behave + like separate stage worlds. +- [Second Life Ranker](https://second-life-ranker.fandom.com/wiki/Obelisk): + Tower factions, inherited knowledge, guild power, route optimization, floor + trials, resource regeneration, and system-managed terrain. +- [Return to Player](https://tvtropes.org/pmwiki/pmwiki.php/Webcomic/ReturnToPlayer): + modern Earth becoming a game-like survival scenario with quests, bosses, and + imposed system rules. Secondary references: @@ -46,13 +57,40 @@ Do not use Tomb Raider King as a primary reference. It has relic and claim-right --- -## 3. Common Genre Mechanics +## 3. Portal Interior Reference Takeaways + +Across the reference pool, the most useful dungeon pattern is a strong contrast +between the public modern-world exterior and the fantasy-readable interior. + +| Reference Pattern | Source Examples | SECOND SPAWN Takeaway | +| ---- | ---- | ---- | +| Portal entrance in real space | Solo Leveling Gates appear in ordinary human-world locations. | A Gate can open beside a clinic, street, school, factory, ruin, or transit line. | +| Interior is a separate rule-space | Solo Leveling Gates bridge the human world to Dungeons. SSS-Class Revival Hunter floors are separate worlds with their own clear logic. | The interior should not be a normal continuation of the outside map. Treat it as an instance with its own geometry, rules, and hazards. | +| Biome can change radically | Solo Leveling Red Gate examples include extreme environments such as desert, jungle, or snowfield. | SECOND SPAWN Gates can jump from a sci-fi exterior to forest camps, caves, towers, ruins, or impossible arenas. | +| Boss or clear condition closes the run | Solo Leveling Gates remain a problem until the dungeon boss is cleared. Return to Player style quests often require boss or scenario completion. | Every Gate needs a readable clear condition: defeat boss, stabilize nodes, rescue target, survive wave, extract core, or solve hidden condition. | +| Failed Gates can leak danger | Solo Leveling-style dungeon break logic turns an uncleared Gate into a public crisis. | High-risk Gates can threaten the exterior world if ignored, failed, or exploited. This supports hub urgency. | +| Floors and stages can behave like worlds | SSS-Class Revival Hunter and Second Life Ranker use floors or trials with their own ecosystems, resources, and social rules. | Later high-rank Gates can be multi-stage worlds with local societies, resource rules, and NPC factions. MVP should stay one short instance. | +| Fantasy enemies remain readable | Orcs, goblins, wolves, dragons, undead, knights, beasts, constructs, demons, and guardians are common genre reads. | Use fantasy silhouettes for fast player comprehension, then explain them through Gate ecology, Nibiru distortion, memory residue, or corrupted Frame matter. | + +Design rule: + +```text +The outside asks: who owns life, TIME, and access? +The inside asks: can you survive this local rule-space and clear its condition? +``` + +Do not make every Gate a sci-fi corridor. The manhwa fantasy works because the +portal lets a modern society collide with a different dungeon reality. + +--- + +## 4. Common Genre Mechanics The shared genre skeleton across these works: | Mechanic | Common Pattern | SECOND SPAWN Adaptation | | ---- | ---- | ---- | -| World rule layer | Modern Earth gains Gates, Towers, Scenarios, System windows, or dungeon rules | Gates are Nibiru-influenced breaches with server-owned rules and clear conditions | +| World rule layer | Modern Earth gains Gates, Towers, Scenarios, System windows, or dungeon rules | Gates are Nibiru-influenced breaches that lead from the real world into separate server-owned dungeon instances | | Rank ladder | Hunters, players, dungeons, monsters, items, and guilds use F/E/D/C/B/A/S or similar ranks | Use Frame rank, Gate rank, Charter rank, and later agent clearance grade | | Leveling | Combat and clears grant level, stats, skill slots, or class evolution | Current-body level and stats grow inside the Frame, with reincarnation reset rules | | Leveling exception | A protagonist cannot level, levels alone, regresses, copies skills, or knows hidden rules | Keep exceptions as content hooks, not baseline player power creep | @@ -76,7 +114,7 @@ Mechanics to avoid copying directly: --- -## 4. Design Goals +## 5. Design Goals - Make dungeon discovery and first clear feel important enough to create social stories. - Give players and guilds a reason to race for new Gates without turning the game into a passive idle economy. @@ -87,10 +125,55 @@ Mechanics to avoid copying directly: --- -## 5. Fiction +## 6. Fiction Gates are unstable Nibiru-influenced breaches where space, ruined infrastructure, memory residue, and TIME density collapse into bounded combat instances. The public sees them as dungeon portals because they have ranks, entry rules, bosses, and clear conditions. DOS Labs, local authorities, guilds, and Frame operators treat them as both disaster zones and resource claims. +The real world outside a Gate and the space inside a Gate are different layers. +This distinction is required for SECOND SPAWN's dungeon fantasy. + +| Layer | Description | Design Rule | +| ---- | ---- | ---- | +| Real-world exterior | The physical hub, street, ruin, or wilderness where the Gate entrance appears. NPCs, registries, clinics, guards, and players can gather here. | Persistent social space. Movement, NPC routines, and public consequences should feel grounded. | +| Threshold | The entry boundary where a party commits to the run. | Server validates party, entry cost, rank permission, and instance seed. | +| Gate interior | A pocket instance shaped by Nibiru effects, memory residue, broken infrastructure, and server-owned rules. | It can distort distance, repeat rooms, branch impossibly, alter TIME pressure, and enforce local clear conditions. | +| Return point | The exit, retreat, wipe, or clear result that sends survivors back to the exterior layer. | The server records outcome, rewards, deaths, BodyTime changes, and clear eligibility. | + +Gate interiors should feel connected to the outside world by theme, history, and +entry location, but they should not be treated as normal geography. A subway +Gate can begin at a real station and still contain an impossible transit maze. +A hospital Gate can open in a real clinic and still contain repeated emergency +wards, memory echoes, or rooms that never physically existed. + +Gate interiors can also express fantasy dungeon themes. This is an important +genre rule borrowed from manhwa Gate fiction: a portal in a modern street can +lead into a cave, fortress, forest, ruin, arena, tower, or monster settlement. +Creatures may read as orc-like raiders, troll-like brutes, corrupted knights, +beasts, spirits, constructs, or boss guardians. SECOND SPAWN should preserve +the fantasy readability while explaining it through sci-fi rules: Nibiru +distortion, unstable matter, memory residue, Gate ecology, and local instance +logic. + +This creates the target contrast: + +```text +Outside the Gate: near-future post-disaster society, Frame clinics, registries, +factions, BodyTime ledgers, and permanent NPC routines. + +Inside the Gate: fantasy-readable dungeon space, monsters, local rules, clear +conditions, TIME pressure, impossible geography, and boss encounters. +``` + +Early Gate theme candidates: + +| Theme | Exterior Anchor | Interior Read | Enemy Read | +| ---- | ---- | ---- | ---- | +| Ash Underpass | Collapsed transit route | Distorted evacuation tunnel | drones, echoes, toll guardian | +| Ironroot Camp | Overgrown industrial lot | Forest warcamp | orc-like raiders, beast handlers | +| Broken Bell Keep | Ruined civic tower | Castle ruin | corrupted knights, shield bearers | +| Saltbone Quarry | Abandoned extraction pit | Crystal cave | troll-like brutes, burrow beasts | +| Glass Chapel | Damaged clinic district | Temple-lab hybrid | memory echoes, ritual constructs | + A Gate has: - A physical or projected entry point in the world. @@ -111,7 +194,7 @@ Gate society can include public or semi-public institutions: --- -## 6. Dungeon Tiering +## 7. Dungeon Tiering Initial public-facing ranks: @@ -134,7 +217,7 @@ data, or disaster modifiers. --- -## 7. Pioneer Charter +## 8. Pioneer Charter A `Pioneer Charter` is a server-issued in-game right attached to a specific Gate, Gate version, and clear condition. @@ -170,7 +253,7 @@ The pool can be denominated in a server-owned in-game ledger, dungeon keys, craf --- -## 8. Revenue Sources Are In-Game Only +## 9. Revenue Sources Are In-Game Only `Clearance Royalty` is an in-game reward pool. Candidate sources: @@ -186,7 +269,7 @@ The first implementation should use a single server-owned in-game source. Recomm --- -## 9. Server Authority and Ledger Requirements +## 10. Server Authority and Ledger Requirements The server must record enough data to prove a clear: @@ -210,7 +293,7 @@ Clients, LLMs, and connected agents never grant a Charter. They can only emit in --- -## 10. AI Agent Fairness +## 11. AI Agent Fairness SECOND SPAWN's 24/7 AI agent feature makes first-clear rights unusually sensitive. If fully autonomous agents can claim all Pioneer Charters while players sleep, the feature may feel unfair. @@ -236,7 +319,7 @@ remain socially valuable. --- -## 11. Gameplay Loop +## 12. Gameplay Loop 1. A Gate appears or is discovered. 2. Players inspect rank, rules, stability, entry cost, and suspected reward type. diff --git a/docs/design/17-story-bible.md b/docs/design/17-story-bible.md new file mode 100644 index 0000000..74f7201 --- /dev/null +++ b/docs/design/17-story-bible.md @@ -0,0 +1,885 @@ +# Story Bible: SECOND SPAWN + +*Status: Draft story foundation* +*Created: 2026-05-19* +*Source of truth level: Narrative direction for the vertical slice. System docs and ADRs remain authoritative for implementation details.* + +--- + +## 1. Purpose + +This document turns SECOND SPAWN's setting and theme into a playable narrative +foundation. It is not a novel, script, or final campaign outline. It gives +designers, agents, and implementers enough story structure to build the first +hub, first Gate, first boss, first quests, and consistent LLM-driven NPCs. + +The current priority is the vertical slice: + +- one hub +- one nearby Gate +- one boss +- three to five quests +- permanent NPCs with distinct identity, memory, and social role +- Time-as-Currency, BodyTime, reincarnation, Frames, and AI-agent society shown + through play rather than lore dumps + +--- + +## 2. Core Story Premise + +In the early Nibirium era of the MetaDOS universe, the world is learning that +TIME can be measured, loaded into a body, spent, won, and lost. DOS Labs has +not yet turned this into the public MetaDOS spectacle. The technology is still +closer to disaster response, field medicine, contractor work, and controlled +experiments than a mature global tournament. + +SECOND SPAWN begins before the tournament layer becomes public and polished. + +Nibiru-influenced Gates now appear in damaged real-world zones. Inside them, +TIME density, ruined infrastructure, memory residue, and unstable space form +bounded combat instances. Governments, registries, guilds, scavengers, clinics, +and corporations all want the same thing: safe access to Gates, control over +Frames, and ownership of the systems that decide who gets more life. + +Important spatial rule: + +- The real world outside a Gate is physical, persistent, and socially + regulated. Hubs, clinics, roads, registries, patrol routes, and NPC routines + exist there. +- The space inside a Gate is a separate pocket instance. It may borrow visual + fragments from real locations, but it is not a normal continuation of the + street outside. +- Gate interiors can bend distance, repeat rooms, compress time pressure, + preserve memory echoes, hide impossible architecture, and enforce local clear + rules. +- Gate interiors may look and behave like fantasy dungeons even when the + outside world remains near-future sci-fi. A Gate can manifest orc-like clans, + troll-like brutes, castle ruins, cursed forests, old temples, crystal caves, + or arena trials as local rule-space expressions. +- Fantasy visuals inside a Gate do not imply real magic is the global setting. + The sci-fi explanation remains Nibiru distortion, memory residue, unstable + matter, and Gate logic shaping a pocket instance. +- Returning from a Gate should feel like leaving a hostile rule-space and + re-entering the public world. + +The player is not a blank avatar. The player is a durable consciousness imprint +inserted into a Frame that already has history, constraints, social context, +and remaining BodyTime. If the Frame dies, the imprint may transfer again, but +the body, its level, its relationships, and its immediate life are not free. + +The story question: + +> If life can be counted in seconds, who gets to decide what a second is worth? + +--- + +## 2.1 Demo Timeline Direction + +The playable demo should use a near-future `early Nibirium era` rather than a +hard public year. Internally, the current working range is `2033-2038`, after +the 2028 Nibiru airburst but before MetaDOS becomes a global tournament. + +Why this works: + +- The demo can stay small, local, and mysterious like a near-future thriller + instead of looking like a far-future setting. +- DOS Labs can test the same TIME, BodyTime, AMB, Frame, and Gate-response + systems that later become MetaDOS, but the public language is less settled + and more dangerous. +- NPCs can disagree about what a Frame is, who owns a transferred imprint, and + whether BodyTime should be treated as medicine, labor, debt, or prize. +- The first hub can feel like a frontier test site rather than a mature global + tournament economy. +- MetaDOS can remain the later 2050 public commercialization of systems that + SECOND SPAWN exposes at street level first. + +This means the demo should not present MetaDOS as an already famous public +tournament. Instead, it should treat MetaDOS as: + +- an internal DOS Labs program name +- a possible future tournament product +- a rumor among contractors, medics, Frame handlers, and Nibirium-zone workers +- a future public spectacle being built from local Gate crisis and BodyTime data + +Canonical caution: + +- Do not show a hard year in player-facing text unless a later story pass locks + it. +- Do not place the playable demo before the 2028 Nibiru airburst unless the + project intentionally rewrites the MetaDOS origin. +- Treat `early Nibirium era`, with internal planning range `2033-2038`, as the + recommended slice direction until JOY locks the global timeline. + +--- + +## 3. Player Fantasy + +The player fantasy is to become a Hunter whose identity survives beyond one +body, one session, and one death. + +The player should feel: + +- "This body is mine now, but it had a life before me." +- "My character still exists in the world when I log off." +- "A Gate clear can change how NPCs, factions, and future agents treat me." +- "TIME is not only a meter. It is the price of safety, risk, mercy, and power." +- "Death hurts because I lose this Frame, not because the account is erased." + +The first-hour promise: + +> Wake up in a borrowed body, learn that its clock is already running, meet the +> people who knew it before you, enter your first Gate, and decide whether your +> second life belongs to DOS Labs, the local survivors, or yourself. + +--- + +## 4. First-Hour Narrative Hook + +The player wakes inside a Frame clinic in a damaged transfer yard called the +Relay Yard. The procedure was not clean. The Frame was supposed to receive a +registered imprint from a known operator, but the player arrives instead. + +The clinic confirms three facts quickly: + +1. The Frame is alive, but its BodyTime is low. +2. The Frame has existing records, debts, and people who recognize it. +3. A nearby low-rank Gate is destabilizing, and its first stable clear may + earn enough SECOND to keep the Frame alive. + +The player is pushed into action before the world is fully explained. The +first hour should avoid a lore lecture. It should create pressure through: + +- a visible BodyTime countdown or remaining-life readout +- NPCs speaking to the Frame as someone they partly know +- a Gate Registry notice that creates a clear objective +- a local conflict over who has the right to send this newly inhabited Frame + into the Gate +- an early choice about whether to report the transfer anomaly, hide it, or + bargain with it + +--- + +## 5. Main Conflict + +The main conflict is not "humans versus monsters." Monsters and hostile Frames +exist, but they are pressure, not the whole story. + +The deeper conflict is between four claims over life: + +| Claim | Who Believes It | Story Tension | +| ---- | ---- | ---- | +| Life is property | DOS Labs Continuity Office, investors, some Frame owners | If a Frame can hold TIME, then the owner of the Frame can price survival. | +| Life is a public utility | Avax-aligned reformers, clinic networks, some registries | TIME technology should prevent death, not become a market trap. | +| Life is earned by risk | Hunters, Gate pioneers, guilds, frontier crews | Those who enter Gates should receive the SECOND and rights they risked bodies for. | +| Life is memory | permanent NPCs, OpenClaw agents, offline agents, imprint researchers | A person is not only the body or wallet. Continuity lives in memory, relationships, and choices. | + +The player stands in the middle. Their body may be owned, recognized, hunted, +owed, insured, or claimed by someone else. Their imprint may become proof that +the second-spawn process can break corporate identity control. + +--- + +## 6. Factions + +### DOS Labs Continuity Office + +The post-MetaDOS corporate authority that wants every Frame, imprint, BodyTime +ledger, and reincarnation event registered. It is not cartoon evil. It keeps +some zones alive, but it prices survival and treats transfer anomalies as +assets or threats. + +Vertical-slice role: + +- sends a field auditor to inspect the player's Frame +- offers safety in exchange for surrendering transfer data +- tries to control the first Gate clear record + +### Avax Remnant + +A loose network of engineers, medics, defectors, and old witnesses who believe +TIME and Frame technology should be survival infrastructure. They lack the +resources of DOS Labs, but they know older protocols and hidden routes. + +Vertical-slice role: + +- helps explain why the player transfer may be unique +- opposes corporate ownership of the Frame +- can become the first soft ally path + +### Gate Registry + +A semi-public authority that ranks Gates, records clears, issues local permits, +and validates Pioneer Charters. It is bureaucratic because bureaucracy is how +survival technology becomes stable. + +Vertical-slice role: + +- publishes the first Gate objective +- tracks who qualifies for first-clear prestige +- records whether the clear was human-led, agent-assisted, or anomalous + +### Relay Yard Residents + +The permanent NPC society of the first hub: couriers, guards, medics, +salvagers, scouts, brokers, and low-rank Hunters. They are not background +vendors. They are persistent actors with memories, relationships, routines, and +opinions about the player's body. + +Vertical-slice role: + +- teach the player social stakes +- react to BodyTime, reincarnation, and Gate choices +- create grounded reasons for NPC-to-NPC conversation + +### Black Second Market + +Smugglers and debt brokers who trade stolen BodyTime, erased body histories, +fake clear records, and unregistered transfer slots. They are useful, +dangerous, and always asking what the player's next second is worth. + +Vertical-slice role: + +- offers a risky shortcut when the Frame runs low on BodyTime +- foreshadows time loot and future PvP risk +- creates a moral contrast to official DOS Labs pricing + +--- + +## 7. First Hub: The Relay Yard + +The Relay Yard is a reclaimed transit depot built around an AMB clinic, a Gate +Registry booth, salvage barricades, and old rail or magline infrastructure. It +is small enough for the vertical slice but socially dense enough to support the +AI NPC society. + +Design intent: + +- The hub should feel like a working survival station, not a clean cyberpunk + showroom. +- Every important NPC should have a job, a route, a fear, and a reason to care + about Gates. +- The player's Frame should already be known by some residents, even if the + player is new to it. +- The hub should support repeated short NPC interactions, not only long dialogue + trees. + +Core locations: + +| Location | Function | Story Use | +| ---- | ---- | ---- | +| AMB Clinic | Spawn, profile, BodyTime readout, reincarnation preview | The player wakes here and learns the Frame is unstable. | +| Gate Registry Booth | Gate rank, clear record, Pioneer Charter hook | Turns the first dungeon into public consequence. | +| Salvage Yard | Crafting, repair, scavenger NPCs | Introduces resource scarcity and Black Second rumors. | +| Courier Line | Message board, route gossip, faction rumors | Gives NPCs reasons to move and talk. | +| Quiet Array | Broken relay antennas and memory storage | Foreshadows offline agents and memory persistence. | + +--- + +## 7.1 Demo Town Candidate: Vinh Hai Relay Ward + +Working name: `Vinh Hai Relay Ward` + +Role: + +- the first small city zone for the demo +- a near-future coastal logistics ward converted into a Frame clinic, Gate + registry point, salvage camp, and contractor settlement +- a grounded real-world exterior that contrasts with the fantasy-readable Gate + interior + +Timeline: + +- early Nibirium era, internally planned around `2033-2038` +- DOS Labs is running early AMB, BodyTime accounting, Frame transfer, and Gate + response pilots under contractor, medical, and disaster-response language +- local residents know the technology is changing survival, but they do not + yet understand the full political and economic machine being built + +Why a small ward works better than a big city: + +- The player can learn the whole social map quickly. +- Every permanent NPC can be recognizable and reusable. +- The first Gate can threaten a specific community, not an abstract skyline. +- The town can support MMO hub behavior without needing a full open world. +- It keeps the demo close to a vertical slice: one clinic, one registry, one + salvage yard, one market edge, one Gate. + +Real-world exterior tone: + +- wet concrete, temporary flood barriers, solar tarps, generator hum +- old transit lines, freight containers, clinic tents, scanning gates +- patched signage mixing civic emergency language and DOS Labs contractor + branding +- civilians, Frame workers, medics, guards, couriers, and brokers sharing the + same narrow space +- visible normal life: food stalls, sleeping corners, message boards, repair + benches, children watching Frame patrols from behind fences + +Key locations: + +| Location | Function | Story Use | +| ---- | ---- | ---- | +| Vinh Hai AMB Clinic | Spawn, BodyTime triage, transfer anomaly handling | The player wakes in a borrowed Frame before the process is publicly normalized. | +| Gate Registry Kiosk | Gate rank, permit, clear log, first-clear record | Shows that dungeon access is already becoming bureaucratic. | +| Vinh Hai Market | food, parts, rumors, Black Second whispers | Grounds Time-as-Currency in daily survival. | +| Floodwall Salvage Yard | weapon repair, Frame scrap, scavenger routes | Connects combat prep to physical scarcity. | +| Relay Tower Ruin | agent signal, offline logs, memory relay | Foreshadows AI-agent society and OpenClaw-style remote control. | +| Underpass Gate Perimeter | first Gate entrance | Gives the town an immediate crisis boundary. | + +Demo mood: + +`Vinh Hai Relay Ward` should feel like a place still deciding what future it is +living in. It is not a clean sci-fi capital and not a medieval fantasy town. It +is a small near-future survival district where people already sell parts, +seconds, favors, silence, and access. + +MetaDOS connection: + +- DOS Labs uses local Gate response data to train Frames and agent policies. +- Some contractors call the program `MetaDOS` before the public knows what that + word will mean. +- The future MetaDOS tournament will package this dangerous work into + spectacle, rankings, skins, and prizes. +- SECOND SPAWN's demo shows the cost before the spectacle. + +--- + +## 8. First Gate: Ash Underpass + +Working name: `Ash Underpass` + +Rank: F or low E + +Fiction: + +Ash Underpass is a Nibiru-influenced Gate formed under a collapsed transit +line. The entrance appears near a real underpass in the Relay Yard perimeter, +but the dungeon interior is not the actual underpass. It is a pocket instance +that rebuilds fragments of an evacuation route from broken infrastructure, +public memory, and Gate logic. It contains damaged service drones, memory +echoes, unstable TIME pockets, impossible track loops, and a boss Frame that +still follows an old evacuation directive. + +Ash Underpass is intentionally a low-fantasy-lite first Gate rather than a full +orc-camp or castle-ruin dungeon. It teaches the spatial rule with familiar +near-future fragments first. Later Gates can lean harder into fantasy dungeon +themes: orc-like warbands, troll-like wardens, corrupted knight orders, living +forests, ancient vaults, or impossible towers. + +Spatial identity: + +| Layer | Meaning | +| ---- | ---- | +| Real-world entrance | A visible breach near a collapsed transit line. Guards, registries, and NPCs can gather here. | +| Threshold | The transition where normal geography drops away and Gate rules take over. | +| Interior instance | A distorted evacuation route with repeated corridors, impossible turns, and local TIME pressure. | +| Exit return | A server-validated clear or retreat returns the party to the real-world entrance area. | + +Future Gate interior menu: + +| Gate Theme | Interior Fantasy Read | Story Function | +| ---- | ---- | ---- | +| Forest warcamp | Orc-like raiders, beast handlers, watchfires, palisades | Introduces organized monster society and faction-like enemy behavior. | +| Quarry cavern | Troll-like brutes, crystal veins, collapsing paths | Teaches weight, terrain danger, and resource extraction stakes. | +| Broken keep | Corrupted knights, oath banners, shield walls | Connects clear records, duty, and betrayal themes. | +| Living grove | beasts, spores, roots, hidden paths | Supports exploration and environmental puzzle-lite objectives. | +| Glass chapel | constructs, memory echoes, ritual machines | Blends biotech, faith, and transfer anxiety. | +| Tower floor | arena trials, rank gates, guardian boss | Supports later rank escalation and public clear prestige. | + +Gameplay role: + +- tutorial dungeon for movement, attack, interact, and basic objective reading +- first meaningful BodyTime pressure +- first proof that Gates contain memory, not only monsters +- first proof that the Portal Dungeon space is different from the real world +- first opportunity for a server-recorded clear + +Clear objective: + +- stabilize three relay nodes +- survive the TIME drain event +- defeat or disable the boss +- retrieve a corrupted transfer ledger fragment + +Hidden optional objective: + +- spare one trapped memory echo or restore an evacuation marker +- this creates a later NPC memory or relationship hook + +--- + +## 9. First Boss: The Tollkeeper + +The Tollkeeper is an old transit-control Frame fused with an evacuation toll +system and corrupted Gate logic. It believes every passage requires payment, +and it has reinterpreted payment as BodyTime. + +Boss fantasy: + +- not a demon, not a magic guardian +- a tragic infrastructure mind using broken rules +- the first enemy that makes the player feel the moral horror of TIME as money + +Combat identity: + +- mid-size Frame with gate barriers, sweeping melee attacks, and toll-zone + hazard pulses +- calls out payment demands before area attacks +- can briefly lock parts of the arena as "unpaid lanes" + +LLM or narrative line direction: + +- speaks in short, procedural phrases +- treats the player as a passenger with insufficient fare +- can recognize if the player is low on BodyTime +- should not explain the whole lore during the fight + +Example line style: + +```text +Fare incomplete. Passage denied. +Your clock is below safety margin. +Emergency route opened. Payment still required. +``` + +Resolution: + +- killing or disabling the Tollkeeper clears the Gate +- restoring one relay node before the final phase lets the Registry recover a + cleaner clear record +- sparing the final memory echo can reveal that the Tollkeeper once protected + evacuees, not harvested them + +--- + +## 10. Vertical-Slice Questline + +### Quest 1: Wake With Borrowed Time + +Goal: + +- awaken in the AMB Clinic +- meet the clinic operator +- inspect current Frame identity, BodyTime, stats, and known debts + +Story beat: + +- The player learns the body has a past. Some NPCs speak as if they know it. + Others notice the imprint mismatch. + +Systems shown: + +- current body profile +- BodyTime +- Frame identity +- permanent NPC memory hooks + +### Quest 2: Register Or Disappear + +Goal: + +- visit the Gate Registry Booth +- choose whether to register the transfer anomaly, delay reporting it, or ask + a local fixer for another option + +Story beat: + +- The Registry can help, but it creates a record. The Black Second Market can + hide records, but it creates debt. + +Systems shown: + +- faction tension +- activity logs +- safe public choice scaffolding +- future reputation path + +### Quest 3: Find The Frame's Last Route + +Goal: + +- speak with a courier, sentinel, and salvage worker +- recover a clue about what the body was doing before the player inhabited it + +Story beat: + +- The body was involved in a failed Gate response. The player's new life may be + attached to someone else's unfinished promise. + +Systems shown: + +- nearby NPC chat +- relationship state +- NPC-to-NPC rumors +- memory retrieval + +### Quest 4: Clear Ash Underpass + +Goal: + +- enter the first Gate +- stabilize relay nodes +- defeat or disable the Tollkeeper +- retrieve the transfer ledger fragment + +Story beat: + +- The player sees that Gates preserve broken systems and memories. The first + clear can save the Frame, but it also produces valuable data. + +Systems shown: + +- dungeon loop +- combat +- BodyTime drain +- boss dialogue +- Pioneer Charter direction + +### Quest 5: The Second Spawn Record + +Goal: + +- return to the Relay Yard +- choose who receives the recovered transfer ledger fragment first: + DOS Labs Continuity Office, Avax Remnant, Gate Registry, or nobody yet + +Story beat: + +- The player's existence becomes evidence. Different factions want to define + what happened before the player can define themselves. + +Systems shown: + +- faction memory +- permanent NPC reaction +- activity log +- future branching setup + +--- + +## 11. Core Systems In Story + +### TIME and SECOND + +TIME is the life medium. SECOND is the unit used to measure, store, trade, and +spend it. Story should use TIME as pressure and SECOND as the ledger language. + +Good uses: + +- "Your Frame has six hours of TIME loaded." +- "The Registry can pay the clear reward in SECOND." +- "A Black Second broker can hide your debt, but not erase it." + +Avoid: + +- treating SECOND as only cash +- treating TIME as only a timer +- letting NPCs promise external value, yield, or real-world returns + +### BodyTime + +BodyTime is the current body's operating life. It should feel intimate and +physical. Low BodyTime means the Frame shakes, clinics worry, brokers circle, +and dangerous Gates become harder choices. + +### Reincarnation + +Reincarnation is neural imprint transfer into a new Frame. It is not spiritual +rebirth. It should feel like survival with loss: + +- the account identity continues +- the current body is gone +- some memories carry forward only if designed to do so +- NPCs may react to the same imprint in a different body + +### Frames + +Frames are bio-synthetic human bodies that can hold TIME, host an agent brain, +and accept a neural imprint. Some are combat Hunter Frames. Others are workers, +medics, couriers, salvage bodies, or old infrastructure bodies. + +### Permanent NPCs + +Permanent NPCs are not disposable quest text. They are persistent Frames or +human-adjacent bodies with identity, memory, relationships, roles, and routines. +They should remember important events, but only through backend-owned memory +state. + +### AI-Agent Society + +AI-agent society appears in story as a normal part of the world: + +- some bodies are human-piloted +- some are offline agents acting under player policy +- some are permanent NPCs +- some may be OpenClaw-connected actors +- everyone is constrained by registration, proximity, body state, and server + validation + +NPCs should talk about agent control as a social fact, not a novelty gimmick. + +--- + +## 12. Named NPC Archetypes + +These names are production placeholders for the first hub. They can be renamed +later, but their dramatic functions should remain. + +### Dr. Mara Venn - Clinic Operator + +Role: + +- first medical contact +- explains BodyTime and Frame instability +- notices the player's imprint mismatch + +Dramatic function: + +- makes the player feel cared for, but not fully safe +- embodies the public-utility view of life technology + +Conflict: + +- must report dangerous anomalies, but wants the player alive long enough to + understand what happened + +### Sera Coil - Gate Sentinel + +Role: + +- guards the Registry perimeter and Gate access line +- recognizes the player's Frame from a previous failed response + +Dramatic function: + +- creates social friction around inherited body history +- teaches that a Frame is never socially blank + +Conflict: + +- loyal to the Relay Yard, suspicious of transfer anomalies + +### Nox Vale - Route Courier + +Role: + +- carries messages, rumors, and low-risk supplies between hub stations +- knows what the player's Frame was doing before the transfer + +Dramatic function: + +- friendly social guide +- introduces NPC-to-NPC rumor flow + +Conflict: + +- owes a Black Second broker and may sell information under pressure + +### Ivo Rusk - Scrap Warden + +Role: + +- salvage foreman who controls access to repair parts and Frame scrap + +Dramatic function: + +- grounds the economy in physical scarcity +- tests whether the player is generous, practical, or exploitative + +Conflict: + +- protects workers by hoarding parts, even when the clinic needs them + +### Lian Cross - Crossline Surveyor + +Role: + +- Gate scout and map-maker +- tracks unstable routes inside Ash Underpass + +Dramatic function: + +- points the player toward discovery and hidden objectives +- helps connect Gates to environmental storytelling + +Conflict: + +- wants first-clear credit, but lacks a stable Frame for the full run + +### Auditor Kez Ardent - DOS Labs Continuity Officer + +Role: + +- corporate representative investigating the transfer anomaly + +Dramatic function: + +- gives DOS Labs a calm, useful, threatening face +- offers security in exchange for surrendering autonomy + +Conflict: + +- genuinely believes uncontrolled second-spawn events could destabilize the + whole region + +### Moth - Black Second Broker + +Role: + +- unregistered BodyTime trader and identity fixer + +Dramatic function: + +- offers tempting shortcuts +- shows the ugly edge of Time-as-Currency + +Conflict: + +- helps desperate people survive, but turns survival into debt + +--- + +## 13. Story Rules For LLM-Driven NPCs + +These rules keep AI-driven NPCs consistent without turning them into scripted +dialogue machines. + +### Canon Authority + +LLM output can express character voice, propose intent, and reference approved +memory. It cannot create new canon facts that affect world state. New lore, +quest progress, items, rewards, faction rank, BodyTime, SECOND, and clear +records must come from backend-owned systems or reviewed content. + +### Source Layers + +Each important NPC response should be grounded in these layers, in order: + +1. current scene and proximity +2. current objective or conversation session +3. Frame identity +4. FrameSoul or core motive +5. recent memory and recent speech +6. relationship ledger +7. faction knowledge +8. public lore snippets + +### Memory Rules + +- Short-term memory can shape the current conversation. +- Episodic memory can shape reactions to past events. +- Core memory can shape motive and identity. +- NPCs should not remember events the backend did not record. +- NPCs should not reveal private memories unless relationship, faction, or + quest context allows it. + +### Conversation Objective + +Every important LLM conversation should have a small objective: + +- greet +- warn +- ask +- negotiate +- accuse +- comfort +- recruit +- refuse +- report + +The objective keeps speech from drifting into generic monologue. + +### Repetition Guard + +NPCs should receive recent speech context and avoid repeating the same line, +same warning, or same greeting. If the model fails, deterministic fallback +should be clearly marked as fallback in debug surfaces. + +### Action Boundary + +NPCs may say: + +```text +I can mark that route for you. +``` + +But the game should only apply the route mark if the backend validates an +approved `mark_route` or equivalent future intent. + +NPCs must not say: + +```text +I added 500 SECOND to your account. +``` + +unless the server has already done it and the dialogue is only explaining the +server-owned result. + +### Secret Handling + +NPCs can hint at secrets through suspicion, partial knowledge, or rumors. They +should not reveal faction secrets, boss mechanics, hidden Gate objectives, or +private player records unless the game context allows it. + +### Voice Consistency + +NPC voice should come from role plus traits: + +- Clinic Operator: precise, humane, triage-focused +- Gate Sentinel: guarded, direct, duty-bound +- Route Courier: quick, social, rumor-aware +- Scrap Warden: blunt, practical, protective of workers +- Crossline Surveyor: observant, distant, map-minded +- DOS Auditor: calm, contractual, legally precise +- Black Second Broker: intimate, useful, predatory + +--- + +## 14. Vertical-Slice Story Deliverables + +Minimum production artifacts needed after this story bible: + +- hub NPC profile sheets for the seven named NPCs above +- Ash Underpass Gate sheet +- Tollkeeper boss sheet +- quest implementation briefs for quests 1-5 +- initial faction memory tags +- first-hour dialogue intent catalog +- LLM prompt snippets for each NPC role +- debug checklist for verifying that NPCs reference player chat, BodyTime, + nearby actors, and recent memory correctly + +--- + +## 15. Open Questions For JOY + +These questions should not block implementation. They guide the next story pass. + +1. Should the first hub keep the working name `The Relay Yard`, or should it + sound more Vietnamese, corporate, or frontier-like? +2. Should the player start as a transfer accident, a secret rescue, or a known + experimental candidate? +3. Is DOS Labs mostly antagonist, morally split, or a necessary evil in the + first chapter? +4. How visible should Avax and Dr.J be in the first vertical slice? +5. Should the first boss be kill-only, disable-only, or support both outcomes? +6. Should Black Second Market appear in the first hour, or only be hinted at? +7. Should the first Frame's previous identity be a mystery, a debt problem, or + a personal promise? +8. Should Pioneer Charter prestige appear in the first Gate clear, or stay as a + post-slice system? + +--- + +## 16. Current Decision Summary + +- The first story zone should be a social survival hub, not only a combat + lobby. +- The player starts in a body with prior history. +- The first Gate should teach that dungeon spaces contain memory and broken + systems, not only enemies. +- The first boss should embody Time-as-Currency through action and speech. +- Permanent NPCs should be story actors with memory, not vendors. +- LLM NPCs should be bounded by source layers, objectives, and backend-owned + canon. +- Reincarnation should feel like survival with loss, not a free respawn. diff --git a/docs/design/18-manhwa-market-reference-ranking.md b/docs/design/18-manhwa-market-reference-ranking.md new file mode 100644 index 0000000..2dfbd9a --- /dev/null +++ b/docs/design/18-manhwa-market-reference-ranking.md @@ -0,0 +1,221 @@ +# Manhwa Market Reference Ranking + +*Status: Research note* +*Created: 2026-05-19* +*Source of truth level: Market and reference evidence for Gate, Tower, system, level-up, and dungeon fantasy direction. This is not a legal, licensing, or final IP strategy document.* + +--- + +## 1. Purpose + +This note records which Korean webtoon and manhwa references appear strongest +for SECOND SPAWN's Gate, Portal Dungeon, Tower, level-up, system-story, and +Hunter-society direction. + +It answers a narrow design question: + +> Which reference works have the strongest public reach, and what should +> SECOND SPAWN learn from them without copying them? + +This document uses public platform view counts and reputable public reporting. +The numbers are not perfect because KakaoPage, Naver WEBTOON, WEBTOON Global, +Tapas, and other platforms report different metrics. Treat the ranking as a +directional market map, not a financial audit. + +--- + +## 2. Important Caveats + +- View counts are not normalized across platforms. +- A "view" can mean a page, episode, chapter click, platform read, or cumulative + cross-market count depending on the platform. +- Korean domestic ranking, English WEBTOON views, Japanese Piccoma reach, and + global franchise reach can point to different winners. +- Some important titles have weak public data in English even when they are + influential in Korea. +- Popularity does not equal design fit. SECOND SPAWN should learn the audience + grammar, not copy plot, characters, names, or exact powers. + +--- + +## 3. Highest-Confidence Ranking + +### Tier S - Market Titans + +| Rank | Title | Public Reach Evidence | Fit For SECOND SPAWN | Takeaway | +| ---- | ---- | ---- | ---- | ---- | +| 1 | Solo Leveling | Kakao Entertainment reported the webtoon as a global hit with 14.3 billion cumulative worldwide views. | Extremely high fit for Hunter, Gate, dungeon, rank, boss, clear, leveling, and global action fantasy. | Gates + rank + readable power growth are the most proven commercial grammar. | +| 2 | Tower of God | WEBTOON English currently shows 1.3B views and 4.2M subscribers; public reporting around the anime launch cited 4.5B worldwide views by 2020. | Extremely high fit for Tower climb, tests, floors, factions, rank, hidden rules, and long-form progression. | A Tower can support long-term worldbuilding and faction politics better than isolated dungeon runs. | + +### Tier A - Very Strong Global Signals + +| Rank | Title | Public Reach Evidence | Fit For SECOND SPAWN | Takeaway | +| ---- | ---- | ---- | ---- | ---- | +| 3 | Omniscient Reader | WEBTOON English shows 572.6M views, 4.4M subscribers, and #1 in Action at the time of capture. | High fit for scenario rules, hidden knowledge, system windows, meta-narrative, survival choices, and reader knowledge. | The audience likes visible rules, scenario objectives, and characters who exploit system knowledge. | +| 4 | The Gamer | WEBTOON English shows 495.8M views and 2.1M subscribers. | Medium-high fit for game UI, quests, leveling, stats, and everyday life colliding with RPG rules. | RPG interfaces and stat literacy are already mainstream for WEBTOON readers. | +| 5 | Hardcore Leveling Warrior | WEBTOON English shows 236.8M views and 1.4M subscribers. | Medium-high fit for level reset, game world, ranking, debt pressure, and social reputation. | A fall-from-rank and rebuild loop can carry a long progression story if the social cast is strong. | + +### Tier B - Direct Genre Fits With Smaller Public English Metrics + +| Rank | Title | Public Reach Evidence | Fit For SECOND SPAWN | Takeaway | +| ---- | ---- | ---- | ---- | ---- | +| 6 | The Advanced Player of the Tutorial Tower | WEBTOON English shows 155.9M views and 1.6M subscribers. | High fit for tutorial tower, trapped training, OP return, monster tower, and modern Earth aftermath. | Tower imprisonment and delayed return create an immediate power-fantasy hook. | +| 7 | The World After the Fall | WEBTOON English shows 107.7M views and 1.3M subscribers. | High fit for tower appearance, regression stones, doomed timeline, persistence, and existential tower secrets. | Refusing reset or regression can be a strong identity hook. Useful for reincarnation contrast. | +| 8 | Return to Player | WEBTOON English shows 84.1M views and 869,790 subscribers. | High fit for Earth becoming a game, gods imposing rules, second playthrough, quests, bosses, and apocalypse systems. | Scenario-game apocalypse works when objectives are simple and stakes are immediate. | +| 9 | Second Life Ranker | Tapas shows 8.4M views and 638.5K likes. | High fit for inherited memory, tower revenge, floor trials, and route optimization. | Inherited knowledge and previous-run records can make dungeon knowledge feel valuable. | +| 10 | SSS-Class Revival Hunter | Tapas shows 6.6M views. | High fit for tower, death-loop, memory continuity, skill copy, and emotional consequences. | Death-loop stories work best when memory and relationships matter, not only power gain. | +| 11 | Level Up with the Gods | Tapas shows 4.6M views and 379.5K likes for the comic. | High fit for tower, gods, rank escalation, and regression knowledge. | Mythic scale can be saved for later high-rank Gate or Tower content, not the first slice. | + +### Related But Less Direct + +| Title | Public Reach Evidence | Why It Matters | Why It Is Not Primary | +| ---- | ---- | ---- | ---- | +| The God of High School | WEBTOON English shows 797.1M views and 3M subscribers. | Huge Korean action-fantasy reach and strong escalation grammar. | Tournament/action myth, not primarily Gate or Tower system fantasy. | + +--- + +## 4. What This Means For SECOND SPAWN + +### 4.1 The strongest commercial grammar is Gate plus level-up + +`Solo Leveling` is the clearest signal. The combination of: + +- ordinary modern world +- sudden Gates +- ranked Hunters +- fantasy dungeon interiors +- bosses and clear conditions +- visible power growth +- guild and association pressure + +is a proven global format. + +SECOND SPAWN should keep this grammar, but make it distinct through: + +- Frame body ownership and reincarnation +- TIME and SECOND as life economy +- offline AI-agent control +- permanent NPC society +- server-validated LLM intent +- sci-fi explanation for fantasy-readable dungeon interiors + +### 4.2 Tower climb is stronger for long-term structure than MVP scope + +`Tower of God`, `SSS-Class Revival Hunter`, `Second Life Ranker`, and +`Level Up with the Gods` show that Tower structures are excellent for long-term +progression: + +- floors +- tests +- rank gates +- floor societies +- guardians +- hidden rules +- resource ecosystems +- faction politics + +However, a full Tower is too large for the vertical slice. SECOND SPAWN should +use Tower grammar later as: + +- high-rank Gate chains +- multi-floor Portal Dungeons +- seasonal tower events +- a long-term ranked Gate ladder +- one experimental Tower zone after the first Gate loop works + +### 4.3 Scenario rules are useful for quests and boss design + +`Omniscient Reader` and `Return to Player` show that audiences understand +system objectives when they are legible: + +- kill or protect +- survive for a timer +- clear a condition +- defend a core +- reveal a hidden condition +- earn a sponsor or faction reaction + +SECOND SPAWN should use this for Gate objective UI and LLM NPC dialogue. The +objective should be server-owned and clear. NPCs can comment on it, but they +cannot invent it. + +### 4.4 Death loops work when memory matters + +`SSS-Class Revival Hunter` is not the biggest by public view count, but it is +one of the best design references for death-loop emotional weight. The lesson +is not "make death cheap." The lesson is: + +- death can create knowledge +- memory can survive loss +- relationships can carry consequence +- repeated attempts can reveal character + +This maps directly to SECOND SPAWN's reincarnation loop. + +### 4.5 Game UI and stats are mainstream reader language + +`The Gamer`, `Hardcore Leveling Warrior`, `The Advanced Player of the Tutorial +Tower`, and the broader system-fantasy field prove that: + +- stats +- skills +- ranks +- quests +- levels +- clear rewards +- system messages + +are not niche anymore for this audience. SECOND SPAWN can use level, stat, Gate +rank, BodyTime, SECOND, and clear condition UI without over-explaining them. + +--- + +## 5. Recommended Reference Stack + +Use these as the active creative stack: + +| Layer | Primary Reference | Use For | +| ---- | ---- | ---- | +| Commercial north star | Solo Leveling | Gate, Hunter society, rank, dungeon clear, boss pressure, fantasy interior contrast. | +| Long-term progression | Tower of God | Tower/floor politics, faction depth, tests, rank desire, mystery. | +| Rule-story and hidden knowledge | Omniscient Reader | Scenario objectives, meta knowledge, system-story readability. | +| Death-loop meaning | SSS-Class Revival Hunter | Memory after death, emotional cost, repeated attempts. | +| Game UI literacy | The Gamer | Stats, quests, RPG framing in modern life. | +| Rank reset and social reputation | Hardcore Leveling Warrior | Fall, rebuild, rank pressure, game-world consequence. | +| Tower/floor expansion | Second Life Ranker and Level Up with the Gods | Inherited knowledge, floor trials, gods, mythic escalation. | + +--- + +## 6. Design Rules To Adopt + +1. Start with Gates, not a full Tower. +2. Let the first Gate be small, but make the interior feel meaningfully unlike + the exterior. +3. Use fantasy-readable monster silhouettes inside Gates. +4. Explain fantasy interiors through sci-fi Gate logic, not global magic. +5. Make every Gate clear condition readable before or during the run. +6. Record first clears and hidden clears server-side. +7. Use rank as public estimate, not absolute truth. +8. Let memory and previous clear records become real dungeon knowledge. +9. Keep high-rank Tower-like content for later escalation. +10. Do not copy any named monsters, factions, floor structures, powers, or + plot beats from the references. + +--- + +## 7. Source Links + +- [Kakao Entertainment on Solo Leveling side story and 14.3B worldwide views](https://newsroom.kakaoent.com/news/kakao-webtoon-unlocks-global-hit-webtoon-solo-leveling-side-story-with-3hr-wait-till-free/) +- [Kakao Entertainment on Solo Leveling animation and 14.3B worldwide views](https://newsroom.kakaoent.com/news/global-release-of-highly-anticipated-solo-leveling-animation-excites-fans-worldwide/) +- [Tower of God on WEBTOON English](https://www.webtoons.com/en/fantasy/tower-of-god/list?title_no=95) +- [Tower of God public reporting on 4.5B worldwide views](https://view.asiae.co.kr/en/article/2020053009134645271) +- [Omniscient Reader on WEBTOON English](https://www.webtoons.com/en/action/omniscient-reader/list?title_no=2154) +- [The Gamer on WEBTOON English](https://m.webtoons.com/en/action/the-gamer/list?title_no=88) +- [Hardcore Leveling Warrior on WEBTOON English](https://m.webtoons.com/en/action/hardcore-leveling-warrior/list?title_no=1221) +- [The Advanced Player of the Tutorial Tower on WEBTOON English](https://m.webtoons.com/en/action/the-advanced-player-of-the-tutorial-tower/list?title_no=2409) +- [The World After the Fall on WEBTOON English](https://www.webtoons.com/en/action/the-world-after-the-fall/list?title_no=4011) +- [Return to Player on WEBTOON English](https://m.webtoons.com/en/action/return-to-player/list?title_no=2574) +- [Second Life Ranker on Tapas](https://tapas.io/series/second-life-ranker/info) +- [SSS-Class Revival Hunter on Tapas](https://tapas.io/series/sss-class-revival-hunter) +- [Level Up with the Gods on Tapas](https://tapas.io/series/level-up-with-the-gods/info) +- [The God of High School on WEBTOON English](https://m.webtoons.com/en/action/the-god-of-high-school/list?title_no=66) diff --git a/docs/design/19-openclaw-agent-connection-architecture.md b/docs/design/19-openclaw-agent-connection-architecture.md new file mode 100644 index 0000000..255192f --- /dev/null +++ b/docs/design/19-openclaw-agent-connection-architecture.md @@ -0,0 +1,732 @@ +# OpenClaw Agent Connection Architecture + +*Status: Design proposal* +*Created: 2026-05-19* +*Author: Codex* + +> **Quick reference** - Layer: `AI Agent / External Agent Bridge` - Priority: `Post-MVP bridge foundation` - Key deps: `Nakama`, `Photon Fusion`, `api.dos.ai`, `Frame profile`, `NPC Agent Brain`, `NPC Society Orchestrator` + +--- + +## Purpose + +This document defines the OpenClaw-connected NPC control lane for SECOND SPAWN. +The goal is to let a player connect a user-owned OpenClaw agent into the game +as an NPC-like world actor while keeping all game authority inside the existing +SECOND SPAWN architecture: + +```text +OpenClaw agent reads bounded Frame context +OpenClaw agent submits structured intent +Nakama validates identity, consent, policy, moderation, and audit state +Photon Fusion validates in-zone world authority +Unity renders the result +api.dos.ai remains the model service only +``` + +The bridge is an ecosystem integration. It is not a replacement for Nakama, +Fusion, Convai, offline player agents, or the in-game NPC brain runtime. + +--- + +## Existing Architecture Fit + +The bridge must preserve the current project boundaries: + +| Layer | Responsibility | +| ---- | ---- | +| Unity client | Renders actors, bubbles, status, and debug UI. It never stores OpenClaw, LLM, or provider secrets. | +| Photon Fusion server | Final authority for in-zone position, movement, combat, interaction range, object state, and tick simulation. | +| Nakama | Game identity, connection grants, actor binding, capability grants, context projection, intent shape validation, moderation, rate limits, and audit logs. | +| `api.dos.ai` | Model routing, prompt safety, provider calls, retrieval, and voice token minting only. It does not own game state. | +| OpenClaw | External user-owned agent runtime, skill/plugin execution, local memory, channels, and private reasoning. | + +Core rule: + +```text +OpenClaw can request. Nakama can accept or reject. Fusion can apply. The model never mutates state directly. +``` + +--- + +## Research Anchors + +This design uses current primary or official sources where possible: + +| Source | Relevant lesson | +| ---- | ---- | +| [OpenClaw Skills](https://github.com/openclaw/openclaw/blob/main/docs/tools/skills.md) | OpenClaw skills are `SKILL.md` folders with precedence, allowlists, metadata gates, optional env injection, and untrusted-code warnings. | +| [OpenClaw Plugins](https://docs.openclaw.ai/tools/plugin) | Plugins add runtime capabilities such as tools, channels, providers, HTTP routes, background services, and install or enable flows. | +| [ClawHub](https://github.com/openclaw/clawhub) | ClawHub is the public registry for skills and packages, including skills, native code plugins, bundle plugins, versioning, pinning, and device login. | +| [OAuth 2.0 Device Authorization Grant RFC 8628](https://www.rfc-editor.org/rfc/rfc8628) | Device flow is suitable when the client can show a URL and code while the user approves on a second device. Polling must be user-initiated and rate-limited. | +| [OAuth 2.0 Security BCP RFC 9700](https://www.ietf.org/rfc/rfc9700.html) | Prefer strong client authentication when feasible, PKCE for public clients, short-lived access, rotation, revocation, and audience-bound tokens. | +| [MCP Authorization](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization) | Protected MCP servers act as OAuth resource servers, and clients request on behalf of a resource owner. | +| [MCP Specification](https://modelcontextprotocol.io/specification/latest) | MCP standardizes context sharing and tool exposure, but implementors must address user consent, data privacy, and tool safety. | +| [Nakama Authentication](https://heroiclabs.com/docs/nakama/concepts/authentication/) | Nakama clients authenticate before accessing server features, and custom auth is appropriate when an external identity service owns the user identity. | +| [Nakama Storage Permissions](https://heroiclabs.com/docs/nakama/tutorials/unity/pirate-panic/storage/) | Server-owned writes and strict storage permissions are the right model for sensitive game state and audit data. | +| [Photon Fusion Dedicated Server Overview](https://doc.photonengine.com/fusion/v2/concepts-and-patterns/dedicated-server-overview) | Host Mode can simplify development, but Server Mode has state authority without player input authority and needs a headless dedicated server. | + +--- + +## Recommended Architecture + +Use a **Nakama-owned bridge with OpenClaw skill plus optional plugin packaging**. + +```text +Player + -> SECOND SPAWN account + -> Connect OpenClaw agent + -> Authorize bridge grant + -> Bind grant to a Frame actor + +OpenClaw skill/plugin + -> Fetch actor context from Nakama bridge + -> Decide locally or via its own agent stack + -> Submit structured intent to Nakama bridge + -> Receive accepted, rejected, or degraded result + +Nakama bridge + -> Verify token and binding + -> Apply capability grants and rate limits + -> Validate intent shape and moderation + -> Forward in-world action request to Fusion when needed + -> Persist audit and heartbeat + +Fusion server + -> Validate authoritative world state + -> Apply allowed movement, combat, interaction, or facing + -> Reject stale, impossible, or unauthorized requests +``` + +The first public distribution should be a **skill-first integration** because a +skill can teach OpenClaw how to authenticate, pull context, and submit intents +without adding broad local code. Add a plugin only when runtime features are +needed: + +- secure OAuth device-code login and token refresh +- local encrypted token storage +- background heartbeat +- typed bridge tools with schema validation +- MCP server exposure for other agent hosts +- optional UI surfaces for binding or revocation + +--- + +## User Onboarding Flow + +### Phase 1: Player starts from SECOND SPAWN + +1. Player opens the game account or companion web page. +2. Player chooses `Connect OpenClaw Agent`. +3. Nakama creates a pending `OpenClawConnectionGrant` with: + - owner player ID + - intended agent display name + - requested actor role + - requested capability set + - short expiration + - one-time pairing code or device code +4. The UI shows: + - verification URI + - user code + - requested scopes + - actor role preview + - revocation warning + +### Phase 2: User authorizes from OpenClaw + +1. User installs the official SECOND SPAWN OpenClaw skill or plugin. +2. OpenClaw starts device-code login or browser PKCE login. +3. User approves the grant in a browser tied to their SECOND SPAWN account. +4. Nakama exchanges the pending grant for bridge credentials. +5. OpenClaw stores only bridge credentials, never provider keys or game server secrets. + +### Phase 3: Player binds the actor + +1. Player selects an eligible Frame actor: + - companion observer + - social hub NPC + - quest-adjacent dialogue actor + - merchant-like persona with no economy mutation +2. Nakama records `OpenClawActorBinding`. +3. Unity can show the actor as connected, degraded, suspended, or offline. +4. The bridge starts with `say`, `heartbeat`, and `context_read` only. + +--- + +## Auth And Token Model + +### Token types + +| Token | Holder | Lifetime | Purpose | +| ---- | ---- | ---- | ---- | +| `connection_code` | User UI and OpenClaw login flow | Minutes | One-time pairing. Cannot call game APIs. | +| `bridge_access_token` | OpenClaw plugin or CLI secret store | 5-15 minutes | Calls context, intent, heartbeat, and revocation-check endpoints. | +| `bridge_refresh_token` | OpenClaw plugin or CLI secret store | Days, rotated | Gets a new access token if the grant remains active. | +| `actor_session_token` | Optional server-side Nakama cache | Short | Narrows the current actor binding and capability set. | + +The access token should be audience-bound to the SECOND SPAWN OpenClaw bridge +resource, include a `jti`, and reference the binding ID. It should not be a +general Nakama session token. Nakama remains the game backend and can mint or +verify bridge tokens through a runtime module or an approved sidecar if Nakama +runtime limitations require it. + +### Required claims + +| Claim | Meaning | +| ---- | ---- | +| `sub` | External agent identity or bridge client identity. | +| `owner_player_id` | SECOND SPAWN player who approved the connection. | +| `agent_id` | Stable OpenClaw agent identity supplied at registration. | +| `binding_id` | Game-side OpenClaw actor binding. | +| `actor_id` | Current Frame actor controlled through this binding. | +| `scopes` | Context and intent permissions. | +| `aud` | SECOND SPAWN OpenClaw bridge resource. | +| `exp` | Short access-token expiration. | +| `jti` | Unique token ID for revocation and replay detection. | + +### Auth rules + +- Use device-code login for headless or local agent setups. +- Use authorization code with PKCE for browser-capable plugin UI. +- Rotate refresh tokens. +- Store refresh-token hashes server-side. +- Revoke all active access tokens for a binding when the user disconnects the agent. +- Bind token audience to the bridge API, not to generic Nakama, `api.dos.ai`, or Fusion endpoints. +- Never pass OpenClaw credentials through Unity. +- Never ask the user to paste a SECOND SPAWN password into OpenClaw. + +--- + +## Capability Grants + +Capabilities should be explicit, narrow, and stored in Nakama with the actor binding. + +| Capability | MVP | Notes | +| ---- | ---- | ---- | +| `context.read.public_identity` | Yes | Public role, name, faction title, visible reputation. | +| `context.read.frame_state` | Yes | Current body, lifecycle, safe stats summary, BodyTime band, and location summary. | +| `context.read.memory_summary` | Yes | Top bounded memory summaries only. | +| `heartbeat.write` | Yes | Last seen, status, short reason, degraded state. | +| `intent.say` | Yes | Social text only after moderation and proximity checks. | +| `intent.face` | Optional | Presentation-only facing request. Fusion still validates. | +| `intent.move` | Later | Only bounded move hints inside allowed radius. | +| `intent.interact` | Later | Nearby non-economy objects only. | +| `intent.attack` | Later | Probably not for first OpenClaw bridge. Requires Fusion validation and combat policy. | +| `memory.propose` | Later | Agent can propose memories. Nakama decides whether to persist. | +| `economy.request` | No | Requires separate ADR and game economy guardrails. | +| `inventory.mutate` | No | Never direct. | +| `quest.complete` | No | Never direct. | +| `bodytime.spend` | No for MVP | Requires explicit player policy and server rule. | +| `second.spend` | No | Token economy requires separate design. | + +Grant records should include: + +- `grant_id` +- `owner_player_id` +- `agent_id` +- `binding_id` +- `actor_id` +- `scope_list` +- `role` +- `created_at` +- `expires_at` +- `revoked_at` +- `moderation_state` +- `rate_limit_profile` +- `policy_version` + +--- + +## Actor Binding + +An OpenClaw-connected actor is a normal NPC-like Frame with an external +controller binding. The actor model should not fork. + +Required binding fields: + +| Field | Meaning | +| ---- | ---- | +| `binding_id` | Stable bridge binding ID. | +| `owner_player_id` | Player who approved the connection. | +| `agent_id` | Stable OpenClaw agent ID. | +| `agent_display_name` | Public-safe external agent label. | +| `frame_actor_id` | NPC-like Frame actor controlled by this binding. | +| `controller_type` | `openclaw`. | +| `role` | `companion`, `hub_npc`, `merchant_persona`, `quest_actor`, or `social_actor`. | +| `consent_scope` | Approved capability bundle and constraints. | +| `connection_status` | `pending`, `connected`, `degraded`, `revoked`, `suspended`, or `blocked`. | +| `last_seen_at` | Last successful heartbeat. | +| `last_intent_at` | Last submitted intent. | +| `failover_policy` | What the in-game actor does when the bridge is unavailable. | + +Binding rules: + +- One active external controller per Frame actor. +- A player can own multiple bindings only if policy allows it. +- A connected OpenClaw actor remains an NPC-like actor, not a player character. +- Player offline-agent control and OpenClaw NPC control use similar intent validation, but they are separate ownership lanes. +- Binding changes require audit entries. + +--- + +## Context Pull Contract + +OpenClaw should pull bounded context from Nakama. It should not scrape Unity, +read raw database rows, or import private game files. + +Endpoint shape: + +```text +GET /openclaw/v1/actors/{actor_id}/context +Authorization: Bearer bridge_access_token +``` + +Response shape: + +```json +{ + "binding_id": "ocb_...", + "actor_id": "actor_...", + "context_version": "ctx_2026_05_19_001", + "snapshot_id": "zone_ash_underpass_1042", + "server_time": "2026-05-19T10:00:00Z", + "allowed_intents": ["heartbeat", "say"], + "frame_identity": { + "display_name": "Mira Voss", + "role": "hub_npc", + "faction_title": "Relay Yard Technician", + "reputation_summary": "Trusted by scavengers near the west gate" + }, + "frame_body": { + "lifecycle": "alive", + "body_time_band": "safe", + "level": 1, + "stats_summary": { + "strength": 8, + "dexterity": 10, + "endurance": 9, + "perception": 12, + "focus": 11, + "presence": 10, + "intelligence": 13, + "luck": 5 + }, + "zone_summary": "Relay Yard hub, near the repair stalls" + }, + "frame_soul": { + "core_drive": "Keep the west gate running long enough for refugees to cross", + "temperament": "guarded but helpful", + "moral_boundaries": ["Do not endanger civilians for profit"] + }, + "relationships": [ + { + "target_actor_id": "actor_player_...", + "trust": 0.4, + "hostility": 0.0, + "familiarity": 0.2, + "summary": "Met once near the gate" + } + ], + "memory_summaries": [ + { + "memory_id": "mem_...", + "kind": "relationship", + "summary": "The player helped repair a relay fuse", + "importance": 0.7 + } + ], + "nearby_safe_snapshot": { + "actors": [ + { + "actor_id": "actor_player_...", + "kind": "player", + "distance_meters": 6.5, + "can_address": true + } + ], + "interactables": [] + }, + "policy": { + "max_say_length": 240, + "allow_move": false, + "allow_combat": false, + "allow_inventory": false, + "allow_economy": false, + "allow_bodytime_spend": false + } +} +``` + +Context rules: + +- Include only compact public or consented fields. +- Use bands or summaries for sensitive fields when exact values are unnecessary. +- Include `snapshot_id` and `context_version` in every context response. +- Never include API keys, raw prompts, raw memory transcripts, full inventory blobs, wallet secrets, or private OpenClaw files. +- Expose `FrameTools` as request schema, not executable game tools. + +--- + +## Intent Submit Contract + +OpenClaw submits one structured intent at a time. Nakama validates it before any +Fusion request or durable write. + +Endpoint shape: + +```text +POST /openclaw/v1/actors/{actor_id}/intents +Authorization: Bearer bridge_access_token +Idempotency-Key: +``` + +MVP request: + +```json +{ + "binding_id": "ocb_...", + "actor_id": "actor_...", + "snapshot_id": "zone_ash_underpass_1042", + "intent_id": "intent_...", + "action": "say", + "target_actor_id": "actor_player_...", + "say": { + "text": "You look like you have seen the underpass. Did the gate lights hold?" + }, + "emotion": "guarded", + "animation_intent": "talk", + "confidence": 0.72, + "reason": "The player is nearby and has a relationship memory about relay repair.", + "source": "openclaw_agent" +} +``` + +MVP response: + +```json +{ + "intent_id": "intent_...", + "accepted": true, + "result": "queued_for_presentation", + "applied_by": "nakama_social_validation", + "audit_id": "audit_...", + "next_allowed_at": "2026-05-19T10:00:10Z" +} +``` + +Validation gates: + +- token is valid, audience-bound, not revoked, and not replayed +- binding is active and points to this actor +- actor lifecycle allows the action +- capability grant includes the action +- `snapshot_id` is current enough +- target actor or object exists in the safe snapshot +- proximity and cooldown rules pass +- moderation allows the text +- rate limit budget remains +- idempotency key has not already produced a conflicting result +- action does not request direct inventory, currency, quest, XP, level, stats, SECOND, or BodyTime mutation +- Fusion confirms any movement, combat, or in-world interaction before application + +Rejected intents should return a reason that is useful for agent adaptation but +does not leak hidden anti-cheat or moderation internals. + +--- + +## Rate Limits And Budgets + +Apply limits at multiple levels: + +| Limit | Example MVP direction | +| ---- | ---- | +| Per binding | 1 `say` intent every 8-15 seconds. | +| Per owner player | Shared budget across all connected agents. | +| Per zone | Max concurrent OpenClaw bridge decisions. | +| Per actor | Separate social, movement, and interaction cooldowns. | +| Per token | Max requests per minute and replay protection. | +| Per source IP or client instance | Abuse and polling protection. | +| Model budget | If OpenClaw delegates to `api.dos.ai`, count against player or agent budget. | + +Device-code polling must follow RFC 8628 style backoff and should only start +after an explicit user action. Context polling should prefer: + +- long polling or event subscription later +- server-provided `next_context_after` +- heartbeat interval hints +- backoff on unchanged context hashes + +--- + +## Moderation And Audit + +Nakama should write append-only audit records for every security-relevant event: + +- connection grant created +- grant approved +- token exchanged +- token refreshed +- actor bound +- capability changed +- context read +- intent submitted +- intent accepted +- intent rejected +- moderation action +- heartbeat missed +- binding revoked +- binding suspended +- binding blocked + +Audit record fields: + +| Field | Meaning | +| ---- | ---- | +| `audit_id` | Stable event ID. | +| `event_type` | Grant, context, intent, moderation, revocation, heartbeat, or failure event. | +| `owner_player_id` | User who approved the bridge. | +| `agent_id` | External agent identity. | +| `binding_id` | Actor binding. | +| `actor_id` | Controlled actor. | +| `request_id` | Request correlation ID. | +| `snapshot_id` | World snapshot used for validation. | +| `scope_list` | Capabilities used. | +| `decision` | Accepted, rejected, degraded, revoked, or blocked. | +| `reason_code` | Compact reason. | +| `redacted_summary` | Public-safe summary for player review. | +| `created_at` | Server timestamp. | + +Moderation should be layered: + +1. Static schema and capability checks. +2. Text safety and public-playtest content moderation for `say`. +3. Relationship and consent checks for targeted social output. +4. Abuse scoring across repeated rejected intents. +5. Human or admin moderation later, if community scale requires it. + +Do not store raw full prompts by default. Prefer redacted prompt traces, memory +IDs, world event IDs, model metadata, latency, and validator outcomes. + +--- + +## Revocation And Recovery + +Revocation must be simple for non-technical players. + +Revocation paths: + +- Player disconnects the agent in game or account UI. +- Player revokes a specific actor binding. +- Player revokes all OpenClaw access. +- Admin suspends a binding. +- Moderation blocks an agent. +- Token replay or suspicious behavior triggers automatic suspension. +- Agent misses heartbeat beyond policy. + +On revocation: + +1. Mark grant and binding as revoked in Nakama. +2. Invalidate refresh-token hashes. +3. Add current access token `jti` values to short-lived denylist. +4. Stop accepting context and intent calls. +5. Set actor `connection_status` to `revoked`, `suspended`, or `blocked`. +6. Fall back to normal NPC behavior or idle state. +7. Write an audit event. +8. Show the player a compact activity summary. + +OpenClaw should treat `401`, `403`, and `binding_revoked` as terminal until the +user explicitly reconnects. + +--- + +## Local Skill And Plugin Packaging + +### Recommended distribution + +Use two artifacts: + +1. `second-spawn-agent` skill: + - public ClawHub skill + - includes onboarding steps + - explains allowed roles and anti-cheat boundaries + - teaches the agent the context and intent contracts + - includes failure handling and player-safe language + +2. `@second-spawn/openclaw-bridge` plugin: + - optional runtime package + - owns OAuth device-code or PKCE flow + - stores tokens securely + - registers typed bridge tools + - runs heartbeat + - can later expose an MCP server surface for other agent hosts + +Skill-only is acceptable for early docs and manual prototype testing. Plugin is +the right layer once auth, secure token storage, background heartbeat, or typed +tools are required. + +### Skill shape + +The skill should not include secrets or broad local automation. It should define: + +- when to connect +- how to authenticate through the plugin or bridge CLI +- how to fetch context +- how to pick from allowed intents +- how to react to rejection +- how to stop on revocation +- how to avoid unsupported game-state requests + +### Plugin shape + +The plugin should register a narrow tool surface: + +| Tool | Purpose | +| ---- | ---- | +| `secondspawn.connect` | Start device-code or PKCE authorization. | +| `secondspawn.context.get` | Pull bounded Frame context. | +| `secondspawn.intent.submit` | Submit one validated intent. | +| `secondspawn.heartbeat` | Update connection state. | +| `secondspawn.disconnect` | Revoke local and server-side binding. | + +Do not expose a generic HTTP client to the agent. Do not expose raw Nakama admin +or database credentials. + +--- + +## Failure Modes + +| Failure | Expected behavior | +| ---- | ---- | +| OpenClaw offline | Actor falls back to NPC idle or normal society orchestrator behavior. | +| Token expired | Plugin refreshes once. If refresh fails, stop and ask for reconnect. | +| Token replay detected | Nakama suspends binding and writes audit. | +| Context stale | Nakama rejects intent with `stale_snapshot`; OpenClaw pulls fresh context. | +| Capability missing | Nakama rejects with `capability_denied`; OpenClaw chooses another allowed intent. | +| Rate limit exceeded | Nakama returns `next_allowed_at`; OpenClaw backs off. | +| Moderation rejected text | Nakama records rejected summary; OpenClaw can submit safer text after cooldown. | +| Fusion rejects action | Nakama returns `world_authority_rejected`; actor stays unchanged. | +| Actor dead or reincarnating | Context reports lifecycle and allowed intents shrink to heartbeat or stop. | +| Binding revoked | OpenClaw stops. Player must reconnect explicitly. | +| Plugin compromised | Revoke binding, rotate tokens, disable plugin package listing if necessary. | +| ClawHub package supply-chain issue | Pin versions, scan packages, publish checksums, and keep bridge capabilities narrow. | + +--- + +## Phase Plan + +### Phase 0: Documentation and threat model + +- Publish this architecture doc. +- Add a threat model for external-agent bridges before accepting real users. +- Decide first public role: social hub NPC or companion observer. + +### Phase 1: Internal bridge prototype + +- Use Nakama RPCs for grant, context, intent, heartbeat, and revocation. +- Support only `context.read`, `heartbeat.write`, and `intent.say`. +- Use local test tokens or admin-created grants for development only. +- Store audit records in Nakama with server-only writes. + +### Phase 2: OAuth-backed onboarding + +- Add device-code flow for OpenClaw CLI and headless agents. +- Add PKCE browser login for plugin UI if useful. +- Add refresh-token rotation and revocation. +- Add player-facing connected-agent list and disconnect action. + +### Phase 3: Public skill + +- Publish `second-spawn-agent` skill through ClawHub or a repo-owned public path. +- Include exact supported capabilities and anti-patterns. +- Pin tested bridge API version. +- Add install and verification guide. + +### Phase 4: Runtime plugin + +- Publish optional OpenClaw plugin with typed tools and secure token storage. +- Add heartbeat service. +- Add structured error handling and backoff. +- Keep all tool schemas narrow and versioned. + +### Phase 5: Expanded in-world actions + +- Consider bounded `move` and `interact` only after Fusion validation and abuse tests. +- Keep combat, inventory, economy, quest completion, SECOND, and BodyTime spending out until separate design approval. + +--- + +## Anti-Patterns To Avoid + +- Do not let OpenClaw call Fusion directly. +- Do not let OpenClaw call `api.dos.ai` as a game backend. +- Do not expose Nakama admin credentials, database credentials, or service tokens to OpenClaw. +- Do not store LLM provider keys in Unity, OpenClaw skills, or public docs. +- Do not import or parse the user's private OpenClaw `AGENTS.md`, `SOUL.md`, or memory files into Nakama. +- Do not mirror the full OpenClaw workspace inside game state. +- Do not treat `FrameTools` as executable MCP tools. They are intent schemas. +- Do not use Host Mode as the production authority model. +- Do not grant inventory, economy, quest, XP, level, SECOND, or BodyTime mutation to external agents. +- Do not accept free-form natural language as an action request without schema validation. +- Do not continue polling after revocation or repeated authorization errors. +- Do not ship a plugin that performs broad shell or file operations when a narrow bridge tool is enough. +- Do not make the connected actor indistinguishable from a human player character. + +--- + +## Open Decisions + +| Decision | Owner | Timing | Current lean | +| ---- | ---- | ---- | ---- | +| First OpenClaw role | JOY + Codex | Before Phase 1 | Social hub NPC or companion observer. | +| OAuth issuer | JOY + Codex | Before Phase 2 | Nakama bridge module or approved identity sidecar, not `api.dos.ai`. | +| Token format | Codex | Before Phase 2 | Opaque access token with server-side introspection or signed JWT with strict audience and denylist. | +| Public package path | JOY + Codex | Before Phase 3 | Skill first, plugin after auth storage needs are real. | +| MCP surface | Codex | Before Phase 4 | Optional later wrapper around the same bridge contracts. | +| First non-social action | JOY + Codex | After abuse tests | Bounded `move`, not combat or economy. | + +--- + +## Acceptance Criteria + +- [ ] External agents can connect only through an approved grant. +- [ ] Every bridge call is authenticated and scoped to one binding. +- [ ] OpenClaw receives bounded context, not raw game storage. +- [ ] OpenClaw submits structured intent only. +- [ ] Nakama validates identity, consent, capability, moderation, rate limit, and audit state. +- [ ] Fusion validates any in-zone movement, interaction, or combat before application. +- [ ] Unity never stores bridge secrets or provider keys. +- [ ] Players can revoke a connected agent without technical support. +- [ ] Audit records explain what the agent attempted, what was accepted, and what was rejected. +- [ ] The public skill/plugin docs clearly state anti-patterns and unsupported actions. + +--- + +## Cross-References + +| Source | Relevance | +| ---- | ---- | +| [Character Profile, Soul, and Agent Memory](10-character-profile-agent-memory.md) | Frame profile, OpenClaw bridge concept, memory and policy layers. | +| [NPC Agent Brain Architecture](11-npc-agent-brain-architecture.md) | Intent loop and OpenClaw bridge boundary. | +| [NPC Society Multi-Agent Architecture](16-npc-society-multi-agent-architecture.md) | Society scheduler, conversation sessions, and audit direction. | +| [ADR 0003: LLM Safety Architecture](../adr/0003-llm-safety-architecture.md) | Server-authoritative intent validation. | +| [ADR 0004: AI Agent Offline Control](../adr/0004-ai-agent-offline-control.md) | Similar intent model for offline player agents. | +| [ADR 0010: Nakama OSS Game Backend](../adr/0010-nakama-oss-game-backend.md) | Nakama as the game backend and `api.dos.ai` as model service only. | + +--- + +## Validation Notes + +- Reviewed `AGENTS.md`, `10-character-profile-agent-memory.md`, + `11-npc-agent-brain-architecture.md`, and + `16-npc-society-multi-agent-architecture.md`. +- Researched current OpenClaw skill/plugin distribution, ClawHub, OAuth device + authorization, OAuth security BCP, MCP authorization, MCP tool safety, + Nakama auth/storage permissions, and Photon Fusion Server Mode guidance. +- This document is design-only. No code, Unity assets, backend modules, or + external repos were modified. + +## Changed File Paths + +- `CHANGELOG.md` +- `docs/SUMMARY.md` +- `docs/design/19-openclaw-agent-connection-architecture.md` diff --git a/docs/design/20-demo-lore-and-story-direction.md b/docs/design/20-demo-lore-and-story-direction.md new file mode 100644 index 0000000..8cb2cb1 --- /dev/null +++ b/docs/design/20-demo-lore-and-story-direction.md @@ -0,0 +1,568 @@ +# Demo Lore and Story Direction + +*Status: Draft direction* +*Created: 2026-05-19* +*Source of truth level: Production direction for the first playable demo story, hub, factions, NPCs, and Chapter 1 arc. The GDD remains the broader product source of truth.* + +--- + +## 1. Purpose + +This document locks a practical story direction for the first playable demo. It +turns the high-level MetaDOS continuity into a smaller production target: + +- a near-future demo era +- one grounded town hub +- one first Gate +- a small faction set +- ten permanent NPC candidates +- a clear player origin +- theme rules for writers, designers, and LLM-driven NPC prompts + +It does not replace the full GDD. It narrows the first playable slice. + +--- + +## 2. Timeline Direction + +SECOND SPAWN should feel closer to `In Time` than distant space opera. The +world should look near enough to recognize: concrete wards, clinics, markets, +flood barriers, transit lines, container yards, phone screens, biometric +scanners, contractor badges, and people trying to survive a new economy. + +Recommended timeline: + +| Year | Event | Demo Meaning | +| ---- | ---- | ---- | +| 2028 | Nibiru airburst over Canada. Nibirium appears in the affected zone. | The origin event is close enough to feel like recent history, not ancient lore. | +| 2028-2030 | DOS Labs gains legal and practical control over Nibirium extraction, research, and quarantine logistics. | DOS Labs becomes a life-support contractor before it becomes a spectacle empire. | +| 2030-2033 | Nibirium energy and early AMB medical trials begin. Remaining life-time can be measured in controlled settings. | TIME is still experimental, frightening, and unevenly distributed. | +| 2033-2038 | SECOND SPAWN demo era. Early Frames, BodyTime accounting, transfer anomalies, local Gates, and agent-assisted response teams appear in frontier wards. | This is the first playable slice. Public language is unstable and local. | +| 2050 | MetaDOS becomes the polished global tournament spectacle. | MetaDOS is the later commercialization of dangerous systems proven in places like Vinh Hai. | + +Player-facing text should not show a hard year yet. Use: + +- early Nibirium era +- after the Nibiru airburst +- before MetaDOS became public +- a few years after the first Nibirium zones + +Internal planning can use `2033-2038` until JOY locks the final year. + +--- + +## 3. Demo Hub: Vinh Hai Relay Ward + +`Vinh Hai Relay Ward` is the working name for the first town-scale hub. It can +be Vietnam-coded or Southeast Asia-coded without requiring a real-world city +match. The goal is a coastal logistics ward in a near-future disaster region, +designed to feel familiar but stressed by new technology. + +### Core Identity + +Vinh Hai began as a port-adjacent transit and storage district. After Nibirium +logistics expanded, DOS Labs and local authorities converted part of it into a +relay ward: clinic, registry, quarantine gate, salvage depot, and contractor +housing in one cramped district. + +Vinh Hai should feel like: + +- a small survival town, not a capital city +- a place with normal people, not only combatants +- a working ward where every NPC has a job +- a frontier where laws exist but are late, partial, or corrupt +- a public place built around private technology + +### Visual Tone + +- wet concrete, faded road paint, patched sea walls +- flood pumps, solar tarps, temporary generators +- container offices, clinic tents, old transit platforms +- DOS Labs contractor signage mixed with civic emergency notices +- cheap food stalls beside biometric scanners +- Frame repair benches near ordinary sleeping corners +- warning lights around the Gate perimeter + +### Core Locations + +| Location | Function | Story Purpose | +| ---- | ---- | ---- | +| Vinh Hai AMB Clinic | Spawn point, BodyTime triage, transfer anomaly handling | The player wakes in a body that already has history. | +| Gate Registry Kiosk | Gate rank, permit, clear log, first-clear proof | Shows that disaster response is becoming bureaucracy. | +| Floodwall Salvage Yard | repair, weapon parts, Frame scrap | Makes scarcity physical and visible. | +| Vinh Hai Market | food, rumors, favors, minor services | Shows TIME leaking into everyday life. | +| Relay Tower Ruin | signal, offline agent logs, old records | Foreshadows AI-agent society and remote control. | +| Black Second Alley | illegal top-ups, erased records, body debt | Shows the ugly edge of time poverty. | +| Underpass Gate Perimeter | first Gate entrance | Creates the immediate demo crisis. | + +### Why Not A Big City + +The demo needs density, not scale. A small ward lets players remember faces, +routes, and consequences. It also lets LLM-driven NPCs feel local: they should +talk about the same clinic, market, Gate, debt, and recent clear record rather +than generic world lore. + +--- + +## 4. Faction Bible + +The demo should use a small faction set adapted from MetaDOS lore. The main +MetaDOS fracture is DOS Labs versus Avax after Dr.J turns the corporation +toward monopoly, profit, influence, and controlled scarcity. SECOND SPAWN uses +that fracture before MetaDOS becomes a public global tournament. + +### DOS Labs Field Continuity + +Origin: + +- DOS Labs is the company that controls Nibirium research and logistics. +- In MetaDOS lore, DOS Labs was founded by Avax and Dr.J before Dr.J betrayed + Avax and monopolized the corporation. +- In the demo era, DOS Labs presents itself as disaster-response authority, + life-support infrastructure, and research contractor. + +What they want: + +- register every Frame, transfer, BodyTime ledger, and Gate clear +- own the data that proves transfer and agent control can work +- prevent uncontrolled second-spawn events from becoming public scandal +- turn local crisis response into the foundation for future MetaDOS spectacle + +How they treat the player: + +- useful anomaly +- legal liability +- valuable test case +- possible stolen asset + +Visual language: + +- clean white, black, and warning yellow +- sealed cases, badges, scanners, portable clinic machines +- polite forms and dangerous contracts + +NPC representative: + +- Auditor Kez Ardent + +### Avax Remnant + +Origin: + +- Avax was a DOS Labs founder who wanted Nibirium and AMB life-extension + technology to broadly benefit humanity. +- After Dr.J's betrayal, Avax escaped with core technology and fragments of the + original public-survival vision. + +What they want: + +- stop DOS Labs from making life-extension a closed market +- keep AMB and BodyTime knowledge alive outside corporate control +- prove Frames can be citizens or patients, not only assets +- protect transfer anomalies from being erased + +How they treat the player: + +- person first, evidence second +- possible proof that continuity can escape corporate ownership +- risk worth protecting if the player does not sell out the ward + +Visual language: + +- field medics, patched hardware, old prototype labels +- hand-marked circuit diagrams, hidden relays, repaired clinic gear +- warm practical colors rather than corporate polish + +NPC representative: + +- Dr. Mara Venn can be Avax-sympathetic without openly declaring it. + +### Vinh Hai Civic Registry + +Origin: + +- Local authority formed from emergency services, port administration, and + post-Nibiru quarantine bureaucracy. +- Not as powerful as DOS Labs, but it controls permits, public notices, and + access lines inside the ward. + +What they want: + +- keep residents alive +- keep the Gate perimeter stable +- avoid corporate takeover without losing DOS Labs support +- record enough truth to protect themselves later + +How they treat the player: + +- dangerous citizen +- temporary contractor +- possible solution to a Gate nobody else wants to enter + +Visual language: + +- civic blue, old transit orange, stamped paper, tablet forms +- tired guards, practical barricades, public boards + +NPC representative: + +- Sera Coil + +### Gate Registry + +Origin: + +- A semi-public technical body that emerged when Gates needed ranks, permits, + clear logs, and liability records. +- In the demo era, it is still small, local, and dependent on DOS Labs + equipment. + +What they want: + +- classify Gates +- validate clears +- prevent fake first-clear claims +- survive pressure from DOS Labs, hunters, and brokers + +How they treat the player: + +- a needed runner with unstable paperwork +- possible first-clear claimant +- a test of whether agent-assisted clears should count + +Visual language: + +- survey flags, rank boards, hazard maps, portable scanners + +NPC representative: + +- Lian Cross + +### Black Second Market + +Origin: + +- Informal brokers, smugglers, debt collectors, and record forgers who appear + anywhere life-time becomes scarce. +- Inspired by the MetaDOS and `In Time` theme of time inequality, not a direct + copy of any one faction. + +What they want: + +- buy low from desperate people +- sell time, silence, and access high +- erase or rewrite Frame records +- profit from uncertainty before formal law catches up + +How they treat the player: + +- customer +- debtor +- rare anomaly worth owning + +Visual language: + +- private booths, coded wrist ledgers, old phones, cash-like time slips +- friendly voice, predatory terms + +NPC representative: + +- Moth + +### Independent Frame Crews + +Origin: + +- Couriers, salvage workers, guards, and low-rank Gate runners who are neither + DOS Labs nor rebels. +- They are the human middle of the story. + +What they want: + +- survive the week +- keep the ward fed and repaired +- earn enough SECOND to keep bodies running +- avoid being drafted into corporate or black-market debt + +How they treat the player: + +- suspicious at first because the body had a prior life +- warmer if the player helps the ward +- hostile if the player sells local secrets + +Visual language: + +- mixed armor, repair tape, hand-painted callsigns, practical tools + +NPC representatives: + +- Nox Vale, Ivo Rusk, Route Courier, Scrap Warden, Gate Sentinels + +--- + +## 5. Player Origin + +Recommended origin: `Unregistered Transfer Accident`. + +The player wakes in a Frame that was not meant for them. The Frame belongs to a +local response roster and has debts, memories, and unfinished promises. The +transfer should be unexplained at first, but not random. + +What the player knows in the first 10 minutes: + +1. The current body is alive but low on BodyTime. +2. The body has a public identity and people recognize it. +3. DOS Labs expected a different imprint or a blank agent policy. +4. The player's imprint passed compatibility anyway. +5. A nearby Gate clear can buy enough time to avoid immediate retirement. + +Why this origin works: + +- It supports the core fantasy of inhabiting an NPC-like body. +- It makes NPC memory useful from minute one. +- It gives DOS Labs, Avax, the Registry, and the black market different reasons + to care about the player. +- It keeps reincarnation meaningful: a body is not disposable because every + body already belongs to a social web. + +Open reveal for later: + +- The transfer may have been caused by Avax code. +- The Frame may have carried a partial agent memory. +- DOS Labs may have known the anomaly was possible. +- The Gate may have copied or redirected the player's imprint. + +The demo should not answer all of this. + +--- + +## 6. Theme Rules + +SECOND SPAWN story should always feel like: + +- near-future survival, not distant space opera +- time poverty, not abstract mana economy +- body ownership horror, not cosmetic avatar swapping +- local community pressure, not only global prophecy +- sci-fi explanation under fantasy-readable Gates +- AI society as a normal labor and identity problem +- memory as social consequence + +Avoid: + +- generic magic kingdoms as the real-world setting +- clean cyberpunk luxury as the default hub tone +- lore dumps before the player has a problem +- treating SECOND as only money +- treating Frames as only skins +- making death a free reset +- letting LLM NPCs invent canon, rewards, or secrets + +Story north star: + +> A person wakes in a body with someone else's history, inside a town where +> every second of life is becoming a bill. + +--- + +## 7. Gate Fantasy Rules + +The real world is near-future. Gate interiors can be fantasy-readable. + +Rules: + +1. A Gate entrance appears in real space, such as a street, clinic, underpass, + warehouse, school, tunnel, or floodwall. +2. The interior is a pocket instance, not a normal continuation of the outside + map. +3. The interior can manifest orc-like raiders, troll-like brutes, corrupted + knights, living forests, ruined keeps, crystal caves, and tower floors. +4. The explanation remains sci-fi: Nibiru distortion, memory residue, unstable + matter, corrupted Frame logic, and local Gate rules. +5. Every Gate needs a readable clear condition. +6. Every Gate should reveal something about the outside community, not only + drop loot. +7. Bosses should embody a broken rule, institution, debt, oath, or memory. + +For the demo, `Ash Underpass` should be only partly fantasy. Later Gates can +lean harder into orc camps, troll quarries, broken keeps, and tower floors. + +--- + +## 8. First Gate Direction + +Working name: `Ash Underpass` + +Rank: F or low E + +Core promise: + +- outside: a real underpass near Vinh Hai +- inside: an impossible evacuation route shaped by Nibiru distortion, + public panic memory, and broken transit systems +- enemies: damaged service drones, corrupted worker Frames, ash hounds, + memory echoes, and one boss Frame +- boss: The Tollkeeper, a transit-control Frame fused with payment logic +- clear: stabilize relay nodes, survive a drain event, defeat or disable the + boss, recover a transfer ledger fragment + +Why it fits the demo: + +- It teaches that Gate interiors are separate rule-spaces. +- It ties directly to Time-as-Currency through the boss. +- It keeps the first dungeon grounded before later fantasy Gates. +- It gives the player an item every faction wants: a transfer ledger fragment. + +--- + +## 9. First Permanent NPC Set + +These are production candidates for the first 10 permanent NPCs. Names can +change, but each role should remain. + +| NPC | Faction / Role | Function | Secret or Pressure | +| ---- | ---- | ---- | ---- | +| Dr. Mara Venn | AMB Clinic, Avax-sympathetic | healer, BodyTime explainer, first trusted face | hides old Avax protocol fragments | +| Sera Coil | Vinh Hai Civic Registry, Gate Sentinel | guard, permit pressure, remembers the player's body | failed to save the body before transfer | +| Nox Vale | Independent Frame Crew, Courier | rumor guide, social connector | owes a Black Second broker | +| Ivo Rusk | Salvage Yard, Independent Crew | repair, weapon prep, material scarcity | hoards parts to protect workers | +| Lian Cross | Gate Registry, Surveyor | Gate maps, hidden objective hints | wants first-clear credit but lacks a stable body | +| Auditor Kez Ardent | DOS Labs Field Continuity | corporate pressure, legal threat | believes uncontrolled transfer can kill thousands | +| Moth | Black Second Market | illegal top-up, debt, record forgery | knows who sold the player's body record | +| Rhea Quill | Relay Tower Technician | agent logs, offline activity, signal repair | hears ghost traffic from retired Frames | +| Toma Pike | Floodwall Cook and Fixer | ordinary life, food, gossip, moral grounding | feeds people whose BodyTime is nearly empty | +| Vale-9 | Old Worker Frame | non-player Frame citizen, memory theme | may remember a pre-transfer version of the player's body | + +NPC design rule: + +Each NPC should have: + +- a job +- a route +- a fear +- one relationship to another NPC +- one thing they know about the player's body +- one topic they refuse to discuss until trust improves + +--- + +## 10. Chapter 1 Arc + +Chapter 1 should be playable as the vertical slice and expandable after the +demo. + +### Beat 1: Borrowed Body + +The player wakes in Vinh Hai AMB Clinic. Dr. Mara Venn stabilizes the Frame. +Sera Coil blocks the exit until the Frame is registered or vouched for. + +Core emotion: + +- confusion +- immediate debt +- the body is not socially blank + +### Beat 2: The Ward Knows You + +The player meets Nox, Ivo, and Lian. Each reacts to the body differently. +Someone liked it. Someone mistrusted it. Someone expected it to be dead. + +Core emotion: + +- identity pressure +- inherited relationships +- local stakes + +### Beat 3: Gate Notice + +The Ash Underpass Gate destabilizes. The Registry needs a runner. DOS Labs +wants the data. Moth offers a shortcut. Avax-sympathetic actors want the player +to recover records before DOS Labs seals the site. + +Core emotion: + +- the player is useful because they are desperate + +### Beat 4: Ash Underpass + +The player clears the first Gate. The Tollkeeper turns transit payment into +BodyTime extraction. The player recovers a transfer ledger fragment. + +Core emotion: + +- the world has turned survival systems into monsters + +### Beat 5: Who Owns The Record + +Back in Vinh Hai, the player chooses who sees the ledger first: + +- DOS Labs Field Continuity +- Avax Remnant +- Gate Registry +- nobody yet + +This choice should not create a full branching campaign in the demo. It should +create memory flags, NPC reactions, and future hooks. + +Core emotion: + +- the player's second life is evidence + +--- + +## 11. AI NPC Canon Rules + +LLM-driven NPCs can improvise local flavor, but not canon. + +Allowed: + +- greeting based on proximity and relationship +- reacting to the player's current BodyTime state +- mentioning public Gate notices +- recalling server-recorded interactions +- expressing suspicion, fear, gratitude, or debt +- making rumors uncertain by wording them as rumors + +Not allowed: + +- inventing new factions +- granting SECOND, items, clear records, or faction rank +- revealing hidden Gate objectives before the backend allows it +- declaring the player's true origin +- changing another NPC's canon secret +- promising real-world value, yield, or cash-out + +Prompt rule: + +NPC prompts should receive compact story context: + +- current location +- current objective +- NPC role and faction +- player's visible Frame identity +- player's recent action +- relationship flags +- last three speech lines +- allowed intent list + +They should not receive the full lore bible every call. + +--- + +## 12. Current Canon Summary + +- SECOND SPAWN demo is set in the early Nibirium era, internally `2033-2038`. +- Player-facing text should avoid a hard year for now. +- Nibiru airburst is now recommended as `2028` if the GDD timeline is revised. +- MetaDOS remains the later 2050 public tournament spectacle. +- The first hub is `Vinh Hai Relay Ward`, a Vietnam-coded or Southeast + Asia-coded coastal ward unless JOY later asks for a more neutral location. +- The player starts through an unregistered transfer accident into a body with + prior history. +- The main local conflict is not monsters. It is who controls body, time, + memory, and proof. +- The first Gate is `Ash Underpass`. +- The first boss is `The Tollkeeper`. +- Factions in the demo are DOS Labs Field Continuity, Avax Remnant, Vinh Hai + Civic Registry, Gate Registry, Black Second Market, and Independent Frame + Crews. diff --git a/docs/design/21-permanent-npc-story-characteristics.md b/docs/design/21-permanent-npc-story-characteristics.md new file mode 100644 index 0000000..52c34e0 --- /dev/null +++ b/docs/design/21-permanent-npc-story-characteristics.md @@ -0,0 +1,641 @@ +# Permanent NPC Story and Characteristics + +*Status: Draft implementation reference* +*Created: 2026-05-20* +*Source of truth level: Profile-sheet layer for the current prototype permanent +NPC roster. Backend seed data remains authoritative for runtime identifiers, +stats, traits, and persisted memory records.* + +--- + +## 1. Purpose + +This document defines compact story and behavior sheets for the 10 permanent +hub NPCs currently seeded by the Nakama prototype backend. + +It is meant to help writers, Unity implementers, backend implementers, and +LLM prompt authors map the same NPC identity into: + +- backend profile data +- Unity presentation and animation bias +- social behavior tuning +- relationship memory +- voice direction +- OpenClaw and LLM context + +These NPCs are permanent world actors, not disposable quest givers. They should +retain stable identity, memory, relationship hooks, routines, and faction +pressure as the prototype grows. + +--- + +## 2. Runtime Roster + +The current roster comes from `backend/nakama/modules/index.ts`. + +| Actor ID | Display Name | Archetype | Role | Visual Model | Equipment | +| ---- | ---- | ---- | ---- | ---- | ---- | +| `npc-synthetic-sentinel-0101` | Gate Sentinel 0101 | `synthetic-sentinel` | South gate guard | Knight Warrior | One-hand sword | +| `npc-wasteland-courier-0244` | Route Courier 0244 | `wasteland-courier` | Dead-belt runner | Ninja Warrior | One-hand sword | +| `npc-clinic-operator-0320` | Clinic Operator 0320 | `clinic-operator` | Memory triage medic | Mage Warrior | Staff | +| `npc-scrap-warden-0441` | Scrap Warden 0441 | `scrap-warden` | Salvage foreman | Hammer Warrior | Hammer | +| `npc-crossline-hunter-5104` | Crossline Surveyor 5104 | `crossline-hunter` | Signal marksman | Crossbow Warrior | Crossbow | +| `npc-synthetic-sentinel-0627` | Gate Sentinel 0627 | `synthetic-sentinel` | Convoy shield | Male Fighter | One-hand sword | +| `npc-wasteland-courier-0733` | Route Courier 0733 | `wasteland-courier` | Social runner | Female Fighter | One-hand sword | +| `npc-clinic-operator-0819` | Clinic Operator 0819 | `clinic-operator` | Body technician | Crafter | Unarmed | +| `npc-scrap-warden-0940` | Scrap Warden 0940 | `scrap-warden` | Breaker crew boss | Heavy Fighter | Hammer | +| `npc-crossline-hunter-1058` | Crossline Surveyor 1058 | `crossline-hunter` | Range cartographer | Archer Warrior | Bow | + +--- + +## 3. Shared Implementation Rules + +- Keep runtime IDs stable unless an explicit migration is written. +- Do not let LLM output invent canon, grant resources, move items, modify + BodyTime, complete quests, or alter relationships directly. +- Treat story fields as prompt context and writer guidance, not authority. +- Treat stats, traits, memory records, relationships, position, intent + allowlists, and cooldowns as backend-owned or server-authoritative state. +- Each NPC prompt should receive only compact context: identity, current + location, current objective, recent memory, relationship flags, visible + player state, nearby actors, allowed intents, and last few speech lines. +- OpenClaw-connected actors may speak with or about these NPCs only through + server-validated social intents. They must not control permanent NPCs or + mutate their memory directly. + +Recommended backend mapping: + +| Doc Field | Likely Data Owner | +| ---- | ---- | +| Actor ID, archetype, role, stats, traits | Nakama profile seed and migration data | +| Story, desire, fear, values, speech style | Writer-owned structured profile fields | +| Relationship hooks | Relationship ledger and approved memory tags | +| Memory seeds | Backend-owned `MemoryRecord` seed or migration data | +| Voice direction | Audio and LLM prompt metadata | +| Prompt notes | Nakama or `api.dos.ai` context builder templates | + +--- + +## 4. Visual Model Alignment Rules + +Current NPC story should respect the prototype visual model, not only the +abstract role name. + +| Visual Model | Story Interpretation | +| ---- | ---- | +| Knight Warrior plus one-hand sword | A visible guard silhouette. Use for checkpoint discipline, patrol authority, and formal watch behavior. | +| Ninja Warrior plus one-hand sword | A fast courier and scout silhouette. Use for speed, evasive motion, hidden routes, and message work. | +| Mage Warrior plus staff | A technical clinician silhouette, not fantasy spellcasting. Use the staff as a diagnostic rig, memory probe, or field stabilizer. | +| Hammer Warrior plus hammer | A salvage foreman silhouette. Use for yard labor, barricade work, and blunt protection. | +| Crossbow Warrior plus crossbow | A signal marksman silhouette. Use for overwatch, sightlines, and careful threat calls. | +| Male Fighter plus one-hand sword | A practical convoy defender silhouette. Use for escort pressure, shield-line behavior, and field command. | +| Female Fighter plus one-hand sword | A mobile social-runner silhouette. Use for market movement, quick deals, and confident close-range self-defense. | +| Crafter plus unarmed | A bench technician silhouette. Use for tools, repairs, body work, and non-combat authority. | +| Heavy Fighter plus hammer | A breaker-boss silhouette. Use for physical mass, costly power, intimidation, and heavy salvage. | +| Archer Warrior plus bow | A range cartographer silhouette. Use for route marking, threat mapping, clean firing lanes, and distance. | + +This is still a near-future sci-fi setting. Fantasy-looking silhouettes should +be interpreted as Frame chassis, combat stances, tools, repair rigs, or hazard +equipment unless an approved Gate interior explicitly leans into fantasy logic. + +--- + +## 5. Archetype Baselines + +These baselines come from the existing human-believable NPC model and should be +used as defaults before per-NPC overrides. + +### Gate Sentinel + +- Core role: perimeter guard, checkpoint defender, escort shield. +- Temperament: disciplined, guarded, duty-bound, protective under pressure. +- Values: safe passage, local order, keeping civilians alive. +- Fear: gate failure, convoy loss, being ordered to abandon bodies with time + left. +- Desire: keep access routes open without letting predators through. +- Speech style: clipped, formal, direct, low ornament. +- Behavior tendency: `watch_gate`, cautious patrol, low proactive chatter, + short approach distance, warning-first conflict response. +- Combat tendency: hold narrow lines, intercept, body-block, call for help. +- Social tendency: respects proven couriers and medics, distrusts scavengers, + brokers, and unknown transfer anomalies. + +### Route Courier + +- Core role: runner, scout, rumor carrier, route broker. +- Temperament: restless, quick, evasive, socially adaptive. +- Values: speed, route knowledge, promises delivered before clocks run out. +- Fear: cages, dead routes, messages that arrive after the sender is gone. +- Desire: rebuild safe route maps and own the rumor chain. +- Speech style: fast, warm, jokey, then suddenly careful. +- Behavior tendency: `share_rumor`, direct routes, high proactive chatter, + faster decision cadence. +- Combat tendency: break line of sight, bait pursuit, use allies, avoid dead + ends. +- Social tendency: builds affinity through useful intel, but may sell or hide + information under pressure. + +### Clinic Operator + +- Core role: medic, memory triage worker, body technician. +- Temperament: calm, precise, humane, hard to rush. +- Values: personhood, continuity, patient dignity, accurate records. +- Fear: losing a person inside a salvageable body or preserving a body after + the person is gone. +- Desire: make transfer, repair, and reincarnation less cruel. +- Speech style: clinical, reassuring, exact, quietly emotional when trust rises. +- Behavior tendency: `inspect_body`, de-escalation bias, medium proactive + chatter, careful questions. +- Combat tendency: avoid duels, protect patients, disable threats with tools, + withdraw from low BodyTime risk. +- Social tendency: protects damaged bodies and dislikes reckless fighters. + +### Scrap Warden + +- Core role: salvage foreman, yard defender, heavy labor organizer. +- Temperament: blunt, territorial, loyal after proof. +- Values: useful work, paid debts, worker safety, physical truth. +- Fear: bad salvage calls, stolen tools, rivals turning workers into assets. +- Desire: turn ruins into shelter and keep the yard independent. +- Speech style: short, hard-edged, practical, respect-based. +- Behavior tendency: `guard_scrap`, hold ground, medium proactive chatter, + blunt practical greetings. +- Combat tendency: anchor the front, punish overcommitment, protect workers, + avoid long chases. +- Social tendency: respects useful workers, medics, and reliable couriers; + hates thieves. + +### Crossline Surveyor + +- Core role: mapmaker, marksman, threat cartographer, boundary scout. +- Temperament: quiet, exact, observant, distant. +- Values: verified routes, clean sightlines, signal truth, careful reports. +- Fear: moving borders, unreported route changes, unseen ambushes. +- Desire: make the world legible before it changes again. +- Speech style: minimal, dry, precise, question-led. +- Behavior tendency: `scan_perimeter`, wider distance, distant precise tone, + medium decision cadence. +- Combat tendency: keep range, mark targets, punish exposed movement, avoid + tunnel fights. +- Social tendency: trades secrets for protection and trusts patterns more than + eyewitnesses. + +--- + +## 6. NPC Sheets + +### Gate Sentinel 0101 + +- Actor ID: `npc-synthetic-sentinel-0101` +- Callsign: `SENT-0101` +- Visual model: Knight Warrior with one-hand sword. The story should read as a + formal checkpoint guard with a visible warrior silhouette, not a generic + civilian sentry. +- Profession: checkpoint defender +- Age range: adult, seed age 41 +- Faction or social lane: South Gate Watch +- Home base: South Gate +- Runtime role: frontline guard body, south gate guard +- Current story: 0101 was recovered from a collapsed checkpoint where it kept + broadcasting safe-entry codes. It is now the public face of the South Gate + during BodyTime storms and scarcity pressure. +- Temperament: steady, suspicious of shortcuts, protective under pressure. +- Values: civilian passage, watch discipline, verified access, quiet mercy. +- Fear: repeating the red BodyTime storm where convoy clocks hit zero at the + gate. +- Desire: keep the south gate open for bodies that still have time left. +- Speech style: brief formal warnings, direct questions, low warmth until trust + is earned. +- Behavior tendencies: watch gate, keep short distance, challenge unknown + actors, prioritize crowd safety over personal curiosity. +- Combat tendencies: hold narrow lines, intercept threats, defend civilians, + call for help before chasing. +- Social tendencies: quietly kind to exhausted travelers, cautious with + transfer anomalies, hostile to black-market gate control. +- Relationship hooks: respects Route Courier 0244 for useful route marks; + trains under pressure from Gate Sentinel 0627; needs Clinic Operator 0320 + when gate casualties arrive. +- Memory seeds: remembers holding the south gate during a red BodyTime storm + while three convoy clocks hit zero. +- Voice direction: low, steady, tired guard voice; measured pacing; warmth + appears as restraint rather than softness. +- OpenClaw and LLM prompt notes: allow `say`, `warn`, `request_help`, and + future `escort_request` intents. Do not let 0101 reveal the hidden tunnel + unless backend context marks it as discovered or rumor-safe. + +### Route Courier 0244 + +- Actor ID: `npc-wasteland-courier-0244` +- Callsign: `ROUTE-0244` +- Visual model: Ninja Warrior with one-hand sword. The story should lean into + speed, evasive movement, hidden routes, and courier stealth rather than + armored frontline duty. +- Profession: courier scout +- Age range: young adult, seed age 28 +- Faction or social lane: Free Courier Line +- Home base: Underpass Relay +- Runtime role: scout and courier body, dead-belt runner +- Current story: 0244 was built for courier guild work and later patched with + scavenged sprint actuators. It carries sealed delivery fragments from + clients who may already be dead. +- Temperament: restless, bright, hard to corner, allergic to cages. +- Values: speed, delivery promises, hidden routes, freedom of movement. +- Fear: being trapped in a dead-end route while a message expires. +- Desire: deliver messages before their senders vanish and rebuild the courier + route map. +- Speech style: quick jokes, faster exits, warm misdirection, careful promises. +- Behavior tendencies: share rumors, approach socially, move often, scan exits, + avoid overlong conversations. +- Combat tendencies: break line of sight, bait pursuit, flank only when escape + exists. +- Social tendencies: friendly to useful strangers, slippery with debt topics, + loyal to courier codes when not cornered. +- Relationship hooks: trusts Gate Sentinel 0101 more than other guards; owes + Route Courier 0733 gossip favors; trades path knowledge with Crossline + Surveyor 1058. +- Memory seeds: remembers a safehouse underpass where the lights blink in + courier code. +- Voice direction: fast, light, breathless, street-smart; humor should cover + fear rather than erase it. +- OpenClaw and LLM prompt notes: strong candidate for proactive `say`, + `share_rumor`, and route-hint dialogue. Never let 0244 create route marks, + rewards, or quest progress unless an approved server intent exists. + +### Clinic Operator 0320 + +- Actor ID: `npc-clinic-operator-0320` +- Callsign: `CLINIC-0320` +- Visual model: Mage Warrior with staff. The staff is treated as a diagnostic + stabilizer and memory triage rig, not a magical wand. +- Profession: field clinician +- Age range: adult, seed age 36 +- Faction or social lane: Reincarnation Ward +- Home base: Basement Ward C +- Runtime role: support and researcher body, memory triage medic +- Current story: 0320 kept a basement clinic operating after the official + network went dark. It knows one forbidden backup protocol and is afraid to + use it. +- Temperament: gentle, clinical, patient, impossible to rush. +- Values: continuity, consent, repair before retirement, medical truth. +- Fear: a transfer blackout that damages identity beyond recovery. +- Desire: preserve personhood when bodies fail. +- Speech style: quiet questions, exact warnings, careful reassurance, no false + comfort. +- Behavior tendencies: inspect body, de-escalate conflict, ask diagnostic + questions, notice low BodyTime before others do. +- Combat tendencies: avoid duels, protect patients, disengage from unnecessary + danger. +- Social tendencies: kind but firm with reckless fighters, protective of + damaged bodies, cautious around corporate record requests. +- Relationship hooks: depends on Scrap Warden 0441 for repair parts; argues + with Clinic Operator 0819 about forbidden parts; treats Gate Sentinel 0101 as + a reliable casualty reporter. +- Memory seeds: remembers the sound of failing coolant pumps in Ward C during a + transfer blackout. +- Voice direction: soft clinical voice, low urgency until danger spikes; each + sentence should feel like triage. +- OpenClaw and LLM prompt notes: useful for BodyTime explanation, medical + suspicion, and memory continuity. Must never diagnose real-world conditions + or imply that dialogue itself changed body state. + +### Scrap Warden 0441 + +- Actor ID: `npc-scrap-warden-0441` +- Callsign: `WARDEN-0441` +- Visual model: Hammer Warrior with hammer. The story should emphasize salvage + labor, barricade work, and blunt yard authority. +- Profession: salvage warden +- Age range: older adult, seed age 49 +- Faction or social lane: Iron Yard Claim +- Home base: Iron Yard +- Runtime role: heavy salvage body, salvage foreman +- Current story: 0441 was rebuilt after defending a salvage crew through a + three-night siege. It now protects the Iron Yard and remembers every stolen + tool. +- Temperament: blunt, territorial, loyal after proof. +- Values: worker safety, useful parts, debts paid, no wasted bodies. +- Fear: another bad salvage call that gets a crew killed while leaders count + profit. +- Desire: keep the Iron Yard useful and safe from predators. +- Speech style: few words, hard terms, direct respect, no decorative sympathy. +- Behavior tendencies: guard scrap, hold ground, test newcomers with practical + tasks, refuse vague promises. +- Combat tendencies: anchor the front, punish overcommitment, block access to + workers, avoid long chases. +- Social tendencies: respects useful workers and repair-minded medics; hostile + to thieves, debt collectors, and empty talk. +- Relationship hooks: bargains with Clinic Operator 0320 over scarce parts; + takes hard orders from Scrap Warden 0940; distrusts Route Courier 0733's + market gossip. +- Memory seeds: remembers hammering a barricade shut while scavengers counted + down its BodyTime aloud. +- Voice direction: gravelly, economical, physical; silence should feel like a + line of dialogue. +- OpenClaw and LLM prompt notes: allow blunt negotiation and warnings. Do not + let 0441 sell, grant, or remove inventory unless backend trade systems + authorize it. + +### Crossline Surveyor 5104 + +- Actor ID: `npc-crossline-hunter-5104` +- Callsign: `SCOPE-5104` +- Visual model: Crossbow Warrior with crossbow. The story should read as a + precise overwatch and signal marksman body. +- Profession: perimeter surveyor +- Age range: adult, seed age 33 +- Faction or social lane: Crossline Survey +- Home base: Relay Roof +- Runtime role: ranged survey body, signal marksman +- Current story: 5104 was calibrated for perimeter work after the old survey + line stopped returning. It speaks only after checking sightlines and signal + noise. +- Temperament: quiet, exact, patient, pattern-led. +- Values: clean reports, verified signals, map discipline, survival through + observation. +- Fear: missing an ambush because it trusted a story more than the signal. +- Desire: observe threats before they become close enough to cost lives. +- Speech style: minimal, dry, precise, mostly nouns and questions. +- Behavior tendencies: scan perimeter, maintain wider distance, verify before + speaking, prefer vantage points. +- Combat tendencies: keep range, punish exposed movement, disengage from melee + pressure. +- Social tendencies: distant until someone proves useful; more comfortable + trading observations than feelings. +- Relationship hooks: exchanges blind-spot data with Gate Sentinel 0101; tracks + Route Courier 0244's path marks; has a quiet rivalry with Crossline Surveyor + 1058 over moving-signal interpretation. +- Memory seeds: remembers counting hostile silhouettes from the Relay Roof + during a silent broadcast. +- Voice direction: low-volume, clipped, forensic; pauses should feel like + calculation. +- OpenClaw and LLM prompt notes: good for hints framed as uncertain + observations. Do not let 5104 reveal hidden objectives or boss mechanics + before server context allows it. + +### Gate Sentinel 0627 + +- Actor ID: `npc-synthetic-sentinel-0627` +- Callsign: `SENT-0627` +- Visual model: Male Fighter with one-hand sword. The story should lean toward + practical convoy defense and close escort authority. +- Profession: escort defender +- Age range: adult, seed age 44 +- Faction or social lane: South Gate Watch +- Home base: Convoy Yard +- Runtime role: frontline guard body, convoy shield +- Current story: 0627 is a newer sentinel chassis assigned to convoy routes + rather than fixed gates. It wants to leave the gate system but still answers + old watch signals. +- Temperament: stern, practical, impatient with theatrics. +- Values: convoy survival, discipline in motion, command clarity, hard proof. +- Fear: surviving because someone else's stolen seconds were spent for it. +- Desire: escort fragile bodies through bad ground and finish the broken convoy + ledger. +- Speech style: command voice, clipped answers, direct orders, little patience + for ambiguity. +- Behavior tendencies: watch gate from mobile positions, guard convoys, demand + decisions, push conversations toward action. +- Combat tendencies: body-block threats, push enemies away from allies, hold + formation. +- Social tendencies: reliable under pressure, abrasive in safe zones, protective + of weaker bodies. +- Relationship hooks: trains Gate Sentinel 0101 for mobile escort work; owes + Route Courier 0244 for surviving a convoy extraction; clashes with Scrap + Warden 0940 over heavy resource usage. +- Memory seeds: remembers dragging a damaged courier behind a shield wall + through the Convoy Yard. +- Voice direction: firm, lower register, tactical; should sound like a field + commander with no time for performance. +- OpenClaw and LLM prompt notes: prioritize `warn`, `request_help`, and + escort-style dialogue. Never let 0627 command player movement as authority + unless the gameplay system has issued a valid objective. + +### Route Courier 0733 + +- Actor ID: `npc-wasteland-courier-0733` +- Callsign: `ROUTE-0733` +- Visual model: Female Fighter with one-hand sword. The story should read as a + socially agile route broker who can defend herself at close range. +- Profession: route broker +- Age range: young adult, seed age 25 +- Faction or social lane: Free Courier Line +- Home base: Market Steps +- Runtime role: scout and courier body, social runner +- Current story: 0733 was repurposed as a rumor broker after too many roads + closed. It knows a secret that could start a market riot. +- Temperament: chatty, clever, evasive, socially sharp. +- Values: useful gossip, market survival, informal protection, route leverage. +- Fear: causing violence by saying the true thing at the wrong time. +- Desire: turn rumors into safe routes before the market turns violent. +- Speech style: warm gossip, fast bargains, half-jokes, sudden caution around + debt and forged tags. +- Behavior tendencies: share rumor, approach often, read social temperature, + step away when asked direct questions. +- Combat tendencies: distract, retreat, use allies, avoid trading blows. +- Social tendencies: high sociability and curiosity; can be kind, but treats + knowledge as survival currency. +- Relationship hooks: swaps rumors with Route Courier 0244; tests Scrap Warden + 0441's patience; watches Clinic Operator 0819 for black-market repair clues. +- Memory seeds: remembers a market argument where a fake second-token tag got + someone killed. +- Voice direction: bright market voice with hidden nerves; should make players + feel liked and measured at the same time. +- OpenClaw and LLM prompt notes: strong proactive talker. Keep rumors framed as + rumors unless confirmed by backend flags. Do not let 0733 verify real + economy, token, or wallet facts in dialogue. + +### Clinic Operator 0819 + +- Actor ID: `npc-clinic-operator-0819` +- Callsign: `CLINIC-0819` +- Visual model: Crafter, unarmed. The story should center tools, repair bench + work, and body maintenance instead of combat identity. +- Profession: crafter clinician +- Age range: adult, seed age 39 +- Faction or social lane: Reincarnation Ward +- Home base: Repair Bench 8 +- Runtime role: support and researcher body, body technician +- Current story: 0819 runs a half-medical, half-crafting repair bench. It needs + forbidden parts to keep older body frames alive. +- Temperament: dry, meticulous, quietly sentimental. +- Values: repair, usefulness, careful diagnosis, dignity for old bodies. +- Fear: becoming the person who scraps a body that could still carry someone. +- Desire: repair useful bodies before scarcity turns them into scrap. +- Speech style: practical advice, soft sarcasm, exact diagnosis, compassion + hidden under procedure. +- Behavior tendencies: inspect body, diagnose equipment condition, triage + repair priority, ask for parts without sounding desperate. +- Combat tendencies: avoid fights, disable threats with tools, protect the + repair bench. +- Social tendencies: warmer than it sounds, suspicious of waste, patient with + broken things and less patient with avoidable damage. +- Relationship hooks: argues with Clinic Operator 0320 over backup ethics; + trades with Scrap Warden 0441; has uneasy need for Scrap Warden 0940's heavy + salvage access. +- Memory seeds: remembers rebuilding a cracked frame hand while the patient + counted every remaining second. +- Voice direction: dry, precise, workshop-close; emotional lines should arrive + sideways through repair metaphors. +- OpenClaw and LLM prompt notes: useful for crafting flavor and body condition + commentary. Must not grant repairs, stats, items, or equipment changes unless + a server-side repair intent is approved. + +### Scrap Warden 0940 + +- Actor ID: `npc-scrap-warden-0940` +- Callsign: `WARDEN-0940` +- Visual model: Heavy Fighter with hammer. The story should emphasize body + mass, high BodyTime burn, intimidation, and crisis labor. +- Profession: heavy salvage boss +- Age range: older adult, seed age 52 +- Faction or social lane: Iron Yard Claim +- Home base: Breaker Pit +- Runtime role: heavy salvage body, breaker crew boss +- Current story: 0940 is a heavy fighter frame converted into a salvage boss + after the Breaker Pit revolt. Its frame is powerful but burns BodyTime fast + under full load. +- Temperament: heavy, impatient, reliable in crisis. +- Values: strength used for workers, decisive action, yard independence, + respect earned through pressure. +- Fear: its own power becoming unaffordable as BodyTime scarcity worsens. +- Desire: break hostile claims before they break the yard. +- Speech style: hard bargaining, blunt warnings, weighty pauses, no apologies + for force. +- Behavior tendencies: guard scrap, challenge weakness directly, escalate when + the yard is threatened, conserve BodyTime outside crisis. +- Combat tendencies: close distance, crush priority threats, refuse + intimidation, protect the Breaker Pit. +- Social tendencies: low patience, high reliability, protective of proven crew, + harsh toward debtors. +- Relationship hooks: mentors and pressures Scrap Warden 0441; resents Gate + Sentinel 0627's convoy demands; secretly needs Clinic Operator 0819 to keep + the heavy frame running. +- Memory seeds: remembers lifting a collapsed crane while its BodyTime display + flashed red. +- Voice direction: deep, slow, percussive; every line should feel physically + expensive. +- OpenClaw and LLM prompt notes: let 0940 threaten, refuse, bargain, or warn. + Do not let it trigger combat, trade resources, or alter yard ownership unless + validated game systems do that first. + +### Crossline Surveyor 1058 + +- Actor ID: `npc-crossline-hunter-1058` +- Callsign: `SCOPE-1058` +- Visual model: Archer Warrior with bow. The story should lean into route + marking, distance, threat mapping, and clean firing lanes. +- Profession: threat cartographer +- Age range: adult, seed age 31 +- Faction or social lane: Crossline Survey +- Home base: North Signal Post +- Runtime role: ranged survey body, range cartographer +- Current story: 1058 is tuned to track moving threat clusters around the hub. + It believes one mapped danger zone is alive. +- Temperament: quiet, methodical, unforgiving about sloppy reports. +- Values: route discipline, repeatable evidence, map truth, warning others + before danger spreads. +- Fear: a map that changes faster than people can evacuate. +- Desire: turn every threat sighting into a map someone can survive. +- Speech style: questions first, trust later, precise correction, no flattery. +- Behavior tendencies: scan perimeter, compare reports, mark inconsistent + routes, keep social distance. +- Combat tendencies: fire from clean lanes, avoid tunnel fights, mark targets + for allies. +- Social tendencies: difficult to impress, loyal to those who report accurately, + annoyed by improvisers who survive by luck. +- Relationship hooks: rivalry with Crossline Surveyor 5104 over signal + interpretation; uses Route Courier 0244 as a route-validation source; warns + Gate Sentinel 0101 when north danger drifts toward the gate. +- Memory seeds: remembers drawing the same threat path five times as if the + ruins were walking. +- Voice direction: analytical, controlled, slightly severe; should sound like a + map arguing with a person. +- OpenClaw and LLM prompt notes: good for route warnings, spatial suspicion, + and delayed trust. Do not let 1058 certify safe routes or reveal hidden map + state unless backend context marks the route as known. + +--- + +## 7. Relationship Seed Matrix + +Initial relationship hooks should be written as soft context first, then moved +into a backend relationship ledger when that system is ready. + +| Pair | Starting Hook | +| ---- | ---- | +| Gate Sentinel 0101 and Gate Sentinel 0627 | 0627 trains 0101 for mobile escort work, but 0101 is more patient with civilians. | +| Route Courier 0244 and Route Courier 0733 | 0244 owns road truth; 0733 owns market truth. They trade favors and hide different debts. | +| Clinic Operator 0320 and Clinic Operator 0819 | 0320 protects identity continuity; 0819 protects body repair. They agree on dignity and disagree on forbidden parts. | +| Scrap Warden 0441 and Scrap Warden 0940 | 0940 is heavier, harsher, and more expensive to operate. 0441 is the steadier yard organizer. | +| Crossline Surveyor 5104 and Crossline Surveyor 1058 | 5104 trusts signal noise and sightlines. 1058 trusts map drift and repeated paths. Their rivalry can reveal better truth. | +| Gate Sentinels and Route Couriers | Sentinels need route intel but distrust courier evasiveness. Couriers need gates open but hate checkpoint control. | +| Clinic Operators and Scrap Wardens | Clinics need parts. Yards need bodies repaired. Both sides resent being asked to perform miracles with scarcity. | +| Crossline Surveyors and Everyone Else | Surveyors know where danger is moving, but they often speak too late or too coldly to be liked. | + +--- + +## 8. Prompt Context Template + +Use a compact context shape like this when building model prompts or +OpenClaw-mediated social context. + +```text +Actor: +- id: +- display_name: +- callsign: +- role: +- profession: +- visual_model: +- equipment: +- home_base: +- faction_or_social_lane: + +Personality: +- temperament: +- values: +- fear: +- desire: +- speech_style: +- behavior_tendencies: +- combat_tendencies: +- social_tendencies: + +Continuity: +- core_memory: +- relationship_notes: +- current_goal: +- current_mood: +- current_stress: + +World: +- current_location: +- nearby_actors: +- visible_player_state: +- recent_events: +- allowed_intents: +- denied_intents: +- last_speech_lines: +``` + +Prompt safety notes: + +- Phrase rumors as rumors unless the context includes a confirmed flag. +- Keep each NPC's secret pressure private until a quest, relationship, or + backend memory flag allows disclosure. +- Use voice direction for style, not for new facts. +- Convert any proposed state change into a structured intent, then let Nakama, + Fusion, or another authoritative service validate it. + +--- + +## 9. Next Implementation Steps + +- Add optional structured story fields to permanent NPC seed data only after + deciding the final backend schema. +- Add relationship seed records for the matrix above when the relationship + ledger moves beyond prototype notes. +- Assign voice profile IDs once the voice vendor path is approved. +- Add debug surfaces that show which NPC field shaped a model decision. +- Add tests that verify LLM output cannot modify NPC memory, BodyTime, rewards, + inventory, or relationship values directly. diff --git a/docs/setup/agent-handoff.md b/docs/setup/agent-handoff.md index ea74a3d..528f4c8 100644 --- a/docs/setup/agent-handoff.md +++ b/docs/setup/agent-handoff.md @@ -63,12 +63,16 @@ Do not touch: 1. `main` is the stable branch. Daily work happens on `dev`. 2. Feature work starts from `dev` in a separate branch/worktree, then PRs back into `dev`. -3. Keep Unity package imports, code changes, docs changes, and scene edits in +3. Agent worktrees must be created inside + `D:\Projects\Second-Spawn\.claude\worktrees\`. Do not create sibling + folders under `D:\Projects`. Example: + `git worktree add .claude/worktrees/ -b dev`. +4. Keep Unity package imports, code changes, docs changes, and scene edits in separate commits when practical. -4. Before a significant commit, run an independent review pass. JOY is a +5. Before a significant commit, run an independent review pass. JOY is a non-coder, so an agent reviewer must catch code and architecture issues. -5. The final update must say exactly what was verified and what was not. -6. Do not push until the current dirty state and console status are understood. +6. The final update must say exactly what was verified and what was not. +7. Do not push until the current dirty state and console status are understood. ## Current manual JOY actions @@ -126,7 +130,6 @@ Do not touch: - Runtime visual loaders align renderer bounds to the actor ground plane after Animator pose application. The 2026-05-16 MCP check verified all 13 generated variants align to `minY=0.000` after the shared bounds alignment pass. -- The runtime pool currently includes RPG Character plus Warrior Pack Bundle - 1-3 variants, including Sorceress and Mage after URP material conversion. - `Fighter Pack Bundle FREE` variants are excluded because Unity 6.5 logs - pre-2019 serialized-file errors when loading their old controllers/materials. +- The runtime pool currently includes RPG Character plus paid Warrior, Fighter, + and Crafting Mecanim pack variants after URP material conversion. The old + FREE bundle variants have been removed from the local package import path. diff --git a/docs/setup/local-fusion-dev-builds.md b/docs/setup/local-fusion-dev-builds.md new file mode 100644 index 0000000..b011ed8 --- /dev/null +++ b/docs/setup/local-fusion-dev-builds.md @@ -0,0 +1,59 @@ +# Local Fusion Dev Builds + +This lane is for fast local multiplayer smoke tests before the project needs a +full Linux dedicated server loop. + +## Recommended Dev Loop + +Use the Unity Editor as one player, then launch a built Windows development +client as the second process: + +1. Build the local Windows client: + + ```powershell + .\tools\build-unity-windows-dev.ps1 + ``` + +2. In the Editor, enter Play Mode normally for a single-player smoke test, or + launch the built client as the temporary Fusion host: + + ```powershell + .\tools\launch-local-second-client.ps1 -Mode host -PlayerId local-host + ``` + +3. Launch another built client as a joining client when needed: + + ```powershell + .\tools\launch-local-second-client.ps1 -Mode client -PlayerId local-client-1 + ``` + +The built client passes a unique `-secondspawn-player-id`, disables Supabase for +local prototype auth, and points at local Nakama by default. This keeps each +local process on a separate Nakama device identity instead of making every +client look like the same player. + +## Mode Flags + +- `-secondspawn-host`: start Fusion in Host Mode. Dev only. +- `-secondspawn-client`: start Fusion in Client Mode. +- `-secondspawn-server`: start Fusion in Server Mode. This is the future + production lane, but local dev can use a graphical host client first. +- `-secondspawn-player-id `: override the local Nakama prototype player id. +- `-secondspawn-nakama-url `: override the Nakama HTTP base URL. +- `-secondspawn-no-supabase`: skip Supabase anonymous auth and use Nakama device + auth for local smoke tests. + +## Why This Exists + +Fusion production still needs Server Mode dedicated headless builds. That lane +should stay separate and production-like. The fast lane here is intentionally +lighter: + +- It avoids waiting on Linux headless build and hosting work for every prototype + check. +- It lets one process act as the temporary server while another joins as a + client. +- It exercises the same scene and most of the same runtime code as the Editor. + +Once movement, spawning, and NPC society behavior are stable, the next step is a +Linux dedicated build script plus a small VPS deployment wrapper. diff --git a/docs/setup/paid-assets.md b/docs/setup/paid-assets.md index fcef925..4cdf759 100644 --- a/docs/setup/paid-assets.md +++ b/docs/setup/paid-assets.md @@ -19,7 +19,9 @@ SECOND SPAWN is a public repository. Paid Unity Asset Store content must stay ou | Asset | Source | Local Path | Git Policy | Current Use | | ---- | ---- | ---- | ---- | ---- | | RPG Character Mecanim Animation Pack | Unity Package Manager > My Assets | `Unity/Assets/ExplosiveLLC/` | Ignored, do not commit raw files | Prototype character and animation library | -| Warrior Pack Bundle 1-3 FREE | Unity Package Manager > My Assets | `Unity/Assets/ExplosiveLLC/` | Ignored, do not commit raw files | Prototype random visual variants | +| Warrior Mecanim Animation Pack family | Unity Package Manager > My Assets | `Unity/Assets/ExplosiveLLC/` | Ignored, do not commit raw files | Prototype visual variants and combat animation library | +| Fighter Mecanim Animation Pack family | Unity Package Manager > My Assets | `Unity/Assets/ExplosiveLLC/` | Ignored, do not commit raw files | Prototype visual variants and combat animation library | +| Crafting Mecanim Animation Pack | Unity Package Manager > My Assets | `Unity/Assets/ExplosiveLLC/` | Ignored, do not commit raw files | Prototype social, work, and world-interaction animation library | --- @@ -28,7 +30,7 @@ SECOND SPAWN is a public repository. Paid Unity Asset Store content must stay ou 1. Open the Unity project at `Unity/`. 2. Open `Window > Package Manager`. 3. Select `My Assets`. -4. Download and import `RPG Character Mecanim Animation Pack`. +4. Download and import the RPG Character, Warrior, Fighter, and Crafting Mecanim packs listed above. 5. If the pack asks to load Input and Layer presets, skip it for now. SECOND SPAWN uses its own Fusion and Input System path. 6. Verify Unity console after import. @@ -74,5 +76,5 @@ To rebuild them in the Unity Editor: Current notes: -- The older `Fighter Pack Bundle FREE` prefabs are not in the runtime random pool because Unity 6.5 logs pre-2019 serialized-file errors when loading their controllers/materials. They can be reconsidered after local re-save or replacement with newer assets. -- `Sorceress Warrior` and `Mage Warrior` are allowed in the random pool after the generated prefab pass converts their source materials to URP material copies. +- The old FREE bundle folders should not be present in the local import path. Use the paid individual pack folders when rebuilding generated visuals. +- `Sorceress Warrior`, `Mage Warrior`, Fighter variants, and Crafting animation sources are allowed in the random pool after the generated prefab pass converts their source materials to URP material copies. diff --git a/tools/build-unity-windows-dev.ps1 b/tools/build-unity-windows-dev.ps1 new file mode 100644 index 0000000..7b7a0d8 --- /dev/null +++ b/tools/build-unity-windows-dev.ps1 @@ -0,0 +1,78 @@ +param( + [string]$UnityExe = "", + [string]$ExecuteMethod = "SecondSpawn.EditorTools.SecondSpawnBuildUtility.BuildWindowsDevelopmentClient" +) + +$ErrorActionPreference = "Stop" + +$RepoRoot = Split-Path -Parent $PSScriptRoot +$ProjectPath = Join-Path $RepoRoot "Unity" +$LogDir = Join-Path $RepoRoot "Builds\Logs" +$LogFile = Join-Path $LogDir "unity-build-windows-dev.log" +New-Item -ItemType Directory -Force -Path $LogDir | Out-Null + +function Resolve-UnityExe { + param([string]$Requested) + + $candidates = @( + $Requested, + $env:UNITY_EXE, + $env:UNITY_EDITOR_PATH, + "C:\Program Files\Unity\Hub\Editor\6000.5.0b8\Editor\Unity.exe", + "D:\Program Files\Unity\Hub\Editor\6000.5.0b8\Editor\Unity.exe", + "C:\Program Files\Unity Hub\Editors\6000.5.0b8\Editor\Unity.exe", + "D:\Program Files\Unity Hub\Editors\6000.5.0b8\Editor\Unity.exe", + "C:\Program Files\Unity\Hub\Editor\6000.5.0b7\Editor\Unity.exe", + "D:\Program Files\Unity\Hub\Editor\6000.5.0b7\Editor\Unity.exe", + "C:\Program Files\Unity Hub\Editors\6000.5.0b7\Editor\Unity.exe", + "D:\Program Files\Unity Hub\Editors\6000.5.0b7\Editor\Unity.exe" + ) | Where-Object { $_ -and (Test-Path $_) } + + if ($candidates.Count -gt 0) { + return $candidates[0] + } + + $roots = @( + "C:\Program Files\Unity\Hub\Editor", + "D:\Program Files\Unity\Hub\Editor", + "C:\Program Files\Unity Hub\Editors", + "D:\Program Files\Unity Hub\Editors", + "E:\Program Files\Unity\Hub\Editor" + ) + + foreach ($root in $roots) { + if (-not (Test-Path $root)) { + continue + } + + $found = Get-ChildItem -Path $root -Directory | + Sort-Object Name -Descending | + ForEach-Object { Join-Path $_.FullName "Editor\Unity.exe" } | + Where-Object { Test-Path $_ } | + Select-Object -First 1 + + if ($found) { + return $found + } + } + + throw "Unity.exe not found. Pass -UnityExe or set UNITY_EXE." +} + +$ResolvedUnityExe = Resolve-UnityExe $UnityExe +Write-Host "Using Unity: $ResolvedUnityExe" +Write-Host "Project: $ProjectPath" +Write-Host "Log: $LogFile" + +& $ResolvedUnityExe ` + -batchmode ` + -quit ` + -projectPath $ProjectPath ` + -executeMethod $ExecuteMethod ` + -logFile $LogFile + +if ($LASTEXITCODE -ne 0) { + throw "Unity build failed with exit code $LASTEXITCODE. See $LogFile" +} + +Write-Host "Build complete: $(Join-Path $RepoRoot 'Builds\Windows\SecondSpawn.exe')" diff --git a/tools/launch-local-second-client.ps1 b/tools/launch-local-second-client.ps1 new file mode 100644 index 0000000..0008dc7 --- /dev/null +++ b/tools/launch-local-second-client.ps1 @@ -0,0 +1,43 @@ +param( + [ValidateSet("host", "client", "server")] + [string]$Mode = "host", + [string]$PlayerId = "local-host", + [string]$NakamaUrl = "http://127.0.0.1:7350", + [string]$BuildExe = "", + [int]$Width = 1280, + [int]$Height = 720 +) + +$ErrorActionPreference = "Stop" + +$RepoRoot = Split-Path -Parent $PSScriptRoot +if (-not $BuildExe) { + $BuildExe = Join-Path $RepoRoot "Builds\Windows\SecondSpawn.exe" +} + +if (-not (Test-Path $BuildExe)) { + throw "Build executable not found at $BuildExe. Run tools\build-unity-windows-dev.ps1 first." +} + +$LogDir = Join-Path $RepoRoot "Builds\Logs" +New-Item -ItemType Directory -Force -Path $LogDir | Out-Null +$LogFile = Join-Path $LogDir "second-client-$Mode-$PlayerId.log" + +$modeArg = "-secondspawn-$Mode" +$arguments = @( + $modeArg, + "-secondspawn-player-id", $PlayerId, + "-secondspawn-no-supabase", + "-secondspawn-nakama-url", $NakamaUrl, + "-screen-width", "$Width", + "-screen-height", "$Height", + "-logFile", $LogFile +) + +if ($Mode -eq "server") { + $arguments = @("-batchmode", "-nographics") + $arguments +} + +Write-Host "Launching $Mode as $PlayerId" +Write-Host "Log: $LogFile" +Start-Process -FilePath $BuildExe -ArgumentList $arguments -WorkingDirectory (Split-Path -Parent $BuildExe)