@clawtopia/werewolf-evolution 0.1.10 → 0.1.12

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.d.ts CHANGED
@@ -110,6 +110,10 @@ interface BoundRun {
110
110
  consumed: boolean;
111
111
  proposalAttempts: number;
112
112
  promptContext?: string;
113
+ terminalDiagnostic?: {
114
+ status: string;
115
+ code: string;
116
+ };
113
117
  boundAt: number;
114
118
  expiresAt: number;
115
119
  }
@@ -148,20 +152,28 @@ interface AgentRunContextLike {
148
152
  declare class EvolutionContextStore {
149
153
  private readonly inboundByRun;
150
154
  private readonly inboundBySession;
155
+ private readonly inboundByStableKey;
156
+ private readonly stableKeyByInbound;
157
+ private readonly stableKeyExpiresAt;
158
+ private readonly boundTombstoneKeys;
159
+ private readonly releasedTombstones;
151
160
  private readonly boundByRun;
152
161
  private readonly hashByDebriefId;
153
162
  private readonly toolCalls;
154
163
  capture(event: MessageReceivedLike, ctx: MessageContextLike, now?: number): CapturedInbound | undefined;
155
164
  getPending(runId?: string, sessionKey?: string, prompt?: string, now?: number): CapturedInbound | undefined;
165
+ private stableInboundKey;
156
166
  private storeInbound;
157
167
  private removeInbound;
168
+ private compactBoundTombstone;
158
169
  bindAgentRun(event: AgentRunEventLike, ctx: AgentRunContextLike, binding: AgentAccountBinding | undefined, now?: number, explicitOwnerAuthorized?: boolean, pendingInbound?: CapturedInbound): BoundRun | undefined;
159
170
  getBound(runId?: string, sessionKey?: string, now?: number): BoundRun | undefined;
160
171
  getBoundForToolCall(runId: string | undefined, sessionKey: string | undefined, agentId: string | undefined, now?: number): BoundRun | undefined;
161
172
  private resolveBoundForToolCall;
162
- releaseRun(runId: string | undefined, sessionKey?: string): boolean;
173
+ releaseRun(runId: string | undefined, sessionKey?: string): BoundRun | undefined;
163
174
  consume(runId: string, sessionKey: string, now?: number): BoundRun;
164
175
  authorizeToolCall(runId: string | undefined, sessionKey: string | undefined, toolCallId: string | undefined, now?: number, agentId?: string): BoundRun;
176
+ inspectAuthorizedToolCall(toolCallId: string, sessionKey: string | undefined, agentId: string | undefined, now?: number): BoundRun | undefined;
165
177
  consumeToolCall(toolCallId: string, sessionKey?: string, now?: number): BoundRun;
166
178
  beginProposalToolCall(toolCallId: string, sessionKey?: string, now?: number): BoundRun;
167
179
  private beginToolCall;
@@ -180,6 +192,11 @@ interface SuggestionDecisionInput {
180
192
  suggestionId: string;
181
193
  decision: "accept" | "reject";
182
194
  }
195
+ interface DebriefToolDiagnostic {
196
+ debriefId: string;
197
+ runId: string;
198
+ agentId: string;
199
+ }
183
200
  interface PromptContextLike extends AgentRunContextLike {
184
201
  }
185
202
  interface PromptBuildEventLike {
@@ -197,6 +214,26 @@ interface MessageSendingLike {
197
214
  to: string;
198
215
  content?: string;
199
216
  }
217
+ interface InboundClaimLike {
218
+ senderId?: string;
219
+ content: string;
220
+ channel: string;
221
+ accountId?: string;
222
+ sessionKey?: string;
223
+ runId?: string;
224
+ messageId?: string;
225
+ conversationId?: string;
226
+ isGroup?: boolean;
227
+ }
228
+ interface InboundClaimContextLike {
229
+ channelId?: string;
230
+ accountId?: string;
231
+ sessionKey?: string;
232
+ runId?: string;
233
+ messageId?: string;
234
+ senderId?: string;
235
+ conversationId?: string;
236
+ }
200
237
  declare class WerewolfEvolutionService {
201
238
  readonly contexts: EvolutionContextStore;
202
239
  private readonly version;
@@ -210,12 +247,22 @@ declare class WerewolfEvolutionService {
210
247
  private cleanupSystemDebriefSessions;
211
248
  private matchesSystemDebriefTarget;
212
249
  captureMessage(event: MessageReceivedLike, ctx: MessageContextLike): CapturedInbound | undefined;
250
+ captureInboundClaim(event: InboundClaimLike, ctx?: InboundClaimContextLike): CapturedInbound | undefined;
213
251
  isSystemDebriefMessage(event: MessageSendingLike, ctx: Pick<MessageContextLike, "channelId" | "accountId" | "sessionKey" | "conversationId">): boolean;
214
252
  private pendingOrdinaryDirectMessage;
215
253
  private consumeOrdinaryDirectMessage;
216
254
  bindAgentRun(event: AgentRunEventLike, ctx: AgentRunContextLike, binding: AgentAccountBinding | undefined, explicitOwnerAuthorized?: boolean, pendingInbound?: CapturedDebrief | CapturedSuggestionCommand, pendingOrdinary?: OrdinaryDirectMessage): BoundRun | undefined;
217
255
  bindPromptRun(event: PromptBuildEventLike, ctx: AgentRunContextLike, config: unknown): BoundRun | undefined;
218
- finishRun(ctx: Pick<AgentRunContextLike, "runId" | "sessionKey">): void;
256
+ recordTerminalDiagnostic(runId: string, sessionKey: string | undefined, terminal: {
257
+ status: string;
258
+ code: string;
259
+ }): BoundRun | undefined;
260
+ finishRun(ctx: Pick<AgentRunContextLike, "runId" | "sessionKey"> & {
261
+ success?: boolean;
262
+ }): {
263
+ bound: BoundRun;
264
+ terminalCreated: boolean;
265
+ } | undefined;
219
266
  buildPromptContext(ctx: PromptContextLike, hooks?: TransactionHooks): {
220
267
  prependContext: string;
221
268
  } | undefined;
@@ -235,6 +282,7 @@ declare class WerewolfEvolutionService {
235
282
  block?: boolean;
236
283
  blockReason?: string;
237
284
  } | undefined;
285
+ inspectDebriefToolCall(toolCallId: string, ctx: Pick<OpenClawPluginToolContext, "sessionKey" | "agentId">): DebriefToolDiagnostic | undefined;
238
286
  private persistIncident;
239
287
  commit(toolCallId: string, ctx: OpenClawPluginToolContext, input: CommitInput, hooks?: TransactionHooks): Record<string, unknown>;
240
288
  decideSuggestion(toolCallId: string, ctx: OpenClawPluginToolContext, input: SuggestionDecisionInput, hooks?: TransactionHooks): Record<string, unknown>;
package/dist/index.js CHANGED
@@ -4,6 +4,9 @@ import {
4
4
  emptyPluginConfigSchema
5
5
  } from "openclaw/plugin-sdk/core";
6
6
 
7
+ // src/context-store.ts
8
+ import { createHash as createHash2 } from "crypto";
9
+
7
10
  // src/envelope.ts
8
11
  import { createHash } from "crypto";
9
12
  import { z } from "zod";
@@ -316,6 +319,11 @@ function isTrustedDebriefOrigin(channelId, from) {
316
319
  if (channelId !== "clawtopia" && channelId !== "coolclaw") return false;
317
320
  return from === `${channelId}:human:0`;
318
321
  }
322
+ function isTrustedDebriefClaimOrigin(channelId, senderId, conversationId) {
323
+ if (channelId !== "clawtopia" && channelId !== "coolclaw") return false;
324
+ if (senderId) return isTrustedDebriefOrigin(channelId, senderId);
325
+ return conversationId?.trim().toLowerCase() === "human:0";
326
+ }
319
327
  function isUnknownEligibilityValue(value) {
320
328
  return UNKNOWN_VALUE.test(value.trim());
321
329
  }
@@ -369,6 +377,11 @@ function resolveAgentAccountBinding(config, channelId, accountId) {
369
377
  var EvolutionContextStore = class {
370
378
  inboundByRun = /* @__PURE__ */ new Map();
371
379
  inboundBySession = /* @__PURE__ */ new Map();
380
+ inboundByStableKey = /* @__PURE__ */ new Map();
381
+ stableKeyByInbound = /* @__PURE__ */ new Map();
382
+ stableKeyExpiresAt = /* @__PURE__ */ new Map();
383
+ boundTombstoneKeys = /* @__PURE__ */ new Set();
384
+ releasedTombstones = /* @__PURE__ */ new Map();
372
385
  boundByRun = /* @__PURE__ */ new Map();
373
386
  hashByDebriefId = /* @__PURE__ */ new Map();
374
387
  toolCalls = /* @__PURE__ */ new Map();
@@ -377,6 +390,11 @@ var EvolutionContextStore = class {
377
390
  const runId = event.runId ?? ctx.runId;
378
391
  const sessionKey = event.sessionKey ?? ctx.sessionKey;
379
392
  if (!sessionKey) return void 0;
393
+ const stableKey = this.stableInboundKey(ctx, sessionKey, event);
394
+ const existing = this.inboundByStableKey.get(stableKey);
395
+ if (existing) return existing;
396
+ if (this.releasedTombstones.has(stableKey)) return void 0;
397
+ if (this.inboundByStableKey.size + this.releasedTombstones.size >= MAX_CAPTURES) return void 0;
380
398
  if (isTrustedDebriefOrigin(ctx.channelId, event.from)) {
381
399
  try {
382
400
  const { envelope, bodyHash } = parseDebriefBody(event.content);
@@ -397,7 +415,7 @@ var EvolutionContextStore = class {
397
415
  ...prior && prior.hash !== bodyHash ? { conflict: true } : {}
398
416
  };
399
417
  this.hashByDebriefId.set(envelope.debriefId, prior ?? { hash: bodyHash, capturedAt: now });
400
- this.storeInbound(captured);
418
+ this.storeInbound(captured, stableKey);
401
419
  return captured;
402
420
  } catch {
403
421
  return void 0;
@@ -419,7 +437,7 @@ var EvolutionContextStore = class {
419
437
  decision: match[1] === "\u91C7\u7EB3" ? "accept" : "reject",
420
438
  capturedAt: now
421
439
  };
422
- this.storeInbound(command);
440
+ this.storeInbound(command, stableKey);
423
441
  return command;
424
442
  }
425
443
  getPending(runId, sessionKey, prompt, now = Date.now()) {
@@ -434,7 +452,12 @@ var EvolutionContextStore = class {
434
452
  if (!pending) return void 0;
435
453
  return pending.find((candidate) => prompt.includes(candidate.content));
436
454
  }
437
- storeInbound(inbound) {
455
+ stableInboundKey(ctx, sessionKey, event) {
456
+ const messageId = event.messageId?.trim();
457
+ const identity = messageId ? ["message", messageId] : ["content", createHash2("sha256").update(event.content).digest("hex")];
458
+ return JSON.stringify([ctx.channelId, normalizedAccountId(ctx.accountId), sessionKey, identity]);
459
+ }
460
+ storeInbound(inbound, stableKey) {
438
461
  if (inbound.runId) {
439
462
  const previous = this.inboundByRun.get(inbound.runId);
440
463
  if (previous) this.removeInbound(previous);
@@ -443,8 +466,20 @@ var EvolutionContextStore = class {
443
466
  const pending = this.inboundBySession.get(inbound.sessionKey) ?? [];
444
467
  pending.push(inbound);
445
468
  this.inboundBySession.set(inbound.sessionKey, pending);
446
- }
447
- removeInbound(inbound) {
469
+ this.inboundByStableKey.set(stableKey, inbound);
470
+ this.stableKeyByInbound.set(inbound, stableKey);
471
+ this.stableKeyExpiresAt.set(stableKey, inbound.capturedAt + CAPTURE_TTL_MS);
472
+ }
473
+ removeInbound(inbound, preserveStableKey = false) {
474
+ if (!preserveStableKey) {
475
+ const stableKey = this.stableKeyByInbound.get(inbound);
476
+ if (stableKey && this.inboundByStableKey.get(stableKey) === inbound) {
477
+ this.inboundByStableKey.delete(stableKey);
478
+ this.stableKeyExpiresAt.delete(stableKey);
479
+ this.boundTombstoneKeys.delete(stableKey);
480
+ }
481
+ this.stableKeyByInbound.delete(inbound);
482
+ }
448
483
  if (inbound.runId && this.inboundByRun.get(inbound.runId) === inbound) {
449
484
  this.inboundByRun.delete(inbound.runId);
450
485
  }
@@ -454,6 +489,16 @@ var EvolutionContextStore = class {
454
489
  if (index >= 0) pending.splice(index, 1);
455
490
  if (pending.length === 0) this.inboundBySession.delete(inbound.sessionKey);
456
491
  }
492
+ compactBoundTombstone(bound) {
493
+ const stableKey = this.stableKeyByInbound.get(bound.inbound);
494
+ if (!stableKey) return;
495
+ const expiresAt = this.stableKeyExpiresAt.get(stableKey) ?? bound.expiresAt;
496
+ this.inboundByStableKey.delete(stableKey);
497
+ this.stableKeyByInbound.delete(bound.inbound);
498
+ this.stableKeyExpiresAt.delete(stableKey);
499
+ this.boundTombstoneKeys.delete(stableKey);
500
+ this.releasedTombstones.set(stableKey, expiresAt);
501
+ }
457
502
  bindAgentRun(event, ctx, binding, now = Date.now(), explicitOwnerAuthorized = false, pendingInbound) {
458
503
  this.cleanup(now);
459
504
  if (!ctx.runId || !ctx.sessionKey || !ctx.agentId || !ctx.workspaceDir) return void 0;
@@ -470,7 +515,13 @@ var EvolutionContextStore = class {
470
515
  } else {
471
516
  if (!explicitOwnerAuthorized || event.senderIsOwner !== true || !event.senderId || normalizedSender(event.senderId) !== normalizedSender(inbound.from)) return void 0;
472
517
  }
473
- this.removeInbound(inbound);
518
+ const stableKey = this.stableKeyByInbound.get(inbound);
519
+ const expiresAt = now + CAPTURE_TTL_MS;
520
+ if (stableKey) {
521
+ this.boundTombstoneKeys.add(stableKey);
522
+ this.stableKeyExpiresAt.set(stableKey, expiresAt);
523
+ }
524
+ this.removeInbound(inbound, true);
474
525
  const bound = {
475
526
  runId: ctx.runId,
476
527
  sessionKey: ctx.sessionKey,
@@ -482,7 +533,7 @@ var EvolutionContextStore = class {
482
533
  consumed: false,
483
534
  proposalAttempts: 0,
484
535
  boundAt: now,
485
- expiresAt: now + CAPTURE_TTL_MS
536
+ expiresAt
486
537
  };
487
538
  this.boundByRun.set(ctx.runId, bound);
488
539
  return bound;
@@ -512,14 +563,15 @@ var EvolutionContextStore = class {
512
563
  return bound;
513
564
  }
514
565
  releaseRun(runId, sessionKey) {
515
- if (!runId) return false;
566
+ if (!runId) return void 0;
516
567
  const bound = this.boundByRun.get(runId);
517
- if (!bound || sessionKey && bound.sessionKey !== sessionKey) return false;
568
+ if (!bound || sessionKey && bound.sessionKey !== sessionKey) return void 0;
518
569
  this.boundByRun.delete(runId);
570
+ this.compactBoundTombstone(bound);
519
571
  for (const [toolCallId, authorized] of this.toolCalls) {
520
572
  if (authorized.runId === runId) this.toolCalls.delete(toolCallId);
521
573
  }
522
- return true;
574
+ return bound;
523
575
  }
524
576
  consume(runId, sessionKey, now = Date.now()) {
525
577
  const bound = this.getBound(runId, sessionKey, now);
@@ -538,6 +590,16 @@ var EvolutionContextStore = class {
538
590
  this.toolCalls.set(toolCallId, { runId: bound.runId, sessionKey, expiresAt: bound.expiresAt });
539
591
  return bound;
540
592
  }
593
+ inspectAuthorizedToolCall(toolCallId, sessionKey, agentId, now = Date.now()) {
594
+ this.cleanup(now);
595
+ const authorized = this.toolCalls.get(toolCallId);
596
+ if (!authorized || authorized.expiresAt < now || !sessionKey || authorized.sessionKey !== sessionKey) {
597
+ return void 0;
598
+ }
599
+ const bound = this.boundByRun.get(authorized.runId);
600
+ if (!bound || bound.sessionKey !== sessionKey || bound.expiresAt < now) return void 0;
601
+ return agentId && bound.agentId !== agentId ? void 0 : bound;
602
+ }
541
603
  consumeToolCall(toolCallId, sessionKey, now = Date.now()) {
542
604
  const bound = this.beginToolCall(toolCallId, sessionKey, now);
543
605
  return this.consume(bound.runId, bound.sessionKey, now);
@@ -565,16 +627,16 @@ var EvolutionContextStore = class {
565
627
  return bound;
566
628
  }
567
629
  cleanup(now = Date.now()) {
568
- for (const [key, value] of this.inboundByRun) {
569
- if (now - value.capturedAt > CAPTURE_TTL_MS) this.removeInbound(value);
570
- }
571
- for (const [key, values] of this.inboundBySession) {
572
- const current = values.filter((value) => now - value.capturedAt <= CAPTURE_TTL_MS);
573
- if (current.length === 0) this.inboundBySession.delete(key);
574
- else if (current.length !== values.length) this.inboundBySession.set(key, current);
630
+ for (const [key, value] of this.inboundByStableKey) {
631
+ if ((this.stableKeyExpiresAt.get(key) ?? value.capturedAt + CAPTURE_TTL_MS) < now) {
632
+ this.removeInbound(value);
633
+ }
575
634
  }
576
635
  for (const [key, value] of this.boundByRun) {
577
- if (value.expiresAt < now) this.boundByRun.delete(key);
636
+ if (value.expiresAt < now) {
637
+ this.boundByRun.delete(key);
638
+ this.compactBoundTombstone(value);
639
+ }
578
640
  }
579
641
  for (const [key, value] of this.toolCalls) {
580
642
  if (value.expiresAt < now) this.toolCalls.delete(key);
@@ -582,11 +644,19 @@ var EvolutionContextStore = class {
582
644
  for (const [key, value] of this.hashByDebriefId) {
583
645
  if (now - value.capturedAt > CAPTURE_TTL_MS) this.hashByDebriefId.delete(key);
584
646
  }
647
+ for (const [key, expiresAt] of this.releasedTombstones) {
648
+ if (expiresAt < now) this.releasedTombstones.delete(key);
649
+ }
585
650
  while (this.inboundByRun.size > MAX_CAPTURES) {
586
651
  const first = this.inboundByRun.values().next().value;
587
652
  if (!first) break;
588
653
  this.removeInbound(first);
589
654
  }
655
+ while (this.inboundByStableKey.size - this.boundTombstoneKeys.size > MAX_CAPTURES) {
656
+ const first = [...this.inboundByStableKey].find(([key]) => !this.boundTombstoneKeys.has(key))?.[1];
657
+ if (!first) break;
658
+ this.removeInbound(first);
659
+ }
590
660
  while ([...this.inboundBySession.values()].reduce((total, values) => total + values.length, 0) > MAX_CAPTURES) {
591
661
  const firstKey = this.inboundBySession.keys().next().value;
592
662
  if (!firstKey) break;
@@ -598,7 +668,6 @@ var EvolutionContextStore = class {
598
668
  }
599
669
  this.removeInbound(first);
600
670
  }
601
- while (this.boundByRun.size > MAX_CAPTURES) this.boundByRun.delete(this.boundByRun.keys().next().value);
602
671
  while (this.toolCalls.size > MAX_CAPTURES) this.toolCalls.delete(this.toolCalls.keys().next().value);
603
672
  while (this.hashByDebriefId.size > MAX_CAPTURES) this.hashByDebriefId.delete(this.hashByDebriefId.keys().next().value);
604
673
  }
@@ -689,6 +758,40 @@ var EXECUTION_PROPOSAL_TEMPLATES = {
689
758
  var STRATEGY_LANGUAGE = /(?:改变|改投|改票|转票|投给|投票目标|查验目标|验谁|刀谁|刀口|毒谁|救谁|用药|开枪|起跳|跳预言家|自刀|悍跳|倒钩|站边|目标座位|targetSeat|actionType|vote target|check target|kill target)/i;
690
759
  var FIXED_RULE_LANGUAGE = /(?:JSON\s*schema|JSON格式|非法动作|角色动作合法|私有信息保护|不虚构时间线|工具失败|输出超时|现实人格|人身攻击)/i;
691
760
  var COUNTER_EFFECT_LANGUAGE = /(?:未能|没有|无法|无效|反而|恶化|失败|矛盾|误导|暴露|did not|failed|ineffective|worse|contradict)/i;
761
+ var NO_TARGET_ALTERNATIVE_LANGUAGE = /(?:保留投票权|等待更多信息|暂不(?:投票|选择|行动)|弃票|不选(?:择)?(?:任何)?(?:目标|座位)|不指定目标|不设目标|继续观望|\b(?:wait for more information|abstain|hold (?:the )?vote|choose no target)\b)/i;
762
+ var EXPLICIT_TARGET_LANGUAGE = /(?:(?:改投|改票(?:到|给)?|归票|票投|投票(?:给|到)?|投(?:给|到)?|查验|验|刀|毒|救|开枪带走|目标(?:改为|是)?)\s*|target(?:\s+seat)?[^0-9]{0,6})([1-9][0-9]*)\s*(?:号|座|\b)/gi;
763
+ var FINAL_RESULT_LANGUAGE = /(?:最终|终局|全场|对局结果|比赛结果)[^。;,,!!]{0,16}(?:获胜|胜利|胜出|取胜|赢了|输了|落败|失败)|(?:好人(?:阵营)?|村民|平民|狼人(?:阵营)?|狼队)[^。;,,!!]{0,10}(?:获胜|胜利|胜出|取胜|赢了|输了|落败)|(?:险胜|惨胜|翻盘获胜|为(?:最终)?胜利铺路)|赢下(?:本局|这局|对局|比赛)|(?:GOOD|WOLF)(?:_TEAM)?_WIN|(?:the\s+)?(?:(?:good|village|wolf)\s+team|villagers?|village|wolves|wolf|werewolves?)\s+(?:wins?|won|loses?|lost)|(?:won|lost) the game|final (?:victory|defeat)/i;
764
+ var SEAT_REFERENCE_LANGUAGE = /([1-9][0-9]*)\s*号(?:玩家)?/g;
765
+ var BEHAVIOR_TERMS = "\u53D1\u8A00|\u8868\u73B0|\u884C\u4E3A|\u8BF4\u6CD5|\u5185\u5BB9|\u7AD9\u8FB9|\u7968\u578B|\u6295\u7968|\u5F52\u7968|\u7529\u9505|\u8D28\u7591|\u5BF9\u8DF3|\u8D77\u8DF3|\u608D\u8DF3|\u5012\u94A9|\u67E5\u6740|\u4FDD\u4EBA|\u8E29\u4EBA|\u653B\u51FB|\u8FA9\u89E3|\u8DDF\u7968|\u51B2\u7968|\u8868\u6C34";
766
+ var FIRST_NIGHT_DAYTIME_INFORMATION = new RegExp(
767
+ `(?:\u73A9\u5BB6)?\u53D1\u8A00\u98CE\u683C|(?:\u767D\u5929|\u767D\u663C|\u65E5\u95F4|\u9996\u65E5|\u7B2C\u4E00\u5929|\u5929\u4EAE\u540E|\u6B21\u65E5|\u7B2C\u4E8C\u5929|\u968F\u540E|\u540E\u7EED)[^\u3002\uFF1B\uFF0C,!\uFF01]{0,16}(?:${BEHAVIOR_TERMS})|(?:${BEHAVIOR_TERMS})[^\u3002\uFF1B\uFF0C,!\uFF01]{0,16}(?:\u767D\u5929|\u767D\u663C|\u65E5\u95F4|\u9996\u65E5|\u7B2C\u4E00\u5929|\u5929\u4EAE\u540E|\u6B21\u65E5|\u7B2C\u4E8C\u5929|\u968F\u540E|\u540E\u7EED)`,
768
+ "i"
769
+ );
770
+ var DIRECTLY_NEGATED_DAYTIME_INFORMATION = /(?:尚无|暂无|没有|尚未(?:出现|发生)?)(?:任何)?(?:白天|白昼|日间|首日|第一天)?(?:发言|站边|票型|归票|信息)|不(?:得|可|能|应)?(?:参考|使用|依赖)(?:(?:任何)?(?:白天|白昼|日间|首日|第一天)(?:发言|站边|票型|归票|信息)|(?:玩家)?发言风格)|(?:白天|白昼|日间|首日|第一天)(?:发言|站边|票型|归票|信息)(?:尚无|暂无|尚未(?:出现|发生)|不可用|不能使用)/gi;
771
+ var RELATIVE_FUTURE_BEHAVIOR_LANGUAGE = new RegExp(
772
+ `(?:(?:\u540E\u7F6E\u4F4D|\u5176\u4ED6\u73A9\u5BB6)[^\u3002\uFF1B\uFF0C,!\uFF01]{0,10}(?:\u968F\u540E|\u4E4B\u540E|\u5C06\u4F1A?|\u7A0D\u540E)|\u5929\u4EAE(?:\u540E|\u4E4B\u540E)|\u6B21\u65E5|\u4E0B\u4E00(?:\u5929|\u8F6E|\u4E2A\u767D\u5929))[^\u3002\uFF1B\uFF0C,!\uFF01]{0,20}(?:${BEHAVIOR_TERMS})`,
773
+ "i"
774
+ );
775
+ var ABSOLUTE_DAY_BEHAVIOR_LANGUAGE = new RegExp(`\u7B2C([0-9\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u5341]+)\u5929[^\u3002\uFF1B\uFF0C,!\uFF01]{0,24}(?:${BEHAVIOR_TERMS})`, "gi");
776
+ var BEHAVIOR_OCCURRENCE_LANGUAGE = new RegExp(`(?:${BEHAVIOR_TERMS})`, "i");
777
+ var PAST_BEHAVIOR_LANGUAGE = new RegExp(`(?:\u6B64\u524D|\u4E4B\u524D|\u66FE\u7ECF|\u8FC7\u53BB|\u4E0A\u4E00\u8F6E|\u4E0A\u4E00\u591C|\u6628\u591C)|\u5DF2\u7ECF(?!\u51B3\u5B9A)[^\u3002\uFF1B\uFF0C,!\uFF01]{0,4}(?:${BEHAVIOR_TERMS})`, "i");
778
+ var CURRENT_ACTOR_ACTION_LANGUAGE = /(?:当前|本次|此时|轮到|发言时|投票时|行动时|查验时|已经决定|正在|正要|准备|计划|将要)/i;
779
+ var NEGATED_BEHAVIOR_LANGUAGE = new RegExp(`(?:\u6CA1\u6709|\u5E76\u672A|\u672A\u66FE|\u4E0D\u66FE|\u4ECE\u672A|\u5C1A\u672A|\u4E0D)[^\u3002\uFF1B\uFF0C,!\uFF01]{0,6}(?:${BEHAVIOR_TERMS})|(?:did not|never|no)\\b`, "i");
780
+ var BEHAVIOR_TARGET_LANGUAGE = /(?:归票|投票(?:给|到)?|票投(?:给|到)?|投(?:给|到)|跟票(?:给|到)?|冲票(?:给|到)?|查杀|保人|踩|攻击|质疑)(?:给|到|向)?\s*([1-9][0-9]*)\s*号/i;
781
+ var TARGET_REFERENCE_PREFIX = /(?:归票|投票|票投|投给|投到|跟票|冲票|查杀|保人|踩|攻击|质疑)(?:给|到|向)?\s*$/i;
782
+ var SPEECH_FACT_TYPES = /* @__PURE__ */ new Set(["DAY_SPEAK", "LAST_WORD", "WOLF_SPEECH"]);
783
+ var VOTE_FACT_TYPES = /* @__PURE__ */ new Set(["DAY_VOTE_SUBMIT", "DAY_REVOTE_SUBMIT"]);
784
+ var BEHAVIOR_GROUPS = [
785
+ /(?:投票|归票|跟票|冲票|票投|出票)/i,
786
+ /(?:甩锅|推责|责任推|把责任)/i,
787
+ /(?:站边|支持|认好|认狼|side with|support)/i,
788
+ /(?:质疑|怀疑|攻击|踩人|question|suspect|attack)/i,
789
+ /(?:对跳|起跳|悍跳|拍身份|公开身份|role claim|claim(?:ed)? (?:seer|witch|hunter))/i,
790
+ /(?:倒钩)/i,
791
+ /(?:查杀)/i,
792
+ /(?:保人|金水)/i,
793
+ /(?:辩解|表水)/i
794
+ ];
692
795
  var LOCAL_OUTCOME_FACT_TYPES = /* @__PURE__ */ new Set([
693
796
  "WOLF_CHOOSE",
694
797
  "WOLF_SPEECH",
@@ -776,6 +879,164 @@ function similarity(left, right) {
776
879
  function sameSemanticText(left, right) {
777
880
  return typeof left === "string" && semanticText(left) === semanticText(right);
778
881
  }
882
+ function stripUnavailableDaytimeInformation(value) {
883
+ return value.replace(DIRECTLY_NEGATED_DAYTIME_INFORMATION, "");
884
+ }
885
+ function behaviorTarget(value) {
886
+ const direct = BEHAVIOR_TARGET_LANGUAGE.exec(value);
887
+ if (direct) return Number(direct[1]);
888
+ for (const match of value.matchAll(SEAT_REFERENCE_LANGUAGE)) {
889
+ const prefix = value.slice(Math.max(0, match.index - 12), match.index);
890
+ if (TARGET_REFERENCE_PREFIX.test(prefix)) return Number(match[1]);
891
+ }
892
+ return void 0;
893
+ }
894
+ function factSupportsBehaviorClaim(fact, claim) {
895
+ if (fact.actorSeat == null) return false;
896
+ const summary = fact.summary;
897
+ const claimedTarget = behaviorTarget(claim);
898
+ if (claimedTarget !== void 0) {
899
+ const observedTarget = fact.targetSeat ?? behaviorTarget(summary);
900
+ if (observedTarget !== claimedTarget) return false;
901
+ }
902
+ if (NEGATED_BEHAVIOR_LANGUAGE.test(claim) !== NEGATED_BEHAVIOR_LANGUAGE.test(summary)) {
903
+ return false;
904
+ }
905
+ const groups = BEHAVIOR_GROUPS.filter((pattern) => pattern.test(claim));
906
+ if (groups.length > 0) {
907
+ if (groups.some((pattern) => pattern.test(summary))) return true;
908
+ return groups.some((pattern) => pattern === BEHAVIOR_GROUPS[0] && VOTE_FACT_TYPES.has(fact.type));
909
+ }
910
+ if (/(?:发言|说法|内容)/i.test(claim) && SPEECH_FACT_TYPES.has(fact.type)) {
911
+ const shortGenericClaim = semanticText(claim).length <= 6;
912
+ return shortGenericClaim || similarity(claim, summary) >= 0.28;
913
+ }
914
+ return similarity(claim, summary) >= 0.35;
915
+ }
916
+ function seatBehaviorClaims(value) {
917
+ const claims = [];
918
+ for (const clause of value.split(/[。;,,!!]/)) {
919
+ const seats = [...clause.matchAll(SEAT_REFERENCE_LANGUAGE)];
920
+ for (let index = 0; index < seats.length; index++) {
921
+ const match = seats[index];
922
+ const start = match.index;
923
+ const nextSeat = seats[index + 1];
924
+ const beforeNextSeat = nextSeat ? clause.slice(start + match[0].length, nextSeat.index) : "";
925
+ const end = nextSeat && TARGET_REFERENCE_PREFIX.test(beforeNextSeat) ? nextSeat.index + nextSeat[0].length : nextSeat?.index ?? clause.length;
926
+ const claim = clause.slice(start, end).trim();
927
+ if (BEHAVIOR_OCCURRENCE_LANGUAGE.test(claim)) claims.push({ seat: Number(match[1]), claim });
928
+ }
929
+ }
930
+ return claims;
931
+ }
932
+ function isCurrentDecisionActorClaim(claim) {
933
+ return !PAST_BEHAVIOR_LANGUAGE.test(claim) && CURRENT_ACTOR_ACTION_LANGUAGE.test(claim);
934
+ }
935
+ function chineseNumber(value) {
936
+ if (/^[0-9]+$/.test(value)) return Number(value);
937
+ const digits = {
938
+ \u4E00: 1,
939
+ \u4E8C: 2,
940
+ \u4E09: 3,
941
+ \u56DB: 4,
942
+ \u4E94: 5,
943
+ \u516D: 6,
944
+ \u4E03: 7,
945
+ \u516B: 8,
946
+ \u4E5D: 9
947
+ };
948
+ if (value === "\u5341") return 10;
949
+ if (value.startsWith("\u5341")) return 10 + (digits[value[1]] ?? 0);
950
+ if (value.endsWith("\u5341")) return (digits[value[0]] ?? 0) * 10;
951
+ const [tens, ones] = value.split("\u5341");
952
+ if (ones !== void 0) return (digits[tens] ?? 0) * 10 + (digits[ones] ?? 0);
953
+ return digits[value];
954
+ }
955
+ function dependsOnFutureBehavior(value, currentRound) {
956
+ if (RELATIVE_FUTURE_BEHAVIOR_LANGUAGE.test(value)) return true;
957
+ if (currentRound === void 0) return false;
958
+ for (const match of value.matchAll(ABSOLUTE_DAY_BEHAVIOR_LANGUAGE)) {
959
+ const referencedRound = chineseNumber(match[1]);
960
+ if (referencedRound !== void 0 && referencedRound > currentRound) return true;
961
+ }
962
+ return false;
963
+ }
964
+ function assertBehaviorIsObserved(proposal) {
965
+ const behavior = proposal.behavior ?? "";
966
+ const overlap = Math.max(
967
+ similarity(behavior, proposal.alternativeAction ?? ""),
968
+ similarity(behavior, proposal.rule ?? "")
969
+ );
970
+ if (overlap >= 0.68) {
971
+ throw new ProposalError(
972
+ "BEHAVIOR_COUNTERFACTUAL",
973
+ "behavior must describe the observed action, not the recommended alternative"
974
+ );
975
+ }
976
+ }
977
+ function assertAlternativeTargetConsistent(proposal) {
978
+ const target = proposal.alternativeTargetSeat;
979
+ if (target == null) return;
980
+ const action = proposal.alternativeAction ?? "";
981
+ const mentionedTargets = [...action.matchAll(EXPLICIT_TARGET_LANGUAGE)].map((match) => Number(match[1]));
982
+ if (mentionedTargets.length === 0 && NO_TARGET_ALTERNATIVE_LANGUAGE.test(action)) {
983
+ throw new ProposalError(
984
+ "ALTERNATIVE_TARGET_CONTRADICTION",
985
+ "alternativeTargetSeat contradicts an alternative action that selects no target"
986
+ );
987
+ }
988
+ if (mentionedTargets.length > 0 && !mentionedTargets.includes(target)) {
989
+ throw new ProposalError(
990
+ "ALTERNATIVE_TARGET_CONTRADICTION",
991
+ "alternativeTargetSeat contradicts the target explicitly named by alternativeAction"
992
+ );
993
+ }
994
+ }
995
+ function assertLocalOutcomeEvidence(outcomeCount, localOutcomeCount, observed) {
996
+ if (outcomeCount === 0 || localOutcomeCount === 0) {
997
+ throw new ProposalError(
998
+ "LOCAL_OUTCOME_FACT_REQUIRED",
999
+ "Victory, final identity, or other postgame facts cannot be the only outcome evidence"
1000
+ );
1001
+ }
1002
+ if (FINAL_RESULT_LANGUAGE.test(observed.trim())) {
1003
+ throw new ProposalError("FINAL_RESULT_NOT_LOCAL", "Final victory or defeat is not a local effect");
1004
+ }
1005
+ }
1006
+ function assertActionTimeSemantics(proposal, window, anchor, knownFacts) {
1007
+ const actionTimeFields = [
1008
+ proposal.trigger,
1009
+ proposal.rule,
1010
+ proposal.boundary,
1011
+ proposal.alternativeAction
1012
+ ].filter((value) => typeof value === "string");
1013
+ if (window.phase === "SEER_TURN" && anchor.availableAt.round === 1 && proposal.alternativeActionType === "SEER_CHECK") {
1014
+ const rationale = actionTimeFields.map(stripUnavailableDaytimeInformation).join("\u3002 ");
1015
+ if (FIRST_NIGHT_DAYTIME_INFORMATION.test(rationale)) {
1016
+ throw new ProposalError(
1017
+ "SEER_DAY_INFORMATION_UNAVAILABLE",
1018
+ "A first-night seer check cannot depend on later daytime behavior"
1019
+ );
1020
+ }
1021
+ }
1022
+ if (actionTimeFields.some((value) => dependsOnFutureBehavior(value, anchor.availableAt.round))) {
1023
+ throw new ProposalError(
1024
+ "FUTURE_BEHAVIOR_DEPENDENCY",
1025
+ "A proposal field cannot depend on behavior after the decision anchor"
1026
+ );
1027
+ }
1028
+ const actionTimeText = actionTimeFields.join("\u3002 ");
1029
+ for (const { seat, claim } of seatBehaviorClaims(actionTimeText)) {
1030
+ if (seat === window.actorSeat && isCurrentDecisionActorClaim(claim)) continue;
1031
+ const supported = [anchor, ...knownFacts].some((fact) => fact.actorSeat === seat && factSupportsBehaviorClaim(fact, claim));
1032
+ if (!supported) {
1033
+ throw new ProposalError(
1034
+ "UNKNOWN_SEAT_BEHAVIOR_DEPENDENCY",
1035
+ "A trigger or alternative action cannot depend on an unsupported seat behavior"
1036
+ );
1037
+ }
1038
+ }
1039
+ }
779
1040
  function factVisibleToActor(visibility, window) {
780
1041
  if (visibility === "PUBLIC") return true;
781
1042
  if (visibility === "POSTGAME_ONLY") return false;
@@ -956,8 +1217,11 @@ function parseAndValidateProposal(raw, envelope, evidence, activeProfile) {
956
1217
  if (!anchor || anchor.visibility === "POSTGAME_ONLY") {
957
1218
  throw new ProposalError("ANCHOR_NOT_OBSERVABLE", "The action anchor is missing or postgame-only");
958
1219
  }
1220
+ assertBehaviorIsObserved(proposal);
1221
+ proposal.behavior = anchor.summary;
959
1222
  const known = proposal.knownFactRefs ?? [];
960
1223
  const outcomes = proposal.outcomeFactRefs ?? [];
1224
+ const knownFacts = [];
961
1225
  unique(known, "DUPLICATE_KNOWN_FACT");
962
1226
  unique(outcomes, "DUPLICATE_OUTCOME_FACT");
963
1227
  for (const ref of known) {
@@ -975,6 +1239,7 @@ function parseAndValidateProposal(raw, envelope, evidence, activeProfile) {
975
1239
  if (fact.availableAt.historyIndex >= anchor.availableAt.historyIndex) {
976
1240
  throw new ProposalError("KNOWN_FACT_TOO_LATE", `Known fact is not earlier than the action: ${ref}`);
977
1241
  }
1242
+ knownFacts.push(fact);
978
1243
  }
979
1244
  let localOutcomeCount = 0;
980
1245
  for (const ref of outcomes) {
@@ -987,19 +1252,16 @@ function parseAndValidateProposal(raw, envelope, evidence, activeProfile) {
987
1252
  localOutcomeCount++;
988
1253
  }
989
1254
  }
990
- if (outcomes.length === 0 || localOutcomeCount === 0) {
991
- throw new ProposalError("LOCAL_OUTCOME_FACT_REQUIRED", "Victory, final identity, or other postgame facts cannot be the only outcome evidence");
992
- }
1255
+ assertActionTimeSemantics(proposal, window, anchor, knownFacts);
1256
+ assertLocalOutcomeEvidence(outcomes.length, localOutcomeCount, observed);
993
1257
  const allRefs = /* @__PURE__ */ new Set([...known, ...outcomes]);
994
1258
  if (allRefs.size !== known.length + outcomes.length) {
995
1259
  throw new ProposalError("FACT_ROLE_CONFLICT", "A fact cannot be both known information and an outcome");
996
1260
  }
997
- if (/^(?:因此|所以)?(?:最终)?(?:好人|狼人|狼队|阵营)?(?:获胜|胜利|输了|失败|赢了)[。.!!]?$/i.test(observed.trim())) {
998
- throw new ProposalError("FINAL_RESULT_NOT_LOCAL", "Final victory or defeat is not a local effect");
999
- }
1000
1261
  let risk = classifyRisk(proposal, window.allowedDecisionTypes.find((item) => item === decisionType));
1001
1262
  if (risk === "execution" && alternativeActionType !== window.actionType) risk = "strategy";
1002
1263
  assertAlternativeTarget(proposal, window, risk);
1264
+ assertAlternativeTargetConsistent(proposal);
1003
1265
  if (existing) {
1004
1266
  assertExistingSemantics(proposal, existing, window, action, envelope.game.players);
1005
1267
  if (action === "REFINE") assertRefinement(proposal, existing, risk);
@@ -2558,6 +2820,30 @@ var WerewolfEvolutionService = class {
2558
2820
  }
2559
2821
  return captured;
2560
2822
  }
2823
+ captureInboundClaim(event, ctx = {}) {
2824
+ if (event.isGroup === true) return void 0;
2825
+ const channelId = event.channel || ctx.channelId || "";
2826
+ const senderId = event.senderId ?? ctx.senderId;
2827
+ const conversationId = event.conversationId ?? ctx.conversationId;
2828
+ if (!isTrustedDebriefClaimOrigin(channelId, senderId, conversationId)) return void 0;
2829
+ const trustedSenderId = senderId ?? `${channelId}:human:0`;
2830
+ return this.captureMessage(
2831
+ {
2832
+ from: trustedSenderId,
2833
+ content: event.content,
2834
+ messageId: event.messageId ?? ctx.messageId,
2835
+ sessionKey: event.sessionKey ?? ctx.sessionKey,
2836
+ runId: event.runId ?? ctx.runId
2837
+ },
2838
+ {
2839
+ channelId,
2840
+ accountId: event.accountId ?? ctx.accountId,
2841
+ sessionKey: event.sessionKey ?? ctx.sessionKey,
2842
+ runId: event.runId ?? ctx.runId,
2843
+ conversationId
2844
+ }
2845
+ );
2846
+ }
2561
2847
  isSystemDebriefMessage(event, ctx) {
2562
2848
  const now = Date.now();
2563
2849
  this.cleanupSystemDebriefSessions(now);
@@ -2654,9 +2940,15 @@ var WerewolfEvolutionService = class {
2654
2940
  );
2655
2941
  return bound ?? this.contexts.getBound(ctx.runId, ctx.sessionKey);
2656
2942
  }
2943
+ recordTerminalDiagnostic(runId, sessionKey, terminal) {
2944
+ const bound = this.contexts.getBound(runId, sessionKey);
2945
+ if (!bound || bound.inbound.kind !== "debrief") return void 0;
2946
+ bound.terminalDiagnostic ??= terminal;
2947
+ return bound;
2948
+ }
2657
2949
  finishRun(ctx) {
2658
- if (!ctx.runId) return;
2659
- this.contexts.releaseRun(ctx.runId, ctx.sessionKey);
2950
+ if (!ctx.runId) return void 0;
2951
+ const bound = this.contexts.releaseRun(ctx.runId, ctx.sessionKey);
2660
2952
  this.observedRuns.delete(ctx.runId);
2661
2953
  this.ownerDirectRuns.delete(ctx.runId);
2662
2954
  const systemDebrief = ctx.sessionKey ? this.systemDebriefSessions.get(ctx.sessionKey) : void 0;
@@ -2666,6 +2958,16 @@ var WerewolfEvolutionService = class {
2666
2958
  Date.now() + SYSTEM_DEBRIEF_DELIVERY_GRACE_MS
2667
2959
  );
2668
2960
  }
2961
+ if (!bound) return void 0;
2962
+ let terminalCreated = false;
2963
+ if (bound.inbound.kind === "debrief" && !bound.terminalDiagnostic) {
2964
+ bound.terminalDiagnostic = {
2965
+ status: "abandoned",
2966
+ code: ctx.success === false ? "AGENT_RUN_FAILED" : "COMMIT_NOT_ATTEMPTED"
2967
+ };
2968
+ terminalCreated = true;
2969
+ }
2970
+ return { bound, terminalCreated };
2669
2971
  }
2670
2972
  buildPromptContext(ctx, hooks = {}) {
2671
2973
  const bound = this.contexts.getBound(ctx.runId, ctx.sessionKey);
@@ -2712,18 +3014,25 @@ var WerewolfEvolutionService = class {
2712
3014
  const incidents = incidentReasons(captured.envelope);
2713
3015
  if (incidents.length > 0) {
2714
3016
  let incidentStatus = "already-handled";
3017
+ let incidentCode = "already-handled";
2715
3018
  let incidentError;
2716
3019
  if (!bound.consumed) {
2717
3020
  try {
2718
3021
  const result = this.persistIncident(captured, bound.workspaceDir, incidents, hooks);
2719
3022
  incidentStatus = String(result.status);
3023
+ incidentCode = "outcome" in result ? String(result.outcome) : incidentStatus;
2720
3024
  } catch (error) {
2721
3025
  incidentStatus = "failed";
3026
+ incidentCode = "INCIDENT_PERSIST_FAILED";
2722
3027
  incidentError = error instanceof Error ? error.message : String(error);
2723
3028
  } finally {
2724
3029
  if (!bound.consumed) this.contexts.consume(bound.runId, bound.sessionKey);
2725
3030
  }
2726
3031
  }
3032
+ bound.terminalDiagnostic ??= {
3033
+ status: incidentStatus === "failed" ? "final-rejected" : incidentStatus,
3034
+ code: incidentCode
3035
+ };
2727
3036
  bound.promptContext = [
2728
3037
  "[werewolf-evolution trusted context]",
2729
3038
  `debriefId=${captured.envelope.debriefId}`,
@@ -2757,6 +3066,10 @@ var WerewolfEvolutionService = class {
2757
3066
  }
2758
3067
  if (!stateAvailable) {
2759
3068
  if (!bound.consumed) this.contexts.consume(bound.runId, bound.sessionKey);
3069
+ bound.terminalDiagnostic ??= {
3070
+ status: "final-rejected",
3071
+ code: "WORKSPACE_STATE_UNAVAILABLE"
3072
+ };
2760
3073
  bound.promptContext = [
2761
3074
  "[werewolf-evolution trusted context]",
2762
3075
  `debriefId=${captured.envelope.debriefId}`,
@@ -2786,6 +3099,7 @@ var WerewolfEvolutionService = class {
2786
3099
  `decisionWindows=${JSON.stringify(captured.envelope.decisionWindows)}`,
2787
3100
  `existingTopics=${JSON.stringify(topics)}`,
2788
3101
  `executionTemplates=${JSON.stringify(EXECUTION_PROPOSAL_TEMPLATES)}`,
3102
+ `localOutcomeFactTypes=${JSON.stringify([...LOCAL_OUTCOME_FACT_TYPES])}`,
2789
3103
  `stateAvailable=${stateAvailable}`,
2790
3104
  "The proposal profile must equal activeProfile. The Arena envelope is not the profile authority.",
2791
3105
  "Scan SELF, OBSERVED, and EXEMPLAR, then submit at most one SKIP/SUPPORT/COUNTER/REFINE/NEW proposal.",
@@ -2799,6 +3113,16 @@ var WerewolfEvolutionService = class {
2799
3113
  "- Never send null for an omitted field. Omit the key instead. alternativeTargetSeat may be null only to represent an explicit DAY_VOTE abstention.",
2800
3114
  "- Copy decisionType exactly from the selected decisionWindow.allowedDecisionTypes. Copy alternativeActionType exactly from that same window.availableActionTypes; these are different fields and must not be mixed.",
2801
3115
  "- If alternativeActionType=DAY_VOTE, copy a legal seat from that window.availableTargetSeats, or send alternativeTargetSeat=null for explicit abstention. Do not omit the target for DAY_VOTE.",
3116
+ "- SELF must use a decisionWindow whose actorSeat equals eligibility.recipientSeat. OBSERVED and EXEMPLAR must use another actor's decisionWindow.",
3117
+ "- knownFactRefs must be earlier than the anchor and visible to the window actor; POSTGAME_ONLY is never known, SEAT_n_ONLY is visible only to that seat, and WOLF_TEAM is visible only to a wolf actor.",
3118
+ "- outcomeFactRefs must be later than the anchor and include at least one local outcome fact whose type appears in localOutcomeFactTypes.",
3119
+ "- GAME_FINISHED, FINAL_IDENTITY, and GAME_RESULT are never local outcome facts and cannot be the only outcome evidence.",
3120
+ "- behavior must describe only what actually happened at the anchor; never copy rule or alternativeAction into behavior as if it occurred.",
3121
+ "- The plugin stores behavior from the trusted anchor summary; model prose is checked for counterfactual confusion but never becomes the persisted fact source.",
3122
+ "- alternativeAction must describe a counterfactual action that did not happen; never swap behavior and alternativeAction.",
3123
+ "- observedLocalEffect must not contain the final winner or loser; describe only a later local effect backed by outcomeFactRefs.",
3124
+ "- alternativeTargetSeat must agree with alternativeAction. Text that only waits, retains the vote, or chooses no target and names no later target cannot carry a seat.",
3125
+ "- alternatives must contain at least one plausible alternative explanation. falsifier must state a concrete later observation that would disprove the rule.",
2802
3126
  "Execution versus strategy contract:",
2803
3127
  "- executionOperation must be one of the exact template operations. To claim execution risk, copy that template's operation, decisionType, trigger, rule, boundary, and alternativeAction exactly.",
2804
3128
  "- Strategy proposals must omit executionOperation. CHOOSE_VOTE_TARGET and CHOOSE_ROLE_CLAIM_TIMING are decision types, never executionOperation values.",
@@ -2852,6 +3176,15 @@ var WerewolfEvolutionService = class {
2852
3176
  }
2853
3177
  return void 0;
2854
3178
  }
3179
+ inspectDebriefToolCall(toolCallId, ctx) {
3180
+ const bound = this.contexts.inspectAuthorizedToolCall(toolCallId, ctx.sessionKey, ctx.agentId);
3181
+ if (!bound || bound.inbound.kind !== "debrief") return void 0;
3182
+ return {
3183
+ debriefId: bound.inbound.envelope.debriefId,
3184
+ runId: bound.runId,
3185
+ agentId: bound.agentId
3186
+ };
3187
+ }
2855
3188
  persistIncident(captured, workspaceDir, incidents, hooks) {
2856
3189
  if (captured.conflict) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
2857
3190
  const paths = resolveWorkspacePaths(workspaceDir);
@@ -3061,7 +3394,7 @@ var proposalParameters = Type.Object({
3061
3394
  alternatives: Type.Optional(Type.Array(Type.String())),
3062
3395
  skipReason: Type.Optional(Type.String())
3063
3396
  }, { additionalProperties: false });
3064
- function createDebriefCommitTool(service, ctx) {
3397
+ function createDebriefCommitTool(service, ctx, onExecution) {
3065
3398
  return {
3066
3399
  name: "werewolf_debrief_commit",
3067
3400
  label: "Commit Werewolf Play Debrief",
@@ -3071,11 +3404,18 @@ function createDebriefCommitTool(service, ctx) {
3071
3404
  proposal: proposalParameters
3072
3405
  }, { additionalProperties: false }),
3073
3406
  async execute(toolCallId, raw) {
3407
+ const diagnostic = service.inspectDebriefToolCall(toolCallId, ctx);
3408
+ let details;
3074
3409
  try {
3075
- return jsonResult(service.commit(toolCallId, ctx, raw));
3410
+ details = service.commit(toolCallId, ctx, raw);
3076
3411
  } catch (error) {
3077
- return jsonResult(proposalFailure(error));
3412
+ details = proposalFailure(error);
3078
3413
  }
3414
+ try {
3415
+ onExecution?.({ toolCallId, diagnostic, details });
3416
+ } catch {
3417
+ }
3418
+ return jsonResult(details);
3079
3419
  }
3080
3420
  };
3081
3421
  }
@@ -3104,10 +3444,51 @@ function createSuggestionDecideTool(service, ctx) {
3104
3444
 
3105
3445
  // index.ts
3106
3446
  function registerWerewolfEvolution(api, service = getSharedWerewolfEvolutionService()) {
3107
- api.registerTool((ctx) => createDebriefCommitTool(service, ctx), { name: "werewolf_debrief_commit" });
3447
+ const loggedCaptures = /* @__PURE__ */ new WeakSet();
3448
+ const loggedBindings = /* @__PURE__ */ new WeakSet();
3449
+ const loggedTerminals = /* @__PURE__ */ new WeakSet();
3450
+ const info = (line) => {
3451
+ try {
3452
+ api.logger?.info?.(line);
3453
+ } catch {
3454
+ }
3455
+ };
3456
+ const field = (value) => String(value ?? "unknown").replace(/\s+/g, "_").slice(0, 200);
3457
+ const logTerminal = (capability, diagnostic, terminal) => {
3458
+ if (loggedTerminals.has(capability)) return;
3459
+ loggedTerminals.add(capability);
3460
+ info(
3461
+ `[werewolf-evolution] DEBRIEF_TERMINAL debriefId=${field(diagnostic.debriefId)} runId=${field(diagnostic.runId)} status=${field(terminal.status)} code=${field(terminal.code)}`
3462
+ );
3463
+ };
3464
+ const logCapture = (captured, sourceHook) => {
3465
+ if (!captured || captured.kind !== "debrief" || loggedCaptures.has(captured)) return;
3466
+ loggedCaptures.add(captured);
3467
+ info(
3468
+ `[werewolf-evolution] DEBRIEF_CAPTURED debriefId=${field(captured.envelope.debriefId)} messageId=${field(captured.messageId)} sessionKey=${field(captured.sessionKey)} sourceHook=${field(sourceHook)}`
3469
+ );
3470
+ };
3471
+ api.registerTool((ctx) => createDebriefCommitTool(service, ctx, ({ diagnostic, details }) => {
3472
+ if (!diagnostic || details === null || typeof details !== "object" || Array.isArray(details)) return;
3473
+ const result = details;
3474
+ if (result.status === "rejected" && result.retryable === true) return;
3475
+ const terminal = {
3476
+ status: result.status === "rejected" ? "final-rejected" : result.status,
3477
+ code: result.code ?? result.outcome ?? result.status
3478
+ };
3479
+ const bound = service.recordTerminalDiagnostic(diagnostic.runId, ctx.sessionKey, {
3480
+ status: field(terminal.status),
3481
+ code: field(terminal.code)
3482
+ });
3483
+ logTerminal(bound ?? diagnostic, diagnostic, terminal);
3484
+ }), { name: "werewolf_debrief_commit" });
3108
3485
  api.registerTool((ctx) => createSuggestionDecideTool(service, ctx), { name: "werewolf_suggestion_decide" });
3486
+ api.on("inbound_claim", (event, ctx) => {
3487
+ logCapture(service.captureInboundClaim(event, ctx), "inbound_claim");
3488
+ });
3109
3489
  api.on("message_received", (event, ctx) => {
3110
3490
  const captured = service.captureMessage(event, ctx);
3491
+ logCapture(captured, "message_received");
3111
3492
  if (!captured && event.content.includes(DEBRIEF_HEADER)) {
3112
3493
  api.logger.warn(
3113
3494
  `[werewolf-evolution] DEBRIEF_CAPTURE_REJECTED runId=${event.runId ?? ctx.runId ?? "unknown"} sessionKey=${event.sessionKey ?? ctx.sessionKey ?? "unknown"}`
@@ -3116,17 +3497,40 @@ function registerWerewolfEvolution(api, service = getSharedWerewolfEvolutionServ
3116
3497
  });
3117
3498
  api.on("before_prompt_build", (event, ctx) => {
3118
3499
  const bound = service.bindPromptRun(event, ctx, api.config);
3500
+ if (bound?.inbound.kind === "debrief" && !loggedBindings.has(bound)) {
3501
+ loggedBindings.add(bound);
3502
+ info(
3503
+ `[werewolf-evolution] DEBRIEF_BOUND debriefId=${field(bound.inbound.envelope.debriefId)} runId=${field(bound.runId)} sessionKey=${field(bound.sessionKey)} agentId=${field(bound.agentId)}`
3504
+ );
3505
+ }
3119
3506
  if (!bound && event.prompt.includes(DEBRIEF_HEADER)) {
3120
3507
  api.logger.warn(
3121
3508
  `[werewolf-evolution] DEBRIEF_BIND_MISS runId=${ctx.runId ?? "unknown"} sessionKey=${ctx.sessionKey ?? "unknown"} agentId=${ctx.agentId ?? "unknown"}`
3122
3509
  );
3123
3510
  }
3124
- return service.buildPromptContext(ctx);
3511
+ const promptContext = service.buildPromptContext(ctx);
3512
+ if (bound?.inbound.kind === "debrief" && bound.terminalDiagnostic) {
3513
+ logTerminal(bound, {
3514
+ debriefId: bound.inbound.envelope.debriefId,
3515
+ runId: bound.runId
3516
+ }, bound.terminalDiagnostic);
3517
+ }
3518
+ return promptContext;
3125
3519
  });
3126
3520
  api.on("before_tool_call", (event, ctx) => service.beforeToolCall(event, ctx));
3127
3521
  api.on("message_sending", (event, ctx) => service.isSystemDebriefMessage(event, ctx) ? { cancel: true } : void 0);
3128
3522
  api.on("agent_end", (event, ctx) => {
3129
- service.finishRun({ runId: event.runId ?? ctx.runId, sessionKey: ctx.sessionKey });
3523
+ const finished = service.finishRun({
3524
+ runId: event.runId ?? ctx.runId,
3525
+ sessionKey: ctx.sessionKey,
3526
+ success: event.success
3527
+ });
3528
+ if (finished?.terminalCreated && finished.bound.inbound.kind === "debrief") {
3529
+ logTerminal(finished.bound, {
3530
+ debriefId: finished.bound.inbound.envelope.debriefId,
3531
+ runId: finished.bound.runId
3532
+ }, finished.bound.terminalDiagnostic);
3533
+ }
3130
3534
  });
3131
3535
  }
3132
3536
  var entry = definePluginEntry({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawtopia/werewolf-evolution",
3
- "version": "0.1.10",
3
+ "version": "0.1.12",
4
4
  "description": "Deterministic postgame evolution runtime for the Clawtopia Werewolf Play skill.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",