Repository navigation
Expand file tree
/
Copy pathmap-evolution-debug.js
More file actions
459 lines (435 loc) · 18.9 KB
/
Copy pathmap-evolution-debug.js
File metadata and controls
459 lines (435 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import { createChatCommitGuard, chatCommitResult } from './src/state/pass-affinity.js';
import { getActiveChatId } from './state-manager.js';
/**
* Map Evolution testing ground — time, entities, and independent ticks
* without playing through a campaign. Logic lives here; the popup UI is
* src/ui/panel/panel-map-evolution-debug.js.
*/
import {
getSettings,
persistMapEvolutionState,
saveChatState,
} from './state-manager.js';
import { runtimeState } from './src/app/runtime-state.js';
import { saveSettings } from './src/app/runtime-bridge.js';
import {
extractCurrentTimeStr,
formatInWorldTime,
parseInWorldTime,
replaceMemoCurrentTime,
} from './memo-processor.js';
import {
MAP_ASSET_KINDS,
applyDungeonMapTransaction,
normalizeDungeonLabel,
normalizeMapSiteKind,
} from './dungeon-reality.js';
import {
appendEvolutionBacklogEntry,
appendEvolutionThreads,
clearEvolutionHistoryForSite,
describeEvolutionBacklog,
describeEvolutionMemoryUsage,
describeEvolutionThreads,
describeEvolutionTimeWindow,
MAX_MAP_EVOLUTION_THREADS,
summarizeEvolutionDigest,
threadsFromMapTransaction,
applyTestingGroundWorldState,
cloneTestingGroundWorldState,
} from './map-evolution-lib.js';
import {
applyDungeonMapCommit,
isRouterRunning,
loadAllMappedSiteContexts,
restoreCampaignLocationsBook,
snapshotCampaignLocationsBook,
} from './router.js';
import {
isMapEvolutionRunning,
listMappedEvolutionSites,
runMapEvolutionPass,
} from './map-evolution.js';
import { isMapUpdaterRunning } from './map-updater.js';
export { MAP_ASSET_KINDS, replaceMemoCurrentTime };
/** Last Testing Ground Evolution/simulate pass. In-memory only; closing the popup keeps it until reload. */
let lastTestingGroundPass = null;
export function peekTestingGroundLastPass() {
if (!lastTestingGroundPass || lastTestingGroundPass.snapshot?.chatId !== getActiveChatId()) return null;
return {
action: { ...lastTestingGroundPass.action },
undone: !!lastTestingGroundPass.undone,
siteRoot: lastTestingGroundPass.action?.siteRoot || '',
};
}
export function clearTestingGroundLastPass() {
lastTestingGroundPass = null;
}
export async function snapshotTestingGroundWorld() {
const ownsChat = createChatCommitGuard(getActiveChatId(), getActiveChatId);
const world = cloneTestingGroundWorldState(getSettings());
world.chatId = getActiveChatId();
world.locationsBook = chatCommitResult(ownsChat, await snapshotCampaignLocationsBook());
return world;
}
export async function restoreTestingGroundWorld(snapshot) {
const ownsChat = createChatCommitGuard(getActiveChatId(), getActiveChatId);
if (!snapshot) return { ok: false, error: 'No snapshot to restore.' };
if (snapshot.chatId !== getActiveChatId()) return { ok: false, skipped: 'chat_changed' };
if (snapshot.locationsBook) {
const restored = chatCommitResult(ownsChat, await restoreCampaignLocationsBook(snapshot.locationsBook));
if (!restored) return { ok: false, error: 'Could not restore the Locations book.' };
}
applyTestingGroundWorldState(snapshot, getSettings());
persistMapEvolutionState();
persistMemo(snapshot.memo || getSettings().currentMemo || '');
if (typeof runtimeState.updateMapEvolutionScheduleDisplayRef === 'function') {
runtimeState.updateMapEvolutionScheduleDisplayRef();
}
return { ok: true };
}
async function captureTestingGroundCheckpoint(action) {
const ownsChat = createChatCommitGuard(getActiveChatId(), getActiveChatId);
lastTestingGroundPass = {
action: { ...action },
snapshot: chatCommitResult(ownsChat, await snapshotTestingGroundWorld()),
undone: false,
};
return lastTestingGroundPass;
}
export function currentCampaignTimeLabel(memo = getSettings().currentMemo) {
const match = String(memo || '').match(/\[TIME\]([\s\S]*?)\[\/TIME\]/i);
return match ? extractCurrentTimeStr(match[1]) : '';
}
export function currentCampaignTimeMinutes(memo = getSettings().currentMemo) {
const label = currentCampaignTimeLabel(memo);
const minutes = parseInWorldTime(label);
return minutes != null && Number.isFinite(minutes) && minutes >= 0 ? minutes : -1;
}
function persistMemo(nextMemo) {
const settings = getSettings();
settings.currentMemo = nextMemo;
const chatId = runtimeState.currentChatId;
if (settings.chatLinkEnabled && chatId) saveChatState(chatId);
else void saveSettings();
if (typeof runtimeState.refreshTrackerViewRef === 'function') {
runtimeState.refreshTrackerViewRef();
}
}
export function setCampaignTimeLabel(timeLabel) {
const label = String(timeLabel || '').trim();
if (!label) return { ok: false, error: 'Supply an in-world time label.' };
const minutes = parseInWorldTime(label);
if (minutes == null || !Number.isFinite(minutes) || minutes < 0) {
return { ok: false, error: `Could not parse in-world time: ${label}` };
}
const formatted = formatInWorldTime(minutes);
persistMemo(replaceMemoCurrentTime(getSettings().currentMemo || '', formatted));
return { ok: true, timeLabel: formatted, minutes };
}
export function advanceCampaignTime(deltaMinutes) {
const delta = Math.floor(Number(deltaMinutes) || 0);
if (!Number.isFinite(delta) || delta === 0) {
return { ok: false, error: 'Advance time by a non-zero number of in-world minutes.' };
}
const current = currentCampaignTimeMinutes();
if (current < 0) return { ok: false, error: 'No parseable [TIME] block in the current memo.' };
const next = Math.max(0, current + delta);
return setCampaignTimeLabel(formatInWorldTime(next));
}
export async function describeEvolutionSandbox(siteRoot = '') {
const ownsChat = createChatCommitGuard(getActiveChatId(), getActiveChatId);
const settings = getSettings();
const sites = chatCommitResult(ownsChat, await listMappedEvolutionSites());
const wanted = normalizeDungeonLabel(siteRoot) || sites.find(site => site.current)?.siteRoot || sites[0]?.siteRoot || '';
const loaded = wanted ? chatCommitResult(ownsChat, await loadAllMappedSiteContexts()) : null;
const site = (loaded?.sites || []).find(candidate =>
normalizeDungeonLabel(candidate.siteRoot) === normalizeDungeonLabel(wanted),
);
const timeLabel = currentCampaignTimeLabel();
const timeWindow = describeEvolutionTimeWindow(
settings.mapEvolutionLastFiredBySite?.[normalizeDungeonLabel(wanted)],
timeLabel,
);
return {
timeLabel,
minutes: currentCampaignTimeMinutes(),
sites,
siteRoot: site?.siteRoot || wanted,
kind: site ? normalizeMapSiteKind(site.document?.kind) : '',
document: site?.document || null,
timeWindow,
backlog: describeEvolutionBacklog(settings.mapEvolutionBacklogBySite, wanted, timeWindow.elapsedMinutes),
threads: describeEvolutionThreads(settings.mapEvolutionThreadsBySite, wanted, {
lookback: MAX_MAP_EVOLUTION_THREADS,
}),
lastEvolved: settings.mapEvolutionLastFiredBySite?.[normalizeDungeonLabel(wanted)] || 'Never',
memory: describeEvolutionMemoryUsage(
settings.mapEvolutionThreadsBySite,
settings.mapEvolutionBacklogBySite,
wanted,
{
threshold: settings.mapEvolutionCompressThreshold,
compressEnabled: settings.mapEvolutionCompressEnabled !== false,
},
),
};
}
function debugOperationId(suffix) {
const stamp = String(Date.now());
const slug = String(suffix || 'op').replace(/[^A-Za-z0-9._:-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'op';
return `debug-${stamp}-${slug}`.slice(0, 120);
}
async function commitSandboxTransaction(siteRoot, transaction) {
const ownsChat = createChatCommitGuard(getActiveChatId(), getActiveChatId);
const loaded = chatCommitResult(ownsChat, await loadAllMappedSiteContexts());
const site = (loaded?.sites || []).find(candidate =>
normalizeDungeonLabel(candidate.siteRoot) === normalizeDungeonLabel(siteRoot),
);
if (!site) return { ok: false, error: `No mapped site named ${siteRoot}.` };
const timeLabel = currentCampaignTimeLabel();
const validation = applyDungeonMapTransaction(site.document, transaction, { currentTime: timeLabel });
if (!validation.ok) {
return {
ok: false,
error: (validation.errors || []).map(issue => `${issue.code}: ${issue.hint}`).join('; ') || 'Invalid map transaction.',
errors: validation.errors,
};
}
const result = chatCommitResult(ownsChat, await applyDungeonMapCommit(transaction, site, loaded.books, timeLabel, {
requireActive: false,
}));
if (!result.ok) {
return {
ok: false,
error: (result.errors || []).map(issue => `${issue.code}: ${issue.hint}`).join('; ') || 'Map commit failed.',
errors: result.errors,
};
}
const settings = getSettings();
settings.mapEvolutionThreadsBySite = appendEvolutionThreads(
settings.mapEvolutionThreadsBySite,
site.siteRoot,
threadsFromMapTransaction(transaction, {
at: timeLabel,
createdAssets: result.createdAssets || validation.createdAssets || [],
}),
);
const digestLine = summarizeEvolutionDigest(site.siteRoot, transaction);
if (digestLine) {
settings.mapEvolutionBacklogBySite = appendEvolutionBacklogEntry(
settings.mapEvolutionBacklogBySite,
site.siteRoot,
{
kind: 'commit',
at: timeLabel,
elapsedMinutes: -1,
operationId: transaction.operation_id,
summary: digestLine,
},
);
}
persistMapEvolutionState();
if (typeof runtimeState.refreshTrackerViewRef === 'function') {
runtimeState.refreshTrackerViewRef();
}
return { ok: true, result, createdAssets: result.createdAssets || validation.createdAssets || [] };
}
export async function debugAddAsset({
siteRoot,
name,
kind = 'CREATURE',
location,
state = 'ACTIVE',
knowledge = 'UNREVEALED',
faction = '',
detail = '',
count,
cause,
actor = '',
} = {}) {
const ownsChat = createChatCommitGuard(getActiveChatId(), getActiveChatId);
const causeText = String(cause || '').trim();
if (!String(name || '').trim()) return { ok: false, error: 'Name is required.' };
if (!String(location || '').trim()) return { ok: false, error: 'Location (area id) is required.' };
if (!causeText) return { ok: false, error: 'Cause is required.' };
const operation = {
op: 'ADD_ASSET',
evidence: 'CONFIRMED',
name: String(name).trim(),
kind,
location: String(location).trim(),
state,
knowledge,
detail: String(detail || '').trim(),
origin: 'DEBUG_SANDBOX',
cause: causeText,
};
const parsedCount = Math.floor(Number(count));
if (Number.isFinite(parsedCount) && parsedCount >= 1) operation.count = parsedCount;
if (faction) operation.faction = String(faction).trim();
if (actor) operation.actor = String(actor).trim();
if (['DEAD', 'DESTROYED'].includes(String(state).toUpperCase()) && !operation.actor) {
return { ok: false, error: 'DEAD/DESTROYED requires an actor (party, asset id, or off-map name).' };
}
return commitSandboxTransaction(siteRoot, {
operation_id: debugOperationId(name),
operations: [operation],
chronicles: [],
});
}
export async function debugSetAsset({
siteRoot,
assetId,
state,
detail,
count,
cause,
actor = '',
threadStatus = '',
} = {}) {
const ownsChat = createChatCommitGuard(getActiveChatId(), getActiveChatId);
const causeText = String(cause || '').trim();
if (!String(assetId || '').trim()) return { ok: false, error: 'Asset id is required.' };
if (!causeText) return { ok: false, error: 'Cause is required.' };
const operation = {
op: 'SET_ASSET',
evidence: 'CONFIRMED',
asset_id: String(assetId).trim(),
cause: causeText,
};
if (state) operation.state = state;
if (detail != null && detail !== '') operation.detail = String(detail);
const parsedCount = Math.floor(Number(count));
if (Number.isFinite(parsedCount) && parsedCount >= 1) operation.count = parsedCount;
if (actor) operation.actor = String(actor).trim();
if (threadStatus) operation.thread_status = threadStatus;
if (['DEAD', 'DESTROYED'].includes(String(state || '').toUpperCase()) && !operation.actor) {
return { ok: false, error: 'DEAD/DESTROYED requires an actor (party, asset id, or off-map name).' };
}
return commitSandboxTransaction(siteRoot, {
operation_id: debugOperationId(assetId),
operations: [operation],
chronicles: [],
});
}
export function evolutionAgentsBusy() {
return isRouterRunning() || isMapUpdaterRunning() || isMapEvolutionRunning();
}
export async function debugRunEvolution(siteRoot) {
const ownsChat = createChatCommitGuard(getActiveChatId(), getActiveChatId);
if (evolutionAgentsBusy()) return { ok: false, skipped: 'busy', error: 'An agent is already running.' };
const root = String(siteRoot || '').trim();
if (!root) return { ok: false, error: 'Pick a mapped site.' };
chatCommitResult(ownsChat, await captureTestingGroundCheckpoint({ type: 'evolve', siteRoot: root }));
return runMapEvolutionPass({ trigger: 'manual', isManual: true, siteRoots: [root] });
}
async function runSimulateTicks({
siteRoot,
ticks = 1,
hoursPerTick = 0,
onTick = null,
} = {}) {
const ownsChat = createChatCommitGuard(getActiveChatId(), getActiveChatId);
const root = String(siteRoot || '').trim();
if (!root) return { ok: false, error: 'Pick a mapped site.' };
const count = Math.max(1, Math.min(20, Math.floor(Number(ticks) || 1)));
const hours = Math.max(1, Math.floor(Number(hoursPerTick) || Number(getSettings().mapEvolutionIntervalHours) || 8));
const results = [];
for (let index = 0; index < count; index++) {
if (evolutionAgentsBusy()) {
return { ok: false, skipped: 'busy', error: 'An agent is already running.', results };
}
const advanced = advanceCampaignTime(hours * 60);
if (!advanced.ok) return { ...advanced, results };
if (typeof onTick === 'function') {
onTick({ index, count, timeLabel: advanced.timeLabel, phase: 'time' });
}
const evolved = chatCommitResult(ownsChat, await runMapEvolutionPass({ trigger: 'manual', isManual: true, siteRoots: [root] }));
results.push({ timeLabel: advanced.timeLabel, evolved });
if (typeof onTick === 'function') {
onTick({ index, count, timeLabel: advanced.timeLabel, phase: 'evolved', evolved });
}
if (evolved?.skipped === 'busy' || evolved?.skipped === 'stopped') {
return { ok: false, skipped: evolved.skipped, results };
}
}
return { ok: true, ticks: count, hoursPerTick: hours, results };
}
/**
* Advance in-world time by the configured interval (or a supplied hour count)
* and run Map Evolution that many times. This is the simulation loop.
*/
export async function debugSimulateTicks({
siteRoot,
ticks = 1,
hoursPerTick = 0,
onTick = null,
} = {}) {
const ownsChat = createChatCommitGuard(getActiveChatId(), getActiveChatId);
const root = String(siteRoot || '').trim();
if (!root) return { ok: false, error: 'Pick a mapped site.' };
if (evolutionAgentsBusy()) return { ok: false, skipped: 'busy', error: 'An agent is already running.' };
const count = Math.max(1, Math.min(20, Math.floor(Number(ticks) || 1)));
const hours = Math.max(1, Math.floor(Number(hoursPerTick) || Number(getSettings().mapEvolutionIntervalHours) || 8));
chatCommitResult(ownsChat, await captureTestingGroundCheckpoint({
type: 'simulate',
siteRoot: root,
ticks: count,
hoursPerTick: hours,
}));
return runSimulateTicks({ siteRoot: root, ticks: count, hoursPerTick: hours, onTick });
}
export async function debugUndoLastEvolutionPass() {
const ownsChat = createChatCommitGuard(getActiveChatId(), getActiveChatId);
if (!lastTestingGroundPass) return { ok: false, error: 'No Evolution pass to undo. Run one first.' };
if (lastTestingGroundPass.undone) return { ok: false, error: 'Last pass is already undone. Redo it or run a new one.' };
if (evolutionAgentsBusy()) return { ok: false, skipped: 'busy', error: 'An agent is already running.' };
const restored = chatCommitResult(ownsChat, await restoreTestingGroundWorld(lastTestingGroundPass.snapshot));
if (!restored.ok) return restored;
lastTestingGroundPass.undone = true;
return {
ok: true,
undone: true,
siteRoot: lastTestingGroundPass.action.siteRoot,
action: { ...lastTestingGroundPass.action },
};
}
export async function debugRedoLastEvolutionPass({ onTick = null } = {}) {
const ownsChat = createChatCommitGuard(getActiveChatId(), getActiveChatId);
if (!lastTestingGroundPass) return { ok: false, error: 'No Evolution pass to redo. Run one first.' };
if (evolutionAgentsBusy()) return { ok: false, skipped: 'busy', error: 'An agent is already running.' };
const restored = chatCommitResult(ownsChat, await restoreTestingGroundWorld(lastTestingGroundPass.snapshot));
if (!restored.ok) return restored;
const action = lastTestingGroundPass.action;
const result = action.type === 'simulate'
? chatCommitResult(ownsChat, await runSimulateTicks({
siteRoot: action.siteRoot,
ticks: action.ticks,
hoursPerTick: action.hoursPerTick,
onTick,
}))
: chatCommitResult(ownsChat, await runMapEvolutionPass({ trigger: 'manual', isManual: true, siteRoots: [action.siteRoot] }));
lastTestingGroundPass.undone = false;
return { ...result, redone: true, action: { ...action } };
}
/**
* Wipe this site's Evolution backlog, causal threads, and considered World
* Report bookkeeping. Map occupancy and Last Evolved clocks stay put.
*/
export function debugClearEvolutionHistory(siteRoot) {
const root = String(siteRoot || '').trim();
if (!root) return { ok: false, error: 'Pick a mapped site.' };
const settings = getSettings();
const cleared = clearEvolutionHistoryForSite({
backlogBySite: settings.mapEvolutionBacklogBySite,
threadsBySite: settings.mapEvolutionThreadsBySite,
reportApplicationsBySite: settings.mapEvolutionWorldReportApplications,
}, root);
if (!cleared.cleared) return { ok: false, error: 'Could not resolve that site.' };
settings.mapEvolutionBacklogBySite = cleared.backlogBySite;
settings.mapEvolutionThreadsBySite = cleared.threadsBySite;
settings.mapEvolutionWorldReportApplications = cleared.reportApplicationsBySite;
persistMapEvolutionState();
return { ok: true, siteRoot: root };
}