@clawtopia/werewolf-evolution 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,36 +1,325 @@
1
- import {
2
- EXECUTION_PROPOSAL_TEMPLATES,
3
- ProposalError,
4
- assertWorkspaceOwner,
5
- assertWorkspaceSetupReady,
6
- customProfilePath,
7
- getWerewolfEvolutionVersion,
8
- inspectRuntimeProjection,
9
- installedProfilePath,
10
- isProtectedToolWrite,
11
- isTrustedDebriefOrigin,
12
- isUnknownEligibilityValue,
13
- isWorkspaceOwner,
14
- parseAndValidateProposal,
15
- parseDebriefBody,
16
- profileOverridePath,
17
- projectProfilePlaybook,
18
- readWorkspaceState,
19
- renderSuggestions,
20
- resolveWorkspacePaths,
21
- runWorkspaceRead,
22
- runWorkspaceTransaction,
23
- sha256,
24
- verifyWorkspaceDocuments,
25
- workspaceChanges
26
- } from "./chunk-UZXHRLA6.js";
27
-
28
1
  // index.ts
29
2
  import {
30
3
  definePluginEntry,
31
4
  emptyPluginConfigSchema
32
5
  } from "openclaw/plugin-sdk/core";
33
6
 
7
+ // src/envelope.ts
8
+ import { createHash } from "crypto";
9
+ import { z } from "zod";
10
+
11
+ // src/types.ts
12
+ var DEBRIEF_HEADER = "[WEREWOLF_DEBRIEF v2]";
13
+ var DEBRIEF_POLICY_VERSION = "werewolf-debrief-v3";
14
+ var ENVELOPE_START = "== DEBRIEF_ENVELOPE_JSON ==";
15
+ var ENVELOPE_END = "== END_DEBRIEF_ENVELOPE_JSON ==";
16
+
17
+ // src/envelope.ts
18
+ var MAX_DEBRIEF_BODY_BYTES = 64 * 1024;
19
+ var SAFE_ID = /^[A-Za-z0-9:_-]{1,200}$/;
20
+ var SAFE_PROFILE = /^[a-z0-9][a-z0-9_-]{0,63}$/;
21
+ var SAFE_UPPER_TOKEN = /^[A-Z][A-Z0-9_]{1,79}$/;
22
+ var VISIBILITY = /^(?:PUBLIC|WOLF_TEAM|POSTGAME_ONLY|SEAT_[1-9][0-9]*_ONLY)$/;
23
+ var UNKNOWN_VALUE = /^(?:\?|UNKNOWN|UNAVAILABLE|UNDETERMINED)$/i;
24
+ var TERMINAL_FACT_TYPES = /* @__PURE__ */ new Set(["GAME_FINISHED", "FINAL_IDENTITY", "GAME_RESULT"]);
25
+ var FACT_TYPES = [
26
+ "INIT_COMPLETED",
27
+ "NIGHT_BEGIN_WOLF",
28
+ "WOLF_CHOOSE",
29
+ "WOLF_SPEECH",
30
+ "WOLF_TARGET_CONFIRMED",
31
+ "WOLF_TARGET_RANDOM",
32
+ "WOLF_TARGET_NONE",
33
+ "WOLF_TARGET_CONFLICT_RETRY",
34
+ "WOLF_KILL_FAILED",
35
+ "WITCH_PROMPT_INFO",
36
+ "WITCH_SAVE",
37
+ "WITCH_SKIP_SAVE",
38
+ "WITCH_POISON",
39
+ "WITCH_SKIP_POISON",
40
+ "WITCH_INFO",
41
+ "WITCH_PASS",
42
+ "SEER_CHECK",
43
+ "SEER_SKIP_CHECK",
44
+ "SEER_RESULT",
45
+ "NIGHT_RESOLVED",
46
+ "DAWN_ANNOUNCE",
47
+ "PRIVATE_NIGHT_HUNTER_START",
48
+ "PRIVATE_NIGHT_HUNTER_SHOOT",
49
+ "PRIVATE_NIGHT_HUNTER_PASS",
50
+ "HUNTER_SKILL_START",
51
+ "HUNTER_SHOOT",
52
+ "HUNTER_PASS",
53
+ "DAY_SPEECH_START",
54
+ "DAY_SPEAK",
55
+ "LAST_WORD_START",
56
+ "LAST_WORD",
57
+ "DAY_VOTE_START",
58
+ "DAY_VOTE_SUBMIT",
59
+ "DAY_VOTE_PRIVATE_VOTE_REASON",
60
+ "DAY_VOTE_COUNT",
61
+ "DAY_VOTE_TIE",
62
+ "DAY_VOTE_ELIMINATED",
63
+ "DAY_REVOTE_BEGIN",
64
+ "DAY_REVOTE_VOTE_START",
65
+ "DAY_REVOTE_SUBMIT",
66
+ "DAY_REVOTE_COUNT",
67
+ "DAY_REVOTE_ELIMINATED",
68
+ "DAY_REVOTE_TIE",
69
+ "DAY_PEACE",
70
+ "DAY_RESOLVED",
71
+ "GAME_FINISHED",
72
+ "NARRATOR",
73
+ "FINAL_IDENTITY",
74
+ "GAME_RESULT"
75
+ ];
76
+ var DECISION_ACTION_RULES = {
77
+ WOLF_KILL: { anchorTypes: ["WOLF_CHOOSE"], phases: ["WOLF_TURN"], roles: ["WOLF"] },
78
+ WITCH_SAVE: { anchorTypes: ["WITCH_SAVE"], phases: ["WITCH_TURN"], roles: ["WITCH"] },
79
+ WITCH_SKIP_SAVE: { anchorTypes: ["WITCH_SKIP_SAVE", "WITCH_PASS"], phases: ["WITCH_TURN"], roles: ["WITCH"] },
80
+ WITCH_POISON: { anchorTypes: ["WITCH_POISON"], phases: ["WITCH_TURN"], roles: ["WITCH"] },
81
+ WITCH_SKIP_POISON: { anchorTypes: ["WITCH_SKIP_POISON", "WITCH_PASS"], phases: ["WITCH_TURN"], roles: ["WITCH"] },
82
+ WITCH_PASS: { anchorTypes: ["WITCH_PASS"], phases: ["WITCH_TURN"], roles: ["WITCH"] },
83
+ SEER_CHECK: { anchorTypes: ["SEER_CHECK"], phases: ["SEER_TURN"], roles: ["SEER"] },
84
+ SEER_SKIP_CHECK: { anchorTypes: ["SEER_SKIP_CHECK"], phases: ["SEER_TURN"], roles: ["SEER"] },
85
+ DAY_SPEAK: { anchorTypes: ["DAY_SPEAK"], phases: ["SPEECH", "REVOTE_SPEECH"] },
86
+ LAST_WORD: { anchorTypes: ["LAST_WORD"], phases: ["LAST_WORD"] },
87
+ DAY_VOTE: { anchorTypes: ["DAY_VOTE_SUBMIT", "DAY_REVOTE_SUBMIT"], phases: ["VOTE", "REVOTE_VOTE"] },
88
+ HUNTER_SHOOT: {
89
+ anchorTypes: ["HUNTER_SHOOT", "PRIVATE_NIGHT_HUNTER_SHOOT"],
90
+ phases: ["HUNTER_TRIGGER", "NIGHT_HUNTER_SKILL"],
91
+ roles: ["HUNTER"]
92
+ },
93
+ HUNTER_PASS: {
94
+ anchorTypes: ["HUNTER_PASS", "PRIVATE_NIGHT_HUNTER_PASS"],
95
+ phases: ["HUNTER_TRIGGER", "NIGHT_HUNTER_SKILL"],
96
+ roles: ["HUNTER"]
97
+ }
98
+ };
99
+ var factSchema = z.object({
100
+ factId: z.string().regex(SAFE_ID),
101
+ anchor: z.string().regex(/^h:[0-9]+$/),
102
+ type: z.enum(FACT_TYPES),
103
+ visibility: z.string().regex(VISIBILITY),
104
+ availableAt: z.object({
105
+ historyIndex: z.number().int().nonnegative(),
106
+ round: z.number().int().nonnegative().optional(),
107
+ phase: z.string().regex(SAFE_UPPER_TOKEN).optional()
108
+ }).strict(),
109
+ actorSeat: z.number().int().positive().nullable().optional(),
110
+ targetSeat: z.number().int().positive().nullable().optional(),
111
+ summary: z.string().min(1).max(500)
112
+ }).strict();
113
+ var decisionWindowSchema = z.object({
114
+ decisionWindowId: z.string().regex(SAFE_ID),
115
+ anchorFactId: z.string().regex(SAFE_ID),
116
+ actorSeat: z.number().int().positive(),
117
+ actorRole: z.string().regex(SAFE_UPPER_TOKEN),
118
+ phase: z.string().regex(SAFE_UPPER_TOKEN),
119
+ actionType: z.string().regex(SAFE_UPPER_TOKEN),
120
+ allowedDecisionTypes: z.array(z.string().regex(SAFE_UPPER_TOKEN)).min(1).max(32),
121
+ availableActionTypes: z.array(z.string().regex(SAFE_UPPER_TOKEN)).min(1).max(32),
122
+ availableTargetSeats: z.array(z.number().int().positive().max(32)).max(32).optional()
123
+ }).strict();
124
+ var envelopeSchema = z.object({
125
+ schemaVersion: z.literal(2),
126
+ debriefId: z.string().regex(SAFE_ID),
127
+ game: z.object({
128
+ gameId: z.union([z.string().regex(/^[0-9]{1,30}$/), z.number().int().nonnegative()]).transform(String),
129
+ recipientAgentId: z.union([z.string().regex(/^[0-9]{1,30}$/), z.number().int().nonnegative()]).transform(String),
130
+ recipientSeat: z.number().int().positive().max(32),
131
+ reviewDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
132
+ profile: z.string().regex(SAFE_PROFILE).optional(),
133
+ normalEnd: z.boolean(),
134
+ role: z.enum(["WOLF", "WITCH", "SEER", "HUNTER", "VILLAGER", "UNKNOWN", "UNAVAILABLE", "?"]),
135
+ team: z.enum(["WOLF", "GOOD", "UNKNOWN", "UNAVAILABLE", "?"]),
136
+ finalState: z.enum(["ALIVE", "DEAD", "UNKNOWN", "UNAVAILABLE", "?"]),
137
+ result: z.enum([
138
+ "GOOD_WIN",
139
+ "WOLF_WIN",
140
+ "DRAW",
141
+ "ABNORMAL_END",
142
+ "UNKNOWN",
143
+ "UNAVAILABLE",
144
+ "UNDETERMINED",
145
+ "?"
146
+ ]),
147
+ players: z.number().int().positive().max(32),
148
+ systemHealthGate: z.enum(["PASS", "SKIP_REQUIRED"]),
149
+ timelineComplete: z.boolean(),
150
+ voteConsistency: z.enum(["CONSISTENT", "INCONSISTENT", "NOT_APPLICABLE"])
151
+ }).strict(),
152
+ facts: z.array(factSchema).max(512),
153
+ decisionWindows: z.array(decisionWindowSchema).max(256)
154
+ }).strict();
155
+ var EnvelopeError = class extends Error {
156
+ constructor(code, message) {
157
+ super(message);
158
+ this.code = code;
159
+ this.name = "EnvelopeError";
160
+ }
161
+ code;
162
+ };
163
+ function sha256(value) {
164
+ return createHash("sha256").update(value).digest("hex");
165
+ }
166
+ function expectedDebriefId(envelope) {
167
+ return `werewolf:${envelope.game.gameId}:agent:${envelope.game.recipientAgentId}:v2`;
168
+ }
169
+ function exactLine(content, line) {
170
+ const escaped = line.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
171
+ const matches = [...content.matchAll(new RegExp(`^${escaped}\\r?$`, "gm"))];
172
+ if (matches.length !== 1) {
173
+ throw new EnvelopeError("CONTROL_LINE_AMBIGUOUS", `Expected exactly one control line: ${line}`);
174
+ }
175
+ return matches[0];
176
+ }
177
+ function assertFactVisibility(fact, envelope) {
178
+ if ((fact.actorSeat ?? 1) > envelope.game.players || (fact.targetSeat ?? 1) > envelope.game.players) {
179
+ throw new EnvelopeError("FACT_SEAT_OUT_OF_RANGE", `Fact seat is outside this game: ${fact.factId}`);
180
+ }
181
+ if (fact.visibility === "WOLF_TEAM" && envelope.game.role.toUpperCase() !== "WOLF") {
182
+ throw new EnvelopeError("WOLF_FACT_FOR_NON_WOLF", `Wolf-team fact is not visible to this recipient: ${fact.factId}`);
183
+ }
184
+ const seatOnly = /^SEAT_([1-9][0-9]*)_ONLY$/.exec(fact.visibility);
185
+ if (seatOnly && Number(seatOnly[1]) !== envelope.game.recipientSeat) {
186
+ throw new EnvelopeError("OTHER_SEAT_PRIVATE_FACT", `Private fact belongs to another seat: ${fact.factId}`);
187
+ }
188
+ if (TERMINAL_FACT_TYPES.has(fact.type) && fact.visibility !== "POSTGAME_ONLY") {
189
+ throw new EnvelopeError("POSTGAME_FACT_VISIBILITY", `Terminal facts must be postgame-only: ${fact.factId}`);
190
+ }
191
+ }
192
+ function validateEnvelopeRelations(envelope) {
193
+ if (envelope.game.recipientSeat > envelope.game.players) {
194
+ throw new EnvelopeError("RECIPIENT_SEAT_OUT_OF_RANGE", "Recipient seat is outside this game");
195
+ }
196
+ if (envelope.debriefId !== expectedDebriefId(envelope)) {
197
+ throw new EnvelopeError("DEBRIEF_ID_MISMATCH", "debriefId does not match game and recipient");
198
+ }
199
+ if (envelope.game.result === "ABNORMAL_END" && envelope.game.normalEnd) {
200
+ throw new EnvelopeError("NORMAL_END_RESULT_CONFLICT", "ABNORMAL_END cannot be marked as a normal end");
201
+ }
202
+ const factIds = /* @__PURE__ */ new Set();
203
+ const historyIndexes = /* @__PURE__ */ new Set();
204
+ for (const fact of envelope.facts) {
205
+ if (factIds.has(fact.factId)) throw new EnvelopeError("DUPLICATE_FACT_ID", `Duplicate factId: ${fact.factId}`);
206
+ if (historyIndexes.has(fact.availableAt.historyIndex)) {
207
+ throw new EnvelopeError("DUPLICATE_HISTORY_INDEX", `Duplicate history index: ${fact.availableAt.historyIndex}`);
208
+ }
209
+ const expectedId = `${envelope.debriefId}:h:${fact.availableAt.historyIndex}`;
210
+ if (fact.factId !== expectedId || fact.anchor !== `h:${fact.availableAt.historyIndex}`) {
211
+ throw new EnvelopeError("FACT_ANCHOR_MISMATCH", `Fact ID or anchor is not deterministic: ${fact.factId}`);
212
+ }
213
+ assertFactVisibility(fact, envelope);
214
+ factIds.add(fact.factId);
215
+ historyIndexes.add(fact.availableAt.historyIndex);
216
+ }
217
+ const windowIds = /* @__PURE__ */ new Set();
218
+ for (let index = 0; index < envelope.decisionWindows.length; index++) {
219
+ const window = envelope.decisionWindows[index];
220
+ if (windowIds.has(window.decisionWindowId)) {
221
+ throw new EnvelopeError("DUPLICATE_DECISION_WINDOW", `Duplicate decision window: ${window.decisionWindowId}`);
222
+ }
223
+ if (window.decisionWindowId !== `${envelope.debriefId}:d:${index}`) {
224
+ throw new EnvelopeError("DECISION_WINDOW_ID_MISMATCH", `Decision window ID is not deterministic: ${window.decisionWindowId}`);
225
+ }
226
+ if (window.availableTargetSeats && new Set(window.availableTargetSeats).size !== window.availableTargetSeats.length) {
227
+ throw new EnvelopeError("DUPLICATE_AVAILABLE_TARGET", `Duplicate target in ${window.decisionWindowId}`);
228
+ }
229
+ const anchor = envelope.facts.find((fact) => fact.factId === window.anchorFactId);
230
+ if (!anchor || anchor.visibility === "POSTGAME_ONLY") {
231
+ throw new EnvelopeError("DECISION_WINDOW_ANCHOR_INVALID", `Decision window has no observable action anchor: ${window.decisionWindowId}`);
232
+ }
233
+ if (anchor.actorSeat != null && anchor.actorSeat !== window.actorSeat) {
234
+ throw new EnvelopeError("DECISION_WINDOW_ACTOR_MISMATCH", `Decision window actor does not match its anchor: ${window.decisionWindowId}`);
235
+ }
236
+ const actionRule = DECISION_ACTION_RULES[window.actionType];
237
+ if (!actionRule) {
238
+ throw new EnvelopeError("DECISION_ACTION_UNSUPPORTED", `Unsupported decision action: ${window.actionType}`);
239
+ }
240
+ if (!actionRule.anchorTypes.includes(anchor.type)) {
241
+ throw new EnvelopeError("DECISION_ACTION_ANCHOR_MISMATCH", `Decision action does not match its anchor event: ${window.decisionWindowId}`);
242
+ }
243
+ if (anchor.availableAt.phase !== window.phase || !actionRule.phases.includes(window.phase)) {
244
+ throw new EnvelopeError("DECISION_PHASE_MISMATCH", `Decision phase does not match its action or anchor: ${window.decisionWindowId}`);
245
+ }
246
+ if (actionRule.roles && !actionRule.roles.includes(window.actorRole)) {
247
+ throw new EnvelopeError("DECISION_ACTION_ROLE_MISMATCH", `Role cannot perform this decision action: ${window.decisionWindowId}`);
248
+ }
249
+ if (window.actorSeat > envelope.game.players) {
250
+ throw new EnvelopeError("DECISION_WINDOW_SEAT_OUT_OF_RANGE", `Decision window seat is outside this game: ${window.decisionWindowId}`);
251
+ }
252
+ if (!window.availableActionTypes.includes(window.actionType)) {
253
+ throw new EnvelopeError("ACTION_NOT_AVAILABLE", `Recorded action was not available in its decision window: ${window.decisionWindowId}`);
254
+ }
255
+ if (window.availableTargetSeats && anchor.targetSeat != null && !window.availableTargetSeats.includes(anchor.targetSeat)) {
256
+ throw new EnvelopeError(
257
+ "ANCHOR_TARGET_UNAVAILABLE",
258
+ `Anchor target is absent from trusted targets: ${window.decisionWindowId}`
259
+ );
260
+ }
261
+ if (UNKNOWN_VALUE.test(window.actorRole)) {
262
+ throw new EnvelopeError("DECISION_ROLE_UNKNOWN", `Decision window actor role is unknown: ${window.decisionWindowId}`);
263
+ }
264
+ windowIds.add(window.decisionWindowId);
265
+ }
266
+ if (envelope.game.timelineComplete) {
267
+ const finished = envelope.facts.filter((fact) => fact.type === "GAME_FINISHED");
268
+ const resultFacts = envelope.facts.filter((fact) => fact.type === "GAME_RESULT");
269
+ if (finished.length !== 1 || resultFacts.length !== 1 || resultFacts[0].summary !== `result=${envelope.game.result}`) {
270
+ throw new EnvelopeError(
271
+ "TERMINAL_FACTS_INCONSISTENT",
272
+ "A complete timeline requires one matching GAME_FINISHED and GAME_RESULT fact"
273
+ );
274
+ }
275
+ }
276
+ }
277
+ function parseDebriefBody(content) {
278
+ if (Buffer.byteLength(content, "utf8") > MAX_DEBRIEF_BODY_BYTES) {
279
+ throw new EnvelopeError("BODY_TOO_LARGE", "Debrief body exceeds the plugin limit");
280
+ }
281
+ const header = exactLine(content, DEBRIEF_HEADER);
282
+ const policy = exactLine(content, `policyVersion: ${DEBRIEF_POLICY_VERSION}`);
283
+ const schema = exactLine(content, "schemaVersion: 2");
284
+ const declaredId = [...content.matchAll(/^debriefId:\s*([^\s]+)\r?$/gm)];
285
+ if (declaredId.length !== 1) {
286
+ throw new EnvelopeError("DEBRIEF_ID_LINE", "Expected exactly one debriefId control line");
287
+ }
288
+ const start = exactLine(content, ENVELOPE_START);
289
+ const end = exactLine(content, ENVELOPE_END);
290
+ const positions = [header.index, policy.index, schema.index, declaredId[0].index, start.index, end.index];
291
+ if (!positions.every((value, index) => index === 0 || value > positions[index - 1])) {
292
+ throw new EnvelopeError("CONTROL_LINE_ORDER", "Debrief control lines are out of order");
293
+ }
294
+ const rawJson = content.slice(start.index + start[0].length, end.index).trim();
295
+ if (!rawJson || Buffer.byteLength(rawJson, "utf8") > MAX_DEBRIEF_BODY_BYTES) {
296
+ throw new EnvelopeError("ENVELOPE_EMPTY", "Debrief envelope is empty or oversized");
297
+ }
298
+ let raw;
299
+ try {
300
+ raw = JSON.parse(rawJson);
301
+ } catch (error) {
302
+ throw new EnvelopeError("ENVELOPE_JSON", `Invalid debrief envelope JSON: ${String(error)}`);
303
+ }
304
+ const parsed = envelopeSchema.safeParse(raw);
305
+ if (!parsed.success) {
306
+ throw new EnvelopeError("ENVELOPE_SCHEMA", parsed.error.issues.map((issue) => issue.message).join("; "));
307
+ }
308
+ const envelope = parsed.data;
309
+ if (declaredId[0][1] !== envelope.debriefId) {
310
+ throw new EnvelopeError("DECLARED_ID_MISMATCH", "Header debriefId does not match the managed envelope");
311
+ }
312
+ validateEnvelopeRelations(envelope);
313
+ return { envelope, bodyHash: sha256(content) };
314
+ }
315
+ function isTrustedDebriefOrigin(channelId, from) {
316
+ if (channelId !== "clawtopia" && channelId !== "coolclaw") return false;
317
+ return from === `${channelId}:human:0`;
318
+ }
319
+ function isUnknownEligibilityValue(value) {
320
+ return UNKNOWN_VALUE.test(value.trim());
321
+ }
322
+
34
323
  // src/context-store.ts
35
324
  var CAPTURE_TTL_MS = 10 * 60 * 1e3;
36
325
  var MAX_CAPTURES = 256;
@@ -128,6 +417,12 @@ var EvolutionContextStore = class {
128
417
  this.inboundByRun.set(runId, command);
129
418
  return command;
130
419
  }
420
+ getPending(runId, sessionKey, now = Date.now()) {
421
+ this.cleanup(now);
422
+ if (!runId || !sessionKey) return void 0;
423
+ const inbound = this.inboundByRun.get(runId);
424
+ return inbound?.sessionKey === sessionKey && now - inbound.capturedAt <= CAPTURE_TTL_MS ? inbound : void 0;
425
+ }
131
426
  bindAgentRun(event, ctx, binding, now = Date.now(), explicitOwnerAuthorized = false) {
132
427
  this.cleanup(now);
133
428
  if (!ctx.runId || !ctx.sessionKey || !ctx.agentId || !ctx.workspaceDir) return void 0;
@@ -209,16 +504,1020 @@ var EvolutionContextStore = class {
209
504
  }
210
505
  };
211
506
 
507
+ // src/documents.ts
508
+ import { existsSync, lstatSync as lstatSync2, readFileSync } from "fs";
509
+ import { z as z3 } from "zod";
510
+
511
+ // src/proposal.ts
512
+ import { z as z2 } from "zod";
513
+ var SAFE_TOPIC = /^L-[a-z0-9][a-z0-9_-]{0,63}-\d{3,6}$/;
514
+ var SAFE_PROFILE2 = /^[a-z0-9][a-z0-9_-]{0,63}$/;
515
+ var SAFE_TOKEN = /^[A-Z][A-Z0-9_]{1,79}$/;
516
+ var proposalSchema = z2.object({
517
+ schemaVersion: z2.literal(1),
518
+ action: z2.enum(["SKIP", "SUPPORT", "COUNTER", "REFINE", "NEW"]),
519
+ source: z2.enum(["SELF", "OBSERVED", "EXEMPLAR"]),
520
+ topicId: z2.string().regex(SAFE_TOPIC).nullable().optional(),
521
+ profile: z2.string().regex(SAFE_PROFILE2).optional(),
522
+ decisionWindowId: z2.string().min(1).max(200).optional(),
523
+ decisionType: z2.string().regex(SAFE_TOKEN).optional(),
524
+ executionOperation: z2.enum([
525
+ "REPORT_DECIDED_ROLE_CLAIM",
526
+ "EXPLAIN_DECIDED_VOTE",
527
+ "RETRACT_PUBLIC_JUDGMENT",
528
+ "AVOID_REPEATING_PRIOR_SPEAKERS",
529
+ "EXPLAIN_DECIDED_WOLF_TARGET"
530
+ ]).optional(),
531
+ alternativeActionType: z2.string().regex(SAFE_TOKEN).optional(),
532
+ alternativeTargetSeat: z2.number().int().positive().nullable().optional(),
533
+ anchorFactId: z2.string().min(1).max(200).optional(),
534
+ knownFactRefs: z2.array(z2.string().min(1).max(200)).max(64).optional(),
535
+ outcomeFactRefs: z2.array(z2.string().min(1).max(200)).max(64).optional(),
536
+ trigger: z2.string().min(1).max(500).optional(),
537
+ rule: z2.string().min(1).max(500).optional(),
538
+ boundary: z2.string().min(1).max(500).optional(),
539
+ behavior: z2.string().min(1).max(800).optional(),
540
+ alternativeAction: z2.string().min(1).max(500).optional(),
541
+ expectedLocalEffect: z2.string().min(1).max(500).optional(),
542
+ observedLocalEffect: z2.string().min(1).max(500).optional(),
543
+ falsifier: z2.string().min(1).max(500).optional(),
544
+ alternatives: z2.array(z2.string().min(1).max(500)).min(1).max(8).optional(),
545
+ skipReason: z2.string().min(1).max(500).optional()
546
+ }).strict();
547
+ var EXECUTION_PROPOSAL_TEMPLATES = {
548
+ REPORT_DECIDED_ROLE_CLAIM: {
549
+ operation: "REPORT_DECIDED_ROLE_CLAIM",
550
+ decisionType: "REPORT_DECIDED_ROLE_CLAIM",
551
+ trigger: "\u5DF2\u7ECF\u51B3\u5B9A\u516C\u5F00\u9884\u8A00\u5BB6\u8EAB\u4EFD\uFF0C\u9700\u8981\u7EC4\u7EC7\u9996\u8F6E\u516C\u5F00\u53D1\u8A00",
552
+ rule: "\u5B8C\u6574\u8BF4\u660E\u67E5\u9A8C\u5EA7\u4F4D\u3001\u7ED3\u679C\u548C\u4E0B\u4E00\u591C\u9A8C\u4EBA\u8BA1\u5212",
553
+ boundary: "\u4E0D\u6539\u53D8\u662F\u5426\u8D77\u8DF3\u4EE5\u53CA\u67E5\u9A8C\u76EE\u6807",
554
+ alternativeAction: "\u5728\u540C\u4E00\u53D1\u8A00\u4E2D\u8865\u5145\u5B8C\u6574\u7684\u540E\u7EED\u4FE1\u606F\u94FE"
555
+ },
556
+ EXPLAIN_DECIDED_VOTE: {
557
+ operation: "EXPLAIN_DECIDED_VOTE",
558
+ decisionType: "EXPLAIN_DECIDED_VOTE",
559
+ trigger: "\u5DF2\u7ECF\u51B3\u5B9A\u6295\u7968\u76EE\u6807\uFF0C\u9700\u8981\u8BF4\u660E\u516C\u5F00\u7406\u7531",
560
+ rule: "\u53EA\u4F7F\u7528\u884C\u52A8\u524D\u516C\u5F00\u4FE1\u606F\u8BF4\u660E\u5DF2\u7ECF\u786E\u5B9A\u7684\u6295\u7968\u7406\u7531",
561
+ boundary: "\u4E0D\u6539\u53D8\u6295\u7968\u76EE\u6807\u6216\u53F7\u53EC\u5176\u4ED6\u73A9\u5BB6\u6539\u53D8\u6295\u7968\u76EE\u6807",
562
+ alternativeAction: "\u5728\u63D0\u4EA4\u76F8\u540C\u6295\u7968\u76EE\u6807\u65F6\u8865\u5145\u4E0E\u516C\u5F00\u4FE1\u606F\u4E00\u81F4\u7684\u7406\u7531"
563
+ },
564
+ RETRACT_PUBLIC_JUDGMENT: {
565
+ operation: "RETRACT_PUBLIC_JUDGMENT",
566
+ decisionType: "RETRACT_PUBLIC_JUDGMENT",
567
+ trigger: "\u5DF2\u7ECF\u786E\u8BA4\u6B64\u524D\u516C\u5F00\u5224\u65AD\u9519\u8BEF\uFF0C\u9700\u8981\u5728\u540E\u7EED\u53D1\u8A00\u4E2D\u66F4\u6B63",
568
+ rule: "\u660E\u786E\u64A4\u56DE\u65E7\u5224\u65AD\u5E76\u8BF4\u660E\u66F4\u65B0\u6240\u4F9D\u636E\u7684\u516C\u5F00\u4FE1\u606F",
569
+ boundary: "\u4E0D\u636E\u6B64\u6539\u53D8\u5F53\u524D\u6295\u7968\u76EE\u6807\u3001\u7528\u836F\u3001\u5F00\u67AA\u6216\u8EAB\u4EFD\u51B3\u7B56",
570
+ alternativeAction: "\u5728\u540E\u7EED\u53D1\u8A00\u4E2D\u660E\u786E\u64A4\u56DE\u65E7\u5224\u65AD\u5E76\u8BF4\u660E\u66F4\u65B0\u4F9D\u636E"
571
+ },
572
+ AVOID_REPEATING_PRIOR_SPEAKERS: {
573
+ operation: "AVOID_REPEATING_PRIOR_SPEAKERS",
574
+ decisionType: "AVOID_REPEATING_PRIOR_SPEAKERS",
575
+ trigger: "\u8F6E\u5230\u81EA\u5DF1\u53D1\u8A00\u4E14\u524D\u7F6E\u4F4D\u5DF2\u7ECF\u5B8C\u6574\u8868\u8FBE\u76F8\u540C\u89C2\u70B9",
576
+ rule: "\u7701\u7565\u5BF9\u524D\u7F6E\u4F4D\u89C2\u70B9\u7684\u590D\u8FF0\uFF0C\u53EA\u8865\u5145\u81EA\u5DF1\u7684\u65B0\u589E\u5224\u65AD\u4F9D\u636E",
577
+ boundary: "\u4E0D\u6539\u53D8\u5F53\u524D\u7AD9\u8FB9\u3001\u6295\u7968\u76EE\u6807\u6216\u8EAB\u4EFD\u51B3\u7B56",
578
+ alternativeAction: "\u53EA\u8868\u8FBE\u76F8\u5BF9\u4E8E\u524D\u7F6E\u53D1\u8A00\u65B0\u589E\u7684\u5224\u65AD\u4F9D\u636E"
579
+ },
580
+ EXPLAIN_DECIDED_WOLF_TARGET: {
581
+ operation: "EXPLAIN_DECIDED_WOLF_TARGET",
582
+ decisionType: "EXPLAIN_DECIDED_WOLF_TARGET",
583
+ trigger: "\u72FC\u961F\u884C\u52A8\u76EE\u6807\u5DF2\u7ECF\u786E\u5B9A\uFF0C\u9700\u8981\u5411\u961F\u53CB\u8BF4\u660E\u8BA1\u5212",
584
+ rule: "\u53EA\u4F7F\u7528\u72FC\u961F\u5F53\u65F6\u5DF2\u77E5\u7684\u4FE1\u606F\u8BF4\u660E\u5DF2\u7ECF\u786E\u5B9A\u7684\u884C\u52A8\u8BA1\u5212",
585
+ boundary: "\u4E0D\u6539\u53D8\u884C\u52A8\u76EE\u6807\u6216\u884C\u52A8\u7C7B\u578B",
586
+ alternativeAction: "\u5411\u961F\u53CB\u8BF4\u660E\u76F8\u540C\u884C\u52A8\u76EE\u6807\u7684\u516C\u5F00\u4F9D\u636E\u548C\u540E\u7EED\u8BA1\u5212"
587
+ }
588
+ };
589
+ var STRATEGY_LANGUAGE = /(?:改变|改投|改票|转票|投给|投票目标|查验目标|验谁|刀谁|刀口|毒谁|救谁|用药|开枪|起跳|跳预言家|自刀|悍跳|倒钩|站边|目标座位|targetSeat|actionType|vote target|check target|kill target)/i;
590
+ var FIXED_RULE_LANGUAGE = /(?:JSON\s*schema|JSON格式|非法动作|角色动作合法|私有信息保护|不虚构时间线|工具失败|输出超时|现实人格|人身攻击)/i;
591
+ var COUNTER_EFFECT_LANGUAGE = /(?:未能|没有|无法|无效|反而|恶化|失败|矛盾|误导|暴露|did not|failed|ineffective|worse|contradict)/i;
592
+ var LOCAL_OUTCOME_FACT_TYPES = /* @__PURE__ */ new Set([
593
+ "WOLF_CHOOSE",
594
+ "WOLF_SPEECH",
595
+ "WOLF_TARGET_CONFIRMED",
596
+ "WOLF_TARGET_RANDOM",
597
+ "WOLF_TARGET_NONE",
598
+ "WOLF_TARGET_CONFLICT_RETRY",
599
+ "WITCH_SAVE",
600
+ "WITCH_SKIP_SAVE",
601
+ "WITCH_POISON",
602
+ "WITCH_SKIP_POISON",
603
+ "WITCH_PASS",
604
+ "SEER_CHECK",
605
+ "SEER_SKIP_CHECK",
606
+ "NIGHT_RESOLVED",
607
+ "DAWN_ANNOUNCE",
608
+ "PRIVATE_NIGHT_HUNTER_SHOOT",
609
+ "PRIVATE_NIGHT_HUNTER_PASS",
610
+ "HUNTER_SHOOT",
611
+ "HUNTER_PASS",
612
+ "DAY_SPEAK",
613
+ "LAST_WORD",
614
+ "DAY_VOTE_SUBMIT",
615
+ "DAY_VOTE_COUNT",
616
+ "DAY_VOTE_TIE",
617
+ "DAY_VOTE_ELIMINATED",
618
+ "DAY_REVOTE_SUBMIT",
619
+ "DAY_REVOTE_COUNT",
620
+ "DAY_REVOTE_ELIMINATED",
621
+ "DAY_REVOTE_TIE",
622
+ "DAY_PEACE",
623
+ "DAY_RESOLVED"
624
+ ]);
625
+ var TARGET_REQUIRED_ACTIONS = /* @__PURE__ */ new Set([
626
+ "WOLF_KILL",
627
+ "WITCH_SAVE",
628
+ "WITCH_POISON",
629
+ "SEER_CHECK",
630
+ "HUNTER_SHOOT"
631
+ ]);
632
+ var TARGETLESS_ACTIONS = /* @__PURE__ */ new Set([
633
+ "WITCH_SKIP_SAVE",
634
+ "WITCH_SKIP_POISON",
635
+ "WITCH_PASS",
636
+ "SEER_SKIP_CHECK",
637
+ "HUNTER_PASS"
638
+ ]);
639
+ var ProposalError = class extends Error {
640
+ constructor(code, message) {
641
+ super(message);
642
+ this.code = code;
643
+ this.name = "ProposalError";
644
+ }
645
+ code;
646
+ };
647
+ function requireText(proposal, key, min = 2) {
648
+ const value = proposal[key];
649
+ if (typeof value !== "string" || value.trim().length < min) {
650
+ throw new ProposalError("QUALITY_FIELD_MISSING", `${String(key)} must be concrete and non-empty`);
651
+ }
652
+ return value.trim();
653
+ }
654
+ function unique(values, code) {
655
+ if (new Set(values).size !== values.length) throw new ProposalError(code, "Fact references must be unique");
656
+ }
657
+ function semanticText(value) {
658
+ return value.toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, "");
659
+ }
660
+ function ngrams(value) {
661
+ const normalized = semanticText(value);
662
+ const out = /* @__PURE__ */ new Set();
663
+ for (let index = 0; index < normalized.length - 1; index++) out.add(normalized.slice(index, index + 2));
664
+ if (out.size === 0 && normalized) out.add(normalized);
665
+ return out;
666
+ }
667
+ function similarity(left, right) {
668
+ const a = ngrams(left);
669
+ const b = ngrams(right);
670
+ if (a.size === 0 || b.size === 0) return 0;
671
+ let intersection = 0;
672
+ for (const item of a) if (b.has(item)) intersection++;
673
+ return 2 * intersection / (a.size + b.size);
674
+ }
675
+ function sameSemanticText(left, right) {
676
+ return typeof left === "string" && semanticText(left) === semanticText(right);
677
+ }
678
+ function factVisibleToActor(visibility, window) {
679
+ if (visibility === "PUBLIC") return true;
680
+ if (visibility === "POSTGAME_ONLY") return false;
681
+ if (visibility === "WOLF_TEAM") {
682
+ return window.actorRole === "WOLF" || window.actorRole === "WEREWOLF";
683
+ }
684
+ const seatOnly = /^SEAT_([1-9][0-9]*)_ONLY$/.exec(visibility);
685
+ return seatOnly !== null && Number(seatOnly[1]) === window.actorSeat;
686
+ }
687
+ function assertAlternativeTarget(proposal, window, risk) {
688
+ if (risk === "execution") {
689
+ if (proposal.alternativeTargetSeat !== void 0) {
690
+ throw new ProposalError(
691
+ "EXECUTION_TARGET_NOT_ALLOWED",
692
+ "An execution proposal cannot introduce or change a target"
693
+ );
694
+ }
695
+ return;
696
+ }
697
+ const actionType = proposal.alternativeActionType;
698
+ const target = proposal.alternativeTargetSeat;
699
+ if (TARGET_REQUIRED_ACTIONS.has(actionType) && target == null) {
700
+ throw new ProposalError("ALTERNATIVE_TARGET_REQUIRED", `${actionType} requires an alternative target`);
701
+ }
702
+ if (TARGETLESS_ACTIONS.has(actionType) && target != null) {
703
+ throw new ProposalError("ALTERNATIVE_TARGET_FORBIDDEN", `${actionType} cannot carry a target`);
704
+ }
705
+ if (actionType === "DAY_VOTE" && target === void 0) {
706
+ throw new ProposalError("ALTERNATIVE_TARGET_REQUIRED", "DAY_VOTE must explicitly choose a seat or abstain");
707
+ }
708
+ if (target != null) {
709
+ if (!window.availableTargetSeats) {
710
+ throw new ProposalError(
711
+ "TARGET_SET_UNAVAILABLE",
712
+ "The trusted decision window did not preserve the legal target set"
713
+ );
714
+ }
715
+ if (!window.availableTargetSeats.includes(target)) {
716
+ throw new ProposalError("ALTERNATIVE_TARGET_UNAVAILABLE", "The alternative target was not legal at that point");
717
+ }
718
+ }
719
+ }
720
+ function matchesExecutionDefinition(value, allowRefinement, requireAlternativeAction) {
721
+ const operation = value.executionOperation;
722
+ const template = operation ? EXECUTION_PROPOSAL_TEMPLATES[operation] : void 0;
723
+ if (!template || template.decisionType !== value.decisionType || !sameSemanticText(value.rule, template.rule) || requireAlternativeAction && !sameSemanticText(value.alternativeAction, template.alternativeAction)) return false;
724
+ const trigger = semanticText(value.trigger ?? "");
725
+ const boundary = semanticText(value.boundary ?? "");
726
+ const expectedTrigger = semanticText(template.trigger);
727
+ const expectedBoundary = semanticText(template.boundary);
728
+ if (allowRefinement) {
729
+ if (!trigger.startsWith(expectedTrigger) || !boundary.startsWith(expectedBoundary)) return false;
730
+ const addedScope = `${trigger.slice(expectedTrigger.length)} ${boundary.slice(expectedBoundary.length)}`;
731
+ if (STRATEGY_LANGUAGE.test(addedScope)) return false;
732
+ } else if (trigger !== expectedTrigger || boundary !== expectedBoundary) {
733
+ return false;
734
+ }
735
+ return true;
736
+ }
737
+ function classifyRisk(proposal, decisionType = proposal.decisionType ?? "") {
738
+ return matchesExecutionDefinition(
739
+ { ...proposal, decisionType },
740
+ proposal.action === "REFINE",
741
+ true
742
+ ) ? "execution" : "strategy";
743
+ }
744
+ function assertExistingSemantics(proposal, existing, window, action, players) {
745
+ if (existing.status === "archived") {
746
+ throw new ProposalError("TOPIC_ARCHIVED", `Archived topic cannot receive ${action}`);
747
+ }
748
+ if (proposal.decisionType !== existing.decisionType || existing.risk === "execution" && proposal.executionOperation !== existing.executionOperation || window.phase !== existing.phase || window.actorRole !== existing.role || window.actionType !== existing.actionType || players !== existing.players) {
749
+ throw new ProposalError("TOPIC_SEMANTICS_MISMATCH", `${action} does not describe the selected topic`);
750
+ }
751
+ if (action === "SUPPORT" || action === "COUNTER") {
752
+ if (!sameSemanticText(proposal.trigger, existing.trigger) || !sameSemanticText(proposal.rule, existing.rule) || !sameSemanticText(proposal.boundary, existing.boundary) || !sameSemanticText(proposal.expectedLocalEffect, existing.expectedLocalEffect) || !sameSemanticText(proposal.falsifier, existing.falsifier)) {
753
+ throw new ProposalError("TOPIC_OUTCOME_SEMANTICS_MISMATCH", `${action} changed the topic's causal claim`);
754
+ }
755
+ }
756
+ if (action === "COUNTER" && !COUNTER_EFFECT_LANGUAGE.test(proposal.observedLocalEffect ?? "")) {
757
+ throw new ProposalError("COUNTER_NOT_FALSIFYING", "COUNTER must describe a concrete failed or adverse local outcome");
758
+ }
759
+ }
760
+ function assertRefinement(proposal, existing, risk) {
761
+ if (!sameSemanticText(proposal.rule, existing.rule)) {
762
+ throw new ProposalError("REFINE_RULE_CHANGED", "REFINE must narrow applicability without replacing the behavior rule");
763
+ }
764
+ if (risk !== existing.risk) {
765
+ throw new ProposalError("REFINE_RISK_CHANGED", "REFINE cannot silently change the topic risk class");
766
+ }
767
+ const oldScope = `${existing.trigger} ${existing.boundary}`;
768
+ const newScope = `${proposal.trigger} ${proposal.boundary}`;
769
+ if (semanticText(oldScope) === semanticText(newScope) || semanticText(newScope).length <= semanticText(oldScope).length || similarity(oldScope, newScope) < 0.5) {
770
+ throw new ProposalError("REFINE_NOT_NARROWER", "REFINE must preserve the topic and add a materially narrower trigger or boundary");
771
+ }
772
+ }
773
+ function parseAndValidateProposal(raw, envelope, evidence, activeProfile) {
774
+ const parsed = proposalSchema.safeParse(raw);
775
+ if (!parsed.success) {
776
+ throw new ProposalError("PROPOSAL_SCHEMA", parsed.error.issues.map((issue) => issue.message).join("; "));
777
+ }
778
+ const proposal = parsed.data;
779
+ if (proposal.action === "SKIP") {
780
+ requireText(proposal, "skipReason", 4);
781
+ const evolutionaryFields = [
782
+ proposal.topicId,
783
+ proposal.decisionWindowId,
784
+ proposal.anchorFactId,
785
+ proposal.executionOperation,
786
+ proposal.trigger,
787
+ proposal.rule,
788
+ proposal.boundary
789
+ ];
790
+ if (evolutionaryFields.some((value) => value != null)) {
791
+ throw new ProposalError("SKIP_WITH_EVOLUTION", "SKIP cannot carry a lesson mutation");
792
+ }
793
+ return { proposal };
794
+ }
795
+ const action = proposal.action;
796
+ if (action === "NEW" && proposal.topicId) throw new ProposalError("NEW_WITH_TOPIC", "NEW must not provide topicId");
797
+ if (action !== "NEW" && !proposal.topicId) {
798
+ throw new ProposalError("EXISTING_TOPIC_REQUIRED", `${action} requires topicId`);
799
+ }
800
+ const existing = proposal.topicId ? evidence.lessons.find((lesson) => lesson.id === proposal.topicId) : void 0;
801
+ if (action !== "NEW" && !existing) throw new ProposalError("TOPIC_NOT_FOUND", `Unknown topicId: ${proposal.topicId}`);
802
+ const profile = requireText(proposal, "profile");
803
+ if (envelope.game.profile !== void 0 && envelope.game.profile !== activeProfile) {
804
+ throw new ProposalError("ENVELOPE_PROFILE_MISMATCH", "Envelope profile conflicts with the workspace runtime");
805
+ }
806
+ if (profile !== activeProfile) {
807
+ throw new ProposalError("PROFILE_MISMATCH", "Proposal profile does not match the workspace runtime");
808
+ }
809
+ if (existing && existing.profile !== profile) {
810
+ throw new ProposalError("TOPIC_PROFILE_MISMATCH", "Topic belongs to a different profile");
811
+ }
812
+ const decisionWindowId = requireText(proposal, "decisionWindowId");
813
+ const window = envelope.decisionWindows.find((item) => item.decisionWindowId === decisionWindowId);
814
+ if (!window) throw new ProposalError("DECISION_WINDOW_NOT_FOUND", "Proposal does not reference a trusted decision window");
815
+ const decisionType = requireText(proposal, "decisionType");
816
+ if (!window.allowedDecisionTypes.includes(decisionType)) {
817
+ throw new ProposalError("DECISION_TYPE_NOT_ALLOWED", "decisionType is not valid for the trusted action window");
818
+ }
819
+ const alternativeActionType = requireText(proposal, "alternativeActionType");
820
+ if (!window.availableActionTypes.includes(alternativeActionType)) {
821
+ throw new ProposalError("ALTERNATIVE_ACTION_UNAVAILABLE", "The proposed alternative action was unavailable at that decision point");
822
+ }
823
+ if (proposal.source === "SELF" && window.actorSeat !== envelope.game.recipientSeat) {
824
+ throw new ProposalError("SELF_ACTOR_MISMATCH", "SELF evidence must anchor the recipient's own action");
825
+ }
826
+ if (proposal.source !== "SELF" && window.actorSeat === envelope.game.recipientSeat) {
827
+ throw new ProposalError("OTHER_ACTOR_MISMATCH", "OBSERVED and EXEMPLAR evidence must anchor another player's action");
828
+ }
829
+ const anchorFactId = requireText(proposal, "anchorFactId");
830
+ if (anchorFactId !== window.anchorFactId) {
831
+ throw new ProposalError("ANCHOR_WINDOW_MISMATCH", "anchorFactId does not match the trusted decision window");
832
+ }
833
+ requireText(proposal, "trigger", 4);
834
+ const rule = requireText(proposal, "rule", 4);
835
+ requireText(proposal, "boundary", 4);
836
+ requireText(proposal, "behavior", 4);
837
+ requireText(proposal, "alternativeAction", 4);
838
+ requireText(proposal, "expectedLocalEffect", 4);
839
+ const observed = requireText(proposal, "observedLocalEffect", 4);
840
+ requireText(proposal, "falsifier", 4);
841
+ if (!proposal.alternatives?.some((item) => item.trim().length >= 4)) {
842
+ throw new ProposalError("ALTERNATIVE_EXPLANATION_REQUIRED", "At least one plausible alternative explanation is required");
843
+ }
844
+ if (FIXED_RULE_LANGUAGE.test(rule)) {
845
+ throw new ProposalError("FIXED_RULE_NOT_LEARNABLE", "Permanent safety and protocol rules cannot be learned");
846
+ }
847
+ const facts = new Map(envelope.facts.map((fact) => [fact.factId, fact]));
848
+ const anchor = facts.get(anchorFactId);
849
+ if (!anchor || anchor.visibility === "POSTGAME_ONLY") {
850
+ throw new ProposalError("ANCHOR_NOT_OBSERVABLE", "The action anchor is missing or postgame-only");
851
+ }
852
+ const known = proposal.knownFactRefs ?? [];
853
+ const outcomes = proposal.outcomeFactRefs ?? [];
854
+ unique(known, "DUPLICATE_KNOWN_FACT");
855
+ unique(outcomes, "DUPLICATE_OUTCOME_FACT");
856
+ for (const ref of known) {
857
+ const fact = facts.get(ref);
858
+ if (!fact) throw new ProposalError("KNOWN_FACT_NOT_FOUND", `Unknown knownFactRef: ${ref}`);
859
+ if (fact.visibility === "POSTGAME_ONLY") {
860
+ throw new ProposalError("POSTGAME_FACT_AS_KNOWN", `Postgame-only fact used as known fact: ${ref}`);
861
+ }
862
+ if (!factVisibleToActor(fact.visibility, window)) {
863
+ throw new ProposalError(
864
+ "KNOWN_FACT_NOT_VISIBLE_TO_ACTOR",
865
+ `Known fact was not visible to the decision actor: ${ref}`
866
+ );
867
+ }
868
+ if (fact.availableAt.historyIndex >= anchor.availableAt.historyIndex) {
869
+ throw new ProposalError("KNOWN_FACT_TOO_LATE", `Known fact is not earlier than the action: ${ref}`);
870
+ }
871
+ }
872
+ let localOutcomeCount = 0;
873
+ for (const ref of outcomes) {
874
+ const fact = facts.get(ref);
875
+ if (!fact) throw new ProposalError("OUTCOME_FACT_NOT_FOUND", `Unknown outcomeFactRef: ${ref}`);
876
+ if (fact.availableAt.historyIndex <= anchor.availableAt.historyIndex) {
877
+ throw new ProposalError("OUTCOME_FACT_TOO_EARLY", `Outcome fact is not later than the action: ${ref}`);
878
+ }
879
+ if (LOCAL_OUTCOME_FACT_TYPES.has(fact.type)) {
880
+ localOutcomeCount++;
881
+ }
882
+ }
883
+ if (outcomes.length === 0 || localOutcomeCount === 0) {
884
+ throw new ProposalError("LOCAL_OUTCOME_FACT_REQUIRED", "Victory, final identity, or other postgame facts cannot be the only outcome evidence");
885
+ }
886
+ const allRefs = /* @__PURE__ */ new Set([...known, ...outcomes]);
887
+ if (allRefs.size !== known.length + outcomes.length) {
888
+ throw new ProposalError("FACT_ROLE_CONFLICT", "A fact cannot be both known information and an outcome");
889
+ }
890
+ if (/^(?:因此|所以)?(?:最终)?(?:好人|狼人|狼队|阵营)?(?:获胜|胜利|输了|失败|赢了)[。.!!]?$/i.test(observed.trim())) {
891
+ throw new ProposalError("FINAL_RESULT_NOT_LOCAL", "Final victory or defeat is not a local effect");
892
+ }
893
+ let risk = classifyRisk(proposal, window.allowedDecisionTypes.find((item) => item === decisionType));
894
+ if (risk === "execution" && alternativeActionType !== window.actionType) risk = "strategy";
895
+ assertAlternativeTarget(proposal, window, risk);
896
+ if (existing) {
897
+ assertExistingSemantics(proposal, existing, window, action, envelope.game.players);
898
+ if (action === "REFINE") assertRefinement(proposal, existing, risk);
899
+ }
900
+ if (action === "NEW") {
901
+ const proposedText = `${proposal.trigger} ${proposal.rule} ${proposal.boundary}`;
902
+ const duplicate = evidence.lessons.find((lesson) => lesson.status !== "archived" && lesson.profile === profile && similarity(proposedText, `${lesson.trigger} ${lesson.rule} ${lesson.boundary}`) >= 0.72);
903
+ if (duplicate) {
904
+ throw new ProposalError("SIMILAR_TOPIC_EXISTS", `Use SUPPORT, COUNTER or REFINE for ${duplicate.id}`);
905
+ }
906
+ }
907
+ return { proposal, risk, existing, decisionWindow: window };
908
+ }
909
+
910
+ // src/workspace.ts
911
+ import { lstatSync, mkdirSync, realpathSync } from "fs";
912
+ import path from "path";
913
+ var RUNTIME_START = "<!-- WEREWOLF_RUNTIME_START -->";
914
+ var RUNTIME_END = "<!-- WEREWOLF_RUNTIME_END -->";
915
+ var LEGACY_RUNTIME_START = "<!-- WOLF_PLAY_RUNTIME_START -->";
916
+ var LEGACY_RUNTIME_END = "<!-- WOLF_PLAY_RUNTIME_END -->";
917
+ function assertWorkspaceRootIdentity(paths) {
918
+ let stat;
919
+ let resolved;
920
+ try {
921
+ stat = lstatSync(paths.root);
922
+ resolved = realpathSync(paths.root);
923
+ } catch {
924
+ throw new Error("WORKSPACE_ROOT_CHANGED");
925
+ }
926
+ if (!stat.isDirectory() || stat.isSymbolicLink() || resolved !== paths.root || stat.dev !== paths.rootDevice || stat.ino !== paths.rootInode) {
927
+ throw new Error("WORKSPACE_ROOT_CHANGED");
928
+ }
929
+ }
930
+ function assertNoSymlinkFromExistingAncestor(candidate, root) {
931
+ const relative = path.relative(root, candidate);
932
+ if (relative.startsWith("..") || path.isAbsolute(relative)) throw new Error("PATH_OUTSIDE_WORKSPACE");
933
+ let current = root;
934
+ for (const segment of relative.split(path.sep).filter(Boolean)) {
935
+ current = path.join(current, segment);
936
+ try {
937
+ if (lstatSync(current).isSymbolicLink()) throw new Error(`SYMLINK_NOT_ALLOWED:${current}`);
938
+ } catch (error) {
939
+ const code = error.code;
940
+ if (code === "ENOENT") break;
941
+ throw error;
942
+ }
943
+ }
944
+ }
945
+ function assertSafeWorkspacePath(candidate, paths) {
946
+ assertWorkspaceRootIdentity(paths);
947
+ assertNoSymlinkFromExistingAncestor(path.resolve(candidate), paths.root);
948
+ }
949
+ function resolveWorkspacePaths(workspaceDir, createMemory = true) {
950
+ if (!workspaceDir || !path.isAbsolute(workspaceDir)) throw new Error("WORKSPACE_ABSOLUTE_REQUIRED");
951
+ const root = realpathSync(workspaceDir);
952
+ const rootStat = lstatSync(root);
953
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) throw new Error("WORKSPACE_ROOT_INVALID");
954
+ const memory = path.join(root, "memory");
955
+ assertNoSymlinkFromExistingAncestor(memory, root);
956
+ if (createMemory) mkdirSync(memory, { recursive: true, mode: 448 });
957
+ assertNoSymlinkFromExistingAncestor(memory, root);
958
+ const paths = {
959
+ root,
960
+ rootDevice: rootStat.dev,
961
+ rootInode: rootStat.ino,
962
+ memory,
963
+ evidence: path.join(memory, "werewolf-evidence-v3.md"),
964
+ incidents: path.join(memory, "werewolf-incidents.md"),
965
+ suggestions: path.join(memory, "werewolf-suggestions.md"),
966
+ ownerBinding: path.join(memory, "werewolf-evolution-owner.json"),
967
+ ledger: path.join(memory, "werewolf-evolution-ledger.md"),
968
+ agents: path.join(root, "AGENTS.md"),
969
+ overrides: path.join(memory, "werewolf-profile-overrides"),
970
+ customProfiles: path.join(memory, "werewolf-custom-profiles"),
971
+ skill: path.join(root, "skills", "werewolf-play"),
972
+ skillReferences: path.join(root, "skills", "werewolf-play", "references"),
973
+ legacyEvidenceV2: path.join(memory, "wolf-play-evidence-v2.md"),
974
+ legacySuggestions: path.join(memory, "wolf-play-suggestions.md"),
975
+ migrationMarker: path.join(memory, "werewolf-evolution-migration-v3.md"),
976
+ legacySkill: path.join(root, "skills", "wolf-play"),
977
+ backups: path.join(root, "werewolf-evolution-backups"),
978
+ setupLock: path.join(root, ".werewolf-evolution-setup.lock"),
979
+ lock: path.join(memory, ".werewolf-evolution.lock"),
980
+ journal: path.join(memory, ".werewolf-evolution-transaction.json")
981
+ };
982
+ assertWorkspaceRootIdentity(paths);
983
+ for (const value of Object.values(paths)) {
984
+ if (typeof value === "string") assertNoSymlinkFromExistingAncestor(value, root);
985
+ }
986
+ return paths;
987
+ }
988
+ function profileOverridePath(paths, profile) {
989
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(profile)) throw new Error("PROFILE_NAME_INVALID");
990
+ return path.join(paths.overrides, `${profile}.md`);
991
+ }
992
+ function customProfilePath(paths, profile) {
993
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(profile)) throw new Error("PROFILE_NAME_INVALID");
994
+ return path.join(paths.customProfiles, `${profile}.md`);
995
+ }
996
+ function installedProfilePath(paths, profile) {
997
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(profile)) throw new Error("PROFILE_NAME_INVALID");
998
+ return path.join(paths.skillReferences, `profile-${profile.replaceAll("_", "-")}.md`);
999
+ }
1000
+ function assertFixedTarget(target, paths) {
1001
+ const allowed = /* @__PURE__ */ new Set([
1002
+ paths.evidence,
1003
+ paths.incidents,
1004
+ paths.suggestions,
1005
+ paths.ownerBinding,
1006
+ paths.ledger,
1007
+ paths.agents,
1008
+ paths.legacyEvidenceV2,
1009
+ paths.legacySuggestions,
1010
+ paths.migrationMarker
1011
+ ]);
1012
+ const resolved = path.resolve(target);
1013
+ const overrideRelative = path.relative(paths.overrides, resolved);
1014
+ const isOverride = overrideRelative.length > 0 && !overrideRelative.startsWith("..") && !path.isAbsolute(overrideRelative) && /^[a-z0-9][a-z0-9_-]{0,63}\.md$/.test(overrideRelative);
1015
+ const archiveRelative = path.relative(paths.memory, resolved);
1016
+ const isLegacyArchive = !archiveRelative.startsWith("..") && !path.isAbsolute(archiveRelative) && /^werewolf-(?:evidence|suggestions)-legacy-v2-[0-9]{8}T[0-9]{9}Z\.md$/.test(archiveRelative);
1017
+ if (!allowed.has(resolved) && !isOverride && !isLegacyArchive) throw new Error(`TARGET_NOT_ALLOWED:${target}`);
1018
+ assertSafeWorkspacePath(resolved, paths);
1019
+ }
1020
+ function resolvedDerivedPath(value, paths) {
1021
+ return path.resolve(paths.root, value);
1022
+ }
1023
+ function isProtectedPath(value, paths, includeAgents) {
1024
+ const resolved = resolvedDerivedPath(value, paths);
1025
+ if (includeAgents && resolved === paths.agents || resolved === paths.evidence || resolved === paths.incidents || resolved === paths.suggestions || resolved === paths.ledger || resolved === paths.lock || resolved === paths.ownerBinding || resolved === paths.setupLock || resolved === paths.journal || resolved === paths.legacyEvidenceV2 || resolved === paths.legacySuggestions || resolved === paths.migrationMarker || resolved === paths.legacySkill || resolved === paths.backups) return true;
1026
+ const protectedDirectories = [paths.overrides, paths.skill, paths.legacySkill, paths.backups];
1027
+ if (includeAgents) protectedDirectories.push(paths.customProfiles);
1028
+ return protectedDirectories.some((directory) => {
1029
+ const relative = path.relative(directory, resolved);
1030
+ return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
1031
+ });
1032
+ }
1033
+ function isProtectedToolWrite(toolName, params, derivedPaths, paths, blockAllMutation = true, toolKind) {
1034
+ if (toolName === "werewolf_debrief_commit" || toolName === "werewolf_suggestion_decide") return false;
1035
+ const action = typeof params.action === "string" ? params.action : "";
1036
+ const isGenericMutation = /(?:^|_)(?:write|edit|patch|replace|append|delete|remove|rename|move|copy)(?:$|_)/i.test(toolName) || /^(?:exec|shell|terminal|apply_patch)$/i.test(toolName) || /^(?:write|edit|patch|replace|append|delete|remove|rename|move|copy)$/i.test(action);
1037
+ if (blockAllMutation && isGenericMutation) return true;
1038
+ if (!blockAllMutation && !isGenericMutation && toolKind !== "code_mode_exec") return false;
1039
+ if (derivedPaths?.some((value) => isProtectedPath(value, paths, blockAllMutation))) return true;
1040
+ let serialized = "";
1041
+ try {
1042
+ serialized = JSON.stringify(params);
1043
+ } catch {
1044
+ return true;
1045
+ }
1046
+ const managedState = /(?:werewolf-evolution-owner\.json|werewolf-(?:evidence-v3|incidents|suggestions|evolution-ledger|evolution-migration-v3|(?:evidence|suggestions)-legacy-v2-[^/\\]+)\.md|wolf-play-(?:evidence-v2|suggestions)\.md|werewolf-profile-overrides|werewolf-evolution-backups|skills[/\\]wolf-play|\.werewolf-evolution-(?:setup\.lock|lock|transaction))/i;
1047
+ const runtimeProjection = /(?:(?:WEREWOLF|WOLF_PLAY)_RUNTIME_(?:START|END)|###\s+(?:GAME_EVENT execution contract|active lessons)|(?:werewolf|wolf)-play runtime|AGENTS\.md)/i;
1048
+ return managedState.test(serialized) || blockAllMutation && runtimeProjection.test(serialized);
1049
+ }
1050
+
1051
+ // src/documents.ts
1052
+ var DATA_START = "<!-- WEREWOLF_EVOLUTION_DATA_START -->";
1053
+ var DATA_END = "<!-- WEREWOLF_EVOLUTION_DATA_END -->";
1054
+ var MAX_MANAGED_FILE_BYTES = 2 * 1024 * 1024;
1055
+ var MAX_RUNTIME_CHARS = 8e3;
1056
+ var SAFE_PROFILE3 = /^[a-z0-9][a-z0-9_-]{0,63}$/;
1057
+ var SAFE_TOKEN2 = /^[A-Z][A-Z0-9_]{1,79}$/;
1058
+ var SAFE_LESSON = /^L-[a-z0-9][a-z0-9_-]{0,63}-\d{3,6}$/;
1059
+ var SAFE_SUGGESTION = /^S-\d{3,6}$/;
1060
+ var SAFE_DEBRIEF = /^werewolf:[0-9]{1,30}:agent:[0-9]{1,30}:v2$/;
1061
+ var DATE = /^\d{4}-\d{2}-\d{2}$/;
1062
+ var HASH = /^[a-f0-9]{64}$/;
1063
+ var sampleSchema = z3.object({
1064
+ gameId: z3.string().regex(/^[0-9]{1,30}$/),
1065
+ debriefId: z3.string().regex(SAFE_DEBRIEF),
1066
+ reviewDate: z3.string().regex(DATE),
1067
+ source: z3.enum(["SELF", "OBSERVED", "EXEMPLAR"]),
1068
+ decisionWindowId: z3.string().min(1).max(200),
1069
+ anchorFactId: z3.string().min(1).max(200),
1070
+ alternativeActionType: z3.string().regex(SAFE_TOKEN2),
1071
+ alternativeTargetSeat: z3.number().int().positive().nullable().optional(),
1072
+ knownFactRefs: z3.array(z3.string().min(1).max(200)).max(64),
1073
+ outcomeFactRefs: z3.array(z3.string().min(1).max(200)).min(1).max(64),
1074
+ behavior: z3.string().min(1).max(800),
1075
+ observedLocalEffect: z3.string().min(1).max(500),
1076
+ alternatives: z3.array(z3.string().min(1).max(500)).min(1).max(8)
1077
+ }).strict();
1078
+ var lessonSchema = z3.object({
1079
+ id: z3.string().regex(SAFE_LESSON),
1080
+ status: z3.enum(["candidate", "probation", "active", "contested", "archived"]),
1081
+ risk: z3.enum(["execution", "strategy"]),
1082
+ profile: z3.string().regex(SAFE_PROFILE3),
1083
+ phase: z3.string().regex(SAFE_TOKEN2),
1084
+ role: z3.string().regex(SAFE_TOKEN2),
1085
+ players: z3.number().int().positive().max(32),
1086
+ actionType: z3.string().regex(SAFE_TOKEN2),
1087
+ decisionType: z3.string().regex(SAFE_TOKEN2),
1088
+ executionOperation: z3.enum([
1089
+ "REPORT_DECIDED_ROLE_CLAIM",
1090
+ "EXPLAIN_DECIDED_VOTE",
1091
+ "RETRACT_PUBLIC_JUDGMENT",
1092
+ "AVOID_REPEATING_PRIOR_SPEAKERS",
1093
+ "EXPLAIN_DECIDED_WOLF_TARGET"
1094
+ ]).optional(),
1095
+ trigger: z3.string().min(1).max(500),
1096
+ rule: z3.string().min(1).max(500),
1097
+ boundary: z3.string().min(1).max(500),
1098
+ expectedLocalEffect: z3.string().min(1).max(500),
1099
+ falsifier: z3.string().min(1).max(500),
1100
+ supportGames: z3.array(sampleSchema).max(512),
1101
+ counterGames: z3.array(sampleSchema).max(512),
1102
+ probationStartedAtSupportCount: z3.number().int().positive().optional(),
1103
+ supersedesLessonId: z3.string().regex(SAFE_LESSON).optional(),
1104
+ supersededByLessonId: z3.string().regex(SAFE_LESSON).optional(),
1105
+ createdAt: z3.string().datetime({ offset: true }),
1106
+ lastReviewed: z3.string().regex(DATE)
1107
+ }).strict();
1108
+ var evidenceSchema = z3.object({
1109
+ schemaVersion: z3.literal(3),
1110
+ lessons: z3.array(lessonSchema).max(4096)
1111
+ }).strict();
1112
+ var incidentSchema = z3.object({
1113
+ debriefId: z3.string().regex(SAFE_DEBRIEF),
1114
+ gameId: z3.string().regex(/^[0-9]{1,30}$/),
1115
+ reviewDate: z3.string().regex(DATE),
1116
+ reasons: z3.array(z3.string().regex(/^[A-Z][A-Z0-9_]{1,79}$/)).min(1).max(16),
1117
+ recordedAt: z3.string().datetime({ offset: true })
1118
+ }).strict();
1119
+ var incidentsSchema = z3.object({
1120
+ schemaVersion: z3.literal(1),
1121
+ incidents: z3.array(incidentSchema).max(4096)
1122
+ }).strict();
1123
+ var suggestionSchema = z3.object({
1124
+ id: z3.string().regex(SAFE_SUGGESTION),
1125
+ lessonId: z3.string().regex(SAFE_LESSON),
1126
+ profile: z3.string().regex(SAFE_PROFILE3),
1127
+ status: z3.enum(["pending", "accepted", "rejected", "paused", "withdrawn"]),
1128
+ trigger: z3.string().min(1).max(500),
1129
+ rule: z3.string().min(1).max(500),
1130
+ boundary: z3.string().min(1).max(500),
1131
+ supportCount: z3.number().int().nonnegative(),
1132
+ counterCount: z3.number().int().nonnegative(),
1133
+ createdAt: z3.string().datetime({ offset: true }),
1134
+ reminderSentAt: z3.string().datetime({ offset: true }).optional(),
1135
+ decidedAt: z3.string().datetime({ offset: true }).optional(),
1136
+ decidedBy: z3.string().min(1).max(200).optional(),
1137
+ pausedAt: z3.string().datetime({ offset: true }).optional(),
1138
+ pauseReason: z3.string().min(1).max(200).optional()
1139
+ }).strict();
1140
+ var suggestionsSchema = z3.object({
1141
+ schemaVersion: z3.literal(1),
1142
+ suggestions: z3.array(suggestionSchema).max(4096)
1143
+ }).strict();
1144
+ var ledgerEntrySchema = z3.object({
1145
+ debriefId: z3.string().regex(SAFE_DEBRIEF),
1146
+ gameId: z3.string().regex(/^[0-9]{1,30}$/),
1147
+ bodyHash: z3.string().regex(HASH),
1148
+ action: z3.enum(["SKIP", "SUPPORT", "COUNTER", "REFINE", "NEW", "INCIDENT"]),
1149
+ outcome: z3.string().min(1).max(100),
1150
+ processedAt: z3.string().datetime({ offset: true })
1151
+ }).strict();
1152
+ var ledgerSchema = z3.object({
1153
+ schemaVersion: z3.literal(1),
1154
+ entries: z3.array(ledgerEntrySchema).max(1e5),
1155
+ legacyGameIds: z3.array(z3.string().regex(/^[0-9]{1,30}$/)).max(1e5).default([])
1156
+ }).strict();
1157
+ var emptyEvidence = () => ({ schemaVersion: 3, lessons: [] });
1158
+ var emptyIncidents = () => ({ schemaVersion: 1, incidents: [] });
1159
+ var emptySuggestions = () => ({ schemaVersion: 1, suggestions: [] });
1160
+ var emptyLedger = () => ({ schemaVersion: 1, entries: [], legacyGameIds: [] });
1161
+ function renderManaged(title, value) {
1162
+ return [
1163
+ `# ${title}`,
1164
+ "",
1165
+ "This file is managed by werewolf-evolution. Do not edit its data block manually.",
1166
+ "",
1167
+ DATA_START,
1168
+ "```json",
1169
+ JSON.stringify(value, null, 2),
1170
+ "```",
1171
+ DATA_END,
1172
+ ""
1173
+ ].join("\n");
1174
+ }
1175
+ function parseManaged(content, label) {
1176
+ const start = content.indexOf(DATA_START);
1177
+ const end = content.indexOf(DATA_END);
1178
+ if (start < 0 || end <= start || content.indexOf(DATA_START, start + 1) >= 0 || content.indexOf(DATA_END, end + 1) >= 0) {
1179
+ throw new Error(`MANAGED_MARKERS_INVALID:${label}`);
1180
+ }
1181
+ const block = content.slice(start + DATA_START.length, end).trim();
1182
+ const match = /^```json[ \t]*\r?\n([\s\S]*)\r?\n```$/.exec(block);
1183
+ if (!match) throw new Error(`MANAGED_JSON_BLOCK_INVALID:${label}`);
1184
+ try {
1185
+ return JSON.parse(match[1]);
1186
+ } catch (error) {
1187
+ throw new Error(`MANAGED_JSON_INVALID:${label}:${String(error)}`);
1188
+ }
1189
+ }
1190
+ function readOrDefault(file, fallback, label, schema) {
1191
+ if (!existsSync(file)) return fallback();
1192
+ const stat = lstatSync2(file);
1193
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_MANAGED_FILE_BYTES) {
1194
+ throw new Error(`MANAGED_FILE_INVALID:${label}`);
1195
+ }
1196
+ const parsed = schema.safeParse(parseManaged(readFileSync(file, "utf8"), label));
1197
+ if (!parsed.success) throw new Error(`MANAGED_SCHEMA_INVALID:${label}:${parsed.error.message}`);
1198
+ return parsed.data;
1199
+ }
1200
+ function uniqueValues(values, code) {
1201
+ if (new Set(values).size !== values.length) throw new Error(code);
1202
+ }
1203
+ function independentDates(samples) {
1204
+ return new Set(samples.map((sample2) => sample2.reviewDate)).size;
1205
+ }
1206
+ function semanticValue(value) {
1207
+ return value.toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, "");
1208
+ }
1209
+ function validateSampleRefs(sample2, expectedActions, ledgerByDebrief) {
1210
+ const prefix = `${sample2.debriefId}:`;
1211
+ if (!sample2.decisionWindowId.startsWith(`${prefix}d:`) || !sample2.anchorFactId.startsWith(`${prefix}h:`) || [...sample2.knownFactRefs, ...sample2.outcomeFactRefs].some((ref) => !ref.startsWith(`${prefix}h:`))) {
1212
+ throw new Error(`SAMPLE_FACT_SCOPE_MISMATCH:${sample2.debriefId}`);
1213
+ }
1214
+ uniqueValues(sample2.knownFactRefs, `DUPLICATE_SAMPLE_KNOWN_FACT:${sample2.debriefId}`);
1215
+ uniqueValues(sample2.outcomeFactRefs, `DUPLICATE_SAMPLE_OUTCOME_FACT:${sample2.debriefId}`);
1216
+ if (sample2.knownFactRefs.some((ref) => sample2.outcomeFactRefs.includes(ref))) {
1217
+ throw new Error(`SAMPLE_FACT_ROLE_CONFLICT:${sample2.debriefId}`);
1218
+ }
1219
+ const ledger = ledgerByDebrief.get(sample2.debriefId);
1220
+ if (!ledger || ledger.gameId !== sample2.gameId || !expectedActions.has(ledger.action)) {
1221
+ throw new Error(`SAMPLE_LEDGER_MISMATCH:${sample2.debriefId}`);
1222
+ }
1223
+ }
1224
+ function validateLessonReachability(lesson) {
1225
+ if (!lesson.id.startsWith(`L-${lesson.profile}-`)) throw new Error(`LESSON_PROFILE_ID_MISMATCH:${lesson.id}`);
1226
+ const supports = lesson.supportGames.length;
1227
+ const counters = lesson.counterGames.length;
1228
+ const dates = independentDates(lesson.supportGames);
1229
+ if (supports < 1) throw new Error(`LESSON_WITHOUT_SUPPORT:${lesson.id}`);
1230
+ if (lesson.risk === "strategy") {
1231
+ if (lesson.executionOperation !== void 0) throw new Error(`STRATEGY_EXECUTION_OPERATION:${lesson.id}`);
1232
+ if (lesson.status === "probation" || lesson.status === "active") {
1233
+ throw new Error(`STRATEGY_RUNTIME_STATUS:${lesson.id}`);
1234
+ }
1235
+ if (lesson.status === "candidate" && counters > 0) throw new Error(`STRATEGY_CANDIDATE_WITH_COUNTER:${lesson.id}`);
1236
+ if (lesson.status === "contested" && counters < 1) throw new Error(`STRATEGY_CONTESTED_WITHOUT_COUNTER:${lesson.id}`);
1237
+ if (lesson.probationStartedAtSupportCount !== void 0) {
1238
+ throw new Error(`STRATEGY_PROBATION_METADATA:${lesson.id}`);
1239
+ }
1240
+ return;
1241
+ }
1242
+ if (!matchesExecutionDefinition(lesson, lesson.supersedesLessonId !== void 0, false)) {
1243
+ throw new Error(`EXECUTION_DEFINITION_INVALID:${lesson.id}`);
1244
+ }
1245
+ if (lesson.status === "candidate" && counters > 0) throw new Error(`EXECUTION_CANDIDATE_WITH_COUNTER:${lesson.id}`);
1246
+ if (lesson.status === "probation") {
1247
+ if (supports < 3 || dates < 2 || counters > 0 || lesson.probationStartedAtSupportCount === void 0 || lesson.probationStartedAtSupportCount < 3 || lesson.probationStartedAtSupportCount > supports) {
1248
+ throw new Error(`EXECUTION_PROBATION_UNREACHABLE:${lesson.id}`);
1249
+ }
1250
+ }
1251
+ if (lesson.status === "active") {
1252
+ const started = lesson.probationStartedAtSupportCount;
1253
+ if (started === void 0 || started < 3 || supports - started < 2 || dates < 2 || counters >= 2) {
1254
+ throw new Error(`EXECUTION_ACTIVE_UNREACHABLE:${lesson.id}`);
1255
+ }
1256
+ }
1257
+ if (lesson.status === "contested" && counters < 1) {
1258
+ throw new Error(`EXECUTION_CONTESTED_WITHOUT_COUNTER:${lesson.id}`);
1259
+ }
1260
+ if (lesson.status === "candidate" && lesson.probationStartedAtSupportCount !== void 0) {
1261
+ throw new Error(`EXECUTION_PROBATION_METADATA_INVALID:${lesson.id}`);
1262
+ }
1263
+ }
1264
+ function validateState(state) {
1265
+ uniqueValues(state.evidence.lessons.map((lesson) => lesson.id), "DUPLICATE_LESSON_ID");
1266
+ uniqueValues(state.suggestions.suggestions.map((item) => item.id), "DUPLICATE_SUGGESTION_ID");
1267
+ uniqueValues(state.ledger.entries.map((entry2) => entry2.debriefId), "DUPLICATE_LEDGER_DEBRIEF");
1268
+ uniqueValues(state.ledger.entries.map((entry2) => entry2.gameId), "DUPLICATE_LEDGER_GAME");
1269
+ uniqueValues(state.ledger.legacyGameIds, "DUPLICATE_LEGACY_LEDGER_GAME");
1270
+ if (state.ledger.entries.some((entry2) => state.ledger.legacyGameIds.includes(entry2.gameId))) {
1271
+ throw new Error("LEGACY_LEDGER_GAME_OVERLAP");
1272
+ }
1273
+ uniqueValues(state.incidents.incidents.map((entry2) => entry2.debriefId), "DUPLICATE_INCIDENT_DEBRIEF");
1274
+ const ledgerByDebrief = new Map(state.ledger.entries.map((entry2) => [entry2.debriefId, entry2]));
1275
+ const sampleGames = /* @__PURE__ */ new Set();
1276
+ for (const lesson of state.evidence.lessons) {
1277
+ const supports = lesson.supportGames.map((sample2) => sample2.gameId);
1278
+ const counters = lesson.counterGames.map((sample2) => sample2.gameId);
1279
+ uniqueValues(supports, `DUPLICATE_SUPPORT_GAME:${lesson.id}`);
1280
+ uniqueValues(counters, `DUPLICATE_COUNTER_GAME:${lesson.id}`);
1281
+ if (supports.some((gameId) => counters.includes(gameId))) throw new Error(`SUPPORT_COUNTER_OVERLAP:${lesson.id}`);
1282
+ validateLessonReachability(lesson);
1283
+ for (const sample2 of [...lesson.supportGames, ...lesson.counterGames]) {
1284
+ if (sampleGames.has(sample2.gameId)) throw new Error(`GAME_SAMPLE_REUSED:${sample2.gameId}`);
1285
+ sampleGames.add(sample2.gameId);
1286
+ }
1287
+ for (const sample2 of lesson.supportGames) {
1288
+ validateSampleRefs(sample2, /* @__PURE__ */ new Set(["NEW", "SUPPORT", "REFINE"]), ledgerByDebrief);
1289
+ }
1290
+ for (const sample2 of lesson.counterGames) {
1291
+ validateSampleRefs(sample2, /* @__PURE__ */ new Set(["COUNTER"]), ledgerByDebrief);
1292
+ }
1293
+ }
1294
+ for (const incident of state.incidents.incidents) {
1295
+ const ledger = ledgerByDebrief.get(incident.debriefId);
1296
+ if (!ledger || ledger.gameId !== incident.gameId || ledger.action !== "INCIDENT") {
1297
+ throw new Error(`INCIDENT_LEDGER_MISMATCH:${incident.debriefId}`);
1298
+ }
1299
+ }
1300
+ const lessonById = new Map(state.evidence.lessons.map((lesson) => [lesson.id, lesson]));
1301
+ for (const suggestion of state.suggestions.suggestions) {
1302
+ const lesson = lessonById.get(suggestion.lessonId);
1303
+ if (!lesson || lesson.risk !== "strategy" || lesson.profile !== suggestion.profile) {
1304
+ throw new Error(`SUGGESTION_LESSON_MISMATCH:${suggestion.id}`);
1305
+ }
1306
+ if (suggestion.trigger !== lesson.trigger || suggestion.rule !== lesson.rule || suggestion.boundary !== lesson.boundary) {
1307
+ throw new Error(`SUGGESTION_SEMANTICS_MISMATCH:${suggestion.id}`);
1308
+ }
1309
+ if (suggestion.supportCount !== lesson.supportGames.length || suggestion.counterCount !== lesson.counterGames.length) {
1310
+ throw new Error(`SUGGESTION_COUNT_MISMATCH:${suggestion.id}`);
1311
+ }
1312
+ const sourceSet = new Set(lesson.supportGames.map((sample2) => sample2.source));
1313
+ if (suggestion.supportCount < 5 || independentDates(lesson.supportGames) < 2 || !sourceSet.has("SELF") || !sourceSet.has("OBSERVED") && !sourceSet.has("EXEMPLAR")) {
1314
+ throw new Error(`SUGGESTION_THRESHOLD_UNREACHABLE:${suggestion.id}`);
1315
+ }
1316
+ if ((suggestion.status === "pending" || suggestion.status === "accepted") && suggestion.counterCount > 0) {
1317
+ throw new Error(`SUGGESTION_LIVE_WITH_COUNTER:${suggestion.id}`);
1318
+ }
1319
+ if ((suggestion.status === "pending" || suggestion.status === "accepted") && lesson.status !== "candidate") {
1320
+ throw new Error(`SUGGESTION_LIVE_LESSON_STATUS:${suggestion.id}`);
1321
+ }
1322
+ if (suggestion.status === "pending" && (suggestion.decidedAt || suggestion.decidedBy || suggestion.pausedAt || suggestion.pauseReason)) {
1323
+ throw new Error(`SUGGESTION_PENDING_METADATA:${suggestion.id}`);
1324
+ }
1325
+ if ((suggestion.status === "accepted" || suggestion.status === "rejected" || suggestion.status === "paused") && (!suggestion.decidedAt || !suggestion.decidedBy)) {
1326
+ throw new Error(`SUGGESTION_DECISION_METADATA_MISSING:${suggestion.id}`);
1327
+ }
1328
+ if ((suggestion.status === "accepted" || suggestion.status === "rejected") && (suggestion.pausedAt || suggestion.pauseReason)) {
1329
+ throw new Error(`SUGGESTION_DECISION_METADATA_INVALID:${suggestion.id}`);
1330
+ }
1331
+ if (suggestion.status === "paused" && (!suggestion.pausedAt || !suggestion.pauseReason || suggestion.counterCount !== 1 || lesson.status !== "contested")) {
1332
+ throw new Error(`SUGGESTION_PAUSE_UNREACHABLE:${suggestion.id}`);
1333
+ }
1334
+ if (suggestion.status === "withdrawn" && (!suggestion.decidedAt || suggestion.counterCount < 2 && lesson.status !== "archived" || suggestion.counterCount >= 2 && lesson.status !== "contested")) {
1335
+ throw new Error(`SUGGESTION_WITHDRAWAL_UNREACHABLE:${suggestion.id}`);
1336
+ }
1337
+ }
1338
+ for (const lesson of state.evidence.lessons) {
1339
+ if (lesson.supersedesLessonId) {
1340
+ const prior = lessonById.get(lesson.supersedesLessonId);
1341
+ if (!prior || prior.id === lesson.id || prior.supersededByLessonId !== lesson.id || prior.status !== "archived" || prior.profile !== lesson.profile || prior.risk !== lesson.risk || prior.phase !== lesson.phase || prior.role !== lesson.role || prior.players !== lesson.players || prior.actionType !== lesson.actionType || prior.decisionType !== lesson.decisionType || prior.executionOperation !== lesson.executionOperation || semanticValue(prior.rule) !== semanticValue(lesson.rule) || semanticValue(`${prior.trigger} ${prior.boundary}`) === semanticValue(`${lesson.trigger} ${lesson.boundary}`)) {
1342
+ throw new Error(`LESSON_SUPERSESSION_INVALID:${lesson.id}`);
1343
+ }
1344
+ }
1345
+ if (lesson.supersededByLessonId) {
1346
+ const next = lessonById.get(lesson.supersededByLessonId);
1347
+ if (!next || next.id === lesson.id || next.supersedesLessonId !== lesson.id || lesson.status !== "archived" || next.profile !== lesson.profile || next.risk !== lesson.risk) {
1348
+ throw new Error(`LESSON_SUPERSESSION_INVALID:${lesson.id}`);
1349
+ }
1350
+ }
1351
+ const visited = /* @__PURE__ */ new Set([lesson.id]);
1352
+ let cursor = lesson;
1353
+ while (cursor.supersededByLessonId) {
1354
+ if (visited.has(cursor.supersededByLessonId)) throw new Error(`LESSON_SUPERSESSION_CYCLE:${lesson.id}`);
1355
+ visited.add(cursor.supersededByLessonId);
1356
+ cursor = lessonById.get(cursor.supersededByLessonId);
1357
+ }
1358
+ }
1359
+ const sampledDebriefs = new Set(sampleGames.size > 0 ? state.evidence.lessons.flatMap((lesson) => [...lesson.supportGames, ...lesson.counterGames].map((sample2) => sample2.debriefId)) : []);
1360
+ const incidentDebriefs = new Set(state.incidents.incidents.map((incident) => incident.debriefId));
1361
+ for (const entry2 of state.ledger.entries) {
1362
+ if (["NEW", "SUPPORT", "COUNTER", "REFINE"].includes(entry2.action) && !sampledDebriefs.has(entry2.debriefId)) {
1363
+ throw new Error(`LEDGER_SAMPLE_MISSING:${entry2.debriefId}`);
1364
+ }
1365
+ if (entry2.action === "INCIDENT" && !incidentDebriefs.has(entry2.debriefId)) {
1366
+ throw new Error(`LEDGER_INCIDENT_MISSING:${entry2.debriefId}`);
1367
+ }
1368
+ if (entry2.action === "SKIP" && (sampledDebriefs.has(entry2.debriefId) || incidentDebriefs.has(entry2.debriefId))) {
1369
+ throw new Error(`LEDGER_SKIP_HAS_MUTATION:${entry2.debriefId}`);
1370
+ }
1371
+ }
1372
+ const profiles = new Set(state.evidence.lessons.map((lesson) => lesson.profile));
1373
+ for (const profile of profiles) {
1374
+ const records = state.evidence.lessons.filter((lesson) => lesson.profile === profile);
1375
+ if (records.filter((lesson) => lesson.status === "candidate").length > 12 || records.filter((lesson) => lesson.status === "active").length > 6 || records.filter((lesson) => lesson.status === "probation").length > 1) {
1376
+ throw new Error(`PROFILE_LIMIT_EXCEEDED:${profile}`);
1377
+ }
1378
+ }
1379
+ }
1380
+ function oneLine(block, pattern, label) {
1381
+ const matches = [...block.matchAll(pattern)];
1382
+ if (matches.length !== 1) throw new Error(`RUNTIME_FIELD_INVALID:${label}`);
1383
+ return matches[0];
1384
+ }
1385
+ function inspectRuntimeProjection(content) {
1386
+ if (content.includes(LEGACY_RUNTIME_START) || content.includes(LEGACY_RUNTIME_END)) {
1387
+ throw new Error("LEGACY_RUNTIME_REQUIRES_MIGRATION");
1388
+ }
1389
+ const starts = content.split(RUNTIME_START).length - 1;
1390
+ const ends = content.split(RUNTIME_END).length - 1;
1391
+ if (starts === 0 && ends === 0) return null;
1392
+ if (starts !== 1 || ends !== 1) throw new Error("RUNTIME_MARKERS_INVALID");
1393
+ const startIndex = content.indexOf(RUNTIME_START);
1394
+ const endMarkerIndex = content.indexOf(RUNTIME_END);
1395
+ if (startIndex < 0 || endMarkerIndex <= startIndex) throw new Error("RUNTIME_MARKERS_INVALID");
1396
+ const endIndex = endMarkerIndex + RUNTIME_END.length;
1397
+ const block = content.slice(startIndex, endIndex);
1398
+ if (block.length > MAX_RUNTIME_CHARS) throw new Error("RUNTIME_TOO_LARGE");
1399
+ const heading = oneLine(block, /^## werewolf-play runtime v1[ \t]*\r?$/gm, "heading");
1400
+ const version = oneLine(block, /^runtime_version:[ \t]*(\S+)[ \t]*\r?$/gm, "version");
1401
+ const profile = oneLine(block, /^active_profile:[ \t]*(\S+)[ \t]*\r?$/gm, "profile");
1402
+ const contract = oneLine(block, /^### GAME_EVENT execution contract[ \t]*\r?$/gm, "contract");
1403
+ const playbook = oneLine(block, /^### active profile playbook[ \t]*\r?$/gm, "playbook");
1404
+ const lessons = oneLine(block, /^### active lessons[ \t]*\r?$/gm, "lessons");
1405
+ const order = [heading.index, version.index, profile.index, contract.index, playbook.index, lessons.index];
1406
+ if (version[1] !== "1" || !SAFE_PROFILE3.test(profile[1]) || !order.every((value, index) => index === 0 || value > order[index - 1])) {
1407
+ throw new Error("RUNTIME_STRUCTURE_INVALID");
1408
+ }
1409
+ const playbookBodyStart = playbook.index + playbook[0].length;
1410
+ const playbookBodyEnd = lessons.index;
1411
+ const lessonsBodyStart = lessons.index + lessons[0].length;
1412
+ const lessonsBodyEnd = block.length - RUNTIME_END.length;
1413
+ const playbookText = block.slice(playbookBodyStart, playbookBodyEnd).trim();
1414
+ const lessonsText = block.slice(lessonsBodyStart, lessonsBodyEnd).trim();
1415
+ if (!block.slice(contract.index + contract[0].length, playbook.index).trim() || !playbookText || !lessonsText) throw new Error("RUNTIME_BODY_INVALID");
1416
+ return {
1417
+ startIndex,
1418
+ endIndex,
1419
+ block,
1420
+ activeProfile: profile[1],
1421
+ playbook: playbookText,
1422
+ lessons: lessonsText,
1423
+ playbookBodyStart,
1424
+ playbookBodyEnd,
1425
+ lessonsBodyStart,
1426
+ lessonsBodyEnd
1427
+ };
1428
+ }
1429
+ function readWorkspaceState(paths, agentsTextOverride) {
1430
+ const state = {
1431
+ evidence: readOrDefault(paths.evidence, emptyEvidence, "evidence", evidenceSchema),
1432
+ incidents: readOrDefault(paths.incidents, emptyIncidents, "incidents", incidentsSchema),
1433
+ suggestions: readOrDefault(paths.suggestions, emptySuggestions, "suggestions", suggestionsSchema),
1434
+ ledger: readOrDefault(paths.ledger, emptyLedger, "ledger", ledgerSchema),
1435
+ agentsText: agentsTextOverride ?? (existsSync(paths.agents) ? readFileSync(paths.agents, "utf8") : "")
1436
+ };
1437
+ validateState(state);
1438
+ inspectRuntimeProjection(state.agentsText);
1439
+ return state;
1440
+ }
1441
+ function renderEvidence(value) {
1442
+ return renderManaged("werewolf evidence v3", value);
1443
+ }
1444
+ function renderIncidents(value) {
1445
+ return renderManaged("werewolf incidents", value);
1446
+ }
1447
+ function renderSuggestions(value) {
1448
+ return renderManaged("werewolf suggestions", value);
1449
+ }
1450
+ function renderLedger(value) {
1451
+ return renderManaged("werewolf evolution ledger", value);
1452
+ }
1453
+ function renderRuntimeLessons(state, activeProfile) {
1454
+ const records = state.evidence.lessons.filter((lesson) => lesson.profile === activeProfile && lesson.risk === "execution" && (lesson.status === "active" || lesson.status === "probation"));
1455
+ const active = records.filter((lesson) => lesson.status === "active").sort((left, right) => right.lastReviewed.localeCompare(left.lastReviewed)).slice(0, 6);
1456
+ const probation = records.filter((lesson) => lesson.status === "probation").sort((left, right) => right.lastReviewed.localeCompare(left.lastReviewed)).slice(0, 1);
1457
+ if (active.length === 0 && probation.length === 0) return "none";
1458
+ const lines = [];
1459
+ for (const lesson of [...active, ...probation]) {
1460
+ if (lines.length > 0) lines.push("");
1461
+ lines.push(
1462
+ `**\u6807\u7B7E**\uFF1Aid=${lesson.id} | status=${lesson.status} | risk=execution | profile=${lesson.profile} | phase=${lesson.phase} | role=${lesson.role} | players=${lesson.players}`,
1463
+ `**\u89E6\u53D1**\uFF1A${lesson.trigger}`,
1464
+ `**\u89C4\u5219**\uFF1A${lesson.rule}`,
1465
+ `**\u8FB9\u754C**\uFF1A${lesson.boundary}`
1466
+ );
1467
+ }
1468
+ return lines.join("\n");
1469
+ }
1470
+ function projectRuntime(state) {
1471
+ const runtime = inspectRuntimeProjection(state.agentsText);
1472
+ if (!runtime) return state.agentsText;
1473
+ const lessons = renderRuntimeLessons(state, runtime.activeProfile);
1474
+ if (runtime.lessons === lessons.trim()) return state.agentsText;
1475
+ const nextBlock = `${runtime.block.slice(0, runtime.lessonsBodyStart)}
1476
+
1477
+ ${lessons}
1478
+ ${runtime.block.slice(runtime.lessonsBodyEnd)}`;
1479
+ return `${state.agentsText.slice(0, runtime.startIndex)}${nextBlock}${state.agentsText.slice(runtime.endIndex)}`;
1480
+ }
1481
+ function projectProfilePlaybook(agentsText, expectedProfile, body) {
1482
+ const runtime = inspectRuntimeProjection(agentsText);
1483
+ if (!runtime || runtime.activeProfile !== expectedProfile) return agentsText;
1484
+ if (runtime.playbook === body.trim()) return agentsText;
1485
+ const nextBlock = `${runtime.block.slice(0, runtime.playbookBodyStart)}
1486
+
1487
+ ${body.trim()}
1488
+
1489
+ ${runtime.block.slice(runtime.playbookBodyEnd)}`;
1490
+ return `${agentsText.slice(0, runtime.startIndex)}${nextBlock}${agentsText.slice(runtime.endIndex)}`;
1491
+ }
1492
+ function workspaceChanges(paths, state) {
1493
+ const changes = /* @__PURE__ */ new Map([
1494
+ [paths.evidence, renderEvidence(state.evidence)],
1495
+ [paths.incidents, renderIncidents(state.incidents)],
1496
+ [paths.suggestions, renderSuggestions(state.suggestions)],
1497
+ [paths.ledger, renderLedger(state.ledger)]
1498
+ ]);
1499
+ const projected = projectRuntime(state);
1500
+ const currentAgents = existsSync(paths.agents) ? readFileSync(paths.agents, "utf8") : "";
1501
+ if (projected !== currentAgents) changes.set(paths.agents, projected);
1502
+ return changes;
1503
+ }
1504
+ function verifyWorkspaceDocuments(paths) {
1505
+ const state = readWorkspaceState(paths);
1506
+ if (inspectRuntimeProjection(state.agentsText) && projectRuntime(state) !== state.agentsText) {
1507
+ throw new Error("RUNTIME_PROJECTION_MISMATCH");
1508
+ }
1509
+ }
1510
+
212
1511
  // src/profile.ts
213
- import { existsSync, lstatSync, readFileSync } from "fs";
1512
+ import { existsSync as existsSync2, lstatSync as lstatSync3, readFileSync as readFileSync2 } from "fs";
214
1513
  var OWNER_START = "<!-- WEREWOLF_OWNER_OVERRIDES_START -->";
215
1514
  var OWNER_END = "<!-- WEREWOLF_OWNER_OVERRIDES_END -->";
216
1515
  var MAX_PROFILE_CHARS = 5e3;
217
1516
  var RESERVED = /(?:WEREWOLF_RUNTIME_(?:START|END)|^runtime_version:|^active_profile:|^### (?:GAME_EVENT execution contract|active profile playbook|active lessons)\s*$)/m;
218
1517
  function readRegularFile(file) {
219
- if (!existsSync(file)) return void 0;
220
- if (!lstatSync(file).isFile() || lstatSync(file).isSymbolicLink()) throw new Error(`PROFILE_SOURCE_INVALID:${file}`);
221
- return readFileSync(file, "utf8");
1518
+ if (!existsSync2(file)) return void 0;
1519
+ if (!lstatSync3(file).isFile() || lstatSync3(file).isSymbolicLink()) throw new Error(`PROFILE_SOURCE_INVALID:${file}`);
1520
+ return readFileSync2(file, "utf8");
222
1521
  }
223
1522
  function stripOwnerSection(body) {
224
1523
  const starts = body.split(OWNER_START).length - 1;
@@ -318,6 +1617,411 @@ function verifyProfileOverride(file, profile, expectedContent) {
318
1617
  parseProfileMarkdown(content, profile);
319
1618
  }
320
1619
 
1620
+ // src/owner-binding.ts
1621
+ import { existsSync as existsSync3, lstatSync as lstatSync4, readFileSync as readFileSync3 } from "fs";
1622
+ import { z as z4 } from "zod";
1623
+ var OWNER = /^(clawtopia|coolclaw):human:([1-9][0-9]*)$/;
1624
+ var ownerBindingSchema = z4.object({
1625
+ schemaVersion: z4.literal(1),
1626
+ channelId: z4.enum(["clawtopia", "coolclaw"]),
1627
+ ownerSenderId: z4.string().regex(OWNER),
1628
+ boundAt: z4.iso.datetime({ offset: true }),
1629
+ updatedAt: z4.iso.datetime({ offset: true })
1630
+ }).strict();
1631
+ function normalizeOwnerSenderId(value) {
1632
+ const normalized = value.trim().toLowerCase();
1633
+ if (!OWNER.test(normalized)) {
1634
+ throw new Error("OWNER_ID_INVALID");
1635
+ }
1636
+ return normalized;
1637
+ }
1638
+ function verifyOwnerBinding(value) {
1639
+ const parsed = ownerBindingSchema.safeParse(value);
1640
+ if (!parsed.success) throw new Error(`WORKSPACE_OWNER_BINDING_INVALID:${parsed.error.message}`);
1641
+ if (!parsed.data.ownerSenderId.startsWith(`${parsed.data.channelId}:`)) {
1642
+ throw new Error("WORKSPACE_OWNER_CHANNEL_MISMATCH");
1643
+ }
1644
+ return parsed.data;
1645
+ }
1646
+ function readOwnerBinding(paths) {
1647
+ assertSafeWorkspacePath(paths.ownerBinding, paths);
1648
+ if (!existsSync3(paths.ownerBinding)) return void 0;
1649
+ const stat = lstatSync4(paths.ownerBinding);
1650
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("WORKSPACE_OWNER_BINDING_INVALID");
1651
+ try {
1652
+ return verifyOwnerBinding(JSON.parse(readFileSync3(paths.ownerBinding, "utf8")));
1653
+ } catch (error) {
1654
+ if (error instanceof SyntaxError) throw new Error(`WORKSPACE_OWNER_BINDING_INVALID:${error.message}`);
1655
+ throw error;
1656
+ }
1657
+ }
1658
+ function assertWorkspaceOwner(paths, owner) {
1659
+ const expected = normalizeOwnerSenderId(owner);
1660
+ const binding = readOwnerBinding(paths);
1661
+ if (!binding) throw new Error("WORKSPACE_OWNER_BINDING_MISSING");
1662
+ if (binding.ownerSenderId !== expected) throw new Error("WORKSPACE_OWNER_MISMATCH");
1663
+ return binding;
1664
+ }
1665
+ function isWorkspaceOwner(paths, channelId, senderId) {
1666
+ if (!senderId || channelId !== "clawtopia" && channelId !== "coolclaw") return false;
1667
+ try {
1668
+ const owner = normalizeOwnerSenderId(senderId);
1669
+ return owner.startsWith(`${channelId}:`) && readOwnerBinding(paths)?.ownerSenderId === owner;
1670
+ } catch {
1671
+ return false;
1672
+ }
1673
+ }
1674
+
1675
+ // src/migration.ts
1676
+ import {
1677
+ existsSync as existsSync5,
1678
+ lstatSync as lstatSync6,
1679
+ mkdirSync as mkdirSync3,
1680
+ readFileSync as readFileSync5,
1681
+ readdirSync,
1682
+ renameSync as renameSync2
1683
+ } from "fs";
1684
+ import path3 from "path";
1685
+ import { z as z6 } from "zod";
1686
+
1687
+ // src/transaction.ts
1688
+ import { randomUUID } from "crypto";
1689
+ import {
1690
+ closeSync,
1691
+ existsSync as existsSync4,
1692
+ fsyncSync,
1693
+ lstatSync as lstatSync5,
1694
+ mkdirSync as mkdirSync2,
1695
+ openSync,
1696
+ readFileSync as readFileSync4,
1697
+ renameSync,
1698
+ rmSync,
1699
+ writeSync
1700
+ } from "fs";
1701
+ import path2 from "path";
1702
+ import { z as z5 } from "zod";
1703
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
1704
+ var HASH2 = /^[a-f0-9]{64}$/;
1705
+ var journalSchema = z5.object({
1706
+ schemaVersion: z5.literal(1),
1707
+ id: z5.string().regex(UUID),
1708
+ state: z5.enum(["prepared", "committing", "committed"]),
1709
+ committedCount: z5.number().int().nonnegative(),
1710
+ files: z5.array(z5.object({
1711
+ target: z5.string().min(1),
1712
+ temp: z5.string().min(1),
1713
+ backup: z5.string().min(1),
1714
+ beforeExists: z5.boolean(),
1715
+ beforeHash: z5.string().regex(HASH2).optional(),
1716
+ newHash: z5.string().regex(HASH2)
1717
+ }).strict()).min(1).max(32)
1718
+ }).strict();
1719
+ function readLock(paths) {
1720
+ const parsed = JSON.parse(readFileSync4(paths.lock, "utf8"));
1721
+ const checked = z5.object({
1722
+ pid: z5.number().int().positive(),
1723
+ token: z5.string().regex(UUID),
1724
+ createdAt: z5.number().int().nonnegative()
1725
+ }).strict().safeParse(parsed);
1726
+ if (!checked.success) throw new Error("EVOLUTION_WORKSPACE_LOCK_INVALID");
1727
+ return checked.data;
1728
+ }
1729
+ var STALE_LOCK_MIN_AGE_MS = 10 * 60 * 1e3;
1730
+ function assertSetupLockAccess(paths, setupLock) {
1731
+ if (!existsSync4(paths.setupLock)) return;
1732
+ const current = readLockFile(paths.setupLock, "EVOLUTION_SETUP_LOCK_INVALID");
1733
+ if (setupLock?.file === paths.setupLock && setupLock.token === current.token) return;
1734
+ throw new Error("EVOLUTION_SETUP_LOCKED");
1735
+ }
1736
+ function readLockFile(file, invalidCode) {
1737
+ const stat = lstatSync5(file);
1738
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(invalidCode);
1739
+ const parsed = JSON.parse(readFileSync4(file, "utf8"));
1740
+ const checked = z5.object({
1741
+ pid: z5.number().int().positive(),
1742
+ token: z5.string().regex(UUID),
1743
+ createdAt: z5.number().int().nonnegative()
1744
+ }).strict().safeParse(parsed);
1745
+ if (!checked.success) throw new Error(invalidCode);
1746
+ return checked.data;
1747
+ }
1748
+ function acquireLock(paths, setupLock) {
1749
+ assertSafeWorkspacePath(paths.lock, paths);
1750
+ assertSetupLockAccess(paths, setupLock);
1751
+ const token = randomUUID();
1752
+ try {
1753
+ const fd = openSync(paths.lock, "wx", 384);
1754
+ writeSync(fd, JSON.stringify({ pid: process.pid, token, createdAt: Date.now() }));
1755
+ fsyncSync(fd);
1756
+ return { fd, token };
1757
+ } catch (error) {
1758
+ if (error.code !== "EEXIST") throw error;
1759
+ readLock(paths);
1760
+ throw new Error("EVOLUTION_WORKSPACE_LOCKED");
1761
+ }
1762
+ }
1763
+ function releaseLock(paths, lock) {
1764
+ try {
1765
+ closeSync(lock.fd);
1766
+ } finally {
1767
+ try {
1768
+ assertSafeWorkspacePath(paths.lock, paths);
1769
+ if (readLock(paths).token === lock.token) rmSync(paths.lock, { force: true });
1770
+ } catch {
1771
+ }
1772
+ }
1773
+ }
1774
+ function syncDirectory(directory) {
1775
+ let fd;
1776
+ try {
1777
+ fd = openSync(directory, "r");
1778
+ fsyncSync(fd);
1779
+ } finally {
1780
+ if (fd !== void 0) closeSync(fd);
1781
+ }
1782
+ }
1783
+ function writeSynced(file, content) {
1784
+ mkdirSync2(path2.dirname(file), { recursive: true, mode: 448 });
1785
+ const fd = openSync(file, "wx", 384);
1786
+ try {
1787
+ writeSync(fd, content, void 0, "utf8");
1788
+ fsyncSync(fd);
1789
+ } finally {
1790
+ closeSync(fd);
1791
+ }
1792
+ }
1793
+ function expectedArtifacts(target, id) {
1794
+ const suffix = `.werewolf-evolution-${id}`;
1795
+ return { temp: `${target}${suffix}.tmp`, backup: `${target}${suffix}.bak` };
1796
+ }
1797
+ function validateJournal(paths, raw) {
1798
+ const parsed = journalSchema.safeParse(raw);
1799
+ if (!parsed.success) throw new Error(`TRANSACTION_JOURNAL_INVALID:${parsed.error.message}`);
1800
+ const journal = parsed.data;
1801
+ if (journal.committedCount > journal.files.length || journal.state === "prepared" && journal.committedCount !== 0 || journal.state === "committed" && journal.committedCount !== journal.files.length) {
1802
+ throw new Error("TRANSACTION_JOURNAL_PROGRESS_INVALID");
1803
+ }
1804
+ const targets = /* @__PURE__ */ new Set();
1805
+ for (const item of journal.files) {
1806
+ assertFixedTarget(item.target, paths);
1807
+ if (targets.has(item.target)) throw new Error("TRANSACTION_TARGET_DUPLICATED");
1808
+ targets.add(item.target);
1809
+ if (item.beforeExists !== Boolean(item.beforeHash)) throw new Error("TRANSACTION_BEFORE_HASH_INVALID");
1810
+ const expected = expectedArtifacts(item.target, journal.id);
1811
+ if (item.temp !== expected.temp || item.backup !== expected.backup) {
1812
+ throw new Error("TRANSACTION_ARTIFACT_PATH_INVALID");
1813
+ }
1814
+ assertSafeWorkspacePath(item.temp, paths);
1815
+ assertSafeWorkspacePath(item.backup, paths);
1816
+ }
1817
+ return journal;
1818
+ }
1819
+ function readJournal(paths) {
1820
+ try {
1821
+ return validateJournal(paths, JSON.parse(readFileSync4(paths.journal, "utf8")));
1822
+ } catch (error) {
1823
+ if (error instanceof SyntaxError) throw new Error(`TRANSACTION_JOURNAL_INVALID:${error.message}`);
1824
+ throw error;
1825
+ }
1826
+ }
1827
+ function writeJournal(paths, journal) {
1828
+ validateJournal(paths, journal);
1829
+ const swap = `${paths.journal}.${journal.id}.tmp`;
1830
+ assertSafeWorkspacePath(swap, paths);
1831
+ rmSync(swap, { force: true });
1832
+ writeSynced(swap, JSON.stringify(journal, null, 2));
1833
+ renameSync(swap, paths.journal);
1834
+ syncDirectory(paths.memory);
1835
+ }
1836
+ function hashFile(file) {
1837
+ return sha256(readFileSync4(file));
1838
+ }
1839
+ function removeArtifacts(paths, journal) {
1840
+ validateJournal(paths, journal);
1841
+ for (const item of journal.files) {
1842
+ rmSync(item.temp, { force: true });
1843
+ rmSync(item.backup, { force: true });
1844
+ }
1845
+ rmSync(paths.journal, { force: true });
1846
+ syncDirectory(paths.memory);
1847
+ }
1848
+ function rollback(paths, journal) {
1849
+ validateJournal(paths, journal);
1850
+ for (let index = journal.files.length - 1; index >= 0; index--) {
1851
+ const item = journal.files[index];
1852
+ if (existsSync4(item.backup)) {
1853
+ const backupStat = lstatSync5(item.backup);
1854
+ if (!item.beforeExists || !item.beforeHash || !backupStat.isFile() || backupStat.isSymbolicLink() || hashFile(item.backup) !== item.beforeHash) {
1855
+ throw new Error(`TRANSACTION_BACKUP_HASH_MISMATCH:${item.target}`);
1856
+ }
1857
+ rmSync(item.target, { force: true });
1858
+ renameSync(item.backup, item.target);
1859
+ } else if (!item.beforeExists) {
1860
+ rmSync(item.target, { force: true });
1861
+ } else if (!existsSync4(item.target) || hashFile(item.target) !== item.beforeHash) {
1862
+ throw new Error(`TRANSACTION_ROLLBACK_SOURCE_MISSING:${item.target}`);
1863
+ }
1864
+ rmSync(item.temp, { force: true });
1865
+ }
1866
+ rmSync(paths.journal, { force: true });
1867
+ syncDirectory(paths.memory);
1868
+ syncDirectory(paths.root);
1869
+ }
1870
+ function recoverTransactionLocked(paths) {
1871
+ if (!existsSync4(paths.journal)) return "none";
1872
+ const journal = readJournal(paths);
1873
+ const allNew = journal.files.every((item) => existsSync4(item.target) && !lstatSync5(item.target).isSymbolicLink() && hashFile(item.target) === item.newHash);
1874
+ if (journal.state === "committed" && allNew) {
1875
+ removeArtifacts(paths, journal);
1876
+ return "completed";
1877
+ }
1878
+ rollback(paths, journal);
1879
+ return "rolled-back";
1880
+ }
1881
+ function commitLocked(paths, changes, verify, hooks) {
1882
+ if (changes.size === 0) return;
1883
+ const id = randomUUID();
1884
+ const files = [];
1885
+ for (const [target, content] of changes) {
1886
+ assertFixedTarget(target, paths);
1887
+ const beforeExists = existsSync4(target);
1888
+ const artifacts = expectedArtifacts(target, id);
1889
+ rmSync(artifacts.temp, { force: true });
1890
+ rmSync(artifacts.backup, { force: true });
1891
+ writeSynced(artifacts.temp, content);
1892
+ files.push({
1893
+ target,
1894
+ ...artifacts,
1895
+ beforeExists,
1896
+ ...beforeExists ? { beforeHash: hashFile(target) } : {},
1897
+ newHash: sha256(content)
1898
+ });
1899
+ }
1900
+ const journal = {
1901
+ schemaVersion: 1,
1902
+ id,
1903
+ state: "prepared",
1904
+ committedCount: 0,
1905
+ files
1906
+ };
1907
+ writeJournal(paths, journal);
1908
+ journal.state = "committing";
1909
+ writeJournal(paths, journal);
1910
+ try {
1911
+ for (let index = 0; index < files.length; index++) {
1912
+ const item = files[index];
1913
+ if (item.beforeExists) renameSync(item.target, item.backup);
1914
+ renameSync(item.temp, item.target);
1915
+ syncDirectory(path2.dirname(item.target));
1916
+ journal.committedCount = index + 1;
1917
+ writeJournal(paths, journal);
1918
+ hooks.afterRename?.(journal.committedCount);
1919
+ }
1920
+ verify();
1921
+ for (const item of files) {
1922
+ if (!existsSync4(item.target) || lstatSync5(item.target).isSymbolicLink() || hashFile(item.target) !== item.newHash) {
1923
+ throw new Error(`TRANSACTION_VERIFY_FAILED:${item.target}`);
1924
+ }
1925
+ }
1926
+ journal.state = "committed";
1927
+ writeJournal(paths, journal);
1928
+ removeArtifacts(paths, journal);
1929
+ } catch (error) {
1930
+ rollback(paths, journal);
1931
+ throw error;
1932
+ }
1933
+ }
1934
+ function runWorkspaceTransaction(paths, build, hooks = {}, setupLock) {
1935
+ const lock = acquireLock(paths, setupLock);
1936
+ try {
1937
+ recoverTransactionLocked(paths);
1938
+ const plan = build();
1939
+ commitLocked(paths, plan.changes, plan.verify ?? (() => void 0), hooks);
1940
+ return plan.result;
1941
+ } finally {
1942
+ releaseLock(paths, lock);
1943
+ }
1944
+ }
1945
+ function runWorkspaceRead(paths, read) {
1946
+ const lock = acquireLock(paths);
1947
+ try {
1948
+ recoverTransactionLocked(paths);
1949
+ return read();
1950
+ } finally {
1951
+ releaseLock(paths, lock);
1952
+ }
1953
+ }
1954
+
1955
+ // src/migration.ts
1956
+ var MIGRATION_DATA_START = "<!-- WEREWOLF_EVOLUTION_MIGRATION_DATA_START -->";
1957
+ var MIGRATION_DATA_END = "<!-- WEREWOLF_EVOLUTION_MIGRATION_DATA_END -->";
1958
+ var SAFE_VERSION = /^[0-9]+.[0-9]+.[0-9]+(?:-[0-9A-Za-z.-]+)?$/;
1959
+ var SAFE_GAME_ID = /^[0-9]{1,30}$/;
1960
+ var MAX_LEGACY_FILE_BYTES = 2 * 1024 * 1024;
1961
+ var sourceSchema = z6.object({
1962
+ kind: z6.enum(["evidence", "suggestions"]),
1963
+ sourcePath: z6.string().min(1),
1964
+ archivePath: z6.string().min(1),
1965
+ sha256: z6.string().regex(/^[a-f0-9]{64}$/),
1966
+ bytes: z6.number().int().nonnegative().max(MAX_LEGACY_FILE_BYTES),
1967
+ recognized: z6.boolean()
1968
+ }).strict();
1969
+ var migrationMarkerSchema = z6.object({
1970
+ schemaVersion: z6.literal(1),
1971
+ migrationVersion: z6.literal(3),
1972
+ evolutionVersion: z6.string().regex(SAFE_VERSION),
1973
+ skillVersion: z6.string().regex(SAFE_VERSION),
1974
+ migratedAt: z6.string().datetime({ offset: true }),
1975
+ legacyGameIds: z6.array(z6.string().regex(SAFE_GAME_ID)).max(1e5),
1976
+ sources: z6.array(sourceSchema).max(2),
1977
+ skillBackup: z6.string().min(1).optional(),
1978
+ warnings: z6.array(z6.string().regex(/^[A-Z][A-Z0-9_]{1,79}$/)).max(16)
1979
+ }).strict();
1980
+ function markerJson(content) {
1981
+ const start = content.indexOf(MIGRATION_DATA_START);
1982
+ const end = content.indexOf(MIGRATION_DATA_END);
1983
+ if (start < 0 || end <= start || content.indexOf(MIGRATION_DATA_START, start + 1) >= 0 || content.indexOf(MIGRATION_DATA_END, end + 1) >= 0) {
1984
+ throw new Error("MIGRATION_MARKERS_INVALID");
1985
+ }
1986
+ const block = content.slice(start + MIGRATION_DATA_START.length, end).trim();
1987
+ const match = /^```json[ \t]*\r?\n([\s\S]*)\r?\n```$/.exec(block);
1988
+ if (!match) throw new Error("MIGRATION_JSON_BLOCK_INVALID");
1989
+ try {
1990
+ return JSON.parse(match[1]);
1991
+ } catch (error) {
1992
+ throw new Error(`MIGRATION_JSON_INVALID:${String(error)}`);
1993
+ }
1994
+ }
1995
+ function readMigrationMarker(paths) {
1996
+ if (!existsSync5(paths.migrationMarker)) throw new Error("MIGRATION_REQUIRED");
1997
+ const stat = lstatSync6(paths.migrationMarker);
1998
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_LEGACY_FILE_BYTES) {
1999
+ throw new Error("MIGRATION_MARKER_INVALID");
2000
+ }
2001
+ const parsed = migrationMarkerSchema.safeParse(markerJson(readFileSync5(paths.migrationMarker, "utf8")));
2002
+ if (!parsed.success) throw new Error(`MIGRATION_SCHEMA_INVALID:${parsed.error.message}`);
2003
+ return parsed.data;
2004
+ }
2005
+ function assertWorkspaceSetupReady(paths, expectedVersion) {
2006
+ assertWorkspaceRootIdentity(paths);
2007
+ if (!readOwnerBinding(paths)) throw new Error("WORKSPACE_OWNER_BINDING_MISSING");
2008
+ const marker = readMigrationMarker(paths);
2009
+ if (existsSync5(paths.legacySkill)) throw new Error("LEGACY_SKILL_STILL_DISCOVERABLE");
2010
+ const metaPath = path3.join(paths.skill, "_meta.json");
2011
+ if (!existsSync5(metaPath) || lstatSync6(metaPath).isSymbolicLink() || !lstatSync6(metaPath).isFile()) {
2012
+ throw new Error("WEREWOLF_PLAY_NOT_INSTALLED");
2013
+ }
2014
+ let meta;
2015
+ try {
2016
+ meta = JSON.parse(readFileSync5(metaPath, "utf8"));
2017
+ } catch (error) {
2018
+ throw new Error(`WEREWOLF_PLAY_META_INVALID:${String(error)}`);
2019
+ }
2020
+ const parsed = z6.object({ version: z6.string() }).passthrough().safeParse(meta);
2021
+ if (!parsed.success || parsed.data.version !== expectedVersion) throw new Error("WEREWOLF_PLAY_VERSION_MISMATCH");
2022
+ return marker;
2023
+ }
2024
+
321
2025
  // src/state-machine.ts
322
2026
  var MAX_CANDIDATE = 12;
323
2027
  var MAX_ACTIVE = 6;
@@ -545,6 +2249,22 @@ function incidentReasons(envelope) {
545
2249
  return reasons;
546
2250
  }
547
2251
 
2252
+ // src/version.ts
2253
+ import { readFileSync as readFileSync6 } from "fs";
2254
+ import { fileURLToPath } from "url";
2255
+ import { z as z7 } from "zod";
2256
+ var cachedVersion;
2257
+ function getWerewolfEvolutionVersion() {
2258
+ if (cachedVersion) return cachedVersion;
2259
+ const packagePath = fileURLToPath(new URL("../package.json", import.meta.url));
2260
+ const parsed = z7.object({
2261
+ name: z7.literal("@clawtopia/werewolf-evolution"),
2262
+ version: z7.string().regex(/^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/)
2263
+ }).passthrough().parse(JSON.parse(readFileSync6(packagePath, "utf8")));
2264
+ cachedVersion = parsed.version;
2265
+ return cachedVersion;
2266
+ }
2267
+
548
2268
  // src/service.ts
549
2269
  function clone(value) {
550
2270
  return structuredClone(value);
@@ -699,6 +2419,38 @@ var WerewolfEvolutionService = class {
699
2419
  });
700
2420
  }
701
2421
  }
2422
+ bindPromptRun(ctx, config) {
2423
+ const pending = this.contexts.getPending(ctx.runId, ctx.sessionKey);
2424
+ const ordinary = ctx.runId ? this.ordinaryDirectMessages.get(ctx.runId) : void 0;
2425
+ const inbound = pending ?? ordinary;
2426
+ const channelId = inbound?.channelId;
2427
+ const accountId = inbound?.accountId;
2428
+ const senderId = inbound?.from;
2429
+ const globallyAuthorized = isExplicitConfiguredOwner(config, channelId, senderId);
2430
+ let workspaceAuthorized = false;
2431
+ if (globallyAuthorized && ctx.workspaceDir && channelId && senderId) {
2432
+ try {
2433
+ workspaceAuthorized = isWorkspaceOwner(
2434
+ resolveWorkspacePaths(ctx.workspaceDir, false),
2435
+ channelId,
2436
+ senderId
2437
+ );
2438
+ } catch {
2439
+ workspaceAuthorized = false;
2440
+ }
2441
+ }
2442
+ this.bindAgentRun(
2443
+ {
2444
+ channelId,
2445
+ accountId,
2446
+ senderId,
2447
+ senderIsOwner: workspaceAuthorized
2448
+ },
2449
+ ctx,
2450
+ resolveAgentAccountBinding(config, channelId, accountId),
2451
+ workspaceAuthorized
2452
+ );
2453
+ }
702
2454
  buildPromptContext(ctx) {
703
2455
  const bound = this.contexts.getBound(ctx.runId, ctx.sessionKey);
704
2456
  if (!bound) {
@@ -1008,21 +2760,10 @@ function registerWerewolfEvolution(api, service = new WerewolfEvolutionService()
1008
2760
  api.on("message_received", (event, ctx) => {
1009
2761
  service.captureMessage(event, ctx);
1010
2762
  });
1011
- api.on("before_agent_run", (event, ctx) => {
1012
- const globallyAuthorized = isExplicitConfiguredOwner(api.config, event.channelId, event.senderId);
1013
- const workspaceAuthorized = globallyAuthorized && Boolean(ctx.workspaceDir) && isWorkspaceOwner(
1014
- resolveWorkspacePaths(ctx.workspaceDir, false),
1015
- event.channelId,
1016
- event.senderId
1017
- );
1018
- service.bindAgentRun(
1019
- event,
1020
- ctx,
1021
- resolveAgentAccountBinding(api.config, event.channelId, event.accountId),
1022
- workspaceAuthorized
1023
- );
2763
+ api.on("before_prompt_build", (_event, ctx) => {
2764
+ service.bindPromptRun(ctx, api.config);
2765
+ return service.buildPromptContext(ctx);
1024
2766
  });
1025
- api.on("before_prompt_build", (_event, ctx) => service.buildPromptContext(ctx));
1026
2767
  api.on("before_tool_call", (event, ctx) => service.beforeToolCall(event, ctx));
1027
2768
  }
1028
2769
  var entry = definePluginEntry({