@clawtopia/werewolf-evolution 0.1.19 → 2.0.0-alpha.18
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/README.md +37 -54
- package/bin/werewolf-evolution.mjs +69 -0
- package/package.json +12 -66
- package/skills/werewolf-evolution/SKILL.md +64 -0
- package/skills/werewolf-evolution/VERSION +1 -0
- package/skills/werewolf-evolution/scripts/evo.mjs +330 -0
- package/skills/werewolf-evolution/scripts/lib/api.mjs +24 -0
- package/skills/werewolf-evolution/scripts/lib/baseline.mjs +46 -0
- package/skills/werewolf-evolution/scripts/lib/brief.mjs +109 -0
- package/skills/werewolf-evolution/scripts/lib/context.mjs +46 -0
- package/skills/werewolf-evolution/scripts/lib/facts.mjs +155 -0
- package/skills/werewolf-evolution/scripts/lib/lessons.mjs +362 -0
- package/skills/werewolf-evolution/scripts/lib/metrics.mjs +57 -0
- package/skills/werewolf-evolution/scripts/lib/notify.mjs +22 -0
- package/skills/werewolf-evolution/scripts/lib/outcomes.mjs +119 -0
- package/skills/werewolf-evolution/scripts/lib/pool.mjs +70 -0
- package/skills/werewolf-evolution/scripts/lib/projection.mjs +155 -0
- package/skills/werewolf-evolution/scripts/lib/projector.mjs +139 -0
- package/skills/werewolf-evolution/scripts/lib/seat.mjs +42 -0
- package/skills/werewolf-evolution/scripts/lib/store.mjs +82 -0
- package/skills/werewolf-evolution/scripts/lib/sync.mjs +157 -0
- package/skills/werewolf-evolution/seeds.json +62 -0
- package/dist/index.d.ts +0 -294
- package/dist/index.js +0 -4160
- package/openclaw.plugin.json +0 -19
package/dist/index.js
DELETED
|
@@ -1,4160 +0,0 @@
|
|
|
1
|
-
// index.ts
|
|
2
|
-
import {
|
|
3
|
-
definePluginEntry,
|
|
4
|
-
emptyPluginConfigSchema
|
|
5
|
-
} from "openclaw/plugin-sdk/core";
|
|
6
|
-
|
|
7
|
-
// src/context-store.ts
|
|
8
|
-
import { createHash as createHash2 } from "crypto";
|
|
9
|
-
|
|
10
|
-
// src/types.ts
|
|
11
|
-
var DEBRIEF_HEADER = "[WEREWOLF_DEBRIEF v2]";
|
|
12
|
-
var DEBRIEF_POLICY_VERSION = "werewolf-debrief-v3";
|
|
13
|
-
var ENVELOPE_START = "== DEBRIEF_ENVELOPE_JSON ==";
|
|
14
|
-
var ENVELOPE_END = "== END_DEBRIEF_ENVELOPE_JSON ==";
|
|
15
|
-
|
|
16
|
-
// src/envelope.ts
|
|
17
|
-
import { createHash } from "crypto";
|
|
18
|
-
import { z } from "zod";
|
|
19
|
-
var MAX_DEBRIEF_BODY_BYTES = 64 * 1024;
|
|
20
|
-
var SAFE_ID = /^[A-Za-z0-9:_-]{1,200}$/;
|
|
21
|
-
var SAFE_PROFILE = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
22
|
-
var SAFE_UPPER_TOKEN = /^[A-Z][A-Z0-9_]{1,79}$/;
|
|
23
|
-
var VISIBILITY = /^(?:PUBLIC|WOLF_TEAM|POSTGAME_ONLY|SEAT_[1-9][0-9]*_ONLY)$/;
|
|
24
|
-
var UNKNOWN_VALUE = /^(?:\?|UNKNOWN|UNAVAILABLE|UNDETERMINED)$/i;
|
|
25
|
-
var TERMINAL_FACT_TYPES = /* @__PURE__ */ new Set(["GAME_FINISHED", "FINAL_IDENTITY", "GAME_RESULT"]);
|
|
26
|
-
var FACT_TYPES = [
|
|
27
|
-
"INIT_COMPLETED",
|
|
28
|
-
"NIGHT_BEGIN_WOLF",
|
|
29
|
-
"WOLF_CHOOSE",
|
|
30
|
-
"WOLF_SPEECH",
|
|
31
|
-
"WOLF_TARGET_CONFIRMED",
|
|
32
|
-
"WOLF_TARGET_RANDOM",
|
|
33
|
-
"WOLF_TARGET_NONE",
|
|
34
|
-
"WOLF_TARGET_CONFLICT_RETRY",
|
|
35
|
-
"WOLF_KILL_FAILED",
|
|
36
|
-
"WITCH_PROMPT_INFO",
|
|
37
|
-
"WITCH_SAVE",
|
|
38
|
-
"WITCH_SKIP_SAVE",
|
|
39
|
-
"WITCH_POISON",
|
|
40
|
-
"WITCH_SKIP_POISON",
|
|
41
|
-
"WITCH_INFO",
|
|
42
|
-
"WITCH_PASS",
|
|
43
|
-
"SEER_CHECK",
|
|
44
|
-
"SEER_SKIP_CHECK",
|
|
45
|
-
"SEER_RESULT",
|
|
46
|
-
"NIGHT_RESOLVED",
|
|
47
|
-
"DAWN_ANNOUNCE",
|
|
48
|
-
"PRIVATE_NIGHT_HUNTER_START",
|
|
49
|
-
"PRIVATE_NIGHT_HUNTER_SHOOT",
|
|
50
|
-
"PRIVATE_NIGHT_HUNTER_PASS",
|
|
51
|
-
"HUNTER_SKILL_START",
|
|
52
|
-
"HUNTER_SHOOT",
|
|
53
|
-
"HUNTER_PASS",
|
|
54
|
-
"DAY_SPEECH_START",
|
|
55
|
-
"DAY_SPEAK",
|
|
56
|
-
"LAST_WORD_START",
|
|
57
|
-
"LAST_WORD",
|
|
58
|
-
"DAY_VOTE_START",
|
|
59
|
-
"DAY_VOTE_SUBMIT",
|
|
60
|
-
"DAY_VOTE_PRIVATE_VOTE_REASON",
|
|
61
|
-
"DAY_VOTE_COUNT",
|
|
62
|
-
"DAY_VOTE_TIE",
|
|
63
|
-
"DAY_VOTE_ELIMINATED",
|
|
64
|
-
"DAY_REVOTE_BEGIN",
|
|
65
|
-
"DAY_REVOTE_VOTE_START",
|
|
66
|
-
"DAY_REVOTE_SUBMIT",
|
|
67
|
-
"DAY_REVOTE_COUNT",
|
|
68
|
-
"DAY_REVOTE_ELIMINATED",
|
|
69
|
-
"DAY_REVOTE_TIE",
|
|
70
|
-
"DAY_PEACE",
|
|
71
|
-
"DAY_RESOLVED",
|
|
72
|
-
"GAME_FINISHED",
|
|
73
|
-
"NARRATOR",
|
|
74
|
-
"FINAL_IDENTITY",
|
|
75
|
-
"GAME_RESULT"
|
|
76
|
-
];
|
|
77
|
-
var DECISION_ACTION_RULES = {
|
|
78
|
-
WOLF_KILL: { anchorTypes: ["WOLF_CHOOSE"], phases: ["WOLF_TURN"], roles: ["WOLF"] },
|
|
79
|
-
WITCH_SAVE: { anchorTypes: ["WITCH_SAVE"], phases: ["WITCH_TURN"], roles: ["WITCH"] },
|
|
80
|
-
WITCH_SKIP_SAVE: { anchorTypes: ["WITCH_SKIP_SAVE", "WITCH_PASS"], phases: ["WITCH_TURN"], roles: ["WITCH"] },
|
|
81
|
-
WITCH_POISON: { anchorTypes: ["WITCH_POISON"], phases: ["WITCH_TURN"], roles: ["WITCH"] },
|
|
82
|
-
WITCH_SKIP_POISON: { anchorTypes: ["WITCH_SKIP_POISON", "WITCH_PASS"], phases: ["WITCH_TURN"], roles: ["WITCH"] },
|
|
83
|
-
WITCH_PASS: { anchorTypes: ["WITCH_PASS"], phases: ["WITCH_TURN"], roles: ["WITCH"] },
|
|
84
|
-
SEER_CHECK: { anchorTypes: ["SEER_CHECK"], phases: ["SEER_TURN"], roles: ["SEER"] },
|
|
85
|
-
SEER_SKIP_CHECK: { anchorTypes: ["SEER_SKIP_CHECK"], phases: ["SEER_TURN"], roles: ["SEER"] },
|
|
86
|
-
DAY_SPEAK: { anchorTypes: ["DAY_SPEAK"], phases: ["SPEECH", "REVOTE_SPEECH"] },
|
|
87
|
-
LAST_WORD: { anchorTypes: ["LAST_WORD"], phases: ["LAST_WORD"] },
|
|
88
|
-
DAY_VOTE: { anchorTypes: ["DAY_VOTE_SUBMIT", "DAY_REVOTE_SUBMIT"], phases: ["VOTE", "REVOTE_VOTE"] },
|
|
89
|
-
HUNTER_SHOOT: {
|
|
90
|
-
anchorTypes: ["HUNTER_SHOOT", "PRIVATE_NIGHT_HUNTER_SHOOT"],
|
|
91
|
-
phases: ["HUNTER_TRIGGER", "NIGHT_HUNTER_SKILL"],
|
|
92
|
-
roles: ["HUNTER"]
|
|
93
|
-
},
|
|
94
|
-
HUNTER_PASS: {
|
|
95
|
-
anchorTypes: ["HUNTER_PASS", "PRIVATE_NIGHT_HUNTER_PASS"],
|
|
96
|
-
phases: ["HUNTER_TRIGGER", "NIGHT_HUNTER_SKILL"],
|
|
97
|
-
roles: ["HUNTER"]
|
|
98
|
-
}
|
|
99
|
-
};
|
|
100
|
-
var factSchema = z.object({
|
|
101
|
-
factId: z.string().regex(SAFE_ID),
|
|
102
|
-
anchor: z.string().regex(/^h:[0-9]+$/),
|
|
103
|
-
type: z.enum(FACT_TYPES),
|
|
104
|
-
visibility: z.string().regex(VISIBILITY),
|
|
105
|
-
availableAt: z.object({
|
|
106
|
-
historyIndex: z.number().int().nonnegative(),
|
|
107
|
-
round: z.number().int().nonnegative().optional(),
|
|
108
|
-
phase: z.string().regex(SAFE_UPPER_TOKEN).optional()
|
|
109
|
-
}).strict(),
|
|
110
|
-
actorSeat: z.number().int().positive().nullable().optional(),
|
|
111
|
-
targetSeat: z.number().int().positive().nullable().optional(),
|
|
112
|
-
summary: z.string().min(1).max(500)
|
|
113
|
-
}).strict();
|
|
114
|
-
var decisionWindowSchema = z.object({
|
|
115
|
-
decisionWindowId: z.string().regex(SAFE_ID),
|
|
116
|
-
anchorFactId: z.string().regex(SAFE_ID),
|
|
117
|
-
actorSeat: z.number().int().positive(),
|
|
118
|
-
actorRole: z.string().regex(SAFE_UPPER_TOKEN),
|
|
119
|
-
phase: z.string().regex(SAFE_UPPER_TOKEN),
|
|
120
|
-
actionType: z.string().regex(SAFE_UPPER_TOKEN),
|
|
121
|
-
allowedDecisionTypes: z.array(z.string().regex(SAFE_UPPER_TOKEN)).min(1).max(32),
|
|
122
|
-
availableActionTypes: z.array(z.string().regex(SAFE_UPPER_TOKEN)).min(1).max(32),
|
|
123
|
-
availableTargetSeats: z.array(z.number().int().positive().max(32)).max(32).optional()
|
|
124
|
-
}).strict();
|
|
125
|
-
var envelopeSchema = z.object({
|
|
126
|
-
schemaVersion: z.literal(2),
|
|
127
|
-
debriefId: z.string().regex(SAFE_ID),
|
|
128
|
-
game: z.object({
|
|
129
|
-
gameId: z.union([z.string().regex(/^[0-9]{1,30}$/), z.number().int().nonnegative()]).transform(String),
|
|
130
|
-
recipientAgentId: z.union([z.string().regex(/^[0-9]{1,30}$/), z.number().int().nonnegative()]).transform(String),
|
|
131
|
-
recipientSeat: z.number().int().positive().max(32),
|
|
132
|
-
reviewDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
|
133
|
-
profile: z.string().regex(SAFE_PROFILE).optional(),
|
|
134
|
-
normalEnd: z.boolean(),
|
|
135
|
-
role: z.enum(["WOLF", "WITCH", "SEER", "HUNTER", "VILLAGER", "UNKNOWN", "UNAVAILABLE", "?"]),
|
|
136
|
-
team: z.enum(["WOLF", "GOOD", "UNKNOWN", "UNAVAILABLE", "?"]),
|
|
137
|
-
finalState: z.enum(["ALIVE", "DEAD", "UNKNOWN", "UNAVAILABLE", "?"]),
|
|
138
|
-
result: z.enum([
|
|
139
|
-
"GOOD_WIN",
|
|
140
|
-
"WOLF_WIN",
|
|
141
|
-
"DRAW",
|
|
142
|
-
"ABNORMAL_END",
|
|
143
|
-
"UNKNOWN",
|
|
144
|
-
"UNAVAILABLE",
|
|
145
|
-
"UNDETERMINED",
|
|
146
|
-
"?"
|
|
147
|
-
]),
|
|
148
|
-
players: z.number().int().positive().max(32),
|
|
149
|
-
systemHealthGate: z.enum(["PASS", "SKIP_REQUIRED"]),
|
|
150
|
-
timelineComplete: z.boolean(),
|
|
151
|
-
voteConsistency: z.enum(["CONSISTENT", "INCONSISTENT", "NOT_APPLICABLE"])
|
|
152
|
-
}).strict(),
|
|
153
|
-
facts: z.array(factSchema).max(512),
|
|
154
|
-
decisionWindows: z.array(decisionWindowSchema).max(256)
|
|
155
|
-
}).strict();
|
|
156
|
-
var EnvelopeError = class extends Error {
|
|
157
|
-
constructor(code, message) {
|
|
158
|
-
super(message);
|
|
159
|
-
this.code = code;
|
|
160
|
-
this.name = "EnvelopeError";
|
|
161
|
-
}
|
|
162
|
-
code;
|
|
163
|
-
};
|
|
164
|
-
function sha256(value) {
|
|
165
|
-
return createHash("sha256").update(value).digest("hex");
|
|
166
|
-
}
|
|
167
|
-
function expectedDebriefId(envelope) {
|
|
168
|
-
return `werewolf:${envelope.game.gameId}:agent:${envelope.game.recipientAgentId}:v2`;
|
|
169
|
-
}
|
|
170
|
-
function exactLine(content, line) {
|
|
171
|
-
const escaped = line.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
172
|
-
const matches = [...content.matchAll(new RegExp(`^${escaped}\\r?$`, "gm"))];
|
|
173
|
-
if (matches.length !== 1) {
|
|
174
|
-
throw new EnvelopeError("CONTROL_LINE_AMBIGUOUS", `Expected exactly one control line: ${line}`);
|
|
175
|
-
}
|
|
176
|
-
return matches[0];
|
|
177
|
-
}
|
|
178
|
-
function assertFactVisibility(fact, envelope) {
|
|
179
|
-
if ((fact.actorSeat ?? 1) > envelope.game.players || (fact.targetSeat ?? 1) > envelope.game.players) {
|
|
180
|
-
throw new EnvelopeError("FACT_SEAT_OUT_OF_RANGE", `Fact seat is outside this game: ${fact.factId}`);
|
|
181
|
-
}
|
|
182
|
-
if (fact.visibility === "WOLF_TEAM" && envelope.game.role.toUpperCase() !== "WOLF") {
|
|
183
|
-
throw new EnvelopeError("WOLF_FACT_FOR_NON_WOLF", `Wolf-team fact is not visible to this recipient: ${fact.factId}`);
|
|
184
|
-
}
|
|
185
|
-
const seatOnly = /^SEAT_([1-9][0-9]*)_ONLY$/.exec(fact.visibility);
|
|
186
|
-
if (seatOnly && Number(seatOnly[1]) !== envelope.game.recipientSeat) {
|
|
187
|
-
throw new EnvelopeError("OTHER_SEAT_PRIVATE_FACT", `Private fact belongs to another seat: ${fact.factId}`);
|
|
188
|
-
}
|
|
189
|
-
if (TERMINAL_FACT_TYPES.has(fact.type) && fact.visibility !== "POSTGAME_ONLY") {
|
|
190
|
-
throw new EnvelopeError("POSTGAME_FACT_VISIBILITY", `Terminal facts must be postgame-only: ${fact.factId}`);
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
function validateEnvelopeRelations(envelope) {
|
|
194
|
-
if (envelope.game.recipientSeat > envelope.game.players) {
|
|
195
|
-
throw new EnvelopeError("RECIPIENT_SEAT_OUT_OF_RANGE", "Recipient seat is outside this game");
|
|
196
|
-
}
|
|
197
|
-
if (envelope.debriefId !== expectedDebriefId(envelope)) {
|
|
198
|
-
throw new EnvelopeError("DEBRIEF_ID_MISMATCH", "debriefId does not match game and recipient");
|
|
199
|
-
}
|
|
200
|
-
if (envelope.game.result === "ABNORMAL_END" && envelope.game.normalEnd) {
|
|
201
|
-
throw new EnvelopeError("NORMAL_END_RESULT_CONFLICT", "ABNORMAL_END cannot be marked as a normal end");
|
|
202
|
-
}
|
|
203
|
-
const factIds = /* @__PURE__ */ new Set();
|
|
204
|
-
const historyIndexes = /* @__PURE__ */ new Set();
|
|
205
|
-
for (const fact of envelope.facts) {
|
|
206
|
-
if (factIds.has(fact.factId)) throw new EnvelopeError("DUPLICATE_FACT_ID", `Duplicate factId: ${fact.factId}`);
|
|
207
|
-
if (historyIndexes.has(fact.availableAt.historyIndex)) {
|
|
208
|
-
throw new EnvelopeError("DUPLICATE_HISTORY_INDEX", `Duplicate history index: ${fact.availableAt.historyIndex}`);
|
|
209
|
-
}
|
|
210
|
-
const expectedId = `${envelope.debriefId}:h:${fact.availableAt.historyIndex}`;
|
|
211
|
-
if (fact.factId !== expectedId || fact.anchor !== `h:${fact.availableAt.historyIndex}`) {
|
|
212
|
-
throw new EnvelopeError("FACT_ANCHOR_MISMATCH", `Fact ID or anchor is not deterministic: ${fact.factId}`);
|
|
213
|
-
}
|
|
214
|
-
assertFactVisibility(fact, envelope);
|
|
215
|
-
factIds.add(fact.factId);
|
|
216
|
-
historyIndexes.add(fact.availableAt.historyIndex);
|
|
217
|
-
}
|
|
218
|
-
const windowIds = /* @__PURE__ */ new Set();
|
|
219
|
-
for (let index = 0; index < envelope.decisionWindows.length; index++) {
|
|
220
|
-
const window = envelope.decisionWindows[index];
|
|
221
|
-
if (windowIds.has(window.decisionWindowId)) {
|
|
222
|
-
throw new EnvelopeError("DUPLICATE_DECISION_WINDOW", `Duplicate decision window: ${window.decisionWindowId}`);
|
|
223
|
-
}
|
|
224
|
-
if (window.decisionWindowId !== `${envelope.debriefId}:d:${index}`) {
|
|
225
|
-
throw new EnvelopeError("DECISION_WINDOW_ID_MISMATCH", `Decision window ID is not deterministic: ${window.decisionWindowId}`);
|
|
226
|
-
}
|
|
227
|
-
if (window.availableTargetSeats && new Set(window.availableTargetSeats).size !== window.availableTargetSeats.length) {
|
|
228
|
-
throw new EnvelopeError("DUPLICATE_AVAILABLE_TARGET", `Duplicate target in ${window.decisionWindowId}`);
|
|
229
|
-
}
|
|
230
|
-
const anchor = envelope.facts.find((fact) => fact.factId === window.anchorFactId);
|
|
231
|
-
if (!anchor || anchor.visibility === "POSTGAME_ONLY") {
|
|
232
|
-
throw new EnvelopeError("DECISION_WINDOW_ANCHOR_INVALID", `Decision window has no observable action anchor: ${window.decisionWindowId}`);
|
|
233
|
-
}
|
|
234
|
-
if (anchor.actorSeat != null && anchor.actorSeat !== window.actorSeat) {
|
|
235
|
-
throw new EnvelopeError("DECISION_WINDOW_ACTOR_MISMATCH", `Decision window actor does not match its anchor: ${window.decisionWindowId}`);
|
|
236
|
-
}
|
|
237
|
-
const actionRule = DECISION_ACTION_RULES[window.actionType];
|
|
238
|
-
if (!actionRule) {
|
|
239
|
-
throw new EnvelopeError("DECISION_ACTION_UNSUPPORTED", `Unsupported decision action: ${window.actionType}`);
|
|
240
|
-
}
|
|
241
|
-
if (!actionRule.anchorTypes.includes(anchor.type)) {
|
|
242
|
-
throw new EnvelopeError("DECISION_ACTION_ANCHOR_MISMATCH", `Decision action does not match its anchor event: ${window.decisionWindowId}`);
|
|
243
|
-
}
|
|
244
|
-
if (anchor.availableAt.phase !== window.phase || !actionRule.phases.includes(window.phase)) {
|
|
245
|
-
throw new EnvelopeError("DECISION_PHASE_MISMATCH", `Decision phase does not match its action or anchor: ${window.decisionWindowId}`);
|
|
246
|
-
}
|
|
247
|
-
if (actionRule.roles && !actionRule.roles.includes(window.actorRole)) {
|
|
248
|
-
throw new EnvelopeError("DECISION_ACTION_ROLE_MISMATCH", `Role cannot perform this decision action: ${window.decisionWindowId}`);
|
|
249
|
-
}
|
|
250
|
-
if (window.actorSeat > envelope.game.players) {
|
|
251
|
-
throw new EnvelopeError("DECISION_WINDOW_SEAT_OUT_OF_RANGE", `Decision window seat is outside this game: ${window.decisionWindowId}`);
|
|
252
|
-
}
|
|
253
|
-
if (!window.availableActionTypes.includes(window.actionType)) {
|
|
254
|
-
throw new EnvelopeError("ACTION_NOT_AVAILABLE", `Recorded action was not available in its decision window: ${window.decisionWindowId}`);
|
|
255
|
-
}
|
|
256
|
-
if (window.availableTargetSeats && anchor.targetSeat != null && !window.availableTargetSeats.includes(anchor.targetSeat)) {
|
|
257
|
-
throw new EnvelopeError(
|
|
258
|
-
"ANCHOR_TARGET_UNAVAILABLE",
|
|
259
|
-
`Anchor target is absent from trusted targets: ${window.decisionWindowId}`
|
|
260
|
-
);
|
|
261
|
-
}
|
|
262
|
-
if (UNKNOWN_VALUE.test(window.actorRole)) {
|
|
263
|
-
throw new EnvelopeError("DECISION_ROLE_UNKNOWN", `Decision window actor role is unknown: ${window.decisionWindowId}`);
|
|
264
|
-
}
|
|
265
|
-
windowIds.add(window.decisionWindowId);
|
|
266
|
-
}
|
|
267
|
-
if (envelope.game.timelineComplete) {
|
|
268
|
-
const finished = envelope.facts.filter((fact) => fact.type === "GAME_FINISHED");
|
|
269
|
-
const resultFacts = envelope.facts.filter((fact) => fact.type === "GAME_RESULT");
|
|
270
|
-
if (finished.length !== 1 || resultFacts.length !== 1 || resultFacts[0].summary !== `result=${envelope.game.result}`) {
|
|
271
|
-
throw new EnvelopeError(
|
|
272
|
-
"TERMINAL_FACTS_INCONSISTENT",
|
|
273
|
-
"A complete timeline requires one matching GAME_FINISHED and GAME_RESULT fact"
|
|
274
|
-
);
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
function parseDebriefBody(content) {
|
|
279
|
-
if (Buffer.byteLength(content, "utf8") > MAX_DEBRIEF_BODY_BYTES) {
|
|
280
|
-
throw new EnvelopeError("BODY_TOO_LARGE", "Debrief body exceeds the plugin limit");
|
|
281
|
-
}
|
|
282
|
-
const header = exactLine(content, DEBRIEF_HEADER);
|
|
283
|
-
const policy = exactLine(content, `policyVersion: ${DEBRIEF_POLICY_VERSION}`);
|
|
284
|
-
const schema = exactLine(content, "schemaVersion: 2");
|
|
285
|
-
const declaredId = [...content.matchAll(/^debriefId:\s*([^\s]+)\r?$/gm)];
|
|
286
|
-
if (declaredId.length !== 1) {
|
|
287
|
-
throw new EnvelopeError("DEBRIEF_ID_LINE", "Expected exactly one debriefId control line");
|
|
288
|
-
}
|
|
289
|
-
const start = exactLine(content, ENVELOPE_START);
|
|
290
|
-
const end = exactLine(content, ENVELOPE_END);
|
|
291
|
-
const positions = [header.index, policy.index, schema.index, declaredId[0].index, start.index, end.index];
|
|
292
|
-
if (!positions.every((value, index) => index === 0 || value > positions[index - 1])) {
|
|
293
|
-
throw new EnvelopeError("CONTROL_LINE_ORDER", "Debrief control lines are out of order");
|
|
294
|
-
}
|
|
295
|
-
const rawJson = content.slice(start.index + start[0].length, end.index).trim();
|
|
296
|
-
if (!rawJson || Buffer.byteLength(rawJson, "utf8") > MAX_DEBRIEF_BODY_BYTES) {
|
|
297
|
-
throw new EnvelopeError("ENVELOPE_EMPTY", "Debrief envelope is empty or oversized");
|
|
298
|
-
}
|
|
299
|
-
let raw;
|
|
300
|
-
try {
|
|
301
|
-
raw = JSON.parse(rawJson);
|
|
302
|
-
} catch (error) {
|
|
303
|
-
throw new EnvelopeError("ENVELOPE_JSON", `Invalid debrief envelope JSON: ${String(error)}`);
|
|
304
|
-
}
|
|
305
|
-
const parsed = envelopeSchema.safeParse(raw);
|
|
306
|
-
if (!parsed.success) {
|
|
307
|
-
throw new EnvelopeError("ENVELOPE_SCHEMA", parsed.error.issues.map((issue) => issue.message).join("; "));
|
|
308
|
-
}
|
|
309
|
-
const envelope = parsed.data;
|
|
310
|
-
if (declaredId[0][1] !== envelope.debriefId) {
|
|
311
|
-
throw new EnvelopeError("DECLARED_ID_MISMATCH", "Header debriefId does not match the managed envelope");
|
|
312
|
-
}
|
|
313
|
-
validateEnvelopeRelations(envelope);
|
|
314
|
-
return { envelope, bodyHash: sha256(content) };
|
|
315
|
-
}
|
|
316
|
-
function isTrustedDebriefOrigin(channelId, from) {
|
|
317
|
-
if (channelId !== "clawtopia" && channelId !== "coolclaw") return false;
|
|
318
|
-
return from === `${channelId}:human:0`;
|
|
319
|
-
}
|
|
320
|
-
function isTrustedDebriefClaimOrigin(channelId, senderId, conversationId) {
|
|
321
|
-
if (channelId !== "clawtopia" && channelId !== "coolclaw") return false;
|
|
322
|
-
if (senderId) return isTrustedDebriefOrigin(channelId, senderId);
|
|
323
|
-
return conversationId?.trim().toLowerCase() === "human:0";
|
|
324
|
-
}
|
|
325
|
-
function isUnknownEligibilityValue(value) {
|
|
326
|
-
return UNKNOWN_VALUE.test(value.trim());
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
// src/context-store.ts
|
|
330
|
-
var CAPTURE_TTL_MS = 10 * 60 * 1e3;
|
|
331
|
-
var MAX_CAPTURES = 256;
|
|
332
|
-
var SUGGESTION_COMMAND = /^\s*(采纳|忽略|拒绝)\s+(S-\d{3,6})\s*[。.!!]?\s*$/i;
|
|
333
|
-
var LEGACY_DIRECT_CONVERSATION = /^private:(?:HUMAN|human):([0-9]+)$/;
|
|
334
|
-
function promptContainsInbound(prompt, inbound) {
|
|
335
|
-
if (prompt.includes(inbound.content)) return true;
|
|
336
|
-
if (inbound.kind !== "debrief") return false;
|
|
337
|
-
const lines = prompt.split(/\r?\n/);
|
|
338
|
-
return lines.includes(DEBRIEF_HEADER) && lines.some((line) => /^debriefId:\s*(\S+)\s*$/.exec(line)?.[1] === inbound.envelope.debriefId);
|
|
339
|
-
}
|
|
340
|
-
function isExplicitConfiguredOwner(config, channelId, senderId) {
|
|
341
|
-
if (channelId !== "clawtopia" && channelId !== "coolclaw" || !senderId) return false;
|
|
342
|
-
const owners = record(record(config)?.commands)?.ownerAllowFrom;
|
|
343
|
-
if (!Array.isArray(owners) || owners.length === 0) return false;
|
|
344
|
-
const normalized = owners.map((value) => String(value ?? "").trim().toLowerCase()).filter(Boolean);
|
|
345
|
-
const relevant = normalized.filter((value) => value === "*" || !value.includes(":") || value.startsWith(`${channelId}:`));
|
|
346
|
-
if (relevant.some((value) => value === "*" || value === `${channelId}:*`)) return false;
|
|
347
|
-
const rawSender = senderId.trim().toLowerCase();
|
|
348
|
-
const canonical = rawSender.startsWith(`${channelId}:`) ? rawSender : `${channelId}:${rawSender}`;
|
|
349
|
-
return relevant.includes(canonical) && new RegExp(`^${channelId}:human:[0-9]+$`).test(canonical);
|
|
350
|
-
}
|
|
351
|
-
function normalizedSender(value) {
|
|
352
|
-
return value.replace(/^(?:clawtopia|coolclaw):/, "").replace(/^human:/, "");
|
|
353
|
-
}
|
|
354
|
-
function sameHumanSender(left, right) {
|
|
355
|
-
return normalizedSender(left) === normalizedSender(right);
|
|
356
|
-
}
|
|
357
|
-
function isHumanDirectMessage(event, ctx) {
|
|
358
|
-
if (ctx.channelId !== "clawtopia" && ctx.channelId !== "coolclaw") return false;
|
|
359
|
-
if (!ctx.conversationId) return false;
|
|
360
|
-
const legacy = LEGACY_DIRECT_CONVERSATION.exec(ctx.conversationId);
|
|
361
|
-
const canonical = new RegExp(`^${ctx.channelId}:human:([0-9]+)$`).exec(ctx.conversationId);
|
|
362
|
-
const humanId = legacy?.[1] ?? canonical?.[1];
|
|
363
|
-
return humanId !== void 0 && humanId !== "0" && event.from === `${ctx.channelId}:human:${humanId}`;
|
|
364
|
-
}
|
|
365
|
-
function normalizedAccountId(value) {
|
|
366
|
-
return value?.trim() || "default";
|
|
367
|
-
}
|
|
368
|
-
function record(value) {
|
|
369
|
-
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
370
|
-
}
|
|
371
|
-
function resolveAgentAccountBinding(config, channelId, accountId) {
|
|
372
|
-
if (channelId !== "clawtopia" && channelId !== "coolclaw") return void 0;
|
|
373
|
-
const normalizedAccount = normalizedAccountId(accountId);
|
|
374
|
-
const channels = record(record(config)?.channels);
|
|
375
|
-
const channel = record(channels?.[channelId]);
|
|
376
|
-
const account = record(record(channel?.accounts)?.[normalizedAccount]);
|
|
377
|
-
const platformAgentId = typeof account?.agentId === "string" ? account.agentId.trim() : "";
|
|
378
|
-
if (!platformAgentId) return void 0;
|
|
379
|
-
return { channelId, accountId: normalizedAccount, platformAgentId };
|
|
380
|
-
}
|
|
381
|
-
var EvolutionContextStore = class {
|
|
382
|
-
inboundByRun = /* @__PURE__ */ new Map();
|
|
383
|
-
inboundBySession = /* @__PURE__ */ new Map();
|
|
384
|
-
inboundByStableKey = /* @__PURE__ */ new Map();
|
|
385
|
-
stableKeyByInbound = /* @__PURE__ */ new Map();
|
|
386
|
-
stableKeyExpiresAt = /* @__PURE__ */ new Map();
|
|
387
|
-
boundTombstoneKeys = /* @__PURE__ */ new Set();
|
|
388
|
-
releasedTombstones = /* @__PURE__ */ new Map();
|
|
389
|
-
boundByRun = /* @__PURE__ */ new Map();
|
|
390
|
-
hashByDebriefId = /* @__PURE__ */ new Map();
|
|
391
|
-
toolCalls = /* @__PURE__ */ new Map();
|
|
392
|
-
capture(event, ctx, now = Date.now()) {
|
|
393
|
-
this.cleanup(now);
|
|
394
|
-
const runId = event.runId ?? ctx.runId;
|
|
395
|
-
const sessionKey = event.sessionKey ?? ctx.sessionKey;
|
|
396
|
-
if (!sessionKey) return void 0;
|
|
397
|
-
const stableKey = this.stableInboundKey(ctx, sessionKey, event);
|
|
398
|
-
const existing = this.inboundByStableKey.get(stableKey);
|
|
399
|
-
if (existing) return existing;
|
|
400
|
-
if (this.releasedTombstones.has(stableKey)) return void 0;
|
|
401
|
-
if (this.inboundByStableKey.size + this.releasedTombstones.size >= MAX_CAPTURES) return void 0;
|
|
402
|
-
if (isTrustedDebriefOrigin(ctx.channelId, event.from)) {
|
|
403
|
-
try {
|
|
404
|
-
const { envelope, bodyHash } = parseDebriefBody(event.content);
|
|
405
|
-
const prior = this.hashByDebriefId.get(envelope.debriefId);
|
|
406
|
-
const captured = {
|
|
407
|
-
kind: "debrief",
|
|
408
|
-
channelId: ctx.channelId,
|
|
409
|
-
accountId: normalizedAccountId(ctx.accountId),
|
|
410
|
-
from: event.from,
|
|
411
|
-
sessionKey,
|
|
412
|
-
runId,
|
|
413
|
-
conversationId: ctx.conversationId,
|
|
414
|
-
messageId: event.messageId,
|
|
415
|
-
content: event.content,
|
|
416
|
-
bodyHash,
|
|
417
|
-
envelope,
|
|
418
|
-
capturedAt: now,
|
|
419
|
-
...prior && prior.hash !== bodyHash ? { conflict: true } : {}
|
|
420
|
-
};
|
|
421
|
-
this.hashByDebriefId.set(envelope.debriefId, prior ?? { hash: bodyHash, capturedAt: now });
|
|
422
|
-
this.storeInbound(captured, stableKey);
|
|
423
|
-
return captured;
|
|
424
|
-
} catch {
|
|
425
|
-
return void 0;
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
const match = SUGGESTION_COMMAND.exec(event.content);
|
|
429
|
-
if (!match || !isHumanDirectMessage(event, ctx)) return void 0;
|
|
430
|
-
const command = {
|
|
431
|
-
kind: "suggestion-command",
|
|
432
|
-
channelId: ctx.channelId,
|
|
433
|
-
accountId: normalizedAccountId(ctx.accountId),
|
|
434
|
-
from: event.from,
|
|
435
|
-
sessionKey,
|
|
436
|
-
runId,
|
|
437
|
-
conversationId: ctx.conversationId,
|
|
438
|
-
messageId: event.messageId,
|
|
439
|
-
content: event.content,
|
|
440
|
-
suggestionId: match[2].toUpperCase(),
|
|
441
|
-
decision: match[1] === "\u91C7\u7EB3" ? "accept" : "reject",
|
|
442
|
-
capturedAt: now
|
|
443
|
-
};
|
|
444
|
-
this.storeInbound(command, stableKey);
|
|
445
|
-
return command;
|
|
446
|
-
}
|
|
447
|
-
getPending(runId, sessionKey, prompt, now = Date.now()) {
|
|
448
|
-
this.cleanup(now);
|
|
449
|
-
if (!runId || !sessionKey) return void 0;
|
|
450
|
-
const inbound = this.inboundByRun.get(runId);
|
|
451
|
-
if (inbound) {
|
|
452
|
-
return inbound.sessionKey === sessionKey && now - inbound.capturedAt <= CAPTURE_TTL_MS ? inbound : void 0;
|
|
453
|
-
}
|
|
454
|
-
if (!prompt) return void 0;
|
|
455
|
-
const pending = this.inboundBySession.get(sessionKey);
|
|
456
|
-
if (!pending) return void 0;
|
|
457
|
-
const matches = pending.filter((candidate) => promptContainsInbound(prompt, candidate));
|
|
458
|
-
return matches.length === 1 ? matches[0] : void 0;
|
|
459
|
-
}
|
|
460
|
-
stableInboundKey(ctx, sessionKey, event) {
|
|
461
|
-
const messageId = event.messageId?.trim();
|
|
462
|
-
const identity = messageId ? ["message", messageId] : ["content", createHash2("sha256").update(event.content).digest("hex")];
|
|
463
|
-
return JSON.stringify([ctx.channelId, normalizedAccountId(ctx.accountId), sessionKey, identity]);
|
|
464
|
-
}
|
|
465
|
-
storeInbound(inbound, stableKey) {
|
|
466
|
-
if (inbound.runId) {
|
|
467
|
-
const previous = this.inboundByRun.get(inbound.runId);
|
|
468
|
-
if (previous) this.removeInbound(previous);
|
|
469
|
-
this.inboundByRun.set(inbound.runId, inbound);
|
|
470
|
-
}
|
|
471
|
-
const pending = this.inboundBySession.get(inbound.sessionKey) ?? [];
|
|
472
|
-
pending.push(inbound);
|
|
473
|
-
this.inboundBySession.set(inbound.sessionKey, pending);
|
|
474
|
-
this.inboundByStableKey.set(stableKey, inbound);
|
|
475
|
-
this.stableKeyByInbound.set(inbound, stableKey);
|
|
476
|
-
this.stableKeyExpiresAt.set(stableKey, inbound.capturedAt + CAPTURE_TTL_MS);
|
|
477
|
-
}
|
|
478
|
-
removeInbound(inbound, preserveStableKey = false) {
|
|
479
|
-
if (!preserveStableKey) {
|
|
480
|
-
const stableKey = this.stableKeyByInbound.get(inbound);
|
|
481
|
-
if (stableKey && this.inboundByStableKey.get(stableKey) === inbound) {
|
|
482
|
-
this.inboundByStableKey.delete(stableKey);
|
|
483
|
-
this.stableKeyExpiresAt.delete(stableKey);
|
|
484
|
-
this.boundTombstoneKeys.delete(stableKey);
|
|
485
|
-
}
|
|
486
|
-
this.stableKeyByInbound.delete(inbound);
|
|
487
|
-
}
|
|
488
|
-
if (inbound.runId && this.inboundByRun.get(inbound.runId) === inbound) {
|
|
489
|
-
this.inboundByRun.delete(inbound.runId);
|
|
490
|
-
}
|
|
491
|
-
const pending = this.inboundBySession.get(inbound.sessionKey);
|
|
492
|
-
if (!pending) return;
|
|
493
|
-
const index = pending.indexOf(inbound);
|
|
494
|
-
if (index >= 0) pending.splice(index, 1);
|
|
495
|
-
if (pending.length === 0) this.inboundBySession.delete(inbound.sessionKey);
|
|
496
|
-
}
|
|
497
|
-
compactBoundTombstone(bound) {
|
|
498
|
-
const stableKey = this.stableKeyByInbound.get(bound.inbound);
|
|
499
|
-
if (!stableKey) return;
|
|
500
|
-
const expiresAt = this.stableKeyExpiresAt.get(stableKey) ?? bound.expiresAt;
|
|
501
|
-
this.inboundByStableKey.delete(stableKey);
|
|
502
|
-
this.stableKeyByInbound.delete(bound.inbound);
|
|
503
|
-
this.stableKeyExpiresAt.delete(stableKey);
|
|
504
|
-
this.boundTombstoneKeys.delete(stableKey);
|
|
505
|
-
this.releasedTombstones.set(stableKey, expiresAt);
|
|
506
|
-
}
|
|
507
|
-
bindAgentRun(event, ctx, binding, now = Date.now(), explicitOwnerAuthorized = false, pendingInbound) {
|
|
508
|
-
this.cleanup(now);
|
|
509
|
-
if (!ctx.runId || !ctx.sessionKey || !ctx.agentId || !ctx.workspaceDir) return void 0;
|
|
510
|
-
const runInbound = this.inboundByRun.get(ctx.runId);
|
|
511
|
-
const sessionPending = this.inboundBySession.get(ctx.sessionKey);
|
|
512
|
-
const pendingIndex = pendingInbound ? sessionPending?.indexOf(pendingInbound) ?? -1 : -1;
|
|
513
|
-
const inbound = runInbound ?? (pendingIndex >= 0 ? pendingInbound : void 0);
|
|
514
|
-
if (!inbound || inbound.sessionKey !== ctx.sessionKey || now - inbound.capturedAt > CAPTURE_TTL_MS) return void 0;
|
|
515
|
-
const eventAccountId = normalizedAccountId(event.accountId);
|
|
516
|
-
if (event.channelId !== inbound.channelId || eventAccountId !== inbound.accountId) return void 0;
|
|
517
|
-
if (!binding || binding.channelId !== inbound.channelId || binding.accountId !== inbound.accountId) return void 0;
|
|
518
|
-
if (inbound.kind === "debrief") {
|
|
519
|
-
if (inbound.envelope.game.recipientAgentId !== binding.platformAgentId) return void 0;
|
|
520
|
-
} else {
|
|
521
|
-
if (!explicitOwnerAuthorized || event.senderIsOwner !== true || !event.senderId || normalizedSender(event.senderId) !== normalizedSender(inbound.from)) return void 0;
|
|
522
|
-
}
|
|
523
|
-
const stableKey = this.stableKeyByInbound.get(inbound);
|
|
524
|
-
const expiresAt = now + CAPTURE_TTL_MS;
|
|
525
|
-
if (stableKey) {
|
|
526
|
-
this.boundTombstoneKeys.add(stableKey);
|
|
527
|
-
this.stableKeyExpiresAt.set(stableKey, expiresAt);
|
|
528
|
-
}
|
|
529
|
-
this.removeInbound(inbound, true);
|
|
530
|
-
const bound = {
|
|
531
|
-
runId: ctx.runId,
|
|
532
|
-
sessionKey: ctx.sessionKey,
|
|
533
|
-
agentId: ctx.agentId,
|
|
534
|
-
workspaceDir: ctx.workspaceDir,
|
|
535
|
-
inbound,
|
|
536
|
-
senderId: event.senderId,
|
|
537
|
-
senderIsOwner: event.senderIsOwner === true,
|
|
538
|
-
consumed: false,
|
|
539
|
-
proposalAttempts: 0,
|
|
540
|
-
boundAt: now,
|
|
541
|
-
expiresAt
|
|
542
|
-
};
|
|
543
|
-
this.boundByRun.set(ctx.runId, bound);
|
|
544
|
-
return bound;
|
|
545
|
-
}
|
|
546
|
-
getBound(runId, sessionKey, now = Date.now()) {
|
|
547
|
-
this.cleanup(now);
|
|
548
|
-
if (!runId || !sessionKey) return void 0;
|
|
549
|
-
const bound = this.boundByRun.get(runId);
|
|
550
|
-
return bound?.sessionKey === sessionKey && bound.expiresAt >= now ? bound : void 0;
|
|
551
|
-
}
|
|
552
|
-
getBoundForToolCall(runId, sessionKey, agentId, now = Date.now()) {
|
|
553
|
-
return this.resolveBoundForToolCall(runId, sessionKey, agentId, true, now);
|
|
554
|
-
}
|
|
555
|
-
resolveBoundForToolCall(runId, sessionKey, agentId, includeConsumed, now) {
|
|
556
|
-
this.cleanup(now);
|
|
557
|
-
if (!sessionKey) return void 0;
|
|
558
|
-
if (runId) {
|
|
559
|
-
const bound2 = this.getBound(runId, sessionKey, now);
|
|
560
|
-
if (bound2 && agentId && bound2.agentId !== agentId) throw new Error("BOUND_AGENT_MISMATCH");
|
|
561
|
-
return bound2;
|
|
562
|
-
}
|
|
563
|
-
const matches = [...this.boundByRun.values()].filter((bound2) => bound2.sessionKey === sessionKey && bound2.expiresAt >= now && (includeConsumed || !bound2.consumed));
|
|
564
|
-
if (matches.length === 0) return void 0;
|
|
565
|
-
if (matches.length > 1) throw new Error("AMBIGUOUS_BOUND_CAPABILITY");
|
|
566
|
-
const bound = matches[0];
|
|
567
|
-
if (agentId && bound.agentId !== agentId) throw new Error("BOUND_AGENT_MISMATCH");
|
|
568
|
-
return bound;
|
|
569
|
-
}
|
|
570
|
-
releaseRun(runId, sessionKey) {
|
|
571
|
-
if (!runId) return void 0;
|
|
572
|
-
const bound = this.boundByRun.get(runId);
|
|
573
|
-
if (!bound || sessionKey && bound.sessionKey !== sessionKey) return void 0;
|
|
574
|
-
this.boundByRun.delete(runId);
|
|
575
|
-
this.compactBoundTombstone(bound);
|
|
576
|
-
for (const [toolCallId, authorized] of this.toolCalls) {
|
|
577
|
-
if (authorized.runId === runId) this.toolCalls.delete(toolCallId);
|
|
578
|
-
}
|
|
579
|
-
return bound;
|
|
580
|
-
}
|
|
581
|
-
consume(runId, sessionKey, now = Date.now()) {
|
|
582
|
-
const bound = this.getBound(runId, sessionKey, now);
|
|
583
|
-
if (!bound) throw new Error("NO_BOUND_CAPABILITY");
|
|
584
|
-
if (bound.consumed) throw new Error("CAPABILITY_ALREADY_CONSUMED");
|
|
585
|
-
bound.consumed = true;
|
|
586
|
-
return bound;
|
|
587
|
-
}
|
|
588
|
-
authorizeToolCall(runId, sessionKey, toolCallId, now = Date.now(), agentId) {
|
|
589
|
-
this.cleanup(now);
|
|
590
|
-
if (!sessionKey || !toolCallId) throw new Error("TOOL_CALL_CONTEXT_MISSING");
|
|
591
|
-
const bound = this.resolveBoundForToolCall(runId, sessionKey, agentId, false, now);
|
|
592
|
-
if (!bound) throw new Error("NO_BOUND_CAPABILITY");
|
|
593
|
-
if (bound.consumed) throw new Error("CAPABILITY_ALREADY_CONSUMED");
|
|
594
|
-
if (this.toolCalls.has(toolCallId)) throw new Error("TOOL_CALL_ALREADY_AUTHORIZED");
|
|
595
|
-
this.toolCalls.set(toolCallId, { runId: bound.runId, sessionKey, expiresAt: bound.expiresAt });
|
|
596
|
-
return bound;
|
|
597
|
-
}
|
|
598
|
-
inspectAuthorizedToolCall(toolCallId, sessionKey, agentId, now = Date.now()) {
|
|
599
|
-
this.cleanup(now);
|
|
600
|
-
const authorized = this.toolCalls.get(toolCallId);
|
|
601
|
-
if (!authorized || authorized.expiresAt < now || !sessionKey || authorized.sessionKey !== sessionKey) {
|
|
602
|
-
return void 0;
|
|
603
|
-
}
|
|
604
|
-
const bound = this.boundByRun.get(authorized.runId);
|
|
605
|
-
if (!bound || bound.sessionKey !== sessionKey || bound.expiresAt < now) return void 0;
|
|
606
|
-
return agentId && bound.agentId !== agentId ? void 0 : bound;
|
|
607
|
-
}
|
|
608
|
-
consumeToolCall(toolCallId, sessionKey, now = Date.now()) {
|
|
609
|
-
const bound = this.beginToolCall(toolCallId, sessionKey, now);
|
|
610
|
-
return this.consume(bound.runId, bound.sessionKey, now);
|
|
611
|
-
}
|
|
612
|
-
beginProposalToolCall(toolCallId, sessionKey, now = Date.now()) {
|
|
613
|
-
const bound = this.beginToolCall(toolCallId, sessionKey, now);
|
|
614
|
-
if (bound.inbound.kind !== "debrief") throw new Error("DEBRIEF_CAPABILITY_REQUIRED");
|
|
615
|
-
if (bound.proposalAttempts >= 2) {
|
|
616
|
-
bound.consumed = true;
|
|
617
|
-
throw new Error("CAPABILITY_ALREADY_CONSUMED");
|
|
618
|
-
}
|
|
619
|
-
bound.proposalAttempts += 1;
|
|
620
|
-
return bound;
|
|
621
|
-
}
|
|
622
|
-
beginToolCall(toolCallId, sessionKey, now = Date.now()) {
|
|
623
|
-
this.cleanup(now);
|
|
624
|
-
const authorized = this.toolCalls.get(toolCallId);
|
|
625
|
-
this.toolCalls.delete(toolCallId);
|
|
626
|
-
if (!authorized || authorized.expiresAt < now || !sessionKey || authorized.sessionKey !== sessionKey) {
|
|
627
|
-
throw new Error("UNAUTHORIZED_TOOL_CALL");
|
|
628
|
-
}
|
|
629
|
-
const bound = this.getBound(authorized.runId, authorized.sessionKey, now);
|
|
630
|
-
if (!bound) throw new Error("NO_BOUND_CAPABILITY");
|
|
631
|
-
if (bound.consumed) throw new Error("CAPABILITY_ALREADY_CONSUMED");
|
|
632
|
-
return bound;
|
|
633
|
-
}
|
|
634
|
-
cleanup(now = Date.now()) {
|
|
635
|
-
for (const [key, value] of this.inboundByStableKey) {
|
|
636
|
-
if ((this.stableKeyExpiresAt.get(key) ?? value.capturedAt + CAPTURE_TTL_MS) < now) {
|
|
637
|
-
this.removeInbound(value);
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
for (const [key, value] of this.boundByRun) {
|
|
641
|
-
if (value.expiresAt < now) {
|
|
642
|
-
this.boundByRun.delete(key);
|
|
643
|
-
this.compactBoundTombstone(value);
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
for (const [key, value] of this.toolCalls) {
|
|
647
|
-
if (value.expiresAt < now) this.toolCalls.delete(key);
|
|
648
|
-
}
|
|
649
|
-
for (const [key, value] of this.hashByDebriefId) {
|
|
650
|
-
if (now - value.capturedAt > CAPTURE_TTL_MS) this.hashByDebriefId.delete(key);
|
|
651
|
-
}
|
|
652
|
-
for (const [key, expiresAt] of this.releasedTombstones) {
|
|
653
|
-
if (expiresAt < now) this.releasedTombstones.delete(key);
|
|
654
|
-
}
|
|
655
|
-
while (this.inboundByRun.size > MAX_CAPTURES) {
|
|
656
|
-
const first = this.inboundByRun.values().next().value;
|
|
657
|
-
if (!first) break;
|
|
658
|
-
this.removeInbound(first);
|
|
659
|
-
}
|
|
660
|
-
while (this.inboundByStableKey.size - this.boundTombstoneKeys.size > MAX_CAPTURES) {
|
|
661
|
-
const first = [...this.inboundByStableKey].find(([key]) => !this.boundTombstoneKeys.has(key))?.[1];
|
|
662
|
-
if (!first) break;
|
|
663
|
-
this.removeInbound(first);
|
|
664
|
-
}
|
|
665
|
-
while ([...this.inboundBySession.values()].reduce((total, values) => total + values.length, 0) > MAX_CAPTURES) {
|
|
666
|
-
const firstKey = this.inboundBySession.keys().next().value;
|
|
667
|
-
if (!firstKey) break;
|
|
668
|
-
const values = this.inboundBySession.get(firstKey);
|
|
669
|
-
const first = values[0];
|
|
670
|
-
if (!first) {
|
|
671
|
-
this.inboundBySession.delete(firstKey);
|
|
672
|
-
continue;
|
|
673
|
-
}
|
|
674
|
-
this.removeInbound(first);
|
|
675
|
-
}
|
|
676
|
-
while (this.toolCalls.size > MAX_CAPTURES) this.toolCalls.delete(this.toolCalls.keys().next().value);
|
|
677
|
-
while (this.hashByDebriefId.size > MAX_CAPTURES) this.hashByDebriefId.delete(this.hashByDebriefId.keys().next().value);
|
|
678
|
-
}
|
|
679
|
-
};
|
|
680
|
-
|
|
681
|
-
// src/documents.ts
|
|
682
|
-
import { existsSync, lstatSync as lstatSync2, readFileSync } from "fs";
|
|
683
|
-
import { z as z3 } from "zod";
|
|
684
|
-
|
|
685
|
-
// src/proposal.ts
|
|
686
|
-
import { z as z2 } from "zod";
|
|
687
|
-
var SAFE_TOPIC = /^L-[a-z0-9][a-z0-9_-]{0,63}-\d{3,6}$/;
|
|
688
|
-
var SAFE_PROFILE2 = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
689
|
-
var SAFE_TOKEN = /^[A-Z][A-Z0-9_]{1,79}$/;
|
|
690
|
-
var proposalSchema = z2.object({
|
|
691
|
-
schemaVersion: z2.literal(1),
|
|
692
|
-
action: z2.enum(["SKIP", "SUPPORT", "COUNTER", "REFINE", "NEW"]),
|
|
693
|
-
source: z2.enum(["SELF", "OBSERVED", "EXEMPLAR"]),
|
|
694
|
-
topicId: z2.string().regex(SAFE_TOPIC).optional(),
|
|
695
|
-
profile: z2.string().regex(SAFE_PROFILE2).optional(),
|
|
696
|
-
decisionWindowId: z2.string().min(1).max(200).optional(),
|
|
697
|
-
decisionType: z2.string().regex(SAFE_TOKEN).optional(),
|
|
698
|
-
executionOperation: z2.enum([
|
|
699
|
-
"REPORT_DECIDED_ROLE_CLAIM",
|
|
700
|
-
"EXPLAIN_DECIDED_VOTE",
|
|
701
|
-
"RETRACT_PUBLIC_JUDGMENT",
|
|
702
|
-
"AVOID_REPEATING_PRIOR_SPEAKERS",
|
|
703
|
-
"EXPLAIN_DECIDED_WOLF_TARGET"
|
|
704
|
-
]).optional(),
|
|
705
|
-
alternativeActionType: z2.string().regex(SAFE_TOKEN).optional(),
|
|
706
|
-
alternativeTargetSeat: z2.number().int().positive().nullable().optional(),
|
|
707
|
-
anchorFactId: z2.string().min(1).max(200).optional(),
|
|
708
|
-
knownFactRefs: z2.array(z2.string().min(1).max(200)).max(64).optional(),
|
|
709
|
-
outcomeFactRefs: z2.array(z2.string().min(1).max(200)).max(64).optional(),
|
|
710
|
-
trigger: z2.string().min(1).max(500).optional(),
|
|
711
|
-
rule: z2.string().min(1).max(500).optional(),
|
|
712
|
-
boundary: z2.string().min(1).max(500).optional(),
|
|
713
|
-
behavior: z2.string().min(1).max(800).optional(),
|
|
714
|
-
alternativeAction: z2.string().min(1).max(500).optional(),
|
|
715
|
-
expectedLocalEffect: z2.string().min(1).max(500).optional(),
|
|
716
|
-
observedLocalEffect: z2.string().min(1).max(500).optional(),
|
|
717
|
-
falsifier: z2.string().min(1).max(500).optional(),
|
|
718
|
-
alternatives: z2.array(z2.string().min(1).max(500)).min(1).max(8).optional(),
|
|
719
|
-
skipReason: z2.string().min(1).max(500).optional()
|
|
720
|
-
}).strict();
|
|
721
|
-
var EXECUTION_PROPOSAL_TEMPLATES = {
|
|
722
|
-
REPORT_DECIDED_ROLE_CLAIM: {
|
|
723
|
-
operation: "REPORT_DECIDED_ROLE_CLAIM",
|
|
724
|
-
decisionType: "REPORT_DECIDED_ROLE_CLAIM",
|
|
725
|
-
trigger: "\u5DF2\u7ECF\u51B3\u5B9A\u516C\u5F00\u9884\u8A00\u5BB6\u8EAB\u4EFD\uFF0C\u9700\u8981\u7EC4\u7EC7\u9996\u8F6E\u516C\u5F00\u53D1\u8A00",
|
|
726
|
-
rule: "\u5B8C\u6574\u8BF4\u660E\u67E5\u9A8C\u5EA7\u4F4D\u3001\u7ED3\u679C\u548C\u4E0B\u4E00\u591C\u9A8C\u4EBA\u8BA1\u5212",
|
|
727
|
-
boundary: "\u4E0D\u6539\u53D8\u662F\u5426\u8D77\u8DF3\u4EE5\u53CA\u67E5\u9A8C\u76EE\u6807",
|
|
728
|
-
alternativeAction: "\u5728\u540C\u4E00\u53D1\u8A00\u4E2D\u8865\u5145\u5B8C\u6574\u7684\u540E\u7EED\u4FE1\u606F\u94FE"
|
|
729
|
-
},
|
|
730
|
-
EXPLAIN_DECIDED_VOTE: {
|
|
731
|
-
operation: "EXPLAIN_DECIDED_VOTE",
|
|
732
|
-
decisionType: "EXPLAIN_DECIDED_VOTE",
|
|
733
|
-
trigger: "\u5DF2\u7ECF\u51B3\u5B9A\u6295\u7968\u76EE\u6807\uFF0C\u9700\u8981\u8BF4\u660E\u516C\u5F00\u7406\u7531",
|
|
734
|
-
rule: "\u53EA\u4F7F\u7528\u884C\u52A8\u524D\u516C\u5F00\u4FE1\u606F\u8BF4\u660E\u5DF2\u7ECF\u786E\u5B9A\u7684\u6295\u7968\u7406\u7531",
|
|
735
|
-
boundary: "\u4E0D\u6539\u53D8\u6295\u7968\u76EE\u6807\u6216\u53F7\u53EC\u5176\u4ED6\u73A9\u5BB6\u6539\u53D8\u6295\u7968\u76EE\u6807",
|
|
736
|
-
alternativeAction: "\u5728\u63D0\u4EA4\u76F8\u540C\u6295\u7968\u76EE\u6807\u65F6\u8865\u5145\u4E0E\u516C\u5F00\u4FE1\u606F\u4E00\u81F4\u7684\u7406\u7531"
|
|
737
|
-
},
|
|
738
|
-
RETRACT_PUBLIC_JUDGMENT: {
|
|
739
|
-
operation: "RETRACT_PUBLIC_JUDGMENT",
|
|
740
|
-
decisionType: "RETRACT_PUBLIC_JUDGMENT",
|
|
741
|
-
trigger: "\u5DF2\u7ECF\u786E\u8BA4\u6B64\u524D\u516C\u5F00\u5224\u65AD\u9519\u8BEF\uFF0C\u9700\u8981\u5728\u540E\u7EED\u53D1\u8A00\u4E2D\u66F4\u6B63",
|
|
742
|
-
rule: "\u660E\u786E\u64A4\u56DE\u65E7\u5224\u65AD\u5E76\u8BF4\u660E\u66F4\u65B0\u6240\u4F9D\u636E\u7684\u516C\u5F00\u4FE1\u606F",
|
|
743
|
-
boundary: "\u4E0D\u636E\u6B64\u6539\u53D8\u5F53\u524D\u6295\u7968\u76EE\u6807\u3001\u7528\u836F\u3001\u5F00\u67AA\u6216\u8EAB\u4EFD\u51B3\u7B56",
|
|
744
|
-
alternativeAction: "\u5728\u540E\u7EED\u53D1\u8A00\u4E2D\u660E\u786E\u64A4\u56DE\u65E7\u5224\u65AD\u5E76\u8BF4\u660E\u66F4\u65B0\u4F9D\u636E"
|
|
745
|
-
},
|
|
746
|
-
AVOID_REPEATING_PRIOR_SPEAKERS: {
|
|
747
|
-
operation: "AVOID_REPEATING_PRIOR_SPEAKERS",
|
|
748
|
-
decisionType: "AVOID_REPEATING_PRIOR_SPEAKERS",
|
|
749
|
-
trigger: "\u8F6E\u5230\u81EA\u5DF1\u53D1\u8A00\u4E14\u524D\u7F6E\u4F4D\u5DF2\u7ECF\u5B8C\u6574\u8868\u8FBE\u76F8\u540C\u89C2\u70B9",
|
|
750
|
-
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",
|
|
751
|
-
boundary: "\u4E0D\u6539\u53D8\u5F53\u524D\u7AD9\u8FB9\u3001\u6295\u7968\u76EE\u6807\u6216\u8EAB\u4EFD\u51B3\u7B56",
|
|
752
|
-
alternativeAction: "\u53EA\u8868\u8FBE\u76F8\u5BF9\u4E8E\u524D\u7F6E\u53D1\u8A00\u65B0\u589E\u7684\u5224\u65AD\u4F9D\u636E"
|
|
753
|
-
},
|
|
754
|
-
EXPLAIN_DECIDED_WOLF_TARGET: {
|
|
755
|
-
operation: "EXPLAIN_DECIDED_WOLF_TARGET",
|
|
756
|
-
decisionType: "EXPLAIN_DECIDED_WOLF_TARGET",
|
|
757
|
-
trigger: "\u72FC\u961F\u884C\u52A8\u76EE\u6807\u5DF2\u7ECF\u786E\u5B9A\uFF0C\u9700\u8981\u5411\u961F\u53CB\u8BF4\u660E\u8BA1\u5212",
|
|
758
|
-
rule: "\u53EA\u4F7F\u7528\u72FC\u961F\u5F53\u65F6\u5DF2\u77E5\u7684\u4FE1\u606F\u8BF4\u660E\u5DF2\u7ECF\u786E\u5B9A\u7684\u884C\u52A8\u8BA1\u5212",
|
|
759
|
-
boundary: "\u4E0D\u6539\u53D8\u884C\u52A8\u76EE\u6807\u6216\u884C\u52A8\u7C7B\u578B",
|
|
760
|
-
alternativeAction: "\u5411\u961F\u53CB\u8BF4\u660E\u76F8\u540C\u884C\u52A8\u76EE\u6807\u7684\u516C\u5F00\u4F9D\u636E\u548C\u540E\u7EED\u8BA1\u5212"
|
|
761
|
-
}
|
|
762
|
-
};
|
|
763
|
-
var STRATEGY_LANGUAGE = /(?:改变|改投|改票|转票|投给|投票目标|查验目标|验谁|刀谁|刀口|毒谁|救谁|用药|开枪|起跳|跳预言家|自刀|悍跳|倒钩|站边|目标座位|targetSeat|actionType|vote target|check target|kill target)/i;
|
|
764
|
-
var FIXED_RULE_LANGUAGE = /(?:JSON\s*schema|JSON格式|非法动作|角色动作合法|私有信息保护|不虚构时间线|工具失败|输出超时|现实人格|人身攻击)/i;
|
|
765
|
-
var COUNTER_EFFECT_LANGUAGE = /(?:未能|没有|无法|无效|反而|恶化|失败|矛盾|误导|暴露|did not|failed|ineffective|worse|contradict)/i;
|
|
766
|
-
var ADVERSE_LOCAL_EFFECT_LANGUAGE = /(?:未能|无法|无效|反而|恶化|失败|错误|矛盾|误导|暴露|质疑|追问|要求补充|分歧|混乱|降低|减少|缩小|被[^。;,,!!]{0,8}(?:放逐|投出|淘汰)|(?:狼面|好人面)[^。;,,!!]{0,6}(?:拉满|下降)|did not|failed|ineffective|worse|questioned|challenged)/i;
|
|
767
|
-
var BENEFICIAL_LOCAL_EFFECT_LANGUAGE = /(?:成功|改善|提升|增加|跟进|认可|支持|聚焦|集中|形成[^。;,,!!]{0,8}(?:讨论|站边|共识)|达成[^。;,,!!]{0,8}(?:一致|共识)|(?:提交|改投)[^。;,,!!]{0,8}投票|(?:放逐|投出|淘汰)[^。;,,!!]{0,6}(?:目标|狼人|狼)|没有再次(?:质疑|追问|要求补充)|不再(?:质疑|追问|要求补充)|succeeded|improved|followed up|supported|reached consensus)/i;
|
|
768
|
-
var NO_TARGET_ALTERNATIVE_LANGUAGE = /(?:保留投票权|等待更多信息|暂不(?:投票|选择|行动)|弃票|不选(?:择)?(?:任何)?(?:目标|座位)|不指定目标|不设目标|继续观望|\b(?:wait for more information|abstain|hold (?:the )?vote|choose no target)\b)/i;
|
|
769
|
-
var AMBIGUOUS_ALTERNATIVE_LANGUAGE = /(?:或者|或是|要么|二选一|[号座]\s*或\s*[1-9]|[1-9][0-9]*\s*[、/]\s*[1-9][0-9]*|[1-9][0-9]*\s*号?\s*(?:和|与)\s*[1-9][0-9]*\s*号?\s*(?:(?:中|之间)\s*)?(?:选择|选一个|任选|择一|中的一个)|\bor\b)/i;
|
|
770
|
-
var TARGET_UNCHANGED_LANGUAGE = /(?:不|不得|不会)(?:改变|更改|调整|切换)(?:当前|原有|既定)?(?:的)?(?:行动|投票|查验|刀人|用药|开枪)?目标|(?:保持|维持)(?:原有|原定|既定|当前|相同)(?:的)?(?:行动|投票|查验|刀人|用药|开枪)?目标/i;
|
|
771
|
-
var RETAINED_TARGET_SEAT_LANGUAGE = /(?:行动|投票|查验|刀人|用药|开枪)?目标\s*(?:仍(?:然)?|依然|依旧|继续|保持|维持|不变)\s*(?:是|为)?\s*([1-9][0-9]*)\s*号/i;
|
|
772
|
-
var LOCAL_OUTCOME_INFERENCE_LANGUAGE = /(?:,|;|。|,|;)\s*(?:(?:由此|因此|从而|所以)(?:可见|可知|可判断|说明|证明|表明|意味着)?|(?:这)?(?:说明|证明|表明|意味着|可见|足以(?:说明|证明|表明))|\b(?:therefore|thus|this (?:proves?|shows?|means?))\b)/i;
|
|
773
|
-
var SOCIAL_OUTCOME_LANGUAGE = /(?:将|把)[^。;,,!!]{0,12}(?:怀疑|焦点|注意力)[^。;,,!!]{0,8}(?:导向|转向|锁定)|(?:被|已被|因此被)?[^。;,,!!]{0,8}(?:排除|移出)[^。;,,!!]{0,8}(?:怀疑|狼坑|焦点)|(?:形成|达成|建立)[^。;,,!!]{0,8}(?:统一站边|一致判断|共识)|(?:狼面|好人面)[^。;,,!!]{0,6}(?:拉满|上升|下降)|(?:纠错|怀疑)(?:空间|范围)[^。;,,!!]{0,6}(?:缩小|扩大)|\b(?:cleared from suspicion|consensus formed|attention shifted to)\b/i;
|
|
774
|
-
var ABSOLUTE_STRATEGY_LANGUAGE = /(?:必须|必然|绝对|肯定|一定|毫无疑问|等于直接|唯一(?:正确|合理)?(?:的)?(?:选择|做法)|只能|只能够|无论如何(?:都)?|非[^。;,,!!]{0,8}不可|别无选择|\bmust\b|\balways\b|\bnever\b|\bdefinitely\b|\bcertain(?:ly)?\b|\bguaranteed?\b|the only (?:correct |valid )?(?:choice|option))/i;
|
|
775
|
-
var EXPLICIT_TARGET_LANGUAGE = /(?:(?:改投|改票(?:到|给)?|归票|票投|投票(?:给|到)?|投(?:给|到)?|查验|验|刀|毒|救|开枪带走|目标(?:改为|是)?)\s*|target(?:\s+seat)?[^0-9]{0,6})([1-9][0-9]*)\s*(?:号|座|\b)/gi;
|
|
776
|
-
var FINAL_RESULT_LANGUAGE = /(?:最终|终局|全场|对局结果|比赛结果)[^。;,,!!]{0,16}(?:获胜|胜利|胜出|取胜|赢了|输了|落败|失败)|(?:好人(?:阵营)?|村民|平民|狼人(?:阵营)?|狼队)[^。;,,!!]{0,10}(?:获胜|胜利|胜出|取胜|赢了|输了|落败)|(?:险胜|惨胜|翻盘获胜|为(?:最终)?胜利铺路)|赢下(?:本局|这局|对局|比赛)|(?:GOOD|WOLF)(?:_TEAM)?_WIN|(?:the\s+)?(?:(?:good|village|wolf)\s+team|villagers?|village|wolves|wolf|werewolves?)\s+(?:wins?|won|loses?|lost)|(?:won|lost) the game|final (?:victory|defeat)/i;
|
|
777
|
-
var SEAT_REFERENCE_LANGUAGE = /([1-9][0-9]*)\s*号(?:玩家)?/g;
|
|
778
|
-
var BEHAVIOR_TERMS = "\u53D1\u8A00|\u8868\u73B0|\u884C\u4E3A|\u8BF4\u6CD5|\u5185\u5BB9|\u7AD9\u8FB9|\u7968\u578B|\u6295\u7968|\u5F52\u7968|\u7529\u9505|\u8D28\u7591|\u6000\u7591|\u63D0\u95EE|\u53D1\u95EE|\u5BF9\u8DF3|\u8D77\u8DF3|\u608D\u8DF3|\u5012\u94A9|\u67E5\u6740|\u4FDD\u4EBA|\u8E29\u4EBA|\u653B\u51FB|\u8FA9\u89E3|\u8DDF\u7968|\u51B2\u7968|\u8868\u6C34|\u81EA\u79F0|\u58F0\u79F0|\u516C\u5F00\u8EAB\u4EFD|\u516C\u5F00\u9884\u8A00\u5BB6|\u516C\u5F00\u5973\u5DEB|\u516C\u5F00\u730E\u4EBA|\u8DF3\u9884\u8A00\u5BB6|\u8DF3\u5973\u5DEB|\u8DF3\u730E\u4EBA";
|
|
779
|
-
var FIRST_NIGHT_DAYTIME_INFORMATION = new RegExp(
|
|
780
|
-
`(?:\u73A9\u5BB6)?\u53D1\u8A00\u98CE\u683C|(?:\u767D\u5929|\u767D\u663C|\u65E5\u95F4|\u9996\u65E5|\u7B2C\u4E00\u5929|\u5929\u4EAE\u540E|\u6B21\u65E5|\u7B2C\u4E8C\u5929|\u7B2C\u4E8C\u591C|\u660E\u5929|\u660E\u65E5|\u4E0B\u4E2A(?:\u56DE\u5408|\u8F6E|\u767D\u5929|\u591C\u665A)|\u4E0B\u4E00(?:\u5929|\u56DE\u5408|\u8F6E|\u591C|\u591C\u665A)|\u968F\u540E|\u540E\u7EED)[^\u3002\uFF1B\uFF0C,!\uFF01]{0,16}(?:${BEHAVIOR_TERMS})|(?:${BEHAVIOR_TERMS})[^\u3002\uFF1B\uFF0C,!\uFF01]{0,16}(?:\u767D\u5929|\u767D\u663C|\u65E5\u95F4|\u9996\u65E5|\u7B2C\u4E00\u5929|\u5929\u4EAE\u540E|\u6B21\u65E5|\u7B2C\u4E8C\u5929|\u7B2C\u4E8C\u591C|\u660E\u5929|\u660E\u65E5|\u4E0B\u4E2A(?:\u56DE\u5408|\u8F6E|\u767D\u5929|\u591C\u665A)|\u4E0B\u4E00(?:\u5929|\u56DE\u5408|\u8F6E|\u591C|\u591C\u665A)|\u968F\u540E|\u540E\u7EED)`,
|
|
781
|
-
"i"
|
|
782
|
-
);
|
|
783
|
-
var DIRECTLY_NEGATED_DAYTIME_INFORMATION = /(?:尚无|暂无|没有|尚未(?:出现|发生)?)(?:任何)?(?:白天|白昼|日间|首日|第一天)?(?:发言|站边|票型|归票|信息)|不(?:得|可|能|应)?(?:参考|使用|依赖)(?:(?:任何)?(?:白天|白昼|日间|首日|第一天)(?:发言|站边|票型|归票|信息)|(?:玩家)?发言风格)|(?:白天|白昼|日间|首日|第一天)(?:发言|站边|票型|归票|信息)(?:尚无|暂无|尚未(?:出现|发生)|不可用|不能使用)/gi;
|
|
784
|
-
var RELATIVE_FUTURE_BEHAVIOR_LANGUAGE = new RegExp(
|
|
785
|
-
`(?:(?:\u540E\u7F6E\u4F4D|\u5176\u4ED6\u73A9\u5BB6)[^\u3002\uFF1B\uFF0C,!\uFF01]{0,10}(?:\u968F\u540E|\u4E4B\u540E|\u5C06\u4F1A?|\u7A0D\u540E)|\u5929\u4EAE(?:\u540E|\u4E4B\u540E)|\u6B21\u65E5|\u660E\u5929|\u660E\u65E5|\u4E0B\u4E2A(?:\u5929|\u56DE\u5408|\u8F6E|\u767D\u5929|\u591C\u665A)|\u4E0B\u4E00(?:\u5929|\u56DE\u5408|\u8F6E|\u4E2A\u767D\u5929|\u591C|\u591C\u665A))[^\u3002\uFF1B\uFF0C,!\uFF01]{0,20}(?:${BEHAVIOR_TERMS})`,
|
|
786
|
-
"i"
|
|
787
|
-
);
|
|
788
|
-
var ABSOLUTE_DAY_BEHAVIOR_LANGUAGE = new RegExp(`(?:\u7B2C([0-9\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u5341]+)|([\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u5341]+))\\s*(?:\u5929|\u8F6E|\u56DE\u5408|\u591C|\u591C\u665A)[^\u3002\uFF1B\uFF0C,!\uFF01]{0,24}(?:${BEHAVIOR_TERMS})`, "gi");
|
|
789
|
-
var BEHAVIOR_OCCURRENCE_LANGUAGE = new RegExp(`(?:${BEHAVIOR_TERMS})`, "i");
|
|
790
|
-
var PAST_BEHAVIOR_LANGUAGE = new RegExp(`(?:\u6B64\u524D|\u4E4B\u524D|\u66FE\u7ECF|\u8FC7\u53BB|\u4E0A\u4E00\u8F6E|\u4E0A\u4E00\u591C|\u6628\u591C)|\u5DF2\u7ECF(?!\u51B3\u5B9A)[^\u3002\uFF1B\uFF0C,!\uFF01]{0,4}(?:${BEHAVIOR_TERMS})`, "i");
|
|
791
|
-
var CURRENT_ACTOR_ACTION_LANGUAGE = /(?:当前|本次|此时|轮到|发言(?:时|中)|投票时|行动时|查验时|已经决定|正在|正要|准备|计划|将要)/i;
|
|
792
|
-
var NEGATED_BEHAVIOR_LANGUAGE = new RegExp(`(?:\u6CA1\u6709|\u5E76\u672A|\u672A\u66FE|\u4E0D\u66FE|\u4ECE\u672A|\u5C1A\u672A|\u4E0D)[^\u3002\uFF1B\uFF0C,!\uFF01]{0,6}(?:${BEHAVIOR_TERMS})|(?:did not|never|no)\\b`, "i");
|
|
793
|
-
var BEHAVIOR_TARGET_LANGUAGE = /(?:归票|投票(?:给|到)?|票投(?:给|到)?|投(?:给|到)|跟票(?:给|到)?|冲票(?:给|到)?|查杀|保人|踩|攻击|质疑|怀疑|提问|发问)(?:给|到|向)?\s*([1-9][0-9]*)\s*号|(?:对|向)\s*([1-9][0-9]*)\s*号(?:玩家)?\s*(?:的\s*)?(?:(?:提出|发起|进行)\s*)?(?:质疑|怀疑|攻击|踩人|提问|发问)/i;
|
|
794
|
-
var TARGET_REFERENCE_PREFIX = /(?:归票|投票|票投|投给|投到|跟票|冲票|查杀|保人|踩|攻击|质疑)(?:给|到|向)?\s*$/i;
|
|
795
|
-
var TARGET_OBJECT_PREFIX = /(?:对|向)\s*$/i;
|
|
796
|
-
var TARGET_OBJECT_BEHAVIOR = /^\s*(?:的\s*)?(?:(?:提出|发起|进行)\s*)?(?:质疑|怀疑|攻击|踩人|提问|发问)/i;
|
|
797
|
-
var COORDINATED_SEAT_CONNECTOR = /^\s*(?:和|与|、)\s*$/;
|
|
798
|
-
var GENERIC_SPEECH_REFERENCE_LANGUAGE = /^[1-9][0-9]*\s*号(?:玩家)?(?:的)?(?:发言|说法|内容)(?:差异|区别|异同|风格|逻辑|观点)?$/i;
|
|
799
|
-
var SPEECH_FACT_TYPES = /* @__PURE__ */ new Set(["DAY_SPEAK", "LAST_WORD", "WOLF_SPEECH"]);
|
|
800
|
-
var VOTE_FACT_TYPES = /* @__PURE__ */ new Set(["DAY_VOTE_SUBMIT", "DAY_REVOTE_SUBMIT"]);
|
|
801
|
-
var CHALLENGE_BEHAVIOR_LANGUAGE = /(?:质疑|怀疑|攻击|踩人|提问|发问|question|suspect|attack)/i;
|
|
802
|
-
var BEHAVIOR_GROUPS = [
|
|
803
|
-
/(?:投票|归票|跟票|冲票|票投|出票)/i,
|
|
804
|
-
/(?:甩锅|推责|责任推|把责任)/i,
|
|
805
|
-
/(?:站边|支持|认好|认狼|side with|support)/i,
|
|
806
|
-
CHALLENGE_BEHAVIOR_LANGUAGE,
|
|
807
|
-
/(?:对跳|起跳|悍跳|拍身份|公开身份|自称|声称|(?:公开|跳)(?:预言家|女巫|猎人)|role claim|claim(?:ed)? (?:seer|witch|hunter))/i,
|
|
808
|
-
/(?:倒钩)/i,
|
|
809
|
-
/(?:查杀)/i,
|
|
810
|
-
/(?:保人|金水)/i,
|
|
811
|
-
/(?:辩解|表水)/i
|
|
812
|
-
];
|
|
813
|
-
var ROLE_NAME = "\u9884\u8A00\u5BB6|\u5973\u5DEB|\u730E\u4EBA|\u72FC\u4EBA|\u597D\u4EBA|\u5E73\u6C11|\u6751\u6C11";
|
|
814
|
-
var ENGLISH_ROLE_NAME = "seer|witch|hunter|werewolf|wolf|good(?: player)?|villager";
|
|
815
|
-
var CONDITIONAL_IDENTITY_LANGUAGE = /(?:如果|若|假如|假设|可能|或许|怀疑|认为|倾向|猜测|未必|不确定)[^。;,,!!]{0,8}$/i;
|
|
816
|
-
var SPEECH_OUTCOME_FACT_TYPES = /* @__PURE__ */ new Set(["DAY_SPEAK", "LAST_WORD", "WOLF_SPEECH"]);
|
|
817
|
-
var LOCAL_OUTCOME_FACT_TYPES = /* @__PURE__ */ new Set([
|
|
818
|
-
"WOLF_CHOOSE",
|
|
819
|
-
"WOLF_SPEECH",
|
|
820
|
-
"WOLF_TARGET_CONFIRMED",
|
|
821
|
-
"WOLF_TARGET_RANDOM",
|
|
822
|
-
"WOLF_TARGET_NONE",
|
|
823
|
-
"WOLF_TARGET_CONFLICT_RETRY",
|
|
824
|
-
"WITCH_SAVE",
|
|
825
|
-
"WITCH_SKIP_SAVE",
|
|
826
|
-
"WITCH_POISON",
|
|
827
|
-
"WITCH_SKIP_POISON",
|
|
828
|
-
"WITCH_PASS",
|
|
829
|
-
"SEER_CHECK",
|
|
830
|
-
"SEER_SKIP_CHECK",
|
|
831
|
-
"NIGHT_RESOLVED",
|
|
832
|
-
"DAWN_ANNOUNCE",
|
|
833
|
-
"PRIVATE_NIGHT_HUNTER_SHOOT",
|
|
834
|
-
"PRIVATE_NIGHT_HUNTER_PASS",
|
|
835
|
-
"HUNTER_SHOOT",
|
|
836
|
-
"HUNTER_PASS",
|
|
837
|
-
"DAY_SPEAK",
|
|
838
|
-
"LAST_WORD",
|
|
839
|
-
"DAY_VOTE_SUBMIT",
|
|
840
|
-
"DAY_VOTE_COUNT",
|
|
841
|
-
"DAY_VOTE_TIE",
|
|
842
|
-
"DAY_VOTE_ELIMINATED",
|
|
843
|
-
"DAY_REVOTE_SUBMIT",
|
|
844
|
-
"DAY_REVOTE_COUNT",
|
|
845
|
-
"DAY_REVOTE_ELIMINATED",
|
|
846
|
-
"DAY_REVOTE_TIE",
|
|
847
|
-
"DAY_PEACE",
|
|
848
|
-
"DAY_RESOLVED"
|
|
849
|
-
]);
|
|
850
|
-
var TARGET_REQUIRED_ACTIONS = /* @__PURE__ */ new Set([
|
|
851
|
-
"WOLF_KILL",
|
|
852
|
-
"WITCH_SAVE",
|
|
853
|
-
"WITCH_POISON",
|
|
854
|
-
"SEER_CHECK",
|
|
855
|
-
"HUNTER_SHOOT"
|
|
856
|
-
]);
|
|
857
|
-
var TARGETLESS_ACTIONS = /* @__PURE__ */ new Set([
|
|
858
|
-
"WITCH_SKIP_SAVE",
|
|
859
|
-
"WITCH_SKIP_POISON",
|
|
860
|
-
"WITCH_PASS",
|
|
861
|
-
"SEER_SKIP_CHECK",
|
|
862
|
-
"HUNTER_PASS"
|
|
863
|
-
]);
|
|
864
|
-
var ProposalError = class extends Error {
|
|
865
|
-
constructor(code, message) {
|
|
866
|
-
super(message);
|
|
867
|
-
this.code = code;
|
|
868
|
-
this.name = "ProposalError";
|
|
869
|
-
}
|
|
870
|
-
code;
|
|
871
|
-
retryable = false;
|
|
872
|
-
};
|
|
873
|
-
function requireText(proposal, key, min = 2) {
|
|
874
|
-
const value = proposal[key];
|
|
875
|
-
if (typeof value !== "string" || value.trim().length < min) {
|
|
876
|
-
throw new ProposalError("QUALITY_FIELD_MISSING", `${String(key)} must be concrete and non-empty`);
|
|
877
|
-
}
|
|
878
|
-
return value.trim();
|
|
879
|
-
}
|
|
880
|
-
function unique(values, code) {
|
|
881
|
-
if (new Set(values).size !== values.length) throw new ProposalError(code, "Fact references must be unique");
|
|
882
|
-
}
|
|
883
|
-
function semanticText(value) {
|
|
884
|
-
return value.toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, "");
|
|
885
|
-
}
|
|
886
|
-
function ngrams(value) {
|
|
887
|
-
const normalized = semanticText(value);
|
|
888
|
-
const out = /* @__PURE__ */ new Set();
|
|
889
|
-
for (let index = 0; index < normalized.length - 1; index++) out.add(normalized.slice(index, index + 2));
|
|
890
|
-
if (out.size === 0 && normalized) out.add(normalized);
|
|
891
|
-
return out;
|
|
892
|
-
}
|
|
893
|
-
function similarity(left, right) {
|
|
894
|
-
const a = ngrams(left);
|
|
895
|
-
const b = ngrams(right);
|
|
896
|
-
if (a.size === 0 || b.size === 0) return 0;
|
|
897
|
-
let intersection = 0;
|
|
898
|
-
for (const item of a) if (b.has(item)) intersection++;
|
|
899
|
-
return 2 * intersection / (a.size + b.size);
|
|
900
|
-
}
|
|
901
|
-
function sameSemanticText(left, right) {
|
|
902
|
-
return typeof left === "string" && semanticText(left) === semanticText(right);
|
|
903
|
-
}
|
|
904
|
-
function stripUnavailableDaytimeInformation(value) {
|
|
905
|
-
return value.replace(DIRECTLY_NEGATED_DAYTIME_INFORMATION, "");
|
|
906
|
-
}
|
|
907
|
-
function behaviorTarget(value) {
|
|
908
|
-
const direct = BEHAVIOR_TARGET_LANGUAGE.exec(value);
|
|
909
|
-
if (direct) return Number(direct[1] ?? direct[2]);
|
|
910
|
-
for (const match of value.matchAll(SEAT_REFERENCE_LANGUAGE)) {
|
|
911
|
-
const prefix = value.slice(Math.max(0, match.index - 12), match.index);
|
|
912
|
-
if (TARGET_REFERENCE_PREFIX.test(prefix)) return Number(match[1]);
|
|
913
|
-
}
|
|
914
|
-
return void 0;
|
|
915
|
-
}
|
|
916
|
-
function questionTargetsSeat(summary, target) {
|
|
917
|
-
return summary.split(/[。;;\n]/).some((sentence) => {
|
|
918
|
-
if (!/[??]/.test(sentence)) return false;
|
|
919
|
-
const seats = new Set([...sentence.matchAll(SEAT_REFERENCE_LANGUAGE)].map((match) => Number(match[1])));
|
|
920
|
-
return seats.size === 1 && seats.has(target);
|
|
921
|
-
});
|
|
922
|
-
}
|
|
923
|
-
function factSupportsBehaviorClaim(fact, claim) {
|
|
924
|
-
if (fact.actorSeat == null) return false;
|
|
925
|
-
const summary = fact.summary;
|
|
926
|
-
const claimedTarget = behaviorTarget(claim);
|
|
927
|
-
const summaryMentionsClaimedTarget = claimedTarget !== void 0 && new RegExp(`(?:^|[^0-9])${claimedTarget}\\s*\u53F7`).test(summary);
|
|
928
|
-
if (claimedTarget !== void 0) {
|
|
929
|
-
const observedTarget = fact.targetSeat ?? behaviorTarget(summary);
|
|
930
|
-
const questionSupportsChallenge = SPEECH_FACT_TYPES.has(fact.type) && CHALLENGE_BEHAVIOR_LANGUAGE.test(claim) && questionTargetsSeat(summary, claimedTarget);
|
|
931
|
-
if (observedTarget !== claimedTarget && !questionSupportsChallenge) return false;
|
|
932
|
-
}
|
|
933
|
-
if (NEGATED_BEHAVIOR_LANGUAGE.test(claim) !== NEGATED_BEHAVIOR_LANGUAGE.test(summary)) {
|
|
934
|
-
return false;
|
|
935
|
-
}
|
|
936
|
-
const groups = BEHAVIOR_GROUPS.filter((pattern) => pattern.test(claim));
|
|
937
|
-
const isCompletedVoteClaim = /(?:投票|投给|投到|票投|出票)/i.test(claim) && claimedTarget !== void 0;
|
|
938
|
-
if (isCompletedVoteClaim) {
|
|
939
|
-
return VOTE_FACT_TYPES.has(fact.type) && (fact.targetSeat ?? behaviorTarget(summary)) === claimedTarget;
|
|
940
|
-
}
|
|
941
|
-
if (groups.length > 0) {
|
|
942
|
-
if (!SPEECH_FACT_TYPES.has(fact.type)) return false;
|
|
943
|
-
return groups.every((pattern) => pattern.test(summary) || pattern === CHALLENGE_BEHAVIOR_LANGUAGE && claimedTarget !== void 0 && summaryMentionsClaimedTarget && questionTargetsSeat(summary, claimedTarget));
|
|
944
|
-
}
|
|
945
|
-
if (/(?:发言|说法|内容)/i.test(claim) && SPEECH_FACT_TYPES.has(fact.type)) {
|
|
946
|
-
if (GENERIC_SPEECH_REFERENCE_LANGUAGE.test(claim.trim())) return true;
|
|
947
|
-
const shortGenericClaim = semanticText(claim).length <= 6;
|
|
948
|
-
return shortGenericClaim || similarity(claim, summary) >= 0.28;
|
|
949
|
-
}
|
|
950
|
-
return similarity(claim, summary) >= 0.35;
|
|
951
|
-
}
|
|
952
|
-
function behaviorActorSeats(value) {
|
|
953
|
-
const actors = new Set(seatBehaviorClaims(value).map(({ seat }) => seat));
|
|
954
|
-
for (const match of value.matchAll(/(?:^|[。;,,;]\s*)seat\s*=?\s*([1-9][0-9]*)\s*(?:;|,)?\s*(?:content\s*=)?/gi)) {
|
|
955
|
-
actors.add(Number(match[1]));
|
|
956
|
-
}
|
|
957
|
-
return actors;
|
|
958
|
-
}
|
|
959
|
-
function seatBehaviorClaims(value) {
|
|
960
|
-
const claims = [];
|
|
961
|
-
for (const clause of value.split(/[。;,,!!]/)) {
|
|
962
|
-
const seats = [...clause.matchAll(SEAT_REFERENCE_LANGUAGE)];
|
|
963
|
-
const targetSeatIndexes = /* @__PURE__ */ new Set();
|
|
964
|
-
const coordinatedActorIndexes = /* @__PURE__ */ new Set();
|
|
965
|
-
for (let index = 0; index < seats.length; index++) {
|
|
966
|
-
if (targetSeatIndexes.has(index) || coordinatedActorIndexes.has(index)) continue;
|
|
967
|
-
const match = seats[index];
|
|
968
|
-
const start = match.index;
|
|
969
|
-
const nextSeat = seats[index + 1];
|
|
970
|
-
const beforeNextSeat = nextSeat ? clause.slice(start + match[0].length, nextSeat.index) : "";
|
|
971
|
-
const afterNextSeat = nextSeat ? clause.slice(nextSeat.index + nextSeat[0].length) : "";
|
|
972
|
-
const directTarget = nextSeat && TARGET_REFERENCE_PREFIX.test(beforeNextSeat);
|
|
973
|
-
const postpositiveTarget = nextSeat && TARGET_OBJECT_PREFIX.test(beforeNextSeat) && TARGET_OBJECT_BEHAVIOR.test(afterNextSeat);
|
|
974
|
-
if (directTarget || postpositiveTarget) targetSeatIndexes.add(index + 1);
|
|
975
|
-
if (nextSeat && COORDINATED_SEAT_CONNECTOR.test(beforeNextSeat)) {
|
|
976
|
-
const coordinatedClaim = `${match[0]}${afterNextSeat}`.trim();
|
|
977
|
-
const nextCoordinatedClaim = `${nextSeat[0]}${afterNextSeat}`.trim();
|
|
978
|
-
if (BEHAVIOR_OCCURRENCE_LANGUAGE.test(coordinatedClaim) && BEHAVIOR_OCCURRENCE_LANGUAGE.test(nextCoordinatedClaim)) {
|
|
979
|
-
claims.push(
|
|
980
|
-
{ seat: Number(match[1]), claim: coordinatedClaim },
|
|
981
|
-
{ seat: Number(nextSeat[1]), claim: nextCoordinatedClaim }
|
|
982
|
-
);
|
|
983
|
-
coordinatedActorIndexes.add(index + 1);
|
|
984
|
-
continue;
|
|
985
|
-
}
|
|
986
|
-
}
|
|
987
|
-
const end = postpositiveTarget ? clause.length : directTarget ? nextSeat.index + nextSeat[0].length : nextSeat?.index ?? clause.length;
|
|
988
|
-
const claim = clause.slice(start, end).trim();
|
|
989
|
-
if (BEHAVIOR_OCCURRENCE_LANGUAGE.test(claim)) claims.push({ seat: Number(match[1]), claim });
|
|
990
|
-
}
|
|
991
|
-
}
|
|
992
|
-
return claims;
|
|
993
|
-
}
|
|
994
|
-
function isCurrentDecisionActorClaim(claim) {
|
|
995
|
-
return !PAST_BEHAVIOR_LANGUAGE.test(claim) && CURRENT_ACTOR_ACTION_LANGUAGE.test(claim);
|
|
996
|
-
}
|
|
997
|
-
function chineseNumber(value) {
|
|
998
|
-
if (/^[0-9]+$/.test(value)) return Number(value);
|
|
999
|
-
const digits = {
|
|
1000
|
-
\u4E00: 1,
|
|
1001
|
-
\u4E8C: 2,
|
|
1002
|
-
\u4E09: 3,
|
|
1003
|
-
\u56DB: 4,
|
|
1004
|
-
\u4E94: 5,
|
|
1005
|
-
\u516D: 6,
|
|
1006
|
-
\u4E03: 7,
|
|
1007
|
-
\u516B: 8,
|
|
1008
|
-
\u4E5D: 9
|
|
1009
|
-
};
|
|
1010
|
-
if (value === "\u5341") return 10;
|
|
1011
|
-
if (value.startsWith("\u5341")) return 10 + (digits[value[1]] ?? 0);
|
|
1012
|
-
if (value.endsWith("\u5341")) return (digits[value[0]] ?? 0) * 10;
|
|
1013
|
-
const [tens, ones] = value.split("\u5341");
|
|
1014
|
-
if (ones !== void 0) return (digits[tens] ?? 0) * 10 + (digits[ones] ?? 0);
|
|
1015
|
-
return digits[value];
|
|
1016
|
-
}
|
|
1017
|
-
function dependsOnFutureBehavior(value, currentRound) {
|
|
1018
|
-
if (RELATIVE_FUTURE_BEHAVIOR_LANGUAGE.test(value)) return true;
|
|
1019
|
-
if (currentRound === void 0) return false;
|
|
1020
|
-
for (const match of value.matchAll(ABSOLUTE_DAY_BEHAVIOR_LANGUAGE)) {
|
|
1021
|
-
const referencedRound = chineseNumber(match[1] ?? match[2] ?? "");
|
|
1022
|
-
if (referencedRound !== void 0 && referencedRound > currentRound) return true;
|
|
1023
|
-
}
|
|
1024
|
-
return false;
|
|
1025
|
-
}
|
|
1026
|
-
function assertBehaviorIsObserved(proposal) {
|
|
1027
|
-
const behavior = proposal.behavior ?? "";
|
|
1028
|
-
const overlap = proposal.source === "EXEMPLAR" || proposal.action === "COUNTER" ? similarity(behavior, proposal.alternativeAction ?? "") : Math.max(
|
|
1029
|
-
similarity(behavior, proposal.alternativeAction ?? ""),
|
|
1030
|
-
similarity(behavior, proposal.rule ?? "")
|
|
1031
|
-
);
|
|
1032
|
-
if (overlap >= 0.68) {
|
|
1033
|
-
throw new ProposalError(
|
|
1034
|
-
"BEHAVIOR_COUNTERFACTUAL",
|
|
1035
|
-
"behavior must describe the observed action, not the counterfactual action"
|
|
1036
|
-
);
|
|
1037
|
-
}
|
|
1038
|
-
}
|
|
1039
|
-
function assertBehaviorMatchesAnchor(proposal, behavior, anchor) {
|
|
1040
|
-
const explicitActors = behaviorActorSeats(behavior);
|
|
1041
|
-
if ([...explicitActors].some((seat) => anchor.actorSeat !== seat)) {
|
|
1042
|
-
throw new ProposalError(
|
|
1043
|
-
"BEHAVIOR_FACT_MISMATCH",
|
|
1044
|
-
"behavior actor seat does not match the trusted anchor fact"
|
|
1045
|
-
);
|
|
1046
|
-
}
|
|
1047
|
-
if (factSupportsBehaviorClaim(anchor, behavior)) return;
|
|
1048
|
-
throw new ProposalError(
|
|
1049
|
-
"BEHAVIOR_FACT_MISMATCH",
|
|
1050
|
-
"behavior is not supported by the trusted anchor fact"
|
|
1051
|
-
);
|
|
1052
|
-
}
|
|
1053
|
-
function assertAlternativeTargetConsistent(proposal) {
|
|
1054
|
-
const target = proposal.alternativeTargetSeat;
|
|
1055
|
-
if (target == null) return;
|
|
1056
|
-
const action = proposal.alternativeAction ?? "";
|
|
1057
|
-
const mentionedTargets = [...action.matchAll(EXPLICIT_TARGET_LANGUAGE)].map((match) => Number(match[1]));
|
|
1058
|
-
if (mentionedTargets.length === 0 && NO_TARGET_ALTERNATIVE_LANGUAGE.test(action)) {
|
|
1059
|
-
throw new ProposalError(
|
|
1060
|
-
"ALTERNATIVE_TARGET_CONTRADICTION",
|
|
1061
|
-
"alternativeTargetSeat contradicts an alternative action that selects no target"
|
|
1062
|
-
);
|
|
1063
|
-
}
|
|
1064
|
-
if (mentionedTargets.length > 0 && !mentionedTargets.includes(target)) {
|
|
1065
|
-
throw new ProposalError(
|
|
1066
|
-
"ALTERNATIVE_TARGET_CONTRADICTION",
|
|
1067
|
-
"alternativeTargetSeat contradicts the target explicitly named by alternativeAction"
|
|
1068
|
-
);
|
|
1069
|
-
}
|
|
1070
|
-
}
|
|
1071
|
-
function assertCounterfactualCoherence(proposal, anchor) {
|
|
1072
|
-
const alternative = proposal.alternativeAction ?? "";
|
|
1073
|
-
if (AMBIGUOUS_ALTERNATIVE_LANGUAGE.test(alternative)) {
|
|
1074
|
-
throw new ProposalError(
|
|
1075
|
-
"ALTERNATIVE_ACTION_AMBIGUOUS",
|
|
1076
|
-
"alternativeAction must contain exactly one counterfactual action"
|
|
1077
|
-
);
|
|
1078
|
-
}
|
|
1079
|
-
const target = proposal.alternativeTargetSeat;
|
|
1080
|
-
const boundary = proposal.boundary ?? "";
|
|
1081
|
-
const retainedTarget = RETAINED_TARGET_SEAT_LANGUAGE.exec(boundary);
|
|
1082
|
-
if (target != null && (target !== anchor.targetSeat && TARGET_UNCHANGED_LANGUAGE.test(boundary) || retainedTarget && (Number(retainedTarget[1]) !== anchor.targetSeat || Number(retainedTarget[1]) !== target))) {
|
|
1083
|
-
throw new ProposalError(
|
|
1084
|
-
"ALTERNATIVE_BOUNDARY_CONTRADICTION",
|
|
1085
|
-
"A changed alternative target contradicts a boundary that preserves the target"
|
|
1086
|
-
);
|
|
1087
|
-
}
|
|
1088
|
-
}
|
|
1089
|
-
function assertNoAbsoluteStrategyClaim(proposal) {
|
|
1090
|
-
const causalClaim = [proposal.rule, proposal.expectedLocalEffect, proposal.falsifier].filter((value) => typeof value === "string").join("\u3002").replace(/(?:(?:不一定|未必|并非|不是)\s*(?:必须|必然|绝对|肯定|一定|只能|只能够|唯一(?:正确|合理)?(?:的)?(?:选择|做法))?|not (?:always|necessarily)(?:\s+(?:must|always|certain|guaranteed|the only (?:choice|option)))?)/gi, "");
|
|
1091
|
-
if (ABSOLUTE_STRATEGY_LANGUAGE.test(causalClaim)) {
|
|
1092
|
-
throw new ProposalError(
|
|
1093
|
-
"SINGLE_GAME_ABSOLUTE_CLAIM",
|
|
1094
|
-
"A single review cannot establish an absolute cross-game strategy claim"
|
|
1095
|
-
);
|
|
1096
|
-
}
|
|
1097
|
-
}
|
|
1098
|
-
function omitsRepeatedContent(value) {
|
|
1099
|
-
return /(?:省略|删去|跳过|避免|减少|不(?:再|要)?)[^。;,,!!]{0,20}(?:复述|重复)|\b(?:omit|skip|remove|avoid|reduce|do not)\b[^.;]{0,20}\b(?:repeat|duplicate)/i.test(value);
|
|
1100
|
-
}
|
|
1101
|
-
function addsNewInformation(value) {
|
|
1102
|
-
const withoutNegatedAdd = value.replace(/(?:不|没有|未)(?:再)?(?:补充|新增|提供|增加)[^。;,,!!]{0,8}(?:信息|观点|判断|依据|逻辑|内容)/gi, "");
|
|
1103
|
-
return /(?:(?:补充|新增)[^。;,,!!]{0,8}(?:信息|观点|判断|依据|逻辑|内容)|新(?:的)?(?:信息|观点|判断|依据|逻辑|内容)|相对于前置(?:发言|内容))|\b(?:add|provide|state|include)\b[^.;]{0,20}\bnew (?:information|reasoning|judgment|evidence)/i.test(withoutNegatedAdd);
|
|
1104
|
-
}
|
|
1105
|
-
function repeatsPriorContent(value) {
|
|
1106
|
-
return !omitsRepeatedContent(value) && /(?:完整|再次|继续|直接)?[^。;,,!!]{0,4}(?:复述|重复)[^。;,,!!]{0,12}(?:前置|已有|相同|观点|内容|立场)|\b(?:repeat|duplicate)\b[^.;]{0,20}\b(?:prior|same|existing)/i.test(value);
|
|
1107
|
-
}
|
|
1108
|
-
function retractsPriorJudgment(value) {
|
|
1109
|
-
const withoutNegatedRetraction = value.replace(/(?:不|没有|并未|未曾|尚未)(?:再)?[^。;,,!!]{0,4}(?:撤回|收回|更正|纠正|修正|改口|更新)[^。;,,!!]{0,12}(?:判断|观点|结论|说法|发言)/gi, "");
|
|
1110
|
-
return /(?:撤回|收回|更正|纠正|修正|改口|更新)[^。;,,!!]{0,12}(?:旧|此前|之前|先前|原有|原先)?[^。;,,!!]{0,4}(?:判断|观点|结论|说法|发言)|(?:旧|此前|之前|先前|原有|原先)[^。;,,!!]{0,8}(?:判断|观点|结论|说法|发言)[^。;,,!!]{0,8}(?:撤回|收回|更正|纠正|修正|改口|更新)|\b(?:retract|withdraw|correct|revise|update)\b[^.;]{0,20}\b(?:prior|previous|old)\b/i.test(withoutNegatedRetraction);
|
|
1111
|
-
}
|
|
1112
|
-
function discussesOwnRoleClaimTiming(value) {
|
|
1113
|
-
const roleClaimPattern = /(?:起跳|悍跳|跳(?:预言家|女巫|猎人)|公开(?:自己|自身|本人的)?(?:身份|神职)|公开(?:预言家|女巫|猎人)身份|拍(?:明)?身份|亮明身份|隐藏身份|身份宣称|role claim|claim (?:seer|witch|hunter))/i;
|
|
1114
|
-
const timingPattern = /(?:决定|选择|是否|何时|时机|首日|第一天|立即|直接|暂缓|延后|推迟|隐藏|不跳|起跳|公开|when|whether|timing|immediately|delay)/i;
|
|
1115
|
-
return topicHasAffirmedMatch(value, roleClaimPattern, true) && topicHasAffirmedMatch(value, timingPattern, false);
|
|
1116
|
-
}
|
|
1117
|
-
function assertDecisionTopic(decisionType, topic, required, allowDirectNegation = false) {
|
|
1118
|
-
if (required.every((pattern) => topicHasAffirmedMatch(topic, pattern, allowDirectNegation))) return;
|
|
1119
|
-
throw new ProposalError(
|
|
1120
|
-
"DECISION_TYPE_SEMANTICS_MISMATCH",
|
|
1121
|
-
`${decisionType} does not match the rule and alternative action topic`
|
|
1122
|
-
);
|
|
1123
|
-
}
|
|
1124
|
-
function topicHasAffirmedMatch(value, pattern, allowDirectNegation) {
|
|
1125
|
-
const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
|
|
1126
|
-
for (const match of value.matchAll(new RegExp(pattern.source, flags))) {
|
|
1127
|
-
if (!topicMatchIsDisclaimed(value, match.index, match[0].length, allowDirectNegation)) return true;
|
|
1128
|
-
}
|
|
1129
|
-
return false;
|
|
1130
|
-
}
|
|
1131
|
-
function topicMatchIsDisclaimed(value, start, length, allowDirectNegation) {
|
|
1132
|
-
const clauseStart = Math.max(
|
|
1133
|
-
value.lastIndexOf("\u3002", start - 1),
|
|
1134
|
-
value.lastIndexOf("\uFF1B", start - 1),
|
|
1135
|
-
value.lastIndexOf("\uFF0C", start - 1),
|
|
1136
|
-
value.lastIndexOf(".", start - 1),
|
|
1137
|
-
value.lastIndexOf(";", start - 1),
|
|
1138
|
-
value.lastIndexOf(",", start - 1),
|
|
1139
|
-
value.lastIndexOf("?", start - 1),
|
|
1140
|
-
value.lastIndexOf("\uFF1F", start - 1),
|
|
1141
|
-
value.lastIndexOf("!", start - 1),
|
|
1142
|
-
value.lastIndexOf("\uFF01", start - 1)
|
|
1143
|
-
) + 1;
|
|
1144
|
-
const remaining = value.slice(start + length);
|
|
1145
|
-
const relativeClauseEnd = remaining.search(/[。;,.!!,;??]/);
|
|
1146
|
-
const clauseEnd = relativeClauseEnd === -1 ? value.length : start + length + relativeClauseEnd;
|
|
1147
|
-
const before = value.slice(clauseStart, start);
|
|
1148
|
-
const after = value.slice(start + length, clauseEnd);
|
|
1149
|
-
const clause = value.slice(clauseStart, clauseEnd);
|
|
1150
|
-
const disclaimedBefore = /(?:不|未|没有|并未|无需|无须|拒绝)(?:再)?(?:涉及|讨论|处理|针对|关于|考虑|选择|决定|说明|解释|报告|执行|进行|使用|改变)\s*[^。;,,!!]{0,4}$/i.test(before);
|
|
1151
|
-
const directlyNegated = /(?:不|未|没有|并未)\s*$/i.test(before);
|
|
1152
|
-
const disclaimedAfter = /^[^。;,,!!]{0,10}(?:无关|予以排除|不予(?:考虑|纳入)|不(?:再|被)?(?:涉及|讨论|处理|考虑|选择|决定|说明|解释|报告|执行|进行|使用|改变|包含|覆盖|纳入))/i.test(after);
|
|
1153
|
-
const englishDisclaimedBefore = /\b(?:(?:is|are|was|were|be|being|been)\s+)?not\s+(?:about|related\s+to|concerned\s+with|focused\s+on|intended\s+to|meant\s+to|dealing\s+with)\s+[^.;,!?]{0,18}$/i.test(before) || /\b(?:do|does|did|will|would|should|must|can|cannot|could)\s+not\s+(?:address|discuss|handle|choose|decide|consider|explain|report|perform|use|change|involve)\s+[^.;,!?]{0,18}$/i.test(before);
|
|
1154
|
-
const englishDirectlyNegated = /\b(?:(?:do|does|did|will|would|should|must|can|cannot|could)\s+not|never)\s*$/i.test(before);
|
|
1155
|
-
const englishDisclaimedAfter = /^[^.;,!?]{0,18}\b(?:is|are)?\s*(?:excluded|omitted|rejected|unrelated|outside\s+(?:the\s+)?scope|out\s+of\s+scope|not\s+(?:addressed|discussed|handled|chosen|decided|considered|explained|reported|performed|used|changed|covered|included))/i.test(after);
|
|
1156
|
-
const metaTopicLanguage = /(?:本|该|这条|当前)?(?:规则|主题|议题|建议|提案|内容|范围)|\b(?:rule|topic|subject|proposal|scope)\b/i;
|
|
1157
|
-
const metaExclusionLanguage = /(?:排除|避开|回避|无关|不(?:在|属于)[^。;,,!!]{0,10}(?:范围|议题|主题)|不(?:涉及|讨论|处理|针对|关于|考虑|包含|覆盖)|不予(?:考虑|纳入))|\b(?:excludes?|avoids?|omits?|rejects?|irrelevant|unrelated|nothing\s+to\s+do\s+with|outside\s+(?:the\s+)?scope|out\s+of\s+scope|does?\s+not\s+(?:cover|include|address|discuss|handle|concern)|not\s+(?:about|related\s+to|concerned\s+with|focused\s+on|dealing\s+with|covered|included))\b/i;
|
|
1158
|
-
const metaTopicDisclaimed = metaTopicLanguage.test(clause) && metaExclusionLanguage.test(clause);
|
|
1159
|
-
return disclaimedBefore || englishDisclaimedBefore || !allowDirectNegation && (directlyNegated || englishDirectlyNegated) || disclaimedAfter || englishDisclaimedAfter || metaTopicDisclaimed;
|
|
1160
|
-
}
|
|
1161
|
-
function assertDecisionTypeSemantics(proposal) {
|
|
1162
|
-
const rule = proposal.rule ?? "";
|
|
1163
|
-
const alternative = proposal.alternativeAction ?? "";
|
|
1164
|
-
const behavior = proposal.behavior ?? "";
|
|
1165
|
-
if (proposal.decisionType === "AVOID_REPEATING_PRIOR_SPEAKERS") {
|
|
1166
|
-
const topic2 = `${rule}\u3002 ${alternative}`;
|
|
1167
|
-
const followsRule = omitsRepeatedContent(behavior) && addsNewInformation(behavior);
|
|
1168
|
-
if (proposal.source !== "EXEMPLAR" && proposal.action !== "COUNTER" && followsRule) {
|
|
1169
|
-
throw new ProposalError(
|
|
1170
|
-
"SOURCE_DIRECTION_MISMATCH",
|
|
1171
|
-
"SELF and OBSERVED must describe a failed action, not an action that already follows the rule"
|
|
1172
|
-
);
|
|
1173
|
-
}
|
|
1174
|
-
if (!omitsRepeatedContent(topic2) || !addsNewInformation(topic2)) {
|
|
1175
|
-
throw new ProposalError(
|
|
1176
|
-
"DECISION_TYPE_SEMANTICS_MISMATCH",
|
|
1177
|
-
"AVOID_REPEATING_PRIOR_SPEAKERS must describe omitting repeated content and adding new information"
|
|
1178
|
-
);
|
|
1179
|
-
}
|
|
1180
|
-
if (proposal.source === "EXEMPLAR" || proposal.action === "COUNTER") {
|
|
1181
|
-
if (!followsRule || proposal.action !== "COUNTER" && !repeatsPriorContent(alternative)) {
|
|
1182
|
-
throw new ProposalError(
|
|
1183
|
-
"SOURCE_DIRECTION_MISMATCH",
|
|
1184
|
-
"EXEMPLAR behavior must follow the rule and contrast with a worse counterfactual"
|
|
1185
|
-
);
|
|
1186
|
-
}
|
|
1187
|
-
}
|
|
1188
|
-
return;
|
|
1189
|
-
}
|
|
1190
|
-
if (proposal.decisionType === "RETRACT_PUBLIC_JUDGMENT") {
|
|
1191
|
-
if (!retractsPriorJudgment(rule) || !retractsPriorJudgment(alternative)) {
|
|
1192
|
-
throw new ProposalError(
|
|
1193
|
-
"DECISION_TYPE_SEMANTICS_MISMATCH",
|
|
1194
|
-
"RETRACT_PUBLIC_JUDGMENT must retract or correct a prior public judgment"
|
|
1195
|
-
);
|
|
1196
|
-
}
|
|
1197
|
-
const followsRule = retractsPriorJudgment(behavior);
|
|
1198
|
-
if ((proposal.source === "EXEMPLAR" || proposal.action === "COUNTER") !== followsRule) {
|
|
1199
|
-
throw new ProposalError(
|
|
1200
|
-
"SOURCE_DIRECTION_MISMATCH",
|
|
1201
|
-
"The observed retraction direction does not match the selected evidence source"
|
|
1202
|
-
);
|
|
1203
|
-
}
|
|
1204
|
-
return;
|
|
1205
|
-
}
|
|
1206
|
-
if (proposal.decisionType === "CHOOSE_ROLE_CLAIM_TIMING" && (!discussesOwnRoleClaimTiming(rule) || !discussesOwnRoleClaimTiming(alternative))) {
|
|
1207
|
-
throw new ProposalError(
|
|
1208
|
-
"DECISION_TYPE_SEMANTICS_MISMATCH",
|
|
1209
|
-
"CHOOSE_ROLE_CLAIM_TIMING must decide when the actor makes or withholds their own role claim"
|
|
1210
|
-
);
|
|
1211
|
-
}
|
|
1212
|
-
if (proposal.decisionType === "CHOOSE_ROLE_CLAIM_TIMING") return;
|
|
1213
|
-
const topic = `${rule}\u3002 ${alternative}`;
|
|
1214
|
-
switch (proposal.decisionType) {
|
|
1215
|
-
case "REPORT_DECIDED_ROLE_CLAIM":
|
|
1216
|
-
const reportTopic = proposal.source === "EXEMPLAR" || proposal.action === "COUNTER" ? behavior : topic;
|
|
1217
|
-
if (/(?:不|没有|并未|拒绝)(?:再)?[^。;,,!!]{0,8}(?:报告|公开|说明|交代)[^。;,,!!]{0,8}(?:身份|神职|查验|验人|role|claim|inspection)|(?:do not|did not|not going to|refuse to)[^.;]{0,12}(?:report|reveal|claim)/i.test(reportTopic)) {
|
|
1218
|
-
throw new ProposalError(
|
|
1219
|
-
"DECISION_TYPE_SEMANTICS_MISMATCH",
|
|
1220
|
-
"REPORT_DECIDED_ROLE_CLAIM must positively report the already-decided claim"
|
|
1221
|
-
);
|
|
1222
|
-
}
|
|
1223
|
-
assertDecisionTopic(proposal.decisionType, reportTopic, [
|
|
1224
|
-
/(?:查验|验人|身份|神职|预言家|女巫|猎人|role claim|claim|inspection)/i,
|
|
1225
|
-
/(?:说明|报告|交代|补充|完整|公开|report|state|explain|include)/i
|
|
1226
|
-
]);
|
|
1227
|
-
return;
|
|
1228
|
-
case "EXPLAIN_DECIDED_VOTE":
|
|
1229
|
-
assertDecisionTopic(proposal.decisionType, topic, [
|
|
1230
|
-
/(?:投票|票投|投给|票型|vote)/i,
|
|
1231
|
-
/(?:理由|依据|解释|说明|reason|because|explain)/i
|
|
1232
|
-
]);
|
|
1233
|
-
return;
|
|
1234
|
-
case "EXPLAIN_DECIDED_WOLF_TARGET":
|
|
1235
|
-
assertDecisionTopic(proposal.decisionType, topic, [
|
|
1236
|
-
/(?:狼队|刀人|行动目标|击杀目标|wolf|kill target)/i,
|
|
1237
|
-
/(?:理由|依据|解释|说明|计划|reason|because|explain|plan)/i
|
|
1238
|
-
]);
|
|
1239
|
-
return;
|
|
1240
|
-
case "CHOOSE_WOLF_KILL_TARGET":
|
|
1241
|
-
assertDecisionTopic(proposal.decisionType, topic, [/(?:刀|击杀|狼队[^。;]{0,8}目标|wolf[^.;]{0,8}target|kill)/i]);
|
|
1242
|
-
return;
|
|
1243
|
-
case "CHOOSE_SEER_TARGET":
|
|
1244
|
-
case "CHOOSE_SEER_CHECK_TARGET":
|
|
1245
|
-
assertDecisionTopic(proposal.decisionType, topic, [/(?:查验|验人|预言家[^。;]{0,8}目标|seer|inspect|check)/i]);
|
|
1246
|
-
return;
|
|
1247
|
-
case "CHOOSE_WITCH_SAVE":
|
|
1248
|
-
assertDecisionTopic(
|
|
1249
|
-
proposal.decisionType,
|
|
1250
|
-
topic,
|
|
1251
|
-
[/(?:救人|救药|解药|使用救|不救|女巫[^。;]{0,8}救|save|antidote)/i],
|
|
1252
|
-
true
|
|
1253
|
-
);
|
|
1254
|
-
return;
|
|
1255
|
-
case "CHOOSE_WITCH_POISON_TARGET":
|
|
1256
|
-
assertDecisionTopic(proposal.decisionType, topic, [/(?:毒药|用毒|毒杀|毒[^。;]{0,8}号|女巫[^。;]{0,8}毒|poison)/i]);
|
|
1257
|
-
return;
|
|
1258
|
-
case "CHOOSE_VOTE_TARGET":
|
|
1259
|
-
assertDecisionTopic(proposal.decisionType, topic, [/(?:投票|改投|票投|投给|vote)/i]);
|
|
1260
|
-
return;
|
|
1261
|
-
case "CHOOSE_HUNTER_SHOT_TARGET":
|
|
1262
|
-
assertDecisionTopic(proposal.decisionType, topic, [/(?:开枪|带走|猎人[^。;]{0,8}目标|shoot)/i]);
|
|
1263
|
-
return;
|
|
1264
|
-
case "IMPROVE_LAST_WORD_CONTENT":
|
|
1265
|
-
assertDecisionTopic(proposal.decisionType, topic, [/(?:遗言|最后发言|last words?)/i]);
|
|
1266
|
-
return;
|
|
1267
|
-
default:
|
|
1268
|
-
throw new ProposalError(
|
|
1269
|
-
"DECISION_TYPE_SEMANTICS_MISMATCH",
|
|
1270
|
-
`Unsupported decisionType semantics: ${proposal.decisionType}`
|
|
1271
|
-
);
|
|
1272
|
-
}
|
|
1273
|
-
}
|
|
1274
|
-
function parseVoteCounts(summary) {
|
|
1275
|
-
const match = /DAY_(?:RE)?VOTE_COUNT:\s*\{?([^}\r\n]*)\}?/i.exec(summary);
|
|
1276
|
-
if (!match) return void 0;
|
|
1277
|
-
const counts = /* @__PURE__ */ new Map();
|
|
1278
|
-
const body = match[1].trim();
|
|
1279
|
-
if (!body) return counts;
|
|
1280
|
-
for (const token of body.split(",")) {
|
|
1281
|
-
const pair = /^\s*([1-9][0-9]*)\s*=\s*([0-9]+)\s*$/.exec(token);
|
|
1282
|
-
if (!pair || counts.has(Number(pair[1]))) return void 0;
|
|
1283
|
-
counts.set(Number(pair[1]), Number(pair[2]));
|
|
1284
|
-
}
|
|
1285
|
-
return counts;
|
|
1286
|
-
}
|
|
1287
|
-
function assertedVoteCounts(observed) {
|
|
1288
|
-
const claims = /* @__PURE__ */ new Map();
|
|
1289
|
-
for (const match of observed.matchAll(/([1-9][0-9]*)\s*号(?:玩家)?[^。;,,!!]{0,12}(?:获得|得到|拿到|有|被)\s*([0-9]+)\s*票/g)) {
|
|
1290
|
-
claims.set(Number(match[1]), Number(match[2]));
|
|
1291
|
-
}
|
|
1292
|
-
for (const section of observed.matchAll(/(?:投票计数|票数|票型)[^。;]*/g)) {
|
|
1293
|
-
for (const match of section[0].matchAll(/([1-9][0-9]*)\s*号?\s*=\s*([0-9]+)/g)) {
|
|
1294
|
-
claims.set(Number(match[1]), Number(match[2]));
|
|
1295
|
-
}
|
|
1296
|
-
}
|
|
1297
|
-
for (const match of observed.matchAll(/(?:seat\s*)?([1-9][0-9]*)\s+(?:received|got|had)\s+([0-9]+)\s+votes?/gi)) {
|
|
1298
|
-
claims.set(Number(match[1]), Number(match[2]));
|
|
1299
|
-
}
|
|
1300
|
-
return [...claims].map(([seat, count]) => ({ seat, count }));
|
|
1301
|
-
}
|
|
1302
|
-
function assertedUnanimousSeat(observed) {
|
|
1303
|
-
const afterSeat = /([1-9][0-9]*)\s*号(?:玩家)?[^。;,,!!]{0,12}(?:全票|一致投票)/.exec(observed);
|
|
1304
|
-
if (afterSeat) return Number(afterSeat[1]);
|
|
1305
|
-
const beforeSeat = /(?:全票|一致投票)[^。;,,!!]{0,12}([1-9][0-9]*)\s*号/.exec(observed);
|
|
1306
|
-
if (beforeSeat) return Number(beforeSeat[1]);
|
|
1307
|
-
const collective = /(?:所有(?:玩家|人)|全部(?:玩家|人)|全体玩家)(?:都|一致)?[^。;,,!!]{0,12}(?:投票?(?:给|到)|投向|把票投给)\s*([1-9][0-9]*)\s*号/.exec(observed);
|
|
1308
|
-
if (collective) return Number(collective[1]);
|
|
1309
|
-
const unanimous = /(?:全部人)?一致投(?:票)?(?:给|到)\s*([1-9][0-9]*)\s*号/.exec(observed);
|
|
1310
|
-
if (unanimous) return Number(unanimous[1]);
|
|
1311
|
-
const english = /(?:all players|everyone)\s+(?:unanimously\s+)?voted\s+for\s+(?:seat\s*)?([1-9][0-9]*)/i.exec(observed);
|
|
1312
|
-
return english ? Number(english[1]) : void 0;
|
|
1313
|
-
}
|
|
1314
|
-
function assertedEliminatedSeats(observed) {
|
|
1315
|
-
const seats = [...observed.matchAll(/([1-9][0-9]*)\s*号(?:玩家)?[^。;,,!!]{0,12}(?:被(?:投出|放逐|票出|投票淘汰|冲出|冲出去))/g)].map((match) => Number(match[1]));
|
|
1316
|
-
for (const match of observed.matchAll(/seat\s*([1-9][0-9]*)[^.;]{0,16}(?:was\s+)?(?:voted out|eliminated by vote)/gi)) {
|
|
1317
|
-
seats.push(Number(match[1]));
|
|
1318
|
-
}
|
|
1319
|
-
return seats;
|
|
1320
|
-
}
|
|
1321
|
-
var SOCIAL_OUTCOME_FAMILIES = [
|
|
1322
|
-
{
|
|
1323
|
-
claim: /(?:怀疑|焦点|注意力|排除|狼面|好人面|纠错|suspicion|focus|attention|cleared)/i,
|
|
1324
|
-
evidence: /(?:怀疑|质疑|焦点|注意力|排除|认好|认狼|狼面|好人面|纠错|suspicion|suspect|question|focus|attention|clear)/i
|
|
1325
|
-
},
|
|
1326
|
-
{
|
|
1327
|
-
claim: /(?:共识|一致判断|统一站边|consensus)/i,
|
|
1328
|
-
evidence: /(?:共识|一致|站边|认可|支持|同意|consensus|agree|support)/i
|
|
1329
|
-
}
|
|
1330
|
-
];
|
|
1331
|
-
function referencedSeats(value) {
|
|
1332
|
-
const seats = new Set([...value.matchAll(SEAT_REFERENCE_LANGUAGE)].map((match) => Number(match[1])));
|
|
1333
|
-
for (const match of value.matchAll(/(?:seat\s*=?\s*)([1-9][0-9]*)\b/gi)) seats.add(Number(match[1]));
|
|
1334
|
-
return seats;
|
|
1335
|
-
}
|
|
1336
|
-
function speechFactSupportsSocialOutcome(fact, observed) {
|
|
1337
|
-
const claimedSeats = referencedSeats(observed);
|
|
1338
|
-
const factSeats = referencedSeats(fact.summary);
|
|
1339
|
-
if (fact.actorSeat != null) factSeats.add(fact.actorSeat);
|
|
1340
|
-
if (fact.targetSeat != null) factSeats.add(fact.targetSeat);
|
|
1341
|
-
if ([...claimedSeats].some((seat) => !factSeats.has(seat))) return false;
|
|
1342
|
-
const claimedRelations = socialActorTargetRelations(observed);
|
|
1343
|
-
const factRelations = socialActorTargetRelations(fact.summary);
|
|
1344
|
-
if ([...claimedRelations].some((relation) => !factRelations.has(relation))) return false;
|
|
1345
|
-
const claimsClearance = /(?:排除[^。;,,!!]{0,12}(?:怀疑|狼坑|焦点)|移出[^。;,,!!]{0,12}(?:怀疑|狼坑|焦点)|不再怀疑|cleared from suspicion)/i.test(observed);
|
|
1346
|
-
if (claimsClearance && !/(?:排除[^。;,,!!]{0,12}(?:怀疑|狼坑|焦点)|移出[^。;,,!!]{0,12}(?:怀疑|狼坑|焦点)|不再怀疑|cleared from suspicion)/i.test(fact.summary)) {
|
|
1347
|
-
return false;
|
|
1348
|
-
}
|
|
1349
|
-
const matchedFamilies = SOCIAL_OUTCOME_FAMILIES.filter(({ claim }) => claim.test(observed));
|
|
1350
|
-
return matchedFamilies.length > 0 && matchedFamilies.every(({ evidence }) => evidence.test(fact.summary));
|
|
1351
|
-
}
|
|
1352
|
-
function socialActorTargetRelations(value) {
|
|
1353
|
-
const relations = /* @__PURE__ */ new Set();
|
|
1354
|
-
const patterns = [
|
|
1355
|
-
/(?:seat\s*=?\s*)?([1-9][0-9]*)\s*号?[^。;,,!!]{0,16}(?:质疑|怀疑|锁定|攻击|suspect|question|focus(?:ed)? on)[^。;,,!!]{0,12}(?:seat\s*)?([1-9][0-9]*)\s*号?/gi,
|
|
1356
|
-
/(?:seat\s*=?\s*)?([1-9][0-9]*)\s*号?[^。;,,!!]{0,20}(?:焦点|注意力)[^。;,,!!]{0,8}(?:锁定到|导向|转向|shifted to)[^。;,,!!]{0,8}(?:seat\s*)?([1-9][0-9]*)\s*号?/gi,
|
|
1357
|
-
/(?:seat\s*=?\s*)?([1-9][0-9]*)\s*号?[^。;,,!!]{0,12}(?:排除|移出)[^。;,,!!]{0,6}(?:对|针对)\s*(?:seat\s*)?([1-9][0-9]*)\s*号?[^。;,,!!]{0,8}(?:怀疑|狼坑|焦点)/gi
|
|
1358
|
-
];
|
|
1359
|
-
for (const pattern of patterns) {
|
|
1360
|
-
for (const match of value.matchAll(pattern)) {
|
|
1361
|
-
relations.add(`${Number(match[1])}->${Number(match[2])}`);
|
|
1362
|
-
}
|
|
1363
|
-
}
|
|
1364
|
-
return relations;
|
|
1365
|
-
}
|
|
1366
|
-
function assertObservedOutcomeSemantics(observed, outcomeFacts) {
|
|
1367
|
-
if (LOCAL_OUTCOME_INFERENCE_LANGUAGE.test(observed)) {
|
|
1368
|
-
throw new ProposalError(
|
|
1369
|
-
"LOCAL_OUTCOME_INFERENCE",
|
|
1370
|
-
"observedLocalEffect must state later facts directly instead of claiming they prove an interpretation"
|
|
1371
|
-
);
|
|
1372
|
-
}
|
|
1373
|
-
if (SOCIAL_OUTCOME_LANGUAGE.test(observed)) {
|
|
1374
|
-
const speechFacts = outcomeFacts.filter((fact) => SPEECH_OUTCOME_FACT_TYPES.has(fact.type));
|
|
1375
|
-
if (speechFacts.length === 0) {
|
|
1376
|
-
throw new ProposalError(
|
|
1377
|
-
"SOCIAL_OUTCOME_FACT_REQUIRED",
|
|
1378
|
-
"A social-state interpretation requires a referenced later speech fact"
|
|
1379
|
-
);
|
|
1380
|
-
}
|
|
1381
|
-
if (!speechFacts.some((fact) => speechFactSupportsSocialOutcome(fact, observed))) {
|
|
1382
|
-
throw new ProposalError(
|
|
1383
|
-
"SOCIAL_OUTCOME_FACT_MISMATCH",
|
|
1384
|
-
"The referenced speech facts do not state the claimed social-state change"
|
|
1385
|
-
);
|
|
1386
|
-
}
|
|
1387
|
-
}
|
|
1388
|
-
const countFacts = outcomeFacts.filter((fact) => fact.type === "DAY_VOTE_COUNT" || fact.type === "DAY_REVOTE_COUNT").map((fact) => parseVoteCounts(fact.summary)).filter((counts) => counts !== void 0);
|
|
1389
|
-
for (const claim of assertedVoteCounts(observed)) {
|
|
1390
|
-
if (!countFacts.some((counts) => counts.get(claim.seat) === claim.count)) {
|
|
1391
|
-
throw new ProposalError(
|
|
1392
|
-
"OUTCOME_FACT_SEMANTICS_MISMATCH",
|
|
1393
|
-
"An asserted vote count does not match the referenced vote facts"
|
|
1394
|
-
);
|
|
1395
|
-
}
|
|
1396
|
-
}
|
|
1397
|
-
const unanimousSeat = assertedUnanimousSeat(observed);
|
|
1398
|
-
if (unanimousSeat !== void 0 && !countFacts.some((counts) => {
|
|
1399
|
-
const positive = [...counts].filter(([, count]) => count > 0);
|
|
1400
|
-
return positive.length === 1 && positive[0][0] === unanimousSeat;
|
|
1401
|
-
})) {
|
|
1402
|
-
throw new ProposalError(
|
|
1403
|
-
"OUTCOME_FACT_SEMANTICS_MISMATCH",
|
|
1404
|
-
"An asserted unanimous vote does not match the referenced vote facts"
|
|
1405
|
-
);
|
|
1406
|
-
}
|
|
1407
|
-
for (const seat of assertedEliminatedSeats(observed)) {
|
|
1408
|
-
if (!outcomeFacts.some((fact) => (fact.type === "DAY_VOTE_ELIMINATED" || fact.type === "DAY_REVOTE_ELIMINATED") && fact.targetSeat === seat)) {
|
|
1409
|
-
throw new ProposalError(
|
|
1410
|
-
"OUTCOME_FACT_SEMANTICS_MISMATCH",
|
|
1411
|
-
"An asserted elimination does not match the referenced elimination facts"
|
|
1412
|
-
);
|
|
1413
|
-
}
|
|
1414
|
-
}
|
|
1415
|
-
}
|
|
1416
|
-
function assertSourceOutcomeDirection(proposal, observed) {
|
|
1417
|
-
const withoutBeneficialNegation = observed.replace(/(?:没有再次|不再)(?:质疑|追问|要求补充)/gi, "");
|
|
1418
|
-
const adverse = ADVERSE_LOCAL_EFFECT_LANGUAGE.test(withoutBeneficialNegation);
|
|
1419
|
-
const beneficial = BENEFICIAL_LOCAL_EFFECT_LANGUAGE.test(observed);
|
|
1420
|
-
if (proposal.action === "COUNTER") {
|
|
1421
|
-
if (!adverse) {
|
|
1422
|
-
throw new ProposalError(
|
|
1423
|
-
"SOURCE_DIRECTION_MISMATCH",
|
|
1424
|
-
"COUNTER must describe an adverse local effect that falsifies the existing rule"
|
|
1425
|
-
);
|
|
1426
|
-
}
|
|
1427
|
-
return;
|
|
1428
|
-
}
|
|
1429
|
-
if (proposal.source === "EXEMPLAR") {
|
|
1430
|
-
if (!beneficial || adverse) {
|
|
1431
|
-
throw new ProposalError(
|
|
1432
|
-
"SOURCE_DIRECTION_MISMATCH",
|
|
1433
|
-
"EXEMPLAR must describe a beneficial local effect without an adverse result"
|
|
1434
|
-
);
|
|
1435
|
-
}
|
|
1436
|
-
return;
|
|
1437
|
-
}
|
|
1438
|
-
if (!adverse) {
|
|
1439
|
-
throw new ProposalError(
|
|
1440
|
-
"SOURCE_DIRECTION_MISMATCH",
|
|
1441
|
-
"SELF and OBSERVED require an adverse local effect as evidence of failed behavior"
|
|
1442
|
-
);
|
|
1443
|
-
}
|
|
1444
|
-
}
|
|
1445
|
-
function assertLocalOutcomeEvidence(outcomeCount, localOutcomeCount, observed) {
|
|
1446
|
-
if (outcomeCount === 0 || localOutcomeCount === 0) {
|
|
1447
|
-
throw new ProposalError(
|
|
1448
|
-
"LOCAL_OUTCOME_FACT_REQUIRED",
|
|
1449
|
-
"Victory, final identity, or other postgame facts cannot be the only outcome evidence"
|
|
1450
|
-
);
|
|
1451
|
-
}
|
|
1452
|
-
if (FINAL_RESULT_LANGUAGE.test(observed.trim())) {
|
|
1453
|
-
throw new ProposalError("FINAL_RESULT_NOT_LOCAL", "Final victory or defeat is not a local effect");
|
|
1454
|
-
}
|
|
1455
|
-
}
|
|
1456
|
-
function actionTimeIdentityAssertions(value) {
|
|
1457
|
-
const assertions = [];
|
|
1458
|
-
const negativePatterns = [
|
|
1459
|
-
new RegExp(`([1-9][0-9]*)\\s*\u53F7(?:\u73A9\u5BB6)?[^\u3002\uFF1B\uFF0C,!\uFF01]{0,8}(?:\u4E0D\u662F|\u5E76\u975E|\u4E0D\u4E3A)\\s*(?:\u771F\u6B63|\u771F\u5B9E)?(?:\u7684)?(${ROLE_NAME})`, "g"),
|
|
1460
|
-
new RegExp(`(?:seat\\s*)?([1-9][0-9]*)[^.;,!]{0,12}(?:is|was)\\s+not\\s+(?:the\\s+)?(?:real\\s+)?(${ENGLISH_ROLE_NAME})\\b`, "gi")
|
|
1461
|
-
];
|
|
1462
|
-
for (const pattern of negativePatterns) {
|
|
1463
|
-
for (const match of value.matchAll(pattern)) {
|
|
1464
|
-
assertions.push({ seat: Number(match[1]), role: normalizeIdentity(match[2]), negated: true });
|
|
1465
|
-
}
|
|
1466
|
-
}
|
|
1467
|
-
const patterns = [
|
|
1468
|
-
new RegExp(`([1-9][0-9]*)\\s*\u53F7(?:\u73A9\u5BB6)?[^\u3002\uFF1B\uFF0C,!\uFF01]{0,8}(?:\u771F\u6B63|\u771F\u5B9E)?(?:\u7684)?(?:\u8EAB\u4EFD)?(?:\u662F|\u4E3A)\\s*(?:\u771F\u6B63|\u771F\u5B9E)?(?:\u7684)?(${ROLE_NAME})`, "g"),
|
|
1469
|
-
new RegExp(`(?:\u771F\u6B63|\u771F\u5B9E)(?:\u7684)?(${ROLE_NAME})\\s*(?:\u662F|\u4E3A)?\\s*([1-9][0-9]*)\\s*\u53F7`, "g")
|
|
1470
|
-
];
|
|
1471
|
-
for (const [index, pattern] of patterns.entries()) {
|
|
1472
|
-
for (const match of value.matchAll(pattern)) {
|
|
1473
|
-
const prefix = value.slice(Math.max(0, match.index - 12), match.index);
|
|
1474
|
-
if (CONDITIONAL_IDENTITY_LANGUAGE.test(prefix) || /(?:自称|声称|号称|可能|或许|怀疑|认为|倾向|猜测|未必|不确定)/i.test(match[0])) continue;
|
|
1475
|
-
assertions.push(index === 0 ? { seat: Number(match[1]), role: match[2] } : { seat: Number(match[2]), role: match[1] });
|
|
1476
|
-
}
|
|
1477
|
-
}
|
|
1478
|
-
const englishPatterns = [
|
|
1479
|
-
new RegExp(`(?:seat\\s*)?([1-9][0-9]*)[^.;,!]{0,12}(?:is|was|=)\\s*(?:the\\s+)?(?:real\\s+)?(${ENGLISH_ROLE_NAME})\\b`, "gi"),
|
|
1480
|
-
new RegExp(`(?:the\\s+)?(?:real\\s+)?(${ENGLISH_ROLE_NAME})\\s+(?:is|was|=)?\\s*(?:seat\\s*)?([1-9][0-9]*)\\b`, "gi")
|
|
1481
|
-
];
|
|
1482
|
-
for (const [index, pattern] of englishPatterns.entries()) {
|
|
1483
|
-
for (const match of value.matchAll(pattern)) {
|
|
1484
|
-
const prefix = value.slice(Math.max(0, match.index - 24), match.index);
|
|
1485
|
-
if (/\b(?:if|maybe|perhaps|suspect|think|likely|uncertain)\s*$/i.test(prefix)) continue;
|
|
1486
|
-
assertions.push(index === 0 ? { seat: Number(match[1]), role: normalizeIdentity(match[2]) } : { seat: Number(match[2]), role: normalizeIdentity(match[1]) });
|
|
1487
|
-
}
|
|
1488
|
-
}
|
|
1489
|
-
return assertions;
|
|
1490
|
-
}
|
|
1491
|
-
function normalizeIdentity(value) {
|
|
1492
|
-
switch (value.trim().toLowerCase()) {
|
|
1493
|
-
case "seer":
|
|
1494
|
-
return "\u9884\u8A00\u5BB6";
|
|
1495
|
-
case "witch":
|
|
1496
|
-
return "\u5973\u5DEB";
|
|
1497
|
-
case "hunter":
|
|
1498
|
-
return "\u730E\u4EBA";
|
|
1499
|
-
case "werewolf":
|
|
1500
|
-
case "wolf":
|
|
1501
|
-
return "\u72FC\u4EBA";
|
|
1502
|
-
case "good":
|
|
1503
|
-
case "good player":
|
|
1504
|
-
return "\u597D\u4EBA";
|
|
1505
|
-
case "villager":
|
|
1506
|
-
return "\u5E73\u6C11";
|
|
1507
|
-
case "\u6751\u6C11":
|
|
1508
|
-
return "\u5E73\u6C11";
|
|
1509
|
-
default:
|
|
1510
|
-
return value;
|
|
1511
|
-
}
|
|
1512
|
-
}
|
|
1513
|
-
function seerResultIdentity(fact) {
|
|
1514
|
-
const match = /(?:=|是|为)\s*(狼人|好人|WOLF|GOOD|true|false)(?=$|[\s;,.,。])/i.exec(fact.summary);
|
|
1515
|
-
if (!match) return void 0;
|
|
1516
|
-
const value = match[1].toLowerCase();
|
|
1517
|
-
if (value === "\u72FC\u4EBA" || value === "wolf" || value === "true") return "\u72FC\u4EBA";
|
|
1518
|
-
return "\u597D\u4EBA";
|
|
1519
|
-
}
|
|
1520
|
-
function factEstablishesIdentity(fact, seat, role) {
|
|
1521
|
-
const identity = normalizeIdentity(role);
|
|
1522
|
-
if (fact.type === "SEER_RESULT" && fact.targetSeat === seat) {
|
|
1523
|
-
return seerResultIdentity(fact) === identity;
|
|
1524
|
-
}
|
|
1525
|
-
if (fact.actorSeat !== seat) return false;
|
|
1526
|
-
if (identity === "\u5973\u5DEB") return fact.type.startsWith("WITCH_");
|
|
1527
|
-
if (identity === "\u9884\u8A00\u5BB6") return fact.type === "SEER_RESULT" || fact.type === "SEER_CHECK" || fact.type === "SEER_SKIP_CHECK";
|
|
1528
|
-
if (identity === "\u730E\u4EBA") return fact.type.includes("HUNTER_SHOOT") || fact.type.includes("HUNTER_PASS");
|
|
1529
|
-
if (identity === "\u72FC\u4EBA") return fact.type.startsWith("WOLF_");
|
|
1530
|
-
if (identity === "\u597D\u4EBA") return fact.type.startsWith("WITCH_") || fact.type.startsWith("SEER_") || fact.type.includes("HUNTER_");
|
|
1531
|
-
return false;
|
|
1532
|
-
}
|
|
1533
|
-
function factEstablishesNegativeIdentity(fact, seat, role) {
|
|
1534
|
-
const identity = normalizeIdentity(role);
|
|
1535
|
-
if (fact.type !== "SEER_RESULT" || fact.targetSeat !== seat || identity !== "\u72FC\u4EBA" && identity !== "\u597D\u4EBA") return false;
|
|
1536
|
-
const actual = seerResultIdentity(fact);
|
|
1537
|
-
return actual !== void 0 && actual !== identity;
|
|
1538
|
-
}
|
|
1539
|
-
function assertActionTimeSemantics(proposal, window, anchor, knownFacts) {
|
|
1540
|
-
const actionTimeFields = [
|
|
1541
|
-
proposal.trigger,
|
|
1542
|
-
proposal.rule,
|
|
1543
|
-
proposal.boundary,
|
|
1544
|
-
proposal.alternativeAction
|
|
1545
|
-
].filter((value) => typeof value === "string");
|
|
1546
|
-
if (window.phase === "SEER_TURN" && anchor.availableAt.round === 1 && proposal.alternativeActionType === "SEER_CHECK") {
|
|
1547
|
-
const rationale = actionTimeFields.map(stripUnavailableDaytimeInformation).join("\u3002 ");
|
|
1548
|
-
if (FIRST_NIGHT_DAYTIME_INFORMATION.test(rationale)) {
|
|
1549
|
-
throw new ProposalError(
|
|
1550
|
-
"SEER_DAY_INFORMATION_UNAVAILABLE",
|
|
1551
|
-
"A first-night seer check cannot depend on later daytime behavior"
|
|
1552
|
-
);
|
|
1553
|
-
}
|
|
1554
|
-
}
|
|
1555
|
-
if (actionTimeFields.some((value) => dependsOnFutureBehavior(value, anchor.availableAt.round))) {
|
|
1556
|
-
throw new ProposalError(
|
|
1557
|
-
"FUTURE_BEHAVIOR_DEPENDENCY",
|
|
1558
|
-
"A proposal field cannot depend on behavior after the decision anchor"
|
|
1559
|
-
);
|
|
1560
|
-
}
|
|
1561
|
-
const actionTimeText = actionTimeFields.join("\u3002 ");
|
|
1562
|
-
for (const identity of actionTimeIdentityAssertions(actionTimeText)) {
|
|
1563
|
-
const established = identity.negated ? knownFacts.some((fact) => factEstablishesNegativeIdentity(fact, identity.seat, identity.role)) : knownFacts.some((fact) => factEstablishesIdentity(fact, identity.seat, identity.role));
|
|
1564
|
-
if (!established) {
|
|
1565
|
-
throw new ProposalError(
|
|
1566
|
-
"ACTION_TIME_IDENTITY_UNSUPPORTED",
|
|
1567
|
-
"A concrete seat identity was not established by visible facts before the action"
|
|
1568
|
-
);
|
|
1569
|
-
}
|
|
1570
|
-
}
|
|
1571
|
-
for (const { seat, claim } of seatBehaviorClaims(actionTimeText)) {
|
|
1572
|
-
if (seat === window.actorSeat && isCurrentDecisionActorClaim(claim)) continue;
|
|
1573
|
-
const supported = [anchor, ...knownFacts].some((fact) => fact.actorSeat === seat && factSupportsBehaviorClaim(fact, claim));
|
|
1574
|
-
if (!supported) {
|
|
1575
|
-
throw new ProposalError(
|
|
1576
|
-
"UNKNOWN_SEAT_BEHAVIOR_DEPENDENCY",
|
|
1577
|
-
"A trigger or alternative action cannot depend on an unsupported seat behavior"
|
|
1578
|
-
);
|
|
1579
|
-
}
|
|
1580
|
-
}
|
|
1581
|
-
}
|
|
1582
|
-
function factVisibleToActor(visibility, window) {
|
|
1583
|
-
if (visibility === "PUBLIC") return true;
|
|
1584
|
-
if (visibility === "POSTGAME_ONLY") return false;
|
|
1585
|
-
if (visibility === "WOLF_TEAM") {
|
|
1586
|
-
return window.actorRole === "WOLF" || window.actorRole === "WEREWOLF";
|
|
1587
|
-
}
|
|
1588
|
-
const seatOnly = /^SEAT_([1-9][0-9]*)_ONLY$/.exec(visibility);
|
|
1589
|
-
return seatOnly !== null && Number(seatOnly[1]) === window.actorSeat;
|
|
1590
|
-
}
|
|
1591
|
-
function assertAlternativeTarget(proposal, window, risk) {
|
|
1592
|
-
if (risk === "execution") {
|
|
1593
|
-
if (proposal.alternativeTargetSeat !== void 0) {
|
|
1594
|
-
throw new ProposalError(
|
|
1595
|
-
"EXECUTION_TARGET_NOT_ALLOWED",
|
|
1596
|
-
"An execution proposal cannot introduce or change a target"
|
|
1597
|
-
);
|
|
1598
|
-
}
|
|
1599
|
-
return;
|
|
1600
|
-
}
|
|
1601
|
-
const actionType = proposal.alternativeActionType;
|
|
1602
|
-
const target = proposal.alternativeTargetSeat;
|
|
1603
|
-
if (TARGET_REQUIRED_ACTIONS.has(actionType) && target == null) {
|
|
1604
|
-
throw new ProposalError("ALTERNATIVE_TARGET_REQUIRED", `${actionType} requires an alternative target`);
|
|
1605
|
-
}
|
|
1606
|
-
if (TARGETLESS_ACTIONS.has(actionType) && target != null) {
|
|
1607
|
-
throw new ProposalError("ALTERNATIVE_TARGET_FORBIDDEN", `${actionType} cannot carry a target`);
|
|
1608
|
-
}
|
|
1609
|
-
if (actionType === "DAY_VOTE" && target === void 0) {
|
|
1610
|
-
throw new ProposalError("ALTERNATIVE_TARGET_REQUIRED", "DAY_VOTE must explicitly choose a seat or abstain");
|
|
1611
|
-
}
|
|
1612
|
-
if (target != null) {
|
|
1613
|
-
if (!window.availableTargetSeats) {
|
|
1614
|
-
throw new ProposalError(
|
|
1615
|
-
"TARGET_SET_UNAVAILABLE",
|
|
1616
|
-
"The trusted decision window did not preserve the legal target set"
|
|
1617
|
-
);
|
|
1618
|
-
}
|
|
1619
|
-
if (!window.availableTargetSeats.includes(target)) {
|
|
1620
|
-
throw new ProposalError("ALTERNATIVE_TARGET_UNAVAILABLE", "The alternative target was not legal at that point");
|
|
1621
|
-
}
|
|
1622
|
-
}
|
|
1623
|
-
}
|
|
1624
|
-
function matchesExecutionDefinition(value, allowRefinement, requireAlternativeAction) {
|
|
1625
|
-
const operation = value.executionOperation;
|
|
1626
|
-
const template = operation ? EXECUTION_PROPOSAL_TEMPLATES[operation] : void 0;
|
|
1627
|
-
if (!template || template.decisionType !== value.decisionType || !sameSemanticText(value.rule, template.rule) || requireAlternativeAction && !sameSemanticText(value.alternativeAction, template.alternativeAction)) return false;
|
|
1628
|
-
const trigger = semanticText(value.trigger ?? "");
|
|
1629
|
-
const boundary = semanticText(value.boundary ?? "");
|
|
1630
|
-
const expectedTrigger = semanticText(template.trigger);
|
|
1631
|
-
const expectedBoundary = semanticText(template.boundary);
|
|
1632
|
-
if (allowRefinement) {
|
|
1633
|
-
if (!trigger.startsWith(expectedTrigger) || !boundary.startsWith(expectedBoundary)) return false;
|
|
1634
|
-
const addedScope = `${trigger.slice(expectedTrigger.length)} ${boundary.slice(expectedBoundary.length)}`;
|
|
1635
|
-
if (STRATEGY_LANGUAGE.test(addedScope)) return false;
|
|
1636
|
-
} else if (trigger !== expectedTrigger || boundary !== expectedBoundary) {
|
|
1637
|
-
return false;
|
|
1638
|
-
}
|
|
1639
|
-
return true;
|
|
1640
|
-
}
|
|
1641
|
-
function classifyRisk(proposal, decisionType = proposal.decisionType ?? "") {
|
|
1642
|
-
return matchesExecutionDefinition(
|
|
1643
|
-
{ ...proposal, decisionType },
|
|
1644
|
-
proposal.action === "REFINE",
|
|
1645
|
-
true
|
|
1646
|
-
) ? "execution" : "strategy";
|
|
1647
|
-
}
|
|
1648
|
-
function assertExistingSemantics(proposal, existing, window, action, players, describedBehavior) {
|
|
1649
|
-
if (existing.status === "archived") {
|
|
1650
|
-
throw new ProposalError("TOPIC_ARCHIVED", `Archived topic cannot receive ${action}`);
|
|
1651
|
-
}
|
|
1652
|
-
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) {
|
|
1653
|
-
throw new ProposalError("TOPIC_SEMANTICS_MISMATCH", `${action} does not describe the selected topic`);
|
|
1654
|
-
}
|
|
1655
|
-
if (action === "SUPPORT" || action === "COUNTER") {
|
|
1656
|
-
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)) {
|
|
1657
|
-
throw new ProposalError("TOPIC_OUTCOME_SEMANTICS_MISMATCH", `${action} changed the topic's causal claim`);
|
|
1658
|
-
}
|
|
1659
|
-
}
|
|
1660
|
-
if (action === "COUNTER" && !COUNTER_EFFECT_LANGUAGE.test(proposal.observedLocalEffect ?? "")) {
|
|
1661
|
-
throw new ProposalError("COUNTER_NOT_FALSIFYING", "COUNTER must describe a concrete failed or adverse local outcome");
|
|
1662
|
-
}
|
|
1663
|
-
if (action === "COUNTER" && !counterBehaviorFollowsRule(proposal, existing, describedBehavior)) {
|
|
1664
|
-
throw new ProposalError(
|
|
1665
|
-
"COUNTER_BEHAVIOR_MISMATCH",
|
|
1666
|
-
"COUNTER behavior must show that the trusted anchor actually executed the existing rule"
|
|
1667
|
-
);
|
|
1668
|
-
}
|
|
1669
|
-
}
|
|
1670
|
-
function counterBehaviorFollowsRule(proposal, existing, behavior) {
|
|
1671
|
-
if (proposal.decisionType === "AVOID_REPEATING_PRIOR_SPEAKERS") {
|
|
1672
|
-
return omitsRepeatedContent(behavior) && addsNewInformation(behavior);
|
|
1673
|
-
}
|
|
1674
|
-
if (proposal.decisionType === "RETRACT_PUBLIC_JUDGMENT") {
|
|
1675
|
-
return retractsPriorJudgment(behavior);
|
|
1676
|
-
}
|
|
1677
|
-
if (proposal.decisionType === "REPORT_DECIDED_ROLE_CLAIM") {
|
|
1678
|
-
return /(?:完整|全部|明确)[^。;,,!!]{0,16}(?:查验|验人|信息链|验人计划)|(?:查验|验人)[^。;,,!!]{0,24}(?:结果|金水|查杀)[^。;,,!!]{0,24}(?:计划|信息链)/i.test(behavior);
|
|
1679
|
-
}
|
|
1680
|
-
const targetDecisionTypes = /* @__PURE__ */ new Set([
|
|
1681
|
-
"CHOOSE_WOLF_KILL_TARGET",
|
|
1682
|
-
"CHOOSE_SEER_TARGET",
|
|
1683
|
-
"CHOOSE_SEER_CHECK_TARGET",
|
|
1684
|
-
"CHOOSE_WITCH_POISON_TARGET",
|
|
1685
|
-
"CHOOSE_VOTE_TARGET",
|
|
1686
|
-
"CHOOSE_HUNTER_SHOT_TARGET"
|
|
1687
|
-
]);
|
|
1688
|
-
if (targetDecisionTypes.has(proposal.decisionType ?? "")) {
|
|
1689
|
-
const expectedTargets = [...existing.rule.matchAll(EXPLICIT_TARGET_LANGUAGE)].map((match) => Number(match[1]));
|
|
1690
|
-
const rawTarget = /->\s*([1-9][0-9]*)\b/.exec(behavior) ?? /(?:WOLF_CHOOSE|SEER_CHECK|WITCH_POISON|HUNTER_SHOOT)\s*:\s*(?:[1-9][0-9]*\s*->\s*)?([1-9][0-9]*)\b/i.exec(behavior);
|
|
1691
|
-
const actualTarget = behaviorTarget(behavior) ?? (rawTarget ? Number(rawTarget[1]) : void 0);
|
|
1692
|
-
const negatedAction = /(?:没有|并未|未曾|不曾|从未|尚未|不)[^。;,,!!]{0,20}(?:改投|投票|查验|验人|刀|毒|救|开枪|起跳|公开身份)|(?:did not|never|not)[^.;]{0,20}(?:vote|check|inspect|kill|poison|save|shoot|claim)/i.test(behavior);
|
|
1693
|
-
return expectedTargets.length === 1 && actualTarget === expectedTargets[0] && !negatedAction;
|
|
1694
|
-
}
|
|
1695
|
-
if (proposal.decisionType === "CHOOSE_ROLE_CLAIM_TIMING") {
|
|
1696
|
-
const withheld = (value) => /(?:不(?:公开|起跳|跳)|隐藏身份|暂缓|延后|推迟)[^。;,,!!]{0,12}(?:身份|神职|起跳|公开)?|(?:withhold|hide|delay|do not claim)/i.test(value);
|
|
1697
|
-
const claimed = (value) => /(?:直接|立即|选择|决定)?(?:公开(?:自己|自身)?(?:身份|神职)|起跳|跳(?:预言家|女巫|猎人)|claim(?:ed)? (?:seer|witch|hunter))/i.test(value);
|
|
1698
|
-
return withheld(existing.rule) && withheld(behavior) || !withheld(existing.rule) && claimed(existing.rule) && claimed(behavior) && !withheld(behavior);
|
|
1699
|
-
}
|
|
1700
|
-
if (proposal.decisionType === "CHOOSE_WITCH_SAVE") {
|
|
1701
|
-
const skipsSave = (value) => /(?:不救|不用|不使用|跳过|放弃)[^。;,,!!]{0,8}(?:救|解药)?|(?:skip|do not use|withhold)[^.;]{0,12}(?:save|antidote)/i.test(value);
|
|
1702
|
-
return skipsSave(existing.rule) === skipsSave(behavior) && /(?:救|解药|save|antidote)/i.test(behavior);
|
|
1703
|
-
}
|
|
1704
|
-
return false;
|
|
1705
|
-
}
|
|
1706
|
-
function assertRefinement(proposal, existing, risk) {
|
|
1707
|
-
if (!sameSemanticText(proposal.rule, existing.rule)) {
|
|
1708
|
-
throw new ProposalError("REFINE_RULE_CHANGED", "REFINE must narrow applicability without replacing the behavior rule");
|
|
1709
|
-
}
|
|
1710
|
-
if (risk !== existing.risk) {
|
|
1711
|
-
throw new ProposalError("REFINE_RISK_CHANGED", "REFINE cannot silently change the topic risk class");
|
|
1712
|
-
}
|
|
1713
|
-
const oldScope = `${existing.trigger} ${existing.boundary}`;
|
|
1714
|
-
const newScope = `${proposal.trigger} ${proposal.boundary}`;
|
|
1715
|
-
if (semanticText(oldScope) === semanticText(newScope) || semanticText(newScope).length <= semanticText(oldScope).length || similarity(oldScope, newScope) < 0.5) {
|
|
1716
|
-
throw new ProposalError("REFINE_NOT_NARROWER", "REFINE must preserve the topic and add a materially narrower trigger or boundary");
|
|
1717
|
-
}
|
|
1718
|
-
}
|
|
1719
|
-
function parseAndValidateProposal(raw, envelope, evidence, activeProfile) {
|
|
1720
|
-
const parsed = proposalSchema.safeParse(raw);
|
|
1721
|
-
if (!parsed.success) {
|
|
1722
|
-
throw new ProposalError("PROPOSAL_SCHEMA", parsed.error.issues.map((issue) => issue.message).join("; "));
|
|
1723
|
-
}
|
|
1724
|
-
const proposal = parsed.data;
|
|
1725
|
-
if (proposal.action === "SKIP") {
|
|
1726
|
-
requireText(proposal, "skipReason", 4);
|
|
1727
|
-
const evolutionaryFields = [
|
|
1728
|
-
proposal.topicId,
|
|
1729
|
-
proposal.decisionWindowId,
|
|
1730
|
-
proposal.anchorFactId,
|
|
1731
|
-
proposal.executionOperation,
|
|
1732
|
-
proposal.trigger,
|
|
1733
|
-
proposal.rule,
|
|
1734
|
-
proposal.boundary
|
|
1735
|
-
];
|
|
1736
|
-
if (evolutionaryFields.some((value) => value != null)) {
|
|
1737
|
-
throw new ProposalError("SKIP_WITH_EVOLUTION", "SKIP cannot carry a lesson mutation");
|
|
1738
|
-
}
|
|
1739
|
-
return { proposal };
|
|
1740
|
-
}
|
|
1741
|
-
const action = proposal.action;
|
|
1742
|
-
if (action === "NEW" && proposal.topicId) throw new ProposalError("NEW_WITH_TOPIC", "NEW must not provide topicId");
|
|
1743
|
-
if (action !== "NEW" && !proposal.topicId) {
|
|
1744
|
-
throw new ProposalError("EXISTING_TOPIC_REQUIRED", `${action} requires topicId`);
|
|
1745
|
-
}
|
|
1746
|
-
const existing = proposal.topicId ? evidence.lessons.find((lesson) => lesson.id === proposal.topicId) : void 0;
|
|
1747
|
-
if (action !== "NEW" && !existing) throw new ProposalError("TOPIC_NOT_FOUND", `Unknown topicId: ${proposal.topicId}`);
|
|
1748
|
-
const profile = requireText(proposal, "profile");
|
|
1749
|
-
if (envelope.game.profile !== void 0 && envelope.game.profile !== activeProfile) {
|
|
1750
|
-
throw new ProposalError("ENVELOPE_PROFILE_MISMATCH", "Envelope profile conflicts with the workspace runtime");
|
|
1751
|
-
}
|
|
1752
|
-
if (profile !== activeProfile) {
|
|
1753
|
-
throw new ProposalError("PROFILE_MISMATCH", "Proposal profile does not match the workspace runtime");
|
|
1754
|
-
}
|
|
1755
|
-
if (existing && existing.profile !== profile) {
|
|
1756
|
-
throw new ProposalError("TOPIC_PROFILE_MISMATCH", "Topic belongs to a different profile");
|
|
1757
|
-
}
|
|
1758
|
-
const decisionWindowId = requireText(proposal, "decisionWindowId");
|
|
1759
|
-
const window = envelope.decisionWindows.find((item) => item.decisionWindowId === decisionWindowId);
|
|
1760
|
-
if (!window) throw new ProposalError("DECISION_WINDOW_NOT_FOUND", "Proposal does not reference a trusted decision window");
|
|
1761
|
-
const decisionType = requireText(proposal, "decisionType");
|
|
1762
|
-
if (!window.allowedDecisionTypes.includes(decisionType)) {
|
|
1763
|
-
throw new ProposalError(
|
|
1764
|
-
"DECISION_TYPE_NOT_ALLOWED",
|
|
1765
|
-
`decisionType must be copied from allowedDecisionTypes: ${JSON.stringify(window.allowedDecisionTypes)}`
|
|
1766
|
-
);
|
|
1767
|
-
}
|
|
1768
|
-
const alternativeActionType = requireText(proposal, "alternativeActionType");
|
|
1769
|
-
if (!window.availableActionTypes.includes(alternativeActionType)) {
|
|
1770
|
-
throw new ProposalError(
|
|
1771
|
-
"ALTERNATIVE_ACTION_UNAVAILABLE",
|
|
1772
|
-
`alternativeActionType must be copied from availableActionTypes: ${JSON.stringify(window.availableActionTypes)}`
|
|
1773
|
-
);
|
|
1774
|
-
}
|
|
1775
|
-
if (proposal.source === "SELF" && window.actorSeat !== envelope.game.recipientSeat) {
|
|
1776
|
-
throw new ProposalError("SELF_ACTOR_MISMATCH", "SELF evidence must anchor the recipient's own action");
|
|
1777
|
-
}
|
|
1778
|
-
if (proposal.source !== "SELF" && window.actorSeat === envelope.game.recipientSeat) {
|
|
1779
|
-
throw new ProposalError("OTHER_ACTOR_MISMATCH", "OBSERVED and EXEMPLAR evidence must anchor another player's action");
|
|
1780
|
-
}
|
|
1781
|
-
if (action === "COUNTER" && proposal.source === "EXEMPLAR") {
|
|
1782
|
-
throw new ProposalError(
|
|
1783
|
-
"COUNTER_SOURCE_INVALID",
|
|
1784
|
-
"COUNTER is limited to SELF or OBSERVED evidence that followed an existing rule and produced an adverse result"
|
|
1785
|
-
);
|
|
1786
|
-
}
|
|
1787
|
-
const anchorFactId = requireText(proposal, "anchorFactId");
|
|
1788
|
-
if (anchorFactId !== window.anchorFactId) {
|
|
1789
|
-
throw new ProposalError("ANCHOR_WINDOW_MISMATCH", "anchorFactId does not match the trusted decision window");
|
|
1790
|
-
}
|
|
1791
|
-
requireText(proposal, "trigger", 4);
|
|
1792
|
-
const rule = requireText(proposal, "rule", 4);
|
|
1793
|
-
requireText(proposal, "boundary", 4);
|
|
1794
|
-
const describedBehavior = requireText(proposal, "behavior", 4);
|
|
1795
|
-
requireText(proposal, "alternativeAction", 4);
|
|
1796
|
-
requireText(proposal, "expectedLocalEffect", 4);
|
|
1797
|
-
const observed = requireText(proposal, "observedLocalEffect", 4);
|
|
1798
|
-
requireText(proposal, "falsifier", 4);
|
|
1799
|
-
if (!proposal.alternatives?.some((item) => item.trim().length >= 4)) {
|
|
1800
|
-
throw new ProposalError("ALTERNATIVE_EXPLANATION_REQUIRED", "At least one plausible alternative explanation is required");
|
|
1801
|
-
}
|
|
1802
|
-
if (FIXED_RULE_LANGUAGE.test(rule)) {
|
|
1803
|
-
throw new ProposalError("FIXED_RULE_NOT_LEARNABLE", "Permanent safety and protocol rules cannot be learned");
|
|
1804
|
-
}
|
|
1805
|
-
assertNoAbsoluteStrategyClaim(proposal);
|
|
1806
|
-
const facts = new Map(envelope.facts.map((fact) => [fact.factId, fact]));
|
|
1807
|
-
const anchor = facts.get(anchorFactId);
|
|
1808
|
-
if (!anchor || anchor.visibility === "POSTGAME_ONLY") {
|
|
1809
|
-
throw new ProposalError("ANCHOR_NOT_OBSERVABLE", "The action anchor is missing or postgame-only");
|
|
1810
|
-
}
|
|
1811
|
-
assertBehaviorIsObserved(proposal);
|
|
1812
|
-
assertCounterfactualCoherence(proposal, anchor);
|
|
1813
|
-
const known = proposal.knownFactRefs ?? [];
|
|
1814
|
-
const outcomes = proposal.outcomeFactRefs ?? [];
|
|
1815
|
-
const knownFacts = [];
|
|
1816
|
-
unique(known, "DUPLICATE_KNOWN_FACT");
|
|
1817
|
-
unique(outcomes, "DUPLICATE_OUTCOME_FACT");
|
|
1818
|
-
for (const ref of known) {
|
|
1819
|
-
const fact = facts.get(ref);
|
|
1820
|
-
if (!fact) throw new ProposalError("KNOWN_FACT_NOT_FOUND", `Unknown knownFactRef: ${ref}`);
|
|
1821
|
-
if (fact.visibility === "POSTGAME_ONLY") {
|
|
1822
|
-
throw new ProposalError("POSTGAME_FACT_AS_KNOWN", `Postgame-only fact used as known fact: ${ref}`);
|
|
1823
|
-
}
|
|
1824
|
-
if (!factVisibleToActor(fact.visibility, window)) {
|
|
1825
|
-
throw new ProposalError(
|
|
1826
|
-
"KNOWN_FACT_NOT_VISIBLE_TO_ACTOR",
|
|
1827
|
-
`Known fact was not visible to the decision actor: ${ref}`
|
|
1828
|
-
);
|
|
1829
|
-
}
|
|
1830
|
-
if (fact.availableAt.historyIndex >= anchor.availableAt.historyIndex) {
|
|
1831
|
-
throw new ProposalError("KNOWN_FACT_TOO_LATE", `Known fact is not earlier than the action: ${ref}`);
|
|
1832
|
-
}
|
|
1833
|
-
knownFacts.push(fact);
|
|
1834
|
-
}
|
|
1835
|
-
let localOutcomeCount = 0;
|
|
1836
|
-
const outcomeFacts = [];
|
|
1837
|
-
for (const ref of outcomes) {
|
|
1838
|
-
const fact = facts.get(ref);
|
|
1839
|
-
if (!fact) throw new ProposalError("OUTCOME_FACT_NOT_FOUND", `Unknown outcomeFactRef: ${ref}`);
|
|
1840
|
-
if (fact.availableAt.historyIndex <= anchor.availableAt.historyIndex) {
|
|
1841
|
-
throw new ProposalError("OUTCOME_FACT_TOO_EARLY", `Outcome fact is not later than the action: ${ref}`);
|
|
1842
|
-
}
|
|
1843
|
-
if (LOCAL_OUTCOME_FACT_TYPES.has(fact.type)) {
|
|
1844
|
-
localOutcomeCount++;
|
|
1845
|
-
}
|
|
1846
|
-
outcomeFacts.push(fact);
|
|
1847
|
-
}
|
|
1848
|
-
assertActionTimeSemantics(proposal, window, anchor, knownFacts);
|
|
1849
|
-
assertDecisionTypeSemantics(proposal);
|
|
1850
|
-
assertBehaviorMatchesAnchor(proposal, describedBehavior, anchor);
|
|
1851
|
-
assertLocalOutcomeEvidence(outcomes.length, localOutcomeCount, observed);
|
|
1852
|
-
assertObservedOutcomeSemantics(observed, outcomeFacts);
|
|
1853
|
-
const allRefs = /* @__PURE__ */ new Set([...known, ...outcomes]);
|
|
1854
|
-
if (allRefs.size !== known.length + outcomes.length) {
|
|
1855
|
-
throw new ProposalError("FACT_ROLE_CONFLICT", "A fact cannot be both known information and an outcome");
|
|
1856
|
-
}
|
|
1857
|
-
let risk = classifyRisk(proposal, window.allowedDecisionTypes.find((item) => item === decisionType));
|
|
1858
|
-
if (risk === "execution" && alternativeActionType !== window.actionType) risk = "strategy";
|
|
1859
|
-
assertAlternativeTarget(proposal, window, risk);
|
|
1860
|
-
assertAlternativeTargetConsistent(proposal);
|
|
1861
|
-
if (existing) {
|
|
1862
|
-
assertExistingSemantics(proposal, existing, window, action, envelope.game.players, describedBehavior);
|
|
1863
|
-
if (action === "REFINE") assertRefinement(proposal, existing, risk);
|
|
1864
|
-
}
|
|
1865
|
-
assertSourceOutcomeDirection(proposal, observed);
|
|
1866
|
-
if (action === "NEW") {
|
|
1867
|
-
const proposedText = `${proposal.trigger} ${proposal.rule} ${proposal.boundary}`;
|
|
1868
|
-
const duplicate = evidence.lessons.find((lesson) => lesson.status !== "archived" && lesson.profile === profile && similarity(proposedText, `${lesson.trigger} ${lesson.rule} ${lesson.boundary}`) >= 0.72);
|
|
1869
|
-
if (duplicate) {
|
|
1870
|
-
throw new ProposalError("SIMILAR_TOPIC_EXISTS", `Use SUPPORT, COUNTER or REFINE for ${duplicate.id}`);
|
|
1871
|
-
}
|
|
1872
|
-
}
|
|
1873
|
-
proposal.behavior = anchor.summary;
|
|
1874
|
-
return { proposal, risk, existing, decisionWindow: window };
|
|
1875
|
-
}
|
|
1876
|
-
|
|
1877
|
-
// src/workspace.ts
|
|
1878
|
-
import { lstatSync, mkdirSync, realpathSync } from "fs";
|
|
1879
|
-
import path from "path";
|
|
1880
|
-
var RUNTIME_START = "<!-- WEREWOLF_RUNTIME_START -->";
|
|
1881
|
-
var RUNTIME_END = "<!-- WEREWOLF_RUNTIME_END -->";
|
|
1882
|
-
var LEGACY_RUNTIME_START = "<!-- WOLF_PLAY_RUNTIME_START -->";
|
|
1883
|
-
var LEGACY_RUNTIME_END = "<!-- WOLF_PLAY_RUNTIME_END -->";
|
|
1884
|
-
function assertWorkspaceRootIdentity(paths) {
|
|
1885
|
-
let stat;
|
|
1886
|
-
let resolved;
|
|
1887
|
-
try {
|
|
1888
|
-
stat = lstatSync(paths.root);
|
|
1889
|
-
resolved = realpathSync(paths.root);
|
|
1890
|
-
} catch {
|
|
1891
|
-
throw new Error("WORKSPACE_ROOT_CHANGED");
|
|
1892
|
-
}
|
|
1893
|
-
if (!stat.isDirectory() || stat.isSymbolicLink() || resolved !== paths.root || stat.dev !== paths.rootDevice || stat.ino !== paths.rootInode) {
|
|
1894
|
-
throw new Error("WORKSPACE_ROOT_CHANGED");
|
|
1895
|
-
}
|
|
1896
|
-
}
|
|
1897
|
-
function assertNoSymlinkFromExistingAncestor(candidate, root) {
|
|
1898
|
-
const relative = path.relative(root, candidate);
|
|
1899
|
-
if (relative.startsWith("..") || path.isAbsolute(relative)) throw new Error("PATH_OUTSIDE_WORKSPACE");
|
|
1900
|
-
let current = root;
|
|
1901
|
-
for (const segment of relative.split(path.sep).filter(Boolean)) {
|
|
1902
|
-
current = path.join(current, segment);
|
|
1903
|
-
try {
|
|
1904
|
-
if (lstatSync(current).isSymbolicLink()) throw new Error(`SYMLINK_NOT_ALLOWED:${current}`);
|
|
1905
|
-
} catch (error) {
|
|
1906
|
-
const code = error.code;
|
|
1907
|
-
if (code === "ENOENT") break;
|
|
1908
|
-
throw error;
|
|
1909
|
-
}
|
|
1910
|
-
}
|
|
1911
|
-
}
|
|
1912
|
-
function assertSafeWorkspacePath(candidate, paths) {
|
|
1913
|
-
assertWorkspaceRootIdentity(paths);
|
|
1914
|
-
assertNoSymlinkFromExistingAncestor(path.resolve(candidate), paths.root);
|
|
1915
|
-
}
|
|
1916
|
-
function resolveWorkspacePaths(workspaceDir, createMemory = true) {
|
|
1917
|
-
if (!workspaceDir || !path.isAbsolute(workspaceDir)) throw new Error("WORKSPACE_ABSOLUTE_REQUIRED");
|
|
1918
|
-
const root = realpathSync(workspaceDir);
|
|
1919
|
-
const rootStat = lstatSync(root);
|
|
1920
|
-
if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) throw new Error("WORKSPACE_ROOT_INVALID");
|
|
1921
|
-
const memory = path.join(root, "memory");
|
|
1922
|
-
assertNoSymlinkFromExistingAncestor(memory, root);
|
|
1923
|
-
if (createMemory) mkdirSync(memory, { recursive: true, mode: 448 });
|
|
1924
|
-
assertNoSymlinkFromExistingAncestor(memory, root);
|
|
1925
|
-
const paths = {
|
|
1926
|
-
root,
|
|
1927
|
-
rootDevice: rootStat.dev,
|
|
1928
|
-
rootInode: rootStat.ino,
|
|
1929
|
-
memory,
|
|
1930
|
-
evidence: path.join(memory, "werewolf-evidence-v3.md"),
|
|
1931
|
-
incidents: path.join(memory, "werewolf-incidents.md"),
|
|
1932
|
-
suggestions: path.join(memory, "werewolf-suggestions.md"),
|
|
1933
|
-
ownerBinding: path.join(memory, "werewolf-evolution-owner.json"),
|
|
1934
|
-
ledger: path.join(memory, "werewolf-evolution-ledger.md"),
|
|
1935
|
-
agents: path.join(root, "AGENTS.md"),
|
|
1936
|
-
overrides: path.join(memory, "werewolf-profile-overrides"),
|
|
1937
|
-
customProfiles: path.join(memory, "werewolf-custom-profiles"),
|
|
1938
|
-
skill: path.join(root, "skills", "werewolf-play"),
|
|
1939
|
-
skillReferences: path.join(root, "skills", "werewolf-play", "references"),
|
|
1940
|
-
legacyEvidenceV2: path.join(memory, "wolf-play-evidence-v2.md"),
|
|
1941
|
-
legacySuggestions: path.join(memory, "wolf-play-suggestions.md"),
|
|
1942
|
-
migrationMarker: path.join(memory, "werewolf-evolution-migration-v3.md"),
|
|
1943
|
-
legacySkill: path.join(root, "skills", "wolf-play"),
|
|
1944
|
-
backups: path.join(root, "werewolf-evolution-backups"),
|
|
1945
|
-
setupLock: path.join(root, ".werewolf-evolution-setup.lock"),
|
|
1946
|
-
lock: path.join(memory, ".werewolf-evolution.lock"),
|
|
1947
|
-
journal: path.join(memory, ".werewolf-evolution-transaction.json")
|
|
1948
|
-
};
|
|
1949
|
-
assertWorkspaceRootIdentity(paths);
|
|
1950
|
-
for (const value of Object.values(paths)) {
|
|
1951
|
-
if (typeof value === "string") assertNoSymlinkFromExistingAncestor(value, root);
|
|
1952
|
-
}
|
|
1953
|
-
return paths;
|
|
1954
|
-
}
|
|
1955
|
-
function profileOverridePath(paths, profile) {
|
|
1956
|
-
if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(profile)) throw new Error("PROFILE_NAME_INVALID");
|
|
1957
|
-
return path.join(paths.overrides, `${profile}.md`);
|
|
1958
|
-
}
|
|
1959
|
-
function customProfilePath(paths, profile) {
|
|
1960
|
-
if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(profile)) throw new Error("PROFILE_NAME_INVALID");
|
|
1961
|
-
return path.join(paths.customProfiles, `${profile}.md`);
|
|
1962
|
-
}
|
|
1963
|
-
function installedProfilePath(paths, profile) {
|
|
1964
|
-
if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(profile)) throw new Error("PROFILE_NAME_INVALID");
|
|
1965
|
-
return path.join(paths.skillReferences, `profile-${profile.replaceAll("_", "-")}.md`);
|
|
1966
|
-
}
|
|
1967
|
-
function assertFixedTarget(target, paths) {
|
|
1968
|
-
const allowed = /* @__PURE__ */ new Set([
|
|
1969
|
-
paths.evidence,
|
|
1970
|
-
paths.incidents,
|
|
1971
|
-
paths.suggestions,
|
|
1972
|
-
paths.ownerBinding,
|
|
1973
|
-
paths.ledger,
|
|
1974
|
-
paths.agents,
|
|
1975
|
-
paths.legacyEvidenceV2,
|
|
1976
|
-
paths.legacySuggestions,
|
|
1977
|
-
paths.migrationMarker
|
|
1978
|
-
]);
|
|
1979
|
-
const resolved = path.resolve(target);
|
|
1980
|
-
const overrideRelative = path.relative(paths.overrides, resolved);
|
|
1981
|
-
const isOverride = overrideRelative.length > 0 && !overrideRelative.startsWith("..") && !path.isAbsolute(overrideRelative) && /^[a-z0-9][a-z0-9_-]{0,63}\.md$/.test(overrideRelative);
|
|
1982
|
-
const archiveRelative = path.relative(paths.memory, resolved);
|
|
1983
|
-
const isLegacyArchive = !archiveRelative.startsWith("..") && !path.isAbsolute(archiveRelative) && /^werewolf-(?:evidence|suggestions)-legacy-v2-[0-9]{8}T[0-9]{9}Z\.md$/.test(archiveRelative);
|
|
1984
|
-
if (!allowed.has(resolved) && !isOverride && !isLegacyArchive) throw new Error(`TARGET_NOT_ALLOWED:${target}`);
|
|
1985
|
-
assertSafeWorkspacePath(resolved, paths);
|
|
1986
|
-
}
|
|
1987
|
-
function resolvedDerivedPath(value, paths) {
|
|
1988
|
-
return path.resolve(paths.root, value);
|
|
1989
|
-
}
|
|
1990
|
-
function isProtectedPath(value, paths, includeAgents) {
|
|
1991
|
-
const resolved = resolvedDerivedPath(value, paths);
|
|
1992
|
-
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;
|
|
1993
|
-
const protectedDirectories = [paths.overrides, paths.skill, paths.legacySkill, paths.backups];
|
|
1994
|
-
if (includeAgents) protectedDirectories.push(paths.customProfiles);
|
|
1995
|
-
return protectedDirectories.some((directory) => {
|
|
1996
|
-
const relative = path.relative(directory, resolved);
|
|
1997
|
-
return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
1998
|
-
});
|
|
1999
|
-
}
|
|
2000
|
-
function isProtectedToolWrite(toolName, params, derivedPaths, paths, blockAllMutation = true, toolKind) {
|
|
2001
|
-
if (toolName === "werewolf_debrief_commit" || toolName === "werewolf_suggestion_decide") return false;
|
|
2002
|
-
const action = typeof params.action === "string" ? params.action : "";
|
|
2003
|
-
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);
|
|
2004
|
-
if (blockAllMutation && isGenericMutation) return true;
|
|
2005
|
-
if (!blockAllMutation && !isGenericMutation && toolKind !== "code_mode_exec") return false;
|
|
2006
|
-
if (derivedPaths?.some((value) => isProtectedPath(value, paths, blockAllMutation))) return true;
|
|
2007
|
-
let serialized = "";
|
|
2008
|
-
try {
|
|
2009
|
-
serialized = JSON.stringify(params);
|
|
2010
|
-
} catch {
|
|
2011
|
-
return true;
|
|
2012
|
-
}
|
|
2013
|
-
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;
|
|
2014
|
-
const runtimeProjection = /(?:(?:WEREWOLF|WOLF_PLAY)_RUNTIME_(?:START|END)|###\s+(?:GAME_EVENT execution contract|active lessons)|(?:werewolf|wolf)-play runtime|AGENTS\.md)/i;
|
|
2015
|
-
return managedState.test(serialized) || blockAllMutation && runtimeProjection.test(serialized);
|
|
2016
|
-
}
|
|
2017
|
-
|
|
2018
|
-
// src/documents.ts
|
|
2019
|
-
var DATA_START = "<!-- WEREWOLF_EVOLUTION_DATA_START -->";
|
|
2020
|
-
var DATA_END = "<!-- WEREWOLF_EVOLUTION_DATA_END -->";
|
|
2021
|
-
var MAX_MANAGED_FILE_BYTES = 2 * 1024 * 1024;
|
|
2022
|
-
var MAX_RUNTIME_CHARS = 8e3;
|
|
2023
|
-
var SAFE_PROFILE3 = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
2024
|
-
var SAFE_TOKEN2 = /^[A-Z][A-Z0-9_]{1,79}$/;
|
|
2025
|
-
var SAFE_LESSON = /^L-[a-z0-9][a-z0-9_-]{0,63}-\d{3,6}$/;
|
|
2026
|
-
var SAFE_SUGGESTION = /^S-\d{3,6}$/;
|
|
2027
|
-
var SAFE_DEBRIEF = /^werewolf:[0-9]{1,30}:agent:[0-9]{1,30}:v2$/;
|
|
2028
|
-
var DATE = /^\d{4}-\d{2}-\d{2}$/;
|
|
2029
|
-
var HASH = /^[a-f0-9]{64}$/;
|
|
2030
|
-
var sampleSchema = z3.object({
|
|
2031
|
-
gameId: z3.string().regex(/^[0-9]{1,30}$/),
|
|
2032
|
-
debriefId: z3.string().regex(SAFE_DEBRIEF),
|
|
2033
|
-
reviewDate: z3.string().regex(DATE),
|
|
2034
|
-
source: z3.enum(["SELF", "OBSERVED", "EXEMPLAR"]),
|
|
2035
|
-
decisionWindowId: z3.string().min(1).max(200),
|
|
2036
|
-
anchorFactId: z3.string().min(1).max(200),
|
|
2037
|
-
alternativeActionType: z3.string().regex(SAFE_TOKEN2),
|
|
2038
|
-
alternativeTargetSeat: z3.number().int().positive().nullable().optional(),
|
|
2039
|
-
knownFactRefs: z3.array(z3.string().min(1).max(200)).max(64),
|
|
2040
|
-
outcomeFactRefs: z3.array(z3.string().min(1).max(200)).min(1).max(64),
|
|
2041
|
-
behavior: z3.string().min(1).max(800),
|
|
2042
|
-
observedLocalEffect: z3.string().min(1).max(500),
|
|
2043
|
-
alternatives: z3.array(z3.string().min(1).max(500)).min(1).max(8)
|
|
2044
|
-
}).strict();
|
|
2045
|
-
var lessonSchema = z3.object({
|
|
2046
|
-
id: z3.string().regex(SAFE_LESSON),
|
|
2047
|
-
status: z3.enum(["candidate", "probation", "active", "contested", "archived"]),
|
|
2048
|
-
risk: z3.enum(["execution", "strategy"]),
|
|
2049
|
-
profile: z3.string().regex(SAFE_PROFILE3),
|
|
2050
|
-
phase: z3.string().regex(SAFE_TOKEN2),
|
|
2051
|
-
role: z3.string().regex(SAFE_TOKEN2),
|
|
2052
|
-
players: z3.number().int().positive().max(32),
|
|
2053
|
-
actionType: z3.string().regex(SAFE_TOKEN2),
|
|
2054
|
-
decisionType: z3.string().regex(SAFE_TOKEN2),
|
|
2055
|
-
executionOperation: z3.enum([
|
|
2056
|
-
"REPORT_DECIDED_ROLE_CLAIM",
|
|
2057
|
-
"EXPLAIN_DECIDED_VOTE",
|
|
2058
|
-
"RETRACT_PUBLIC_JUDGMENT",
|
|
2059
|
-
"AVOID_REPEATING_PRIOR_SPEAKERS",
|
|
2060
|
-
"EXPLAIN_DECIDED_WOLF_TARGET"
|
|
2061
|
-
]).optional(),
|
|
2062
|
-
trigger: z3.string().min(1).max(500),
|
|
2063
|
-
rule: z3.string().min(1).max(500),
|
|
2064
|
-
boundary: z3.string().min(1).max(500),
|
|
2065
|
-
expectedLocalEffect: z3.string().min(1).max(500),
|
|
2066
|
-
falsifier: z3.string().min(1).max(500),
|
|
2067
|
-
supportGames: z3.array(sampleSchema).max(512),
|
|
2068
|
-
counterGames: z3.array(sampleSchema).max(512),
|
|
2069
|
-
probationStartedAtSupportCount: z3.number().int().positive().optional(),
|
|
2070
|
-
supersedesLessonId: z3.string().regex(SAFE_LESSON).optional(),
|
|
2071
|
-
supersededByLessonId: z3.string().regex(SAFE_LESSON).optional(),
|
|
2072
|
-
createdAt: z3.string().datetime({ offset: true }),
|
|
2073
|
-
lastReviewed: z3.string().regex(DATE)
|
|
2074
|
-
}).strict();
|
|
2075
|
-
var evidenceSchema = z3.object({
|
|
2076
|
-
schemaVersion: z3.literal(3),
|
|
2077
|
-
lessons: z3.array(lessonSchema).max(4096)
|
|
2078
|
-
}).strict();
|
|
2079
|
-
var incidentSchema = z3.object({
|
|
2080
|
-
debriefId: z3.string().regex(SAFE_DEBRIEF),
|
|
2081
|
-
gameId: z3.string().regex(/^[0-9]{1,30}$/),
|
|
2082
|
-
reviewDate: z3.string().regex(DATE),
|
|
2083
|
-
reasons: z3.array(z3.string().regex(/^[A-Z][A-Z0-9_]{1,79}$/)).min(1).max(16),
|
|
2084
|
-
recordedAt: z3.string().datetime({ offset: true })
|
|
2085
|
-
}).strict();
|
|
2086
|
-
var incidentsSchema = z3.object({
|
|
2087
|
-
schemaVersion: z3.literal(1),
|
|
2088
|
-
incidents: z3.array(incidentSchema).max(4096)
|
|
2089
|
-
}).strict();
|
|
2090
|
-
var suggestionSchema = z3.object({
|
|
2091
|
-
id: z3.string().regex(SAFE_SUGGESTION),
|
|
2092
|
-
lessonId: z3.string().regex(SAFE_LESSON),
|
|
2093
|
-
profile: z3.string().regex(SAFE_PROFILE3),
|
|
2094
|
-
status: z3.enum(["pending", "accepted", "rejected", "paused", "withdrawn"]),
|
|
2095
|
-
trigger: z3.string().min(1).max(500),
|
|
2096
|
-
rule: z3.string().min(1).max(500),
|
|
2097
|
-
boundary: z3.string().min(1).max(500),
|
|
2098
|
-
supportCount: z3.number().int().nonnegative(),
|
|
2099
|
-
counterCount: z3.number().int().nonnegative(),
|
|
2100
|
-
createdAt: z3.string().datetime({ offset: true }),
|
|
2101
|
-
reminderSentAt: z3.string().datetime({ offset: true }).optional(),
|
|
2102
|
-
decidedAt: z3.string().datetime({ offset: true }).optional(),
|
|
2103
|
-
decidedBy: z3.string().min(1).max(200).optional(),
|
|
2104
|
-
pausedAt: z3.string().datetime({ offset: true }).optional(),
|
|
2105
|
-
pauseReason: z3.string().min(1).max(200).optional()
|
|
2106
|
-
}).strict();
|
|
2107
|
-
var suggestionsSchema = z3.object({
|
|
2108
|
-
schemaVersion: z3.literal(1),
|
|
2109
|
-
suggestions: z3.array(suggestionSchema).max(4096)
|
|
2110
|
-
}).strict();
|
|
2111
|
-
var ledgerEntrySchema = z3.object({
|
|
2112
|
-
debriefId: z3.string().regex(SAFE_DEBRIEF),
|
|
2113
|
-
gameId: z3.string().regex(/^[0-9]{1,30}$/),
|
|
2114
|
-
bodyHash: z3.string().regex(HASH),
|
|
2115
|
-
action: z3.enum(["SKIP", "SUPPORT", "COUNTER", "REFINE", "NEW", "INCIDENT"]),
|
|
2116
|
-
outcome: z3.string().min(1).max(100),
|
|
2117
|
-
processedAt: z3.string().datetime({ offset: true })
|
|
2118
|
-
}).strict();
|
|
2119
|
-
var ledgerSchema = z3.object({
|
|
2120
|
-
schemaVersion: z3.literal(1),
|
|
2121
|
-
entries: z3.array(ledgerEntrySchema).max(1e5),
|
|
2122
|
-
legacyGameIds: z3.array(z3.string().regex(/^[0-9]{1,30}$/)).max(1e5).default([])
|
|
2123
|
-
}).strict();
|
|
2124
|
-
var emptyEvidence = () => ({ schemaVersion: 3, lessons: [] });
|
|
2125
|
-
var emptyIncidents = () => ({ schemaVersion: 1, incidents: [] });
|
|
2126
|
-
var emptySuggestions = () => ({ schemaVersion: 1, suggestions: [] });
|
|
2127
|
-
var emptyLedger = () => ({ schemaVersion: 1, entries: [], legacyGameIds: [] });
|
|
2128
|
-
function renderManaged(title, value) {
|
|
2129
|
-
return [
|
|
2130
|
-
`# ${title}`,
|
|
2131
|
-
"",
|
|
2132
|
-
"This file is managed by werewolf-evolution. Do not edit its data block manually.",
|
|
2133
|
-
"",
|
|
2134
|
-
DATA_START,
|
|
2135
|
-
"```json",
|
|
2136
|
-
JSON.stringify(value, null, 2),
|
|
2137
|
-
"```",
|
|
2138
|
-
DATA_END,
|
|
2139
|
-
""
|
|
2140
|
-
].join("\n");
|
|
2141
|
-
}
|
|
2142
|
-
function parseManaged(content, label) {
|
|
2143
|
-
const start = content.indexOf(DATA_START);
|
|
2144
|
-
const end = content.indexOf(DATA_END);
|
|
2145
|
-
if (start < 0 || end <= start || content.indexOf(DATA_START, start + 1) >= 0 || content.indexOf(DATA_END, end + 1) >= 0) {
|
|
2146
|
-
throw new Error(`MANAGED_MARKERS_INVALID:${label}`);
|
|
2147
|
-
}
|
|
2148
|
-
const block = content.slice(start + DATA_START.length, end).trim();
|
|
2149
|
-
const match = /^```json[ \t]*\r?\n([\s\S]*)\r?\n```$/.exec(block);
|
|
2150
|
-
if (!match) throw new Error(`MANAGED_JSON_BLOCK_INVALID:${label}`);
|
|
2151
|
-
try {
|
|
2152
|
-
return JSON.parse(match[1]);
|
|
2153
|
-
} catch (error) {
|
|
2154
|
-
throw new Error(`MANAGED_JSON_INVALID:${label}:${String(error)}`);
|
|
2155
|
-
}
|
|
2156
|
-
}
|
|
2157
|
-
function readOrDefault(file, fallback, label, schema) {
|
|
2158
|
-
if (!existsSync(file)) return fallback();
|
|
2159
|
-
const stat = lstatSync2(file);
|
|
2160
|
-
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_MANAGED_FILE_BYTES) {
|
|
2161
|
-
throw new Error(`MANAGED_FILE_INVALID:${label}`);
|
|
2162
|
-
}
|
|
2163
|
-
const parsed = schema.safeParse(parseManaged(readFileSync(file, "utf8"), label));
|
|
2164
|
-
if (!parsed.success) throw new Error(`MANAGED_SCHEMA_INVALID:${label}:${parsed.error.message}`);
|
|
2165
|
-
return parsed.data;
|
|
2166
|
-
}
|
|
2167
|
-
function uniqueValues(values, code) {
|
|
2168
|
-
if (new Set(values).size !== values.length) throw new Error(code);
|
|
2169
|
-
}
|
|
2170
|
-
function independentDates(samples) {
|
|
2171
|
-
return new Set(samples.map((sample2) => sample2.reviewDate)).size;
|
|
2172
|
-
}
|
|
2173
|
-
function semanticValue(value) {
|
|
2174
|
-
return value.toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, "");
|
|
2175
|
-
}
|
|
2176
|
-
function validateSampleRefs(sample2, expectedActions, ledgerByDebrief) {
|
|
2177
|
-
const prefix = `${sample2.debriefId}:`;
|
|
2178
|
-
if (!sample2.decisionWindowId.startsWith(`${prefix}d:`) || !sample2.anchorFactId.startsWith(`${prefix}h:`) || [...sample2.knownFactRefs, ...sample2.outcomeFactRefs].some((ref) => !ref.startsWith(`${prefix}h:`))) {
|
|
2179
|
-
throw new Error(`SAMPLE_FACT_SCOPE_MISMATCH:${sample2.debriefId}`);
|
|
2180
|
-
}
|
|
2181
|
-
uniqueValues(sample2.knownFactRefs, `DUPLICATE_SAMPLE_KNOWN_FACT:${sample2.debriefId}`);
|
|
2182
|
-
uniqueValues(sample2.outcomeFactRefs, `DUPLICATE_SAMPLE_OUTCOME_FACT:${sample2.debriefId}`);
|
|
2183
|
-
if (sample2.knownFactRefs.some((ref) => sample2.outcomeFactRefs.includes(ref))) {
|
|
2184
|
-
throw new Error(`SAMPLE_FACT_ROLE_CONFLICT:${sample2.debriefId}`);
|
|
2185
|
-
}
|
|
2186
|
-
const ledger = ledgerByDebrief.get(sample2.debriefId);
|
|
2187
|
-
if (!ledger || ledger.gameId !== sample2.gameId || !expectedActions.has(ledger.action)) {
|
|
2188
|
-
throw new Error(`SAMPLE_LEDGER_MISMATCH:${sample2.debriefId}`);
|
|
2189
|
-
}
|
|
2190
|
-
}
|
|
2191
|
-
function validateLessonReachability(lesson) {
|
|
2192
|
-
if (!lesson.id.startsWith(`L-${lesson.profile}-`)) throw new Error(`LESSON_PROFILE_ID_MISMATCH:${lesson.id}`);
|
|
2193
|
-
const supports = lesson.supportGames.length;
|
|
2194
|
-
const counters = lesson.counterGames.length;
|
|
2195
|
-
const dates = independentDates(lesson.supportGames);
|
|
2196
|
-
if (supports < 1) throw new Error(`LESSON_WITHOUT_SUPPORT:${lesson.id}`);
|
|
2197
|
-
if (lesson.risk === "strategy") {
|
|
2198
|
-
if (lesson.executionOperation !== void 0) throw new Error(`STRATEGY_EXECUTION_OPERATION:${lesson.id}`);
|
|
2199
|
-
if (lesson.status === "probation" || lesson.status === "active") {
|
|
2200
|
-
throw new Error(`STRATEGY_RUNTIME_STATUS:${lesson.id}`);
|
|
2201
|
-
}
|
|
2202
|
-
if (lesson.status === "candidate" && counters > 0) throw new Error(`STRATEGY_CANDIDATE_WITH_COUNTER:${lesson.id}`);
|
|
2203
|
-
if (lesson.status === "contested" && counters < 1) throw new Error(`STRATEGY_CONTESTED_WITHOUT_COUNTER:${lesson.id}`);
|
|
2204
|
-
if (lesson.probationStartedAtSupportCount !== void 0) {
|
|
2205
|
-
throw new Error(`STRATEGY_PROBATION_METADATA:${lesson.id}`);
|
|
2206
|
-
}
|
|
2207
|
-
return;
|
|
2208
|
-
}
|
|
2209
|
-
if (!matchesExecutionDefinition(lesson, lesson.supersedesLessonId !== void 0, false)) {
|
|
2210
|
-
throw new Error(`EXECUTION_DEFINITION_INVALID:${lesson.id}`);
|
|
2211
|
-
}
|
|
2212
|
-
if (lesson.status === "candidate" && counters > 0) throw new Error(`EXECUTION_CANDIDATE_WITH_COUNTER:${lesson.id}`);
|
|
2213
|
-
if (lesson.status === "probation") {
|
|
2214
|
-
if (supports < 3 || dates < 2 || counters > 0 || lesson.probationStartedAtSupportCount === void 0 || lesson.probationStartedAtSupportCount < 3 || lesson.probationStartedAtSupportCount > supports) {
|
|
2215
|
-
throw new Error(`EXECUTION_PROBATION_UNREACHABLE:${lesson.id}`);
|
|
2216
|
-
}
|
|
2217
|
-
}
|
|
2218
|
-
if (lesson.status === "active") {
|
|
2219
|
-
const started = lesson.probationStartedAtSupportCount;
|
|
2220
|
-
if (started === void 0 || started < 3 || supports - started < 2 || dates < 2 || counters >= 2) {
|
|
2221
|
-
throw new Error(`EXECUTION_ACTIVE_UNREACHABLE:${lesson.id}`);
|
|
2222
|
-
}
|
|
2223
|
-
}
|
|
2224
|
-
if (lesson.status === "contested" && counters < 1) {
|
|
2225
|
-
throw new Error(`EXECUTION_CONTESTED_WITHOUT_COUNTER:${lesson.id}`);
|
|
2226
|
-
}
|
|
2227
|
-
if (lesson.status === "candidate" && lesson.probationStartedAtSupportCount !== void 0) {
|
|
2228
|
-
throw new Error(`EXECUTION_PROBATION_METADATA_INVALID:${lesson.id}`);
|
|
2229
|
-
}
|
|
2230
|
-
}
|
|
2231
|
-
function validateState(state) {
|
|
2232
|
-
uniqueValues(state.evidence.lessons.map((lesson) => lesson.id), "DUPLICATE_LESSON_ID");
|
|
2233
|
-
uniqueValues(state.suggestions.suggestions.map((item) => item.id), "DUPLICATE_SUGGESTION_ID");
|
|
2234
|
-
uniqueValues(state.ledger.entries.map((entry2) => entry2.debriefId), "DUPLICATE_LEDGER_DEBRIEF");
|
|
2235
|
-
uniqueValues(state.ledger.entries.map((entry2) => entry2.gameId), "DUPLICATE_LEDGER_GAME");
|
|
2236
|
-
uniqueValues(state.ledger.legacyGameIds, "DUPLICATE_LEGACY_LEDGER_GAME");
|
|
2237
|
-
if (state.ledger.entries.some((entry2) => state.ledger.legacyGameIds.includes(entry2.gameId))) {
|
|
2238
|
-
throw new Error("LEGACY_LEDGER_GAME_OVERLAP");
|
|
2239
|
-
}
|
|
2240
|
-
uniqueValues(state.incidents.incidents.map((entry2) => entry2.debriefId), "DUPLICATE_INCIDENT_DEBRIEF");
|
|
2241
|
-
const ledgerByDebrief = new Map(state.ledger.entries.map((entry2) => [entry2.debriefId, entry2]));
|
|
2242
|
-
const sampleGames = /* @__PURE__ */ new Set();
|
|
2243
|
-
for (const lesson of state.evidence.lessons) {
|
|
2244
|
-
const supports = lesson.supportGames.map((sample2) => sample2.gameId);
|
|
2245
|
-
const counters = lesson.counterGames.map((sample2) => sample2.gameId);
|
|
2246
|
-
uniqueValues(supports, `DUPLICATE_SUPPORT_GAME:${lesson.id}`);
|
|
2247
|
-
uniqueValues(counters, `DUPLICATE_COUNTER_GAME:${lesson.id}`);
|
|
2248
|
-
if (supports.some((gameId) => counters.includes(gameId))) throw new Error(`SUPPORT_COUNTER_OVERLAP:${lesson.id}`);
|
|
2249
|
-
validateLessonReachability(lesson);
|
|
2250
|
-
for (const sample2 of [...lesson.supportGames, ...lesson.counterGames]) {
|
|
2251
|
-
if (sampleGames.has(sample2.gameId)) throw new Error(`GAME_SAMPLE_REUSED:${sample2.gameId}`);
|
|
2252
|
-
sampleGames.add(sample2.gameId);
|
|
2253
|
-
}
|
|
2254
|
-
for (const sample2 of lesson.supportGames) {
|
|
2255
|
-
validateSampleRefs(sample2, /* @__PURE__ */ new Set(["NEW", "SUPPORT", "REFINE"]), ledgerByDebrief);
|
|
2256
|
-
}
|
|
2257
|
-
for (const sample2 of lesson.counterGames) {
|
|
2258
|
-
validateSampleRefs(sample2, /* @__PURE__ */ new Set(["COUNTER"]), ledgerByDebrief);
|
|
2259
|
-
}
|
|
2260
|
-
}
|
|
2261
|
-
for (const incident of state.incidents.incidents) {
|
|
2262
|
-
const ledger = ledgerByDebrief.get(incident.debriefId);
|
|
2263
|
-
if (!ledger || ledger.gameId !== incident.gameId || ledger.action !== "INCIDENT") {
|
|
2264
|
-
throw new Error(`INCIDENT_LEDGER_MISMATCH:${incident.debriefId}`);
|
|
2265
|
-
}
|
|
2266
|
-
}
|
|
2267
|
-
const lessonById = new Map(state.evidence.lessons.map((lesson) => [lesson.id, lesson]));
|
|
2268
|
-
for (const suggestion of state.suggestions.suggestions) {
|
|
2269
|
-
const lesson = lessonById.get(suggestion.lessonId);
|
|
2270
|
-
if (!lesson || lesson.risk !== "strategy" || lesson.profile !== suggestion.profile) {
|
|
2271
|
-
throw new Error(`SUGGESTION_LESSON_MISMATCH:${suggestion.id}`);
|
|
2272
|
-
}
|
|
2273
|
-
if (suggestion.trigger !== lesson.trigger || suggestion.rule !== lesson.rule || suggestion.boundary !== lesson.boundary) {
|
|
2274
|
-
throw new Error(`SUGGESTION_SEMANTICS_MISMATCH:${suggestion.id}`);
|
|
2275
|
-
}
|
|
2276
|
-
if (suggestion.supportCount !== lesson.supportGames.length || suggestion.counterCount !== lesson.counterGames.length) {
|
|
2277
|
-
throw new Error(`SUGGESTION_COUNT_MISMATCH:${suggestion.id}`);
|
|
2278
|
-
}
|
|
2279
|
-
const sourceSet = new Set(lesson.supportGames.map((sample2) => sample2.source));
|
|
2280
|
-
if (suggestion.supportCount < 5 || independentDates(lesson.supportGames) < 2 || !sourceSet.has("SELF") || !sourceSet.has("OBSERVED") && !sourceSet.has("EXEMPLAR")) {
|
|
2281
|
-
throw new Error(`SUGGESTION_THRESHOLD_UNREACHABLE:${suggestion.id}`);
|
|
2282
|
-
}
|
|
2283
|
-
if ((suggestion.status === "pending" || suggestion.status === "accepted") && suggestion.counterCount > 0) {
|
|
2284
|
-
throw new Error(`SUGGESTION_LIVE_WITH_COUNTER:${suggestion.id}`);
|
|
2285
|
-
}
|
|
2286
|
-
if ((suggestion.status === "pending" || suggestion.status === "accepted") && lesson.status !== "candidate") {
|
|
2287
|
-
throw new Error(`SUGGESTION_LIVE_LESSON_STATUS:${suggestion.id}`);
|
|
2288
|
-
}
|
|
2289
|
-
if (suggestion.status === "pending" && (suggestion.decidedAt || suggestion.decidedBy || suggestion.pausedAt || suggestion.pauseReason)) {
|
|
2290
|
-
throw new Error(`SUGGESTION_PENDING_METADATA:${suggestion.id}`);
|
|
2291
|
-
}
|
|
2292
|
-
if ((suggestion.status === "accepted" || suggestion.status === "rejected" || suggestion.status === "paused") && (!suggestion.decidedAt || !suggestion.decidedBy)) {
|
|
2293
|
-
throw new Error(`SUGGESTION_DECISION_METADATA_MISSING:${suggestion.id}`);
|
|
2294
|
-
}
|
|
2295
|
-
if ((suggestion.status === "accepted" || suggestion.status === "rejected") && (suggestion.pausedAt || suggestion.pauseReason)) {
|
|
2296
|
-
throw new Error(`SUGGESTION_DECISION_METADATA_INVALID:${suggestion.id}`);
|
|
2297
|
-
}
|
|
2298
|
-
if (suggestion.status === "paused" && (!suggestion.pausedAt || !suggestion.pauseReason || suggestion.counterCount !== 1 || lesson.status !== "contested")) {
|
|
2299
|
-
throw new Error(`SUGGESTION_PAUSE_UNREACHABLE:${suggestion.id}`);
|
|
2300
|
-
}
|
|
2301
|
-
if (suggestion.status === "withdrawn" && (!suggestion.decidedAt || suggestion.counterCount < 2 && lesson.status !== "archived" || suggestion.counterCount >= 2 && lesson.status !== "contested")) {
|
|
2302
|
-
throw new Error(`SUGGESTION_WITHDRAWAL_UNREACHABLE:${suggestion.id}`);
|
|
2303
|
-
}
|
|
2304
|
-
}
|
|
2305
|
-
for (const lesson of state.evidence.lessons) {
|
|
2306
|
-
if (lesson.supersedesLessonId) {
|
|
2307
|
-
const prior = lessonById.get(lesson.supersedesLessonId);
|
|
2308
|
-
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}`)) {
|
|
2309
|
-
throw new Error(`LESSON_SUPERSESSION_INVALID:${lesson.id}`);
|
|
2310
|
-
}
|
|
2311
|
-
}
|
|
2312
|
-
if (lesson.supersededByLessonId) {
|
|
2313
|
-
const next = lessonById.get(lesson.supersededByLessonId);
|
|
2314
|
-
if (!next || next.id === lesson.id || next.supersedesLessonId !== lesson.id || lesson.status !== "archived" || next.profile !== lesson.profile || next.risk !== lesson.risk) {
|
|
2315
|
-
throw new Error(`LESSON_SUPERSESSION_INVALID:${lesson.id}`);
|
|
2316
|
-
}
|
|
2317
|
-
}
|
|
2318
|
-
const visited = /* @__PURE__ */ new Set([lesson.id]);
|
|
2319
|
-
let cursor = lesson;
|
|
2320
|
-
while (cursor.supersededByLessonId) {
|
|
2321
|
-
if (visited.has(cursor.supersededByLessonId)) throw new Error(`LESSON_SUPERSESSION_CYCLE:${lesson.id}`);
|
|
2322
|
-
visited.add(cursor.supersededByLessonId);
|
|
2323
|
-
cursor = lessonById.get(cursor.supersededByLessonId);
|
|
2324
|
-
}
|
|
2325
|
-
}
|
|
2326
|
-
const sampledDebriefs = new Set(sampleGames.size > 0 ? state.evidence.lessons.flatMap((lesson) => [...lesson.supportGames, ...lesson.counterGames].map((sample2) => sample2.debriefId)) : []);
|
|
2327
|
-
const incidentDebriefs = new Set(state.incidents.incidents.map((incident) => incident.debriefId));
|
|
2328
|
-
for (const entry2 of state.ledger.entries) {
|
|
2329
|
-
if (["NEW", "SUPPORT", "COUNTER", "REFINE"].includes(entry2.action) && !sampledDebriefs.has(entry2.debriefId)) {
|
|
2330
|
-
throw new Error(`LEDGER_SAMPLE_MISSING:${entry2.debriefId}`);
|
|
2331
|
-
}
|
|
2332
|
-
if (entry2.action === "INCIDENT" && !incidentDebriefs.has(entry2.debriefId)) {
|
|
2333
|
-
throw new Error(`LEDGER_INCIDENT_MISSING:${entry2.debriefId}`);
|
|
2334
|
-
}
|
|
2335
|
-
if (entry2.action === "SKIP" && (sampledDebriefs.has(entry2.debriefId) || incidentDebriefs.has(entry2.debriefId))) {
|
|
2336
|
-
throw new Error(`LEDGER_SKIP_HAS_MUTATION:${entry2.debriefId}`);
|
|
2337
|
-
}
|
|
2338
|
-
}
|
|
2339
|
-
const profiles = new Set(state.evidence.lessons.map((lesson) => lesson.profile));
|
|
2340
|
-
for (const profile of profiles) {
|
|
2341
|
-
const records = state.evidence.lessons.filter((lesson) => lesson.profile === profile);
|
|
2342
|
-
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) {
|
|
2343
|
-
throw new Error(`PROFILE_LIMIT_EXCEEDED:${profile}`);
|
|
2344
|
-
}
|
|
2345
|
-
}
|
|
2346
|
-
}
|
|
2347
|
-
function oneLine(block, pattern, label) {
|
|
2348
|
-
const matches = [...block.matchAll(pattern)];
|
|
2349
|
-
if (matches.length !== 1) throw new Error(`RUNTIME_FIELD_INVALID:${label}`);
|
|
2350
|
-
return matches[0];
|
|
2351
|
-
}
|
|
2352
|
-
function inspectRuntimeProjection(content) {
|
|
2353
|
-
if (content.includes(LEGACY_RUNTIME_START) || content.includes(LEGACY_RUNTIME_END)) {
|
|
2354
|
-
throw new Error("LEGACY_RUNTIME_REQUIRES_MIGRATION");
|
|
2355
|
-
}
|
|
2356
|
-
const starts = content.split(RUNTIME_START).length - 1;
|
|
2357
|
-
const ends = content.split(RUNTIME_END).length - 1;
|
|
2358
|
-
if (starts === 0 && ends === 0) return null;
|
|
2359
|
-
if (starts !== 1 || ends !== 1) throw new Error("RUNTIME_MARKERS_INVALID");
|
|
2360
|
-
const startIndex = content.indexOf(RUNTIME_START);
|
|
2361
|
-
const endMarkerIndex = content.indexOf(RUNTIME_END);
|
|
2362
|
-
if (startIndex < 0 || endMarkerIndex <= startIndex) throw new Error("RUNTIME_MARKERS_INVALID");
|
|
2363
|
-
const endIndex = endMarkerIndex + RUNTIME_END.length;
|
|
2364
|
-
const block = content.slice(startIndex, endIndex);
|
|
2365
|
-
if (block.length > MAX_RUNTIME_CHARS) throw new Error("RUNTIME_TOO_LARGE");
|
|
2366
|
-
const heading = oneLine(block, /^## werewolf-play runtime v1[ \t]*\r?$/gm, "heading");
|
|
2367
|
-
const version = oneLine(block, /^runtime_version:[ \t]*(\S+)[ \t]*\r?$/gm, "version");
|
|
2368
|
-
const profile = oneLine(block, /^active_profile:[ \t]*(\S+)[ \t]*\r?$/gm, "profile");
|
|
2369
|
-
const contract = oneLine(block, /^### GAME_EVENT execution contract[ \t]*\r?$/gm, "contract");
|
|
2370
|
-
const playbook = oneLine(block, /^### active profile playbook[ \t]*\r?$/gm, "playbook");
|
|
2371
|
-
const lessons = oneLine(block, /^### active lessons[ \t]*\r?$/gm, "lessons");
|
|
2372
|
-
const order = [heading.index, version.index, profile.index, contract.index, playbook.index, lessons.index];
|
|
2373
|
-
if (version[1] !== "1" || !SAFE_PROFILE3.test(profile[1]) || !order.every((value, index) => index === 0 || value > order[index - 1])) {
|
|
2374
|
-
throw new Error("RUNTIME_STRUCTURE_INVALID");
|
|
2375
|
-
}
|
|
2376
|
-
const playbookBodyStart = playbook.index + playbook[0].length;
|
|
2377
|
-
const playbookBodyEnd = lessons.index;
|
|
2378
|
-
const lessonsBodyStart = lessons.index + lessons[0].length;
|
|
2379
|
-
const lessonsBodyEnd = block.length - RUNTIME_END.length;
|
|
2380
|
-
const playbookText = block.slice(playbookBodyStart, playbookBodyEnd).trim();
|
|
2381
|
-
const lessonsText = block.slice(lessonsBodyStart, lessonsBodyEnd).trim();
|
|
2382
|
-
if (!block.slice(contract.index + contract[0].length, playbook.index).trim() || !playbookText || !lessonsText) throw new Error("RUNTIME_BODY_INVALID");
|
|
2383
|
-
return {
|
|
2384
|
-
startIndex,
|
|
2385
|
-
endIndex,
|
|
2386
|
-
block,
|
|
2387
|
-
activeProfile: profile[1],
|
|
2388
|
-
playbook: playbookText,
|
|
2389
|
-
lessons: lessonsText,
|
|
2390
|
-
playbookBodyStart,
|
|
2391
|
-
playbookBodyEnd,
|
|
2392
|
-
lessonsBodyStart,
|
|
2393
|
-
lessonsBodyEnd
|
|
2394
|
-
};
|
|
2395
|
-
}
|
|
2396
|
-
function readWorkspaceState(paths, agentsTextOverride) {
|
|
2397
|
-
const state = {
|
|
2398
|
-
evidence: readOrDefault(paths.evidence, emptyEvidence, "evidence", evidenceSchema),
|
|
2399
|
-
incidents: readOrDefault(paths.incidents, emptyIncidents, "incidents", incidentsSchema),
|
|
2400
|
-
suggestions: readOrDefault(paths.suggestions, emptySuggestions, "suggestions", suggestionsSchema),
|
|
2401
|
-
ledger: readOrDefault(paths.ledger, emptyLedger, "ledger", ledgerSchema),
|
|
2402
|
-
agentsText: agentsTextOverride ?? (existsSync(paths.agents) ? readFileSync(paths.agents, "utf8") : "")
|
|
2403
|
-
};
|
|
2404
|
-
validateState(state);
|
|
2405
|
-
inspectRuntimeProjection(state.agentsText);
|
|
2406
|
-
return state;
|
|
2407
|
-
}
|
|
2408
|
-
function renderEvidence(value) {
|
|
2409
|
-
return renderManaged("werewolf evidence v3", value);
|
|
2410
|
-
}
|
|
2411
|
-
function renderIncidents(value) {
|
|
2412
|
-
return renderManaged("werewolf incidents", value);
|
|
2413
|
-
}
|
|
2414
|
-
function renderSuggestions(value) {
|
|
2415
|
-
return renderManaged("werewolf suggestions", value);
|
|
2416
|
-
}
|
|
2417
|
-
function renderLedger(value) {
|
|
2418
|
-
return renderManaged("werewolf evolution ledger", value);
|
|
2419
|
-
}
|
|
2420
|
-
function renderRuntimeLessons(state, activeProfile) {
|
|
2421
|
-
const records = state.evidence.lessons.filter((lesson) => lesson.profile === activeProfile && lesson.risk === "execution" && (lesson.status === "active" || lesson.status === "probation"));
|
|
2422
|
-
const active = records.filter((lesson) => lesson.status === "active").sort((left, right) => right.lastReviewed.localeCompare(left.lastReviewed)).slice(0, 6);
|
|
2423
|
-
const probation = records.filter((lesson) => lesson.status === "probation").sort((left, right) => right.lastReviewed.localeCompare(left.lastReviewed)).slice(0, 1);
|
|
2424
|
-
if (active.length === 0 && probation.length === 0) return "none";
|
|
2425
|
-
const lines = [];
|
|
2426
|
-
for (const lesson of [...active, ...probation]) {
|
|
2427
|
-
if (lines.length > 0) lines.push("");
|
|
2428
|
-
lines.push(
|
|
2429
|
-
`**\u6807\u7B7E**\uFF1Aid=${lesson.id} | status=${lesson.status} | risk=execution | profile=${lesson.profile} | phase=${lesson.phase} | role=${lesson.role} | players=${lesson.players}`,
|
|
2430
|
-
`**\u89E6\u53D1**\uFF1A${lesson.trigger}`,
|
|
2431
|
-
`**\u89C4\u5219**\uFF1A${lesson.rule}`,
|
|
2432
|
-
`**\u8FB9\u754C**\uFF1A${lesson.boundary}`
|
|
2433
|
-
);
|
|
2434
|
-
}
|
|
2435
|
-
return lines.join("\n");
|
|
2436
|
-
}
|
|
2437
|
-
function projectRuntime(state) {
|
|
2438
|
-
const runtime = inspectRuntimeProjection(state.agentsText);
|
|
2439
|
-
if (!runtime) return state.agentsText;
|
|
2440
|
-
const lessons = renderRuntimeLessons(state, runtime.activeProfile);
|
|
2441
|
-
if (runtime.lessons === lessons.trim()) return state.agentsText;
|
|
2442
|
-
const nextBlock = `${runtime.block.slice(0, runtime.lessonsBodyStart)}
|
|
2443
|
-
|
|
2444
|
-
${lessons}
|
|
2445
|
-
${runtime.block.slice(runtime.lessonsBodyEnd)}`;
|
|
2446
|
-
return `${state.agentsText.slice(0, runtime.startIndex)}${nextBlock}${state.agentsText.slice(runtime.endIndex)}`;
|
|
2447
|
-
}
|
|
2448
|
-
function projectProfilePlaybook(agentsText, expectedProfile, body) {
|
|
2449
|
-
const runtime = inspectRuntimeProjection(agentsText);
|
|
2450
|
-
if (!runtime || runtime.activeProfile !== expectedProfile) return agentsText;
|
|
2451
|
-
if (runtime.playbook === body.trim()) return agentsText;
|
|
2452
|
-
const nextBlock = `${runtime.block.slice(0, runtime.playbookBodyStart)}
|
|
2453
|
-
|
|
2454
|
-
${body.trim()}
|
|
2455
|
-
|
|
2456
|
-
${runtime.block.slice(runtime.playbookBodyEnd)}`;
|
|
2457
|
-
return `${agentsText.slice(0, runtime.startIndex)}${nextBlock}${agentsText.slice(runtime.endIndex)}`;
|
|
2458
|
-
}
|
|
2459
|
-
function workspaceChanges(paths, state) {
|
|
2460
|
-
const changes = /* @__PURE__ */ new Map([
|
|
2461
|
-
[paths.evidence, renderEvidence(state.evidence)],
|
|
2462
|
-
[paths.incidents, renderIncidents(state.incidents)],
|
|
2463
|
-
[paths.suggestions, renderSuggestions(state.suggestions)],
|
|
2464
|
-
[paths.ledger, renderLedger(state.ledger)]
|
|
2465
|
-
]);
|
|
2466
|
-
const projected = projectRuntime(state);
|
|
2467
|
-
const currentAgents = existsSync(paths.agents) ? readFileSync(paths.agents, "utf8") : "";
|
|
2468
|
-
if (projected !== currentAgents) changes.set(paths.agents, projected);
|
|
2469
|
-
return changes;
|
|
2470
|
-
}
|
|
2471
|
-
function verifyWorkspaceDocuments(paths) {
|
|
2472
|
-
const state = readWorkspaceState(paths);
|
|
2473
|
-
if (inspectRuntimeProjection(state.agentsText) && projectRuntime(state) !== state.agentsText) {
|
|
2474
|
-
throw new Error("RUNTIME_PROJECTION_MISMATCH");
|
|
2475
|
-
}
|
|
2476
|
-
}
|
|
2477
|
-
|
|
2478
|
-
// src/profile.ts
|
|
2479
|
-
import { existsSync as existsSync2, lstatSync as lstatSync3, readFileSync as readFileSync2 } from "fs";
|
|
2480
|
-
var OWNER_START = "<!-- WEREWOLF_OWNER_OVERRIDES_START -->";
|
|
2481
|
-
var OWNER_END = "<!-- WEREWOLF_OWNER_OVERRIDES_END -->";
|
|
2482
|
-
var MAX_PROFILE_CHARS = 5e3;
|
|
2483
|
-
var RESERVED = /(?:WEREWOLF_RUNTIME_(?:START|END)|^runtime_version:|^active_profile:|^### (?:GAME_EVENT execution contract|active profile playbook|active lessons)\s*$)/m;
|
|
2484
|
-
function readRegularFile(file) {
|
|
2485
|
-
if (!existsSync2(file)) return void 0;
|
|
2486
|
-
if (!lstatSync3(file).isFile() || lstatSync3(file).isSymbolicLink()) throw new Error(`PROFILE_SOURCE_INVALID:${file}`);
|
|
2487
|
-
return readFileSync2(file, "utf8");
|
|
2488
|
-
}
|
|
2489
|
-
function stripOwnerSection(body) {
|
|
2490
|
-
const starts = body.split(OWNER_START).length - 1;
|
|
2491
|
-
const ends = body.split(OWNER_END).length - 1;
|
|
2492
|
-
if (starts === 0 && ends === 0) return body.trim();
|
|
2493
|
-
if (starts !== 1 || ends !== 1) throw new Error("OWNER_OVERRIDE_MARKERS_INVALID");
|
|
2494
|
-
const start = body.indexOf(OWNER_START);
|
|
2495
|
-
const end = body.indexOf(OWNER_END);
|
|
2496
|
-
if (end <= start) throw new Error("OWNER_OVERRIDE_MARKERS_INVALID");
|
|
2497
|
-
return `${body.slice(0, start)}${body.slice(end + OWNER_END.length)}`.trim();
|
|
2498
|
-
}
|
|
2499
|
-
function parseProfileMarkdown(content, profile) {
|
|
2500
|
-
if (content.length > MAX_PROFILE_CHARS) throw new Error(`PROFILE_TOO_LARGE:${profile}`);
|
|
2501
|
-
if (RESERVED.test(content)) throw new Error(`PROFILE_RESERVED_CONTENT:${profile}`);
|
|
2502
|
-
const matches = [...content.matchAll(/^## profile:\s*`([^`]+)`([^\r\n]*)\r?$/gm)];
|
|
2503
|
-
if (matches.length !== 1 || matches[0][1] !== profile) throw new Error(`PROFILE_HEADING_INVALID:${profile}`);
|
|
2504
|
-
const heading = matches[0];
|
|
2505
|
-
const body = content.slice(heading.index + heading[0].length).trim();
|
|
2506
|
-
if (!body) throw new Error(`PROFILE_BODY_EMPTY:${profile}`);
|
|
2507
|
-
const baseBody = stripOwnerSection(body);
|
|
2508
|
-
const version = /^base_version:\s*(\S+)\s*$/m.exec(content)?.[1] ?? "unknown";
|
|
2509
|
-
const declaredHash = /^base_hash:\s*([a-f0-9]{64}|unknown)\s*$/m.exec(content)?.[1];
|
|
2510
|
-
return {
|
|
2511
|
-
profileHeading: `## profile: \`${profile}\`${heading[2] ?? ""}`,
|
|
2512
|
-
baseBody,
|
|
2513
|
-
baseVersion: version,
|
|
2514
|
-
baseHash: declaredHash && declaredHash !== "unknown" ? declaredHash : sha256(baseBody)
|
|
2515
|
-
};
|
|
2516
|
-
}
|
|
2517
|
-
function authorityFromRuntime(agentsText, profile) {
|
|
2518
|
-
const runtime = inspectRuntimeProjection(agentsText);
|
|
2519
|
-
if (!runtime || runtime.activeProfile !== profile) return void 0;
|
|
2520
|
-
const baseBody = stripOwnerSection(runtime.playbook);
|
|
2521
|
-
return {
|
|
2522
|
-
profileHeading: `## profile: \`${profile}\`\uFF08\u7528\u6237\u8986\u76D6\uFF09`,
|
|
2523
|
-
baseBody,
|
|
2524
|
-
baseVersion: "unknown",
|
|
2525
|
-
baseHash: sha256(baseBody)
|
|
2526
|
-
};
|
|
2527
|
-
}
|
|
2528
|
-
function resolveProfileAuthority(paths, profile, agentsText) {
|
|
2529
|
-
const candidates = [
|
|
2530
|
-
profileOverridePath(paths, profile),
|
|
2531
|
-
customProfilePath(paths, profile),
|
|
2532
|
-
installedProfilePath(paths, profile)
|
|
2533
|
-
];
|
|
2534
|
-
for (const file of candidates) {
|
|
2535
|
-
const content = readRegularFile(file);
|
|
2536
|
-
if (content !== void 0) return parseProfileMarkdown(content, profile);
|
|
2537
|
-
}
|
|
2538
|
-
const runtime = authorityFromRuntime(agentsText, profile);
|
|
2539
|
-
if (runtime) return runtime;
|
|
2540
|
-
throw new Error(`PROFILE_AUTHORITY_NOT_FOUND:${profile}`);
|
|
2541
|
-
}
|
|
2542
|
-
function renderOwnerSection(suggestions) {
|
|
2543
|
-
const accepted = suggestions.filter((item) => item.status === "accepted").sort((left, right) => left.id.localeCompare(right.id));
|
|
2544
|
-
if (accepted.length === 0) return "";
|
|
2545
|
-
const lines = [OWNER_START, "### Owner-confirmed strategy overrides"];
|
|
2546
|
-
for (const item of accepted) {
|
|
2547
|
-
lines.push(
|
|
2548
|
-
"",
|
|
2549
|
-
`#### ${item.id}`,
|
|
2550
|
-
`- \u89E6\u53D1\uFF1A${item.trigger}`,
|
|
2551
|
-
`- \u89C4\u5219\uFF1A${item.rule}`,
|
|
2552
|
-
`- \u8FB9\u754C\uFF1A${item.boundary}`
|
|
2553
|
-
);
|
|
2554
|
-
}
|
|
2555
|
-
lines.push(OWNER_END);
|
|
2556
|
-
return lines.join("\n");
|
|
2557
|
-
}
|
|
2558
|
-
function buildProfileOverride(paths, profile, agentsText, suggestions) {
|
|
2559
|
-
const authority = resolveProfileAuthority(paths, profile, agentsText);
|
|
2560
|
-
const accepted = suggestions.filter((item) => item.profile === profile && item.status === "accepted");
|
|
2561
|
-
const ownerSection = renderOwnerSection(accepted);
|
|
2562
|
-
const playbook = [authority.baseBody, ownerSection].filter(Boolean).join("\n\n");
|
|
2563
|
-
const acceptedIds = accepted.map((item) => item.id).sort().join(", ") || "none";
|
|
2564
|
-
const content = [
|
|
2565
|
-
"# werewolf-play profile override",
|
|
2566
|
-
`base_version: ${authority.baseVersion}`,
|
|
2567
|
-
`base_hash: ${authority.baseHash}`,
|
|
2568
|
-
`accepted_suggestions: ${acceptedIds}`,
|
|
2569
|
-
"",
|
|
2570
|
-
authority.profileHeading,
|
|
2571
|
-
"",
|
|
2572
|
-
playbook,
|
|
2573
|
-
""
|
|
2574
|
-
].join("\n");
|
|
2575
|
-
parseProfileMarkdown(content, profile);
|
|
2576
|
-
return { file: profileOverridePath(paths, profile), content, playbook };
|
|
2577
|
-
}
|
|
2578
|
-
function verifyProfileOverride(file, profile, expectedContent) {
|
|
2579
|
-
const content = readRegularFile(file);
|
|
2580
|
-
if (content === void 0) throw new Error(`PROFILE_OVERRIDE_MISSING:${profile}`);
|
|
2581
|
-
if (expectedContent !== void 0 && content !== expectedContent) {
|
|
2582
|
-
throw new Error(`PROFILE_OVERRIDE_CONTENT_MISMATCH:${profile}`);
|
|
2583
|
-
}
|
|
2584
|
-
parseProfileMarkdown(content, profile);
|
|
2585
|
-
}
|
|
2586
|
-
|
|
2587
|
-
// src/owner-binding.ts
|
|
2588
|
-
import { existsSync as existsSync3, lstatSync as lstatSync4, readFileSync as readFileSync3 } from "fs";
|
|
2589
|
-
import { z as z4 } from "zod";
|
|
2590
|
-
var OWNER = /^(clawtopia|coolclaw):human:([1-9][0-9]*)$/;
|
|
2591
|
-
var ownerBindingSchema = z4.object({
|
|
2592
|
-
schemaVersion: z4.literal(1),
|
|
2593
|
-
channelId: z4.enum(["clawtopia", "coolclaw"]),
|
|
2594
|
-
ownerSenderId: z4.string().regex(OWNER),
|
|
2595
|
-
boundAt: z4.iso.datetime({ offset: true }),
|
|
2596
|
-
updatedAt: z4.iso.datetime({ offset: true })
|
|
2597
|
-
}).strict();
|
|
2598
|
-
function normalizeOwnerSenderId(value) {
|
|
2599
|
-
const normalized = value.trim().toLowerCase();
|
|
2600
|
-
if (!OWNER.test(normalized)) {
|
|
2601
|
-
throw new Error("OWNER_ID_INVALID");
|
|
2602
|
-
}
|
|
2603
|
-
return normalized;
|
|
2604
|
-
}
|
|
2605
|
-
function verifyOwnerBinding(value) {
|
|
2606
|
-
const parsed = ownerBindingSchema.safeParse(value);
|
|
2607
|
-
if (!parsed.success) throw new Error(`WORKSPACE_OWNER_BINDING_INVALID:${parsed.error.message}`);
|
|
2608
|
-
if (!parsed.data.ownerSenderId.startsWith(`${parsed.data.channelId}:`)) {
|
|
2609
|
-
throw new Error("WORKSPACE_OWNER_CHANNEL_MISMATCH");
|
|
2610
|
-
}
|
|
2611
|
-
return parsed.data;
|
|
2612
|
-
}
|
|
2613
|
-
function readOwnerBinding(paths) {
|
|
2614
|
-
assertSafeWorkspacePath(paths.ownerBinding, paths);
|
|
2615
|
-
if (!existsSync3(paths.ownerBinding)) return void 0;
|
|
2616
|
-
const stat = lstatSync4(paths.ownerBinding);
|
|
2617
|
-
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("WORKSPACE_OWNER_BINDING_INVALID");
|
|
2618
|
-
try {
|
|
2619
|
-
return verifyOwnerBinding(JSON.parse(readFileSync3(paths.ownerBinding, "utf8")));
|
|
2620
|
-
} catch (error) {
|
|
2621
|
-
if (error instanceof SyntaxError) throw new Error(`WORKSPACE_OWNER_BINDING_INVALID:${error.message}`);
|
|
2622
|
-
throw error;
|
|
2623
|
-
}
|
|
2624
|
-
}
|
|
2625
|
-
function assertWorkspaceOwner(paths, owner) {
|
|
2626
|
-
const expected = normalizeOwnerSenderId(owner);
|
|
2627
|
-
const binding = readOwnerBinding(paths);
|
|
2628
|
-
if (!binding) throw new Error("WORKSPACE_OWNER_BINDING_MISSING");
|
|
2629
|
-
if (binding.ownerSenderId !== expected) throw new Error("WORKSPACE_OWNER_MISMATCH");
|
|
2630
|
-
return binding;
|
|
2631
|
-
}
|
|
2632
|
-
function isWorkspaceOwner(paths, channelId, senderId) {
|
|
2633
|
-
if (!senderId || channelId !== "clawtopia" && channelId !== "coolclaw") return false;
|
|
2634
|
-
try {
|
|
2635
|
-
const owner = normalizeOwnerSenderId(senderId);
|
|
2636
|
-
return owner.startsWith(`${channelId}:`) && readOwnerBinding(paths)?.ownerSenderId === owner;
|
|
2637
|
-
} catch {
|
|
2638
|
-
return false;
|
|
2639
|
-
}
|
|
2640
|
-
}
|
|
2641
|
-
|
|
2642
|
-
// src/migration.ts
|
|
2643
|
-
import {
|
|
2644
|
-
existsSync as existsSync5,
|
|
2645
|
-
lstatSync as lstatSync6,
|
|
2646
|
-
mkdirSync as mkdirSync3,
|
|
2647
|
-
readFileSync as readFileSync5,
|
|
2648
|
-
readdirSync,
|
|
2649
|
-
renameSync as renameSync2
|
|
2650
|
-
} from "fs";
|
|
2651
|
-
import path3 from "path";
|
|
2652
|
-
import { z as z6 } from "zod";
|
|
2653
|
-
|
|
2654
|
-
// src/transaction.ts
|
|
2655
|
-
import { randomUUID } from "crypto";
|
|
2656
|
-
import {
|
|
2657
|
-
closeSync,
|
|
2658
|
-
existsSync as existsSync4,
|
|
2659
|
-
fsyncSync,
|
|
2660
|
-
lstatSync as lstatSync5,
|
|
2661
|
-
mkdirSync as mkdirSync2,
|
|
2662
|
-
openSync,
|
|
2663
|
-
readFileSync as readFileSync4,
|
|
2664
|
-
renameSync,
|
|
2665
|
-
rmSync,
|
|
2666
|
-
writeSync
|
|
2667
|
-
} from "fs";
|
|
2668
|
-
import path2 from "path";
|
|
2669
|
-
import { z as z5 } from "zod";
|
|
2670
|
-
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;
|
|
2671
|
-
var HASH2 = /^[a-f0-9]{64}$/;
|
|
2672
|
-
var journalSchema = z5.object({
|
|
2673
|
-
schemaVersion: z5.literal(1),
|
|
2674
|
-
id: z5.string().regex(UUID),
|
|
2675
|
-
state: z5.enum(["prepared", "committing", "committed"]),
|
|
2676
|
-
committedCount: z5.number().int().nonnegative(),
|
|
2677
|
-
files: z5.array(z5.object({
|
|
2678
|
-
target: z5.string().min(1),
|
|
2679
|
-
temp: z5.string().min(1),
|
|
2680
|
-
backup: z5.string().min(1),
|
|
2681
|
-
beforeExists: z5.boolean(),
|
|
2682
|
-
beforeHash: z5.string().regex(HASH2).optional(),
|
|
2683
|
-
newHash: z5.string().regex(HASH2)
|
|
2684
|
-
}).strict()).min(1).max(32)
|
|
2685
|
-
}).strict();
|
|
2686
|
-
function readLock(paths) {
|
|
2687
|
-
const parsed = JSON.parse(readFileSync4(paths.lock, "utf8"));
|
|
2688
|
-
const checked = z5.object({
|
|
2689
|
-
pid: z5.number().int().positive(),
|
|
2690
|
-
token: z5.string().regex(UUID),
|
|
2691
|
-
createdAt: z5.number().int().nonnegative()
|
|
2692
|
-
}).strict().safeParse(parsed);
|
|
2693
|
-
if (!checked.success) throw new Error("EVOLUTION_WORKSPACE_LOCK_INVALID");
|
|
2694
|
-
return checked.data;
|
|
2695
|
-
}
|
|
2696
|
-
var STALE_LOCK_MIN_AGE_MS = 10 * 60 * 1e3;
|
|
2697
|
-
function assertSetupLockAccess(paths, setupLock) {
|
|
2698
|
-
if (!existsSync4(paths.setupLock)) return;
|
|
2699
|
-
const current = readLockFile(paths.setupLock, "EVOLUTION_SETUP_LOCK_INVALID");
|
|
2700
|
-
if (setupLock?.file === paths.setupLock && setupLock.token === current.token) return;
|
|
2701
|
-
throw new Error("EVOLUTION_SETUP_LOCKED");
|
|
2702
|
-
}
|
|
2703
|
-
function readLockFile(file, invalidCode) {
|
|
2704
|
-
const stat = lstatSync5(file);
|
|
2705
|
-
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(invalidCode);
|
|
2706
|
-
const parsed = JSON.parse(readFileSync4(file, "utf8"));
|
|
2707
|
-
const checked = z5.object({
|
|
2708
|
-
pid: z5.number().int().positive(),
|
|
2709
|
-
token: z5.string().regex(UUID),
|
|
2710
|
-
createdAt: z5.number().int().nonnegative()
|
|
2711
|
-
}).strict().safeParse(parsed);
|
|
2712
|
-
if (!checked.success) throw new Error(invalidCode);
|
|
2713
|
-
return checked.data;
|
|
2714
|
-
}
|
|
2715
|
-
function acquireLock(paths, setupLock) {
|
|
2716
|
-
assertSafeWorkspacePath(paths.lock, paths);
|
|
2717
|
-
assertSetupLockAccess(paths, setupLock);
|
|
2718
|
-
const token = randomUUID();
|
|
2719
|
-
try {
|
|
2720
|
-
const fd = openSync(paths.lock, "wx", 384);
|
|
2721
|
-
writeSync(fd, JSON.stringify({ pid: process.pid, token, createdAt: Date.now() }));
|
|
2722
|
-
fsyncSync(fd);
|
|
2723
|
-
return { fd, token };
|
|
2724
|
-
} catch (error) {
|
|
2725
|
-
if (error.code !== "EEXIST") throw error;
|
|
2726
|
-
readLock(paths);
|
|
2727
|
-
throw new Error("EVOLUTION_WORKSPACE_LOCKED");
|
|
2728
|
-
}
|
|
2729
|
-
}
|
|
2730
|
-
function releaseLock(paths, lock) {
|
|
2731
|
-
try {
|
|
2732
|
-
closeSync(lock.fd);
|
|
2733
|
-
} finally {
|
|
2734
|
-
try {
|
|
2735
|
-
assertSafeWorkspacePath(paths.lock, paths);
|
|
2736
|
-
if (readLock(paths).token === lock.token) rmSync(paths.lock, { force: true });
|
|
2737
|
-
} catch {
|
|
2738
|
-
}
|
|
2739
|
-
}
|
|
2740
|
-
}
|
|
2741
|
-
function syncDirectory(directory) {
|
|
2742
|
-
let fd;
|
|
2743
|
-
try {
|
|
2744
|
-
fd = openSync(directory, "r");
|
|
2745
|
-
fsyncSync(fd);
|
|
2746
|
-
} finally {
|
|
2747
|
-
if (fd !== void 0) closeSync(fd);
|
|
2748
|
-
}
|
|
2749
|
-
}
|
|
2750
|
-
function writeSynced(file, content) {
|
|
2751
|
-
mkdirSync2(path2.dirname(file), { recursive: true, mode: 448 });
|
|
2752
|
-
const fd = openSync(file, "wx", 384);
|
|
2753
|
-
try {
|
|
2754
|
-
writeSync(fd, content, void 0, "utf8");
|
|
2755
|
-
fsyncSync(fd);
|
|
2756
|
-
} finally {
|
|
2757
|
-
closeSync(fd);
|
|
2758
|
-
}
|
|
2759
|
-
}
|
|
2760
|
-
function expectedArtifacts(target, id) {
|
|
2761
|
-
const suffix = `.werewolf-evolution-${id}`;
|
|
2762
|
-
return { temp: `${target}${suffix}.tmp`, backup: `${target}${suffix}.bak` };
|
|
2763
|
-
}
|
|
2764
|
-
function validateJournal(paths, raw) {
|
|
2765
|
-
const parsed = journalSchema.safeParse(raw);
|
|
2766
|
-
if (!parsed.success) throw new Error(`TRANSACTION_JOURNAL_INVALID:${parsed.error.message}`);
|
|
2767
|
-
const journal = parsed.data;
|
|
2768
|
-
if (journal.committedCount > journal.files.length || journal.state === "prepared" && journal.committedCount !== 0 || journal.state === "committed" && journal.committedCount !== journal.files.length) {
|
|
2769
|
-
throw new Error("TRANSACTION_JOURNAL_PROGRESS_INVALID");
|
|
2770
|
-
}
|
|
2771
|
-
const targets = /* @__PURE__ */ new Set();
|
|
2772
|
-
for (const item of journal.files) {
|
|
2773
|
-
assertFixedTarget(item.target, paths);
|
|
2774
|
-
if (targets.has(item.target)) throw new Error("TRANSACTION_TARGET_DUPLICATED");
|
|
2775
|
-
targets.add(item.target);
|
|
2776
|
-
if (item.beforeExists !== Boolean(item.beforeHash)) throw new Error("TRANSACTION_BEFORE_HASH_INVALID");
|
|
2777
|
-
const expected = expectedArtifacts(item.target, journal.id);
|
|
2778
|
-
if (item.temp !== expected.temp || item.backup !== expected.backup) {
|
|
2779
|
-
throw new Error("TRANSACTION_ARTIFACT_PATH_INVALID");
|
|
2780
|
-
}
|
|
2781
|
-
assertSafeWorkspacePath(item.temp, paths);
|
|
2782
|
-
assertSafeWorkspacePath(item.backup, paths);
|
|
2783
|
-
}
|
|
2784
|
-
return journal;
|
|
2785
|
-
}
|
|
2786
|
-
function readJournal(paths) {
|
|
2787
|
-
try {
|
|
2788
|
-
return validateJournal(paths, JSON.parse(readFileSync4(paths.journal, "utf8")));
|
|
2789
|
-
} catch (error) {
|
|
2790
|
-
if (error instanceof SyntaxError) throw new Error(`TRANSACTION_JOURNAL_INVALID:${error.message}`);
|
|
2791
|
-
throw error;
|
|
2792
|
-
}
|
|
2793
|
-
}
|
|
2794
|
-
function writeJournal(paths, journal) {
|
|
2795
|
-
validateJournal(paths, journal);
|
|
2796
|
-
const swap = `${paths.journal}.${journal.id}.tmp`;
|
|
2797
|
-
assertSafeWorkspacePath(swap, paths);
|
|
2798
|
-
rmSync(swap, { force: true });
|
|
2799
|
-
writeSynced(swap, JSON.stringify(journal, null, 2));
|
|
2800
|
-
renameSync(swap, paths.journal);
|
|
2801
|
-
syncDirectory(paths.memory);
|
|
2802
|
-
}
|
|
2803
|
-
function hashFile(file) {
|
|
2804
|
-
return sha256(readFileSync4(file));
|
|
2805
|
-
}
|
|
2806
|
-
function removeArtifacts(paths, journal) {
|
|
2807
|
-
validateJournal(paths, journal);
|
|
2808
|
-
for (const item of journal.files) {
|
|
2809
|
-
rmSync(item.temp, { force: true });
|
|
2810
|
-
rmSync(item.backup, { force: true });
|
|
2811
|
-
}
|
|
2812
|
-
rmSync(paths.journal, { force: true });
|
|
2813
|
-
syncDirectory(paths.memory);
|
|
2814
|
-
}
|
|
2815
|
-
function rollback(paths, journal) {
|
|
2816
|
-
validateJournal(paths, journal);
|
|
2817
|
-
for (let index = journal.files.length - 1; index >= 0; index--) {
|
|
2818
|
-
const item = journal.files[index];
|
|
2819
|
-
if (existsSync4(item.backup)) {
|
|
2820
|
-
const backupStat = lstatSync5(item.backup);
|
|
2821
|
-
if (!item.beforeExists || !item.beforeHash || !backupStat.isFile() || backupStat.isSymbolicLink() || hashFile(item.backup) !== item.beforeHash) {
|
|
2822
|
-
throw new Error(`TRANSACTION_BACKUP_HASH_MISMATCH:${item.target}`);
|
|
2823
|
-
}
|
|
2824
|
-
rmSync(item.target, { force: true });
|
|
2825
|
-
renameSync(item.backup, item.target);
|
|
2826
|
-
} else if (!item.beforeExists) {
|
|
2827
|
-
rmSync(item.target, { force: true });
|
|
2828
|
-
} else if (!existsSync4(item.target) || hashFile(item.target) !== item.beforeHash) {
|
|
2829
|
-
throw new Error(`TRANSACTION_ROLLBACK_SOURCE_MISSING:${item.target}`);
|
|
2830
|
-
}
|
|
2831
|
-
rmSync(item.temp, { force: true });
|
|
2832
|
-
}
|
|
2833
|
-
rmSync(paths.journal, { force: true });
|
|
2834
|
-
syncDirectory(paths.memory);
|
|
2835
|
-
syncDirectory(paths.root);
|
|
2836
|
-
}
|
|
2837
|
-
function recoverTransactionLocked(paths) {
|
|
2838
|
-
if (!existsSync4(paths.journal)) return "none";
|
|
2839
|
-
const journal = readJournal(paths);
|
|
2840
|
-
const allNew = journal.files.every((item) => existsSync4(item.target) && !lstatSync5(item.target).isSymbolicLink() && hashFile(item.target) === item.newHash);
|
|
2841
|
-
if (journal.state === "committed" && allNew) {
|
|
2842
|
-
removeArtifacts(paths, journal);
|
|
2843
|
-
return "completed";
|
|
2844
|
-
}
|
|
2845
|
-
rollback(paths, journal);
|
|
2846
|
-
return "rolled-back";
|
|
2847
|
-
}
|
|
2848
|
-
function commitLocked(paths, changes, verify, hooks) {
|
|
2849
|
-
if (changes.size === 0) return;
|
|
2850
|
-
const id = randomUUID();
|
|
2851
|
-
const files = [];
|
|
2852
|
-
for (const [target, content] of changes) {
|
|
2853
|
-
assertFixedTarget(target, paths);
|
|
2854
|
-
const beforeExists = existsSync4(target);
|
|
2855
|
-
const artifacts = expectedArtifacts(target, id);
|
|
2856
|
-
rmSync(artifacts.temp, { force: true });
|
|
2857
|
-
rmSync(artifacts.backup, { force: true });
|
|
2858
|
-
writeSynced(artifacts.temp, content);
|
|
2859
|
-
files.push({
|
|
2860
|
-
target,
|
|
2861
|
-
...artifacts,
|
|
2862
|
-
beforeExists,
|
|
2863
|
-
...beforeExists ? { beforeHash: hashFile(target) } : {},
|
|
2864
|
-
newHash: sha256(content)
|
|
2865
|
-
});
|
|
2866
|
-
}
|
|
2867
|
-
const journal = {
|
|
2868
|
-
schemaVersion: 1,
|
|
2869
|
-
id,
|
|
2870
|
-
state: "prepared",
|
|
2871
|
-
committedCount: 0,
|
|
2872
|
-
files
|
|
2873
|
-
};
|
|
2874
|
-
writeJournal(paths, journal);
|
|
2875
|
-
journal.state = "committing";
|
|
2876
|
-
writeJournal(paths, journal);
|
|
2877
|
-
try {
|
|
2878
|
-
for (let index = 0; index < files.length; index++) {
|
|
2879
|
-
const item = files[index];
|
|
2880
|
-
if (item.beforeExists) renameSync(item.target, item.backup);
|
|
2881
|
-
renameSync(item.temp, item.target);
|
|
2882
|
-
syncDirectory(path2.dirname(item.target));
|
|
2883
|
-
journal.committedCount = index + 1;
|
|
2884
|
-
writeJournal(paths, journal);
|
|
2885
|
-
hooks.afterRename?.(journal.committedCount);
|
|
2886
|
-
}
|
|
2887
|
-
verify();
|
|
2888
|
-
for (const item of files) {
|
|
2889
|
-
if (!existsSync4(item.target) || lstatSync5(item.target).isSymbolicLink() || hashFile(item.target) !== item.newHash) {
|
|
2890
|
-
throw new Error(`TRANSACTION_VERIFY_FAILED:${item.target}`);
|
|
2891
|
-
}
|
|
2892
|
-
}
|
|
2893
|
-
journal.state = "committed";
|
|
2894
|
-
writeJournal(paths, journal);
|
|
2895
|
-
removeArtifacts(paths, journal);
|
|
2896
|
-
} catch (error) {
|
|
2897
|
-
rollback(paths, journal);
|
|
2898
|
-
throw error;
|
|
2899
|
-
}
|
|
2900
|
-
}
|
|
2901
|
-
function runWorkspaceTransaction(paths, build, hooks = {}, setupLock) {
|
|
2902
|
-
const lock = acquireLock(paths, setupLock);
|
|
2903
|
-
try {
|
|
2904
|
-
recoverTransactionLocked(paths);
|
|
2905
|
-
const plan = build();
|
|
2906
|
-
commitLocked(paths, plan.changes, plan.verify ?? (() => void 0), hooks);
|
|
2907
|
-
return plan.result;
|
|
2908
|
-
} finally {
|
|
2909
|
-
releaseLock(paths, lock);
|
|
2910
|
-
}
|
|
2911
|
-
}
|
|
2912
|
-
function runWorkspaceRead(paths, read) {
|
|
2913
|
-
const lock = acquireLock(paths);
|
|
2914
|
-
try {
|
|
2915
|
-
recoverTransactionLocked(paths);
|
|
2916
|
-
return read();
|
|
2917
|
-
} finally {
|
|
2918
|
-
releaseLock(paths, lock);
|
|
2919
|
-
}
|
|
2920
|
-
}
|
|
2921
|
-
|
|
2922
|
-
// src/migration.ts
|
|
2923
|
-
var MIGRATION_DATA_START = "<!-- WEREWOLF_EVOLUTION_MIGRATION_DATA_START -->";
|
|
2924
|
-
var MIGRATION_DATA_END = "<!-- WEREWOLF_EVOLUTION_MIGRATION_DATA_END -->";
|
|
2925
|
-
var SAFE_VERSION = /^[0-9]+.[0-9]+.[0-9]+(?:-[0-9A-Za-z.-]+)?$/;
|
|
2926
|
-
var SAFE_GAME_ID = /^[0-9]{1,30}$/;
|
|
2927
|
-
var MAX_LEGACY_FILE_BYTES = 2 * 1024 * 1024;
|
|
2928
|
-
var sourceSchema = z6.object({
|
|
2929
|
-
kind: z6.enum(["evidence", "suggestions"]),
|
|
2930
|
-
sourcePath: z6.string().min(1),
|
|
2931
|
-
archivePath: z6.string().min(1),
|
|
2932
|
-
sha256: z6.string().regex(/^[a-f0-9]{64}$/),
|
|
2933
|
-
bytes: z6.number().int().nonnegative().max(MAX_LEGACY_FILE_BYTES),
|
|
2934
|
-
recognized: z6.boolean()
|
|
2935
|
-
}).strict();
|
|
2936
|
-
var migrationMarkerSchema = z6.object({
|
|
2937
|
-
schemaVersion: z6.literal(1),
|
|
2938
|
-
migrationVersion: z6.literal(3),
|
|
2939
|
-
evolutionVersion: z6.string().regex(SAFE_VERSION),
|
|
2940
|
-
skillVersion: z6.string().regex(SAFE_VERSION),
|
|
2941
|
-
migratedAt: z6.string().datetime({ offset: true }),
|
|
2942
|
-
legacyGameIds: z6.array(z6.string().regex(SAFE_GAME_ID)).max(1e5),
|
|
2943
|
-
sources: z6.array(sourceSchema).max(2),
|
|
2944
|
-
skillBackup: z6.string().min(1).optional(),
|
|
2945
|
-
warnings: z6.array(z6.string().regex(/^[A-Z][A-Z0-9_]{1,79}$/)).max(16)
|
|
2946
|
-
}).strict();
|
|
2947
|
-
function markerJson(content) {
|
|
2948
|
-
const start = content.indexOf(MIGRATION_DATA_START);
|
|
2949
|
-
const end = content.indexOf(MIGRATION_DATA_END);
|
|
2950
|
-
if (start < 0 || end <= start || content.indexOf(MIGRATION_DATA_START, start + 1) >= 0 || content.indexOf(MIGRATION_DATA_END, end + 1) >= 0) {
|
|
2951
|
-
throw new Error("MIGRATION_MARKERS_INVALID");
|
|
2952
|
-
}
|
|
2953
|
-
const block = content.slice(start + MIGRATION_DATA_START.length, end).trim();
|
|
2954
|
-
const match = /^```json[ \t]*\r?\n([\s\S]*)\r?\n```$/.exec(block);
|
|
2955
|
-
if (!match) throw new Error("MIGRATION_JSON_BLOCK_INVALID");
|
|
2956
|
-
try {
|
|
2957
|
-
return JSON.parse(match[1]);
|
|
2958
|
-
} catch (error) {
|
|
2959
|
-
throw new Error(`MIGRATION_JSON_INVALID:${String(error)}`);
|
|
2960
|
-
}
|
|
2961
|
-
}
|
|
2962
|
-
function readMigrationMarker(paths) {
|
|
2963
|
-
if (!existsSync5(paths.migrationMarker)) throw new Error("MIGRATION_REQUIRED");
|
|
2964
|
-
const stat = lstatSync6(paths.migrationMarker);
|
|
2965
|
-
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_LEGACY_FILE_BYTES) {
|
|
2966
|
-
throw new Error("MIGRATION_MARKER_INVALID");
|
|
2967
|
-
}
|
|
2968
|
-
const parsed = migrationMarkerSchema.safeParse(markerJson(readFileSync5(paths.migrationMarker, "utf8")));
|
|
2969
|
-
if (!parsed.success) throw new Error(`MIGRATION_SCHEMA_INVALID:${parsed.error.message}`);
|
|
2970
|
-
return parsed.data;
|
|
2971
|
-
}
|
|
2972
|
-
function assertWorkspaceSetupReady(paths, expectedVersion) {
|
|
2973
|
-
assertWorkspaceRootIdentity(paths);
|
|
2974
|
-
if (!readOwnerBinding(paths)) throw new Error("WORKSPACE_OWNER_BINDING_MISSING");
|
|
2975
|
-
const marker = readMigrationMarker(paths);
|
|
2976
|
-
if (existsSync5(paths.legacySkill)) throw new Error("LEGACY_SKILL_STILL_DISCOVERABLE");
|
|
2977
|
-
const metaPath = path3.join(paths.skill, "_meta.json");
|
|
2978
|
-
if (!existsSync5(metaPath) || lstatSync6(metaPath).isSymbolicLink() || !lstatSync6(metaPath).isFile()) {
|
|
2979
|
-
throw new Error("WEREWOLF_PLAY_NOT_INSTALLED");
|
|
2980
|
-
}
|
|
2981
|
-
let meta;
|
|
2982
|
-
try {
|
|
2983
|
-
meta = JSON.parse(readFileSync5(metaPath, "utf8"));
|
|
2984
|
-
} catch (error) {
|
|
2985
|
-
throw new Error(`WEREWOLF_PLAY_META_INVALID:${String(error)}`);
|
|
2986
|
-
}
|
|
2987
|
-
const parsed = z6.object({ version: z6.string() }).passthrough().safeParse(meta);
|
|
2988
|
-
if (!parsed.success || parsed.data.version !== expectedVersion) throw new Error("WEREWOLF_PLAY_VERSION_MISMATCH");
|
|
2989
|
-
return marker;
|
|
2990
|
-
}
|
|
2991
|
-
|
|
2992
|
-
// src/state-machine.ts
|
|
2993
|
-
var MAX_CANDIDATE = 12;
|
|
2994
|
-
var MAX_ACTIVE = 6;
|
|
2995
|
-
function nowIso(now) {
|
|
2996
|
-
return now.toISOString();
|
|
2997
|
-
}
|
|
2998
|
-
function nextNumericId(existing, prefix) {
|
|
2999
|
-
const max = existing.reduce((value, id) => {
|
|
3000
|
-
const match = new RegExp(`^${prefix}(\\d+)$`).exec(id);
|
|
3001
|
-
return match ? Math.max(value, Number(match[1])) : value;
|
|
3002
|
-
}, 0);
|
|
3003
|
-
return `${prefix}${String(max + 1).padStart(3, "0")}`;
|
|
3004
|
-
}
|
|
3005
|
-
function sample(proposal, envelope) {
|
|
3006
|
-
return {
|
|
3007
|
-
gameId: envelope.game.gameId,
|
|
3008
|
-
debriefId: envelope.debriefId,
|
|
3009
|
-
reviewDate: envelope.game.reviewDate,
|
|
3010
|
-
source: proposal.source,
|
|
3011
|
-
decisionWindowId: proposal.decisionWindowId,
|
|
3012
|
-
anchorFactId: proposal.anchorFactId,
|
|
3013
|
-
alternativeActionType: proposal.alternativeActionType,
|
|
3014
|
-
...proposal.alternativeTargetSeat === void 0 ? {} : { alternativeTargetSeat: proposal.alternativeTargetSeat },
|
|
3015
|
-
knownFactRefs: proposal.knownFactRefs ?? [],
|
|
3016
|
-
outcomeFactRefs: proposal.outcomeFactRefs ?? [],
|
|
3017
|
-
behavior: proposal.behavior,
|
|
3018
|
-
observedLocalEffect: proposal.observedLocalEffect,
|
|
3019
|
-
alternatives: proposal.alternatives ?? []
|
|
3020
|
-
};
|
|
3021
|
-
}
|
|
3022
|
-
function independentCount(samples) {
|
|
3023
|
-
return new Set(samples.map((entry2) => entry2.gameId)).size;
|
|
3024
|
-
}
|
|
3025
|
-
function dateCount(samples) {
|
|
3026
|
-
return new Set(samples.map((entry2) => entry2.reviewDate)).size;
|
|
3027
|
-
}
|
|
3028
|
-
function sources(samples) {
|
|
3029
|
-
return new Set(samples.map((entry2) => entry2.source));
|
|
3030
|
-
}
|
|
3031
|
-
function addUnique(target, value) {
|
|
3032
|
-
if (!target.some((entry2) => entry2.gameId === value.gameId)) target.push(value);
|
|
3033
|
-
}
|
|
3034
|
-
function newLesson(id, proposal, envelope, window, risk, now, supersedesLessonId) {
|
|
3035
|
-
return {
|
|
3036
|
-
id,
|
|
3037
|
-
status: "candidate",
|
|
3038
|
-
risk,
|
|
3039
|
-
profile: proposal.profile,
|
|
3040
|
-
phase: window.phase,
|
|
3041
|
-
role: window.actorRole,
|
|
3042
|
-
players: envelope.game.players,
|
|
3043
|
-
actionType: window.actionType,
|
|
3044
|
-
decisionType: proposal.decisionType,
|
|
3045
|
-
...risk === "execution" ? { executionOperation: proposal.executionOperation } : {},
|
|
3046
|
-
trigger: proposal.trigger,
|
|
3047
|
-
rule: proposal.rule,
|
|
3048
|
-
boundary: proposal.boundary,
|
|
3049
|
-
expectedLocalEffect: proposal.expectedLocalEffect,
|
|
3050
|
-
falsifier: proposal.falsifier,
|
|
3051
|
-
supportGames: [sample(proposal, envelope)],
|
|
3052
|
-
counterGames: [],
|
|
3053
|
-
...supersedesLessonId ? { supersedesLessonId } : {},
|
|
3054
|
-
createdAt: nowIso(now),
|
|
3055
|
-
lastReviewed: envelope.game.reviewDate
|
|
3056
|
-
};
|
|
3057
|
-
}
|
|
3058
|
-
function reconcileSuggestions(state, lesson, now) {
|
|
3059
|
-
const counters = independentCount(lesson.counterGames);
|
|
3060
|
-
for (const suggestion of state.suggestions.suggestions.filter((item) => item.lessonId === lesson.id)) {
|
|
3061
|
-
suggestion.counterCount = counters;
|
|
3062
|
-
if (suggestion.status === "pending" && (counters > 0 || lesson.status === "archived")) {
|
|
3063
|
-
suggestion.status = "withdrawn";
|
|
3064
|
-
suggestion.decidedAt = nowIso(now);
|
|
3065
|
-
} else if ((suggestion.status === "accepted" || suggestion.status === "paused") && (counters >= 2 || lesson.status === "archived")) {
|
|
3066
|
-
suggestion.status = "withdrawn";
|
|
3067
|
-
suggestion.decidedAt = nowIso(now);
|
|
3068
|
-
suggestion.pauseReason = lesson.status === "archived" ? "LESSON_REFINED" : "COUNTER_EVIDENCE_THRESHOLD";
|
|
3069
|
-
} else if (suggestion.status === "accepted" && counters === 1) {
|
|
3070
|
-
suggestion.status = "paused";
|
|
3071
|
-
suggestion.pausedAt = nowIso(now);
|
|
3072
|
-
suggestion.pauseReason = "COUNTER_EVIDENCE";
|
|
3073
|
-
}
|
|
3074
|
-
}
|
|
3075
|
-
}
|
|
3076
|
-
function enforceProfileLimits(state, profile, now) {
|
|
3077
|
-
const candidates = state.evidence.lessons.filter((lesson) => lesson.profile === profile && lesson.status === "candidate");
|
|
3078
|
-
if (candidates.length > MAX_CANDIDATE) {
|
|
3079
|
-
candidates.sort((left, right) => left.lastReviewed.localeCompare(right.lastReviewed) || left.createdAt.localeCompare(right.createdAt));
|
|
3080
|
-
for (const lesson of candidates.slice(0, candidates.length - MAX_CANDIDATE)) lesson.status = "archived";
|
|
3081
|
-
}
|
|
3082
|
-
const active = state.evidence.lessons.filter((lesson) => lesson.profile === profile && lesson.status === "active");
|
|
3083
|
-
if (active.length > MAX_ACTIVE) {
|
|
3084
|
-
active.sort((left, right) => right.lastReviewed.localeCompare(left.lastReviewed));
|
|
3085
|
-
for (const lesson of active.slice(MAX_ACTIVE)) lesson.status = "archived";
|
|
3086
|
-
}
|
|
3087
|
-
const probation = state.evidence.lessons.filter((lesson) => lesson.profile === profile && lesson.status === "probation");
|
|
3088
|
-
if (probation.length > 1) {
|
|
3089
|
-
probation.sort((left, right) => right.lastReviewed.localeCompare(left.lastReviewed));
|
|
3090
|
-
for (const lesson of probation.slice(1)) lesson.status = "archived";
|
|
3091
|
-
}
|
|
3092
|
-
for (const lesson of state.evidence.lessons.filter((item) => item.profile === profile)) {
|
|
3093
|
-
reconcileSuggestions(state, lesson, now);
|
|
3094
|
-
}
|
|
3095
|
-
}
|
|
3096
|
-
function ensureSuggestion(state, lesson, now) {
|
|
3097
|
-
if (lesson.status !== "candidate") return;
|
|
3098
|
-
if (state.suggestions.suggestions.some((item) => item.lessonId === lesson.id)) return;
|
|
3099
|
-
const sourceSet = sources(lesson.supportGames);
|
|
3100
|
-
if (independentCount(lesson.supportGames) < 5 || dateCount(lesson.supportGames) < 2 || independentCount(lesson.counterGames) > 0 || !sourceSet.has("SELF") || !(sourceSet.has("OBSERVED") || sourceSet.has("EXEMPLAR"))) return;
|
|
3101
|
-
const id = nextNumericId(state.suggestions.suggestions.map((item) => item.id), "S-");
|
|
3102
|
-
state.suggestions.suggestions.push({
|
|
3103
|
-
id,
|
|
3104
|
-
lessonId: lesson.id,
|
|
3105
|
-
profile: lesson.profile,
|
|
3106
|
-
status: "pending",
|
|
3107
|
-
trigger: lesson.trigger,
|
|
3108
|
-
rule: lesson.rule,
|
|
3109
|
-
boundary: lesson.boundary,
|
|
3110
|
-
supportCount: independentCount(lesson.supportGames),
|
|
3111
|
-
counterCount: independentCount(lesson.counterGames),
|
|
3112
|
-
createdAt: nowIso(now)
|
|
3113
|
-
});
|
|
3114
|
-
}
|
|
3115
|
-
function transitionExecution(state, lesson) {
|
|
3116
|
-
const supports = independentCount(lesson.supportGames);
|
|
3117
|
-
const counters = independentCount(lesson.counterGames);
|
|
3118
|
-
if (lesson.status === "candidate") {
|
|
3119
|
-
if (counters > 0) {
|
|
3120
|
-
lesson.status = "contested";
|
|
3121
|
-
} else if (supports >= 3 && dateCount(lesson.supportGames) >= 2) {
|
|
3122
|
-
const existingProbation = state.evidence.lessons.some((item) => item.profile === lesson.profile && item.status === "probation" && item.id !== lesson.id);
|
|
3123
|
-
if (!existingProbation) {
|
|
3124
|
-
lesson.status = "probation";
|
|
3125
|
-
lesson.probationStartedAtSupportCount = supports;
|
|
3126
|
-
}
|
|
3127
|
-
}
|
|
3128
|
-
} else if (lesson.status === "probation") {
|
|
3129
|
-
if (counters >= 1) lesson.status = "contested";
|
|
3130
|
-
else if (supports - (lesson.probationStartedAtSupportCount ?? supports) >= 2) lesson.status = "active";
|
|
3131
|
-
} else if (lesson.status === "active" && counters >= 2) {
|
|
3132
|
-
lesson.status = "contested";
|
|
3133
|
-
}
|
|
3134
|
-
}
|
|
3135
|
-
function applyProposal(state, envelope, bodyHash, proposal, risk, window, now = /* @__PURE__ */ new Date()) {
|
|
3136
|
-
if (state.ledger.entries.some((entry2) => entry2.debriefId === envelope.debriefId)) return { outcome: "duplicate" };
|
|
3137
|
-
if (state.ledger.entries.some((entry2) => entry2.gameId === envelope.game.gameId)) return { outcome: "duplicate-game" };
|
|
3138
|
-
let result = { outcome: "skipped" };
|
|
3139
|
-
if (proposal.action !== "SKIP") {
|
|
3140
|
-
let lesson;
|
|
3141
|
-
if (proposal.action === "NEW") {
|
|
3142
|
-
const id = nextNumericId(
|
|
3143
|
-
state.evidence.lessons.filter((item) => item.profile === proposal.profile).map((item) => item.id),
|
|
3144
|
-
`L-${proposal.profile}-`
|
|
3145
|
-
);
|
|
3146
|
-
lesson = newLesson(id, proposal, envelope, window, risk, now);
|
|
3147
|
-
state.evidence.lessons.push(lesson);
|
|
3148
|
-
} else if (proposal.action === "REFINE") {
|
|
3149
|
-
const prior = state.evidence.lessons.find((item) => item.id === proposal.topicId);
|
|
3150
|
-
const id = nextNumericId(
|
|
3151
|
-
state.evidence.lessons.filter((item) => item.profile === proposal.profile).map((item) => item.id),
|
|
3152
|
-
`L-${proposal.profile}-`
|
|
3153
|
-
);
|
|
3154
|
-
prior.status = "archived";
|
|
3155
|
-
prior.supersededByLessonId = id;
|
|
3156
|
-
prior.lastReviewed = envelope.game.reviewDate;
|
|
3157
|
-
reconcileSuggestions(state, prior, now);
|
|
3158
|
-
lesson = newLesson(id, proposal, envelope, window, risk, now, prior.id);
|
|
3159
|
-
state.evidence.lessons.push(lesson);
|
|
3160
|
-
result.archivedLessonId = prior.id;
|
|
3161
|
-
} else {
|
|
3162
|
-
lesson = state.evidence.lessons.find((item) => item.id === proposal.topicId);
|
|
3163
|
-
const evidence = sample(proposal, envelope);
|
|
3164
|
-
if (proposal.action === "COUNTER") addUnique(lesson.counterGames, evidence);
|
|
3165
|
-
else addUnique(lesson.supportGames, evidence);
|
|
3166
|
-
lesson.lastReviewed = envelope.game.reviewDate;
|
|
3167
|
-
}
|
|
3168
|
-
if (lesson.risk === "execution") transitionExecution(state, lesson);
|
|
3169
|
-
else {
|
|
3170
|
-
if (independentCount(lesson.counterGames) > 0 && lesson.status === "candidate") lesson.status = "contested";
|
|
3171
|
-
ensureSuggestion(state, lesson, now);
|
|
3172
|
-
}
|
|
3173
|
-
reconcileSuggestions(state, lesson, now);
|
|
3174
|
-
enforceProfileLimits(state, lesson.profile, now);
|
|
3175
|
-
result = { ...result, outcome: lesson.status, lessonId: lesson.id, risk: lesson.risk };
|
|
3176
|
-
}
|
|
3177
|
-
state.ledger.entries.push({
|
|
3178
|
-
debriefId: envelope.debriefId,
|
|
3179
|
-
gameId: envelope.game.gameId,
|
|
3180
|
-
bodyHash,
|
|
3181
|
-
action: proposal.action,
|
|
3182
|
-
outcome: result.outcome,
|
|
3183
|
-
processedAt: nowIso(now)
|
|
3184
|
-
});
|
|
3185
|
-
return result;
|
|
3186
|
-
}
|
|
3187
|
-
function applyIncident(state, envelope, bodyHash, reasons, now = /* @__PURE__ */ new Date()) {
|
|
3188
|
-
if (state.ledger.entries.some((entry2) => entry2.debriefId === envelope.debriefId || entry2.gameId === envelope.game.gameId)) return { outcome: "duplicate" };
|
|
3189
|
-
state.incidents.incidents.push({
|
|
3190
|
-
debriefId: envelope.debriefId,
|
|
3191
|
-
gameId: envelope.game.gameId,
|
|
3192
|
-
reviewDate: envelope.game.reviewDate,
|
|
3193
|
-
reasons,
|
|
3194
|
-
recordedAt: nowIso(now)
|
|
3195
|
-
});
|
|
3196
|
-
state.ledger.entries.push({
|
|
3197
|
-
debriefId: envelope.debriefId,
|
|
3198
|
-
gameId: envelope.game.gameId,
|
|
3199
|
-
bodyHash,
|
|
3200
|
-
action: "INCIDENT",
|
|
3201
|
-
outcome: "incident-skipped",
|
|
3202
|
-
processedAt: nowIso(now)
|
|
3203
|
-
});
|
|
3204
|
-
return { outcome: "incident-skipped" };
|
|
3205
|
-
}
|
|
3206
|
-
function incidentReasons(envelope) {
|
|
3207
|
-
const reasons = [];
|
|
3208
|
-
if (!envelope.game.normalEnd) reasons.push("ABNORMAL_END");
|
|
3209
|
-
if (envelope.game.systemHealthGate !== "PASS") reasons.push("SYSTEM_HEALTH_SKIP_REQUIRED");
|
|
3210
|
-
if (!envelope.game.timelineComplete) reasons.push("TIMELINE_INCOMPLETE");
|
|
3211
|
-
if (envelope.game.voteConsistency === "INCONSISTENT") reasons.push("VOTE_RESULT_INCONSISTENT");
|
|
3212
|
-
if (isUnknownEligibilityValue(envelope.game.role)) reasons.push("IDENTITY_UNKNOWN");
|
|
3213
|
-
if (isUnknownEligibilityValue(envelope.game.team)) reasons.push("TEAM_UNKNOWN");
|
|
3214
|
-
if (isUnknownEligibilityValue(envelope.game.finalState)) reasons.push("FINAL_STATE_UNKNOWN");
|
|
3215
|
-
if (isUnknownEligibilityValue(envelope.game.result)) reasons.push("RESULT_UNKNOWN");
|
|
3216
|
-
return reasons;
|
|
3217
|
-
}
|
|
3218
|
-
|
|
3219
|
-
// src/version.ts
|
|
3220
|
-
import { readFileSync as readFileSync6 } from "fs";
|
|
3221
|
-
import { fileURLToPath } from "url";
|
|
3222
|
-
import { z as z7 } from "zod";
|
|
3223
|
-
var cachedVersion;
|
|
3224
|
-
function getWerewolfEvolutionVersion() {
|
|
3225
|
-
if (cachedVersion) return cachedVersion;
|
|
3226
|
-
const packagePath = fileURLToPath(new URL("../package.json", import.meta.url));
|
|
3227
|
-
const parsed = z7.object({
|
|
3228
|
-
name: z7.literal("@clawtopia/werewolf-evolution"),
|
|
3229
|
-
version: z7.string().regex(/^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/)
|
|
3230
|
-
}).passthrough().parse(JSON.parse(readFileSync6(packagePath, "utf8")));
|
|
3231
|
-
cachedVersion = parsed.version;
|
|
3232
|
-
return cachedVersion;
|
|
3233
|
-
}
|
|
3234
|
-
|
|
3235
|
-
// src/service.ts
|
|
3236
|
-
var DIRECT_MESSAGE_TTL_MS = 10 * 60 * 1e3;
|
|
3237
|
-
var MAX_DIRECT_MESSAGES = 256;
|
|
3238
|
-
var SYSTEM_DEBRIEF_DELIVERY_GRACE_MS = 30 * 1e3;
|
|
3239
|
-
function clone(value) {
|
|
3240
|
-
return structuredClone(value);
|
|
3241
|
-
}
|
|
3242
|
-
function requireToolWorkspace(ctx, bound) {
|
|
3243
|
-
if (!ctx.workspaceDir || !ctx.agentId || !ctx.sessionKey) throw new Error("TOOL_CONTEXT_INCOMPLETE");
|
|
3244
|
-
if (ctx.workspaceDir !== bound.workspaceDir || ctx.agentId !== bound.agentId || ctx.sessionKey !== bound.sessionKey) {
|
|
3245
|
-
throw new Error("BOUND_CONTEXT_MISMATCH");
|
|
3246
|
-
}
|
|
3247
|
-
if (ctx.messageChannel !== bound.inbound.channelId || (ctx.deliveryContext?.accountId?.trim() || "default") !== bound.inbound.accountId) {
|
|
3248
|
-
throw new Error("BOUND_DELIVERY_MISMATCH");
|
|
3249
|
-
}
|
|
3250
|
-
return ctx.workspaceDir;
|
|
3251
|
-
}
|
|
3252
|
-
function normalizedSender2(value) {
|
|
3253
|
-
return value.replace(/^(?:clawtopia|coolclaw):/, "").replace(/^human:/, "");
|
|
3254
|
-
}
|
|
3255
|
-
function assertOwnerDirectContext(ctx, bound, command, input) {
|
|
3256
|
-
if (!bound.senderIsOwner || !bound.senderId || !ctx.requesterSenderId) throw new Error("OWNER_REQUIRED");
|
|
3257
|
-
if (!ctx.messageChannel || ctx.messageChannel !== command.channelId) throw new Error("CHANNEL_MISMATCH");
|
|
3258
|
-
const to = ctx.deliveryContext?.to;
|
|
3259
|
-
if (!to || !to.startsWith(`${command.channelId}:human:`) || normalizedSender2(to) === "0") {
|
|
3260
|
-
throw new Error("DIRECT_MESSAGE_REQUIRED");
|
|
3261
|
-
}
|
|
3262
|
-
const expected = normalizedSender2(command.from);
|
|
3263
|
-
if (normalizedSender2(bound.senderId) !== expected || normalizedSender2(ctx.requesterSenderId) !== expected || normalizedSender2(to) !== expected) {
|
|
3264
|
-
throw new Error("OWNER_SENDER_MISMATCH");
|
|
3265
|
-
}
|
|
3266
|
-
if (command.suggestionId !== input.suggestionId || command.decision !== input.decision) {
|
|
3267
|
-
throw new Error("OWNER_COMMAND_MISMATCH");
|
|
3268
|
-
}
|
|
3269
|
-
}
|
|
3270
|
-
function relevantTopics(state, profile) {
|
|
3271
|
-
return state.evidence.lessons.filter((lesson) => lesson.profile === profile && lesson.status !== "archived").sort((left, right) => right.lastReviewed.localeCompare(left.lastReviewed)).slice(0, 24).map((lesson) => ({
|
|
3272
|
-
id: lesson.id,
|
|
3273
|
-
status: lesson.status,
|
|
3274
|
-
risk: lesson.risk,
|
|
3275
|
-
profile: lesson.profile,
|
|
3276
|
-
phase: lesson.phase,
|
|
3277
|
-
role: lesson.role,
|
|
3278
|
-
players: lesson.players,
|
|
3279
|
-
actionType: lesson.actionType,
|
|
3280
|
-
decisionType: lesson.decisionType,
|
|
3281
|
-
executionOperation: lesson.executionOperation,
|
|
3282
|
-
trigger: lesson.trigger,
|
|
3283
|
-
rule: lesson.rule,
|
|
3284
|
-
boundary: lesson.boundary,
|
|
3285
|
-
expectedLocalEffect: lesson.expectedLocalEffect,
|
|
3286
|
-
falsifier: lesson.falsifier,
|
|
3287
|
-
supportCount: lesson.supportGames.length,
|
|
3288
|
-
counterCount: lesson.counterGames.length
|
|
3289
|
-
}));
|
|
3290
|
-
}
|
|
3291
|
-
function activeRuntimeProfile(state, envelopeProfile) {
|
|
3292
|
-
const runtime = inspectRuntimeProjection(state.agentsText);
|
|
3293
|
-
if (!runtime) throw new Error("PROFILE_UNKNOWN");
|
|
3294
|
-
if (envelopeProfile !== void 0 && envelopeProfile !== runtime.activeProfile) {
|
|
3295
|
-
throw new Error("ENVELOPE_PROFILE_MISMATCH");
|
|
3296
|
-
}
|
|
3297
|
-
return runtime.activeProfile;
|
|
3298
|
-
}
|
|
3299
|
-
function changedAcceptedProfiles(current, next) {
|
|
3300
|
-
const acceptedByProfile = (items) => {
|
|
3301
|
-
const map = /* @__PURE__ */ new Map();
|
|
3302
|
-
for (const profile of new Set(items.map((item) => item.profile))) {
|
|
3303
|
-
map.set(profile, items.filter((item) => item.profile === profile && item.status === "accepted").map((item) => item.id).sort().join(","));
|
|
3304
|
-
}
|
|
3305
|
-
return map;
|
|
3306
|
-
};
|
|
3307
|
-
const before = acceptedByProfile(current);
|
|
3308
|
-
const after = acceptedByProfile(next);
|
|
3309
|
-
return [.../* @__PURE__ */ new Set([...before.keys(), ...after.keys()])].filter((profile) => before.get(profile) !== after.get(profile));
|
|
3310
|
-
}
|
|
3311
|
-
function addProfileUpdates(paths, current, next, changes) {
|
|
3312
|
-
const profiles = changedAcceptedProfiles(current.suggestions.suggestions, next.suggestions.suggestions);
|
|
3313
|
-
const expected = /* @__PURE__ */ new Map();
|
|
3314
|
-
for (const profile of profiles) {
|
|
3315
|
-
const update = buildProfileOverride(paths, profile, current.agentsText, next.suggestions.suggestions);
|
|
3316
|
-
changes.set(update.file, update.content);
|
|
3317
|
-
next.agentsText = projectProfilePlaybook(next.agentsText, profile, update.playbook);
|
|
3318
|
-
expected.set(profile, { file: update.file, content: update.content });
|
|
3319
|
-
}
|
|
3320
|
-
return expected;
|
|
3321
|
-
}
|
|
3322
|
-
function claimPendingSuggestionReminder(paths, expectedVersion) {
|
|
3323
|
-
return runWorkspaceTransaction(paths, () => {
|
|
3324
|
-
assertWorkspaceSetupReady(paths, expectedVersion);
|
|
3325
|
-
const current = readWorkspaceState(paths);
|
|
3326
|
-
const pending = current.suggestions.suggestions.filter((item) => item.status === "pending" && !item.reminderSentAt).sort((left, right) => left.id.localeCompare(right.id))[0];
|
|
3327
|
-
if (!pending) return { changes: /* @__PURE__ */ new Map(), result: void 0 };
|
|
3328
|
-
const next = clone(current);
|
|
3329
|
-
const selected = next.suggestions.suggestions.find((item) => item.id === pending.id);
|
|
3330
|
-
selected.reminderSentAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3331
|
-
return {
|
|
3332
|
-
changes: /* @__PURE__ */ new Map([[paths.suggestions, renderSuggestions(next.suggestions)]]),
|
|
3333
|
-
result: selected,
|
|
3334
|
-
verify: () => verifyWorkspaceDocuments(paths)
|
|
3335
|
-
};
|
|
3336
|
-
});
|
|
3337
|
-
}
|
|
3338
|
-
var WerewolfEvolutionService = class {
|
|
3339
|
-
contexts = new EvolutionContextStore();
|
|
3340
|
-
version;
|
|
3341
|
-
ordinaryDirectMessages = /* @__PURE__ */ new Map();
|
|
3342
|
-
ordinaryDirectMessagesBySession = /* @__PURE__ */ new Map();
|
|
3343
|
-
ownerDirectRuns = /* @__PURE__ */ new Map();
|
|
3344
|
-
observedRuns = /* @__PURE__ */ new Map();
|
|
3345
|
-
systemDebriefSessions = /* @__PURE__ */ new Map();
|
|
3346
|
-
constructor(version = getWerewolfEvolutionVersion()) {
|
|
3347
|
-
this.version = version;
|
|
3348
|
-
}
|
|
3349
|
-
cleanupOrdinaryDirectMessages(now) {
|
|
3350
|
-
for (const [runId, inbound] of this.ordinaryDirectMessages) {
|
|
3351
|
-
if (now - inbound.capturedAt > DIRECT_MESSAGE_TTL_MS) this.ordinaryDirectMessages.delete(runId);
|
|
3352
|
-
}
|
|
3353
|
-
for (const [sessionKey, inbounds] of this.ordinaryDirectMessagesBySession) {
|
|
3354
|
-
const current = inbounds.filter((inbound) => now - inbound.capturedAt <= DIRECT_MESSAGE_TTL_MS);
|
|
3355
|
-
if (current.length === 0) this.ordinaryDirectMessagesBySession.delete(sessionKey);
|
|
3356
|
-
else if (current.length !== inbounds.length) this.ordinaryDirectMessagesBySession.set(sessionKey, current);
|
|
3357
|
-
}
|
|
3358
|
-
while (this.ordinaryDirectMessages.size > MAX_DIRECT_MESSAGES) {
|
|
3359
|
-
this.ordinaryDirectMessages.delete(this.ordinaryDirectMessages.keys().next().value);
|
|
3360
|
-
}
|
|
3361
|
-
while ([...this.ordinaryDirectMessagesBySession.values()].reduce((total, inbounds) => total + inbounds.length, 0) > MAX_DIRECT_MESSAGES) {
|
|
3362
|
-
const firstKey = this.ordinaryDirectMessagesBySession.keys().next().value;
|
|
3363
|
-
if (!firstKey) break;
|
|
3364
|
-
const inbounds = this.ordinaryDirectMessagesBySession.get(firstKey);
|
|
3365
|
-
inbounds.shift();
|
|
3366
|
-
if (inbounds.length === 0) this.ordinaryDirectMessagesBySession.delete(firstKey);
|
|
3367
|
-
}
|
|
3368
|
-
}
|
|
3369
|
-
cleanupSystemDebriefSessions(now) {
|
|
3370
|
-
for (const [sessionKey, session] of this.systemDebriefSessions) {
|
|
3371
|
-
if (session.expiresAt < now) this.systemDebriefSessions.delete(sessionKey);
|
|
3372
|
-
}
|
|
3373
|
-
while (this.systemDebriefSessions.size > MAX_DIRECT_MESSAGES) {
|
|
3374
|
-
this.systemDebriefSessions.delete(this.systemDebriefSessions.keys().next().value);
|
|
3375
|
-
}
|
|
3376
|
-
}
|
|
3377
|
-
matchesSystemDebriefTarget(session, event, ctx) {
|
|
3378
|
-
const expected = session.target.trim().toLowerCase();
|
|
3379
|
-
const values = [event.to, ctx.conversationId].filter((value) => typeof value === "string" && value.trim().length > 0).map((value) => value.trim().toLowerCase());
|
|
3380
|
-
if (values.includes(expected)) return true;
|
|
3381
|
-
const targetMatch = /^(?:clawtopia|coolclaw):human:(\d+)$/.exec(expected);
|
|
3382
|
-
if (!targetMatch) return false;
|
|
3383
|
-
return values.some((value) => value === `private:human:${targetMatch[1]}` || value === `human:${targetMatch[1]}`);
|
|
3384
|
-
}
|
|
3385
|
-
captureMessage(event, ctx) {
|
|
3386
|
-
const now = Date.now();
|
|
3387
|
-
this.cleanupOrdinaryDirectMessages(now);
|
|
3388
|
-
this.cleanupSystemDebriefSessions(now);
|
|
3389
|
-
const captured = this.contexts.capture(event, ctx);
|
|
3390
|
-
const sessionKey = event.sessionKey ?? ctx.sessionKey;
|
|
3391
|
-
if (captured?.kind === "debrief" && sessionKey) {
|
|
3392
|
-
this.systemDebriefSessions.set(sessionKey, {
|
|
3393
|
-
channelId: captured.channelId,
|
|
3394
|
-
accountId: captured.accountId,
|
|
3395
|
-
expiresAt: now + DIRECT_MESSAGE_TTL_MS,
|
|
3396
|
-
sessionKey,
|
|
3397
|
-
target: captured.from
|
|
3398
|
-
});
|
|
3399
|
-
}
|
|
3400
|
-
const runId = event.runId ?? ctx.runId;
|
|
3401
|
-
if (!captured && sessionKey && isHumanDirectMessage(event, ctx)) {
|
|
3402
|
-
const direct = {
|
|
3403
|
-
channelId: ctx.channelId,
|
|
3404
|
-
accountId: normalizedAccountId(ctx.accountId),
|
|
3405
|
-
from: event.from,
|
|
3406
|
-
sessionKey,
|
|
3407
|
-
content: event.content,
|
|
3408
|
-
capturedAt: now
|
|
3409
|
-
};
|
|
3410
|
-
if (runId) {
|
|
3411
|
-
this.ordinaryDirectMessages.set(runId, direct);
|
|
3412
|
-
} else {
|
|
3413
|
-
const pending = this.ordinaryDirectMessagesBySession.get(sessionKey) ?? [];
|
|
3414
|
-
pending.push(direct);
|
|
3415
|
-
this.ordinaryDirectMessagesBySession.set(sessionKey, pending);
|
|
3416
|
-
}
|
|
3417
|
-
this.cleanupOrdinaryDirectMessages(now);
|
|
3418
|
-
}
|
|
3419
|
-
return captured;
|
|
3420
|
-
}
|
|
3421
|
-
captureInboundClaim(event, ctx = {}) {
|
|
3422
|
-
if (event.isGroup === true) return void 0;
|
|
3423
|
-
const channelId = event.channel || ctx.channelId || "";
|
|
3424
|
-
const senderId = event.senderId ?? ctx.senderId;
|
|
3425
|
-
const conversationId = event.conversationId ?? ctx.conversationId;
|
|
3426
|
-
if (!isTrustedDebriefClaimOrigin(channelId, senderId, conversationId)) return void 0;
|
|
3427
|
-
const trustedSenderId = senderId ?? `${channelId}:human:0`;
|
|
3428
|
-
return this.captureMessage(
|
|
3429
|
-
{
|
|
3430
|
-
from: trustedSenderId,
|
|
3431
|
-
content: event.content,
|
|
3432
|
-
messageId: event.messageId ?? ctx.messageId,
|
|
3433
|
-
sessionKey: event.sessionKey ?? ctx.sessionKey,
|
|
3434
|
-
runId: event.runId ?? ctx.runId
|
|
3435
|
-
},
|
|
3436
|
-
{
|
|
3437
|
-
channelId,
|
|
3438
|
-
accountId: event.accountId ?? ctx.accountId,
|
|
3439
|
-
sessionKey: event.sessionKey ?? ctx.sessionKey,
|
|
3440
|
-
runId: event.runId ?? ctx.runId,
|
|
3441
|
-
conversationId
|
|
3442
|
-
}
|
|
3443
|
-
);
|
|
3444
|
-
}
|
|
3445
|
-
isSystemDebriefMessage(event, ctx) {
|
|
3446
|
-
const now = Date.now();
|
|
3447
|
-
this.cleanupSystemDebriefSessions(now);
|
|
3448
|
-
const sessionKey = ctx.sessionKey;
|
|
3449
|
-
return [...this.systemDebriefSessions.values()].some((session) => (!sessionKey || session.sessionKey === sessionKey) && session.channelId === ctx.channelId && session.accountId === normalizedAccountId(ctx.accountId) && session.expiresAt >= now && this.matchesSystemDebriefTarget(session, event, ctx));
|
|
3450
|
-
}
|
|
3451
|
-
pendingOrdinaryDirectMessage(runId, sessionKey, prompt, now) {
|
|
3452
|
-
if (!runId || !sessionKey) return void 0;
|
|
3453
|
-
const byRun = this.ordinaryDirectMessages.get(runId);
|
|
3454
|
-
if (byRun) return byRun.sessionKey === sessionKey ? byRun : void 0;
|
|
3455
|
-
return this.ordinaryDirectMessagesBySession.get(sessionKey)?.find((candidate) => now - candidate.capturedAt <= DIRECT_MESSAGE_TTL_MS && prompt.includes(candidate.content));
|
|
3456
|
-
}
|
|
3457
|
-
consumeOrdinaryDirectMessage(runId, direct) {
|
|
3458
|
-
if (this.ordinaryDirectMessages.get(runId) === direct) {
|
|
3459
|
-
this.ordinaryDirectMessages.delete(runId);
|
|
3460
|
-
return;
|
|
3461
|
-
}
|
|
3462
|
-
const pending = this.ordinaryDirectMessagesBySession.get(direct.sessionKey);
|
|
3463
|
-
const index = pending?.indexOf(direct) ?? -1;
|
|
3464
|
-
if (index < 0) return;
|
|
3465
|
-
pending.splice(index, 1);
|
|
3466
|
-
if (pending.length === 0) this.ordinaryDirectMessagesBySession.delete(direct.sessionKey);
|
|
3467
|
-
}
|
|
3468
|
-
bindAgentRun(event, ctx, binding, explicitOwnerAuthorized = false, pendingInbound, pendingOrdinary) {
|
|
3469
|
-
const now = Date.now();
|
|
3470
|
-
this.cleanupOrdinaryDirectMessages(now);
|
|
3471
|
-
for (const [runId, observed] of this.observedRuns) {
|
|
3472
|
-
if (observed.expiresAt < now) this.observedRuns.delete(runId);
|
|
3473
|
-
}
|
|
3474
|
-
for (const [runId, direct] of this.ownerDirectRuns) {
|
|
3475
|
-
if (direct.expiresAt < now) this.ownerDirectRuns.delete(runId);
|
|
3476
|
-
}
|
|
3477
|
-
if (ctx.runId && ctx.sessionKey && ctx.agentId && ctx.workspaceDir) {
|
|
3478
|
-
this.observedRuns.set(ctx.runId, {
|
|
3479
|
-
sessionKey: ctx.sessionKey,
|
|
3480
|
-
agentId: ctx.agentId,
|
|
3481
|
-
workspaceDir: ctx.workspaceDir,
|
|
3482
|
-
expiresAt: now + 10 * 60 * 1e3
|
|
3483
|
-
});
|
|
3484
|
-
}
|
|
3485
|
-
const bound = this.contexts.bindAgentRun(
|
|
3486
|
-
event,
|
|
3487
|
-
ctx,
|
|
3488
|
-
binding,
|
|
3489
|
-
Date.now(),
|
|
3490
|
-
explicitOwnerAuthorized,
|
|
3491
|
-
pendingInbound
|
|
3492
|
-
);
|
|
3493
|
-
const ordinary = (ctx.runId ? this.ordinaryDirectMessages.get(ctx.runId) : void 0) ?? pendingOrdinary;
|
|
3494
|
-
if (!bound && ordinary && ctx.runId && ctx.sessionKey && ctx.agentId && ctx.workspaceDir && ordinary.sessionKey === ctx.sessionKey && ordinary.channelId === event.channelId && ordinary.accountId === normalizedAccountId(event.accountId) && explicitOwnerAuthorized && event.senderIsOwner === true && event.senderId && sameHumanSender(event.senderId, ordinary.from)) {
|
|
3495
|
-
this.ownerDirectRuns.set(ctx.runId, {
|
|
3496
|
-
sessionKey: ctx.sessionKey,
|
|
3497
|
-
agentId: ctx.agentId,
|
|
3498
|
-
workspaceDir: ctx.workspaceDir,
|
|
3499
|
-
senderId: event.senderId,
|
|
3500
|
-
expiresAt: now + DIRECT_MESSAGE_TTL_MS
|
|
3501
|
-
});
|
|
3502
|
-
this.consumeOrdinaryDirectMessage(ctx.runId, ordinary);
|
|
3503
|
-
}
|
|
3504
|
-
return bound;
|
|
3505
|
-
}
|
|
3506
|
-
bindPromptRun(event, ctx, config) {
|
|
3507
|
-
const pending = this.contexts.getPending(ctx.runId, ctx.sessionKey, event.prompt);
|
|
3508
|
-
const ordinary = this.pendingOrdinaryDirectMessage(ctx.runId, ctx.sessionKey, event.prompt, Date.now());
|
|
3509
|
-
const inbound = pending ?? ordinary;
|
|
3510
|
-
const channelId = inbound?.channelId;
|
|
3511
|
-
const accountId = inbound?.accountId;
|
|
3512
|
-
const senderId = inbound?.from;
|
|
3513
|
-
const globallyAuthorized = isExplicitConfiguredOwner(config, channelId, senderId);
|
|
3514
|
-
let workspaceAuthorized = false;
|
|
3515
|
-
if (globallyAuthorized && ctx.workspaceDir && channelId && senderId) {
|
|
3516
|
-
try {
|
|
3517
|
-
workspaceAuthorized = isWorkspaceOwner(
|
|
3518
|
-
resolveWorkspacePaths(ctx.workspaceDir, false),
|
|
3519
|
-
channelId,
|
|
3520
|
-
senderId
|
|
3521
|
-
);
|
|
3522
|
-
} catch {
|
|
3523
|
-
workspaceAuthorized = false;
|
|
3524
|
-
}
|
|
3525
|
-
}
|
|
3526
|
-
const bound = this.bindAgentRun(
|
|
3527
|
-
{
|
|
3528
|
-
channelId,
|
|
3529
|
-
accountId,
|
|
3530
|
-
senderId,
|
|
3531
|
-
senderIsOwner: workspaceAuthorized
|
|
3532
|
-
},
|
|
3533
|
-
ctx,
|
|
3534
|
-
resolveAgentAccountBinding(config, channelId, accountId),
|
|
3535
|
-
workspaceAuthorized,
|
|
3536
|
-
pending,
|
|
3537
|
-
ordinary
|
|
3538
|
-
);
|
|
3539
|
-
return bound ?? this.contexts.getBound(ctx.runId, ctx.sessionKey);
|
|
3540
|
-
}
|
|
3541
|
-
recordTerminalDiagnostic(runId, sessionKey, terminal) {
|
|
3542
|
-
const bound = this.contexts.getBound(runId, sessionKey);
|
|
3543
|
-
if (!bound || bound.inbound.kind !== "debrief") return void 0;
|
|
3544
|
-
bound.terminalDiagnostic ??= terminal;
|
|
3545
|
-
return bound;
|
|
3546
|
-
}
|
|
3547
|
-
finishRun(ctx) {
|
|
3548
|
-
if (!ctx.runId) return void 0;
|
|
3549
|
-
const bound = this.contexts.releaseRun(ctx.runId, ctx.sessionKey);
|
|
3550
|
-
this.observedRuns.delete(ctx.runId);
|
|
3551
|
-
this.ownerDirectRuns.delete(ctx.runId);
|
|
3552
|
-
const systemDebrief = ctx.sessionKey ? this.systemDebriefSessions.get(ctx.sessionKey) : void 0;
|
|
3553
|
-
if (systemDebrief) {
|
|
3554
|
-
systemDebrief.expiresAt = Math.min(
|
|
3555
|
-
systemDebrief.expiresAt,
|
|
3556
|
-
Date.now() + SYSTEM_DEBRIEF_DELIVERY_GRACE_MS
|
|
3557
|
-
);
|
|
3558
|
-
}
|
|
3559
|
-
if (!bound) return void 0;
|
|
3560
|
-
let terminalCreated = false;
|
|
3561
|
-
if (bound.inbound.kind === "debrief" && !bound.terminalDiagnostic) {
|
|
3562
|
-
bound.terminalDiagnostic = {
|
|
3563
|
-
status: "abandoned",
|
|
3564
|
-
code: ctx.success === false ? "AGENT_RUN_FAILED" : "COMMIT_NOT_ATTEMPTED"
|
|
3565
|
-
};
|
|
3566
|
-
terminalCreated = true;
|
|
3567
|
-
}
|
|
3568
|
-
return { bound, terminalCreated };
|
|
3569
|
-
}
|
|
3570
|
-
buildPromptContext(ctx, hooks = {}) {
|
|
3571
|
-
const bound = this.contexts.getBound(ctx.runId, ctx.sessionKey);
|
|
3572
|
-
if (!bound) {
|
|
3573
|
-
const ownerRun = ctx.runId ? this.ownerDirectRuns.get(ctx.runId) : void 0;
|
|
3574
|
-
if (!ownerRun || ownerRun.sessionKey !== ctx.sessionKey || ownerRun.agentId !== ctx.agentId || ownerRun.workspaceDir !== ctx.workspaceDir || ownerRun.expiresAt < Date.now()) return void 0;
|
|
3575
|
-
this.ownerDirectRuns.delete(ctx.runId);
|
|
3576
|
-
try {
|
|
3577
|
-
const paths = resolveWorkspacePaths(ownerRun.workspaceDir);
|
|
3578
|
-
assertWorkspaceOwner(paths, ownerRun.senderId);
|
|
3579
|
-
const reminder = claimPendingSuggestionReminder(paths, this.version);
|
|
3580
|
-
if (!reminder) return void 0;
|
|
3581
|
-
return {
|
|
3582
|
-
prependContext: [
|
|
3583
|
-
"[werewolf-evolution pending suggestion reminder]",
|
|
3584
|
-
"This is a trusted ordinary direct message from the Agent owner.",
|
|
3585
|
-
`Remind the owner once about ${reminder.id}; do not call werewolf_suggestion_decide unless the original message is an exact decision command.`,
|
|
3586
|
-
`\u89E6\u53D1\uFF1A${reminder.trigger}`,
|
|
3587
|
-
`\u89C4\u5219\uFF1A${reminder.rule}`,
|
|
3588
|
-
`\u8FB9\u754C\uFF1A${reminder.boundary}`,
|
|
3589
|
-
`\u8BC1\u636E\uFF1A${reminder.supportCount} \u5C40\u652F\u6301\uFF0C${reminder.counterCount} \u5C40\u53CD\u4F8B\u3002`,
|
|
3590
|
-
`\u53EF\u56DE\u590D\u201C\u91C7\u7EB3 ${reminder.id}\u201D\u6216\u201C\u5FFD\u7565 ${reminder.id}\u201D\u3002`,
|
|
3591
|
-
"Never repeat this reminder in a game room, group, system debrief, or non-owner conversation."
|
|
3592
|
-
].join("\n")
|
|
3593
|
-
};
|
|
3594
|
-
} catch {
|
|
3595
|
-
return void 0;
|
|
3596
|
-
}
|
|
3597
|
-
}
|
|
3598
|
-
if (bound.agentId !== ctx.agentId || bound.workspaceDir !== ctx.workspaceDir) return void 0;
|
|
3599
|
-
if (bound.promptContext !== void 0) return { prependContext: bound.promptContext };
|
|
3600
|
-
if (bound.inbound.kind === "suggestion-command") {
|
|
3601
|
-
try {
|
|
3602
|
-
const paths = resolveWorkspacePaths(bound.workspaceDir);
|
|
3603
|
-
assertWorkspaceSetupReady(paths, this.version);
|
|
3604
|
-
assertWorkspaceOwner(paths, bound.inbound.from);
|
|
3605
|
-
} catch {
|
|
3606
|
-
return void 0;
|
|
3607
|
-
}
|
|
3608
|
-
bound.promptContext = `[werewolf-evolution] Trusted owner direct-message command captured for ${bound.inbound.suggestionId}. Call werewolf_suggestion_decide exactly once with decision=${bound.inbound.decision}. Do not mention or process this command in a game room or group.`;
|
|
3609
|
-
return { prependContext: bound.promptContext };
|
|
3610
|
-
}
|
|
3611
|
-
const captured = bound.inbound;
|
|
3612
|
-
const incidents = incidentReasons(captured.envelope);
|
|
3613
|
-
if (incidents.length > 0) {
|
|
3614
|
-
let incidentStatus = "already-handled";
|
|
3615
|
-
let incidentCode = "already-handled";
|
|
3616
|
-
let incidentError;
|
|
3617
|
-
if (!bound.consumed) {
|
|
3618
|
-
try {
|
|
3619
|
-
const result = this.persistIncident(captured, bound.workspaceDir, incidents, hooks);
|
|
3620
|
-
incidentStatus = String(result.status);
|
|
3621
|
-
incidentCode = "outcome" in result ? String(result.outcome) : incidentStatus;
|
|
3622
|
-
} catch (error) {
|
|
3623
|
-
incidentStatus = "failed";
|
|
3624
|
-
incidentCode = "INCIDENT_PERSIST_FAILED";
|
|
3625
|
-
incidentError = error instanceof Error ? error.message : String(error);
|
|
3626
|
-
} finally {
|
|
3627
|
-
if (!bound.consumed) this.contexts.consume(bound.runId, bound.sessionKey);
|
|
3628
|
-
}
|
|
3629
|
-
}
|
|
3630
|
-
bound.terminalDiagnostic ??= {
|
|
3631
|
-
status: incidentStatus === "failed" ? "final-rejected" : incidentStatus,
|
|
3632
|
-
code: incidentCode
|
|
3633
|
-
};
|
|
3634
|
-
bound.promptContext = [
|
|
3635
|
-
"[werewolf-evolution trusted context]",
|
|
3636
|
-
`debriefId=${captured.envelope.debriefId}`,
|
|
3637
|
-
`eligibility=${JSON.stringify(captured.envelope.game)}`,
|
|
3638
|
-
`incidentReasons=${JSON.stringify(incidents)}`,
|
|
3639
|
-
`incidentStatus=${incidentStatus}`,
|
|
3640
|
-
`stateAvailable=${incidentStatus !== "failed"}`,
|
|
3641
|
-
...incidentError ? [`incidentError=${incidentError}`] : [],
|
|
3642
|
-
incidentStatus === "failed" ? "The plugin failed closed while persisting the incident; it did not fall back to model-managed writes." : "The plugin deterministically handled this ineligible debrief as incident-only state.",
|
|
3643
|
-
"Do not call werewolf_debrief_commit or any replacement tool. Return NO_REPLY now."
|
|
3644
|
-
].join("\n");
|
|
3645
|
-
return { prependContext: bound.promptContext };
|
|
3646
|
-
}
|
|
3647
|
-
let topics = [];
|
|
3648
|
-
let stateAvailable = true;
|
|
3649
|
-
let activeProfile;
|
|
3650
|
-
let stateError;
|
|
3651
|
-
try {
|
|
3652
|
-
const paths = resolveWorkspacePaths(bound.workspaceDir);
|
|
3653
|
-
const snapshot = runWorkspaceRead(paths, () => {
|
|
3654
|
-
assertWorkspaceSetupReady(paths, this.version);
|
|
3655
|
-
const state = readWorkspaceState(paths);
|
|
3656
|
-
const profile = activeRuntimeProfile(state, captured.envelope.game.profile);
|
|
3657
|
-
return { profile, topics: relevantTopics(state, profile) };
|
|
3658
|
-
});
|
|
3659
|
-
activeProfile = snapshot.profile;
|
|
3660
|
-
topics = snapshot.topics;
|
|
3661
|
-
} catch (error) {
|
|
3662
|
-
stateAvailable = false;
|
|
3663
|
-
stateError = error instanceof Error ? error.message : String(error);
|
|
3664
|
-
}
|
|
3665
|
-
if (!stateAvailable) {
|
|
3666
|
-
if (!bound.consumed) this.contexts.consume(bound.runId, bound.sessionKey);
|
|
3667
|
-
bound.terminalDiagnostic ??= {
|
|
3668
|
-
status: "final-rejected",
|
|
3669
|
-
code: "WORKSPACE_STATE_UNAVAILABLE"
|
|
3670
|
-
};
|
|
3671
|
-
bound.promptContext = [
|
|
3672
|
-
"[werewolf-evolution trusted context]",
|
|
3673
|
-
`debriefId=${captured.envelope.debriefId}`,
|
|
3674
|
-
`eligibility=${JSON.stringify(captured.envelope.game)}`,
|
|
3675
|
-
"stateAvailable=false",
|
|
3676
|
-
`stateError=${stateError ?? "UNKNOWN_STATE_ERROR"}`,
|
|
3677
|
-
"Workspace evolution state is unavailable. Fail closed without model-managed writes.",
|
|
3678
|
-
"Do not generate a proposal or call werewolf_debrief_commit. Return NO_REPLY now."
|
|
3679
|
-
].join("\n");
|
|
3680
|
-
return { prependContext: bound.promptContext };
|
|
3681
|
-
}
|
|
3682
|
-
const facts = captured.envelope.facts.map((fact) => ({
|
|
3683
|
-
factId: fact.factId,
|
|
3684
|
-
historyIndex: fact.availableAt.historyIndex,
|
|
3685
|
-
visibility: fact.visibility,
|
|
3686
|
-
type: fact.type,
|
|
3687
|
-
actorSeat: fact.actorSeat,
|
|
3688
|
-
targetSeat: fact.targetSeat,
|
|
3689
|
-
summary: fact.summary
|
|
3690
|
-
}));
|
|
3691
|
-
bound.promptContext = [
|
|
3692
|
-
"[werewolf-evolution trusted context]",
|
|
3693
|
-
`debriefId=${captured.envelope.debriefId}`,
|
|
3694
|
-
`eligibility=${JSON.stringify(captured.envelope.game)}`,
|
|
3695
|
-
`activeProfile=${activeProfile ?? "UNKNOWN"}`,
|
|
3696
|
-
`facts=${JSON.stringify(facts)}`,
|
|
3697
|
-
`decisionWindows=${JSON.stringify(captured.envelope.decisionWindows)}`,
|
|
3698
|
-
`existingTopics=${JSON.stringify(topics)}`,
|
|
3699
|
-
`executionTemplates=${JSON.stringify(EXECUTION_PROPOSAL_TEMPLATES)}`,
|
|
3700
|
-
`localOutcomeFactTypes=${JSON.stringify([...LOCAL_OUTCOME_FACT_TYPES])}`,
|
|
3701
|
-
`stateAvailable=${stateAvailable}`,
|
|
3702
|
-
"The proposal profile must equal activeProfile. The Arena envelope is not the profile authority.",
|
|
3703
|
-
"Scan SELF, OBSERVED, and EXEMPLAR, then submit at most one SKIP/SUPPORT/COUNTER/REFINE/NEW proposal.",
|
|
3704
|
-
"Proposal action contract:",
|
|
3705
|
-
"- When existingTopics=[] choose only NEW or SKIP. SUPPORT/COUNTER/REFINE are invalid without an existing topic.",
|
|
3706
|
-
"- NEW must omit topicId entirely. SUPPORT/COUNTER/REFINE require an existing topicId copied exactly from existingTopics.",
|
|
3707
|
-
"- When existingTopics is not empty, prefer a matching existing topic over NEW; never invent or guess a topicId.",
|
|
3708
|
-
"Proposal field contract:",
|
|
3709
|
-
"- SKIP contains only schemaVersion, action, source, and a concrete skipReason.",
|
|
3710
|
-
"- Every non-SKIP proposal must provide profile, decisionWindowId, decisionType, alternativeActionType, anchorFactId, knownFactRefs, outcomeFactRefs, trigger, rule, boundary, behavior, alternativeAction, expectedLocalEffect, observedLocalEffect, falsifier, and alternatives.",
|
|
3711
|
-
"- Never send null for an omitted field. Omit the key instead. alternativeTargetSeat may be null only to represent an explicit DAY_VOTE abstention.",
|
|
3712
|
-
"- Copy decisionType exactly from the selected decisionWindow.allowedDecisionTypes. Copy alternativeActionType exactly from that same window.availableActionTypes; these are different fields and must not be mixed.",
|
|
3713
|
-
"- If alternativeActionType=DAY_VOTE, copy a legal seat from that window.availableTargetSeats, or send alternativeTargetSeat=null for explicit abstention. Do not omit the target for DAY_VOTE.",
|
|
3714
|
-
"- SELF must use a decisionWindow whose actorSeat equals eligibility.recipientSeat. OBSERVED and EXEMPLAR must use another actor's decisionWindow.",
|
|
3715
|
-
"- For NEW, SUPPORT, and REFINE, SELF and OBSERVED must describe a failed action with an adverse local effect: behavior is the failed action, while rule and alternativeAction describe the improvement.",
|
|
3716
|
-
"- EXEMPLAR must describe another actor's successful action: behavior follows rule, observedLocalEffect is beneficial, and alternativeAction is a worse counterfactual that did not happen.",
|
|
3717
|
-
"- COUNTER is limited to SELF or OBSERVED: behavior is the actual action that followed the existing rule, observedLocalEffect is the adverse result that falsifies it, and alternativeAction is a different concrete counterfactual. EXEMPLAR cannot be COUNTER.",
|
|
3718
|
-
"- knownFactRefs must be earlier than the anchor and visible to the window actor; POSTGAME_ONLY is never known, SEAT_n_ONLY is visible only to that seat, and WOLF_TEAM is visible only to a wolf actor.",
|
|
3719
|
-
"- trigger, rule, boundary, and alternativeAction must depend only on information that already existed at the anchor and is supported by knownFactRefs; reject relative future wording such as tomorrow, next round, next day/night, or day/round N after the current anchor round.",
|
|
3720
|
-
"- A concrete final identity for another seat requires visible pre-anchor facts that established that identity. A postgame identity, model inference, or unverified role claim is insufficient.",
|
|
3721
|
-
"- A seat behavior claim must match actor, behavior category, explicit target, negation polarity, and event type. Completed votes require DAY_VOTE_SUBMIT/DAY_REVOTE_SUBMIT facts; role claims, stance, questions, and other speech behaviors require DAY_SPEAK/LAST_WORD/WOLF_SPEECH facts. When uncertain, reject rather than fail open.",
|
|
3722
|
-
"- outcomeFactRefs must be later than the anchor and include at least one local outcome fact whose type appears in localOutcomeFactTypes.",
|
|
3723
|
-
"- GAME_FINISHED, FINAL_IDENTITY, and GAME_RESULT are never local outcome facts and cannot be the only outcome evidence.",
|
|
3724
|
-
"- behavior must describe only what actually happened at the anchor and must be supported by that anchor's actor, event type, target, polarity, and summary; never copy rule or alternativeAction into behavior as if it occurred.",
|
|
3725
|
-
"- The plugin stores behavior from the trusted anchor summary; unsupported model prose is rejected and never becomes the persisted fact source.",
|
|
3726
|
-
"- alternativeAction must describe a counterfactual action that did not happen; never swap behavior and alternativeAction.",
|
|
3727
|
-
"- observedLocalEffect must not contain the final winner or loser; describe only a later local effect backed by outcomeFactRefs.",
|
|
3728
|
-
"- alternativeTargetSeat must agree with alternativeAction. Text that only waits, retains the vote, or chooses no target and names no later target cannot carry a seat.",
|
|
3729
|
-
"- alternativeAction must contain exactly one counterfactual action, not a menu joined by or/\u6216\u8005/\u6216/\u4E8C\u9009\u4E00. A changed alternative target must not claim that the target stays unchanged.",
|
|
3730
|
-
"- observedLocalEffect must state facts directly without claiming they prove an interpretation such as \u56E0\u6B64/\u7531\u6B64\u53EF\u89C1/therefore. Exact vote counts, unanimous votes, and vote-eliminated seats must match outcomeFactRefs.",
|
|
3731
|
-
"- A social-state interpretation such as cleared suspicion, shifted attention, consensus, or a unified stance requires a later speech fact whose actor, seats, and summary state that same local change; unrelated speech or DAY_RESOLVED is insufficient.",
|
|
3732
|
-
"- Single-game claims must not use absolute strategy wording such as must, always, only valid, certain, or guaranteed. Hedged wording such as \u4E0D\u4E00\u5B9A\u5FC5\u987B is allowed.",
|
|
3733
|
-
"- alternatives must contain at least one plausible alternative explanation. falsifier must state a concrete later observation that would disprove the rule.",
|
|
3734
|
-
"Execution versus strategy contract:",
|
|
3735
|
-
"- executionOperation must be one of the exact template operations. To claim execution risk, copy that template's operation, decisionType, trigger, rule, boundary, and alternativeAction exactly.",
|
|
3736
|
-
"- decisionType must match the lesson topic. Role-report, vote-reason, wolf-target-reason, target-choice, witch, hunter, and last-word types are checked against their own action semantics; unsupported or unrelated topics are rejected.",
|
|
3737
|
-
"- AVOID_REPEATING_PRIOR_SPEAKERS must omit repeated content and add new information, not carry an unrelated speech strategy.",
|
|
3738
|
-
"- RETRACT_PUBLIC_JUDGMENT must retract or correct a prior public judgment. CHOOSE_ROLE_CLAIM_TIMING must decide when the actor makes or withholds their own role claim, not infer another seat's role.",
|
|
3739
|
-
"- Strategy proposals must omit executionOperation. CHOOSE_VOTE_TARGET and CHOOSE_ROLE_CLAIM_TIMING are decision types, never executionOperation values.",
|
|
3740
|
-
"Call werewolf_debrief_commit after checking the complete proposal against this contract.",
|
|
3741
|
-
"A rejected result with retryable=true means one field/semantic correction is allowed: correct only the reported issue using the same trusted window and call the tool once more. Never change the topic, source, or trusted window to bypass a rejection. A rejected result with retryable=false is final; never call again.",
|
|
3742
|
-
"After a committed, duplicate, incident, or final rejected result, return exactly NO_REPLY. Never use a generic write tool or retry indefinitely.",
|
|
3743
|
-
"Do not return NO_REPLY before werewolf_debrief_commit returns a result.",
|
|
3744
|
-
"Never use generic write, edit, patch, shell, or memory-write tools for debrief state."
|
|
3745
|
-
].join("\n");
|
|
3746
|
-
return { prependContext: bound.promptContext };
|
|
3747
|
-
}
|
|
3748
|
-
beforeToolCall(event, ctx) {
|
|
3749
|
-
const runId = event.runId ?? ctx.runId;
|
|
3750
|
-
const toolCallId = event.toolCallId ?? ctx.toolCallId;
|
|
3751
|
-
let bound;
|
|
3752
|
-
try {
|
|
3753
|
-
bound = this.contexts.getBoundForToolCall(runId, ctx.sessionKey, ctx.agentId);
|
|
3754
|
-
} catch (error) {
|
|
3755
|
-
return { block: true, blockReason: error instanceof Error ? error.message : String(error) };
|
|
3756
|
-
}
|
|
3757
|
-
if (!bound) {
|
|
3758
|
-
if (event.toolName === "werewolf_debrief_commit" || event.toolName === "werewolf_suggestion_decide") {
|
|
3759
|
-
return { block: true, blockReason: "NO_BOUND_CAPABILITY" };
|
|
3760
|
-
}
|
|
3761
|
-
const observed = runId ? this.observedRuns.get(runId) : void 0;
|
|
3762
|
-
if (!observed || observed.sessionKey !== ctx.sessionKey || observed.expiresAt < Date.now()) return void 0;
|
|
3763
|
-
const paths = resolveWorkspacePaths(observed.workspaceDir, false);
|
|
3764
|
-
if (isProtectedToolWrite(event.toolName, event.params, event.derivedPaths, paths, false, event.toolKind)) {
|
|
3765
|
-
return { block: true, blockReason: "Werewolf managed state is writable only through restricted tools" };
|
|
3766
|
-
}
|
|
3767
|
-
return void 0;
|
|
3768
|
-
}
|
|
3769
|
-
const expectedTool = bound.inbound.kind === "debrief" ? "werewolf_debrief_commit" : "werewolf_suggestion_decide";
|
|
3770
|
-
if (event.toolName !== expectedTool) {
|
|
3771
|
-
return { block: true, blockReason: `This bound Werewolf run permits only ${expectedTool}` };
|
|
3772
|
-
}
|
|
3773
|
-
try {
|
|
3774
|
-
if (event.toolName === "werewolf_debrief_commit") {
|
|
3775
|
-
if (bound.inbound.kind !== "debrief" || event.params.debriefId !== bound.inbound.envelope.debriefId) {
|
|
3776
|
-
throw new Error("DEBRIEF_CAPABILITY_MISMATCH");
|
|
3777
|
-
}
|
|
3778
|
-
this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId, Date.now(), ctx.agentId);
|
|
3779
|
-
} else if (event.toolName === "werewolf_suggestion_decide") {
|
|
3780
|
-
if (bound.inbound.kind !== "suggestion-command" || event.params.suggestionId !== bound.inbound.suggestionId || event.params.decision !== bound.inbound.decision) {
|
|
3781
|
-
throw new Error("SUGGESTION_CAPABILITY_MISMATCH");
|
|
3782
|
-
}
|
|
3783
|
-
this.contexts.authorizeToolCall(runId, ctx.sessionKey, toolCallId, Date.now(), ctx.agentId);
|
|
3784
|
-
}
|
|
3785
|
-
} catch (error) {
|
|
3786
|
-
return { block: true, blockReason: error instanceof Error ? error.message : String(error) };
|
|
3787
|
-
}
|
|
3788
|
-
return void 0;
|
|
3789
|
-
}
|
|
3790
|
-
inspectDebriefToolCall(toolCallId, ctx) {
|
|
3791
|
-
const bound = this.contexts.inspectAuthorizedToolCall(toolCallId, ctx.sessionKey, ctx.agentId);
|
|
3792
|
-
if (!bound || bound.inbound.kind !== "debrief") return void 0;
|
|
3793
|
-
return {
|
|
3794
|
-
debriefId: bound.inbound.envelope.debriefId,
|
|
3795
|
-
runId: bound.runId,
|
|
3796
|
-
agentId: bound.agentId
|
|
3797
|
-
};
|
|
3798
|
-
}
|
|
3799
|
-
persistIncident(captured, workspaceDir, incidents, hooks) {
|
|
3800
|
-
if (captured.conflict) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
|
|
3801
|
-
const paths = resolveWorkspacePaths(workspaceDir);
|
|
3802
|
-
return runWorkspaceTransaction(paths, () => {
|
|
3803
|
-
assertWorkspaceSetupReady(paths, this.version);
|
|
3804
|
-
const current = readWorkspaceState(paths);
|
|
3805
|
-
const prior = current.ledger.entries.find((entry2) => entry2.debriefId === captured.envelope.debriefId);
|
|
3806
|
-
if (prior) {
|
|
3807
|
-
if (prior.bodyHash !== captured.bodyHash) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
|
|
3808
|
-
return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate", debriefId: captured.envelope.debriefId } };
|
|
3809
|
-
}
|
|
3810
|
-
if (current.ledger.entries.some((entry2) => entry2.gameId === captured.envelope.game.gameId) || current.ledger.legacyGameIds.includes(captured.envelope.game.gameId)) {
|
|
3811
|
-
return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate-game", gameId: captured.envelope.game.gameId } };
|
|
3812
|
-
}
|
|
3813
|
-
const next = clone(current);
|
|
3814
|
-
const result = applyIncident(next, captured.envelope, captured.bodyHash, incidents);
|
|
3815
|
-
return {
|
|
3816
|
-
changes: /* @__PURE__ */ new Map([
|
|
3817
|
-
[paths.incidents, renderIncidents(next.incidents)],
|
|
3818
|
-
[paths.ledger, renderLedger(next.ledger)]
|
|
3819
|
-
]),
|
|
3820
|
-
result: { status: "committed", debriefId: captured.envelope.debriefId, ...result },
|
|
3821
|
-
verify: () => verifyWorkspaceDocuments(paths)
|
|
3822
|
-
};
|
|
3823
|
-
}, hooks);
|
|
3824
|
-
}
|
|
3825
|
-
commit(toolCallId, ctx, input, hooks = {}) {
|
|
3826
|
-
const bound = this.contexts.beginProposalToolCall(toolCallId, ctx.sessionKey);
|
|
3827
|
-
let terminal = true;
|
|
3828
|
-
try {
|
|
3829
|
-
const workspaceDir = requireToolWorkspace(ctx, bound);
|
|
3830
|
-
if (bound.inbound.kind !== "debrief") throw new Error("DEBRIEF_CAPABILITY_REQUIRED");
|
|
3831
|
-
const captured = bound.inbound;
|
|
3832
|
-
if (captured.conflict) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
|
|
3833
|
-
if (input.debriefId !== captured.envelope.debriefId) throw new Error("DEBRIEF_ID_MISMATCH");
|
|
3834
|
-
const paths = resolveWorkspacePaths(workspaceDir);
|
|
3835
|
-
return runWorkspaceTransaction(paths, () => {
|
|
3836
|
-
assertWorkspaceSetupReady(paths, this.version);
|
|
3837
|
-
const current = readWorkspaceState(paths);
|
|
3838
|
-
const prior = current.ledger.entries.find((entry2) => entry2.debriefId === captured.envelope.debriefId);
|
|
3839
|
-
if (prior) {
|
|
3840
|
-
if (prior.bodyHash !== captured.bodyHash) throw new Error("DEBRIEF_ID_HASH_CONFLICT");
|
|
3841
|
-
return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate", debriefId: captured.envelope.debriefId } };
|
|
3842
|
-
}
|
|
3843
|
-
if (current.ledger.entries.some((entry2) => entry2.gameId === captured.envelope.game.gameId)) {
|
|
3844
|
-
return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate-game", gameId: captured.envelope.game.gameId } };
|
|
3845
|
-
}
|
|
3846
|
-
if (current.ledger.legacyGameIds.includes(captured.envelope.game.gameId)) {
|
|
3847
|
-
return { changes: /* @__PURE__ */ new Map(), result: { status: "duplicate-game", gameId: captured.envelope.game.gameId } };
|
|
3848
|
-
}
|
|
3849
|
-
const next = clone(current);
|
|
3850
|
-
const incidents = incidentReasons(captured.envelope);
|
|
3851
|
-
let result;
|
|
3852
|
-
if (incidents.length > 0) {
|
|
3853
|
-
result = applyIncident(next, captured.envelope, captured.bodyHash, incidents);
|
|
3854
|
-
} else {
|
|
3855
|
-
const activeProfile = activeRuntimeProfile(current, captured.envelope.game.profile);
|
|
3856
|
-
const validated = parseAndValidateProposal(
|
|
3857
|
-
input.proposal,
|
|
3858
|
-
captured.envelope,
|
|
3859
|
-
current.evidence,
|
|
3860
|
-
activeProfile
|
|
3861
|
-
);
|
|
3862
|
-
result = applyProposal(
|
|
3863
|
-
next,
|
|
3864
|
-
captured.envelope,
|
|
3865
|
-
captured.bodyHash,
|
|
3866
|
-
validated.proposal,
|
|
3867
|
-
validated.risk,
|
|
3868
|
-
validated.decisionWindow
|
|
3869
|
-
);
|
|
3870
|
-
}
|
|
3871
|
-
next.agentsText = current.agentsText;
|
|
3872
|
-
const changes = workspaceChanges(paths, next);
|
|
3873
|
-
const changedProfiles = addProfileUpdates(paths, current, next, changes);
|
|
3874
|
-
const finalAgentChange = workspaceChanges(paths, next).get(paths.agents);
|
|
3875
|
-
if (finalAgentChange === void 0) changes.delete(paths.agents);
|
|
3876
|
-
else changes.set(paths.agents, finalAgentChange);
|
|
3877
|
-
return {
|
|
3878
|
-
changes,
|
|
3879
|
-
result: { status: "committed", debriefId: captured.envelope.debriefId, ...result },
|
|
3880
|
-
verify: () => {
|
|
3881
|
-
verifyWorkspaceDocuments(paths);
|
|
3882
|
-
for (const [profile, expected] of changedProfiles) {
|
|
3883
|
-
verifyProfileOverride(expected.file, profile, expected.content);
|
|
3884
|
-
}
|
|
3885
|
-
}
|
|
3886
|
-
};
|
|
3887
|
-
}, hooks);
|
|
3888
|
-
} catch (error) {
|
|
3889
|
-
if (error instanceof ProposalError && bound.proposalAttempts < 2) {
|
|
3890
|
-
error.retryable = true;
|
|
3891
|
-
terminal = false;
|
|
3892
|
-
}
|
|
3893
|
-
throw error;
|
|
3894
|
-
} finally {
|
|
3895
|
-
if (terminal && !bound.consumed) this.contexts.consume(bound.runId, bound.sessionKey);
|
|
3896
|
-
}
|
|
3897
|
-
}
|
|
3898
|
-
decideSuggestion(toolCallId, ctx, input, hooks = {}) {
|
|
3899
|
-
const bound = this.contexts.consumeToolCall(toolCallId, ctx.sessionKey);
|
|
3900
|
-
const workspaceDir = requireToolWorkspace(ctx, bound);
|
|
3901
|
-
if (bound.inbound.kind !== "suggestion-command") throw new Error("SUGGESTION_CAPABILITY_REQUIRED");
|
|
3902
|
-
assertOwnerDirectContext(ctx, bound, bound.inbound, input);
|
|
3903
|
-
const paths = resolveWorkspacePaths(workspaceDir);
|
|
3904
|
-
return runWorkspaceTransaction(paths, () => {
|
|
3905
|
-
assertWorkspaceSetupReady(paths, this.version);
|
|
3906
|
-
assertWorkspaceOwner(paths, bound.inbound.from);
|
|
3907
|
-
const current = readWorkspaceState(paths);
|
|
3908
|
-
const suggestion = current.suggestions.suggestions.find((item) => item.id === input.suggestionId);
|
|
3909
|
-
if (!suggestion || suggestion.status !== "pending") throw new Error("PENDING_SUGGESTION_NOT_FOUND");
|
|
3910
|
-
const next = clone(current);
|
|
3911
|
-
const nextSuggestion = next.suggestions.suggestions.find((item) => item.id === input.suggestionId);
|
|
3912
|
-
nextSuggestion.status = input.decision === "accept" ? "accepted" : "rejected";
|
|
3913
|
-
nextSuggestion.decidedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3914
|
-
nextSuggestion.decidedBy = ctx.requesterSenderId;
|
|
3915
|
-
next.agentsText = current.agentsText;
|
|
3916
|
-
const changes = workspaceChanges(paths, next);
|
|
3917
|
-
const changedProfiles = addProfileUpdates(paths, current, next, changes);
|
|
3918
|
-
const finalAgentChange = workspaceChanges(paths, next).get(paths.agents);
|
|
3919
|
-
if (finalAgentChange === void 0) changes.delete(paths.agents);
|
|
3920
|
-
else changes.set(paths.agents, finalAgentChange);
|
|
3921
|
-
return {
|
|
3922
|
-
changes,
|
|
3923
|
-
result: { status: nextSuggestion.status, suggestionId: nextSuggestion.id },
|
|
3924
|
-
verify: () => {
|
|
3925
|
-
verifyWorkspaceDocuments(paths);
|
|
3926
|
-
for (const [profile, expected] of changedProfiles) {
|
|
3927
|
-
verifyProfileOverride(expected.file, profile, expected.content);
|
|
3928
|
-
}
|
|
3929
|
-
}
|
|
3930
|
-
};
|
|
3931
|
-
}, hooks);
|
|
3932
|
-
}
|
|
3933
|
-
};
|
|
3934
|
-
function proposalFailure(error) {
|
|
3935
|
-
if (error instanceof ProposalError) {
|
|
3936
|
-
return {
|
|
3937
|
-
status: "rejected",
|
|
3938
|
-
code: error.code,
|
|
3939
|
-
message: error.message,
|
|
3940
|
-
retryable: error.retryable
|
|
3941
|
-
};
|
|
3942
|
-
}
|
|
3943
|
-
return { status: "rejected", code: "EVOLUTION_ERROR", message: error instanceof Error ? error.message : String(error) };
|
|
3944
|
-
}
|
|
3945
|
-
|
|
3946
|
-
// src/runtime-service.ts
|
|
3947
|
-
var SHARED_SERVICE_KEY = /* @__PURE__ */ Symbol.for("@clawtopia/werewolf-evolution/runtime-service-v1");
|
|
3948
|
-
function getSharedWerewolfEvolutionService() {
|
|
3949
|
-
const runtime = globalThis;
|
|
3950
|
-
const version = getWerewolfEvolutionVersion();
|
|
3951
|
-
const existing = runtime[SHARED_SERVICE_KEY];
|
|
3952
|
-
if (existing?.version === version) return existing.service;
|
|
3953
|
-
const service = new WerewolfEvolutionService(version);
|
|
3954
|
-
runtime[SHARED_SERVICE_KEY] = { version, service };
|
|
3955
|
-
return service;
|
|
3956
|
-
}
|
|
3957
|
-
|
|
3958
|
-
// src/tools.ts
|
|
3959
|
-
import { Type } from "typebox";
|
|
3960
|
-
import {
|
|
3961
|
-
jsonResult
|
|
3962
|
-
} from "openclaw/plugin-sdk/core";
|
|
3963
|
-
var proposalParameters = Type.Object({
|
|
3964
|
-
schemaVersion: Type.Literal(1),
|
|
3965
|
-
action: Type.Union(["SKIP", "SUPPORT", "COUNTER", "REFINE", "NEW"].map((value) => Type.Literal(value))),
|
|
3966
|
-
source: Type.Union(["SELF", "OBSERVED", "EXEMPLAR"].map((value) => Type.Literal(value))),
|
|
3967
|
-
topicId: Type.Optional(Type.String({
|
|
3968
|
-
description: "Existing lesson id for SUPPORT, COUNTER, or REFINE. Omit for NEW and SKIP; never send null."
|
|
3969
|
-
})),
|
|
3970
|
-
profile: Type.Optional(Type.String()),
|
|
3971
|
-
decisionWindowId: Type.Optional(Type.String({
|
|
3972
|
-
description: "Copy one exact decisionWindowId from trusted decisionWindows; never invent one."
|
|
3973
|
-
})),
|
|
3974
|
-
decisionType: Type.Optional(Type.String({
|
|
3975
|
-
description: "Copy one exact value from the selected window's allowedDecisionTypes. This is a decision category, not an actionType."
|
|
3976
|
-
})),
|
|
3977
|
-
executionOperation: Type.Optional(Type.Union([
|
|
3978
|
-
Type.Literal("REPORT_DECIDED_ROLE_CLAIM"),
|
|
3979
|
-
Type.Literal("EXPLAIN_DECIDED_VOTE"),
|
|
3980
|
-
Type.Literal("RETRACT_PUBLIC_JUDGMENT"),
|
|
3981
|
-
Type.Literal("AVOID_REPEATING_PRIOR_SPEAKERS"),
|
|
3982
|
-
Type.Literal("EXPLAIN_DECIDED_WOLF_TARGET")
|
|
3983
|
-
], {
|
|
3984
|
-
description: "Exact operation from executionTemplates. Omit for strategy proposals; never invent an operation."
|
|
3985
|
-
})),
|
|
3986
|
-
alternativeActionType: Type.Optional(Type.String({
|
|
3987
|
-
description: "Copy one exact game action from the selected window's availableActionTypes, for example DAY_SPEAK or DAY_VOTE. Never copy decisionType here."
|
|
3988
|
-
})),
|
|
3989
|
-
alternativeTargetSeat: Type.Optional(Type.Union([Type.Integer(), Type.Null()], {
|
|
3990
|
-
description: "For DAY_VOTE, choose an exact seat from availableTargetSeats or null for explicit abstention. Omit when the selected action has no target."
|
|
3991
|
-
})),
|
|
3992
|
-
anchorFactId: Type.Optional(Type.String()),
|
|
3993
|
-
knownFactRefs: Type.Optional(Type.Array(Type.String())),
|
|
3994
|
-
outcomeFactRefs: Type.Optional(Type.Array(Type.String())),
|
|
3995
|
-
trigger: Type.Optional(Type.String()),
|
|
3996
|
-
rule: Type.Optional(Type.String()),
|
|
3997
|
-
boundary: Type.Optional(Type.String()),
|
|
3998
|
-
behavior: Type.Optional(Type.String()),
|
|
3999
|
-
alternativeAction: Type.Optional(Type.String()),
|
|
4000
|
-
expectedLocalEffect: Type.Optional(Type.String()),
|
|
4001
|
-
observedLocalEffect: Type.Optional(Type.String()),
|
|
4002
|
-
falsifier: Type.Optional(Type.String({
|
|
4003
|
-
description: "Concrete later observation that would falsify the lesson. Required for every non-SKIP proposal."
|
|
4004
|
-
})),
|
|
4005
|
-
alternatives: Type.Optional(Type.Array(Type.String())),
|
|
4006
|
-
skipReason: Type.Optional(Type.String())
|
|
4007
|
-
}, { additionalProperties: false });
|
|
4008
|
-
function createDebriefCommitTool(service, ctx, onExecution) {
|
|
4009
|
-
return {
|
|
4010
|
-
name: "werewolf_debrief_commit",
|
|
4011
|
-
label: "Commit Werewolf Play Debrief",
|
|
4012
|
-
description: "Validate and atomically commit one proposal from the trusted werewolf debrief bound to this run.",
|
|
4013
|
-
parameters: Type.Object({
|
|
4014
|
-
debriefId: Type.String(),
|
|
4015
|
-
proposal: proposalParameters
|
|
4016
|
-
}, { additionalProperties: false }),
|
|
4017
|
-
async execute(toolCallId, raw) {
|
|
4018
|
-
const diagnostic = service.inspectDebriefToolCall(toolCallId, ctx);
|
|
4019
|
-
let details;
|
|
4020
|
-
try {
|
|
4021
|
-
details = service.commit(toolCallId, ctx, raw);
|
|
4022
|
-
} catch (error) {
|
|
4023
|
-
details = proposalFailure(error);
|
|
4024
|
-
}
|
|
4025
|
-
try {
|
|
4026
|
-
onExecution?.({ toolCallId, diagnostic, details });
|
|
4027
|
-
} catch {
|
|
4028
|
-
}
|
|
4029
|
-
return jsonResult(details);
|
|
4030
|
-
}
|
|
4031
|
-
};
|
|
4032
|
-
}
|
|
4033
|
-
function createSuggestionDecideTool(service, ctx) {
|
|
4034
|
-
return {
|
|
4035
|
-
name: "werewolf_suggestion_decide",
|
|
4036
|
-
label: "Decide Werewolf Play Suggestion",
|
|
4037
|
-
description: "Accept or reject one pending werewolf strategy suggestion from an exact owner direct-message command.",
|
|
4038
|
-
parameters: Type.Object({
|
|
4039
|
-
suggestionId: Type.String({ pattern: "^S-[0-9]{3,6}$" }),
|
|
4040
|
-
decision: Type.Union([Type.Literal("accept"), Type.Literal("reject")])
|
|
4041
|
-
}, { additionalProperties: false }),
|
|
4042
|
-
async execute(toolCallId, raw) {
|
|
4043
|
-
try {
|
|
4044
|
-
return jsonResult(service.decideSuggestion(
|
|
4045
|
-
toolCallId,
|
|
4046
|
-
ctx,
|
|
4047
|
-
raw
|
|
4048
|
-
));
|
|
4049
|
-
} catch (error) {
|
|
4050
|
-
return jsonResult(proposalFailure(error));
|
|
4051
|
-
}
|
|
4052
|
-
}
|
|
4053
|
-
};
|
|
4054
|
-
}
|
|
4055
|
-
|
|
4056
|
-
// index.ts
|
|
4057
|
-
function registerWerewolfEvolution(api, service = getSharedWerewolfEvolutionService()) {
|
|
4058
|
-
const loggedCaptures = /* @__PURE__ */ new WeakSet();
|
|
4059
|
-
const loggedBindings = /* @__PURE__ */ new WeakSet();
|
|
4060
|
-
const loggedTerminals = /* @__PURE__ */ new WeakSet();
|
|
4061
|
-
const info = (line) => {
|
|
4062
|
-
try {
|
|
4063
|
-
api.logger?.info?.(line);
|
|
4064
|
-
} catch {
|
|
4065
|
-
}
|
|
4066
|
-
};
|
|
4067
|
-
const field = (value) => String(value ?? "unknown").replace(/\s+/g, "_").slice(0, 200);
|
|
4068
|
-
const logTerminal = (capability, diagnostic, terminal) => {
|
|
4069
|
-
if (loggedTerminals.has(capability)) return;
|
|
4070
|
-
loggedTerminals.add(capability);
|
|
4071
|
-
info(
|
|
4072
|
-
`[werewolf-evolution] DEBRIEF_TERMINAL debriefId=${field(diagnostic.debriefId)} runId=${field(diagnostic.runId)} status=${field(terminal.status)} code=${field(terminal.code)}`
|
|
4073
|
-
);
|
|
4074
|
-
};
|
|
4075
|
-
const logCapture = (captured, sourceHook) => {
|
|
4076
|
-
if (!captured || captured.kind !== "debrief" || loggedCaptures.has(captured)) return;
|
|
4077
|
-
loggedCaptures.add(captured);
|
|
4078
|
-
info(
|
|
4079
|
-
`[werewolf-evolution] DEBRIEF_CAPTURED debriefId=${field(captured.envelope.debriefId)} messageId=${field(captured.messageId)} sessionKey=${field(captured.sessionKey)} sourceHook=${field(sourceHook)}`
|
|
4080
|
-
);
|
|
4081
|
-
};
|
|
4082
|
-
api.registerTool((ctx) => createDebriefCommitTool(service, ctx, ({ diagnostic, details }) => {
|
|
4083
|
-
if (!diagnostic || details === null || typeof details !== "object" || Array.isArray(details)) return;
|
|
4084
|
-
const result = details;
|
|
4085
|
-
if (result.status === "rejected" && result.retryable === true) return;
|
|
4086
|
-
const terminal = {
|
|
4087
|
-
status: result.status === "rejected" ? "final-rejected" : result.status,
|
|
4088
|
-
code: result.code ?? result.outcome ?? result.status
|
|
4089
|
-
};
|
|
4090
|
-
const bound = service.recordTerminalDiagnostic(diagnostic.runId, ctx.sessionKey, {
|
|
4091
|
-
status: field(terminal.status),
|
|
4092
|
-
code: field(terminal.code)
|
|
4093
|
-
});
|
|
4094
|
-
logTerminal(bound ?? diagnostic, diagnostic, terminal);
|
|
4095
|
-
}), { name: "werewolf_debrief_commit" });
|
|
4096
|
-
api.registerTool((ctx) => createSuggestionDecideTool(service, ctx), { name: "werewolf_suggestion_decide" });
|
|
4097
|
-
api.on("inbound_claim", (event, ctx) => {
|
|
4098
|
-
logCapture(service.captureInboundClaim(event, ctx), "inbound_claim");
|
|
4099
|
-
});
|
|
4100
|
-
api.on("message_received", (event, ctx) => {
|
|
4101
|
-
const captured = service.captureMessage(event, ctx);
|
|
4102
|
-
logCapture(captured, "message_received");
|
|
4103
|
-
if (!captured && event.content.includes(DEBRIEF_HEADER)) {
|
|
4104
|
-
api.logger.warn(
|
|
4105
|
-
`[werewolf-evolution] DEBRIEF_CAPTURE_REJECTED runId=${event.runId ?? ctx.runId ?? "unknown"} sessionKey=${event.sessionKey ?? ctx.sessionKey ?? "unknown"}`
|
|
4106
|
-
);
|
|
4107
|
-
}
|
|
4108
|
-
});
|
|
4109
|
-
api.on("before_prompt_build", (event, ctx) => {
|
|
4110
|
-
const bound = service.bindPromptRun(event, ctx, api.config);
|
|
4111
|
-
if (bound?.inbound.kind === "debrief" && !loggedBindings.has(bound)) {
|
|
4112
|
-
loggedBindings.add(bound);
|
|
4113
|
-
info(
|
|
4114
|
-
`[werewolf-evolution] DEBRIEF_BOUND debriefId=${field(bound.inbound.envelope.debriefId)} runId=${field(bound.runId)} sessionKey=${field(bound.sessionKey)} agentId=${field(bound.agentId)}`
|
|
4115
|
-
);
|
|
4116
|
-
}
|
|
4117
|
-
if (!bound && event.prompt.includes(DEBRIEF_HEADER)) {
|
|
4118
|
-
api.logger.warn(
|
|
4119
|
-
`[werewolf-evolution] DEBRIEF_BIND_MISS runId=${ctx.runId ?? "unknown"} sessionKey=${ctx.sessionKey ?? "unknown"} agentId=${ctx.agentId ?? "unknown"}`
|
|
4120
|
-
);
|
|
4121
|
-
}
|
|
4122
|
-
const promptContext = service.buildPromptContext(ctx);
|
|
4123
|
-
if (bound?.inbound.kind === "debrief" && bound.terminalDiagnostic) {
|
|
4124
|
-
logTerminal(bound, {
|
|
4125
|
-
debriefId: bound.inbound.envelope.debriefId,
|
|
4126
|
-
runId: bound.runId
|
|
4127
|
-
}, bound.terminalDiagnostic);
|
|
4128
|
-
}
|
|
4129
|
-
return promptContext;
|
|
4130
|
-
});
|
|
4131
|
-
api.on("before_tool_call", (event, ctx) => service.beforeToolCall(event, ctx));
|
|
4132
|
-
api.on("message_sending", (event, ctx) => service.isSystemDebriefMessage(event, ctx) ? { cancel: true } : void 0);
|
|
4133
|
-
api.on("agent_end", (event, ctx) => {
|
|
4134
|
-
const finished = service.finishRun({
|
|
4135
|
-
runId: event.runId ?? ctx.runId,
|
|
4136
|
-
sessionKey: ctx.sessionKey,
|
|
4137
|
-
success: event.success
|
|
4138
|
-
});
|
|
4139
|
-
if (finished?.terminalCreated && finished.bound.inbound.kind === "debrief") {
|
|
4140
|
-
logTerminal(finished.bound, {
|
|
4141
|
-
debriefId: finished.bound.inbound.envelope.debriefId,
|
|
4142
|
-
runId: finished.bound.runId
|
|
4143
|
-
}, finished.bound.terminalDiagnostic);
|
|
4144
|
-
}
|
|
4145
|
-
});
|
|
4146
|
-
}
|
|
4147
|
-
var entry = definePluginEntry({
|
|
4148
|
-
id: "werewolf-evolution",
|
|
4149
|
-
name: "Werewolf Evolution",
|
|
4150
|
-
description: "Validates and atomically commits Werewolf Play postgame evolution proposals.",
|
|
4151
|
-
configSchema: emptyPluginConfigSchema(),
|
|
4152
|
-
register(api) {
|
|
4153
|
-
registerWerewolfEvolution(api);
|
|
4154
|
-
}
|
|
4155
|
-
});
|
|
4156
|
-
var index_default = entry;
|
|
4157
|
-
export {
|
|
4158
|
-
index_default as default,
|
|
4159
|
-
registerWerewolfEvolution
|
|
4160
|
-
};
|