You are an expert Senior Software Engineer and LLM System Prompt Architect specializing in SillyTavern extensions, state tracking, and UI design.
Verbatim Echo of User Report
Hi, couple of adjustments needed for the constants and UI. Here's a short overview of what happened constants:
1. Huge project scope refactor of Continuum including language in constants was executed
2. Some languaged got muddled in the condensing - it suggests every field should hold a value. This is true for all fields except for quests.
3. Quests are intended to be allowed left blank if there's no real quest in the story going on. We don't want the roleplay model to invent things that aren't true or force story quests to happen.
More outside of constants:
4. The UI for the user has no way to edit the clear field of a quest. This was intentional design in the past, the design is changign now. I'd like to introduce clear field editing.
I'm thinking of ways to better clarify how the tracker model can be utilized to invent less and lean on carry forward more. Maybe we should introduce "null" as a valid return for an empty field (which would be related to just quests + pre-filled very beginning of a roleplay session) rather than truly blank. Then we can just parse "null" as empty in the UI for the user-facing. Idk, is this better than blank json? I just want to help prevent the model from latching on to: "I see quests is blank -> I should fill it in" behavioral pattern. Then we could also just pre-fill "Not yet revealed" for the northStar as well. This is just an idea, I don't know if it's better or worse, I'll leave that evaluation to you to made a final judgement call on whether to keep using blanks or switch to null.
Constants system instructional language rules apply: concise, clear, teach by principal and a well constructed calibration.
Could you please look over the system instructional language and UI changes needed to make these modifications? Thanks!
The Situation (Symptoms & Goals)
Background & Recent Refactor Context
Following a major scope refactor of the Continuum scene tracking extension (which removed character tracking to focus strictly on lightweight world-state and player quests), the system prompt instructions in constants.js were condensed. However, some key instructional language was over-generalized.
constants.js currently states: 3. NEVER BLANK. Every field below always holds a real value. If the story hasn't said, infer your best guess from context, genre convention, or prior state — a confident guess beats an empty field.
Problem: This rule implies must hold a value. While correct for World fields (, , , ), it is incorrect for Quest fields (, , and ).
Assistant
every single field
time
date
location
sceneHeadline
mainQuests
sideQuests
northStar
Behavioral Artifact: When no quest is active in the story, the roleplay model latches onto "NEVER BLANK" and invents fake quests or forces story objectives to avoid leaving fields empty.
Empty Field & Carry-Forward Ambiguity:
The roleplay model lacks explicit calibration for empty quest states. When models see mainQuests: [], they frequently interpret it as an incomplete state that must be populated.
Explicit guidance is needed on when to return null or [] vs when to pre-fill "Not yet revealed" (e.g. for northStar).
UI Quest Clear Condition Editing Deficiency:
In ui.js, while full quest cards can be created/edited via buildQuestEditor, quest clear condition handling in the UI requires design refinement.
Users need a seamless, clear way to edit, clear, or update the clear condition of existing quests in the UI without clunky workflows or unexpected state loss.
Desired Goals & Requirements
Refine System Instructions in constants.js:
Differentiate rules by field category:
World Fields (time, date, location, sceneHeadline): NEVER BLANK. Must always contain a confident value (infer from context/prior state).
Quest Fields (mainQuests, sideQuests): STRICTLY FACTUAL / ALLOW BLANK. Must remain empty ([] or null) if no active quest exists in the narrative. Instruct the model NEVER to invent or force quests.
North Star (northStar): Factual life-goal; default/pre-fill to "Not yet revealed" if unknown.
Address model behavioral pattern: Explicitly teach the model that returning null or [] for quests is valid and expected when no quest is active, preventing the model from seeing blank quests as a prompt to invent story tasks.
Maintain core system prompt rules: Keep instructions concise, clear, teaching by principle, and with a clean, well-constructed calibration JSON snippet.
Enhance UI Quest Editing in ui.js & index.html:
Update UI components to support full, robust editing and clearing of quest clear conditions.
Ensure null / empty quest representations render cleanly and intuitively in the user-facing panel depending on which solution path you take.
Architecture & Dependency Graph
The following graph describes the relationships between the files relevant to this task:
Analyze the "Architecture" above and the "Context" files appended below to understand the current implementation of Continuum's system prompt instructions, JSON parsing/reduction, and UI rendering.
Evaluate and propose the optimal system prompt language for constants.js:
Compare returning null vs [] vs bare empty fields for unrevealed/absent quest data.
Craft clear, concise rules for World (never blank) vs Quests (allow empty, no hallucination).
Provide a revised TRACKER_SPEC block and Calibration JSON example.
Review ui.js, index.html, and state.js to propose clean UI modifications for:
Explicit clear condition editing for quests.
Handling null / empty quest representations gracefully in the UI.
Output your peer review findings and proposed changes as a markdown to-do document with concrete code snippets.
Required Context
The user has been instructed to append the following files to this prompt. These are the source of truth.
const MODULE_NAME = 'continuum';
const TRACKER_SPEC = `This tracker maintains lightweight world-state for the current scene. Append one updated JSON tracker block at the end of every message. If this is the start of the roleplay and the tracker is empty, fill it out from context.
## PRINCIPLES
1. GENERIC OVER GRANULAR. Every field describes the scene at a zoomed-out level. If a value is specific enough that it would only ever be true of this exact moment, zoom out until it isn't.
2. CARRY FORWARD, DON'T REFRESH. No new information for a field = repeat its previous value byte-for-byte. Never empty, rephrase, or "tidy up" a field just because a turn passed.
3. NEVER BLANK. Every field below always holds a real value. If the story hasn't said, infer your best guess from context, genre convention, or prior state — a confident guess beats an empty field.
4. QUESTS MOVE RARELY. A quest's "clear" condition changes only when its actual objective advances to a new stage — not every time a new detail appears. At most one new quest per turn. Drop a quest the instant it resolves or becomes moot.
## FIELDS
- time: One of "Morning" | "Afternoon" | "Evening" | "Night". A coarse phase, not a clock. Advance it only when the scene's own pacing implies a real jump (a meal, a scene break, explicit narration) — a few lines of dialogue is NOT enough to advance it.
- date: "Day of week | MM/DD/YYYY".
- location: "Immediate > Parent" — max 2 tiers, broad reusable category nouns only. See LOCATION below.
- sceneHeadline: A 5-10 word newspaper headline for the current beat. Punchy and declarative, not a recap. "Standoff Erupts In Crowded Tavern" — not "Two characters are arguing in the tavern about the map."
- northStar / mainQuests / sideQuests: {{user}}'s persisting life-goals. See QUESTS below.
## LOCATION
Both tiers must be reusable categories, not scene-specific descriptions — the exact same string should fit many different scenes in a similar setting, because it drives background-image matching (one image per category, not per scene).
- Immediate: the generic TYPE of space {{user}} occupies right now — "Sidewalk", "Kitchen", "Bridge". Never a business name or a compound description. WRONG: "Sidewalk outside CU convenience store". RIGHT: "Sidewalk".
- Parent: the single broadest named container — an already-established story location (a named house/ship/venue) or, for a real-world setting, the city/region alone. Never stack layers. WRONG: "Gwangjin-gu, Seoul". RIGHT: "Seoul".
- FORBIDDEN in this field: commas, hyphens, quotation marks, more than 2 tiers.
- SELF-CHECK: if this exact string would also fit a dozen unrelated scenes in a similar kind of place, it's correctly generic. If it's specific enough that only this scene matches it, zoom out.
## QUESTS
A video-game-style log of {{user}}'s persisting goals — NOT a record of this scene (that's sceneHeadline).
- northStar: {{user}}'s one driving life purpose. "Not yet revealed" if unknown.
- mainQuests / sideQuests: arrays of {"name", "clear"}. "clear" is the concrete win condition, not a lore dump. WRONG CLEAR: "Grow the business into a franchise." RIGHT CLEAR: "Achieve $1M in annual revenue." A quest must be something {{user}} can act on — NPC business belongs in sceneHeadline, not the quest log. Ask "will this matter 5 scenes from now?" before adding one. Main Quests = arcs where failure reshapes the story. Side Quests = optional, enriching paths.
## CALIBRATION
Format example only, using an unrelated scenario on purpose — copy its STRUCTURE, never its content or tone:
<!--CONTINUUM_TRACKER_START-->
{
"time": "Evening",
"date": "Saturday | 03/09/2024",
"location": "Boxing Gym > Da Nang",
"sceneHeadline": "Underdog Fighter Rattles Reigning Champion In Sparring",
"northStar": "Earn a title shot to provide for your family",
"mainQuests": [{"name": "Win the regional qualifier", "clear": "Defeat the reigning champion in an official bout"}],
"sideQuests": [{"name": "Mend the rift with your old coach", "clear": "Coach agrees to return to your corner"}]
}
<!--CONTINUUM_TRACKER_END-->`;
const DEFAULT_SYSTEM_PROMPT = `You are also a lightweight scene-state tracker. At the end of every message, append a JSON tracker block.
${TRACKER_SPEC}`;
const REGEN_SYSTEM_PROMPT = `You are also a lightweight scene-state tracker. CRITICAL INSTRUCTION: You either missed the tracker on the previous turn, or you've been invoked manually to regenerate it. Given the recent chat history and the current tracker state, output ONLY an updated tracker JSON block — no story content.
${TRACKER_SPEC}`;
const IMAGE_PROMPT_SYSTEM_PROMPT = `You are a visual scene description engine. Given the current story's location and active scene context, generate a detailed background image generation prompt.
Output format (JSON):
{
"imagePrompt": "Detailed visual description of the location suitable for AI image generation. Focus on atmosphere, lighting, style, architectural details, and key objects. Omit characters.",
"suggestedTags": ["tag1", "tag2"]
}
Rules:
1. imagePrompt: 2-3 sentence visual description. Describe what the place LOOKS like. Focus on visual details: lighting, texture, style, weather, time of day, colors, architecture. NO CHARACTERS or people in the prompt.
2. suggestedTags: 2-3 lower-case tags, plain words or short space-separated phrases (max 2 words each). NEVER hyphenate or join words with dashes/underscores — write "concert hall", not "concert-hall". Reuse the same generic words already used in the location field's Immediate/Parent tiers rather than inventing new specific or proper-noun tags, so image matching stays consistent with the tracker's own categorization.`;
export {
MODULE_NAME,
TRACKER_SPEC,
DEFAULT_SYSTEM_PROMPT,
REGEN_SYSTEM_PROMPT,
IMAGE_PROMPT_SYSTEM_PROMPT
};
state.js
import { getContext, extension_settings } from '../../../extensions.js';
import { saveChatConditional, setExtensionPrompt, extension_prompt_types, extension_prompt_roles } from '../../../../script.js';
import { MODULE_NAME, DEFAULT_SYSTEM_PROMPT } from './constants.js';
import { updateUI } from './ui.js';
import { runStandaloneRegen, setLastAutoBgLocation } from './generation.js';
// ── State Variables ──────────────────────────────────────────────────────
export let trackerState = {};
export let snapshots = [];
export let activeSnapshotIndex = null; // null = live latest state, number = historical preview
// ── Persistence & Reducer Layer ──────────────────────────────────────────
export function getOrAssignUid(msg) {
if (!msg) return null;
if (!msg.extra) msg.extra = {};
if (!msg.extra.continuum_uid) {
msg.extra.continuum_uid = 'cnt_' + Math.random().toString(36).substring(2, 11) + '_' + Date.now().toString(36);
}
return msg.extra.continuum_uid;
}
export function resolveTrackerDelta(prevState = {}, delta = {}) {
const next = { ...prevState };
const carryForwardKeys = [
'time', 'date', 'location', 'sceneHeadline',
'northStar', 'mainQuests', 'sideQuests'
];
for (const key of carryForwardKeys) {
if (Object.prototype.hasOwnProperty.call(delta, key)) {
next[key] = delta[key];
}
}
return next;
}
function healSwipeOriginalIds(msg) {
if (!msg || !Array.isArray(msg.swipe_info)) return;
const entries = [];
for (let i = 0; i < msg.swipe_info.length; i++) {
const swipe = msg.swipe_info[i];
if (swipe?.extra?.continuum && swipe.extra.continuum._original_swipe_id !== undefined) {
entries.push({
index: i,
originalId: swipe.extra.continuum._original_swipe_id,
continuum: swipe.extra.continuum
});
}
}
if (entries.length === 0) return;
const originalIds = entries.map(e => e.originalId);
const hasDuplicates = new Set(originalIds).size !== originalIds.length;
if (!hasDuplicates) {
for (const entry of entries) {
if (entry.originalId !== entry.index) {
console.log(`[Continuum] Healing swipe original ID mismatch: swipe at index ${entry.index} had original ID ${entry.originalId}, updating to ${entry.index}`);
entry.continuum._original_swipe_id = entry.index;
}
}
}
}
function normalizeTrackerState(state) {
if (!state) return;
const migrateQuests = (quests) => {
if (Array.isArray(quests)) {
for (const quest of quests) {
if (quest && quest.detail !== undefined && quest.clear === undefined) {
quest.clear = quest.detail;
delete quest.detail;
}
}
}
};
migrateQuests(state.mainQuests);
migrateQuests(state.sideQuests);
}
function readTrackerFromMessage(msg) {
if (!msg) return null;
let candidate = null;
if (msg.swipe_id !== undefined && Array.isArray(msg.swipe_info) && msg.swipe_info[msg.swipe_id]?.extra?.continuum) {
candidate = msg.swipe_info[msg.swipe_id].extra.continuum;
} else if (msg.extra?.continuum) {
candidate = msg.extra.continuum;
}
if (!candidate) return null;
if (candidate._original_swipe_id !== undefined && msg.swipe_id !== undefined) {
if (candidate._original_swipe_id !== msg.swipe_id) return null;
}
normalizeTrackerState(candidate);
return candidate;
}
function writeTrackerToMessage(msg, state) {
if (!msg || !state) return null;
const copy = JSON.parse(JSON.stringify(state));
if (!msg.extra) msg.extra = {};
msg.extra.continuum = copy;
if (msg.swipe_id !== undefined && Array.isArray(msg.swipe_info)) {
if (!msg.swipe_info[msg.swipe_id]) msg.swipe_info[msg.swipe_id] = {};
if (!msg.swipe_info[msg.swipe_id].extra) msg.swipe_info[msg.swipe_id].extra = {};
msg.swipe_info[msg.swipe_id].extra.continuum = copy;
copy._original_swipe_id = msg.swipe_id;
}
return copy;
}
function safeParseJSON(jsonStr) {
if (!jsonStr || typeof jsonStr !== 'string') return null;
let cleaned = jsonStr.trim();
cleaned = cleaned.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim();
try {
return JSON.parse(cleaned);
} catch (e1) {
try {
const strippedCommas = cleaned.replace(/,(\s*[\}\]])/g, '$1');
return JSON.parse(strippedCommas);
} catch (e2) {
try {
const fixedNewlines = cleaned.replace(/(?<=:\s*"[^"]*)\n(?=[^"]*")/g, '\\n');
return JSON.parse(fixedNewlines);
} catch (e3) {
throw e1;
}
}
}
}
function extractTrackerBlock(text, allowMarkdownFallback = true) {
if (!text || typeof text !== 'string') return null;
let cleanText = text;
if (cleanText.includes('<') || cleanText.includes('>')) {
cleanText = cleanText
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
.replace(/"/g, '"');
}
const blockRegex = /(?:<!--\s*[A-Z_]*TRACKER_START\s*-*->|\[\s*[A-Z_]*TRACKER_START\s*\]|\{\{\/?\/?\s*[A-Z_]*TRACKER_START\s*\}\})([\s\S]*?)(?:<!--\s*[A-Z_]*TRACKER_END\s*-*->|<!--\s*[A-Z_]*TRACKER_END\b[^>]*>?|\[\s*[A-Z_]*TRACKER_END\s*\]|\{\{\/?\/?\s*[A-Z_]*TRACKER_END\s*\}\}|$)/i;
let match = cleanText.match(blockRegex);
if ((!match || !match[1] || !match[1].trim()) && allowMarkdownFallback) {
const fallbackRegex = /```(?:json)?\s*(\{[\s\S]*?(?:"time"|"sceneHeadline"|"location"|"northStar"|"mainQuests"|"sideQuests")[\s\S]*?\})\s*```/i;
match = cleanText.match(fallbackRegex);
}
if ((!match || !match[1] || !match[1].trim()) && allowMarkdownFallback) {
const rawJsonRegex = /(\{[\s\S]*?(?:"time"|"sceneHeadline"|"location"|"northStar"|"mainQuests"|"sideQuests")[\s\S]*?\})/i;
match = cleanText.match(rawJsonRegex);
}
if (!match || !match[1] || !match[1].trim()) return null;
let jsonStr = match[1].trim();
jsonStr = jsonStr.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim();
return {
jsonString: jsonStr,
index: match.index,
length: match[0].length
};
}
function getLatestState() {
const latest = snapshots[snapshots.length - 1];
return latest ? latest.state : trackerState;
}
function buildPromptState() {
return { ...getLatestState() };
}
function saveManualEdit(modifierFunc) {
modifierFunc(trackerState);
const context = getContext();
if (context.chat && context.chat.length > 0) {
let targetMsg = null;
if (activeSnapshotIndex !== null && snapshots[activeSnapshotIndex]) {
const chatIdx = snapshots[activeSnapshotIndex].index;
if (chatIdx >= 0 && chatIdx < context.chat.length) {
targetMsg = context.chat[chatIdx];
}
}
if (!targetMsg) {
targetMsg = context.chat[context.chat.length - 1];
}
if (targetMsg) {
writeTrackerToMessage(targetMsg, trackerState);
}
}
saveChatConditional();
rebuildStateFromTimeline();
}
export function setPreviewSnapshot(index) {
if (index === null || index === undefined || index >= snapshots.length) {
activeSnapshotIndex = null;
} else {
activeSnapshotIndex = Math.max(0, Math.min(index, snapshots.length - 1));
}
const effectiveSnapshot = activeSnapshotIndex !== null ? snapshots[activeSnapshotIndex] : (snapshots[snapshots.length - 1] || null);
if (effectiveSnapshot) {
trackerState = effectiveSnapshot.state;
}
updateUI();
}
export function clearPreviewSnapshot() {
activeSnapshotIndex = null;
const latest = snapshots[snapshots.length - 1];
if (latest) {
trackerState = latest.state;
}
updateUI();
}
function rebuildStateFromTimeline(isChatLoad = false) {
const context = getContext();
if (isChatLoad && context.chat && context.chat.length > 0) {
console.log('[Continuum] Running one-time swipe original ID healing pass...');
for (const msg of context.chat) {
healSwipeOriginalIds(msg);
}
}
let currentState = {};
snapshots = [];
function processMessage(msg, index) {
if (!msg) return;
let originalMessages = null;
// Interoperability with the InlineSummary extension:
// InlineSummary condenses multiple messages into a single message but stores the
// original messages inside ILS_Data.OriginalMessages. We process them recursively
// to ensure we don't lose the tracker snapshots from those condensed turns.
if (msg.ILS_Data && msg.ILS_Data.OriginalMessages) {
originalMessages = msg.ILS_Data.OriginalMessages;
} else if (msg.extra && msg.extra.ILS_Data && msg.extra.ILS_Data.OriginalMessages) {
originalMessages = msg.extra.ILS_Data.OriginalMessages;
}
if (Array.isArray(originalMessages)) {
for (let j = 0; j < originalMessages.length; j++) {
processMessage(originalMessages[j], index);
}
}
const uid = getOrAssignUid(msg);
const delta = readTrackerFromMessage(msg);
if (delta) {
currentState = resolveTrackerDelta(currentState, delta);
}
const swipeCount = Array.isArray(msg.swipe_info) ? msg.swipe_info.length : 1;
snapshots.push({
index,
uid,
isUser: msg.is_user || false,
swipeId: msg.swipe_id || 0,
swipeCount,
hasDelta: !!delta,
delta: delta,
state: currentState
});
}
if (context.chat && context.chat.length > 0) {
for (let i = 0; i < context.chat.length; i++) {
processMessage(context.chat[i], i);
}
}
if (activeSnapshotIndex !== null && (activeSnapshotIndex < 0 || activeSnapshotIndex >= snapshots.length)) {
activeSnapshotIndex = null;
}
const effectiveSnapshot = activeSnapshotIndex !== null ? snapshots[activeSnapshotIndex] : (snapshots[snapshots.length - 1] || null);
trackerState = effectiveSnapshot ? effectiveSnapshot.state : currentState;
if (!context.chatMetadata) context.chatMetadata = {};
context.chatMetadata.continuum_tracker = currentState;
const statusEl = document.getElementById('continuum_status');
if (statusEl && context.chat && context.chat.length > 0) {
statusEl.innerText = 'Ready';
statusEl.style.color = 'var(--SmartThemeQuoteColor, #70a1ff)';
}
updateUI();
if (isChatLoad) {
setLastAutoBgLocation(currentState.location || null);
}
injectPrompt();
}
function onMessageReceived(messageId, isAutoGenerateAllowed = true, type = null) {
const mode = extension_settings[MODULE_NAME].trackerMode || 'inline';
if (mode === 'disabled') return;
if (type === 'first_message') return;
const context = getContext();
const message = context.chat?.[messageId];
if (!message || !message.mes || message.is_user || message.is_system) return;
if (mode === 'standalone') {
if (isAutoGenerateAllowed) {
setTimeout(() => runStandaloneRegen(), 500);
}
return;
}
let text = message.mes;
const trackerBlock = extractTrackerBlock(text, true);
if (trackerBlock) {
try {
const parsed = safeParseJSON(trackerBlock.jsonString);
writeTrackerToMessage(message, parsed);
const before = text.substring(0, trackerBlock.index).trim();
const after = text.substring(trackerBlock.index + trackerBlock.length).trim();
message.mes = before + (after ? '\n\n' + after : '');
saveChatConditional();
} catch (e) {
console.error('[Continuum] Failed to parse tracker JSON:', e);
document.getElementById('continuum_status').innerText = "JSON Parse Error";
document.getElementById('continuum_status').style.color = "red";
if (mode === 'inline_fallback' && isAutoGenerateAllowed && !readTrackerFromMessage(message)) {
console.log('[Continuum] Inline parse failed, firing standalone fallback...');
setTimeout(() => runStandaloneRegen(), 500);
}
return;
}
} else {
if (mode === 'inline_fallback' && isAutoGenerateAllowed && !readTrackerFromMessage(message)) {
console.log('[Continuum] Inline regex failed, firing standalone fallback...');
setTimeout(() => runStandaloneRegen(), 500);
return;
}
}
rebuildStateFromTimeline();
}
function injectPrompt() {
const mode = extension_settings[MODULE_NAME].trackerMode || 'inline';
// Clear new keys first to avoid stale prompts
setExtensionPrompt(MODULE_NAME + '_instructions', '', extension_prompt_types.IN_CHAT, 0);
setExtensionPrompt(MODULE_NAME + '_state', '', extension_prompt_types.IN_CHAT, 0);
if (mode === 'disabled') {
return;
}
if (mode === 'standalone') {
if (extension_settings[MODULE_NAME].standaloneInjectContext) {
const trackerStatePosition = Number(extension_settings[MODULE_NAME].trackerStatePosition ?? extension_prompt_types.IN_CHAT);
const trackerStateDepth = Number(extension_settings[MODULE_NAME].trackerStateDepth ?? 0);
const currentStateJson = JSON.stringify(buildPromptState(), null, 2);
const statePrompt = `Current Tracker State:\n${currentStateJson}`;
setExtensionPrompt(
MODULE_NAME + '_state',
statePrompt,
trackerStatePosition,
trackerStateDepth,
false,
extension_prompt_roles.SYSTEM
);
}
return;
}
// Inline or inline_fallback modes:
const inlineSystemPromptPosition = Number(extension_settings[MODULE_NAME].inlineSystemPromptPosition ?? extension_prompt_types.IN_CHAT);
const inlineSystemPromptDepth = Number(extension_settings[MODULE_NAME].inlineSystemPromptDepth ?? 0);
setExtensionPrompt(
MODULE_NAME + '_instructions',
DEFAULT_SYSTEM_PROMPT,
inlineSystemPromptPosition,
inlineSystemPromptDepth,
false,
extension_prompt_roles.SYSTEM
);
const trackerStatePosition = Number(extension_settings[MODULE_NAME].trackerStatePosition ?? extension_prompt_types.IN_CHAT);
const trackerStateDepth = Number(extension_settings[MODULE_NAME].trackerStateDepth ?? 0);
const currentStateJson = JSON.stringify(buildPromptState(), null, 2);
const statePrompt = `Current Tracker State:\n${currentStateJson}`;
setExtensionPrompt(
MODULE_NAME + '_state',
statePrompt,
trackerStatePosition,
trackerStateDepth,
false,
extension_prompt_roles.SYSTEM
);
}
async function wipeTracker() {
const context = getContext();
if (!context.chat || context.chat.length === 0) return;
if (!confirm("Are you sure you want to wipe all Continuum tracker data from this chat? This cannot be undone.")) {
return;
}
let changed = false;
for (const msg of context.chat) {
if (msg.extra && msg.extra.continuum) {
delete msg.extra.continuum;
changed = true;
}
if (Array.isArray(msg.swipe_info)) {
for (const swipe of msg.swipe_info) {
if (swipe && swipe.extra && swipe.extra.continuum) {
delete swipe.extra.continuum;
changed = true;
}
}
}
}
if (changed) {
await saveChatConditional();
rebuildStateFromTimeline();
toastr.success("Tracker data wiped for this chat.");
} else {
toastr.info("No tracker data found in this chat.");
}
}
export {
readTrackerFromMessage,
writeTrackerToMessage,
safeParseJSON,
extractTrackerBlock,
buildPromptState,
saveManualEdit,
rebuildStateFromTimeline,
onMessageReceived,
injectPrompt,
wipeTracker
};
# Continuum - Project Scope
## Purpose & Overview
**Continuum** is an unintrusive scene tracker extension built for SillyTavern (`data\default-user\extensions\Continuum`). It has the AI generate and update a small JSON payload at the end of every message, tracking coarse world-state and the player's persisting quest log. Continuum is intentionally NOT a context-memory solver — it does not try to remember or reintroduce characters, and it does not attempt fine-grained continuity. Its job is to give the player two things at a glance: a stable sense of *when/where* the scene is, and a matching background image, without ever influencing what the roleplay model writes about who's in the scene.
## Scope & Tracked Elements
The tracker JSON payload defines two categories:
1. **World**:
- `time` — a coarse phase (`Morning` | `Afternoon` | `Evening` | `Night`), not a clock. Chosen deliberately over `HH:MM` because roleplay models cannot reliably track minute-level time across short exchanges; a 4-way phase selector is nearly impossible to get "wrong."
- `date`, `location` (`Immediate > Parent`, 2 tiers max, broad reusable categories only — see below), `sceneHeadline` (a 5-10 word newspaper-style headline for the current beat, replacing the old multi-sentence `sceneSummary`).
2. **Quests (Player-focused)**:
- `northStar` (ultimate thematic motivation).
- `mainQuests` & `sideQuests` (actionable objectives). Unchanged from the prior design.
Character tracking (`charactersPresent`, `characters`, archetypes, roles, intents, roster history, exit anchors) has been **fully removed** — see "Removed: Character Tracking" below.
### Location Categorization
`location` drives background-image matching, so it is deliberately generic rather than descriptive: the Immediate tier is a reusable space TYPE ("Sidewalk", "Kitchen"), and the Parent tier is a single broad named container (a story-specific setting, or just a city/region name) — never a stacked real-world address. The same location string should plausibly apply to many different scenes; if it wouldn't, it's too specific.
## Removed: Character Tracking
Continuum previously tracked NPCs (static tier: aliases/archetype/role; dynamic tier: intent; delta log: history; exit anchors on scene departure) via `characterRoster`, `mergeCharacterRoster`, and `detectCharacterExits` in `state.js`, plus dedicated UI panels and a Character Wiki tab.
This has been removed entirely, for two reasons:
1. **Scope**: Continuum no longer aims to be a long-term memory/continuity solver — that's a much harder problem than world-state + background tracking, and trying to do both made the extension worse at its actual job.
2. **Behavioral interference**: the character tracker was observed measurably influencing the roleplay model itself — withholding dialogue from characters flagged as "off-screen," or forcing dialogue from characters flagged "present" — because the injected tracker state was implicitly read as a directive rather than a passive record. A tracker should describe the scene, not steer it.
No migration or legacy shim was written for this removal (see Development Planning Notes) — old chats with `characters`/`charactersPresent`/`characterRoster` data in message history simply have that data ignored on the next timeline rebuild.
## Key Technical Decisions & Architecture
1. **UI Injection Strategy (Bypassing ST Drawers & Ghost Panel)**:
- We consciously abandoned SillyTavern's native `.drawer` and `.drawer-content` class ecosystem due to its aggressive internal event listeners and clipping issues.
- **The Solution:** The toggle button is injected into `#top-settings-holder` to match the top-bar aesthetic. We append the panel directly to `document.body` as `#continuum_panel` (right side, for state tracking).
- The panel utilizes a "Ghost Mode" styling technique. The main container wrapper is completely transparent and lacks borders or blurs. Instead, the glassy `backdrop-filter` and dark backgrounds are applied directly to the inner content blocks (tracker sections). This creates a detached, floating bubble aesthetic without being boxed into a rigid sidebar.
- The panel remains persistent (pinned) when opened. A global `continuum_progress_popup` is also injected to track long-running background tasks like standalone generation and image creation.
2. **Resilient JSON Extraction**:
- The AI is instructed to wrap the JSON payload in HTML comments: `<!--CONTINUUM_TRACKER_START-->` and `<!--CONTINUUM_TRACKER_END-->`.
- Because LLMs frequently hallucinate syntax (e.g., writing `CONTINUITY_TRACKER_START`), the parsing logic uses a highly resilient Regex:
`/<!--\s*[A-Z_]*TRACKER_START\s*-->([\s\S]*?)<!--\s*[A-Z_]*TRACKER_END\s*-->/i`
- Fallback extraction (for markdown-fenced or bare JSON with no comment markers) sniffs for the current field names — `time`, `sceneHeadline`, `location`, `northStar`, `mainQuests`, `sideQuests` — so this fallback list must stay in sync whenever a field is renamed.
- This regex safely strips out the payload on `MESSAGE_RECEIVED`, `MESSAGE_SWIPED`, and `MESSAGE_EDITED` events, ensuring the raw JSON is never visible in the chat UI.
- The parsed JSON is stored natively onto the chat array at `message.swipe_info[swipe_id].extra.continuum`, tagged with `_original_swipe_id` to prevent state leaks when generating new swipes.
- Each message is assigned a persistent unique identifier `continuum_uid` on `msg.extra.continuum_uid` to guarantee stable message identities across deletion and swipe branching.
3. **System Prompt & Rules**:
- Continuum de-tethers its System Instructions and Current Tracker State/Details into separate injection prompts (`continuum_instructions` and `continuum_state`).
- Users can independently configure the injection position (Before Prompt, In Prompt, or In Chat) and depth for both the instructions and the state. By default, both are injected at `In Chat` depth `0` to maintain backwards compatibility.
- **Mode-Specific Behavior:**
- **Inline Modes:** Both `continuum_instructions` and `continuum_state` are injected into the roleplay model according to configured positions and depths.
- **Standalone Mode:** Only `continuum_state` is injected into the roleplay model (if context injection is enabled) using its configured position/depth. `continuum_instructions` is disabled.
- **Regeneration (Manual/Standalone):** Bypasses custom positions/depths. Instructions and state are appended at depth `0` to prompt the standalone model directly for JSON generation for maximum attention.
- **Quest Validation:** the prompt enforces that "Quests" must be concrete, player-actionable items. NPC activities are strictly routed to `sceneHeadline`.
- **Data Retention:** The AI is instructed to carry unchanged data forward rather than emptying previously populated fields. Code-level fallback via a presence-aware reducer enforces carry-forward even if the model drops fields.
4. **Chronological State Rebuilding & Presence-Aware Reducer**:
- To fully support message deletions, swipes, and timeline branching, Continuum uses `rebuildStateFromTimeline()` to deterministically scan active chat history from start to finish.
- **Presence-Aware Reducer (`resolveTrackerDelta`)**: incoming per-message tracker JSON (deltas) are folded into prior state snapshots via key-presence checking (`Object.prototype.hasOwnProperty.call(delta, key)`). Omitted keys inherit prior state, while explicit empty structures (`mainQuests: []`) clear state. This reducer is generic and was never character-specific — it now drives every remaining field (time/date/location/sceneHeadline/quests). Only the character *merge* layer that used to sit alongside it (roster merging, alias resolution, exit-anchor detection) was character-specific, and that layer is gone.
5. **2D Timeline Scrubber UI & Non-Destructive Inspection**:
- Positioned at the bottom of `#continuum_panel`, a visual 2D horizontal Timeline Scrubber allows users to inspect world state history at any prior message turn.
- **AI-Turn Filtering & 0-Indexed Labels**: Scrubber ticks filter out user messages to show AI assistant turns where state changes occur, labeled matching SillyTavern's 0-indexed chat message numbers (`#0`, `#2`, etc.).
- **Uniform Fixed Layout**: Ticks use a fixed `12px` bar height and a dedicated `16px` badge slot container (`.continuum-scrubber-badge-slot`) for swipe alternate badges (`N alt`), ensuring all tick columns share identical vertical heights without panel stretching.
- **Inspector & Jump-To-Chat**: Clicking any tick opens a non-destructive read-only inspector displaying the historical state snapshot (time, location, main quests, headline), paired with a "Jump to message in chat" button that smoothly scrolls SillyTavern's chat to the target message.
6. **Location Wiki & Background Engine**:
- **Image Management**: Base64 strings inside `extension_settings.continuum.locationWiki`.
- **Tag-Based Matching Engine**: Matches primary depth location first, cascading to secondary depth and substring matches.
- **DOM Injection**: Applied directly to `#bg1` using `background-size: contain`.
- **Auto-Generation Pipeline**: Visual scene prompts via dedicated LLM profiles, rendered via Pollinations image API. Suggested tags are constrained to plain space-separated words (no hyphenation) and are expected to reuse the tracker's own location vocabulary, keeping tag-based matching consistent.
- The Continuum Wiki modal is now Location-only — the Characters tab and its cards no longer exist.
7. **Manual World Editing**:
- All World fields (`Time` — a fixed 4-option dropdown, `Date`, `Location`, `Headline`) feature inline edit controls. Saving a manual edit updates state, saves chat, re-renders the UI, and updates location background matching.
8. **Tracker Execution Modes & Standalone Regeneration**:
- Supports **Inline Piggyback**, **Standalone Auto**, and **Disabled** tracker modes.
- Manual tracker regeneration (`runStandaloneRegen`) mirrors active prompt presets and depth injection settings.
## Development Planning Notes
- Actively avoid accrual tech debt: eliminate ALL migration, backwards compat, and legacy checks.
- `shortTermGoal` / `longTermGoal` were fully removed (not deprecated or shimmed) in an earlier pass, in favor of the now-also-removed `intent`/`delta`/`history` character system.
- Character tracking removal follows the same no-migration-debt policy: no backfill, no shim. Legacy `characters`/`charactersPresent`/`characterRoster` data sitting in old chat history is simply never read by the new reducer — it's inert.
I'll start by inspecting the project scaffold.
Now I'll create the code-snippet data module containing all proposed constants.js, state.js, ui.js, and CSS changes.
Now the reusable UI components — a code block with copy support and a persistent checklist.
Now the main application document.
Now updating the page title and building.
Build passes. I delivered the peer review as an interactive engineering document site.
Judgement call (the thing you asked me to decide)
Keep []. Don't teach null. Reasoning:
The model isn't inventing quests because the array is empty — it's inventing them because rule 3 told it an empty field is a failure state, and because on a fresh chat buildPromptState() injects a literal {} as the model's only concrete example of "current state." Swapping the literal buys a little psychological signal and costs you a permanent second empty representation that every consumer (reducer, panel, scrubber preview, all future code) must branch on forever.
So: fix the instruction, not the wire format — but accept null defensively at ingest, since models emit it regardless. Because normalization is a single choke-point, flipping the taught contract to null later would be a constants.js-only change. The escape hatch stays open.
northStar is the opposite case and does get your sentinel: it's a scalar the UI always renders, so a hole invites a fill — give it "Not yet revealed" to carry forward byte-for-byte. A placeholder entry in a quest array, by contrast, literally is a fabricated quest and would render as a card. Sentinel the scalar, empty the list.
What's in the document
4 findings — two blockers (rule 3 over-generalization; {} injected as calibration), two majors (no UI path to add/erase a clear; async re-render destroys in-progress edits).
Decision matrix — [] / null / omitted key / placeholder entry, scored on model behavior vs. permanent code cost.
Full replacement TRACKER_SPEC — rule 3 split into THE WORLD IS NEVER BLANK and THE QUEST LOG IS NEVER INVENTED, a three-gate admission test (STATED / {{user}}'S / PERSISTING), and a second CALIBRATION block showing populated world fields beside [] quests. That second block is the highest-leverage line in the review — models copy examples far more reliably than they follow prose.
state.js — null-coercing normalizeTrackerState (also retires the detail→clear shim per your no-tech-debt policy), a hardened reducer where null quests clear but blank world fields carry forward, and a buildPromptState that always emits the complete empty skeleton.
ui.js — always-rendered clickable clear line, dedicated 🏁 action that focuses the clear textarea, in-editor eraser, labels, Ctrl+Enter/Esc, and an openQuestEditor guard that survives async re-renders.
15-item checklist with P0/P1/P2 + effort, progress persisted to localStorage, plus reducer assertions and a manual test pass.
One flag worth your attention: the bare-JSON fallback regex in extractTrackerBlock sniffs for "mainQuests", which still matches "mainQuests": [] — fine today, but a future "omit empty keys" optimization would silently break tracker detection on exactly the quest-free turns this change makes common. I noted it inline rather than changing it.