@clawtopia/werewolf-evolution 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/setup.d.ts DELETED
@@ -1,54 +0,0 @@
1
- #!/usr/bin/env node
2
- import { z } from 'zod';
3
-
4
- declare const migrationMarkerSchema: z.ZodObject<{
5
- schemaVersion: z.ZodLiteral<1>;
6
- migrationVersion: z.ZodLiteral<3>;
7
- evolutionVersion: z.ZodString;
8
- skillVersion: z.ZodString;
9
- migratedAt: z.ZodString;
10
- legacyGameIds: z.ZodArray<z.ZodString>;
11
- sources: z.ZodArray<z.ZodObject<{
12
- kind: z.ZodEnum<{
13
- evidence: "evidence";
14
- suggestions: "suggestions";
15
- }>;
16
- sourcePath: z.ZodString;
17
- archivePath: z.ZodString;
18
- sha256: z.ZodString;
19
- bytes: z.ZodNumber;
20
- recognized: z.ZodBoolean;
21
- }, z.core.$strict>>;
22
- skillBackup: z.ZodOptional<z.ZodString>;
23
- warnings: z.ZodArray<z.ZodString>;
24
- }, z.core.$strict>;
25
- type MigrationMarker = z.infer<typeof migrationMarkerSchema>;
26
- interface MigrationResult {
27
- status: "migrated" | "already-migrated";
28
- marker: MigrationMarker;
29
- markerPath: string;
30
- }
31
-
32
- interface SetupOptions {
33
- workspace: string;
34
- owner: string;
35
- transferFrom?: string;
36
- }
37
- interface SetupResult {
38
- version: string;
39
- workspaceDir: string;
40
- owner: string;
41
- configPath: string;
42
- configBackupPath: string;
43
- migration: MigrationResult;
44
- pluginInstalled: boolean;
45
- }
46
- interface SetupDependencies {
47
- run?: (command: string, args: readonly string[]) => string;
48
- now?: () => Date;
49
- version?: string;
50
- }
51
- declare function runSetup(options: SetupOptions, dependencies?: SetupDependencies): SetupResult;
52
- declare function parseSetupArgs(args: string[]): SetupOptions;
53
-
54
- export { type SetupDependencies, type SetupOptions, type SetupResult, parseSetupArgs, runSetup };
package/dist/setup.js DELETED
@@ -1,639 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- assertSafeWorkspacePath,
4
- assertWorkspaceOwner,
5
- assertWorkspaceRootIdentity,
6
- assertWorkspaceSetupReady,
7
- createOwnerBinding,
8
- getWerewolfEvolutionVersion,
9
- migrateWorkspace,
10
- normalizeOwnerSenderId,
11
- readOwnerBinding,
12
- readWorkspaceState,
13
- renderOwnerBinding,
14
- renderSuggestions,
15
- resolveWorkspacePaths,
16
- runWorkspaceSetupExclusive,
17
- runWorkspaceTransaction,
18
- verifyWorkspaceDocuments
19
- } from "./chunk-UZXHRLA6.js";
20
-
21
- // src/setup.ts
22
- import {
23
- closeSync,
24
- copyFileSync,
25
- existsSync as existsSync2,
26
- fsyncSync,
27
- lstatSync as lstatSync2,
28
- mkdirSync as mkdirSync2,
29
- mkdtempSync as mkdtempSync2,
30
- openSync,
31
- readFileSync,
32
- realpathSync,
33
- renameSync,
34
- rmSync as rmSync2,
35
- writeSync
36
- } from "fs";
37
- import { randomUUID } from "crypto";
38
- import { tmpdir as tmpdir2 } from "os";
39
- import path2 from "path";
40
- import { execFileSync } from "child_process";
41
- import { fileURLToPath } from "url";
42
- import { z } from "zod";
43
-
44
- // src/setup-snapshot.ts
45
- import {
46
- cpSync,
47
- existsSync,
48
- lstatSync,
49
- mkdirSync,
50
- mkdtempSync,
51
- readdirSync,
52
- rmSync
53
- } from "fs";
54
- import { tmpdir } from "os";
55
- import path from "path";
56
- var LEGACY_ARCHIVE = /^werewolf-(?:evidence|suggestions)-legacy-v2-[0-9]{8}T[0-9]{9}Z\.md$/;
57
- var SKILL_TRANSIENT = /^\.?werewolf-play\.(?:tmp|bak)-[0-9a-z]+$/i;
58
- function assertRegularTree(source) {
59
- const stat = lstatSync(source);
60
- if (stat.isSymbolicLink() || !stat.isFile() && !stat.isDirectory()) {
61
- throw new Error(`SETUP_SNAPSHOT_PATH_INVALID:${source}`);
62
- }
63
- if (stat.isDirectory()) {
64
- for (const entry of readdirSync(source)) assertRegularTree(path.join(source, entry));
65
- }
66
- }
67
- function copyPath(source, target) {
68
- const stat = lstatSync(source);
69
- assertRegularTree(source);
70
- mkdirSync(path.dirname(target), { recursive: true, mode: 448 });
71
- cpSync(source, target, {
72
- recursive: stat.isDirectory(),
73
- dereference: false,
74
- errorOnExist: true,
75
- force: false,
76
- preserveTimestamps: true,
77
- verbatimSymlinks: true
78
- });
79
- }
80
- function fixedTargets(paths) {
81
- return [
82
- paths.agents,
83
- paths.evidence,
84
- paths.incidents,
85
- paths.suggestions,
86
- paths.ownerBinding,
87
- paths.ledger,
88
- paths.legacyEvidenceV2,
89
- paths.legacySuggestions,
90
- paths.migrationMarker,
91
- paths.overrides,
92
- paths.customProfiles,
93
- paths.skill,
94
- paths.legacySkill,
95
- paths.backups
96
- ];
97
- }
98
- function existingSkillTransients(paths) {
99
- const skills = path.dirname(paths.skill);
100
- if (!existsSync(skills)) return [];
101
- return readdirSync(skills, { withFileTypes: true }).filter((entry) => SKILL_TRANSIENT.test(entry.name)).map((entry) => path.join(skills, entry.name));
102
- }
103
- function existingLegacyArchives(paths) {
104
- if (!existsSync(paths.memory)) return [];
105
- return readdirSync(paths.memory, { withFileTypes: true }).filter((entry) => entry.isFile() && LEGACY_ARCHIVE.test(entry.name)).map((entry) => path.join(paths.memory, entry.name));
106
- }
107
- function removeLegacyArchives(paths) {
108
- if (!existsSync(paths.memory)) return;
109
- for (const entry of readdirSync(paths.memory, { withFileTypes: true })) {
110
- if (entry.isFile() && LEGACY_ARCHIVE.test(entry.name)) {
111
- const target = path.join(paths.memory, entry.name);
112
- assertSafeWorkspacePath(target, paths);
113
- rmSync(target, { force: true });
114
- }
115
- }
116
- }
117
- function removeSkillTransients(paths) {
118
- const skills = path.dirname(paths.skill);
119
- if (!existsSync(skills)) return;
120
- assertSafeWorkspacePath(skills, paths);
121
- for (const entry of readdirSync(skills, { withFileTypes: true })) {
122
- if (!SKILL_TRANSIENT.test(entry.name)) continue;
123
- const target = path.join(skills, entry.name);
124
- assertSafeWorkspacePath(target, paths);
125
- rmSync(target, { recursive: true, force: true });
126
- }
127
- }
128
- function removeEmptyDirectory(directory) {
129
- if (existsSync(directory) && lstatSync(directory).isDirectory() && readdirSync(directory).length === 0) {
130
- rmSync(directory, { recursive: false });
131
- }
132
- }
133
- function captureSetupWorkspace(paths) {
134
- assertWorkspaceRootIdentity(paths);
135
- const temporaryRoot = mkdtempSync(path.join(tmpdir(), "werewolf-evolution-setup-"));
136
- try {
137
- const targets = [
138
- ...fixedTargets(paths),
139
- ...existingLegacyArchives(paths),
140
- ...existingSkillTransients(paths)
141
- ];
142
- const entries = targets.map((target, index) => {
143
- const snapshot = path.join(temporaryRoot, String(index));
144
- const existed = existsSync(target);
145
- if (existed) copyPath(target, snapshot);
146
- return { target, snapshot, existed };
147
- });
148
- return {
149
- temporaryRoot,
150
- entries,
151
- memoryExisted: existsSync(paths.memory),
152
- skillsExisted: existsSync(path.dirname(paths.skill))
153
- };
154
- } catch (error) {
155
- rmSync(temporaryRoot, { recursive: true, force: true });
156
- throw error;
157
- }
158
- }
159
- function restoreSetupWorkspace(paths, snapshot) {
160
- assertSafeWorkspacePath(paths.memory, paths);
161
- assertSafeWorkspacePath(path.dirname(paths.skill), paths);
162
- removeLegacyArchives(paths);
163
- removeSkillTransients(paths);
164
- for (const entry of snapshot.entries) {
165
- assertSafeWorkspacePath(entry.target, paths);
166
- rmSync(entry.target, { recursive: true, force: true });
167
- if (entry.existed) copyPath(entry.snapshot, entry.target);
168
- }
169
- if (!snapshot.skillsExisted) removeEmptyDirectory(path.dirname(paths.skill));
170
- if (!snapshot.memoryExisted) removeEmptyDirectory(paths.memory);
171
- }
172
- function disposeSetupWorkspaceSnapshot(snapshot) {
173
- rmSync(snapshot.temporaryRoot, { recursive: true, force: true });
174
- }
175
-
176
- // src/setup.ts
177
- var OWNER = /^(clawtopia|coolclaw):human:([0-9]+)$/;
178
- var REQUIRED_TOOLS = ["werewolf_debrief_commit", "werewolf_suggestion_decide"];
179
- var REQUIRED_HOOKS = [
180
- "before_agent_run",
181
- "before_prompt_build",
182
- "before_tool_call",
183
- "message_received"
184
- ];
185
- function defaultRun(command, args) {
186
- return execFileSync(command, [...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
187
- }
188
- function expandHome(value) {
189
- if (value === "~") return process.env.HOME ?? value;
190
- if (value.startsWith("~/")) return path2.join(process.env.HOME ?? "~", value.slice(2));
191
- return value;
192
- }
193
- function readJsonCommand(run, args) {
194
- return JSON.parse(run("openclaw", args));
195
- }
196
- function readOptionalConfig(run, configPath) {
197
- try {
198
- return readJsonCommand(run, ["config", "get", configPath, "--json"]);
199
- } catch (error) {
200
- if (/Config path not found:/i.test(errorText(error))) return void 0;
201
- throw error;
202
- }
203
- }
204
- function explicitOwners(value) {
205
- if (value === void 0) return [];
206
- if (!Array.isArray(value)) throw new Error("OWNER_ALLOWLIST_INVALID");
207
- const owners = value.map((entry) => String(entry ?? "").trim()).filter(Boolean);
208
- if (owners.length !== value.length) throw new Error("OWNER_ALLOWLIST_INVALID");
209
- return owners;
210
- }
211
- function validateOwnerConfiguration(owner, owners) {
212
- const match = OWNER.exec(owner);
213
- if (!match || match[2] === "0") throw new Error("--owner must be clawtopia:human:<non-zero-id> or coolclaw:human:<non-zero-id>.");
214
- const channel = match[1];
215
- const lowered = owners.map((entry) => entry.toLowerCase());
216
- if (lowered.some((entry) => entry === "*" || entry === `${channel}:*`)) {
217
- throw new Error("commands.ownerAllowFrom contains a wildcard for this channel; remove it before setup.");
218
- }
219
- return lowered.includes(owner.toLowerCase()) ? owners : [...owners, owner];
220
- }
221
- function validateOwnerTransition(existing, owner, transferFrom) {
222
- if (!existing) {
223
- if (transferFrom) throw new Error("WORKSPACE_OWNER_TRANSFER_SOURCE_UNEXPECTED");
224
- return;
225
- }
226
- if (existing.ownerSenderId === owner) {
227
- if (transferFrom && transferFrom !== existing.ownerSenderId) {
228
- throw new Error("WORKSPACE_OWNER_TRANSFER_SOURCE_MISMATCH");
229
- }
230
- return;
231
- }
232
- if (!transferFrom) throw new Error("WORKSPACE_OWNER_MISMATCH: use --transfer-from with the current Owner");
233
- if (transferFrom !== existing.ownerSenderId) throw new Error("WORKSPACE_OWNER_TRANSFER_SOURCE_MISMATCH");
234
- }
235
- function bindWorkspaceOwner(paths, owner, transferFrom, now, setupLock) {
236
- runWorkspaceTransaction(paths, () => {
237
- const existing = readOwnerBinding(paths);
238
- validateOwnerTransition(existing, owner, transferFrom);
239
- if (existing?.ownerSenderId === owner) return { changes: /* @__PURE__ */ new Map(), result: void 0 };
240
- const changes = /* @__PURE__ */ new Map([
241
- [paths.ownerBinding, renderOwnerBinding(createOwnerBinding(owner, now))]
242
- ]);
243
- if (existing) {
244
- const state = readWorkspaceState(paths);
245
- let remindersChanged = false;
246
- for (const suggestion of state.suggestions.suggestions) {
247
- if (suggestion.status === "pending" && suggestion.reminderSentAt) {
248
- delete suggestion.reminderSentAt;
249
- remindersChanged = true;
250
- }
251
- }
252
- if (remindersChanged) changes.set(paths.suggestions, renderSuggestions(state.suggestions));
253
- }
254
- return {
255
- changes,
256
- result: void 0,
257
- verify: () => {
258
- assertWorkspaceOwner(paths, owner);
259
- verifyWorkspaceDocuments(paths);
260
- }
261
- };
262
- }, {}, setupLock);
263
- }
264
- function resolveConfigPath(configPathOutput) {
265
- const candidate = path2.resolve(expandHome(configPathOutput.trim()));
266
- if (!existsSync2(candidate)) throw new Error(`OpenClaw config does not exist: ${candidate}`);
267
- const stat = lstatSync2(candidate);
268
- if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("OpenClaw config must be a regular non-symlink file.");
269
- return realpathSync(candidate);
270
- }
271
- function backupConfig(configPath, now) {
272
- const stamp = now.toISOString().replace(/[-:.]/g, "");
273
- let backupPath = `${configPath}.werewolf-evolution-${stamp}.bak`;
274
- for (let suffix = 2; existsSync2(backupPath); suffix += 1) {
275
- backupPath = `${configPath}.werewolf-evolution-${stamp}-${suffix}.bak`;
276
- }
277
- copyFileSync(configPath, backupPath);
278
- return { configPath, backupPath };
279
- }
280
- var CONFIG_SETUP_LOCK_MAX_AGE_MS = 10 * 60 * 1e3;
281
- function processIsAlive(pid) {
282
- try {
283
- process.kill(pid, 0);
284
- return true;
285
- } catch (error) {
286
- return error.code !== "ESRCH";
287
- }
288
- }
289
- function readConfigSetupLock(file) {
290
- const stat = lstatSync2(file);
291
- if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("CONFIG_SETUP_LOCK_INVALID");
292
- const parsed = z.object({
293
- pid: z.number().int().positive(),
294
- token: z.string().uuid(),
295
- createdAt: z.number().int().nonnegative()
296
- }).strict().safeParse(JSON.parse(readFileSync(file, "utf8")));
297
- if (!parsed.success) throw new Error("CONFIG_SETUP_LOCK_INVALID");
298
- return parsed.data;
299
- }
300
- function acquireConfigSetupLock(configPath, now) {
301
- const file = `${configPath}.werewolf-evolution-setup.lock`;
302
- if (existsSync2(file)) {
303
- const existing = readConfigSetupLock(file);
304
- if (now - existing.createdAt < CONFIG_SETUP_LOCK_MAX_AGE_MS || processIsAlive(existing.pid)) {
305
- throw new Error("CONFIG_SETUP_LOCKED");
306
- }
307
- const quarantine = `${file}.stale-${existing.token}`;
308
- rmSync2(quarantine, { force: true });
309
- realpathSync(path2.dirname(file));
310
- renameSync(file, quarantine);
311
- const quarantined = readConfigSetupLock(quarantine);
312
- if (quarantined.token !== existing.token) {
313
- if (!existsSync2(file)) renameSync(quarantine, file);
314
- throw new Error("CONFIG_SETUP_LOCK_CHANGED");
315
- }
316
- rmSync2(quarantine, { force: true });
317
- }
318
- const token = randomUUID();
319
- try {
320
- const fd = openSync(file, "wx", 384);
321
- writeSync(fd, JSON.stringify({ pid: process.pid, token, createdAt: now }));
322
- fsyncSync(fd);
323
- return { fd, file, token };
324
- } catch (error) {
325
- if (error.code === "EEXIST") throw new Error("CONFIG_SETUP_LOCKED");
326
- throw error;
327
- }
328
- }
329
- function releaseConfigSetupLock(lock) {
330
- try {
331
- closeSync(lock.fd);
332
- } finally {
333
- try {
334
- if (readConfigSetupLock(lock.file).token === lock.token) rmSync2(lock.file, { force: true });
335
- } catch {
336
- }
337
- }
338
- }
339
- function restoreConfigBackup(config) {
340
- for (const file of [config.configPath, config.backupPath]) {
341
- if (!existsSync2(file)) throw new Error(`CONFIG_ROLLBACK_FILE_MISSING:${file}`);
342
- const stat = lstatSync2(file);
343
- if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`CONFIG_ROLLBACK_PATH_INVALID:${file}`);
344
- }
345
- if (realpathSync(config.configPath) !== config.configPath) throw new Error("CONFIG_ROLLBACK_PATH_CHANGED");
346
- copyFileSync(config.backupPath, config.configPath);
347
- rmSync2(config.backupPath, { force: true });
348
- }
349
- function verifySkillMeta(workspace, version) {
350
- const paths = typeof workspace === "string" ? resolveWorkspacePaths(workspace) : workspace;
351
- assertWorkspaceRootIdentity(paths);
352
- const skill = path2.join(paths.skill, "SKILL.md");
353
- const meta = path2.join(paths.skill, "_meta.json");
354
- if (!existsSync2(skill) || !lstatSync2(skill).isFile() || lstatSync2(skill).isSymbolicLink()) {
355
- throw new Error("WEREWOLF_PLAY_SKILL_MISSING");
356
- }
357
- if (!existsSync2(meta) || !lstatSync2(meta).isFile() || lstatSync2(meta).isSymbolicLink()) {
358
- throw new Error("WEREWOLF_PLAY_META_MISSING");
359
- }
360
- const parsed = z.object({ version: z.literal(version) }).passthrough().safeParse(
361
- JSON.parse(readFileSync(meta, "utf8"))
362
- );
363
- if (!parsed.success) throw new Error("WEREWOLF_PLAY_VERSION_MISMATCH");
364
- }
365
- function preflightSkillPackage(run, version) {
366
- const root = mkdtempSync2(path2.join(tmpdir2(), "werewolf-play-preflight-"));
367
- try {
368
- mkdirSync2(path2.join(root, "memory"), { recursive: true });
369
- run("npx", ["-y", `@clawtopia/werewolf-play@${version}`, "--workspace", root]);
370
- verifySkillMeta(root, version);
371
- } finally {
372
- rmSync2(root, { recursive: true, force: true });
373
- }
374
- }
375
- function runtimePluginInspection(run) {
376
- return readJsonCommand(run, ["plugins", "inspect", "werewolf-evolution", "--runtime", "--json"]);
377
- }
378
- function installedPluginMatches(value, version) {
379
- const parsed = z.object({
380
- plugin: z.object({
381
- id: z.literal("werewolf-evolution"),
382
- packageName: z.literal("@clawtopia/werewolf-evolution"),
383
- version: z.literal(version)
384
- }).passthrough()
385
- }).passthrough().safeParse(value);
386
- return parsed.success;
387
- }
388
- var NPM_PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
389
- var EXACT_SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
390
- function priorPluginInventory(run) {
391
- const raw = readJsonCommand(run, ["plugins", "inspect", "--all", "--json"]);
392
- const parsed = z.array(z.object({
393
- plugin: z.object({
394
- id: z.string().min(1),
395
- packageName: z.string().min(1).optional(),
396
- version: z.string().min(1).optional()
397
- }).passthrough(),
398
- install: z.unknown().optional()
399
- }).passthrough()).safeParse(raw);
400
- if (!parsed.success) throw new Error(`PLUGIN_INVENTORY_INVALID:${parsed.error.message}`);
401
- const matches = parsed.data.filter((entry2) => entry2.plugin.id === "werewolf-evolution");
402
- if (matches.length === 0) return { kind: "absent" };
403
- if (matches.length !== 1) throw new Error("PLUGIN_INVENTORY_DUPLICATED:werewolf-evolution");
404
- const entry = matches[0];
405
- const install = z.object({
406
- source: z.literal("npm"),
407
- resolvedName: z.string().regex(NPM_PACKAGE_NAME),
408
- resolvedVersion: z.string().regex(EXACT_SEMVER)
409
- }).passthrough().safeParse(entry.install);
410
- if (!install.success) throw new Error("PRIOR_PLUGIN_NOT_RESTORABLE:werewolf-evolution");
411
- if (entry.plugin.packageName !== install.data.resolvedName || entry.plugin.version !== install.data.resolvedVersion) {
412
- throw new Error("PRIOR_PLUGIN_INSTALL_RECORD_MISMATCH:werewolf-evolution");
413
- }
414
- return {
415
- kind: "npm",
416
- inspection: entry,
417
- restoreSpec: `${install.data.resolvedName}@${install.data.resolvedVersion}`
418
- };
419
- }
420
- function rollbackPlugin(run, prior) {
421
- if (prior.kind === "npm") {
422
- run("openclaw", [
423
- "plugins",
424
- "install",
425
- "--force",
426
- "--pin",
427
- prior.restoreSpec
428
- ]);
429
- return;
430
- }
431
- run("openclaw", ["plugins", "uninstall", "--force", "werewolf-evolution"]);
432
- }
433
- function errorText(error) {
434
- return error instanceof Error ? error.message : String(error);
435
- }
436
- function verifyPluginInspection(value, version) {
437
- const parsed = z.object({
438
- plugin: z.object({
439
- id: z.literal("werewolf-evolution"),
440
- packageName: z.literal("@clawtopia/werewolf-evolution"),
441
- version: z.literal(version),
442
- enabled: z.literal(true),
443
- status: z.literal("loaded"),
444
- toolNames: z.array(z.string()),
445
- hookNames: z.array(z.string())
446
- }).passthrough()
447
- }).passthrough().safeParse(value);
448
- if (!parsed.success) throw new Error(`WEREWOLF_EVOLUTION_INSPECTION_INVALID:${parsed.error.message}`);
449
- for (const tool of REQUIRED_TOOLS) {
450
- if (!parsed.data.plugin.toolNames.includes(tool)) throw new Error(`WEREWOLF_EVOLUTION_TOOL_MISSING:${tool}`);
451
- }
452
- for (const hook of REQUIRED_HOOKS) {
453
- if (!parsed.data.plugin.hookNames.includes(hook)) throw new Error(`WEREWOLF_EVOLUTION_HOOK_MISSING:${hook}`);
454
- }
455
- }
456
- function verifyFinalConfig(run, owner) {
457
- const owners = explicitOwners(readOptionalConfig(run, "commands.ownerAllowFrom"));
458
- const expected = validateOwnerConfiguration(owner, owners);
459
- if (expected.length !== owners.length) throw new Error("OWNER_CONFIGURATION_NOT_APPLIED");
460
- for (const pathName of [
461
- "plugins.entries.werewolf-evolution.enabled",
462
- "plugins.entries.werewolf-evolution.hooks.allowConversationAccess",
463
- "plugins.entries.werewolf-evolution.hooks.allowPromptInjection"
464
- ]) {
465
- if (readOptionalConfig(run, pathName) !== true) throw new Error(`PLUGIN_CONFIGURATION_NOT_APPLIED:${pathName}`);
466
- }
467
- }
468
- function runSetup(options, dependencies = {}) {
469
- const run = dependencies.run ?? defaultRun;
470
- const version = dependencies.version ?? getWerewolfEvolutionVersion();
471
- if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) throw new Error("EVOLUTION_VERSION_INVALID");
472
- const owner = options.owner.trim().toLowerCase();
473
- const transferFrom = options.transferFrom === void 0 ? void 0 : normalizeOwnerSenderId(options.transferFrom);
474
- const paths = resolveWorkspacePaths(path2.resolve(expandHome(options.workspace)), false);
475
- run("openclaw", ["config", "validate"]);
476
- const now = dependencies.now?.() ?? /* @__PURE__ */ new Date();
477
- return runWorkspaceSetupExclusive(paths, now.getTime(), (setupLock) => {
478
- const configPath = resolveConfigPath(run("openclaw", ["config", "file"]));
479
- const configLock = acquireConfigSetupLock(configPath, now.getTime());
480
- try {
481
- run("openclaw", ["config", "validate"]);
482
- const owners = explicitOwners(readOptionalConfig(run, "commands.ownerAllowFrom"));
483
- const nextOwners = validateOwnerConfiguration(owner, owners);
484
- validateOwnerTransition(readOwnerBinding(paths), owner, transferFrom);
485
- const prior = priorPluginInventory(run);
486
- preflightSkillPackage(run, version);
487
- const config = backupConfig(configPath, now);
488
- let snapshot;
489
- let pluginMutationAttempted = false;
490
- try {
491
- snapshot = captureSetupWorkspace(paths);
492
- const migration = migrateWorkspace(paths, { version, now, setupLock });
493
- assertWorkspaceRootIdentity(paths);
494
- run("npx", [
495
- "-y",
496
- `@clawtopia/werewolf-play@${version}`,
497
- "--workspace",
498
- paths.root,
499
- "--expected-workspace-device",
500
- String(paths.rootDevice),
501
- "--expected-workspace-inode",
502
- String(paths.rootInode)
503
- ]);
504
- verifySkillMeta(paths, version);
505
- bindWorkspaceOwner(paths, owner, transferFrom, now, setupLock);
506
- const pluginInstalled = !installedPluginMatches(prior.inspection, version);
507
- if (pluginInstalled) {
508
- pluginMutationAttempted = true;
509
- run("openclaw", [
510
- "plugins",
511
- "install",
512
- "--force",
513
- "--pin",
514
- `@clawtopia/werewolf-evolution@${version}`
515
- ]);
516
- }
517
- const updates = [
518
- { path: "commands.ownerAllowFrom", value: nextOwners },
519
- { path: "plugins.entries.werewolf-evolution.enabled", value: true },
520
- { path: "plugins.entries.werewolf-evolution.hooks.allowConversationAccess", value: true },
521
- { path: "plugins.entries.werewolf-evolution.hooks.allowPromptInjection", value: true }
522
- ];
523
- const batch = JSON.stringify(updates);
524
- run("openclaw", ["config", "set", "--batch-json", batch, "--dry-run"]);
525
- run("openclaw", ["config", "set", "--batch-json", batch]);
526
- run("openclaw", ["config", "validate"]);
527
- verifyFinalConfig(run, owner);
528
- verifyPluginInspection(runtimePluginInspection(run), version);
529
- assertWorkspaceSetupReady(paths, version);
530
- assertWorkspaceOwner(paths, owner);
531
- disposeSetupWorkspaceSnapshot(snapshot);
532
- snapshot = void 0;
533
- return {
534
- version,
535
- workspaceDir: paths.root,
536
- owner,
537
- configPath: config.configPath,
538
- configBackupPath: config.backupPath,
539
- migration,
540
- pluginInstalled
541
- };
542
- } catch (error) {
543
- const rollbackErrors = [];
544
- if (snapshot) {
545
- try {
546
- restoreSetupWorkspace(paths, snapshot);
547
- disposeSetupWorkspaceSnapshot(snapshot);
548
- snapshot = void 0;
549
- } catch (rollbackError) {
550
- rollbackErrors.push(`workspace:${errorText(rollbackError)}`);
551
- }
552
- }
553
- if (pluginMutationAttempted) {
554
- try {
555
- rollbackPlugin(run, prior);
556
- } catch (rollbackError) {
557
- rollbackErrors.push(`plugin:${errorText(rollbackError)}`);
558
- }
559
- }
560
- try {
561
- restoreConfigBackup(config);
562
- } catch (rollbackError) {
563
- rollbackErrors.push(`config:${errorText(rollbackError)}`);
564
- }
565
- if (rollbackErrors.length > 0) {
566
- throw new Error(`SETUP_FAILED:${errorText(error)};ROLLBACK_FAILED:${rollbackErrors.join("|")}`, {
567
- cause: error
568
- });
569
- }
570
- throw error;
571
- }
572
- } finally {
573
- releaseConfigSetupLock(configLock);
574
- }
575
- });
576
- }
577
- function parseSetupArgs(args) {
578
- if (args[0] !== "setup") throw new Error("Expected the setup command.");
579
- let workspace;
580
- let owner;
581
- let transferFrom;
582
- for (let index = 1; index < args.length; index += 1) {
583
- const argument = args[index];
584
- const assign = (name, value) => {
585
- const flag = name === "transferFrom" ? "transfer-from" : name;
586
- if (!value || value.startsWith("--")) throw new Error(`--${flag} requires a value.`);
587
- if (name === "workspace") workspace = value;
588
- else if (name === "owner") owner = value;
589
- else transferFrom = value;
590
- };
591
- if (argument === "--workspace" || argument === "--owner" || argument === "--transfer-from") {
592
- const name = argument === "--transfer-from" ? "transferFrom" : argument.slice(2);
593
- assign(name, args[index + 1]);
594
- index += 1;
595
- continue;
596
- }
597
- if (argument.startsWith("--workspace=")) {
598
- assign("workspace", argument.slice("--workspace=".length));
599
- continue;
600
- }
601
- if (argument.startsWith("--owner=")) {
602
- assign("owner", argument.slice("--owner=".length));
603
- continue;
604
- }
605
- if (argument.startsWith("--transfer-from=")) {
606
- assign("transferFrom", argument.slice("--transfer-from=".length));
607
- continue;
608
- }
609
- throw new Error(`Unknown argument: ${argument}`);
610
- }
611
- if (!workspace) throw new Error("--workspace is required.");
612
- if (!owner) throw new Error("--owner is required.");
613
- return { workspace, owner, ...transferFrom ? { transferFrom } : {} };
614
- }
615
- function main() {
616
- try {
617
- const result = runSetup(parseSetupArgs(process.argv.slice(2)));
618
- console.log(`[werewolf-evolution] Installed v${result.version} for ${result.workspaceDir}`);
619
- console.log(`[werewolf-evolution] Owner: ${result.owner}`);
620
- console.log(`[werewolf-evolution] Config backup: ${result.configBackupPath}`);
621
- console.log("[werewolf-evolution] Restart the OpenClaw gateway before the next debrief.");
622
- } catch (error) {
623
- console.error(`[werewolf-evolution] Setup failed: ${error instanceof Error ? error.message : String(error)}`);
624
- process.exitCode = 1;
625
- }
626
- }
627
- function isInvokedAsScript() {
628
- if (!process.argv[1]) return false;
629
- try {
630
- return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
631
- } catch {
632
- return false;
633
- }
634
- }
635
- if (isInvokedAsScript()) main();
636
- export {
637
- parseSetupArgs,
638
- runSetup
639
- };