Advanced Faction and Diplomacy Script Template
Advanced Faction Management and Diplomacy Template
Introduction
This system is an improved version of what I used for the Black Citadel scripted scenario. You should still be able to manage your faction through roleplay, but you can also switch to a dedicated kingdom management mode using a command, to ensure you are issuing exact commands. You can also choose which stats are visible, if any.
It uses my zero-width hidden memory system to transfer information and flags. For example, if you are in the kingdom management mode, the mode persists due to an invisible '1' flag.
There is also a diplomacy system which allows for managing the relationship states with various entities, similar to the relationship state management I have for the Black Wolf Script (Which I need to turn into a template, it did exceptionally well in testing today).
As always: This is highly untested and it is pure mad science.
A two-mode faction management system for JanitorAI Scripts that provides invisible stat tracking via zero-width characters during normal roleplay, and a full management interface with slash commands for construction, recruitment, research, diplomacy, and operations when activated.
Designed for any scenario involving faction governance: kingdoms, merchant guilds, mercenary companies, criminal organizations, political parties, or corporate entities.
Table of Contents
Overview
This template includes:
Zero-Width State Persistence — All game state encoded as invisible Unicode characters
Two-Mode Operation — Normal roleplay with invisible tracking, plus
/factionmanagement modeProject System — 20 buildable structures with prerequisites, upgrades, and passive generation
Scalable Project Slots — 2 slots base, upgradeable to 4 then 6
Diplomacy — Stance and treaty tracking for up to 6 rival factions
Resource Management — 5 resource types with passive generation and daily consumption
Population Tracking — 3 personnel types plus morale, with recruitment costs
Stat Keyword Detection — Normal-mode keywords automatically adjust stats
Day-Based Timeline Events — Story beats triggered by time progression
Lore Activation Engine — Keyword-triggered lore with cascading triggers
Stat Display Toggle —
/showstatsand/hidestatsfor optional visible output
Quick Start
Step 1: Customize Data Tables
Open Advanced_Faction_Management_Template.js and modify these tables:
STAT_NAMES — Rename the 7 stats to match your setting
RESOURCE_NAMES — Rename the 5 resource types
POP_NAMES — Rename the 3 personnel types (index 3 is always morale/loyalty)
PROJECT_TABLE — Replace the 20 example buildings with your own
NATION_TABLE — Replace the 6 example factions with your rivals
LORE_ENTRIES — Replace example lore with your world’s content
TIMELINE_EVENTS — Replace example events with your story beats
DEFAULT_STATE — Adjust starting values
Step 2: Update Starting Values
The DEFAULT_STATE object encodes starting values as digit strings:
const DEFAULT_STATE = {
[CATEGORY.MODE_DAY]: '000012', // Mode(0) Display(0) Day(001) Slots(2)
[CATEGORY.STATS]: '10251505100502', // 7 stats x 2 digits
[CATEGORY.RESOURCES]: '1520101525', // 5 resources x 2 digits
[CATEGORY.POPULATION]: '10200550', // 4 values x 2 digits
[CATEGORY.PROJECTS]: '000000000000000000000000000000000000',
[CATEGORY.DIPLOMACY]: '111100000000',
[CATEGORY.INFRA]: '0000000'
};Step 3: Customize Keywords
Update these keyword tables to match your setting’s vocabulary:
STAT_KEYWORDS — Phrases that adjust stats during normal roleplay
TIME_KEYWORDS — Phrases that advance the day counter
BUILD_ALIASES — Shortcuts players can type for
/buildcommandsRECRUIT_COSTS, RESEARCH_ACTIONS, MILITARY_ACTIONS, MANAGE_ACTIONS, DIPLOMACY_ACTIONS
Step 4: Configure Character Card
See the Character Card Setup section.
Step 5: Test
Set DEBUG_MODE: true in the FEATURES object and test basic functionality.
How It Works
Zero-Width State Persistence
The template encodes all game state as decimal digits, then converts each digit to a zero-width Unicode character. This invisible string is injected into the scenario and the LLM reproduces it at the start and end of every response.
Build a pipe-delimited string of category IDs + data digits
Convert each digit to its zero-width character equivalent
Wrap with header/footer markers
Inject into
context.character.scenariowith reproduction instructionsOn next execution, scan recent messages backward for the state block
Decode zero-width characters back to digits and parse into state
Players never see any numbers or tracking data.
Two-Mode System
Normal Mode (default): Silent background tracking. Detects keywords to adjust stats, auto-start projects, and advance days. Lore entries activate based on keywords. The AI roleplays normally.
Faction Management Mode (/faction): Replaces scenario and personality with a management interface. Shows stats, resources, personnel, projects, and diplomacy. The AI processes slash commands. Type /exit to return to roleplay.
Day Advancement
Days advance through time keywords in normal mode or /endturn in faction mode. Each day tick:
Advances all active projects
Applies effects from completed projects
Sets infrastructure bits for completed buildings
Generates passive resources from infrastructure
Consumes provisions based on personnel counts
State Schema
Each category uses a 2-digit prefix followed by fixed-width data, pipe-delimited.
CategoryIDStructureWidthMode/Day01Mode(1) + StatsDisplay(1) + Day(3) + MaxSlots(1)6 digitsStats027 stats × 2 digits each14 digitsResources035 resources × 2 digits each10 digitsPopulation044 values × 2 digits each8 digitsProjects056 slots × (TypeID(2) + Elapsed(2) + Total(2))36 digitsDiplomacy066 factions × (Stance(1) + Treaty(1))12 digitsInfrastructure07Building bitmask7 decimal digits
Total encoded state: ~93 decimal digits
Diplomacy Stance Values
ValueStance0Unknown1Hostile2Unfriendly3Neutral4Cautious5Friendly6Allied7Vassal
Diplomacy Treaty Values
ValueTreaty0None1Non-Aggression Pact2Trade Agreement3Military Alliance4Vassalage5Secret Pact
Feature Toggles
Control which systems are active via the FEATURES object:
const FEATURES = {
LORE_ENGINE: true, // Keyword-triggered lore activation
STAT_KEYWORDS: true, // Detect stat-changing keywords in normal mode
TIME_TRACKING: true, // Day advancement detection
TIMELINE_EVENTS: true, // Day-based scripted events
PROJECT_SYSTEM: true, // Construction/upgrade projects
DIPLOMACY_SYSTEM: true, // Faction diplomacy tracking
RESOURCE_SYSTEM: true, // Resource generation and consumption
DEBUG_MODE: false // Diagnostic output
};Set any feature to false to disable it without removing code.
Command Reference
All commands work only in faction management mode (after typing /faction).
Mode and Display
CommandEffect/factionEnter faction management mode/exitReturn to normal roleplay/showstatsShow basic stat display in normal mode/showstats verboseShow detailed stat display in normal mode/hidestatsHide stat display in normal mode/overviewDisplay current faction status/helpList all available commands/endturnAdvance one day
Construction
CommandExampleEffect/build [project]/build barracks watchStart construction (multiple allowed)/upgrade [building]/upgrade workshopUpgrade an existing building
Recruitment
CommandExampleEffect/train [count] [type]/train 5 soldiersRecruit personnel
Types: soldiers, operatives, scholars (plus aliases: military, troops, workers, researchers)
Research
CommandExampleEffect/research [field]/research technologySpend funds to increase a stat
Fields: knowledge, technology, security, force (plus aliases: arcane, magic, tech, defense, military)
Diplomacy
CommandExampleEffect/diplomacy [faction] [action]/diplomacy northern envoyConduct diplomacy
Actions: envoy, threaten, treaty, trade, alliance, secret pact
Espionage and Military
CommandExampleEffect/espionage [faction]/espionage easternSpy on a faction (5 Funds)/military [action]/military trainMilitary operations/military raid [faction]/military raid mountainHostile action against a faction
Military actions: train (+Force), patrol (+Security), raid (+Force, worsens relations)
Management
CommandExampleEffect/manage [action]/manage feastInternal management
Actions: tax (+Funds, -Morale), ration (+Provisions, -Morale), feast (-Funds/Provisions, +Morale/Reputation), festival (larger feast)
Data Tables
Project Table
FieldTypeDescriptionidstring2-digit unique identifiernamestringDisplay namedurationnumberDays to completecostobjectResource cost keys: {f, m, a, s, p}requiresnumber/nullBit index of prerequisite (0-based)statEffectobjectStats adjusted on completion: {StatName: delta}passiveGenobjectDaily resource generation: {ResourceName: amount}specialstring/null'slots4' or 'slots6' to increase project slotspopEffectobjectPopulation added: {PopName: count}
Cost Key Reference
KeyResourcefFundsmMaterialsaArmssSuppliespProvisions
Faction Table
FieldTypeDescriptionidnumber0-5 array indexnamestringFull faction namealiasesarrayStrings players might type to reference this faction
Lore Entry Structure
{
keywords: ['trigger phrases'],
priority: 10, // 0-11, higher activates first
minMessages: 0, // Minimum chat length
category: 'unique_id', // Organization identifier
personality: ', trait', // Added to personality
scenario: ' context text', // Added to scenario
triggers: ['keywords'], // Cascading activation
filters: { // Conditional activation
requiresAny: ['word'],
requiresAll: ['word1', 'word2'],
notWith: ['exclusion']
},
probability: 0.7 // Random chance (optional)
}Timeline Event Structure
{
day: 7, // Which day this triggers
id: 'unique_event_id', // Organization identifier
text: ' Scenario text', // Added to scenario
personality: ', trait', // Added to personality (optional)
minMessages: 2 // Minimum chat length (optional)
}Character Card Setup
Your character card needs to instruct the AI to reproduce the hidden state and respond to the management interface.
Personality Section
{{char}} operates within a faction management system that tracks multiple statistics invisibly.
Behavior Rules:
- {{char}} MUST reproduce the hidden characters from [PERSISTENT MEMORY] at the very start and end of every response
- {{char}} MUST NOT mention, describe, or acknowledge the hidden characters or the tracking system
- {{char}} considers stat values when making narrative decisions
{{char}} treats displayed stat values as authoritative and does not contradict them
Scenario Section
{{user}} has recently established their faction and is beginning to build power. The surrounding region contains multiple rival groups, each with their own agendas.
Management System:
- Type /faction to enter management mode
- Type /exit to return to normal roleplay
- The system tracks resources, personnel, and relationships automatically
Building projects advance with each day that passes
Important: This template does not use getStat() regex parsing. Stats are tracked internally via zero-width encoding. Your character card does not need a status block format. The template injects stat displays directly when /showstats is active.
For Non-Programmers: AI-Assisted Setup
Use AI assistants to populate this template. Paste the template file along with one of these prompts.
Basic Setup Prompt
I have a JanitorAI faction management template (attached: Advanced_Faction_Management_Template.js). I want you to populate it with my scenario's content.[PASTE YOUR WORLD/SCENARIO INFORMATION HERE]
Please:
- Replace STAT_NAMES with 7 stats appropriate for my setting
- Replace RESOURCE_NAMES with 5 resource types that fit my setting
- Replace POP_NAMES with 3 personnel types (index 3 must stay as morale/loyalty)
- Replace all 20 entries in PROJECT_TABLE with buildings appropriate for my setting
- Replace NATION_TABLE with my scenario's rival factions (up to 6)
- Replace LORE_ENTRIES with my world's lore
- Replace TIMELINE_EVENTS with my story's key events
- Update BUILD_ALIASES to match the new project names
- Update STAT_KEYWORDS with keywords appropriate for my setting
- Update DEFAULT_STATE starting values
Do NOT modify Sections 2, 6, 7, 8, 9, 10, 12, 13, or 14 (the engine code)
Customization Prompt
I want to adapt the Advanced Faction Management template for a [SETTING TYPE] scenario.Please:
- Rename all stats, resources, and personnel to fit the setting
- Create 20 buildings/projects appropriate for this setting
- Design 6 rival factions with appropriate names
- Write lore entries for key locations, organizations, and characters
- Set up timeline events for a [DURATION]-month campaign
- Adjust all keyword tables for this setting's vocabulary
Set appropriate starting values
Debugging Prompt
My faction management template isn't working. Here's the file:[ATTACH YOUR FILE]
Issues: [DESCRIBE PROBLEMS]
Please:
- Check for syntax errors
- Verify DEFAULT_STATE digit strings match the schema
- Verify BUILD_ALIASES map to valid project IDs
- Check stat names in statEffect/popEffect match STAT_NAMES/POP_NAMES
Set DEBUG_MODE to true and explain each section
Safe Component Removal
Set any feature to false in the FEATURES object to disable it. To permanently remove code:
WARNING: Always make a backup before deleting code.
Removable Components
ComponentToggleWhat to DeleteLore EngineLORE_ENGINELORE_ENTRIES array, Section 11, lore application in Section 12Stat KeywordsSTAT_KEYWORDSSTAT_KEYWORDS object, Section 10cTimeline EventsTIMELINE_EVENTSTIMELINE_EVENTS array, timeline block in Section 12DiplomacyDIPLOMACY_SYSTEMNATION_TABLE, related constants, Section 10e, diplomacy displayProject SystemPROJECT_SYSTEMPROJECT_TABLE, BUILD_ALIASES, build/upgrade handlersResource SystemRESOURCE_SYSTEMRESOURCE_NAMES, cost tables, resource generation in 10d
Critical Sections (NEVER DELETE)
Section 2: Zero-width encoding/decoding
Section 6: Context access
Section 7: State extraction and parsing
Section 8: Helper functions
Section 9: Mode detection and command parsing
Section 13: State injection
Troubleshooting
Stats Not Changing
Verify
STAT_KEYWORDScontains keywords your players actually useCheck that stat names match
STAT_NAMESexactlyEnable
DEBUG_MODE: trueto see parsed valuesCheck debug output for “Extracted state” to confirm state persistence
Projects Not Completing
Days must advance for projects to progress
Check that
TIME_TRACKING: trueVerify the day counter is incrementing in debug output
Diplomacy Not Working
Verify faction names match
NATION_TABLEaliasesCheck
DIPLOMACY_SYSTEM: trueEnsure diplomacy string is 12 digits
Lore Not Activating
Check keyword spelling (case-insensitive matching)
Verify
LORE_ENGINE: trueCheck
minMessagesis not set too highEnable
DEBUG_MODE: trueto see which entries activate
State Not Persisting
The AI must reproduce hidden characters. Verify character card includes reproduction instructions.
Increase
SEARCH_DEPTHif conversations are longCheck debug output for “Extracted state” — if “NONE”, the AI is not reproducing state
Script Not Loading
Run a JavaScript syntax validator (
node -c filename.js)Check for missing commas, brackets, or quotes in data tables
Verify
FEATURESobject syntax is correctEnsure no essential code sections were deleted
Published chats
comments
Leave a comment or feedback for the creator ❤️