Advanced Faction and Diplomacy Script Template

Advanced Faction and Diplomacy Script Template

6

10

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 /faction management mode

  • Project 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/showstats and /hidestats for optional visible output

Quick Start

Step 1: Customize Data Tables

Open Advanced_Faction_Management_Template.js and modify these tables:

  1. STAT_NAMES — Rename the 7 stats to match your setting

  2. RESOURCE_NAMES — Rename the 5 resource types

  3. POP_NAMES — Rename the 3 personnel types (index 3 is always morale/loyalty)

  4. PROJECT_TABLE — Replace the 20 example buildings with your own

  5. NATION_TABLE — Replace the 6 example factions with your rivals

  6. LORE_ENTRIES — Replace example lore with your world’s content

  7. TIMELINE_EVENTS — Replace example events with your story beats

  8. 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 /build commands

  • RECRUIT_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.

  1. Build a pipe-delimited string of category IDs + data digits

  2. Convert each digit to its zero-width character equivalent

  3. Wrap with header/footer markers

  4. Inject into context.character.scenario with reproduction instructions

  5. On next execution, scan recent messages backward for the state block

  6. 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:

  1. Advances all active projects

  2. Applies effects from completed projects

  3. Sets infrastructure bits for completed buildings

  4. Generates passive resources from infrastructure

  5. 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:

  1. Replace STAT_NAMES with 7 stats appropriate for my setting
  2. Replace RESOURCE_NAMES with 5 resource types that fit my setting
  3. Replace POP_NAMES with 3 personnel types (index 3 must stay as morale/loyalty)
  4. Replace all 20 entries in PROJECT_TABLE with buildings appropriate for my setting
  5. Replace NATION_TABLE with my scenario's rival factions (up to 6)
  6. Replace LORE_ENTRIES with my world's lore
  7. Replace TIMELINE_EVENTS with my story's key events
  8. Update BUILD_ALIASES to match the new project names
  9. Update STAT_KEYWORDS with keywords appropriate for my setting
  10. Update DEFAULT_STATE starting values
  11. 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:

  1. Rename all stats, resources, and personnel to fit the setting
  2. Create 20 buildings/projects appropriate for this setting
  3. Design 6 rival factions with appropriate names
  4. Write lore entries for key locations, organizations, and characters
  5. Set up timeline events for a [DURATION]-month campaign
  6. Adjust all keyword tables for this setting's vocabulary
  7. Set appropriate starting values

Debugging Prompt

My faction management template isn't working. Here's the file:

[ATTACH YOUR FILE]

Issues: [DESCRIBE PROBLEMS]

Please:

  1. Check for syntax errors
  2. Verify DEFAULT_STATE digit strings match the schema
  3. Verify BUILD_ALIASES map to valid project IDs
  4. Check stat names in statEffect/popEffect match STAT_NAMES/POP_NAMES
  5. 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_KEYWORDS contains keywords your players actually use

  • Check that stat names match STAT_NAMES exactly

  • Enable DEBUG_MODE: true to see parsed values

  • Check debug output for “Extracted state” to confirm state persistence

Projects Not Completing

  • Days must advance for projects to progress

  • Check that TIME_TRACKING: true

  • Verify the day counter is incrementing in debug output

Diplomacy Not Working

  • Verify faction names match NATION_TABLE aliases

  • Check DIPLOMACY_SYSTEM: true

  • Ensure diplomacy string is 12 digits

Lore Not Activating

  • Check keyword spelling (case-insensitive matching)

  • Verify LORE_ENGINE: true

  • Check minMessages is not set too high

  • Enable DEBUG_MODE: true to see which entries activate

State Not Persisting

  • The AI must reproduce hidden characters. Verify character card includes reproduction instructions.

  • Increase SEARCH_DEPTH if conversations are long

  • Check 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 FEATURES object syntax is correct

  • Ensure no essential code sections were deleted

proxy allowed

Published chats

0

comments

Leave a comment or feedback for the creator ❤️