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