@clawtopia/werewolf-evolution 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1041 @@
1
+ import {
2
+ EXECUTION_PROPOSAL_TEMPLATES,
3
+ ProposalError,
4
+ assertWorkspaceOwner,
5
+ assertWorkspaceSetupReady,
6
+ customProfilePath,
7
+ getWerewolfEvolutionVersion,
8
+ inspectRuntimeProjection,
9
+ installedProfilePath,
10
+ isProtectedToolWrite,
11
+ isTrustedDebriefOrigin,
12
+ isUnknownEligibilityValue,
13
+ isWorkspaceOwner,
14
+ parseAndValidateProposal,
15
+ parseDebriefBody,
16
+ profileOverridePath,
17
+ projectProfilePlaybook,
18
+ readWorkspaceState,
19
+ renderSuggestions,
20
+ resolveWorkspacePaths,
21
+ runWorkspaceRead,
22
+ runWorkspaceTransaction,
23
+ sha256,
24
+ verifyWorkspaceDocuments,
25
+ workspaceChanges
26
+ } from "./chunk-3A7SOBN4.js";
27
+
28
+ // index.ts
29
+ import {
30
+ definePluginEntry,
31
+ emptyPluginConfigSchema
32
+ } from "openclaw/plugin-sdk/core";
33
+
34
+ // src/context-store.ts
35
+ var CAPTURE_TTL_MS = 10 * 60 * 1e3;
36
+ var MAX_CAPTURES = 256;
37
+ var SUGGESTION_COMMAND = /^\s*(采纳|忽略|拒绝)\s+(S-\d{3,6})\s*[。.!!]?\s*$/i;
38
+ var DIRECT_CONVERSATION = /^private:(?:HUMAN|human):[0-9]+$/;
39
+ function isExplicitConfiguredOwner(config, channelId, senderId) {
40
+ if (channelId !== "clawtopia" && channelId !== "coolclaw" || !senderId) return false;
41
+ const owners = record(record(config)?.commands)?.ownerAllowFrom;
42
+ if (!Array.isArray(owners) || owners.length === 0) return false;
43
+ const normalized = owners.map((value) => String(value ?? "").trim().toLowerCase()).filter(Boolean);
44
+ const relevant = normalized.filter((value) => value === "*" || !value.includes(":") || value.startsWith(`${channelId}:`));
45
+ if (relevant.some((value) => value === "*" || value === `${channelId}:*`)) return false;
46
+ const rawSender = senderId.trim().toLowerCase();
47
+ const canonical = rawSender.startsWith(`${channelId}:`) ? rawSender : `${channelId}:${rawSender}`;
48
+ return relevant.includes(canonical) && new RegExp(`^${channelId}:human:[0-9]+$`).test(canonical);
49
+ }
50
+ function normalizedSender(value) {
51
+ return value.replace(/^(?:clawtopia|coolclaw):/, "").replace(/^human:/, "");
52
+ }
53
+ function sameHumanSender(left, right) {
54
+ return normalizedSender(left) === normalizedSender(right);
55
+ }
56
+ function isHumanDirectMessage(event, ctx) {
57
+ if (ctx.channelId !== "clawtopia" && ctx.channelId !== "coolclaw") return false;
58
+ if (!ctx.conversationId || !DIRECT_CONVERSATION.test(ctx.conversationId)) return false;
59
+ return event.from.startsWith(`${ctx.channelId}:human:`) && normalizedSender(event.from) !== "0";
60
+ }
61
+ function normalizedAccountId(value) {
62
+ return value?.trim() || "default";
63
+ }
64
+ function record(value) {
65
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
66
+ }
67
+ function resolveAgentAccountBinding(config, channelId, accountId) {
68
+ if (channelId !== "clawtopia" && channelId !== "coolclaw") return void 0;
69
+ const normalizedAccount = normalizedAccountId(accountId);
70
+ const channels = record(record(config)?.channels);
71
+ const channel = record(channels?.[channelId]);
72
+ const account = record(record(channel?.accounts)?.[normalizedAccount]);
73
+ const platformAgentId = typeof account?.agentId === "string" ? account.agentId.trim() : "";
74
+ if (!platformAgentId) return void 0;
75
+ return { channelId, accountId: normalizedAccount, platformAgentId };
76
+ }
77
+ var EvolutionContextStore = class {
78
+ inboundByRun = /* @__PURE__ */ new Map();
79
+ boundByRun = /* @__PURE__ */ new Map();
80
+ hashByDebriefId = /* @__PURE__ */ new Map();
81
+ toolCalls = /* @__PURE__ */ new Map();
82
+ capture(event, ctx, now = Date.now()) {
83
+ this.cleanup(now);
84
+ const runId = event.runId ?? ctx.runId;
85
+ if (!runId || !ctx.sessionKey) return void 0;
86
+ if (isTrustedDebriefOrigin(ctx.channelId, event.from)) {
87
+ try {
88
+ const { envelope, bodyHash } = parseDebriefBody(event.content);
89
+ const prior = this.hashByDebriefId.get(envelope.debriefId);
90
+ const captured = {
91
+ kind: "debrief",
92
+ channelId: ctx.channelId,
93
+ accountId: normalizedAccountId(ctx.accountId),
94
+ from: event.from,
95
+ sessionKey: ctx.sessionKey,
96
+ runId,
97
+ conversationId: ctx.conversationId,
98
+ messageId: event.messageId,
99
+ content: event.content,
100
+ bodyHash,
101
+ envelope,
102
+ capturedAt: now,
103
+ ...prior && prior.hash !== bodyHash ? { conflict: true } : {}
104
+ };
105
+ this.hashByDebriefId.set(envelope.debriefId, prior ?? { hash: bodyHash, capturedAt: now });
106
+ this.inboundByRun.set(runId, captured);
107
+ return captured;
108
+ } catch {
109
+ return void 0;
110
+ }
111
+ }
112
+ const match = SUGGESTION_COMMAND.exec(event.content);
113
+ if (!match || !isHumanDirectMessage(event, ctx)) return void 0;
114
+ const command = {
115
+ kind: "suggestion-command",
116
+ channelId: ctx.channelId,
117
+ accountId: normalizedAccountId(ctx.accountId),
118
+ from: event.from,
119
+ sessionKey: ctx.sessionKey,
120
+ runId,
121
+ conversationId: ctx.conversationId,
122
+ messageId: event.messageId,
123
+ content: event.content,
124
+ suggestionId: match[2].toUpperCase(),
125
+ decision: match[1] === "\u91C7\u7EB3" ? "accept" : "reject",
126
+ capturedAt: now
127
+ };
128
+ this.inboundByRun.set(runId, command);
129
+ return command;
130
+ }
131
+ bindAgentRun(event, ctx, binding, now = Date.now(), explicitOwnerAuthorized = false) {
132
+ this.cleanup(now);
133
+ if (!ctx.runId || !ctx.sessionKey || !ctx.agentId || !ctx.workspaceDir) return void 0;
134
+ const inbound = this.inboundByRun.get(ctx.runId);
135
+ if (!inbound || inbound.sessionKey !== ctx.sessionKey || now - inbound.capturedAt > CAPTURE_TTL_MS) return void 0;
136
+ this.inboundByRun.delete(ctx.runId);
137
+ const eventAccountId = normalizedAccountId(event.accountId);
138
+ if (event.channelId !== inbound.channelId || eventAccountId !== inbound.accountId) return void 0;
139
+ if (!binding || binding.channelId !== inbound.channelId || binding.accountId !== inbound.accountId) return void 0;
140
+ if (inbound.kind === "debrief") {
141
+ if (inbound.envelope.game.recipientAgentId !== binding.platformAgentId) return void 0;
142
+ } else {
143
+ if (!explicitOwnerAuthorized || event.senderIsOwner !== true || !event.senderId || normalizedSender(event.senderId) !== normalizedSender(inbound.from)) return void 0;
144
+ }
145
+ const bound = {
146
+ runId: ctx.runId,
147
+ sessionKey: ctx.sessionKey,
148
+ agentId: ctx.agentId,
149
+ workspaceDir: ctx.workspaceDir,
150
+ inbound,
151
+ senderId: event.senderId,
152
+ senderIsOwner: event.senderIsOwner === true,
153
+ consumed: false,
154
+ boundAt: now,
155
+ expiresAt: now + CAPTURE_TTL_MS
156
+ };
157
+ this.boundByRun.set(ctx.runId, bound);
158
+ return bound;
159
+ }
160
+ getBound(runId, sessionKey, now = Date.now()) {
161
+ this.cleanup(now);
162
+ if (!runId || !sessionKey) return void 0;
163
+ const bound = this.boundByRun.get(runId);
164
+ return bound?.sessionKey === sessionKey && bound.expiresAt >= now ? bound : void 0;
165
+ }
166
+ consume(runId, sessionKey, now = Date.now()) {
167
+ const bound = this.getBound(runId, sessionKey, now);
168
+ if (!bound) throw new Error("NO_BOUND_CAPABILITY");
169
+ if (bound.consumed) throw new Error("CAPABILITY_ALREADY_CONSUMED");
170
+ bound.consumed = true;
171
+ return bound;
172
+ }
173
+ authorizeToolCall(runId, sessionKey, toolCallId, now = Date.now()) {
174
+ this.cleanup(now);
175
+ if (!runId || !sessionKey || !toolCallId) throw new Error("TOOL_CALL_CONTEXT_MISSING");
176
+ const bound = this.getBound(runId, sessionKey, now);
177
+ if (!bound) throw new Error("NO_BOUND_CAPABILITY");
178
+ if (bound.consumed) throw new Error("CAPABILITY_ALREADY_CONSUMED");
179
+ if (this.toolCalls.has(toolCallId)) throw new Error("TOOL_CALL_ALREADY_AUTHORIZED");
180
+ this.toolCalls.set(toolCallId, { runId, sessionKey, expiresAt: bound.expiresAt });
181
+ return bound;
182
+ }
183
+ consumeToolCall(toolCallId, sessionKey, now = Date.now()) {
184
+ this.cleanup(now);
185
+ const authorized = this.toolCalls.get(toolCallId);
186
+ this.toolCalls.delete(toolCallId);
187
+ if (!authorized || authorized.expiresAt < now || !sessionKey || authorized.sessionKey !== sessionKey) {
188
+ throw new Error("UNAUTHORIZED_TOOL_CALL");
189
+ }
190
+ return this.consume(authorized.runId, authorized.sessionKey, now);
191
+ }
192
+ cleanup(now = Date.now()) {
193
+ for (const [key, value] of this.inboundByRun) {
194
+ if (now - value.capturedAt > CAPTURE_TTL_MS) this.inboundByRun.delete(key);
195
+ }
196
+ for (const [key, value] of this.boundByRun) {
197
+ if (value.expiresAt < now) this.boundByRun.delete(key);
198
+ }
199
+ for (const [key, value] of this.toolCalls) {
200
+ if (value.expiresAt < now) this.toolCalls.delete(key);
201
+ }
202
+ for (const [key, value] of this.hashByDebriefId) {
203
+ if (now - value.capturedAt > CAPTURE_TTL_MS) this.hashByDebriefId.delete(key);
204
+ }
205
+ while (this.inboundByRun.size > MAX_CAPTURES) this.inboundByRun.delete(this.inboundByRun.keys().next().value);
206
+ while (this.boundByRun.size > MAX_CAPTURES) this.boundByRun.delete(this.boundByRun.keys().next().value);
207
+ while (this.toolCalls.size > MAX_CAPTURES) this.toolCalls.delete(this.toolCalls.keys().next().value);
208
+ while (this.hashByDebriefId.size > MAX_CAPTURES) this.hashByDebriefId.delete(this.hashByDebriefId.keys().next().value);
209
+ }
210
+ };
211
+
212
+ // src/profile.ts
213
+ import { existsSync, lstatSync, readFileSync } from "fs";
214
+ var OWNER_START = "<!-- WEREWOLF_OWNER_OVERRIDES_START -->";
215
+ var OWNER_END = "<!-- WEREWOLF_OWNER_OVERRIDES_END -->";
216
+ var MAX_PROFILE_CHARS = 5e3;
217
+ var RESERVED = /(?:WEREWOLF_RUNTIME_(?:START|END)|^runtime_version:|^active_profile:|^### (?:GAME_EVENT execution contract|active profile playbook|active lessons)\s*$)/m;
218
+ function readRegularFile(file) {
219
+ if (!existsSync(file)) return void 0;
220
+ if (!lstatSync(file).isFile() || lstatSync(file).isSymbolicLink()) throw new Error(`PROFILE_SOURCE_INVALID:${file}`);
221
+ return readFileSync(file, "utf8");
222
+ }
223
+ function stripOwnerSection(body) {
224
+ const starts = body.split(OWNER_START).length - 1;
225
+ const ends = body.split(OWNER_END).length - 1;
226
+ if (starts === 0 && ends === 0) return body.trim();
227
+ if (starts !== 1 || ends !== 1) throw new Error("OWNER_OVERRIDE_MARKERS_INVALID");
228
+ const start = body.indexOf(OWNER_START);
229
+ const end = body.indexOf(OWNER_END);
230
+ if (end <= start) throw new Error("OWNER_OVERRIDE_MARKERS_INVALID");
231
+ return `${body.slice(0, start)}${body.slice(end + OWNER_END.length)}`.trim();
232
+ }
233
+ function parseProfileMarkdown(content, profile) {
234
+ if (content.length > MAX_PROFILE_CHARS) throw new Error(`PROFILE_TOO_LARGE:${profile}`);
235
+ if (RESERVED.test(content)) throw new Error(`PROFILE_RESERVED_CONTENT:${profile}`);
236
+ const matches = [...content.matchAll(/^## profile:\s*`([^`]+)`([^\r\n]*)\r?$/gm)];
237
+ if (matches.length !== 1 || matches[0][1] !== profile) throw new Error(`PROFILE_HEADING_INVALID:${profile}`);
238
+ const heading = matches[0];
239
+ const body = content.slice(heading.index + heading[0].length).trim();
240
+ if (!body) throw new Error(`PROFILE_BODY_EMPTY:${profile}`);
241
+ const baseBody = stripOwnerSection(body);
242
+ const version = /^base_version:\s*(\S+)\s*$/m.exec(content)?.[1] ?? "unknown";
243
+ const declaredHash = /^base_hash:\s*([a-f0-9]{64}|unknown)\s*$/m.exec(content)?.[1];
244
+ return {
245
+ profileHeading: `## profile: \`${profile}\`${heading[2] ?? ""}`,
246
+ baseBody,
247
+ baseVersion: version,
248
+ baseHash: declaredHash && declaredHash !== "unknown" ? declaredHash : sha256(baseBody)
249
+ };
250
+ }
251
+ function authorityFromRuntime(agentsText, profile) {
252
+ const runtime = inspectRuntimeProjection(agentsText);
253
+ if (!runtime || runtime.activeProfile !== profile) return void 0;
254
+ const baseBody = stripOwnerSection(runtime.playbook);
255
+ return {
256
+ profileHeading: `## profile: \`${profile}\`\uFF08\u7528\u6237\u8986\u76D6\uFF09`,
257
+ baseBody,
258
+ baseVersion: "unknown",
259
+ baseHash: sha256(baseBody)
260
+ };
261
+ }
262
+ function resolveProfileAuthority(paths, profile, agentsText) {
263
+ const candidates = [
264
+ profileOverridePath(paths, profile),
265
+ customProfilePath(paths, profile),
266
+ installedProfilePath(paths, profile)
267
+ ];
268
+ for (const file of candidates) {
269
+ const content = readRegularFile(file);
270
+ if (content !== void 0) return parseProfileMarkdown(content, profile);
271
+ }
272
+ const runtime = authorityFromRuntime(agentsText, profile);
273
+ if (runtime) return runtime;
274
+ throw new Error(`PROFILE_AUTHORITY_NOT_FOUND:${profile}`);
275
+ }
276
+ function renderOwnerSection(suggestions) {
277
+ const accepted = suggestions.filter((item) => item.status === "accepted").sort((left, right) => left.id.localeCompare(right.id));
278
+ if (accepted.length === 0) return "";
279
+ const lines = [OWNER_START, "### Owner-confirmed strategy overrides"];
280
+ for (const item of accepted) {
281
+ lines.push(
282
+ "",
283
+ `#### ${item.id}`,
284
+ `- \u89E6\u53D1\uFF1A${item.trigger}`,
285
+ `- \u89C4\u5219\uFF1A${item.rule}`,
286
+ `- \u8FB9\u754C\uFF1A${item.boundary}`
287
+ );
288
+ }
289
+ lines.push(OWNER_END);
290
+ return lines.join("\n");
291
+ }
292
+ function buildProfileOverride(paths, profile, agentsText, suggestions) {
293
+ const authority = resolveProfileAuthority(paths, profile, agentsText);
294
+ const accepted = suggestions.filter((item) => item.profile === profile && item.status === "accepted");
295
+ const ownerSection = renderOwnerSection(accepted);
296
+ const playbook = [authority.baseBody, ownerSection].filter(Boolean).join("\n\n");
297
+ const acceptedIds = accepted.map((item) => item.id).sort().join(", ") || "none";
298
+ const content = [
299
+ "# werewolf-play profile override",
300
+ `base_version: ${authority.baseVersion}`,
301
+ `base_hash: ${authority.baseHash}`,
302
+ `accepted_suggestions: ${acceptedIds}`,
303
+ "",
304
+ authority.profileHeading,
305
+ "",
306
+ playbook,
307
+ ""
308
+ ].join("\n");
309
+ parseProfileMarkdown(content, profile);
310
+ return { file: profileOverridePath(paths, profile), content, playbook };
311
+ }
312
+ function verifyProfileOverride(file, profile, expectedContent) {
313
+ const content = readRegularFile(file);
314
+ if (content === void 0) throw new Error(`PROFILE_OVERRIDE_MISSING:${profile}`);
315
+ if (expectedContent !== void 0 && content !== expectedContent) {
316
+ throw new Error(`PROFILE_OVERRIDE_CONTENT_MISMATCH:${profile}`);
317
+ }
318
+ parseProfileMarkdown(content, profile);
319
+ }
320
+
321
+ // src/state-machine.ts
322
+ var MAX_CANDIDATE = 12;
323
+ var MAX_ACTIVE = 6;
324
+ function nowIso(now) {
325
+ return now.toISOString();
326
+ }
327
+ function nextNumericId(existing, prefix) {
328
+ const max = existing.reduce((value, id) => {
329
+ const match = new RegExp(`^${prefix}(\\d+)$`).exec(id);
330
+ return match ? Math.max(value, Number(match[1])) : value;
331
+ }, 0);
332
+ return `${prefix}${String(max + 1).padStart(3, "0")}`;
333
+ }
334
+ function sample(proposal, envelope) {
335
+ return {
336
+ gameId: envelope.game.gameId,
337
+ debriefId: envelope.debriefId,
338
+ reviewDate: envelope.game.reviewDate,
339
+ source: proposal.source,
340
+ decisionWindowId: proposal.decisionWindowId,
341
+ anchorFactId: proposal.anchorFactId,
342
+ alternativeActionType: proposal.alternativeActionType,
343
+ ...proposal.alternativeTargetSeat === void 0 ? {} : { alternativeTargetSeat: proposal.alternativeTargetSeat },
344
+ knownFactRefs: proposal.knownFactRefs ?? [],
345
+ outcomeFactRefs: proposal.outcomeFactRefs ?? [],
346
+ behavior: proposal.behavior,
347
+ observedLocalEffect: proposal.observedLocalEffect,
348
+ alternatives: proposal.alternatives ?? []
349
+ };
350
+ }
351
+ function independentCount(samples) {
352
+ return new Set(samples.map((entry2) => entry2.gameId)).size;
353
+ }
354
+ function dateCount(samples) {
355
+ return new Set(samples.map((entry2) => entry2.reviewDate)).size;
356
+ }
357
+ function sources(samples) {
358
+ return new Set(samples.map((entry2) => entry2.source));
359
+ }
360
+ function addUnique(target, value) {
361
+ if (!target.some((entry2) => entry2.gameId === value.gameId)) target.push(value);
362
+ }
363
+ function newLesson(id, proposal, envelope, window, risk, now, supersedesLessonId) {
364
+ return {
365
+ id,
366
+ status: "candidate",
367
+ risk,
368
+ profile: proposal.profile,
369
+ phase: window.phase,
370
+ role: window.actorRole,
371
+ players: envelope.game.players,
372
+ actionType: window.actionType,
373
+ decisionType: proposal.decisionType,
374
+ ...risk === "execution" ? { executionOperation: proposal.executionOperation } : {},
375
+ trigger: proposal.trigger,
376
+ rule: proposal.rule,
377
+ boundary: proposal.boundary,
378
+ expectedLocalEffect: proposal.expectedLocalEffect,
379
+ falsifier: proposal.falsifier,
380
+ supportGames: [sample(proposal, envelope)],
381
+ counterGames: [],
382
+ ...supersedesLessonId ? { supersedesLessonId } : {},
383
+ createdAt: nowIso(now),
384
+ lastReviewed: envelope.game.reviewDate
385
+ };
386
+ }
387
+ function reconcileSuggestions(state, lesson, now) {
388
+ const counters = independentCount(lesson.counterGames);
389
+ for (const suggestion of state.suggestions.suggestions.filter((item) => item.lessonId === lesson.id)) {
390
+ suggestion.counterCount = counters;
391
+ if (suggestion.status === "pending" && (counters > 0 || lesson.status === "archived")) {
392
+ suggestion.status = "withdrawn";
393
+ suggestion.decidedAt = nowIso(now);
394
+ } else if ((suggestion.status === "accepted" || suggestion.status === "paused") && (counters >= 2 || lesson.status === "archived")) {
395
+ suggestion.status = "withdrawn";
396
+ suggestion.decidedAt = nowIso(now);
397
+ suggestion.pauseReason = lesson.status === "archived" ? "LESSON_REFINED" : "COUNTER_EVIDENCE_THRESHOLD";
398
+ } else if (suggestion.status === "accepted" && counters === 1) {
399
+ suggestion.status = "paused";
400
+ suggestion.pausedAt = nowIso(now);
401
+ suggestion.pauseReason = "COUNTER_EVIDENCE";
402
+ }
403
+ }
404
+ }
405
+ function enforceProfileLimits(state, profile) {
406
+ const candidates = state.evidence.lessons.filter((lesson) => lesson.profile === profile && lesson.status === "candidate");
407
+ if (candidates.length > MAX_CANDIDATE) {
408
+ candidates.sort((left, right) => left.lastReviewed.localeCompare(right.lastReviewed) || left.createdAt.localeCompare(right.createdAt));
409
+ for (const lesson of candidates.slice(0, candidates.length - MAX_CANDIDATE)) lesson.status = "archived";
410
+ }
411
+ const active = state.evidence.lessons.filter((lesson) => lesson.profile === profile && lesson.status === "active");
412
+ if (active.length > MAX_ACTIVE) {
413
+ active.sort((left, right) => right.lastReviewed.localeCompare(left.lastReviewed));
414
+ for (const lesson of active.slice(MAX_ACTIVE)) lesson.status = "archived";
415
+ }
416
+ const probation = state.evidence.lessons.filter((lesson) => lesson.profile === profile && lesson.status === "probation");
417
+ if (probation.length > 1) {
418
+ probation.sort((left, right) => right.lastReviewed.localeCompare(left.lastReviewed));
419
+ for (const lesson of probation.slice(1)) lesson.status = "archived";
420
+ }
421
+ }
422
+ function ensureSuggestion(state, lesson, now) {
423
+ if (lesson.status !== "candidate") return;
424
+ if (state.suggestions.suggestions.some((item) => item.lessonId === lesson.id)) return;
425
+ const sourceSet = sources(lesson.supportGames);
426
+ if (independentCount(lesson.supportGames) < 5 || dateCount(lesson.supportGames) < 2 || independentCount(lesson.counterGames) > 0 || !sourceSet.has("SELF") || !(sourceSet.has("OBSERVED") || sourceSet.has("EXEMPLAR"))) return;
427
+ const id = nextNumericId(state.suggestions.suggestions.map((item) => item.id), "S-");
428
+ state.suggestions.suggestions.push({
429
+ id,
430
+ lessonId: lesson.id,
431
+ profile: lesson.profile,
432
+ status: "pending",
433
+ trigger: lesson.trigger,
434
+ rule: lesson.rule,
435
+ boundary: lesson.boundary,
436
+ supportCount: independentCount(lesson.supportGames),
437
+ counterCount: independentCount(lesson.counterGames),
438
+ createdAt: nowIso(now)
439
+ });
440
+ }
441
+ function transitionExecution(state, lesson) {
442
+ const supports = independentCount(lesson.supportGames);
443
+ const counters = independentCount(lesson.counterGames);
444
+ if (lesson.status === "candidate") {
445
+ if (counters > 0) {
446
+ lesson.status = "contested";
447
+ } else if (supports >= 3 && dateCount(lesson.supportGames) >= 2) {
448
+ const existingProbation = state.evidence.lessons.some((item) => item.profile === lesson.profile && item.status === "probation" && item.id !== lesson.id);
449
+ if (!existingProbation) {
450
+ lesson.status = "probation";
451
+ lesson.probationStartedAtSupportCount = supports;
452
+ }
453
+ }
454
+ } else if (lesson.status === "probation") {
455
+ if (counters >= 1) lesson.status = "contested";
456
+ else if (supports - (lesson.probationStartedAtSupportCount ?? supports) >= 2) lesson.status = "active";
457
+ } else if (lesson.status === "active" && counters >= 2) {
458
+ lesson.status = "contested";
459
+ }
460
+ }
461
+ function applyProposal(state, envelope, bodyHash, proposal, risk, window, now = /* @__PURE__ */ new Date()) {
462
+ if (state.ledger.entries.some((entry2) => entry2.debriefId === envelope.debriefId)) return { outcome: "duplicate" };
463
+ if (state.ledger.entries.some((entry2) => entry2.gameId === envelope.game.gameId)) return { outcome: "duplicate-game" };
464
+ let result = { outcome: "skipped" };
465
+ if (proposal.action !== "SKIP") {
466
+ let lesson;
467
+ if (proposal.action === "NEW") {
468
+ const id = nextNumericId(
469
+ state.evidence.lessons.filter((item) => item.profile === proposal.profile).map((item) => item.id),
470
+ `L-${proposal.profile}-`
471
+ );
472
+ lesson = newLesson(id, proposal, envelope, window, risk, now);
473
+ state.evidence.lessons.push(lesson);
474
+ } else if (proposal.action === "REFINE") {
475
+ const prior = state.evidence.lessons.find((item) => item.id === proposal.topicId);
476
+ const id = nextNumericId(
477
+ state.evidence.lessons.filter((item) => item.profile === proposal.profile).map((item) => item.id),
478
+ `L-${proposal.profile}-`
479
+ );
480
+ prior.status = "archived";
481
+ prior.supersededByLessonId = id;
482
+ prior.lastReviewed = envelope.game.reviewDate;
483
+ reconcileSuggestions(state, prior, now);
484
+ lesson = newLesson(id, proposal, envelope, window, risk, now, prior.id);
485
+ state.evidence.lessons.push(lesson);
486
+ result.archivedLessonId = prior.id;
487
+ } else {
488
+ lesson = state.evidence.lessons.find((item) => item.id === proposal.topicId);
489
+ const evidence = sample(proposal, envelope);
490
+ if (proposal.action === "COUNTER") addUnique(lesson.counterGames, evidence);
491
+ else addUnique(lesson.supportGames, evidence);
492
+ lesson.lastReviewed = envelope.game.reviewDate;
493
+ }
494
+ if (lesson.risk === "execution") transitionExecution(state, lesson);
495
+ else {
496
+ if (independentCount(lesson.counterGames) > 0 && lesson.status === "candidate") lesson.status = "contested";
497
+ ensureSuggestion(state, lesson, now);
498
+ }
499
+ reconcileSuggestions(state, lesson, now);
500
+ enforceProfileLimits(state, lesson.profile);
501
+ for (const affected of state.evidence.lessons.filter((item) => item.profile === lesson.profile)) {
502
+ reconcileSuggestions(state, affected, now);
503
+ }
504
+ result = { ...result, outcome: lesson.status, lessonId: lesson.id, risk: lesson.risk };
505
+ }
506
+ state.ledger.entries.push({
507
+ debriefId: envelope.debriefId,
508
+ gameId: envelope.game.gameId,
509
+ bodyHash,
510
+ action: proposal.action,
511
+ outcome: result.outcome,
512
+ processedAt: nowIso(now)
513
+ });
514
+ return result;
515
+ }
516
+ function applyIncident(state, envelope, bodyHash, reasons, now = /* @__PURE__ */ new Date()) {
517
+ if (state.ledger.entries.some((entry2) => entry2.debriefId === envelope.debriefId || entry2.gameId === envelope.game.gameId)) return { outcome: "duplicate" };
518
+ state.incidents.incidents.push({
519
+ debriefId: envelope.debriefId,
520
+ gameId: envelope.game.gameId,
521
+ reviewDate: envelope.game.reviewDate,
522
+ reasons,
523
+ recordedAt: nowIso(now)
524
+ });
525
+ state.ledger.entries.push({
526
+ debriefId: envelope.debriefId,
527
+ gameId: envelope.game.gameId,
528
+ bodyHash,
529
+ action: "INCIDENT",
530
+ outcome: "incident-skipped",
531
+ processedAt: nowIso(now)
532
+ });
533
+ return { outcome: "incident-skipped" };
534
+ }
535
+ function incidentReasons(envelope) {
536
+ const reasons = [];
537
+ if (!envelope.game.normalEnd) reasons.push("ABNORMAL_END");
538
+ if (envelope.game.systemHealthGate !== "PASS") reasons.push("SYSTEM_HEALTH_SKIP_REQUIRED");
539
+ if (!envelope.game.timelineComplete) reasons.push("TIMELINE_INCOMPLETE");
540
+ if (envelope.game.voteConsistency === "INCONSISTENT") reasons.push("VOTE_RESULT_INCONSISTENT");
541
+ if (isUnknownEligibilityValue(envelope.game.role)) reasons.push("IDENTITY_UNKNOWN");
542
+ if (isUnknownEligibilityValue(envelope.game.team)) reasons.push("TEAM_UNKNOWN");
543
+ if (isUnknownEligibilityValue(envelope.game.finalState)) reasons.push("FINAL_STATE_UNKNOWN");
544
+ if (isUnknownEligibilityValue(envelope.game.result)) reasons.push("RESULT_UNKNOWN");
545
+ return reasons;
546
+ }
547
+
548
+ // src/service.ts
549
+ function clone(value) {
550
+ return structuredClone(value);
551
+ }
552
+ function requireToolWorkspace(ctx, bound) {
553
+ if (!ctx.workspaceDir || !ctx.agentId || !ctx.sessionKey) throw new Error("TOOL_CONTEXT_INCOMPLETE");
554
+ if (ctx.workspaceDir !== bound.workspaceDir || ctx.agentId !== bound.agentId || ctx.sessionKey !== bound.sessionKey) {
555
+ throw new Error("BOUND_CONTEXT_MISMATCH");
556
+ }
557
+ if (ctx.messageChannel !== bound.inbound.channelId || (ctx.deliveryContext?.accountId?.trim() || "default") !== bound.inbound.accountId) {
558
+ throw new Error("BOUND_DELIVERY_MISMATCH");
559
+ }
560
+ return ctx.workspaceDir;
561
+ }
562
+ function normalizedSender2(value) {
563
+ return value.replace(/^(?:clawtopia|coolclaw):/, "").replace(/^human:/, "");
564
+ }
565
+ function assertOwnerDirectContext(ctx, bound, command, input) {
566
+ if (!bound.senderIsOwner || !bound.senderId || !ctx.requesterSenderId) throw new Error("OWNER_REQUIRED");
567
+ if (!ctx.messageChannel || ctx.messageChannel !== command.channelId) throw new Error("CHANNEL_MISMATCH");
568
+ const to = ctx.deliveryContext?.to;
569
+ if (!to || !to.startsWith(`${command.channelId}:human:`) || normalizedSender2(to) === "0") {
570
+ throw new Error("DIRECT_MESSAGE_REQUIRED");
571
+ }
572
+ const expected = normalizedSender2(command.from);
573
+ if (normalizedSender2(bound.senderId) !== expected || normalizedSender2(ctx.requesterSenderId) !== expected || normalizedSender2(to) !== expected) {
574
+ throw new Error("OWNER_SENDER_MISMATCH");
575
+ }
576
+ if (command.suggestionId !== input.suggestionId || command.decision !== input.decision) {
577
+ throw new Error("OWNER_COMMAND_MISMATCH");
578
+ }
579
+ }
580
+ function relevantTopics(state, profile) {
581
+ return state.evidence.lessons.filter((lesson) => lesson.profile === profile && lesson.status !== "archived").sort((left, right) => right.lastReviewed.localeCompare(left.lastReviewed)).slice(0, 24).map((lesson) => ({
582
+ id: lesson.id,
583
+ status: lesson.status,
584
+ risk: lesson.risk,
585
+ profile: lesson.profile,
586
+ phase: lesson.phase,
587
+ role: lesson.role,
588
+ players: lesson.players,
589
+ actionType: lesson.actionType,
590
+ decisionType: lesson.decisionType,
591
+ executionOperation: lesson.executionOperation,
592
+ trigger: lesson.trigger,
593
+ rule: lesson.rule,
594
+ boundary: lesson.boundary,
595
+ expectedLocalEffect: lesson.expectedLocalEffect,
596
+ falsifier: lesson.falsifier,
597
+ supportCount: lesson.supportGames.length,
598
+ counterCount: lesson.counterGames.length
599
+ }));
600
+ }
601
+ function activeRuntimeProfile(state, envelopeProfile) {
602
+ const runtime = inspectRuntimeProjection(state.agentsText);
603
+ if (!runtime) throw new Error("PROFILE_UNKNOWN");
604
+ if (envelopeProfile !== void 0 && envelopeProfile !== runtime.activeProfile) {
605
+ throw new Error("ENVELOPE_PROFILE_MISMATCH");
606
+ }
607
+ return runtime.activeProfile;
608
+ }
609
+ function changedAcceptedProfiles(current, next) {
610
+ const acceptedByProfile = (items) => {
611
+ const map = /* @__PURE__ */ new Map();
612
+ for (const profile of new Set(items.map((item) => item.profile))) {
613
+ map.set(profile, items.filter((item) => item.profile === profile && item.status === "accepted").map((item) => item.id).sort().join(","));
614
+ }
615
+ return map;
616
+ };
617
+ const before = acceptedByProfile(current);
618
+ const after = acceptedByProfile(next);
619
+ return [.../* @__PURE__ */ new Set([...before.keys(), ...after.keys()])].filter((profile) => before.get(profile) !== after.get(profile));
620
+ }
621
+ function addProfileUpdates(paths, current, next, changes) {
622
+ const profiles = changedAcceptedProfiles(current.suggestions.suggestions, next.suggestions.suggestions);
623
+ const expected = /* @__PURE__ */ new Map();
624
+ for (const profile of profiles) {
625
+ const update = buildProfileOverride(paths, profile, current.agentsText, next.suggestions.suggestions);
626
+ changes.set(update.file, update.content);
627
+ next.agentsText = projectProfilePlaybook(next.agentsText, profile, update.playbook);
628
+ expected.set(profile, { file: update.file, content: update.content });
629
+ }
630
+ return expected;
631
+ }
632
+ function claimPendingSuggestionReminder(paths, expectedVersion) {
633
+ return runWorkspaceTransaction(paths, () => {
634
+ assertWorkspaceSetupReady(paths, expectedVersion);
635
+ const current = readWorkspaceState(paths);
636
+ const pending = current.suggestions.suggestions.filter((item) => item.status === "pending" && !item.reminderSentAt).sort((left, right) => left.id.localeCompare(right.id))[0];
637
+ if (!pending) return { changes: /* @__PURE__ */ new Map(), result: void 0 };
638
+ const next = clone(current);
639
+ const selected = next.suggestions.suggestions.find((item) => item.id === pending.id);
640
+ selected.reminderSentAt = (/* @__PURE__ */ new Date()).toISOString();
641
+ return {
642
+ changes: /* @__PURE__ */ new Map([[paths.suggestions, renderSuggestions(next.suggestions)]]),
643
+ result: selected,
644
+ verify: () => verifyWorkspaceDocuments(paths)
645
+ };
646
+ });
647
+ }
648
+ var WerewolfEvolutionService = class {
649
+ contexts = new EvolutionContextStore();
650
+ version;
651
+ ordinaryDirectMessages = /* @__PURE__ */ new Map();
652
+ ownerDirectRuns = /* @__PURE__ */ new Map();
653
+ observedRuns = /* @__PURE__ */ new Map();
654
+ constructor(version = getWerewolfEvolutionVersion()) {
655
+ this.version = version;
656
+ }
657
+ captureMessage(event, ctx) {
658
+ const captured = this.contexts.capture(event, ctx);
659
+ const runId = event.runId ?? ctx.runId;
660
+ if (!captured && runId && ctx.sessionKey && isHumanDirectMessage(event, ctx)) {
661
+ this.ordinaryDirectMessages.set(runId, {
662
+ channelId: ctx.channelId,
663
+ accountId: normalizedAccountId(ctx.accountId),
664
+ from: event.from,
665
+ sessionKey: ctx.sessionKey,
666
+ capturedAt: Date.now()
667
+ });
668
+ }
669
+ }
670
+ bindAgentRun(event, ctx, binding, explicitOwnerAuthorized = false) {
671
+ const now = Date.now();
672
+ for (const [runId, observed] of this.observedRuns) {
673
+ if (observed.expiresAt < now) this.observedRuns.delete(runId);
674
+ }
675
+ for (const [runId, direct] of this.ownerDirectRuns) {
676
+ if (direct.expiresAt < now) this.ownerDirectRuns.delete(runId);
677
+ }
678
+ for (const [runId, inbound] of this.ordinaryDirectMessages) {
679
+ if (now - inbound.capturedAt > 10 * 60 * 1e3) this.ordinaryDirectMessages.delete(runId);
680
+ }
681
+ if (ctx.runId && ctx.sessionKey && ctx.agentId && ctx.workspaceDir) {
682
+ this.observedRuns.set(ctx.runId, {
683
+ sessionKey: ctx.sessionKey,
684
+ agentId: ctx.agentId,
685
+ workspaceDir: ctx.workspaceDir,
686
+ expiresAt: now + 10 * 60 * 1e3
687
+ });
688
+ }
689
+ const bound = this.contexts.bindAgentRun(event, ctx, binding, Date.now(), explicitOwnerAuthorized);
690
+ const ordinary = ctx.runId ? this.ordinaryDirectMessages.get(ctx.runId) : void 0;
691
+ if (ctx.runId) this.ordinaryDirectMessages.delete(ctx.runId);
692
+ if (!bound && ordinary && ctx.runId && ctx.sessionKey && ctx.agentId && ctx.workspaceDir && ordinary.sessionKey === ctx.sessionKey && ordinary.channelId === event.channelId && ordinary.accountId === normalizedAccountId(event.accountId) && explicitOwnerAuthorized && event.senderIsOwner === true && event.senderId && sameHumanSender(event.senderId, ordinary.from)) {
693
+ this.ownerDirectRuns.set(ctx.runId, {
694
+ sessionKey: ctx.sessionKey,
695
+ agentId: ctx.agentId,
696
+ workspaceDir: ctx.workspaceDir,
697
+ senderId: event.senderId,
698
+ expiresAt: now + 10 * 60 * 1e3
699
+ });
700
+ }
701
+ }
702
+ buildPromptContext(ctx) {
703
+ const bound = this.contexts.getBound(ctx.runId, ctx.sessionKey);
704
+ if (!bound) {
705
+ const ownerRun = ctx.runId ? this.ownerDirectRuns.get(ctx.runId) : void 0;
706
+ if (!ownerRun || ownerRun.sessionKey !== ctx.sessionKey || ownerRun.agentId !== ctx.agentId || ownerRun.workspaceDir !== ctx.workspaceDir || ownerRun.expiresAt < Date.now()) return void 0;
707
+ this.ownerDirectRuns.delete(ctx.runId);
708
+ try {
709
+ const paths = resolveWorkspacePaths(ownerRun.workspaceDir);
710
+ assertWorkspaceOwner(paths, ownerRun.senderId);
711
+ const reminder = claimPendingSuggestionReminder(paths, this.version);
712
+ if (!reminder) return void 0;
713
+ return {
714
+ appendContext: [
715
+ "[werewolf-evolution pending suggestion reminder]",
716
+ "This is a trusted ordinary direct message from the Agent owner.",
717
+ `Remind the owner once about ${reminder.id}; do not call werewolf_suggestion_decide unless the original message is an exact decision command.`,
718
+ `\u89E6\u53D1\uFF1A${reminder.trigger}`,
719
+ `\u89C4\u5219\uFF1A${reminder.rule}`,
720
+ `\u8FB9\u754C\uFF1A${reminder.boundary}`,
721
+ `\u8BC1\u636E\uFF1A${reminder.supportCount} \u5C40\u652F\u6301\uFF0C${reminder.counterCount} \u5C40\u53CD\u4F8B\u3002`,
722
+ `\u53EF\u56DE\u590D\u201C\u91C7\u7EB3 ${reminder.id}\u201D\u6216\u201C\u5FFD\u7565 ${reminder.id}\u201D\u3002`,
723
+ "Never repeat this reminder in a game room, group, system debrief, or non-owner conversation."
724
+ ].join("\n")
725
+ };
726
+ } catch {
727
+ return void 0;
728
+ }
729
+ }
730
+ if (bound.agentId !== ctx.agentId || bound.workspaceDir !== ctx.workspaceDir) return void 0;
731
+ if (bound.inbound.kind === "suggestion-command") {
732
+ try {
733
+ const paths = resolveWorkspacePaths(bound.workspaceDir);
734
+ assertWorkspaceSetupReady(paths, this.version);
735
+ assertWorkspaceOwner(paths, bound.inbound.from);
736
+ } catch {
737
+ return void 0;
738
+ }
739
+ return {
740
+ appendContext: `[werewolf-evolution] Trusted owner direct-message command captured for ${bound.inbound.suggestionId}. Call werewolf_suggestion_decide exactly once with decision=${bound.inbound.decision}. Do not mention or process this command in a game room or group.`
741
+ };
742
+ }
743
+ const captured = bound.inbound;
744
+ let topics = [];
745
+ let stateAvailable = true;
746
+ let activeProfile;
747
+ let stateError;
748
+ try {
749
+ const paths = resolveWorkspacePaths(bound.workspaceDir);
750
+ const snapshot = runWorkspaceRead(paths, () => {
751
+ assertWorkspaceSetupReady(paths, this.version);
752
+ const state = readWorkspaceState(paths);
753
+ const profile = activeRuntimeProfile(state, captured.envelope.game.profile);
754
+ return { profile, topics: relevantTopics(state, profile) };
755
+ });
756
+ activeProfile = snapshot.profile;
757
+ topics = snapshot.topics;
758
+ } catch (error) {
759
+ stateAvailable = false;
760
+ stateError = error instanceof Error ? error.message : String(error);
761
+ }
762
+ const facts = captured.envelope.facts.map((fact) => ({
763
+ factId: fact.factId,
764
+ historyIndex: fact.availableAt.historyIndex,
765
+ visibility: fact.visibility,
766
+ type: fact.type,
767
+ actorSeat: fact.actorSeat,
768
+ targetSeat: fact.targetSeat,
769
+ summary: fact.summary
770
+ }));
771
+ return {
772
+ appendContext: [
773
+ "[werewolf-evolution trusted context]",
774
+ `debriefId=${captured.envelope.debriefId}`,
775
+ `eligibility=${JSON.stringify(captured.envelope.game)}`,
776
+ `activeProfile=${activeProfile ?? "UNKNOWN"}`,
777
+ `facts=${JSON.stringify(facts)}`,
778
+ `decisionWindows=${JSON.stringify(captured.envelope.decisionWindows)}`,
779
+ `existingTopics=${JSON.stringify(topics)}`,
780
+ `executionTemplates=${JSON.stringify(EXECUTION_PROPOSAL_TEMPLATES)}`,
781
+ `stateAvailable=${stateAvailable}`,
782
+ ...stateError ? [`stateError=${stateError}`] : [],
783
+ ...stateAvailable ? ["The proposal profile must equal activeProfile. The Arena envelope is not the profile authority."] : ["Workspace evolution state is unavailable. Do not infer a profile or submit evolutionary evidence."],
784
+ "Scan SELF, OBSERVED, and EXEMPLAR, then submit at most one SKIP/SUPPORT/COUNTER/REFINE/NEW proposal.",
785
+ "Prefer a matching existing topic over NEW. Call werewolf_debrief_commit exactly once.",
786
+ "Never use generic write, edit, patch, shell, or memory-write tools for debrief state."
787
+ ].join("\n")
788
+ };
789
+ }
790
+ beforeToolCall(event, ctx) {
791
+ const runId = event.runId ?? ctx.runId;
792
+ const toolCallId = event.toolCallId ?? ctx.toolCallId;
793
+ const bound = this.contexts.getBound(runId, ctx.sessionKey);
794
+ if (!bound) {
795
+ const observed = runId ? this.observedRuns.get(runId) : void 0;
796
+ if (!observed || observed.sessionKey !== ctx.sessionKey || observed.expiresAt < Date.now()) return void 0;
797
+ const paths = resolveWorkspacePaths(observed.workspaceDir, false);
798
+ if (isProtectedToolWrite(event.toolName, event.params, event.derivedPaths, paths, false, event.toolKind)) {
799
+ return { block: true, blockReason: "Werewolf managed state is writable only through restricted tools" };
800
+ }
801
+ return void 0;
802
+ }
803
+ const expectedTool = bound.inbound.kind === "debrief" ? "werewolf_debrief_commit" : "werewolf_suggestion_decide";
804
+ if (event.toolName !== expectedTool) {
805
+ return { block: true, blockReason: `This bound Werewolf run permits only ${expectedTool}` };
806
+ }
807
+ try {
808
+ if (event.toolName === "werewolf_debrief_commit") {
809
+ if (bound.inbound.kind !== "debrief" || event.params.debriefId !== bound.inbound.envelope.debriefId) {
810
+ throw new Error("DEBRIEF_CAPABILITY_MISMATCH");
811
+ }
812
+ this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId);
813
+ } else if (event.toolName === "werewolf_suggestion_decide") {
814
+ if (bound.inbound.kind !== "suggestion-command" || event.params.suggestionId !== bound.inbound.suggestionId || event.params.decision !== bound.inbound.decision) {
815
+ throw new Error("SUGGESTION_CAPABILITY_MISMATCH");
816
+ }
817
+ this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId);
818
+ }
819
+ } catch (error) {
820
+ return { block: true, blockReason: error instanceof Error ? error.message : String(error) };
821
+ }
822
+ return void 0;
823
+ }
824
+ commit(toolCallId, ctx, input, hooks = {}) {
825
+ const bound = this.contexts.consumeToolCall(toolCallId, ctx.sessionKey);
826
+ const workspaceDir = requireToolWorkspace(ctx, bound);
827
+ if (bound.inbound.kind !== "debrief") throw new Error("DEBRIEF_CAPABILITY_REQUIRED");
828
+ const captured = bound.inbound;
829
+ if (captured.conflict) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
830
+ if (input.debriefId !== captured.envelope.debriefId) throw new Error("DEBRIEF_ID_MISMATCH");
831
+ const paths = resolveWorkspacePaths(workspaceDir);
832
+ return runWorkspaceTransaction(paths, () => {
833
+ assertWorkspaceSetupReady(paths, this.version);
834
+ const current = readWorkspaceState(paths);
835
+ const prior = current.ledger.entries.find((entry2) => entry2.debriefId === captured.envelope.debriefId);
836
+ if (prior) {
837
+ if (prior.bodyHash !== captured.bodyHash) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
838
+ return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate", debriefId: captured.envelope.debriefId } };
839
+ }
840
+ if (current.ledger.entries.some((entry2) => entry2.gameId === captured.envelope.game.gameId)) {
841
+ return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate-game", gameId: captured.envelope.game.gameId } };
842
+ }
843
+ if (current.ledger.legacyGameIds.includes(captured.envelope.game.gameId)) {
844
+ return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate-game", gameId: captured.envelope.game.gameId } };
845
+ }
846
+ const next = clone(current);
847
+ const incidents = incidentReasons(captured.envelope);
848
+ let result;
849
+ if (incidents.length > 0) {
850
+ result = applyIncident(next, captured.envelope, captured.bodyHash, incidents);
851
+ } else {
852
+ const activeProfile = activeRuntimeProfile(current, captured.envelope.game.profile);
853
+ const validated = parseAndValidateProposal(
854
+ input.proposal,
855
+ captured.envelope,
856
+ current.evidence,
857
+ activeProfile
858
+ );
859
+ result = applyProposal(
860
+ next,
861
+ captured.envelope,
862
+ captured.bodyHash,
863
+ validated.proposal,
864
+ validated.risk,
865
+ validated.decisionWindow
866
+ );
867
+ }
868
+ next.agentsText = current.agentsText;
869
+ const changes = workspaceChanges(paths, next);
870
+ const changedProfiles = addProfileUpdates(paths, current, next, changes);
871
+ const finalAgentChange = workspaceChanges(paths, next).get(paths.agents);
872
+ if (finalAgentChange === void 0) changes.delete(paths.agents);
873
+ else changes.set(paths.agents, finalAgentChange);
874
+ return {
875
+ changes,
876
+ result: { status: "committed", debriefId: captured.envelope.debriefId, ...result },
877
+ verify: () => {
878
+ verifyWorkspaceDocuments(paths);
879
+ for (const [profile, expected] of changedProfiles) {
880
+ verifyProfileOverride(expected.file, profile, expected.content);
881
+ }
882
+ }
883
+ };
884
+ }, hooks);
885
+ }
886
+ decideSuggestion(toolCallId, ctx, input, hooks = {}) {
887
+ const bound = this.contexts.consumeToolCall(toolCallId, ctx.sessionKey);
888
+ const workspaceDir = requireToolWorkspace(ctx, bound);
889
+ if (bound.inbound.kind !== "suggestion-command") throw new Error("SUGGESTION_CAPABILITY_REQUIRED");
890
+ assertOwnerDirectContext(ctx, bound, bound.inbound, input);
891
+ const paths = resolveWorkspacePaths(workspaceDir);
892
+ return runWorkspaceTransaction(paths, () => {
893
+ assertWorkspaceSetupReady(paths, this.version);
894
+ assertWorkspaceOwner(paths, bound.inbound.from);
895
+ const current = readWorkspaceState(paths);
896
+ const suggestion = current.suggestions.suggestions.find((item) => item.id === input.suggestionId);
897
+ if (!suggestion || suggestion.status !== "pending") throw new Error("PENDING_SUGGESTION_NOT_FOUND");
898
+ const next = clone(current);
899
+ const nextSuggestion = next.suggestions.suggestions.find((item) => item.id === input.suggestionId);
900
+ nextSuggestion.status = input.decision === "accept" ? "accepted" : "rejected";
901
+ nextSuggestion.decidedAt = (/* @__PURE__ */ new Date()).toISOString();
902
+ nextSuggestion.decidedBy = ctx.requesterSenderId;
903
+ next.agentsText = current.agentsText;
904
+ const changes = workspaceChanges(paths, next);
905
+ const changedProfiles = addProfileUpdates(paths, current, next, changes);
906
+ const finalAgentChange = workspaceChanges(paths, next).get(paths.agents);
907
+ if (finalAgentChange === void 0) changes.delete(paths.agents);
908
+ else changes.set(paths.agents, finalAgentChange);
909
+ return {
910
+ changes,
911
+ result: { status: nextSuggestion.status, suggestionId: nextSuggestion.id },
912
+ verify: () => {
913
+ verifyWorkspaceDocuments(paths);
914
+ for (const [profile, expected] of changedProfiles) {
915
+ verifyProfileOverride(expected.file, profile, expected.content);
916
+ }
917
+ }
918
+ };
919
+ }, hooks);
920
+ }
921
+ };
922
+ function proposalFailure(error) {
923
+ if (error instanceof ProposalError) return { status: "rejected", code: error.code, message: error.message };
924
+ return { status: "rejected", code: "EVOLUTION_ERROR", message: error instanceof Error ? error.message : String(error) };
925
+ }
926
+
927
+ // src/tools.ts
928
+ import { Type } from "typebox";
929
+ import {
930
+ jsonResult
931
+ } from "openclaw/plugin-sdk/core";
932
+ var proposalParameters = Type.Object({
933
+ schemaVersion: Type.Literal(1),
934
+ action: Type.Union(["SKIP", "SUPPORT", "COUNTER", "REFINE", "NEW"].map((value) => Type.Literal(value))),
935
+ source: Type.Union(["SELF", "OBSERVED", "EXEMPLAR"].map((value) => Type.Literal(value))),
936
+ topicId: Type.Optional(Type.Union([Type.String(), Type.Null()])),
937
+ profile: Type.Optional(Type.String()),
938
+ decisionWindowId: Type.Optional(Type.String()),
939
+ decisionType: Type.Optional(Type.String()),
940
+ executionOperation: Type.Optional(Type.Union([
941
+ Type.Literal("REPORT_DECIDED_ROLE_CLAIM"),
942
+ Type.Literal("EXPLAIN_DECIDED_VOTE"),
943
+ Type.Literal("RETRACT_PUBLIC_JUDGMENT"),
944
+ Type.Literal("AVOID_REPEATING_PRIOR_SPEAKERS"),
945
+ Type.Literal("EXPLAIN_DECIDED_WOLF_TARGET")
946
+ ])),
947
+ alternativeActionType: Type.Optional(Type.String()),
948
+ alternativeTargetSeat: Type.Optional(Type.Union([Type.Integer(), Type.Null()])),
949
+ anchorFactId: Type.Optional(Type.String()),
950
+ knownFactRefs: Type.Optional(Type.Array(Type.String())),
951
+ outcomeFactRefs: Type.Optional(Type.Array(Type.String())),
952
+ trigger: Type.Optional(Type.String()),
953
+ rule: Type.Optional(Type.String()),
954
+ boundary: Type.Optional(Type.String()),
955
+ behavior: Type.Optional(Type.String()),
956
+ alternativeAction: Type.Optional(Type.String()),
957
+ expectedLocalEffect: Type.Optional(Type.String()),
958
+ observedLocalEffect: Type.Optional(Type.String()),
959
+ falsifier: Type.Optional(Type.String()),
960
+ alternatives: Type.Optional(Type.Array(Type.String())),
961
+ skipReason: Type.Optional(Type.String())
962
+ }, { additionalProperties: false });
963
+ function createDebriefCommitTool(service, ctx) {
964
+ return {
965
+ name: "werewolf_debrief_commit",
966
+ label: "Commit Werewolf Play Debrief",
967
+ description: "Validate and atomically commit one proposal from the trusted werewolf debrief bound to this run.",
968
+ parameters: Type.Object({
969
+ debriefId: Type.String(),
970
+ proposal: proposalParameters
971
+ }, { additionalProperties: false }),
972
+ async execute(toolCallId, raw) {
973
+ try {
974
+ return jsonResult(service.commit(toolCallId, ctx, raw));
975
+ } catch (error) {
976
+ return jsonResult(proposalFailure(error));
977
+ }
978
+ }
979
+ };
980
+ }
981
+ function createSuggestionDecideTool(service, ctx) {
982
+ return {
983
+ name: "werewolf_suggestion_decide",
984
+ label: "Decide Werewolf Play Suggestion",
985
+ description: "Accept or reject one pending werewolf strategy suggestion from an exact owner direct-message command.",
986
+ parameters: Type.Object({
987
+ suggestionId: Type.String({ pattern: "^S-[0-9]{3,6}$" }),
988
+ decision: Type.Union([Type.Literal("accept"), Type.Literal("reject")])
989
+ }, { additionalProperties: false }),
990
+ async execute(toolCallId, raw) {
991
+ try {
992
+ return jsonResult(service.decideSuggestion(
993
+ toolCallId,
994
+ ctx,
995
+ raw
996
+ ));
997
+ } catch (error) {
998
+ return jsonResult(proposalFailure(error));
999
+ }
1000
+ }
1001
+ };
1002
+ }
1003
+
1004
+ // index.ts
1005
+ function registerWerewolfEvolution(api, service = new WerewolfEvolutionService()) {
1006
+ api.registerTool((ctx) => createDebriefCommitTool(service, ctx), { name: "werewolf_debrief_commit" });
1007
+ api.registerTool((ctx) => createSuggestionDecideTool(service, ctx), { name: "werewolf_suggestion_decide" });
1008
+ api.on("message_received", (event, ctx) => {
1009
+ service.captureMessage(event, ctx);
1010
+ });
1011
+ api.on("before_agent_run", (event, ctx) => {
1012
+ const globallyAuthorized = isExplicitConfiguredOwner(api.config, event.channelId, event.senderId);
1013
+ const workspaceAuthorized = globallyAuthorized && Boolean(ctx.workspaceDir) && isWorkspaceOwner(
1014
+ resolveWorkspacePaths(ctx.workspaceDir, false),
1015
+ event.channelId,
1016
+ event.senderId
1017
+ );
1018
+ service.bindAgentRun(
1019
+ event,
1020
+ ctx,
1021
+ resolveAgentAccountBinding(api.config, event.channelId, event.accountId),
1022
+ workspaceAuthorized
1023
+ );
1024
+ });
1025
+ api.on("before_prompt_build", (_event, ctx) => service.buildPromptContext(ctx));
1026
+ api.on("before_tool_call", (event, ctx) => service.beforeToolCall(event, ctx));
1027
+ }
1028
+ var entry = definePluginEntry({
1029
+ id: "werewolf-evolution",
1030
+ name: "Werewolf Evolution",
1031
+ description: "Validates and atomically commits Werewolf Play postgame evolution proposals.",
1032
+ configSchema: emptyPluginConfigSchema(),
1033
+ register(api) {
1034
+ registerWerewolfEvolution(api);
1035
+ }
1036
+ });
1037
+ var index_default = entry;
1038
+ export {
1039
+ index_default as default,
1040
+ registerWerewolfEvolution
1041
+ };