@clawtopia/werewolf-evolution 0.1.10 → 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
@@ -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,9 @@ 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;
692
764
  var LOCAL_OUTCOME_FACT_TYPES = /* @__PURE__ */ new Set([
693
765
  "WOLF_CHOOSE",
694
766
  "WOLF_SPEECH",
@@ -776,6 +848,48 @@ function similarity(left, right) {
776
848
  function sameSemanticText(left, right) {
777
849
  return typeof left === "string" && semanticText(left) === semanticText(right);
778
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
+ }
779
893
  function factVisibleToActor(visibility, window) {
780
894
  if (visibility === "PUBLIC") return true;
781
895
  if (visibility === "POSTGAME_ONLY") return false;
@@ -956,6 +1070,8 @@ function parseAndValidateProposal(raw, envelope, evidence, activeProfile) {
956
1070
  if (!anchor || anchor.visibility === "POSTGAME_ONLY") {
957
1071
  throw new ProposalError("ANCHOR_NOT_OBSERVABLE", "The action anchor is missing or postgame-only");
958
1072
  }
1073
+ assertBehaviorIsObserved(proposal);
1074
+ proposal.behavior = anchor.summary;
959
1075
  const known = proposal.knownFactRefs ?? [];
960
1076
  const outcomes = proposal.outcomeFactRefs ?? [];
961
1077
  unique(known, "DUPLICATE_KNOWN_FACT");
@@ -987,19 +1103,15 @@ function parseAndValidateProposal(raw, envelope, evidence, activeProfile) {
987
1103
  localOutcomeCount++;
988
1104
  }
989
1105
  }
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
- }
1106
+ assertLocalOutcomeEvidence(outcomes.length, localOutcomeCount, observed);
993
1107
  const allRefs = /* @__PURE__ */ new Set([...known, ...outcomes]);
994
1108
  if (allRefs.size !== known.length + outcomes.length) {
995
1109
  throw new ProposalError("FACT_ROLE_CONFLICT", "A fact cannot be both known information and an outcome");
996
1110
  }
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
1111
  let risk = classifyRisk(proposal, window.allowedDecisionTypes.find((item) => item === decisionType));
1001
1112
  if (risk === "execution" && alternativeActionType !== window.actionType) risk = "strategy";
1002
1113
  assertAlternativeTarget(proposal, window, risk);
1114
+ assertAlternativeTargetConsistent(proposal);
1003
1115
  if (existing) {
1004
1116
  assertExistingSemantics(proposal, existing, window, action, envelope.game.players);
1005
1117
  if (action === "REFINE") assertRefinement(proposal, existing, risk);
@@ -2558,6 +2670,30 @@ var WerewolfEvolutionService = class {
2558
2670
  }
2559
2671
  return captured;
2560
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
+ }
2561
2697
  isSystemDebriefMessage(event, ctx) {
2562
2698
  const now = Date.now();
2563
2699
  this.cleanupSystemDebriefSessions(now);
@@ -2654,9 +2790,15 @@ var WerewolfEvolutionService = class {
2654
2790
  );
2655
2791
  return bound ?? this.contexts.getBound(ctx.runId, ctx.sessionKey);
2656
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
+ }
2657
2799
  finishRun(ctx) {
2658
- if (!ctx.runId) return;
2659
- this.contexts.releaseRun(ctx.runId, ctx.sessionKey);
2800
+ if (!ctx.runId) return void 0;
2801
+ const bound = this.contexts.releaseRun(ctx.runId, ctx.sessionKey);
2660
2802
  this.observedRuns.delete(ctx.runId);
2661
2803
  this.ownerDirectRuns.delete(ctx.runId);
2662
2804
  const systemDebrief = ctx.sessionKey ? this.systemDebriefSessions.get(ctx.sessionKey) : void 0;
@@ -2666,6 +2808,16 @@ var WerewolfEvolutionService = class {
2666
2808
  Date.now() + SYSTEM_DEBRIEF_DELIVERY_GRACE_MS
2667
2809
  );
2668
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 };
2669
2821
  }
2670
2822
  buildPromptContext(ctx, hooks = {}) {
2671
2823
  const bound = this.contexts.getBound(ctx.runId, ctx.sessionKey);
@@ -2712,18 +2864,25 @@ var WerewolfEvolutionService = class {
2712
2864
  const incidents = incidentReasons(captured.envelope);
2713
2865
  if (incidents.length > 0) {
2714
2866
  let incidentStatus = "already-handled";
2867
+ let incidentCode = "already-handled";
2715
2868
  let incidentError;
2716
2869
  if (!bound.consumed) {
2717
2870
  try {
2718
2871
  const result = this.persistIncident(captured, bound.workspaceDir, incidents, hooks);
2719
2872
  incidentStatus = String(result.status);
2873
+ incidentCode = "outcome" in result ? String(result.outcome) : incidentStatus;
2720
2874
  } catch (error) {
2721
2875
  incidentStatus = "failed";
2876
+ incidentCode = "INCIDENT_PERSIST_FAILED";
2722
2877
  incidentError = error instanceof Error ? error.message : String(error);
2723
2878
  } finally {
2724
2879
  if (!bound.consumed) this.contexts.consume(bound.runId, bound.sessionKey);
2725
2880
  }
2726
2881
  }
2882
+ bound.terminalDiagnostic ??= {
2883
+ status: incidentStatus === "failed" ? "final-rejected" : incidentStatus,
2884
+ code: incidentCode
2885
+ };
2727
2886
  bound.promptContext = [
2728
2887
  "[werewolf-evolution trusted context]",
2729
2888
  `debriefId=${captured.envelope.debriefId}`,
@@ -2757,6 +2916,10 @@ var WerewolfEvolutionService = class {
2757
2916
  }
2758
2917
  if (!stateAvailable) {
2759
2918
  if (!bound.consumed) this.contexts.consume(bound.runId, bound.sessionKey);
2919
+ bound.terminalDiagnostic ??= {
2920
+ status: "final-rejected",
2921
+ code: "WORKSPACE_STATE_UNAVAILABLE"
2922
+ };
2760
2923
  bound.promptContext = [
2761
2924
  "[werewolf-evolution trusted context]",
2762
2925
  `debriefId=${captured.envelope.debriefId}`,
@@ -2786,6 +2949,7 @@ var WerewolfEvolutionService = class {
2786
2949
  `decisionWindows=${JSON.stringify(captured.envelope.decisionWindows)}`,
2787
2950
  `existingTopics=${JSON.stringify(topics)}`,
2788
2951
  `executionTemplates=${JSON.stringify(EXECUTION_PROPOSAL_TEMPLATES)}`,
2952
+ `localOutcomeFactTypes=${JSON.stringify([...LOCAL_OUTCOME_FACT_TYPES])}`,
2789
2953
  `stateAvailable=${stateAvailable}`,
2790
2954
  "The proposal profile must equal activeProfile. The Arena envelope is not the profile authority.",
2791
2955
  "Scan SELF, OBSERVED, and EXEMPLAR, then submit at most one SKIP/SUPPORT/COUNTER/REFINE/NEW proposal.",
@@ -2799,6 +2963,16 @@ var WerewolfEvolutionService = class {
2799
2963
  "- Never send null for an omitted field. Omit the key instead. alternativeTargetSeat may be null only to represent an explicit DAY_VOTE abstention.",
2800
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.",
2801
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.",
2802
2976
  "Execution versus strategy contract:",
2803
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.",
2804
2978
  "- Strategy proposals must omit executionOperation. CHOOSE_VOTE_TARGET and CHOOSE_ROLE_CLAIM_TIMING are decision types, never executionOperation values.",
@@ -2852,6 +3026,15 @@ var WerewolfEvolutionService = class {
2852
3026
  }
2853
3027
  return void 0;
2854
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
+ }
2855
3038
  persistIncident(captured, workspaceDir, incidents, hooks) {
2856
3039
  if (captured.conflict) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
2857
3040
  const paths = resolveWorkspacePaths(workspaceDir);
@@ -3061,7 +3244,7 @@ var proposalParameters = Type.Object({
3061
3244
  alternatives: Type.Optional(Type.Array(Type.String())),
3062
3245
  skipReason: Type.Optional(Type.String())
3063
3246
  }, { additionalProperties: false });
3064
- function createDebriefCommitTool(service, ctx) {
3247
+ function createDebriefCommitTool(service, ctx, onExecution) {
3065
3248
  return {
3066
3249
  name: "werewolf_debrief_commit",
3067
3250
  label: "Commit Werewolf Play Debrief",
@@ -3071,11 +3254,18 @@ function createDebriefCommitTool(service, ctx) {
3071
3254
  proposal: proposalParameters
3072
3255
  }, { additionalProperties: false }),
3073
3256
  async execute(toolCallId, raw) {
3257
+ const diagnostic = service.inspectDebriefToolCall(toolCallId, ctx);
3258
+ let details;
3074
3259
  try {
3075
- return jsonResult(service.commit(toolCallId, ctx, raw));
3260
+ details = service.commit(toolCallId, ctx, raw);
3076
3261
  } catch (error) {
3077
- return jsonResult(proposalFailure(error));
3262
+ details = proposalFailure(error);
3263
+ }
3264
+ try {
3265
+ onExecution?.({ toolCallId, diagnostic, details });
3266
+ } catch {
3078
3267
  }
3268
+ return jsonResult(details);
3079
3269
  }
3080
3270
  };
3081
3271
  }
@@ -3104,10 +3294,51 @@ function createSuggestionDecideTool(service, ctx) {
3104
3294
 
3105
3295
  // index.ts
3106
3296
  function registerWerewolfEvolution(api, service = getSharedWerewolfEvolutionService()) {
3107
- 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" });
3108
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
+ });
3109
3339
  api.on("message_received", (event, ctx) => {
3110
3340
  const captured = service.captureMessage(event, ctx);
3341
+ logCapture(captured, "message_received");
3111
3342
  if (!captured && event.content.includes(DEBRIEF_HEADER)) {
3112
3343
  api.logger.warn(
3113
3344
  `[werewolf-evolution] DEBRIEF_CAPTURE_REJECTED runId=${event.runId ?? ctx.runId ?? "unknown"} sessionKey=${event.sessionKey ?? ctx.sessionKey ?? "unknown"}`
@@ -3116,17 +3347,40 @@ function registerWerewolfEvolution(api, service = getSharedWerewolfEvolutionServ
3116
3347
  });
3117
3348
  api.on("before_prompt_build", (event, ctx) => {
3118
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
+ }
3119
3356
  if (!bound && event.prompt.includes(DEBRIEF_HEADER)) {
3120
3357
  api.logger.warn(
3121
3358
  `[werewolf-evolution] DEBRIEF_BIND_MISS runId=${ctx.runId ?? "unknown"} sessionKey=${ctx.sessionKey ?? "unknown"} agentId=${ctx.agentId ?? "unknown"}`
3122
3359
  );
3123
3360
  }
3124
- 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;
3125
3369
  });
3126
3370
  api.on("before_tool_call", (event, ctx) => service.beforeToolCall(event, ctx));
3127
3371
  api.on("message_sending", (event, ctx) => service.isSystemDebriefMessage(event, ctx) ? { cancel: true } : void 0);
3128
3372
  api.on("agent_end", (event, ctx) => {
3129
- 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
+ }
3130
3384
  });
3131
3385
  }
3132
3386
  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.11",
4
4
  "description": "Deterministic postgame evolution runtime for the Clawtopia Werewolf Play skill.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",