@clawtopia/werewolf-evolution 0.1.9 → 0.1.11

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
@@ -108,7 +108,12 @@ interface BoundRun {
108
108
  senderId?: string;
109
109
  senderIsOwner: boolean;
110
110
  consumed: boolean;
111
+ proposalAttempts: number;
111
112
  promptContext?: string;
113
+ terminalDiagnostic?: {
114
+ status: string;
115
+ code: string;
116
+ };
112
117
  boundAt: number;
113
118
  expiresAt: number;
114
119
  }
@@ -147,21 +152,31 @@ interface AgentRunContextLike {
147
152
  declare class EvolutionContextStore {
148
153
  private readonly inboundByRun;
149
154
  private readonly inboundBySession;
155
+ private readonly inboundByStableKey;
156
+ private readonly stableKeyByInbound;
157
+ private readonly stableKeyExpiresAt;
158
+ private readonly boundTombstoneKeys;
159
+ private readonly releasedTombstones;
150
160
  private readonly boundByRun;
151
161
  private readonly hashByDebriefId;
152
162
  private readonly toolCalls;
153
163
  capture(event: MessageReceivedLike, ctx: MessageContextLike, now?: number): CapturedInbound | undefined;
154
164
  getPending(runId?: string, sessionKey?: string, prompt?: string, now?: number): CapturedInbound | undefined;
165
+ private stableInboundKey;
155
166
  private storeInbound;
156
167
  private removeInbound;
168
+ private compactBoundTombstone;
157
169
  bindAgentRun(event: AgentRunEventLike, ctx: AgentRunContextLike, binding: AgentAccountBinding | undefined, now?: number, explicitOwnerAuthorized?: boolean, pendingInbound?: CapturedInbound): BoundRun | undefined;
158
170
  getBound(runId?: string, sessionKey?: string, now?: number): BoundRun | undefined;
159
171
  getBoundForToolCall(runId: string | undefined, sessionKey: string | undefined, agentId: string | undefined, now?: number): BoundRun | undefined;
160
172
  private resolveBoundForToolCall;
161
- releaseRun(runId: string | undefined, sessionKey?: string): boolean;
173
+ releaseRun(runId: string | undefined, sessionKey?: string): BoundRun | undefined;
162
174
  consume(runId: string, sessionKey: string, now?: number): BoundRun;
163
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;
164
177
  consumeToolCall(toolCallId: string, sessionKey?: string, now?: number): BoundRun;
178
+ beginProposalToolCall(toolCallId: string, sessionKey?: string, now?: number): BoundRun;
179
+ private beginToolCall;
165
180
  cleanup(now?: number): void;
166
181
  }
167
182
 
@@ -177,6 +192,11 @@ interface SuggestionDecisionInput {
177
192
  suggestionId: string;
178
193
  decision: "accept" | "reject";
179
194
  }
195
+ interface DebriefToolDiagnostic {
196
+ debriefId: string;
197
+ runId: string;
198
+ agentId: string;
199
+ }
180
200
  interface PromptContextLike extends AgentRunContextLike {
181
201
  }
182
202
  interface PromptBuildEventLike {
@@ -194,6 +214,26 @@ interface MessageSendingLike {
194
214
  to: string;
195
215
  content?: string;
196
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
+ }
197
237
  declare class WerewolfEvolutionService {
198
238
  readonly contexts: EvolutionContextStore;
199
239
  private readonly version;
@@ -207,12 +247,22 @@ declare class WerewolfEvolutionService {
207
247
  private cleanupSystemDebriefSessions;
208
248
  private matchesSystemDebriefTarget;
209
249
  captureMessage(event: MessageReceivedLike, ctx: MessageContextLike): CapturedInbound | undefined;
250
+ captureInboundClaim(event: InboundClaimLike, ctx?: InboundClaimContextLike): CapturedInbound | undefined;
210
251
  isSystemDebriefMessage(event: MessageSendingLike, ctx: Pick<MessageContextLike, "channelId" | "accountId" | "sessionKey" | "conversationId">): boolean;
211
252
  private pendingOrdinaryDirectMessage;
212
253
  private consumeOrdinaryDirectMessage;
213
254
  bindAgentRun(event: AgentRunEventLike, ctx: AgentRunContextLike, binding: AgentAccountBinding | undefined, explicitOwnerAuthorized?: boolean, pendingInbound?: CapturedDebrief | CapturedSuggestionCommand, pendingOrdinary?: OrdinaryDirectMessage): BoundRun | undefined;
214
255
  bindPromptRun(event: PromptBuildEventLike, ctx: AgentRunContextLike, config: unknown): BoundRun | undefined;
215
- 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;
216
266
  buildPromptContext(ctx: PromptContextLike, hooks?: TransactionHooks): {
217
267
  prependContext: string;
218
268
  } | undefined;
@@ -232,6 +282,7 @@ declare class WerewolfEvolutionService {
232
282
  block?: boolean;
233
283
  blockReason?: string;
234
284
  } | undefined;
285
+ inspectDebriefToolCall(toolCallId: string, ctx: Pick<OpenClawPluginToolContext, "sessionKey" | "agentId">): DebriefToolDiagnostic | undefined;
235
286
  private persistIncident;
236
287
  commit(toolCallId: string, ctx: OpenClawPluginToolContext, input: CommitInput, hooks?: TransactionHooks): Record<string, unknown>;
237
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,
@@ -480,8 +531,9 @@ var EvolutionContextStore = class {
480
531
  senderId: event.senderId,
481
532
  senderIsOwner: event.senderIsOwner === true,
482
533
  consumed: false,
534
+ proposalAttempts: 0,
483
535
  boundAt: now,
484
- expiresAt: now + CAPTURE_TTL_MS
536
+ expiresAt
485
537
  };
486
538
  this.boundByRun.set(ctx.runId, bound);
487
539
  return bound;
@@ -511,14 +563,15 @@ var EvolutionContextStore = class {
511
563
  return bound;
512
564
  }
513
565
  releaseRun(runId, sessionKey) {
514
- if (!runId) return false;
566
+ if (!runId) return void 0;
515
567
  const bound = this.boundByRun.get(runId);
516
- if (!bound || sessionKey && bound.sessionKey !== sessionKey) return false;
568
+ if (!bound || sessionKey && bound.sessionKey !== sessionKey) return void 0;
517
569
  this.boundByRun.delete(runId);
570
+ this.compactBoundTombstone(bound);
518
571
  for (const [toolCallId, authorized] of this.toolCalls) {
519
572
  if (authorized.runId === runId) this.toolCalls.delete(toolCallId);
520
573
  }
521
- return true;
574
+ return bound;
522
575
  }
523
576
  consume(runId, sessionKey, now = Date.now()) {
524
577
  const bound = this.getBound(runId, sessionKey, now);
@@ -537,26 +590,53 @@ var EvolutionContextStore = class {
537
590
  this.toolCalls.set(toolCallId, { runId: bound.runId, sessionKey, expiresAt: bound.expiresAt });
538
591
  return bound;
539
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
+ }
540
603
  consumeToolCall(toolCallId, sessionKey, now = Date.now()) {
604
+ const bound = this.beginToolCall(toolCallId, sessionKey, now);
605
+ return this.consume(bound.runId, bound.sessionKey, now);
606
+ }
607
+ beginProposalToolCall(toolCallId, sessionKey, now = Date.now()) {
608
+ const bound = this.beginToolCall(toolCallId, sessionKey, now);
609
+ if (bound.inbound.kind !== "debrief") throw new Error("DEBRIEF_CAPABILITY_REQUIRED");
610
+ if (bound.proposalAttempts >= 2) {
611
+ bound.consumed = true;
612
+ throw new Error("CAPABILITY_ALREADY_CONSUMED");
613
+ }
614
+ bound.proposalAttempts += 1;
615
+ return bound;
616
+ }
617
+ beginToolCall(toolCallId, sessionKey, now = Date.now()) {
541
618
  this.cleanup(now);
542
619
  const authorized = this.toolCalls.get(toolCallId);
543
620
  this.toolCalls.delete(toolCallId);
544
621
  if (!authorized || authorized.expiresAt < now || !sessionKey || authorized.sessionKey !== sessionKey) {
545
622
  throw new Error("UNAUTHORIZED_TOOL_CALL");
546
623
  }
547
- return this.consume(authorized.runId, authorized.sessionKey, now);
624
+ const bound = this.getBound(authorized.runId, authorized.sessionKey, now);
625
+ if (!bound) throw new Error("NO_BOUND_CAPABILITY");
626
+ if (bound.consumed) throw new Error("CAPABILITY_ALREADY_CONSUMED");
627
+ return bound;
548
628
  }
549
629
  cleanup(now = Date.now()) {
550
- for (const [key, value] of this.inboundByRun) {
551
- if (now - value.capturedAt > CAPTURE_TTL_MS) this.removeInbound(value);
552
- }
553
- for (const [key, values] of this.inboundBySession) {
554
- const current = values.filter((value) => now - value.capturedAt <= CAPTURE_TTL_MS);
555
- if (current.length === 0) this.inboundBySession.delete(key);
556
- 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
+ }
557
634
  }
558
635
  for (const [key, value] of this.boundByRun) {
559
- if (value.expiresAt < now) this.boundByRun.delete(key);
636
+ if (value.expiresAt < now) {
637
+ this.boundByRun.delete(key);
638
+ this.compactBoundTombstone(value);
639
+ }
560
640
  }
561
641
  for (const [key, value] of this.toolCalls) {
562
642
  if (value.expiresAt < now) this.toolCalls.delete(key);
@@ -564,11 +644,19 @@ var EvolutionContextStore = class {
564
644
  for (const [key, value] of this.hashByDebriefId) {
565
645
  if (now - value.capturedAt > CAPTURE_TTL_MS) this.hashByDebriefId.delete(key);
566
646
  }
647
+ for (const [key, expiresAt] of this.releasedTombstones) {
648
+ if (expiresAt < now) this.releasedTombstones.delete(key);
649
+ }
567
650
  while (this.inboundByRun.size > MAX_CAPTURES) {
568
651
  const first = this.inboundByRun.values().next().value;
569
652
  if (!first) break;
570
653
  this.removeInbound(first);
571
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
+ }
572
660
  while ([...this.inboundBySession.values()].reduce((total, values) => total + values.length, 0) > MAX_CAPTURES) {
573
661
  const firstKey = this.inboundBySession.keys().next().value;
574
662
  if (!firstKey) break;
@@ -580,7 +668,6 @@ var EvolutionContextStore = class {
580
668
  }
581
669
  this.removeInbound(first);
582
670
  }
583
- while (this.boundByRun.size > MAX_CAPTURES) this.boundByRun.delete(this.boundByRun.keys().next().value);
584
671
  while (this.toolCalls.size > MAX_CAPTURES) this.toolCalls.delete(this.toolCalls.keys().next().value);
585
672
  while (this.hashByDebriefId.size > MAX_CAPTURES) this.hashByDebriefId.delete(this.hashByDebriefId.keys().next().value);
586
673
  }
@@ -671,6 +758,9 @@ var EXECUTION_PROPOSAL_TEMPLATES = {
671
758
  var STRATEGY_LANGUAGE = /(?:改变|改投|改票|转票|投给|投票目标|查验目标|验谁|刀谁|刀口|毒谁|救谁|用药|开枪|起跳|跳预言家|自刀|悍跳|倒钩|站边|目标座位|targetSeat|actionType|vote target|check target|kill target)/i;
672
759
  var FIXED_RULE_LANGUAGE = /(?:JSON\s*schema|JSON格式|非法动作|角色动作合法|私有信息保护|不虚构时间线|工具失败|输出超时|现实人格|人身攻击)/i;
673
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;
674
764
  var LOCAL_OUTCOME_FACT_TYPES = /* @__PURE__ */ new Set([
675
765
  "WOLF_CHOOSE",
676
766
  "WOLF_SPEECH",
@@ -725,6 +815,7 @@ var ProposalError = class extends Error {
725
815
  this.name = "ProposalError";
726
816
  }
727
817
  code;
818
+ retryable = false;
728
819
  };
729
820
  function requireText(proposal, key, min = 2) {
730
821
  const value = proposal[key];
@@ -757,6 +848,48 @@ function similarity(left, right) {
757
848
  function sameSemanticText(left, right) {
758
849
  return typeof left === "string" && semanticText(left) === semanticText(right);
759
850
  }
851
+ function assertBehaviorIsObserved(proposal) {
852
+ const behavior = proposal.behavior ?? "";
853
+ const overlap = Math.max(
854
+ similarity(behavior, proposal.alternativeAction ?? ""),
855
+ similarity(behavior, proposal.rule ?? "")
856
+ );
857
+ if (overlap >= 0.68) {
858
+ throw new ProposalError(
859
+ "BEHAVIOR_COUNTERFACTUAL",
860
+ "behavior must describe the observed action, not the recommended alternative"
861
+ );
862
+ }
863
+ }
864
+ function assertAlternativeTargetConsistent(proposal) {
865
+ const target = proposal.alternativeTargetSeat;
866
+ if (target == null) return;
867
+ const action = proposal.alternativeAction ?? "";
868
+ const mentionedTargets = [...action.matchAll(EXPLICIT_TARGET_LANGUAGE)].map((match) => Number(match[1]));
869
+ if (mentionedTargets.length === 0 && NO_TARGET_ALTERNATIVE_LANGUAGE.test(action)) {
870
+ throw new ProposalError(
871
+ "ALTERNATIVE_TARGET_CONTRADICTION",
872
+ "alternativeTargetSeat contradicts an alternative action that selects no target"
873
+ );
874
+ }
875
+ if (mentionedTargets.length > 0 && !mentionedTargets.includes(target)) {
876
+ throw new ProposalError(
877
+ "ALTERNATIVE_TARGET_CONTRADICTION",
878
+ "alternativeTargetSeat contradicts the target explicitly named by alternativeAction"
879
+ );
880
+ }
881
+ }
882
+ function assertLocalOutcomeEvidence(outcomeCount, localOutcomeCount, observed) {
883
+ if (outcomeCount === 0 || localOutcomeCount === 0) {
884
+ throw new ProposalError(
885
+ "LOCAL_OUTCOME_FACT_REQUIRED",
886
+ "Victory, final identity, or other postgame facts cannot be the only outcome evidence"
887
+ );
888
+ }
889
+ if (FINAL_RESULT_LANGUAGE.test(observed.trim())) {
890
+ throw new ProposalError("FINAL_RESULT_NOT_LOCAL", "Final victory or defeat is not a local effect");
891
+ }
892
+ }
760
893
  function factVisibleToActor(visibility, window) {
761
894
  if (visibility === "PUBLIC") return true;
762
895
  if (visibility === "POSTGAME_ONLY") return false;
@@ -896,11 +1029,17 @@ function parseAndValidateProposal(raw, envelope, evidence, activeProfile) {
896
1029
  if (!window) throw new ProposalError("DECISION_WINDOW_NOT_FOUND", "Proposal does not reference a trusted decision window");
897
1030
  const decisionType = requireText(proposal, "decisionType");
898
1031
  if (!window.allowedDecisionTypes.includes(decisionType)) {
899
- throw new ProposalError("DECISION_TYPE_NOT_ALLOWED", "decisionType is not valid for the trusted action window");
1032
+ throw new ProposalError(
1033
+ "DECISION_TYPE_NOT_ALLOWED",
1034
+ `decisionType must be copied from allowedDecisionTypes: ${JSON.stringify(window.allowedDecisionTypes)}`
1035
+ );
900
1036
  }
901
1037
  const alternativeActionType = requireText(proposal, "alternativeActionType");
902
1038
  if (!window.availableActionTypes.includes(alternativeActionType)) {
903
- throw new ProposalError("ALTERNATIVE_ACTION_UNAVAILABLE", "The proposed alternative action was unavailable at that decision point");
1039
+ throw new ProposalError(
1040
+ "ALTERNATIVE_ACTION_UNAVAILABLE",
1041
+ `alternativeActionType must be copied from availableActionTypes: ${JSON.stringify(window.availableActionTypes)}`
1042
+ );
904
1043
  }
905
1044
  if (proposal.source === "SELF" && window.actorSeat !== envelope.game.recipientSeat) {
906
1045
  throw new ProposalError("SELF_ACTOR_MISMATCH", "SELF evidence must anchor the recipient's own action");
@@ -931,6 +1070,8 @@ function parseAndValidateProposal(raw, envelope, evidence, activeProfile) {
931
1070
  if (!anchor || anchor.visibility === "POSTGAME_ONLY") {
932
1071
  throw new ProposalError("ANCHOR_NOT_OBSERVABLE", "The action anchor is missing or postgame-only");
933
1072
  }
1073
+ assertBehaviorIsObserved(proposal);
1074
+ proposal.behavior = anchor.summary;
934
1075
  const known = proposal.knownFactRefs ?? [];
935
1076
  const outcomes = proposal.outcomeFactRefs ?? [];
936
1077
  unique(known, "DUPLICATE_KNOWN_FACT");
@@ -962,19 +1103,15 @@ function parseAndValidateProposal(raw, envelope, evidence, activeProfile) {
962
1103
  localOutcomeCount++;
963
1104
  }
964
1105
  }
965
- if (outcomes.length === 0 || localOutcomeCount === 0) {
966
- throw new ProposalError("LOCAL_OUTCOME_FACT_REQUIRED", "Victory, final identity, or other postgame facts cannot be the only outcome evidence");
967
- }
1106
+ assertLocalOutcomeEvidence(outcomes.length, localOutcomeCount, observed);
968
1107
  const allRefs = /* @__PURE__ */ new Set([...known, ...outcomes]);
969
1108
  if (allRefs.size !== known.length + outcomes.length) {
970
1109
  throw new ProposalError("FACT_ROLE_CONFLICT", "A fact cannot be both known information and an outcome");
971
1110
  }
972
- if (/^(?:因此|所以)?(?:最终)?(?:好人|狼人|狼队|阵营)?(?:获胜|胜利|输了|失败|赢了)[。.!!]?$/i.test(observed.trim())) {
973
- throw new ProposalError("FINAL_RESULT_NOT_LOCAL", "Final victory or defeat is not a local effect");
974
- }
975
1111
  let risk = classifyRisk(proposal, window.allowedDecisionTypes.find((item) => item === decisionType));
976
1112
  if (risk === "execution" && alternativeActionType !== window.actionType) risk = "strategy";
977
1113
  assertAlternativeTarget(proposal, window, risk);
1114
+ assertAlternativeTargetConsistent(proposal);
978
1115
  if (existing) {
979
1116
  assertExistingSemantics(proposal, existing, window, action, envelope.game.players);
980
1117
  if (action === "REFINE") assertRefinement(proposal, existing, risk);
@@ -2533,6 +2670,30 @@ var WerewolfEvolutionService = class {
2533
2670
  }
2534
2671
  return captured;
2535
2672
  }
2673
+ captureInboundClaim(event, ctx = {}) {
2674
+ if (event.isGroup === true) return void 0;
2675
+ const channelId = event.channel || ctx.channelId || "";
2676
+ const senderId = event.senderId ?? ctx.senderId;
2677
+ const conversationId = event.conversationId ?? ctx.conversationId;
2678
+ if (!isTrustedDebriefClaimOrigin(channelId, senderId, conversationId)) return void 0;
2679
+ const trustedSenderId = senderId ?? `${channelId}:human:0`;
2680
+ return this.captureMessage(
2681
+ {
2682
+ from: trustedSenderId,
2683
+ content: event.content,
2684
+ messageId: event.messageId ?? ctx.messageId,
2685
+ sessionKey: event.sessionKey ?? ctx.sessionKey,
2686
+ runId: event.runId ?? ctx.runId
2687
+ },
2688
+ {
2689
+ channelId,
2690
+ accountId: event.accountId ?? ctx.accountId,
2691
+ sessionKey: event.sessionKey ?? ctx.sessionKey,
2692
+ runId: event.runId ?? ctx.runId,
2693
+ conversationId
2694
+ }
2695
+ );
2696
+ }
2536
2697
  isSystemDebriefMessage(event, ctx) {
2537
2698
  const now = Date.now();
2538
2699
  this.cleanupSystemDebriefSessions(now);
@@ -2629,9 +2790,15 @@ var WerewolfEvolutionService = class {
2629
2790
  );
2630
2791
  return bound ?? this.contexts.getBound(ctx.runId, ctx.sessionKey);
2631
2792
  }
2793
+ recordTerminalDiagnostic(runId, sessionKey, terminal) {
2794
+ const bound = this.contexts.getBound(runId, sessionKey);
2795
+ if (!bound || bound.inbound.kind !== "debrief") return void 0;
2796
+ bound.terminalDiagnostic ??= terminal;
2797
+ return bound;
2798
+ }
2632
2799
  finishRun(ctx) {
2633
- if (!ctx.runId) return;
2634
- this.contexts.releaseRun(ctx.runId, ctx.sessionKey);
2800
+ if (!ctx.runId) return void 0;
2801
+ const bound = this.contexts.releaseRun(ctx.runId, ctx.sessionKey);
2635
2802
  this.observedRuns.delete(ctx.runId);
2636
2803
  this.ownerDirectRuns.delete(ctx.runId);
2637
2804
  const systemDebrief = ctx.sessionKey ? this.systemDebriefSessions.get(ctx.sessionKey) : void 0;
@@ -2641,6 +2808,16 @@ var WerewolfEvolutionService = class {
2641
2808
  Date.now() + SYSTEM_DEBRIEF_DELIVERY_GRACE_MS
2642
2809
  );
2643
2810
  }
2811
+ if (!bound) return void 0;
2812
+ let terminalCreated = false;
2813
+ if (bound.inbound.kind === "debrief" && !bound.terminalDiagnostic) {
2814
+ bound.terminalDiagnostic = {
2815
+ status: "abandoned",
2816
+ code: ctx.success === false ? "AGENT_RUN_FAILED" : "COMMIT_NOT_ATTEMPTED"
2817
+ };
2818
+ terminalCreated = true;
2819
+ }
2820
+ return { bound, terminalCreated };
2644
2821
  }
2645
2822
  buildPromptContext(ctx, hooks = {}) {
2646
2823
  const bound = this.contexts.getBound(ctx.runId, ctx.sessionKey);
@@ -2687,18 +2864,25 @@ var WerewolfEvolutionService = class {
2687
2864
  const incidents = incidentReasons(captured.envelope);
2688
2865
  if (incidents.length > 0) {
2689
2866
  let incidentStatus = "already-handled";
2867
+ let incidentCode = "already-handled";
2690
2868
  let incidentError;
2691
2869
  if (!bound.consumed) {
2692
2870
  try {
2693
2871
  const result = this.persistIncident(captured, bound.workspaceDir, incidents, hooks);
2694
2872
  incidentStatus = String(result.status);
2873
+ incidentCode = "outcome" in result ? String(result.outcome) : incidentStatus;
2695
2874
  } catch (error) {
2696
2875
  incidentStatus = "failed";
2876
+ incidentCode = "INCIDENT_PERSIST_FAILED";
2697
2877
  incidentError = error instanceof Error ? error.message : String(error);
2698
2878
  } finally {
2699
2879
  if (!bound.consumed) this.contexts.consume(bound.runId, bound.sessionKey);
2700
2880
  }
2701
2881
  }
2882
+ bound.terminalDiagnostic ??= {
2883
+ status: incidentStatus === "failed" ? "final-rejected" : incidentStatus,
2884
+ code: incidentCode
2885
+ };
2702
2886
  bound.promptContext = [
2703
2887
  "[werewolf-evolution trusted context]",
2704
2888
  `debriefId=${captured.envelope.debriefId}`,
@@ -2732,6 +2916,10 @@ var WerewolfEvolutionService = class {
2732
2916
  }
2733
2917
  if (!stateAvailable) {
2734
2918
  if (!bound.consumed) this.contexts.consume(bound.runId, bound.sessionKey);
2919
+ bound.terminalDiagnostic ??= {
2920
+ status: "final-rejected",
2921
+ code: "WORKSPACE_STATE_UNAVAILABLE"
2922
+ };
2735
2923
  bound.promptContext = [
2736
2924
  "[werewolf-evolution trusted context]",
2737
2925
  `debriefId=${captured.envelope.debriefId}`,
@@ -2761,6 +2949,7 @@ var WerewolfEvolutionService = class {
2761
2949
  `decisionWindows=${JSON.stringify(captured.envelope.decisionWindows)}`,
2762
2950
  `existingTopics=${JSON.stringify(topics)}`,
2763
2951
  `executionTemplates=${JSON.stringify(EXECUTION_PROPOSAL_TEMPLATES)}`,
2952
+ `localOutcomeFactTypes=${JSON.stringify([...LOCAL_OUTCOME_FACT_TYPES])}`,
2764
2953
  `stateAvailable=${stateAvailable}`,
2765
2954
  "The proposal profile must equal activeProfile. The Arena envelope is not the profile authority.",
2766
2955
  "Scan SELF, OBSERVED, and EXEMPLAR, then submit at most one SKIP/SUPPORT/COUNTER/REFINE/NEW proposal.",
@@ -2772,11 +2961,24 @@ var WerewolfEvolutionService = class {
2772
2961
  "- SKIP contains only schemaVersion, action, source, and a concrete skipReason.",
2773
2962
  "- Every non-SKIP proposal must provide profile, decisionWindowId, decisionType, alternativeActionType, anchorFactId, knownFactRefs, outcomeFactRefs, trigger, rule, boundary, behavior, alternativeAction, expectedLocalEffect, observedLocalEffect, falsifier, and alternatives.",
2774
2963
  "- Never send null for an omitted field. Omit the key instead. alternativeTargetSeat may be null only to represent an explicit DAY_VOTE abstention.",
2964
+ "- 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.",
2965
+ "- 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.",
2966
+ "- SELF must use a decisionWindow whose actorSeat equals eligibility.recipientSeat. OBSERVED and EXEMPLAR must use another actor's decisionWindow.",
2967
+ "- 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.",
2968
+ "- outcomeFactRefs must be later than the anchor and include at least one local outcome fact whose type appears in localOutcomeFactTypes.",
2969
+ "- GAME_FINISHED, FINAL_IDENTITY, and GAME_RESULT are never local outcome facts and cannot be the only outcome evidence.",
2970
+ "- behavior must describe only what actually happened at the anchor; never copy rule or alternativeAction into behavior as if it occurred.",
2971
+ "- The plugin stores behavior from the trusted anchor summary; model prose is checked for counterfactual confusion but never becomes the persisted fact source.",
2972
+ "- alternativeAction must describe a counterfactual action that did not happen; never swap behavior and alternativeAction.",
2973
+ "- observedLocalEffect must not contain the final winner or loser; describe only a later local effect backed by outcomeFactRefs.",
2974
+ "- 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.",
2975
+ "- alternatives must contain at least one plausible alternative explanation. falsifier must state a concrete later observation that would disprove the rule.",
2775
2976
  "Execution versus strategy contract:",
2776
2977
  "- 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.",
2777
2978
  "- Strategy proposals must omit executionOperation. CHOOSE_VOTE_TARGET and CHOOSE_ROLE_CLAIM_TIMING are decision types, never executionOperation values.",
2778
- "Call werewolf_debrief_commit exactly once after checking the complete proposal against this contract.",
2779
- "After the tool returns, regardless of accepted or rejected status, return exactly NO_REPLY. Never retry the tool call.",
2979
+ "Call werewolf_debrief_commit after checking the complete proposal against this contract.",
2980
+ "A rejected result with retryable=true means one field/semantic correction is allowed: correct only the reported issue using the same trusted window and call the tool once more. A rejected result with retryable=false is final; never call again.",
2981
+ "After a committed, duplicate, incident, or final rejected result, return exactly NO_REPLY. Never use a generic write tool or retry indefinitely.",
2780
2982
  "Do not return NO_REPLY before werewolf_debrief_commit returns a result.",
2781
2983
  "Never use generic write, edit, patch, shell, or memory-write tools for debrief state."
2782
2984
  ].join("\n");
@@ -2824,6 +3026,15 @@ var WerewolfEvolutionService = class {
2824
3026
  }
2825
3027
  return void 0;
2826
3028
  }
3029
+ inspectDebriefToolCall(toolCallId, ctx) {
3030
+ const bound = this.contexts.inspectAuthorizedToolCall(toolCallId, ctx.sessionKey, ctx.agentId);
3031
+ if (!bound || bound.inbound.kind !== "debrief") return void 0;
3032
+ return {
3033
+ debriefId: bound.inbound.envelope.debriefId,
3034
+ runId: bound.runId,
3035
+ agentId: bound.agentId
3036
+ };
3037
+ }
2827
3038
  persistIncident(captured, workspaceDir, incidents, hooks) {
2828
3039
  if (captured.conflict) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
2829
3040
  const paths = resolveWorkspacePaths(workspaceDir);
@@ -2851,66 +3062,77 @@ var WerewolfEvolutionService = class {
2851
3062
  }, hooks);
2852
3063
  }
2853
3064
  commit(toolCallId, ctx, input, hooks = {}) {
2854
- const bound = this.contexts.consumeToolCall(toolCallId, ctx.sessionKey);
2855
- const workspaceDir = requireToolWorkspace(ctx, bound);
2856
- if (bound.inbound.kind !== "debrief") throw new Error("DEBRIEF_CAPABILITY_REQUIRED");
2857
- const captured = bound.inbound;
2858
- if (captured.conflict) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
2859
- if (input.debriefId !== captured.envelope.debriefId) throw new Error("DEBRIEF_ID_MISMATCH");
2860
- const paths = resolveWorkspacePaths(workspaceDir);
2861
- return runWorkspaceTransaction(paths, () => {
2862
- assertWorkspaceSetupReady(paths, this.version);
2863
- const current = readWorkspaceState(paths);
2864
- const prior = current.ledger.entries.find((entry2) => entry2.debriefId === captured.envelope.debriefId);
2865
- if (prior) {
2866
- if (prior.bodyHash !== captured.bodyHash) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
2867
- return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate", debriefId: captured.envelope.debriefId } };
2868
- }
2869
- if (current.ledger.entries.some((entry2) => entry2.gameId === captured.envelope.game.gameId)) {
2870
- return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate-game", gameId: captured.envelope.game.gameId } };
2871
- }
2872
- if (current.ledger.legacyGameIds.includes(captured.envelope.game.gameId)) {
2873
- return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate-game", gameId: captured.envelope.game.gameId } };
2874
- }
2875
- const next = clone(current);
2876
- const incidents = incidentReasons(captured.envelope);
2877
- let result;
2878
- if (incidents.length > 0) {
2879
- result = applyIncident(next, captured.envelope, captured.bodyHash, incidents);
2880
- } else {
2881
- const activeProfile = activeRuntimeProfile(current, captured.envelope.game.profile);
2882
- const validated = parseAndValidateProposal(
2883
- input.proposal,
2884
- captured.envelope,
2885
- current.evidence,
2886
- activeProfile
2887
- );
2888
- result = applyProposal(
2889
- next,
2890
- captured.envelope,
2891
- captured.bodyHash,
2892
- validated.proposal,
2893
- validated.risk,
2894
- validated.decisionWindow
2895
- );
2896
- }
2897
- next.agentsText = current.agentsText;
2898
- const changes = workspaceChanges(paths, next);
2899
- const changedProfiles = addProfileUpdates(paths, current, next, changes);
2900
- const finalAgentChange = workspaceChanges(paths, next).get(paths.agents);
2901
- if (finalAgentChange === void 0) changes.delete(paths.agents);
2902
- else changes.set(paths.agents, finalAgentChange);
2903
- return {
2904
- changes,
2905
- result: { status: "committed", debriefId: captured.envelope.debriefId, ...result },
2906
- verify: () => {
2907
- verifyWorkspaceDocuments(paths);
2908
- for (const [profile, expected] of changedProfiles) {
2909
- verifyProfileOverride(expected.file, profile, expected.content);
2910
- }
3065
+ const bound = this.contexts.beginProposalToolCall(toolCallId, ctx.sessionKey);
3066
+ let terminal = true;
3067
+ try {
3068
+ const workspaceDir = requireToolWorkspace(ctx, bound);
3069
+ if (bound.inbound.kind !== "debrief") throw new Error("DEBRIEF_CAPABILITY_REQUIRED");
3070
+ const captured = bound.inbound;
3071
+ if (captured.conflict) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
3072
+ if (input.debriefId !== captured.envelope.debriefId) throw new Error("DEBRIEF_ID_MISMATCH");
3073
+ const paths = resolveWorkspacePaths(workspaceDir);
3074
+ return runWorkspaceTransaction(paths, () => {
3075
+ assertWorkspaceSetupReady(paths, this.version);
3076
+ const current = readWorkspaceState(paths);
3077
+ const prior = current.ledger.entries.find((entry2) => entry2.debriefId === captured.envelope.debriefId);
3078
+ if (prior) {
3079
+ if (prior.bodyHash !== captured.bodyHash) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
3080
+ return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate", debriefId: captured.envelope.debriefId } };
2911
3081
  }
2912
- };
2913
- }, hooks);
3082
+ if (current.ledger.entries.some((entry2) => entry2.gameId === captured.envelope.game.gameId)) {
3083
+ return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate-game", gameId: captured.envelope.game.gameId } };
3084
+ }
3085
+ if (current.ledger.legacyGameIds.includes(captured.envelope.game.gameId)) {
3086
+ return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate-game", gameId: captured.envelope.game.gameId } };
3087
+ }
3088
+ const next = clone(current);
3089
+ const incidents = incidentReasons(captured.envelope);
3090
+ let result;
3091
+ if (incidents.length > 0) {
3092
+ result = applyIncident(next, captured.envelope, captured.bodyHash, incidents);
3093
+ } else {
3094
+ const activeProfile = activeRuntimeProfile(current, captured.envelope.game.profile);
3095
+ const validated = parseAndValidateProposal(
3096
+ input.proposal,
3097
+ captured.envelope,
3098
+ current.evidence,
3099
+ activeProfile
3100
+ );
3101
+ result = applyProposal(
3102
+ next,
3103
+ captured.envelope,
3104
+ captured.bodyHash,
3105
+ validated.proposal,
3106
+ validated.risk,
3107
+ validated.decisionWindow
3108
+ );
3109
+ }
3110
+ next.agentsText = current.agentsText;
3111
+ const changes = workspaceChanges(paths, next);
3112
+ const changedProfiles = addProfileUpdates(paths, current, next, changes);
3113
+ const finalAgentChange = workspaceChanges(paths, next).get(paths.agents);
3114
+ if (finalAgentChange === void 0) changes.delete(paths.agents);
3115
+ else changes.set(paths.agents, finalAgentChange);
3116
+ return {
3117
+ changes,
3118
+ result: { status: "committed", debriefId: captured.envelope.debriefId, ...result },
3119
+ verify: () => {
3120
+ verifyWorkspaceDocuments(paths);
3121
+ for (const [profile, expected] of changedProfiles) {
3122
+ verifyProfileOverride(expected.file, profile, expected.content);
3123
+ }
3124
+ }
3125
+ };
3126
+ }, hooks);
3127
+ } catch (error) {
3128
+ if (error instanceof ProposalError && bound.proposalAttempts < 2) {
3129
+ error.retryable = true;
3130
+ terminal = false;
3131
+ }
3132
+ throw error;
3133
+ } finally {
3134
+ if (terminal && !bound.consumed) this.contexts.consume(bound.runId, bound.sessionKey);
3135
+ }
2914
3136
  }
2915
3137
  decideSuggestion(toolCallId, ctx, input, hooks = {}) {
2916
3138
  const bound = this.contexts.consumeToolCall(toolCallId, ctx.sessionKey);
@@ -2949,7 +3171,14 @@ var WerewolfEvolutionService = class {
2949
3171
  }
2950
3172
  };
2951
3173
  function proposalFailure(error) {
2952
- if (error instanceof ProposalError) return { status: "rejected", code: error.code, message: error.message };
3174
+ if (error instanceof ProposalError) {
3175
+ return {
3176
+ status: "rejected",
3177
+ code: error.code,
3178
+ message: error.message,
3179
+ retryable: error.retryable
3180
+ };
3181
+ }
2953
3182
  return { status: "rejected", code: "EVOLUTION_ERROR", message: error instanceof Error ? error.message : String(error) };
2954
3183
  }
2955
3184
 
@@ -2978,8 +3207,12 @@ var proposalParameters = Type.Object({
2978
3207
  description: "Existing lesson id for SUPPORT, COUNTER, or REFINE. Omit for NEW and SKIP; never send null."
2979
3208
  })),
2980
3209
  profile: Type.Optional(Type.String()),
2981
- decisionWindowId: Type.Optional(Type.String()),
2982
- decisionType: Type.Optional(Type.String()),
3210
+ decisionWindowId: Type.Optional(Type.String({
3211
+ description: "Copy one exact decisionWindowId from trusted decisionWindows; never invent one."
3212
+ })),
3213
+ decisionType: Type.Optional(Type.String({
3214
+ description: "Copy one exact value from the selected window's allowedDecisionTypes. This is a decision category, not an actionType."
3215
+ })),
2983
3216
  executionOperation: Type.Optional(Type.Union([
2984
3217
  Type.Literal("REPORT_DECIDED_ROLE_CLAIM"),
2985
3218
  Type.Literal("EXPLAIN_DECIDED_VOTE"),
@@ -2989,8 +3222,12 @@ var proposalParameters = Type.Object({
2989
3222
  ], {
2990
3223
  description: "Exact operation from executionTemplates. Omit for strategy proposals; never invent an operation."
2991
3224
  })),
2992
- alternativeActionType: Type.Optional(Type.String()),
2993
- alternativeTargetSeat: Type.Optional(Type.Union([Type.Integer(), Type.Null()])),
3225
+ alternativeActionType: Type.Optional(Type.String({
3226
+ description: "Copy one exact game action from the selected window's availableActionTypes, for example DAY_SPEAK or DAY_VOTE. Never copy decisionType here."
3227
+ })),
3228
+ alternativeTargetSeat: Type.Optional(Type.Union([Type.Integer(), Type.Null()], {
3229
+ description: "For DAY_VOTE, choose an exact seat from availableTargetSeats or null for explicit abstention. Omit when the selected action has no target."
3230
+ })),
2994
3231
  anchorFactId: Type.Optional(Type.String()),
2995
3232
  knownFactRefs: Type.Optional(Type.Array(Type.String())),
2996
3233
  outcomeFactRefs: Type.Optional(Type.Array(Type.String())),
@@ -3007,7 +3244,7 @@ var proposalParameters = Type.Object({
3007
3244
  alternatives: Type.Optional(Type.Array(Type.String())),
3008
3245
  skipReason: Type.Optional(Type.String())
3009
3246
  }, { additionalProperties: false });
3010
- function createDebriefCommitTool(service, ctx) {
3247
+ function createDebriefCommitTool(service, ctx, onExecution) {
3011
3248
  return {
3012
3249
  name: "werewolf_debrief_commit",
3013
3250
  label: "Commit Werewolf Play Debrief",
@@ -3017,11 +3254,18 @@ function createDebriefCommitTool(service, ctx) {
3017
3254
  proposal: proposalParameters
3018
3255
  }, { additionalProperties: false }),
3019
3256
  async execute(toolCallId, raw) {
3257
+ const diagnostic = service.inspectDebriefToolCall(toolCallId, ctx);
3258
+ let details;
3020
3259
  try {
3021
- return jsonResult(service.commit(toolCallId, ctx, raw));
3260
+ details = service.commit(toolCallId, ctx, raw);
3022
3261
  } catch (error) {
3023
- return jsonResult(proposalFailure(error));
3262
+ details = proposalFailure(error);
3024
3263
  }
3264
+ try {
3265
+ onExecution?.({ toolCallId, diagnostic, details });
3266
+ } catch {
3267
+ }
3268
+ return jsonResult(details);
3025
3269
  }
3026
3270
  };
3027
3271
  }
@@ -3050,10 +3294,51 @@ function createSuggestionDecideTool(service, ctx) {
3050
3294
 
3051
3295
  // index.ts
3052
3296
  function registerWerewolfEvolution(api, service = getSharedWerewolfEvolutionService()) {
3053
- api.registerTool((ctx) => createDebriefCommitTool(service, ctx), { name: "werewolf_debrief_commit" });
3297
+ const loggedCaptures = /* @__PURE__ */ new WeakSet();
3298
+ const loggedBindings = /* @__PURE__ */ new WeakSet();
3299
+ const loggedTerminals = /* @__PURE__ */ new WeakSet();
3300
+ const info = (line) => {
3301
+ try {
3302
+ api.logger?.info?.(line);
3303
+ } catch {
3304
+ }
3305
+ };
3306
+ const field = (value) => String(value ?? "unknown").replace(/\s+/g, "_").slice(0, 200);
3307
+ const logTerminal = (capability, diagnostic, terminal) => {
3308
+ if (loggedTerminals.has(capability)) return;
3309
+ loggedTerminals.add(capability);
3310
+ info(
3311
+ `[werewolf-evolution] DEBRIEF_TERMINAL debriefId=${field(diagnostic.debriefId)} runId=${field(diagnostic.runId)} status=${field(terminal.status)} code=${field(terminal.code)}`
3312
+ );
3313
+ };
3314
+ const logCapture = (captured, sourceHook) => {
3315
+ if (!captured || captured.kind !== "debrief" || loggedCaptures.has(captured)) return;
3316
+ loggedCaptures.add(captured);
3317
+ info(
3318
+ `[werewolf-evolution] DEBRIEF_CAPTURED debriefId=${field(captured.envelope.debriefId)} messageId=${field(captured.messageId)} sessionKey=${field(captured.sessionKey)} sourceHook=${field(sourceHook)}`
3319
+ );
3320
+ };
3321
+ api.registerTool((ctx) => createDebriefCommitTool(service, ctx, ({ diagnostic, details }) => {
3322
+ if (!diagnostic || details === null || typeof details !== "object" || Array.isArray(details)) return;
3323
+ const result = details;
3324
+ if (result.status === "rejected" && result.retryable === true) return;
3325
+ const terminal = {
3326
+ status: result.status === "rejected" ? "final-rejected" : result.status,
3327
+ code: result.code ?? result.outcome ?? result.status
3328
+ };
3329
+ const bound = service.recordTerminalDiagnostic(diagnostic.runId, ctx.sessionKey, {
3330
+ status: field(terminal.status),
3331
+ code: field(terminal.code)
3332
+ });
3333
+ logTerminal(bound ?? diagnostic, diagnostic, terminal);
3334
+ }), { name: "werewolf_debrief_commit" });
3054
3335
  api.registerTool((ctx) => createSuggestionDecideTool(service, ctx), { name: "werewolf_suggestion_decide" });
3336
+ api.on("inbound_claim", (event, ctx) => {
3337
+ logCapture(service.captureInboundClaim(event, ctx), "inbound_claim");
3338
+ });
3055
3339
  api.on("message_received", (event, ctx) => {
3056
3340
  const captured = service.captureMessage(event, ctx);
3341
+ logCapture(captured, "message_received");
3057
3342
  if (!captured && event.content.includes(DEBRIEF_HEADER)) {
3058
3343
  api.logger.warn(
3059
3344
  `[werewolf-evolution] DEBRIEF_CAPTURE_REJECTED runId=${event.runId ?? ctx.runId ?? "unknown"} sessionKey=${event.sessionKey ?? ctx.sessionKey ?? "unknown"}`
@@ -3062,17 +3347,40 @@ function registerWerewolfEvolution(api, service = getSharedWerewolfEvolutionServ
3062
3347
  });
3063
3348
  api.on("before_prompt_build", (event, ctx) => {
3064
3349
  const bound = service.bindPromptRun(event, ctx, api.config);
3350
+ if (bound?.inbound.kind === "debrief" && !loggedBindings.has(bound)) {
3351
+ loggedBindings.add(bound);
3352
+ info(
3353
+ `[werewolf-evolution] DEBRIEF_BOUND debriefId=${field(bound.inbound.envelope.debriefId)} runId=${field(bound.runId)} sessionKey=${field(bound.sessionKey)} agentId=${field(bound.agentId)}`
3354
+ );
3355
+ }
3065
3356
  if (!bound && event.prompt.includes(DEBRIEF_HEADER)) {
3066
3357
  api.logger.warn(
3067
3358
  `[werewolf-evolution] DEBRIEF_BIND_MISS runId=${ctx.runId ?? "unknown"} sessionKey=${ctx.sessionKey ?? "unknown"} agentId=${ctx.agentId ?? "unknown"}`
3068
3359
  );
3069
3360
  }
3070
- return service.buildPromptContext(ctx);
3361
+ const promptContext = service.buildPromptContext(ctx);
3362
+ if (bound?.inbound.kind === "debrief" && bound.terminalDiagnostic) {
3363
+ logTerminal(bound, {
3364
+ debriefId: bound.inbound.envelope.debriefId,
3365
+ runId: bound.runId
3366
+ }, bound.terminalDiagnostic);
3367
+ }
3368
+ return promptContext;
3071
3369
  });
3072
3370
  api.on("before_tool_call", (event, ctx) => service.beforeToolCall(event, ctx));
3073
3371
  api.on("message_sending", (event, ctx) => service.isSystemDebriefMessage(event, ctx) ? { cancel: true } : void 0);
3074
3372
  api.on("agent_end", (event, ctx) => {
3075
- service.finishRun({ runId: event.runId ?? ctx.runId, sessionKey: ctx.sessionKey });
3373
+ const finished = service.finishRun({
3374
+ runId: event.runId ?? ctx.runId,
3375
+ sessionKey: ctx.sessionKey,
3376
+ success: event.success
3377
+ });
3378
+ if (finished?.terminalCreated && finished.bound.inbound.kind === "debrief") {
3379
+ logTerminal(finished.bound, {
3380
+ debriefId: finished.bound.inbound.envelope.debriefId,
3381
+ runId: finished.bound.runId
3382
+ }, finished.bound.terminalDiagnostic);
3383
+ }
3076
3384
  });
3077
3385
  }
3078
3386
  var entry = definePluginEntry({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawtopia/werewolf-evolution",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
4
4
  "description": "Deterministic postgame evolution runtime for the Clawtopia Werewolf Play skill.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",