@plaiful/cli 0.6.0 → 0.8.0

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.
Files changed (3) hide show
  1. package/README.md +138 -130
  2. package/package.json +21 -21
  3. package/src/cli.js +1278 -1120
package/src/cli.js CHANGED
@@ -1,1120 +1,1278 @@
1
- 'use strict';
2
-
3
- /**
4
- * The Plaiful CLI (PlaifulCMS docs/system/product/PARTNER_API_AND_CLI.md §4). Every command talks to the partner API
5
- * as the signed-in person; nothing needs AWS. `--json` prints the API's answer as JSON, for agents.
6
- *
7
- * Exit codes: 0 done; 1 the platform said no (invalid, denied, not signed in); 2 the command was wrong.
8
- */
9
-
10
- const fs = require('fs');
11
- const path = require('path');
12
- const { spawn, spawnSync } = require('child_process');
13
- const config = require('./config');
14
- const { version } = require('../package.json');
15
-
16
- const HELP = `plaiful ${version}: work on your Plaiful product from your game repo
17
-
18
- plaiful login sign in (opens the CMS to approve; 12 hours)
19
- plaiful logout sign out
20
- plaiful whoami who you're signed in as, your studio, and the products you may manage
21
- plaiful init [product] write .plaiful.json in this repo (product, env, docsDir) and make the folders
22
- your files go in (resources/world/<product>/, …), each with a README
23
- plaiful docs the platform docs (live): each doc, its summary, when it last changed
24
- plaiful docs read <doc> one doc, current (--section "3.5" or a heading for one section)
25
- plaiful docs search <words...> where the docs say it: each doc's best sections, with a snippet
26
- plaiful docs changes [--since <date>] the docs changed since a date (default: the last 7 days)
27
- plaiful docs pull write your product's own files (client-config.md) into docsDir; the platform
28
- docs stay live (--copies also writes local copies, for offline work)
29
- plaiful mcp an MCP server on stdio with the docs tools, signed in as you
30
- (claude mcp add plaiful -- plaiful mcp)
31
- plaiful ovid check [file] check your OVID declaration (default: <docsDir>/<product>-ovid-declaration.json)
32
- plaiful ovid publish [file] check it and publish it; OVID reads it within about 5 minutes
33
- plaiful ovid show the declaration OVID has now
34
- plaiful seed world|lore|map|personas [paths] dry run: the rows your files make and what changes in dev
35
- (default: every .json in resources/<store>/<product>/; personas = THESPIS
36
- personas and situations)
37
- --apply write them; --reset also put runtime state back to the files
38
- --rows print every row
39
- plaiful status what OVID and THESPIS have for your product in dev
40
- plaiful quests the quests OVID wrote: steps and what each pays (--track <id>, --series <id>)
41
- plaiful quests show <id> one quest: its graph, steps, reward hint and price (--json: the whole record)
42
- plaiful lore the lore sets, with known / hidden snippet counts
43
- plaiful lore show <setId> one set's snippets
44
- plaiful world the world's states and state events in story order, and the clock
45
- plaiful lists your product's SSM lists (NPC roles, SmartBuilder list values, ...)
46
- plaiful lists get <name> one list (a name in your namespace, e.g. shop_type, or the full /path)
47
- plaiful lists set <name> <values...> write a list (values as words, or one comma-separated argument)
48
- plaiful agents your product's SmartBuilder agents in dev
49
- plaiful agents show <name> one agent's deployed config
50
- plaiful agents deploy [files...] deploy or redeploy agents from their config files (default: every .json in
51
- resources/agents/<product>/); a redeploy keeps the agent's own settings
52
- plaiful agents run <name> [key=value...] make one record (placeholder values as key=value)
53
- plaiful agents batch <name> [file] start a batch (a batch body file, or --count <n>) → a job id
54
- plaiful agents status <name> <jobId> a batch's progress
55
- plaiful records import <agent> [file] dry run: records you wrote, into the agent's table (default file:
56
- resources/records/<product>/<agent>.json; matched on the agent's duplicate field)
57
- --apply write them; --no-render don't make new records' art or sound
58
- plaiful midas pricing what MIDAS pays per quest, in your reward kinds (delivered in each quest's rewards)
59
- plaiful midas pricing set <kind> --base <n> --per-effort <n> price a kind (either option alone keeps the other)
60
- plaiful midas pricing unset <kind> stop pricing a kind
61
- plaiful midas pricing weight <step> <n> how much a quest step counts (combat, gather, explore, ...)
62
- plaiful midas pricing apply [file] replace it all from a file (default:
63
- resources/midas/<product>/quest-pricing.json; { kinds, objective_weights, ... })
64
- plaiful assets per agent: records, and how many have their art made, pending, failed or none
65
- plaiful assets <agent> its records: state, why a render failed, where the files are
66
- --state made|pending|failed|none --limit <n> (default 50)
67
- plaiful upload <files...> upload map tiles into your dev assets bucket (map-data/; --dest map-data)
68
- plaiful clone [product] [dir] clone the game repo, write .env.development, docs pull, npm install, open Zed
69
- --no-install --no-open
70
- plaiful env (re)write .env.development from your dev client config (keeps your own lines)
71
-
72
- Options: --json (machine-readable output) --product <id> --api <url> --no-browser (login)
73
- Environment: PLAIFUL_API_URL, PLAIFUL_TOKEN (instead of login: CI, with a product API key from the CMS)
74
- Docs: docs/plaiful/README.md after \`plaiful docs pull\``;
75
-
76
- class UsageError extends Error {}
77
- class ApiError extends Error {
78
- constructor(status, body) {
79
- super((body && body.error) || `the platform answered ${status}`);
80
- this.status = status;
81
- this.body = body;
82
- }
83
- }
84
-
85
- /** Where an agent list's values come from: an SSM path, or the values kept in the agent ({ values: [...] }). */
86
- function listSource(v) {
87
- if (v && typeof v === 'object' && Array.isArray(v.values)) return `in the agent (${v.values.length}: ${v.values.slice(0, 4).join(', ')}${v.values.length > 4 ? ', …' : ''})`;
88
- if (v && typeof v === 'object') return v.path || JSON.stringify(v);
89
- return String(v);
90
- }
91
-
92
- function parse(argv) {
93
- const flags = {};
94
- const args = [];
95
- for (let i = 0; i < argv.length; i += 1) {
96
- const a = argv[i];
97
- if (['--json', '--no-browser', '--help', '-h', '--version', '--apply', '--reset', '--rows', '--no-install', '--no-open', '--copies', '--no-render'].includes(a)) flags[a.replace(/^-+/, '')] = true;
98
- else if (['--product', '--api', '--dir', '--dest', '--count', '--base', '--per-effort', '--track', '--series', '--state', '--limit', '--section', '--since'].includes(a)) {
99
- if (argv[i + 1] === undefined) throw new UsageError(`${a} needs a value`);
100
- flags[a.slice(2)] = argv[i += 1];
101
- } else if (a.startsWith('--')) throw new UsageError(`unknown option ${a}`);
102
- else args.push(a);
103
- }
104
- return { flags, args };
105
- }
106
-
107
- function makeContext(io, flags) {
108
- const url = config.apiUrl(flags);
109
- const out = (text, json) => io.stdout.write(`${flags.json ? JSON.stringify(json === undefined ? text : json, null, 2) : text}\n`);
110
- async function call(method, route, body, { auth = true } = {}) {
111
- const headers = { Accept: 'application/json' };
112
- if (body !== undefined) headers['Content-Type'] = 'application/json';
113
- if (auth) {
114
- const token = config.tokenFor(url);
115
- if (!token) throw new ApiError(401, { error: 'not signed in: run `plaiful login`', code: 'no_session' });
116
- headers.Authorization = `Bearer ${token}`;
117
- }
118
- let res;
119
- try {
120
- res = await io.fetch(`${url}${route}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
121
- } catch (e) {
122
- throw new ApiError(0, { error: `can't reach the Plaiful API at ${url} (${e.message})`, code: 'network' });
123
- }
124
- let data = {};
125
- try { data = await res.json(); } catch { /* empty body */ }
126
- if (!res.ok && !(res.status === 422 || (res.status === 409 && data.errors))) throw new ApiError(res.status, data);
127
- return { status: res.status, data };
128
- }
129
- return { url, flags, out, call, io };
130
- }
131
-
132
- function repo(ctx, { required = true } = {}) {
133
- const found = config.findRepoConfig(ctx.io.cwd());
134
- const product = ctx.flags.product || (found && found.config.product);
135
- if (required && !product) throw new UsageError('no product: run `plaiful init <product>` in your repo, or pass --product');
136
- const root = found ? found.root : ctx.io.cwd();
137
- const docsDir = path.resolve(root, ctx.flags.dir || (found && found.config.docsDir) || config.DEFAULT_DOCS_DIR);
138
- return { product, root, docsDir, found };
139
- }
140
-
141
- // ── Commands ────────────────────────────────────────────────────────────────────────────────────────────────────
142
-
143
- async function login(ctx) {
144
- const start = (await ctx.call('POST', '/partner/cli-login', undefined, { auth: false })).data;
145
- ctx.io.stderr.write(`\nTo sign in, open:\n\n ${start.verification_url}\n\nand check the code matches: ${start.user_code}\n\n`);
146
- if (!ctx.flags['no-browser']) ctx.io.openUrl(start.verification_url);
147
- const deadline = Date.now() + start.expires_in * 1000;
148
- let interval = (start.interval || 3) * 1000;
149
- while (Date.now() < deadline) {
150
- await ctx.io.sleep(interval);
151
- const r = (await ctx.call('POST', '/partner/cli-login/token', { device_code: start.device_code }, { auth: false })).data;
152
- if (r.status === 'approved') {
153
- config.writeCredentials({ api_url: ctx.url, token: r.token, email: r.email, expires_at: r.expires_at });
154
- ctx.out(`Signed in as ${r.email} until ${new Date(r.expires_at).toLocaleString()}.`, { success: true, email: r.email, expires_at: r.expires_at });
155
- return 0;
156
- }
157
- interval = (r.interval || 3) * 1000;
158
- }
159
- throw new ApiError(410, { error: 'the sign-in wasn\'t approved in time; run `plaiful login` again', code: 'expired' });
160
- }
161
-
162
- async function logout(ctx) {
163
- if (config.tokenFor(ctx.url)) {
164
- try { await ctx.call('POST', '/partner/logout'); } catch { /* the local sign-out is what matters */ }
165
- }
166
- config.clearCredentials();
167
- ctx.out('Signed out.', { success: true });
168
- return 0;
169
- }
170
-
171
- async function whoami(ctx) {
172
- const { data } = await ctx.call('GET', '/partner/whoami');
173
- const lines = data.key
174
- ? [`Product API key "${data.key.name}" for ${data.key.product} (${data.key.env}), issued by ${data.email}; scopes: ${data.key.scopes.join(', ')}`]
175
- : [`${data.email}${data.staff ? ' (Plaiful staff)' : ''}, signed in until ${new Date(data.session_expires_at).toLocaleString()}`];
176
- for (const st of data.studios || []) lines.push(`Studio: ${st.name} (${st.role}${st.preset ? `, ${st.preset}` : ''}${st.status !== 'active' ? `, ${st.status}` : ''})`);
177
- lines.push(data.products.length ? 'Products:' : 'No products yet: create one in the CMS (Product deployment), or ask its owner to share it.');
178
- for (const p of data.products) lines.push(` ${p.product_id} (${p.role})`);
179
- ctx.out(lines.join('\n'), data);
180
- return 0;
181
- }
182
-
183
- async function init(ctx, [product]) {
184
- const { data } = await ctx.call('GET', '/partner/whoami');
185
- const mine = data.products.map((p) => p.product_id);
186
- const chosen = product || ctx.flags.product || (mine.length === 1 ? mine[0] : null);
187
- if (!chosen) throw new UsageError(`which product? ${mine.length ? `yours: ${mine.join(', ')}` : 'you have none yet'} (plaiful init <product>)`);
188
- if (!mine.includes(chosen)) throw new ApiError(403, { error: `${data.email} can't manage "${chosen}"${mine.length ? ` (yours: ${mine.join(', ')})` : ''}`, code: 'product_access' });
189
- const existing = config.findRepoConfig(ctx.io.cwd());
190
- const root = existing ? existing.root : ctx.io.cwd();
191
- const next = { ...(existing ? existing.config : { env: 'dev', docsDir: config.DEFAULT_DOCS_DIR }), product: chosen };
192
- const file = config.writeRepoConfig(root, next);
193
- const made = makeLayout(root, chosen, next.docsDir);
194
- const lines = [`Wrote ${path.relative(ctx.io.cwd(), file) || file}: product ${chosen}, docs in ${next.docsDir}.`];
195
- if (made.length) lines.push(`Made ${made.length} folder(s): ${made.join(', ')}`);
196
- lines.push('Next: plaiful docs pull');
197
- ctx.out(lines.join('\n'), { success: true, file, config: next, made });
198
- return 0;
199
- }
200
-
201
- // ── Where things go (product-repo-template.md) ──────────────────────────────────────────────────────────────────
202
-
203
- /** The repo folders the platform's steps read from: [folder, what goes there]. */
204
- function layout(product, docsDir) {
205
- return [
206
- [`resources/${product}-resources`, 'SmartBuilder agent specs (one markdown file per agent, pasted into SmartBuilder)'],
207
- [`resources/agents/${product}`, 'agent configs as JSON, for plaiful agents deploy'],
208
- [`resources/records/${product}`, 'records you write by hand, one <agent>.json per agent, for plaiful records import'],
209
- [`resources/world/${product}`, 'the narrative scaffold, for plaiful seed world'],
210
- [`resources/lore/${product}`, 'lore sets, for plaiful seed lore'],
211
- [`resources/map/${product}`, 'places, for plaiful seed map'],
212
- [`resources/personas/${product}`, 'THESPIS personas and situations, for plaiful seed personas'],
213
- [`resources/midas/${product}`, 'quest-pricing.json, for plaiful midas pricing apply'],
214
- [docsDir, `the pulled docs, and your ${product}-ovid-declaration.json (plaiful ovid check / publish)`],
215
- ];
216
- }
217
-
218
- /** Agent specs (markdown with agent_name and prompt_template) outside resources/<product>-resources/, under docs/ or
219
- * resources/. → relative paths */
220
- function misplacedSpecs(root, product, docsDir) {
221
- const home = path.join(root, 'resources', `${product}-resources`);
222
- const out = [];
223
- const walk = (dir, depth) => {
224
- if (depth > 6 || !fs.existsSync(dir)) return;
225
- for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
226
- const full = path.join(dir, e.name);
227
- if (e.isDirectory()) {
228
- if (!['node_modules', '.git'].includes(e.name) && full !== home && full !== docsDir) walk(full, depth + 1);
229
- } else if (e.name.endsWith('.md')) {
230
- try {
231
- const text = fs.readFileSync(full, 'utf8');
232
- if (/\bagent_name\b/.test(text) && /\bprompt_template\b/.test(text)) out.push(path.relative(root, full).replace(/\\/g, '/'));
233
- } catch { /* unreadable: skip */ }
234
- }
235
- }
236
- };
237
- walk(path.join(root, 'docs'), 0);
238
- walk(path.join(root, 'resources'), 0);
239
- return out;
240
- }
241
-
242
- /** What to write in a folder's README when init makes it. */
243
- const folderReadme = (folder, what) => `# ${folder}\n\n${what[0].toUpperCase()}${what.slice(1)}.\nMade by \`plaiful init\`; see docs/plaiful/product-repo-template.md.\n`;
244
-
245
- /** The folders the platform's steps read from, each with a README saying what goes in it (an agent puts a file where
246
- * a folder for it already exists). → the folders made */
247
- function makeLayout(root, product, docsDir) {
248
- const made = [];
249
- for (const [folder, what] of layout(product, docsDir)) {
250
- const dir = path.join(root, folder);
251
- if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); made.push(folder); }
252
- const readme = path.join(dir, 'README.md');
253
- if (folder !== docsDir && !fs.existsSync(readme)) fs.writeFileSync(readme, folderReadme(folder, what));
254
- }
255
- return made;
256
- }
257
-
258
- function whereThingsGo(ctx, r) {
259
- const lines = ['Where things go:'];
260
- for (const [folder, what] of layout(r.product, path.relative(r.root, r.docsDir).replace(/\\/g, '/') || '.')) {
261
- lines.push(` ${folder.padEnd(32)} ${what}${fs.existsSync(path.join(r.root, folder)) ? '' : ' (missing: plaiful init makes it)'}`);
262
- }
263
- const wrong = misplacedSpecs(r.root, r.product, r.docsDir);
264
- if (wrong.length) {
265
- lines.push(`! Agent specs outside resources/${r.product}-resources/ (move them there):`);
266
- for (const f of wrong) lines.push(` ${f}`);
267
- }
268
- return { lines, misplaced: wrong };
269
- }
270
-
271
- const safeName = (key) => {
272
- const base = path.basename(String(key));
273
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\.md$/.test(base)) return null;
274
- return base;
275
- };
276
-
277
- // What docs pull leaves in docsDir when the platform docs are live (PLATFORM_DOCS_PORTAL.md §4).
278
- const LIVE_DOCS_README = `# Plaiful docs
279
-
280
- The platform docs are **live**, not copied here, so you always read the current version. Read them with the CLI, or
281
- with the plaiful MCP tools in your coding assistant:
282
-
283
- \`\`\`sh
284
- plaiful docs # every doc, and when it last changed
285
- plaiful docs read README # one doc (--section "3.5", or a heading, for one section)
286
- plaiful docs search "batch template" # where the docs say it
287
- plaiful docs changes --since 2026-10-20
288
- plaiful mcp # the same as MCP tools: claude mcp add plaiful -- plaiful mcp
289
- \`\`\`
290
-
291
- Start with \`plaiful docs read README\`. Read a doc again when you start a task; don't keep a copy.
292
-
293
- This folder holds your product's own files: \`client-config.md\` (your keys and endpoints: never commit it) and your
294
- \`<product>-ovid-declaration.json\`. Written by \`plaiful docs pull\`.
295
- `;
296
-
297
- async function docsPull(ctx, r = repo(ctx)) {
298
- const copies = !!ctx.flags.copies;
299
- const { data } = await ctx.call('GET', `/partner/${encodeURIComponent(r.product)}/docs${copies ? '' : '?docs=none'}`);
300
- fs.mkdirSync(r.docsDir, { recursive: true });
301
- const platform = copies ? (data.docs || []) : [];
302
- const files = [...platform, { key: data.client_config.key, title: 'Client config', content: data.client_config.content }];
303
- const result = { written: [], unchanged: [], skipped: [], removed: [] };
304
- // The platform-doc copies an earlier pull wrote ("replaced on every pull, never edit these"): gone, now they're live.
305
- const indexFile = path.join(r.docsDir, '.plaiful-docs.json');
306
- let before = [];
307
- try { before = (JSON.parse(fs.readFileSync(indexFile, 'utf8')).docs || []).map((d) => d.file).filter(Boolean); } catch { before = []; }
308
- const keep = new Set(files.map((f) => safeName(f.key)).filter(Boolean));
309
- if (!copies) keep.add('README.md');
310
- for (const name of before) {
311
- const safe = safeName(name);
312
- if (safe && !keep.has(safe) && fs.existsSync(path.join(r.docsDir, safe))) { fs.unlinkSync(path.join(r.docsDir, safe)); result.removed.push(safe); }
313
- }
314
- if (!copies) files.push({ key: 'README.md', title: 'Plaiful docs (live)', content: LIVE_DOCS_README });
315
- for (const f of files) {
316
- const name = safeName(f.key);
317
- if (!name) { result.skipped.push(f.key); continue; }
318
- const target = path.join(r.docsDir, name);
319
- const prev = fs.existsSync(target) ? fs.readFileSync(target, 'utf8') : null;
320
- if (prev === f.content) { result.unchanged.push(name); continue; }
321
- fs.writeFileSync(target, f.content);
322
- result.written.push(name);
323
- }
324
- const index = {
325
- _note: copies
326
- ? 'Written by `plaiful docs pull --copies`: copies as of pulled_at; the live docs are `plaiful docs`. Replaced on every pull.'
327
- : 'Written by `plaiful docs pull`. The platform docs are live (`plaiful docs`); this folder holds the product\'s own files.',
328
- mode: copies ? 'copies' : 'live',
329
- product: r.product, env: data.env, pulled_at: new Date().toISOString(),
330
- docs: files.map((f) => ({ file: safeName(f.key), title: f.title, description: f.description || '' })).filter((f) => f.file),
331
- };
332
- fs.writeFileSync(indexFile, `${JSON.stringify(index, null, 2)}\n`);
333
- const ignore = ignoreClientConfig(r.docsDir);
334
- const rel = path.relative(ctx.io.cwd(), r.docsDir) || '.';
335
- const lines = [
336
- `${rel}: ${result.written.length} updated, ${result.unchanged.length} unchanged${result.skipped.length ? `, ${result.skipped.length} skipped` : ''}.`,
337
- ...result.written.map((n) => ` updated ${n}`),
338
- ...result.removed.map((n) => ` removed ${n} (a platform doc: read it live, plaiful docs read ${n.replace(/\.md$/, '')})`),
339
- ];
340
- if (ignore.added.length) lines.push(` ${path.join(rel, '.gitignore')}: now keeps ${ignore.added.join(', ')} out of git`);
341
- if (ignore.tracked.length) {
342
- lines.push(`! Already committed, and holding your keys: ${ignore.tracked.join(', ')}. Take them out of git (the files stay):`);
343
- lines.push(` git rm --cached ${ignore.tracked.map((f) => `"${path.relative(ctx.io.cwd(), path.join(r.docsDir, f)).replace(/\\/g, '/')}"`).join(' ')}`);
344
- }
345
- const where = whereThingsGo(ctx, r);
346
- lines.push(...where.lines);
347
- lines.push(copies ? 'Local copies as of now; the live docs are `plaiful docs`.' : 'The platform docs are live: plaiful docs (start with plaiful docs read README).');
348
- ctx.out(lines.join('\n'), { success: true, dir: r.docsDir, ...result, gitignore: ignore, misplaced_specs: where.misplaced });
349
- return 0;
350
- }
351
-
352
- // ── The live docs ─────────────────────────────────────────────────────────────────────────────────────────────────
353
-
354
- const docsRoute = (rest = '', query = {}) => {
355
- const qs = new URLSearchParams(Object.entries(query).filter(([, v]) => v !== undefined && v !== null && v !== ''));
356
- return `/partner/platform/docs${rest}${qs.toString() ? `?${qs}` : ''}`;
357
- };
358
- const docName = (k) => String(k).replace(/\.md$/, '');
359
- const day = (iso) => (iso ? String(iso).slice(0, 10) : ' ');
360
-
361
- async function docsList(ctx) {
362
- const { data } = await ctx.call('GET', docsRoute());
363
- const docs = data.docs || [];
364
- const lines = [`Plaiful docs (live): ${docs.length}. plaiful docs read <doc>`];
365
- let section = null;
366
- for (const d of [...docs].sort((a, b) => (a.order ?? 1e9) - (b.order ?? 1e9))) {
367
- const s = d.section_title || d.category || 'Docs';
368
- if (s !== section) { lines.push(`${s}:`); section = s; }
369
- lines.push(` ${docName(d.key).padEnd(40)} ${day(d.updated_at)} ${d.label || d.title || ''}`);
370
- }
371
- ctx.out(lines.join('\n'), data);
372
- return 0;
373
- }
374
-
375
- async function docsRead(ctx, [name]) {
376
- if (!name) throw new UsageError('which doc? plaiful docs read <doc> (plaiful docs lists them)');
377
- const { data } = await ctx.call('GET', docsRoute(`/${encodeURIComponent(docName(name))}`, { section: ctx.flags.section }));
378
- ctx.out(data.content, data);
379
- return 0;
380
- }
381
-
382
- async function docsSearch(ctx, words) {
383
- const q = words.join(' ').trim();
384
- if (!q) throw new UsageError('search for what? plaiful docs search <words...>');
385
- const { data } = await ctx.call('GET', docsRoute('', { q, limit: ctx.flags.limit }));
386
- const lines = data.results.length ? [`"${q}" in the docs:`] : [`Nothing in the docs mentions all of: ${q}`];
387
- for (const r of data.results) {
388
- lines.push(` ${docName(r.key)} (${r.title})`);
389
- for (const sct of r.sections) lines.push(` § ${sct.heading || r.title}: ${sct.snippet}`);
390
- }
391
- if (data.results.length) lines.push('plaiful docs read <doc> --section "<heading>" for the whole section');
392
- ctx.out(lines.join('\n'), data);
393
- return 0;
394
- }
395
-
396
- async function docsChanges(ctx) {
397
- const since = ctx.flags.since || new Date(Date.now() - 7 * 864e5).toISOString().slice(0, 10);
398
- const { data } = await ctx.call('GET', docsRoute('', { since }));
399
- const lines = [data.docs.length ? `Changed since ${since}:` : `No doc changed since ${since}.`];
400
- for (const d of data.docs) lines.push(` ${day(d.updated_at)} ${docName(d.key).padEnd(40)} ${d.title || ''}`);
401
- ctx.out(lines.join('\n'), data);
402
- return 0;
403
- }
404
-
405
- // client-config.md holds the product's keys and endpoints (the Firebase web key among them), so it never goes in git;
406
- // nor do the older hand-made `<product>-client-config.md` copies.
407
- const CLIENT_CONFIG_IGNORES = ['client-config.md', '*-client-config.md'];
408
-
409
- function ignoreClientConfig(docsDir) {
410
- const file = path.join(docsDir, '.gitignore');
411
- const prev = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
412
- const have = new Set(prev.split(/\r?\n/).map((l) => l.trim()));
413
- const added = CLIENT_CONFIG_IGNORES.filter((p) => !have.has(p));
414
- if (added.length) {
415
- const head = prev ? `${prev.replace(/\s*$/, '')}\n` : '# Written by `plaiful docs pull`: these files hold your product\'s keys.\n';
416
- fs.writeFileSync(file, `${head}${added.join('\n')}\n`);
417
- }
418
- // A .gitignore doesn't untrack what's already committed; say so rather than leave the keys in the repo.
419
- const git = spawnSync('git', ['ls-files', '--', ...CLIENT_CONFIG_IGNORES], { cwd: docsDir, encoding: 'utf8' });
420
- const tracked = git.status === 0 ? git.stdout.split('\n').map((l) => l.trim()).filter(Boolean) : [];
421
- return { added, tracked };
422
- }
423
-
424
- function readDeclaration(ctx, r, file) {
425
- const target = path.resolve(ctx.io.cwd(), file || path.join(r.docsDir, `${r.product}-ovid-declaration.json`));
426
- if (!fs.existsSync(target)) throw new UsageError(`no declaration at ${target} (write it first: ovid-declaration.md)`);
427
- try { return { target, declaration: JSON.parse(fs.readFileSync(target, 'utf8')) }; } catch (e) {
428
- throw new UsageError(`${target} isn't valid JSON: ${e.message}`);
429
- }
430
- }
431
-
432
- function findingsText(data) {
433
- const lines = [];
434
- const where = (x) => `${x.file ? `${x.file} ` : ''}${x.path || '(top level)'}`;
435
- for (const e of data.errors || []) lines.push(` ✗ ${where(e)}: ${e.message} [${e.doc}]`);
436
- for (const w of data.warnings || []) lines.push(` ! ${where(w)}: ${w.message} [${w.doc}]`);
437
- for (const n of data.notes || []) lines.push(` · ${n}`);
438
- return lines;
439
- }
440
-
441
- async function ovidCheck(ctx, [file]) {
442
- const r = repo(ctx);
443
- const { target, declaration } = readDeclaration(ctx, r, file);
444
- const { data } = await ctx.call('POST', `/partner/${encodeURIComponent(r.product)}/ovid/declaration/check`, { declaration });
445
- const head = data.ok
446
- ? `${path.basename(target)} is valid${(data.warnings || []).length ? `, with ${data.warnings.length} warning(s)` : ''}. Publish it with: plaiful ovid publish`
447
- : `${path.basename(target)} has ${data.errors.length} error(s); fix them and check again.`;
448
- ctx.out([head, ...findingsText(data)].join('\n'), data);
449
- return data.ok ? 0 : 1;
450
- }
451
-
452
- async function ovidPublish(ctx, [file]) {
453
- const r = repo(ctx);
454
- const { target, declaration } = readDeclaration(ctx, r, file);
455
- const { data } = await ctx.call('PUT', `/partner/${encodeURIComponent(r.product)}/ovid/declaration`, { declaration });
456
- if (!data.published) {
457
- ctx.out([`Not published: ${data.error || `${path.basename(target)} has ${(data.errors || []).length} error(s)`}`, ...findingsText(data)].join('\n'), data);
458
- return 1;
459
- }
460
- const lines = [`Published ${path.basename(target)} for ${r.product}; OVID reads it ${data.takes_effect}.`];
461
- if (data.tabs && data.tabs.error) lines.push(` ! ${data.tabs.error}`);
462
- lines.push(...findingsText(data));
463
- lines.push('Check it took: GameMaster shows your tier labels, tracks and regions (plaiful ovid show prints what OVID has).');
464
- ctx.out(lines.join('\n'), data);
465
- return 0;
466
- }
467
-
468
- async function ovidShow(ctx) {
469
- const r = repo(ctx);
470
- const { data } = await ctx.call('GET', `/partner/${encodeURIComponent(r.product)}/ovid/declaration`);
471
- if (ctx.flags.json) { ctx.out(data); return 0; }
472
- if (!data.declaration) ctx.out(data.packaged ? `${r.product}'s declaration is packaged: ${data.packaged}` : `${r.product} has no OVID declaration yet (OVID uses its defaults).`);
473
- else ctx.out(`Published ${data.updated_at || '(date unknown)'}${data.published_by ? ` by ${data.published_by}` : ''}:\n${JSON.stringify(data.declaration, null, 2)}`);
474
- return 0;
475
- }
476
-
477
- // ── Seeding (phase 2) ──────────────────────────────────────────────────────────────────────────────────────────
478
-
479
- const STORES = ['world', 'lore', 'map', 'personas'];
480
- const SEED_ROUTE = { world: 'ovid/world', lore: 'ovid/lore', map: 'ovid/map', personas: 'thespis/personas' };
481
- const MARK = { create: '+', update: '~', remove: '-', keep: '=' };
482
-
483
- /** The JSON files to send: the paths given (files or folders), else resources/<store>/<product>/. */
484
- function seedFiles(ctx, r, store, paths) {
485
- const targets = paths.length ? paths.map((x) => path.resolve(ctx.io.cwd(), x)) : [path.join(r.root, 'resources', store, r.product)];
486
- const files = [];
487
- for (const t of targets) {
488
- if (!fs.existsSync(t)) throw new UsageError(`${t} doesn't exist${paths.length ? '' : ` (put your ${store} files there, or pass their paths)`}`);
489
- const list = fs.statSync(t).isDirectory()
490
- ? fs.readdirSync(t).filter((n) => n.toLowerCase().endsWith('.json')).sort().map((n) => path.join(t, n))
491
- : [t];
492
- for (const file of list) {
493
- let content;
494
- try { content = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { throw new UsageError(`${file} isn't valid JSON: ${e.message}`); }
495
- files.push({ name: path.relative(r.root, file).replace(/\\/g, '/'), content });
496
- }
497
- }
498
- if (!files.length) throw new UsageError(`no .json files in ${targets.join(', ')}`);
499
- return files;
500
- }
501
-
502
- async function seedStore(ctx, store, paths) {
503
- if (!STORES.includes(store)) throw new UsageError(`seed what? world, lore, map or personas (plaiful seed ${STORES.join('|')})`);
504
- const r = repo(ctx);
505
- const files = seedFiles(ctx, r, store, paths);
506
- const apply = !!ctx.flags.apply;
507
- const reset = !!ctx.flags.reset;
508
- const { data } = await ctx.call('POST', `/partner/${encodeURIComponent(r.product)}/${SEED_ROUTE[store]}/seed`, { files, apply, reset, rows: !!ctx.flags.rows });
509
- if (ctx.flags.json) { ctx.out(data); return data.ok ? 0 : 1; }
510
- const lines = [];
511
- if (!data.ok) {
512
- lines.push(`${files.length} ${store} file(s) have ${data.errors.length} error(s); nothing was ${apply ? 'written' : 'planned'}. Fix them and run it again.`);
513
- lines.push(...findingsText(data));
514
- ctx.out(lines.join('\n'));
515
- return 1;
516
- }
517
- const s = data.summary;
518
- const counts = Object.entries(data.counts || {}).map(([k, v]) => `${v} ${k}`).join(', ');
519
- lines.push(`${store} for ${r.product} (dev, ${data.table}): ${counts}.`);
520
- lines.push(`${apply ? 'Wrote' : 'Would write'}: ${s.create} new, ${s.update} changed, ${s.remove} removed, ${s.unchanged} unchanged${s.kept ? `, ${s.kept} kept as they are` : ''}.`);
521
- if (data.unmanaged) lines.push(` · ${data.unmanaged} row(s) there weren't written by plaiful seed (${store === 'personas' ? 'the Tuning Studio\'s' : 'OVID\'s, the CMS\'s'}, or an older seeder's): left alone.`);
522
- const shown = data.items.slice(0, 40);
523
- for (const i of shown) lines.push(` ${MARK[i.action] || '?'} ${i.action.padEnd(6)} ${String(i.kind).padEnd(14)} ${i.id}${i.note ? ` (${i.note})` : ''}`);
524
- if (data.items.length > shown.length) lines.push(` … and ${data.items.length - shown.length} more (--json lists them all)`);
525
- lines.push(...findingsText(data));
526
- if (ctx.flags.rows) lines.push(JSON.stringify(data.rows, null, 2));
527
- if (!apply) lines.push(data.writes ? `Dry run: nothing written. Write it with: plaiful seed ${store}${paths.length ? ` ${paths.join(' ')}` : ''}${reset ? ' --reset' : ''} --apply` : 'Dry run: dev already matches your files.');
528
- else if (data.writes) lines.push('Check it with: plaiful status');
529
- ctx.out(lines.join('\n'));
530
- return 0;
531
- }
532
-
533
- async function status(ctx) {
534
- const r = repo(ctx);
535
- const { data } = await ctx.call('GET', `/partner/${encodeURIComponent(r.product)}/status`);
536
- if (ctx.flags.json) { ctx.out(data); return 0; }
537
- const w = data.world || {};
538
- const l = data.lore || {};
539
- const m = data.map || {};
540
- const d = data.declaration || {};
541
- const err = (x) => (x.error ? ` ${x.error}` : null);
542
- const lines = [`${r.product} in dev:`];
543
- lines.push(` world ${err(w) || `${w.events} events (${w.macro} macro, ${w.meso} meso, ${w.micro} micro${w.state_events ? `, ${w.state_events} state events` : ''}), ${w.seeded} seeded`}`);
544
- if (!w.error) lines.push(` clock: ${w.clock ? `${w.clock.mode}, at ${w.clock.currentMicro} (${w.clock.chapterTitle})` : 'not set (seed a worldClock, or set it in GameMaster)'}`);
545
- lines.push(` lore ${err(l) || `${l.sets} sets, ${l.snippets} snippets (${l.known} known, ${l.hidden} hidden), ${l.seeded} rows seeded${l.without_product ? `; ${l.without_product} snippets lack "product" and never reach a character` : ''}`}`);
546
- lines.push(` map ${err(m) || `${m.locations} locations, ${m.settlements} settlements (${m.settlements_with_npcs} with NPCs), ${m.seeded} seeded`}`);
547
- const t = data.thespis || {};
548
- lines.push(` thespis ${err(t) || `${t.personas} personas (${t.active_personas} active), ${t.situations} situations, ${t.seeded} seeded`}`);
549
- lines.push(` declaration ${d.declared ? `published ${d.updated_at || ''}: tiers ${d.timeline ? [d.timeline.macro, d.timeline.meso, d.timeline.micro].join(' / ') : '(defaults)'}; regions ${(d.regions || []).join(', ') || 'none'}; tracks ${(d.tracks || []).join(', ') || '(default)'}` : 'none yet (plaiful ovid publish)'}`);
550
- ctx.out(lines.join('\n'));
551
- return 0;
552
- }
553
-
554
- // ── Lists and uploads (phase 3) ──────────────────────────────────────────────────────────────────────────────────
555
-
556
- /** The route for a list: a name in the namespace goes in the path; a full /path goes in ?path=. */
557
- function listRoute(r, name) {
558
- const base = `/partner/${encodeURIComponent(r.product)}/lists`;
559
- if (!name) return base;
560
- if (name.startsWith('/')) return `${base}?path=${encodeURIComponent(name)}`;
561
- return `${base}/${name.split('/').map(encodeURIComponent).join('/')}`;
562
- }
563
-
564
- async function lists(ctx, [sub, name, ...values]) {
565
- const r = repo(ctx);
566
- if (!sub) {
567
- const { data } = await ctx.call('GET', listRoute(r));
568
- const lines = [`${r.product}'s lists in dev (${data.namespace}):`];
569
- if (!data.lists.length) lines.push(' none yet (plaiful lists set <name> <values...>)');
570
- for (const l of data.lists) lines.push(` ${l.name}${l.type === 'String' ? ' (a setting)' : ''} ${l.values.join(', ')}`);
571
- ctx.out(lines.join('\n'), data);
572
- return 0;
573
- }
574
- if (sub === 'get') {
575
- if (!name) throw new UsageError('which list? plaiful lists get <name>');
576
- const { data } = await ctx.call('GET', listRoute(r, name));
577
- ctx.out(`${data.name}: ${data.values.join(', ')}`, data);
578
- return 0;
579
- }
580
- if (sub === 'set') {
581
- if (!name || !values.length) throw new UsageError('plaiful lists set <name> <values...> (e.g. plaiful lists set shop_type tavern blacksmith healer)');
582
- const parsed = (values.length === 1 ? values[0].split(',') : values).map((v) => v.trim()).filter(Boolean);
583
- const { data } = await ctx.call('PUT', listRoute(r, name), { values: parsed });
584
- const was = data.previous === null ? 'new' : `was: ${data.previous.join(', ')}`;
585
- ctx.out(`${data.name} = ${data.values.join(', ')} (${was})`, data);
586
- return 0;
587
- }
588
- throw new UsageError(`plaiful lists, lists get <name> or lists set <name> <values...> (not "${sub}")`);
589
- }
590
-
591
- // ── SmartBuilder agents ─────────────────────────────────────────────────────────────────────────────────────
592
-
593
- const agentRoute = (r, rest = '') => `/partner/${encodeURIComponent(r.product)}/agents${rest}`;
594
- const AGENT_NAME = /^[a-z0-9][a-z0-9-]{0,62}$/;
595
-
596
- function readJsonFile(ctx, f) {
597
- const file = path.resolve(ctx.io.cwd(), f);
598
- if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw new UsageError(`${file} isn't a file`);
599
- try { return { file, json: JSON.parse(fs.readFileSync(file, 'utf8')) }; } catch (e) { throw new UsageError(`${file} isn't valid JSON (${e.message})`); }
600
- }
601
-
602
- /** The config files to deploy: the ones named, or every .json in resources/agents/<product>/. */
603
- function agentFiles(ctx, r, files) {
604
- if (files.length) return files;
605
- const dir = path.join(ctx.io.cwd(), 'resources', 'agents', r.product);
606
- if (!fs.existsSync(dir)) throw new UsageError(`no files named, and no ${path.relative(ctx.io.cwd(), dir)}/ folder: plaiful agents deploy <file.json>`);
607
- const found = fs.readdirSync(dir).filter((n) => n.endsWith('.json')).map((n) => path.join(dir, n));
608
- if (!found.length) throw new UsageError(`${path.relative(ctx.io.cwd(), dir)}/ has no .json agent configs`);
609
- return found;
610
- }
611
-
612
- async function agents(ctx, [sub, name, ...rest]) {
613
- const r = repo(ctx);
614
- if (!sub) {
615
- const { data } = await ctx.call('GET', agentRoute(r));
616
- const list = data.agents || [];
617
- const lines = [`${r.product}'s SmartBuilder agents in dev:`];
618
- if (!list.length) lines.push(' none yet (plaiful agents deploy <file.json>, or SmartBuilder in the CMS)');
619
- for (const a of list) lines.push(` ${a.name || a.agent_name}${a.display_name ? ` ${a.display_name}` : ''}${a.business_purpose ? ` (${a.business_purpose})` : ''}`);
620
- ctx.out(lines.join('\n'), data);
621
- return 0;
622
- }
623
- if (sub === 'show') {
624
- if (!name) throw new UsageError('which agent? plaiful agents show <name>');
625
- const { data } = await ctx.call('GET', agentRoute(r, `/${encodeURIComponent(name)}`));
626
- const a = data.agent || {};
627
- const lines = [`${a.agent_name || name}: ${a.display_name || ''}`.trim(),
628
- ` table ${(a.storage || {}).table_name || '?'}, version ${(a.metadata || {}).version || '?'}, ${(a.metadata || {}).business_purpose || 'content'}`,
629
- ` fields ${(a.output_fields || []).join(', ')}`,
630
- ` lists ${Object.entries(a.ssm_parameters || {}).map(([k, v]) => `${k} ← ${listSource(v)}`).join('; ') || 'none'}`,
631
- ` dedup ${a.duplicate_detection && a.duplicate_detection.enabled !== false ? `on ${[].concat(a.duplicate_detection.field || 'name').join(', ')}` : 'off'}`,
632
- ' (--json prints the whole config)'];
633
- ctx.out(lines.join('\n'), data);
634
- return 0;
635
- }
636
- if (sub === 'deploy') {
637
- const files = agentFiles(ctx, r, [name, ...rest].filter(Boolean));
638
- const done = [];
639
- for (const f of files) {
640
- const { file, json } = readJsonFile(ctx, f);
641
- const agentName = json.agent_name || path.basename(file, '.json');
642
- if (!AGENT_NAME.test(agentName)) throw new UsageError(`${path.basename(file)}: "${agentName}" isn't an agent name (lowercase letters, digits, hyphens)`);
643
- const { data } = await ctx.call('POST', agentRoute(r, `/${agentName}`), { config: json });
644
- done.push(data);
645
- if (!ctx.flags.json) ctx.out(`${data.redeployed ? 'redeployed' : 'deployed'} ${data.agent_name}: table ${data.table_name}${data.table === 'created' ? ' (new)' : ''}, version ${data.version}`);
646
- }
647
- if (ctx.flags.json) ctx.out('', { success: true, product: r.product, deployed: done });
648
- return 0;
649
- }
650
- if (sub === 'run') {
651
- if (!name) throw new UsageError('which agent? plaiful agents run <name> [key=value...]');
652
- const body = {};
653
- for (const kv of rest) {
654
- const i = kv.indexOf('=');
655
- if (i < 1) throw new UsageError(`"${kv}" isn't key=value`);
656
- body[kv.slice(0, i)] = kv.slice(i + 1);
657
- }
658
- const { data } = await ctx.call('POST', agentRoute(r, `/${encodeURIComponent(name)}/run`), body);
659
- const rec = data.item || data.record || data;
660
- ctx.out(`made ${rec.uuid || 'a record'}${rec.name ? `: ${rec.name}` : ''}`, data);
661
- return 0;
662
- }
663
- if (sub === 'batch') {
664
- if (!name) throw new UsageError('which agent? plaiful agents batch <name> [batch-body.json] (or --count <n>)');
665
- let body;
666
- if (rest[0]) body = readJsonFile(ctx, rest[0]).json;
667
- else if (ctx.flags.count) body = { count: Number(ctx.flags.count) };
668
- else throw new UsageError('give a batch body file, or --count <n>');
669
- const { data } = await ctx.call('POST', agentRoute(r, `/${encodeURIComponent(name)}/batch`), body);
670
- ctx.out(`started batch ${data.job_id} (${data.total_items || '?'} records). plaiful agents status ${name} ${data.job_id}`, data);
671
- return 0;
672
- }
673
- if (sub === 'status') {
674
- const [jobId] = rest;
675
- if (!name || !jobId) throw new UsageError('plaiful agents status <name> <jobId>');
676
- const { data } = await ctx.call('GET', agentRoute(r, `/${encodeURIComponent(name)}/batch/${encodeURIComponent(jobId)}`));
677
- ctx.out(`${data.status || '?'}: ${data.completed_items ?? '?'} done, ${data.failed_items ?? 0} failed of ${data.total_items ?? '?'}`, data);
678
- return 0;
679
- }
680
- throw new UsageError(`plaiful agents, or agents show | deploy | run | batch | status (not "${sub}")`);
681
- }
682
-
683
- /** `plaiful records import <agent> [file]`: records written by hand into the agent's table, saved as the agent saves
684
- * the ones it makes; a dry run unless --apply. The file: a list of records, or { "records": [...] }. */
685
- async function records(ctx, [sub, name, file]) {
686
- if (sub !== 'import') throw new UsageError(`plaiful records import <agent> [file] (not "${sub || ''}")`);
687
- const r = repo(ctx);
688
- if (!name) throw new UsageError('which agent? plaiful records import <agent> [file] (default file: resources/records/<product>/<agent>.json)');
689
- if (!AGENT_NAME.test(name)) throw new UsageError(`"${name}" isn't an agent name (lowercase letters, digits, hyphens)`);
690
- const f = file || path.join(path.relative(ctx.io.cwd(), r.root) || '.', 'resources', 'records', r.product, `${name}.json`);
691
- const { json } = readJsonFile(ctx, f);
692
- const list = Array.isArray(json) ? json : json && Array.isArray(json.records) ? json.records : null;
693
- if (!list) throw new UsageError(`${f}: give a list of records, or { "records": [...] }`);
694
- if (!list.length) throw new UsageError(`${f} has no records`);
695
- const apply = !!ctx.flags.apply;
696
- const { data } = await ctx.call('POST', agentRoute(r, `/${encodeURIComponent(name)}/import`), { records: list, apply, render: !ctx.flags['no-render'] });
697
- if (ctx.flags.json) { ctx.out(data); return data.success ? 0 : 1; }
698
- const lines = [];
699
- if (!data.success) {
700
- lines.push(`${data.error || 'the import was refused'}. Fix them and run it again.`);
701
- for (const e of data.errors || []) lines.push(` ✗ ${e.error}`);
702
- ctx.out(lines.join('\n'));
703
- return 1;
704
- }
705
- const s = data.summary;
706
- lines.push(`${name} for ${r.product} (dev, ${data.table_name})${data.key_field ? `, matched on ${data.key_field}` : ''}:`);
707
- lines.push(`${data.applied ? 'Wrote' : 'Would write'}: ${s.create} new, ${s.update} changed, ${s.unchanged} unchanged.`);
708
- const shown = data.records.filter((x) => x.action !== 'unchanged').slice(0, 40);
709
- const label = (x) => (x.key !== null && x.key !== undefined ? x.key : x.uuid);
710
- for (const x of shown) lines.push(` ${MARK[x.action]} ${x.action === 'create' ? 'new ' : 'change'} ${label(x)}${x.action === 'update' ? ` (${x.changed.join(', ')})` : ''}`);
711
- const more = s.create + s.update - shown.length;
712
- if (more > 0) lines.push(` … and ${more} more (--json lists them all)`);
713
- for (const w of data.warnings || []) lines.push(` ! ${w}`);
714
- const stale = data.records.filter((x) => x.stale_art).map(label);
715
- if (stale.length) lines.push(` ! ${stale.length} changed record(s) keep the art or sound made from their old text (${stale.slice(0, 5).join(', ')}${stale.length > 5 ? ', …' : ''}): make it again in the CMS Library.`);
716
- if (!data.applied) {
717
- lines.push(s.create + s.update ? `Dry run: nothing written. Write it with: plaiful records import ${name}${file ? ` ${file}` : ''} --apply` : 'Dry run: the table already matches your file.');
718
- } else if (data.rendering) lines.push(`Making the art or sound for ${data.rendering} new record(s): plaiful assets ${name}`);
719
- ctx.out(lines.join('\n'));
720
- return 0;
721
- }
722
-
723
- // ── What OVID has: quests, lore, the world ──────────────────────────────────────────────────────────────────────
724
-
725
- const ovidRoute = (r, rest) => `/partner/${encodeURIComponent(r.product)}/ovid/${rest}`;
726
- const priceText = (p) => (p && Object.keys(p).length ? Object.entries(p).map(([k, v]) => `${v} ${k}`).join(', ') : '');
727
-
728
- async function quests(ctx, [sub, id]) {
729
- const r = repo(ctx);
730
- if (sub === 'show') {
731
- if (!id) throw new UsageError('which quest? plaiful quests show <id>');
732
- const { data } = await ctx.call('GET', ovidRoute(r, `quests/${encodeURIComponent(id)}`));
733
- const q = data.quest || {};
734
- const lines = [`${data.title || id} [${data.questType || '?'}] track ${data.quest_track || '?'}${data.series ? `, ${data.series.series_title || data.series.series_id} #${data.series.series_order}` : ''} (${data.status || '?'})`];
735
- if (q.narrative_desc || q.description) lines.push(` ${q.narrative_desc || q.description}`);
736
- for (const st of data.steps_detail || []) {
737
- const n = (q.nodes || {})[st.id] || {};
738
- const say = n.close || n.narrative_desc || (n.dialogue_tree && n.dialogue_tree.nodes && Object.values(n.dialogue_tree.nodes)[0] && Object.values(n.dialogue_tree.nodes)[0].text) || '';
739
- lines.push(` ${st.unreached ? '(unreached) ' : ''}${st.id}: ${st.type}${st.count > 1 ? `×${st.count}` : ''}${say ? ` "${String(say).slice(0, 90)}${String(say).length > 90 ? '…' : ''}"` : ''}`);
740
- }
741
- lines.push(` pays: ${priceText(data.price) || (data.priced ? 'nothing (no step carries effort)' : 'not priced yet (plaiful midas pricing)')}${data.reward_hint ? `; hint: ${data.reward_hint.kinds.join(', ')}` : ''}`);
742
- lines.push(' (--json prints the whole record)');
743
- ctx.out(lines.join('\n'), data);
744
- return 0;
745
- }
746
- if (sub) throw new UsageError(`plaiful quests, or quests show <id> (not "${sub}")`);
747
- const qs = new URLSearchParams();
748
- if (ctx.flags.track) qs.set('track', ctx.flags.track);
749
- if (ctx.flags.series) qs.set('series', ctx.flags.series);
750
- const { data } = await ctx.call('GET', `${ovidRoute(r, 'quests')}${qs.toString() ? `?${qs}` : ''}`);
751
- const lines = [`${r.product}'s quests in dev: ${data.count}${data.priced ? '' : ' (not priced yet: plaiful midas pricing)'}`];
752
- let group = null;
753
- for (const q of data.quests) {
754
- const g = `${q.quest_track || '?'}${q.series ? ` · ${q.series.series_title || q.series.series_id}` : ''}`;
755
- if (g !== group) { lines.push(` ${g}`); group = g; }
756
- const pays = priceText(q.price);
757
- lines.push(` ${q.series ? `${q.series.series_order}. ` : ''}${q.title} [${q.questType || '?'}] ${q.steps.join(' → ')}${pays ? ` pays ${pays}` : ''} ${q.quest_id}`);
758
- }
759
- if (data.truncated) lines.push(' (cut off: more quests than one read returns)');
760
- ctx.out(lines.join('\n'), data);
761
- return 0;
762
- }
763
-
764
- async function lore(ctx, [sub, id]) {
765
- const r = repo(ctx);
766
- if (sub === 'show') {
767
- if (!id) throw new UsageError('which set? plaiful lore show <setId>');
768
- const { data } = await ctx.call('GET', ovidRoute(r, `lore/${encodeURIComponent(id)}`));
769
- const lines = [`${data.title || id}${data.category ? ` (${data.category})` : ''}`];
770
- for (const sn of data.snippets || []) lines.push(` ${sn.world_known ? 'known ' : 'hidden'} ${sn.title || sn.snippet_id}${sn.narrative ? `: ${String(sn.narrative).slice(0, 100)}${String(sn.narrative).length > 100 ? '…' : ''}` : ''}`);
771
- ctx.out(lines.join('\n'), data);
772
- return 0;
773
- }
774
- if (sub) throw new UsageError(`plaiful lore, or lore show <setId> (not "${sub}")`);
775
- const { data } = await ctx.call('GET', ovidRoute(r, 'lore'));
776
- const lines = [`${r.product}'s lore in dev: ${data.sets.length} sets`];
777
- for (const st of data.sets) lines.push(` ${st.lore_set_id} ${st.title || ''} ${st.snippets} snippets (${st.known} known, ${st.hidden} hidden)${st.source === 'plaiful-seed' ? '' : st.source ? ` from ${st.source}` : ''}`);
778
- ctx.out(lines.join('\n'), data);
779
- return 0;
780
- }
781
-
782
- async function world(ctx) {
783
- const r = repo(ctx);
784
- const { data } = await ctx.call('GET', ovidRoute(r, 'world'));
785
- const c = data.clock;
786
- const lines = [`${r.product}'s world in dev: ${data.events.length} states and events; clock ${c ? `${c.mode || '?'}, at ${c.currentMicro || '?'}${c.chapterTitle ? ` (${c.chapterTitle})` : ''}` : 'not set'}`];
787
- const indent = { macro: ' ', meso: ' ', micro: ' ' };
788
- for (const e of data.events) {
789
- const pad = e.kind === 'event' ? ' ' : (indent[e.scope] || ' ');
790
- lines.push(`${pad}${e.kind === 'event' ? '· ' : ''}${e.title || e.event_id} ${e.scope || e.kind}${e.faction ? `, ${e.faction}` : ''}${e.advances ? ', advances' : ''}${c && e.event_id === c.currentMicro ? ' ← now' : ''} ${e.event_id}`);
791
- }
792
- if (data.truncated) lines.push(' (cut off: more rows than one read returns)');
793
- ctx.out(lines.join('\n'), data);
794
- return 0;
795
- }
796
-
797
- // ── What the agents made ────────────────────────────────────────────────────────────────────────────────────────
798
-
799
- const countsText = (a) => `${a.records} records: ${a.made} made, ${a.pending} pending, ${a.failed} failed, ${a.none} none yet${a.truncated ? ' (first 2000)' : ''}`;
800
-
801
- async function assets(ctx, [agent]) {
802
- const r = repo(ctx);
803
- const base = `/partner/${encodeURIComponent(r.product)}/assets`;
804
- if (!agent) {
805
- const { data } = await ctx.call('GET', base);
806
- const lines = [`${r.product}'s agents in dev${data.cdn ? ` (files on https://${data.cdn}/)` : ''}:`];
807
- if (!data.agents.length) lines.push(' none yet (plaiful agents deploy)');
808
- for (const a of data.agents) {
809
- lines.push(` ${a.name.padEnd(24)} ${a.error ? `couldn't read: ${a.error}` : a.makes_art ? countsText(a) : '(makes no art)'}`);
810
- }
811
- ctx.out(lines.join('\n'), data);
812
- return 0;
813
- }
814
- const qs = new URLSearchParams();
815
- if (ctx.flags.state) qs.set('state', ctx.flags.state);
816
- if (ctx.flags.limit) qs.set('limit', ctx.flags.limit);
817
- const { data } = await ctx.call('GET', `${base}/${encodeURIComponent(agent)}${qs.toString() ? `?${qs}` : ''}`);
818
- const lines = [`${agent}: ${countsText(data.counts)}${ctx.flags.state ? `; ${data.matching} ${ctx.flags.state}` : ''}${data.shown < data.matching ? `, showing ${data.shown} (--limit)` : ''}`];
819
- for (const rec of data.records) {
820
- const why = rec.render_error || Object.entries(rec.media || {}).filter(([, m]) => m.error).map(([k, m]) => `${k}: ${m.error}`).join('; ');
821
- const where = rec.state === 'made' && rec.files ? `${rec.files.base}.{${rec.files.try.join('|')}}` : '';
822
- lines.push(` ${rec.state.padEnd(8)} ${rec.name || '(unnamed)'} ${rec.uuid}${why ? ` ${why}` : ''}${where ? ` ${where}` : ''}`);
823
- }
824
- ctx.out(lines.join('\n'), data);
825
- return 0;
826
- }
827
-
828
- // ── MIDAS quest pricing ─────────────────────────────────────────────────────────────────────────────────────────
829
-
830
- const pricingRoute = (r) => `/partner/${encodeURIComponent(r.product)}/midas/pricing`;
831
-
832
- function nonNegative(v, what) {
833
- const n = Number(v);
834
- if (v === undefined || v === true || !Number.isFinite(n) || n < 0) throw new UsageError(`${what} must be a number, 0 or more`);
835
- return n;
836
- }
837
-
838
- function pricingLines(product, data) {
839
- const qp = data.quest_pricing || {};
840
- const kinds = qp.kinds || {};
841
- const declared = ((data.rewards || {}).types || []).filter((k) => k !== 'lore');
842
- const names = [...new Set([...declared, ...Object.keys(kinds)])];
843
- const d = data.defaults || {};
844
- const weights = { ...(d.objective_weights || {}), ...(qp.objective_weights || {}) };
845
- const lines = [`${product}'s quest pricing in dev: price = base + per-effort × the quest's effort`];
846
- if (!names.length) lines.push(' no reward kinds declared (settings.rewards.types in your OVID declaration)');
847
- for (const k of names) {
848
- const p = kinds[k];
849
- lines.push(` ${k.padEnd(12)} ${p ? `base ${p.base ?? 0}, per effort ${p.per_objective ?? 0}` : 'not priced (plaiful midas pricing set ' + k + ' --base <n> --per-effort <n>)'}`);
850
- }
851
- lines.push(` effort: each step's weight, +${qp.count_effort ?? d.count_effort} of it per extra unit (units counted up to ${qp.count_cap ?? d.count_cap})`);
852
- lines.push(` weights: ${Object.entries(weights).map(([t, w]) => `${t} ${w}`).join(', ')}`);
853
- for (const w of data.warnings || []) lines.push(` note: ${w}`);
854
- return lines;
855
- }
856
-
857
- async function midasPricing(ctx, [sub, name, value]) {
858
- const r = repo(ctx);
859
- if (!sub) {
860
- const { data } = await ctx.call('GET', pricingRoute(r));
861
- ctx.out(pricingLines(r.product, data).join('\n'), data);
862
- return 0;
863
- }
864
- const save = async (qp) => {
865
- const { data } = await ctx.call('PUT', pricingRoute(r), { quest_pricing: qp });
866
- ctx.out([...pricingLines(r.product, data), ` ${data.note || 'saved'}`].join('\n'), data);
867
- return 0;
868
- };
869
- if (sub === 'apply') {
870
- const f = name || path.join('resources', 'midas', r.product, 'quest-pricing.json');
871
- const { json } = readJsonFile(ctx, f);
872
- return save(json.quest_pricing !== undefined ? json.quest_pricing : json);
873
- }
874
- if (!['set', 'unset', 'weight'].includes(sub)) throw new UsageError(`plaiful midas pricing, or pricing set | unset | weight | apply (not "${sub}")`);
875
- if (!name) throw new UsageError(sub === 'weight' ? 'plaiful midas pricing weight <step> <n>' : `which kind? plaiful midas pricing ${sub} <kind>`);
876
- const { data } = await ctx.call('GET', pricingRoute(r));
877
- const qp = JSON.parse(JSON.stringify(data.quest_pricing || {}));
878
- if (sub === 'weight') {
879
- qp.objective_weights = { ...(qp.objective_weights || {}), [name]: nonNegative(value, 'the weight') };
880
- } else if (sub === 'unset') {
881
- if (!qp.kinds || !qp.kinds[name]) throw new UsageError(`${name} isn't priced`);
882
- delete qp.kinds[name];
883
- } else {
884
- if (ctx.flags.base === undefined && ctx.flags['per-effort'] === undefined) throw new UsageError(`plaiful midas pricing set ${name} --base <n> --per-effort <n>`);
885
- const cur = (qp.kinds && qp.kinds[name]) || { base: 0, per_objective: 0 };
886
- qp.kinds = {
887
- ...(qp.kinds || {}),
888
- [name]: {
889
- base: ctx.flags.base === undefined ? cur.base : nonNegative(ctx.flags.base, '--base'),
890
- per_objective: ctx.flags['per-effort'] === undefined ? cur.per_objective : nonNegative(ctx.flags['per-effort'], '--per-effort'),
891
- },
892
- };
893
- }
894
- return save(qp);
895
- }
896
-
897
- async function upload(ctx, files) {
898
- const r = repo(ctx);
899
- if (!files.length) throw new UsageError('upload what? plaiful upload <files...> (map tiles: ovid-map-*.json)');
900
- const dest = ctx.flags.dest || 'map-data';
901
- const done = [];
902
- for (const f of files) {
903
- const file = path.resolve(ctx.io.cwd(), f);
904
- if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw new UsageError(`${file} isn't a file`);
905
- const body = fs.readFileSync(file);
906
- const { data } = await ctx.call('POST', `/partner/${encodeURIComponent(r.product)}/uploads`, { dest, name: path.basename(file), size: body.length });
907
- let res;
908
- try {
909
- res = await ctx.io.fetch(data.url, { method: data.method || 'PUT', headers: data.headers, body });
910
- } catch (e) {
911
- throw new ApiError(0, { error: `the upload of ${path.basename(file)} didn't go through (${e.message})`, code: 'network' });
912
- }
913
- if (!res.ok) throw new ApiError(res.status, { error: `storage refused ${path.basename(file)} (${res.status}); run the upload again`, code: 'upload_failed' });
914
- done.push({ file: path.basename(file), bucket: data.bucket, key: data.key, size: body.length });
915
- }
916
- ctx.out([`Uploaded ${done.length} file(s) to ${r.product}'s dev assets:`, ...done.map((d) => ` ${d.file} → s3://${d.bucket}/${d.key} (${d.size} bytes)`)].join('\n'), { success: true, uploaded: done });
917
- return 0;
918
- }
919
-
920
- // ── Clone and .env (the New-Game Flow) ───────────────────────────────────────────────────────────────────────────
921
-
922
- /** The game template's .env variables (plaiful-kit packages/client config.ts ENV_KEYS) ← the client config. */
923
- const ENV_FROM_CONFIG = {
924
- VITE_PLAIFUL_PRODUCT: (c) => c.productId,
925
- VITE_PLAIFUL_ENV: (c) => c.environment,
926
- VITE_PLAIFUL_API_BASE: (c) => c.apiBaseUrl,
927
- VITE_PLAIFUL_CDN_BASE: (c) => c.assetCdnUrl,
928
- VITE_FIREBASE_PROJECT_ID: (c) => c.firebase && c.firebase.projectId,
929
- VITE_FIREBASE_API_KEY: (c) => c.firebase && c.firebase.webApiKey,
930
- VITE_FIREBASE_AUTH_DOMAIN: (c) => c.firebase && c.firebase.authDomain,
931
- VITE_PLAIFUL_OVID_BASE: (c) => c.ovidApiUrl,
932
- VITE_PLAIFUL_PRISM_WS_URL: (c) => c.prismWsUrl,
933
- VITE_PLAIFUL_ANALYTICS_INGEST: (c) => c.analyticsIngestUrl,
934
- VITE_PLAIFUL_ANALYTICS_KEY: (c, game) => game.analytics_ingest_key,
935
- };
936
- const ENV_FILE = '.env.development';
937
- // "(pending)", "(not deployed ...)" and "<...>" placeholders aren't values (the template's config.ts treats them as missing).
938
- const usable = (v) => typeof v === 'string' && v !== '' && !/^\(|not deployed|^</.test(v);
939
-
940
- /**
941
- * Write .env.development in `root` from the game's dev client config: start from the file as it is (or the
942
- * template's .env.development.example), set the variables the platform knows, keep every other line.
943
- * → { file, set: [names], missing: [names] } or null when the repo has neither file (not the web template).
944
- */
945
- function writeEnv(root, game) {
946
- const file = path.join(root, ENV_FILE);
947
- const example = path.join(root, `${ENV_FILE}.example`);
948
- const base = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : fs.existsSync(example) ? fs.readFileSync(example, 'utf8') : null;
949
- if (base === null) return null;
950
- const set = [];
951
- const missing = [];
952
- const lines = base.split(/\r?\n/).map((line) => {
953
- const m = /^\s*([A-Z0-9_]+)\s*=(.*)$/.exec(line);
954
- if (!m || !ENV_FROM_CONFIG[m[1]]) return line;
955
- const v = ENV_FROM_CONFIG[m[1]](game.client_config || {}, game);
956
- if (!usable(v)) { if (!m[2].trim()) missing.push(m[1]); return line; }
957
- set.push(m[1]);
958
- return `${m[1]}=${v}`;
959
- });
960
- fs.writeFileSync(file, lines.join('\n'));
961
- return { file, set, missing };
962
- }
963
-
964
- function envLines(env, game) {
965
- if (!env) return [` · no ${ENV_FILE}(.example) here: not the web game template, so no .env was written (the client config is in docs/plaiful/client-config.md)`];
966
- const out = [` ${ENV_FILE}: ${env.set.length} value(s) from your dev client config`];
967
- if (env.missing.length) {
968
- const why = game.analytics_ingest_key_note && env.missing.includes('VITE_PLAIFUL_ANALYTICS_KEY') ? ` (the analytics key: ${game.analytics_ingest_key_note})` : '';
969
- out.push(` ! still empty: ${env.missing.join(', ')}${why}`);
970
- }
971
- return out;
972
- }
973
-
974
- async function envCmd(ctx) {
975
- const r = repo(ctx);
976
- const { data } = await ctx.call('GET', `/partner/${encodeURIComponent(r.product)}/game`);
977
- const env = writeEnv(r.root, data);
978
- if (!env) throw new UsageError(`no ${ENV_FILE} or ${ENV_FILE}.example in ${r.root}: this repo isn't the web game template`);
979
- ctx.out([`${r.product} (dev):`, ...envLines(env, data)].join('\n'), { success: true, ...env });
980
- return 0;
981
- }
982
-
983
- async function clone(ctx, [productArg, dirArg]) {
984
- let product = productArg || ctx.flags.product;
985
- if (!product) {
986
- const { data } = await ctx.call('GET', '/partner/whoami');
987
- if (data.products.length !== 1) throw new UsageError(`which game? ${data.products.length ? `yours: ${data.products.map((p) => p.product_id).join(', ')}` : 'you have none yet'} (plaiful clone <product>)`);
988
- product = data.products[0].product_id;
989
- }
990
- const { data: game } = await ctx.call('GET', `/partner/${encodeURIComponent(product)}/game`);
991
- if (!game.clone_url) throw new ApiError(409, { error: `${product} has no repo to clone yet: ${game.summary}`, code: 'no_repo' });
992
- const repoLabel = (game.game_repo && game.game_repo.repo) || game.clone_url;
993
- const repoName = String((game.game_repo && game.game_repo.repo) || product).split('/').pop().replace(/\.git$/, '');
994
- const dir = path.resolve(ctx.io.cwd(), dirArg || repoName);
995
- if (fs.existsSync(dir) && fs.readdirSync(dir).length) throw new UsageError(`${dir} already exists and isn't empty; pass another folder: plaiful clone ${product} <dir>`);
996
- ctx.io.stderr.write(`Cloning ${game.clone_url} into ${dir}...\n`);
997
- const git = ctx.io.run('git', ['clone', game.clone_url, dir], { cwd: ctx.io.cwd() });
998
- if (git.status !== 0) {
999
- throw new ApiError(1, {
1000
- error: `git couldn't clone ${repoLabel}. You need access to it on GitHub (ask the product's owner, or Plaiful, to add your account) and git signed in to GitHub (gh auth login, or Git Credential Manager).`,
1001
- code: 'clone_failed',
1002
- });
1003
- }
1004
- const rel = path.relative(ctx.io.cwd(), dir) || '.';
1005
- const steps = [`Cloned ${repoLabel} into ${rel}.`];
1006
- const existing = config.findRepoConfig(dir);
1007
- const own = existing && existing.root === dir ? existing.config : null;
1008
- if (!own) config.writeRepoConfig(dir, { product, env: 'dev', docsDir: config.DEFAULT_DOCS_DIR });
1009
- const made = makeLayout(dir, product, (own && own.docsDir) || config.DEFAULT_DOCS_DIR);
1010
- if (made.length) steps.push(`Made ${made.length} folder(s) your files go in: ${made.join(', ')}`);
1011
- const r = { product, root: dir, docsDir: path.resolve(dir, (own && own.docsDir) || config.DEFAULT_DOCS_DIR) };
1012
- steps.push(...envLines(writeEnv(dir, game), game));
1013
- await docsPull({ ...ctx, out: () => {} }, r);
1014
- steps.push(` ${path.relative(dir, r.docsDir).replace(/\\/g, '/')}: the onboarding docs and client-config.md`);
1015
- if (fs.existsSync(path.join(dir, 'package.json')) && !ctx.flags['no-install']) {
1016
- ctx.io.stderr.write('npm install...\n');
1017
- const npm = ctx.io.run('npm', ['install'], { cwd: dir });
1018
- steps.push(npm.status === 0 ? ' npm install: done'
1019
- : ' ! npm install failed. The @plaiful packages need npm access to the plaiful org (npm login; ask Plaiful), then run npm install there.');
1020
- }
1021
- if (!ctx.flags['no-open']) {
1022
- const zed = ctx.io.run('zed', [dir], { cwd: dir, detached: true });
1023
- steps.push(zed.status === 0 ? ' opened in Zed' : ' open it in your editor (Zed isn\'t installed)');
1024
- }
1025
- steps.push(`Next: cd ${rel}, npm run dev. docs/plaiful/README.md is the guide.`);
1026
- ctx.out(steps.join('\n'), { success: true, product, dir, clone_url: game.clone_url, game_repo: game.game_repo });
1027
- return 0;
1028
- }
1029
-
1030
- const COMMANDS = {
1031
- login: (ctx) => login(ctx),
1032
- logout: (ctx) => logout(ctx),
1033
- whoami: (ctx) => whoami(ctx),
1034
- init: (ctx, rest) => init(ctx, rest),
1035
- 'docs pull': (ctx) => docsPull(ctx),
1036
- 'docs read': (ctx, rest) => docsRead(ctx, rest),
1037
- 'docs search': (ctx, rest) => docsSearch(ctx, rest),
1038
- 'docs changes': (ctx) => docsChanges(ctx),
1039
- docs: (ctx, rest) => {
1040
- if (rest.length) throw new UsageError(`plaiful docs, or docs read | search | changes | pull (not "${rest[0]}")`);
1041
- return docsList(ctx);
1042
- },
1043
- mcp: (ctx) => require('./mcp').serve(ctx),
1044
- 'ovid check': (ctx, rest) => ovidCheck(ctx, rest),
1045
- 'ovid publish': (ctx, rest) => ovidPublish(ctx, rest),
1046
- 'ovid show': (ctx) => ovidShow(ctx),
1047
- seed: (ctx, [store, ...paths]) => seedStore(ctx, store, paths),
1048
- status: (ctx) => status(ctx),
1049
- lists: (ctx, rest) => lists(ctx, rest),
1050
- agents: (ctx, rest) => agents(ctx, rest),
1051
- records: (ctx, rest) => records(ctx, rest),
1052
- 'midas pricing': (ctx, rest) => midasPricing(ctx, rest),
1053
- quests: (ctx, rest) => quests(ctx, rest),
1054
- assets: (ctx, rest) => assets(ctx, rest),
1055
- lore: (ctx, rest) => lore(ctx, rest),
1056
- world: (ctx) => world(ctx),
1057
- upload: (ctx, files) => upload(ctx, files),
1058
- clone: (ctx, rest) => clone(ctx, rest),
1059
- env: (ctx) => envCmd(ctx),
1060
- };
1061
-
1062
- function defaultIo() {
1063
- return {
1064
- fetch: (...a) => fetch(...a),
1065
- stdout: process.stdout,
1066
- stderr: process.stderr,
1067
- cwd: () => process.cwd(),
1068
- sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
1069
- // git, npm and zed for `plaiful clone`, attached to the terminal so their output and prompts show. → { status }
1070
- run: (cmd, args, { cwd, detached = false } = {}) => {
1071
- const shell = process.platform === 'win32'; // npm and zed are .cmd shims on Windows
1072
- try {
1073
- if (detached) {
1074
- const probe = spawnSync(cmd, ['--version'], { shell, stdio: 'ignore' });
1075
- if (probe.status !== 0) return { status: probe.status === null ? 1 : probe.status };
1076
- spawn(cmd, args, { cwd, shell, stdio: 'ignore', detached: true }).on('error', () => {}).unref();
1077
- return { status: 0 };
1078
- }
1079
- const r = spawnSync(cmd, args, { cwd, shell, stdio: 'inherit' });
1080
- return { status: r.status === null ? 1 : r.status };
1081
- } catch { return { status: 1 }; }
1082
- },
1083
- openUrl: (url) => {
1084
- const [cmd, args] = process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
1085
- : process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];
1086
- try { spawn(cmd, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref(); } catch { /* print-only */ }
1087
- },
1088
- };
1089
- }
1090
-
1091
- async function main(argv, io = defaultIo()) {
1092
- let flags = {};
1093
- try {
1094
- const parsed = parse(argv);
1095
- flags = parsed.flags;
1096
- if (flags.version) { io.stdout.write(`${version}\n`); return 0; }
1097
- const [a, b, ...rest] = parsed.args;
1098
- if (flags.help || !a || a === 'help') { io.stdout.write(`${HELP}\n`); return 0; }
1099
- const two = COMMANDS[`${a} ${b}`];
1100
- const one = COMMANDS[a];
1101
- const ctx = makeContext(io, flags);
1102
- if (two) return await two(ctx, rest);
1103
- if (one && !['ovid', 'midas'].includes(a)) return await one(ctx, b === undefined ? rest : [b, ...rest]);
1104
- throw new UsageError(`unknown command "${parsed.args.join(' ')}"`);
1105
- } catch (e) {
1106
- if (e instanceof UsageError) {
1107
- io.stderr.write(`plaiful: ${e.message}\n(plaiful help lists the commands)\n`);
1108
- return 2;
1109
- }
1110
- if (e instanceof ApiError) {
1111
- if (flags.json) io.stdout.write(`${JSON.stringify({ success: false, status: e.status, ...(e.body || {}), error: e.message }, null, 2)}\n`);
1112
- else io.stderr.write(`plaiful: ${e.message}\n`);
1113
- return 1;
1114
- }
1115
- io.stderr.write(`plaiful: ${e.stack || e.message}\n`);
1116
- return 1;
1117
- }
1118
- }
1119
-
1120
- module.exports = { main, parse };
1
+ 'use strict';
2
+
3
+ /**
4
+ * The Plaiful CLI (PlaifulCMS docs/system/product/PARTNER_API_AND_CLI.md §4). Every command talks to the partner API
5
+ * as the signed-in person; nothing needs AWS. `--json` prints the API's answer as JSON, for agents.
6
+ *
7
+ * Exit codes: 0 done; 1 the platform said no (invalid, denied, not signed in); 2 the command was wrong.
8
+ */
9
+
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const { spawn, spawnSync } = require('child_process');
13
+ const config = require('./config');
14
+ const { version } = require('../package.json');
15
+
16
+ const HELP = `plaiful ${version}: work on your Plaiful product from your game repo
17
+
18
+ plaiful login sign in (opens the CMS to approve; 12 hours)
19
+ plaiful logout sign out
20
+ plaiful whoami who you're signed in as, your studio, and the products you may manage
21
+ plaiful init [product] write .plaiful.json in this repo (product, env, docsDir) and make the folders
22
+ your files go in (resources/world/<product>/, …), each with a README
23
+ plaiful docs the platform docs (live): each doc, its summary, when it last changed
24
+ plaiful docs read <doc> one doc, current (--section "3.5" or a heading for one section)
25
+ plaiful docs search <words...> where the docs say it: each doc's best sections, with a snippet
26
+ plaiful docs changes [--since <date>] the docs changed since a date (default: the last 7 days)
27
+ plaiful docs pull write your product's own files (client-config.md) into docsDir; the platform
28
+ docs stay live (--copies also writes local copies, for offline work)
29
+ plaiful mcp an MCP server on stdio with the docs tools, signed in as you
30
+ (claude mcp add plaiful -- plaiful mcp)
31
+ plaiful ovid check [file] check your OVID declaration (default: <docsDir>/<product>-ovid-declaration.json)
32
+ plaiful ovid publish [file] check it and publish it; OVID reads it within about 5 minutes
33
+ plaiful ovid show the declaration OVID has now
34
+ plaiful seed world|lore|map|personas [paths] dry run: the rows your files make and what changes in dev
35
+ (default: every .json in resources/<store>/<product>/; personas = THESPIS
36
+ personas and situations)
37
+ --apply write them; --reset also put runtime state back to the files
38
+ --rows print every row
39
+ plaiful status what OVID and THESPIS have for your product in dev
40
+ plaiful quests the quests OVID wrote: steps and what each pays (--track <id>, --series <id>)
41
+ plaiful quests show <id> one quest: its graph, steps, reward hint and price (--json: the whole record)
42
+ plaiful lore the lore sets, with known / hidden snippet counts
43
+ plaiful lore show <setId> one set's snippets
44
+ plaiful world the world's states and state events in story order, and the clock
45
+ plaiful events script write <eventId> ask OVID for a cinematic script for a state event (a new draft version;
46
+ --note "<what to change>", --wait to wait for it, --force to start over)
47
+ plaiful events script get <eventId> [version] the script as a screenplay page, its versions and the last request
48
+ plaiful events script export <eventId> [version] --fountain|--vo the screenplay (Fountain) or the voice-over
49
+ sheet (CSV); --out <file> to write it to a file
50
+ plaiful lists your product's SSM lists (NPC roles, SmartBuilder list values, ...)
51
+ plaiful lists get <name> one list (a name in your namespace, e.g. shop_type, or the full /path)
52
+ plaiful lists set <name> <values...> write a list (values as words, or one comma-separated argument)
53
+ plaiful agents your product's SmartBuilder agents in dev
54
+ plaiful agents show <name> one agent's deployed config
55
+ plaiful agents deploy [files...] deploy or redeploy agents from their config files (default: every .json in
56
+ resources/agents/<product>/); a redeploy keeps the agent's own settings
57
+ plaiful agents run <name> [key=value...] make one record (placeholder values as key=value)
58
+ plaiful agents batch <name> [file] start a batch (a batch body file, or --count <n>) → a job id
59
+ plaiful agents status <name> <jobId> a batch's progress
60
+ plaiful records import <agent> [file] dry run: records you wrote, into the agent's table (default file:
61
+ resources/records/<product>/<agent>.json; matched on the agent's duplicate field)
62
+ --apply write them; --no-render don't make new records' art or sound
63
+ plaiful midas pricing what MIDAS pays per quest, in your reward kinds (delivered in each quest's rewards)
64
+ plaiful midas pricing set <kind> --base <n> --per-effort <n> price a kind (either option alone keeps the other)
65
+ plaiful midas pricing unset <kind> stop pricing a kind
66
+ plaiful midas pricing weight <step> <n> how much a quest step counts (combat, gather, explore, ...)
67
+ plaiful midas pricing apply [file] replace it all from a file (default:
68
+ resources/midas/<product>/quest-pricing.json; { kinds, objective_weights, ... })
69
+ plaiful assets per agent: records, and how many have their art made, pending, failed or none
70
+ plaiful assets <agent> its records: state, why a render failed, where the files are
71
+ --state made|pending|failed|none --limit <n> (default 50)
72
+ plaiful animation sets the animation sets you can use (a set = a list of animation states, one sprite
73
+ sheet each, run together on a character): the built-ins, Plaiful's and yours
74
+ plaiful animation sets show <id> one set's states
75
+ plaiful animation sets save [files...] save your own sets from files (default: every .json in
76
+ resources/animation/<product>/; { id, name, states: [{ name, method, prompt }], style_ref? })
77
+ plaiful animation sets delete <id> delete one of your sets
78
+ plaiful animation run <set> <agent> [uuids...] run a set on an agent's records (--all: every record with its art
79
+ made; --style <sprite style>, else the set's; --force: make them again)
80
+ plaiful upload <files...> upload map tiles into your dev assets bucket (map-data/; --dest map-data)
81
+ plaiful clone [product] [dir] clone the game repo, write .env.development, docs pull, npm install, open Zed
82
+ --no-install --no-open
83
+ plaiful env (re)write .env.development from your dev client config (keeps your own lines)
84
+
85
+ Options: --json (machine-readable output) --product <id> --api <url> --no-browser (login)
86
+ Environment: PLAIFUL_API_URL, PLAIFUL_TOKEN (instead of login: CI, with a product API key from the CMS)
87
+ Docs: docs/plaiful/README.md after \`plaiful docs pull\``;
88
+
89
+ class UsageError extends Error {}
90
+ class ApiError extends Error {
91
+ constructor(status, body) {
92
+ super((body && body.error) || `the platform answered ${status}`);
93
+ this.status = status;
94
+ this.body = body;
95
+ }
96
+ }
97
+
98
+ /** Where an agent list's values come from: an SSM path, or the values kept in the agent ({ values: [...] }). */
99
+ function listSource(v) {
100
+ if (v && typeof v === 'object' && Array.isArray(v.values)) return `in the agent (${v.values.length}: ${v.values.slice(0, 4).join(', ')}${v.values.length > 4 ? ', …' : ''})`;
101
+ if (v && typeof v === 'object') return v.path || JSON.stringify(v);
102
+ return String(v);
103
+ }
104
+
105
+ function parse(argv) {
106
+ const flags = {};
107
+ const args = [];
108
+ for (let i = 0; i < argv.length; i += 1) {
109
+ const a = argv[i];
110
+ if (['--json', '--no-browser', '--help', '-h', '--version', '--apply', '--reset', '--rows', '--no-install', '--no-open', '--copies', '--no-render', '--wait', '--force', '--fountain', '--vo', '--all'].includes(a)) flags[a.replace(/^-+/, '')] = true;
111
+ else if (['--product', '--api', '--dir', '--dest', '--count', '--base', '--per-effort', '--track', '--series', '--state', '--limit', '--section', '--since', '--note', '--out', '--style'].includes(a)) {
112
+ if (argv[i + 1] === undefined) throw new UsageError(`${a} needs a value`);
113
+ flags[a.slice(2)] = argv[i += 1];
114
+ } else if (a.startsWith('--')) throw new UsageError(`unknown option ${a}`);
115
+ else args.push(a);
116
+ }
117
+ return { flags, args };
118
+ }
119
+
120
+ function makeContext(io, flags) {
121
+ const url = config.apiUrl(flags);
122
+ const out = (text, json) => io.stdout.write(`${flags.json ? JSON.stringify(json === undefined ? text : json, null, 2) : text}\n`);
123
+ async function call(method, route, body, { auth = true } = {}) {
124
+ const headers = { Accept: 'application/json' };
125
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
126
+ if (auth) {
127
+ const token = config.tokenFor(url);
128
+ if (!token) throw new ApiError(401, { error: 'not signed in: run `plaiful login`', code: 'no_session' });
129
+ headers.Authorization = `Bearer ${token}`;
130
+ }
131
+ let res;
132
+ try {
133
+ res = await io.fetch(`${url}${route}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
134
+ } catch (e) {
135
+ throw new ApiError(0, { error: `can't reach the Plaiful API at ${url} (${e.message})`, code: 'network' });
136
+ }
137
+ let data = {};
138
+ try { data = await res.json(); } catch { /* empty body */ }
139
+ if (!res.ok && !(res.status === 422 || (res.status === 409 && data.errors))) throw new ApiError(res.status, data);
140
+ return { status: res.status, data };
141
+ }
142
+ return { url, flags, out, call, io };
143
+ }
144
+
145
+ function repo(ctx, { required = true } = {}) {
146
+ const found = config.findRepoConfig(ctx.io.cwd());
147
+ const product = ctx.flags.product || (found && found.config.product);
148
+ if (required && !product) throw new UsageError('no product: run `plaiful init <product>` in your repo, or pass --product');
149
+ const root = found ? found.root : ctx.io.cwd();
150
+ const docsDir = path.resolve(root, ctx.flags.dir || (found && found.config.docsDir) || config.DEFAULT_DOCS_DIR);
151
+ return { product, root, docsDir, found };
152
+ }
153
+
154
+ // ── Commands ────────────────────────────────────────────────────────────────────────────────────────────────────
155
+
156
+ async function login(ctx) {
157
+ const start = (await ctx.call('POST', '/partner/cli-login', undefined, { auth: false })).data;
158
+ ctx.io.stderr.write(`\nTo sign in, open:\n\n ${start.verification_url}\n\nand check the code matches: ${start.user_code}\n\n`);
159
+ if (!ctx.flags['no-browser']) ctx.io.openUrl(start.verification_url);
160
+ const deadline = Date.now() + start.expires_in * 1000;
161
+ let interval = (start.interval || 3) * 1000;
162
+ while (Date.now() < deadline) {
163
+ await ctx.io.sleep(interval);
164
+ const r = (await ctx.call('POST', '/partner/cli-login/token', { device_code: start.device_code }, { auth: false })).data;
165
+ if (r.status === 'approved') {
166
+ config.writeCredentials({ api_url: ctx.url, token: r.token, email: r.email, expires_at: r.expires_at });
167
+ ctx.out(`Signed in as ${r.email} until ${new Date(r.expires_at).toLocaleString()}.`, { success: true, email: r.email, expires_at: r.expires_at });
168
+ return 0;
169
+ }
170
+ interval = (r.interval || 3) * 1000;
171
+ }
172
+ throw new ApiError(410, { error: 'the sign-in wasn\'t approved in time; run `plaiful login` again', code: 'expired' });
173
+ }
174
+
175
+ async function logout(ctx) {
176
+ if (config.tokenFor(ctx.url)) {
177
+ try { await ctx.call('POST', '/partner/logout'); } catch { /* the local sign-out is what matters */ }
178
+ }
179
+ config.clearCredentials();
180
+ ctx.out('Signed out.', { success: true });
181
+ return 0;
182
+ }
183
+
184
+ async function whoami(ctx) {
185
+ const { data } = await ctx.call('GET', '/partner/whoami');
186
+ const lines = data.key
187
+ ? [`Product API key "${data.key.name}" for ${data.key.product} (${data.key.env}), issued by ${data.email}; scopes: ${data.key.scopes.join(', ')}`]
188
+ : [`${data.email}${data.staff ? ' (Plaiful staff)' : ''}, signed in until ${new Date(data.session_expires_at).toLocaleString()}`];
189
+ for (const st of data.studios || []) lines.push(`Studio: ${st.name} (${st.role}${st.preset ? `, ${st.preset}` : ''}${st.status !== 'active' ? `, ${st.status}` : ''})`);
190
+ lines.push(data.products.length ? 'Products:' : 'No products yet: create one in the CMS (Product deployment), or ask its owner to share it.');
191
+ for (const p of data.products) lines.push(` ${p.product_id} (${p.role})`);
192
+ ctx.out(lines.join('\n'), data);
193
+ return 0;
194
+ }
195
+
196
+ async function init(ctx, [product]) {
197
+ const { data } = await ctx.call('GET', '/partner/whoami');
198
+ const mine = data.products.map((p) => p.product_id);
199
+ const chosen = product || ctx.flags.product || (mine.length === 1 ? mine[0] : null);
200
+ if (!chosen) throw new UsageError(`which product? ${mine.length ? `yours: ${mine.join(', ')}` : 'you have none yet'} (plaiful init <product>)`);
201
+ if (!mine.includes(chosen)) throw new ApiError(403, { error: `${data.email} can't manage "${chosen}"${mine.length ? ` (yours: ${mine.join(', ')})` : ''}`, code: 'product_access' });
202
+ const existing = config.findRepoConfig(ctx.io.cwd());
203
+ const root = existing ? existing.root : ctx.io.cwd();
204
+ const next = { ...(existing ? existing.config : { env: 'dev', docsDir: config.DEFAULT_DOCS_DIR }), product: chosen };
205
+ const file = config.writeRepoConfig(root, next);
206
+ const made = makeLayout(root, chosen, next.docsDir);
207
+ const lines = [`Wrote ${path.relative(ctx.io.cwd(), file) || file}: product ${chosen}, docs in ${next.docsDir}.`];
208
+ if (made.length) lines.push(`Made ${made.length} folder(s): ${made.join(', ')}`);
209
+ lines.push('Next: plaiful docs pull');
210
+ ctx.out(lines.join('\n'), { success: true, file, config: next, made });
211
+ return 0;
212
+ }
213
+
214
+ // ── Where things go (product-repo-template.md) ──────────────────────────────────────────────────────────────────
215
+
216
+ /** The repo folders the platform's steps read from: [folder, what goes there]. */
217
+ function layout(product, docsDir) {
218
+ return [
219
+ [`resources/${product}-resources`, 'SmartBuilder agent specs (one markdown file per agent, pasted into SmartBuilder)'],
220
+ [`resources/agents/${product}`, 'agent configs as JSON, for plaiful agents deploy'],
221
+ [`resources/records/${product}`, 'records you write by hand, one <agent>.json per agent, for plaiful records import'],
222
+ [`resources/world/${product}`, 'the narrative scaffold, for plaiful seed world'],
223
+ [`resources/lore/${product}`, 'lore sets, for plaiful seed lore'],
224
+ [`resources/map/${product}`, 'places, for plaiful seed map'],
225
+ [`resources/personas/${product}`, 'THESPIS personas and situations, for plaiful seed personas'],
226
+ [`resources/midas/${product}`, 'quest-pricing.json, for plaiful midas pricing apply'],
227
+ [docsDir, `the pulled docs, and your ${product}-ovid-declaration.json (plaiful ovid check / publish)`],
228
+ ];
229
+ }
230
+
231
+ /** Agent specs (markdown with agent_name and prompt_template) outside resources/<product>-resources/, under docs/ or
232
+ * resources/. → relative paths */
233
+ function misplacedSpecs(root, product, docsDir) {
234
+ const home = path.join(root, 'resources', `${product}-resources`);
235
+ const out = [];
236
+ const walk = (dir, depth) => {
237
+ if (depth > 6 || !fs.existsSync(dir)) return;
238
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
239
+ const full = path.join(dir, e.name);
240
+ if (e.isDirectory()) {
241
+ if (!['node_modules', '.git'].includes(e.name) && full !== home && full !== docsDir) walk(full, depth + 1);
242
+ } else if (e.name.endsWith('.md')) {
243
+ try {
244
+ const text = fs.readFileSync(full, 'utf8');
245
+ if (/\bagent_name\b/.test(text) && /\bprompt_template\b/.test(text)) out.push(path.relative(root, full).replace(/\\/g, '/'));
246
+ } catch { /* unreadable: skip */ }
247
+ }
248
+ }
249
+ };
250
+ walk(path.join(root, 'docs'), 0);
251
+ walk(path.join(root, 'resources'), 0);
252
+ return out;
253
+ }
254
+
255
+ /** What to write in a folder's README when init makes it. */
256
+ const folderReadme = (folder, what) => `# ${folder}\n\n${what[0].toUpperCase()}${what.slice(1)}.\nMade by \`plaiful init\`; see docs/plaiful/product-repo-template.md.\n`;
257
+
258
+ /** The folders the platform's steps read from, each with a README saying what goes in it (an agent puts a file where
259
+ * a folder for it already exists). → the folders made */
260
+ function makeLayout(root, product, docsDir) {
261
+ const made = [];
262
+ for (const [folder, what] of layout(product, docsDir)) {
263
+ const dir = path.join(root, folder);
264
+ if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); made.push(folder); }
265
+ const readme = path.join(dir, 'README.md');
266
+ if (folder !== docsDir && !fs.existsSync(readme)) fs.writeFileSync(readme, folderReadme(folder, what));
267
+ }
268
+ return made;
269
+ }
270
+
271
+ function whereThingsGo(ctx, r) {
272
+ const lines = ['Where things go:'];
273
+ for (const [folder, what] of layout(r.product, path.relative(r.root, r.docsDir).replace(/\\/g, '/') || '.')) {
274
+ lines.push(` ${folder.padEnd(32)} ${what}${fs.existsSync(path.join(r.root, folder)) ? '' : ' (missing: plaiful init makes it)'}`);
275
+ }
276
+ const wrong = misplacedSpecs(r.root, r.product, r.docsDir);
277
+ if (wrong.length) {
278
+ lines.push(`! Agent specs outside resources/${r.product}-resources/ (move them there):`);
279
+ for (const f of wrong) lines.push(` ${f}`);
280
+ }
281
+ return { lines, misplaced: wrong };
282
+ }
283
+
284
+ const safeName = (key) => {
285
+ const base = path.basename(String(key));
286
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\.md$/.test(base)) return null;
287
+ return base;
288
+ };
289
+
290
+ // What docs pull leaves in docsDir when the platform docs are live (PLATFORM_DOCS_PORTAL.md §4).
291
+ const LIVE_DOCS_README = `# Plaiful docs
292
+
293
+ The platform docs are **live**, not copied here, so you always read the current version. Read them with the CLI, or
294
+ with the plaiful MCP tools in your coding assistant:
295
+
296
+ \`\`\`sh
297
+ plaiful docs # every doc, and when it last changed
298
+ plaiful docs read README # one doc (--section "3.5", or a heading, for one section)
299
+ plaiful docs search "batch template" # where the docs say it
300
+ plaiful docs changes --since 2026-10-20
301
+ plaiful mcp # the same as MCP tools: claude mcp add plaiful -- plaiful mcp
302
+ \`\`\`
303
+
304
+ Start with \`plaiful docs read README\`. Read a doc again when you start a task; don't keep a copy.
305
+
306
+ This folder holds your product's own files: \`client-config.md\` (your keys and endpoints: never commit it) and your
307
+ \`<product>-ovid-declaration.json\`. Written by \`plaiful docs pull\`.
308
+ `;
309
+
310
+ async function docsPull(ctx, r = repo(ctx)) {
311
+ const copies = !!ctx.flags.copies;
312
+ const { data } = await ctx.call('GET', `/partner/${encodeURIComponent(r.product)}/docs${copies ? '' : '?docs=none'}`);
313
+ fs.mkdirSync(r.docsDir, { recursive: true });
314
+ const platform = copies ? (data.docs || []) : [];
315
+ const files = [...platform, { key: data.client_config.key, title: 'Client config', content: data.client_config.content }];
316
+ const result = { written: [], unchanged: [], skipped: [], removed: [] };
317
+ // The platform-doc copies an earlier pull wrote ("replaced on every pull, never edit these"): gone, now they're live.
318
+ const indexFile = path.join(r.docsDir, '.plaiful-docs.json');
319
+ let before = [];
320
+ try { before = (JSON.parse(fs.readFileSync(indexFile, 'utf8')).docs || []).map((d) => d.file).filter(Boolean); } catch { before = []; }
321
+ const keep = new Set(files.map((f) => safeName(f.key)).filter(Boolean));
322
+ if (!copies) keep.add('README.md');
323
+ for (const name of before) {
324
+ const safe = safeName(name);
325
+ if (safe && !keep.has(safe) && fs.existsSync(path.join(r.docsDir, safe))) { fs.unlinkSync(path.join(r.docsDir, safe)); result.removed.push(safe); }
326
+ }
327
+ if (!copies) files.push({ key: 'README.md', title: 'Plaiful docs (live)', content: LIVE_DOCS_README });
328
+ for (const f of files) {
329
+ const name = safeName(f.key);
330
+ if (!name) { result.skipped.push(f.key); continue; }
331
+ const target = path.join(r.docsDir, name);
332
+ const prev = fs.existsSync(target) ? fs.readFileSync(target, 'utf8') : null;
333
+ if (prev === f.content) { result.unchanged.push(name); continue; }
334
+ fs.writeFileSync(target, f.content);
335
+ result.written.push(name);
336
+ }
337
+ const index = {
338
+ _note: copies
339
+ ? 'Written by `plaiful docs pull --copies`: copies as of pulled_at; the live docs are `plaiful docs`. Replaced on every pull.'
340
+ : 'Written by `plaiful docs pull`. The platform docs are live (`plaiful docs`); this folder holds the product\'s own files.',
341
+ mode: copies ? 'copies' : 'live',
342
+ product: r.product, env: data.env, pulled_at: new Date().toISOString(),
343
+ docs: files.map((f) => ({ file: safeName(f.key), title: f.title, description: f.description || '' })).filter((f) => f.file),
344
+ };
345
+ fs.writeFileSync(indexFile, `${JSON.stringify(index, null, 2)}\n`);
346
+ const ignore = ignoreClientConfig(r.docsDir);
347
+ const rel = path.relative(ctx.io.cwd(), r.docsDir) || '.';
348
+ const lines = [
349
+ `${rel}: ${result.written.length} updated, ${result.unchanged.length} unchanged${result.skipped.length ? `, ${result.skipped.length} skipped` : ''}.`,
350
+ ...result.written.map((n) => ` updated ${n}`),
351
+ ...result.removed.map((n) => ` removed ${n} (a platform doc: read it live, plaiful docs read ${n.replace(/\.md$/, '')})`),
352
+ ];
353
+ if (ignore.added.length) lines.push(` ${path.join(rel, '.gitignore')}: now keeps ${ignore.added.join(', ')} out of git`);
354
+ if (ignore.tracked.length) {
355
+ lines.push(`! Already committed, and holding your keys: ${ignore.tracked.join(', ')}. Take them out of git (the files stay):`);
356
+ lines.push(` git rm --cached ${ignore.tracked.map((f) => `"${path.relative(ctx.io.cwd(), path.join(r.docsDir, f)).replace(/\\/g, '/')}"`).join(' ')}`);
357
+ }
358
+ const where = whereThingsGo(ctx, r);
359
+ lines.push(...where.lines);
360
+ lines.push(copies ? 'Local copies as of now; the live docs are `plaiful docs`.' : 'The platform docs are live: plaiful docs (start with plaiful docs read README).');
361
+ ctx.out(lines.join('\n'), { success: true, dir: r.docsDir, ...result, gitignore: ignore, misplaced_specs: where.misplaced });
362
+ return 0;
363
+ }
364
+
365
+ // ── The live docs ─────────────────────────────────────────────────────────────────────────────────────────────────
366
+
367
+ const docsRoute = (rest = '', query = {}) => {
368
+ const qs = new URLSearchParams(Object.entries(query).filter(([, v]) => v !== undefined && v !== null && v !== ''));
369
+ return `/partner/platform/docs${rest}${qs.toString() ? `?${qs}` : ''}`;
370
+ };
371
+ const docName = (k) => String(k).replace(/\.md$/, '');
372
+ const day = (iso) => (iso ? String(iso).slice(0, 10) : ' ');
373
+
374
+ async function docsList(ctx) {
375
+ const { data } = await ctx.call('GET', docsRoute());
376
+ const docs = data.docs || [];
377
+ const lines = [`Plaiful docs (live): ${docs.length}. plaiful docs read <doc>`];
378
+ let section = null;
379
+ for (const d of [...docs].sort((a, b) => (a.order ?? 1e9) - (b.order ?? 1e9))) {
380
+ const s = d.section_title || d.category || 'Docs';
381
+ if (s !== section) { lines.push(`${s}:`); section = s; }
382
+ lines.push(` ${docName(d.key).padEnd(40)} ${day(d.updated_at)} ${d.label || d.title || ''}`);
383
+ }
384
+ ctx.out(lines.join('\n'), data);
385
+ return 0;
386
+ }
387
+
388
+ async function docsRead(ctx, [name]) {
389
+ if (!name) throw new UsageError('which doc? plaiful docs read <doc> (plaiful docs lists them)');
390
+ const { data } = await ctx.call('GET', docsRoute(`/${encodeURIComponent(docName(name))}`, { section: ctx.flags.section }));
391
+ ctx.out(data.content, data);
392
+ return 0;
393
+ }
394
+
395
+ async function docsSearch(ctx, words) {
396
+ const q = words.join(' ').trim();
397
+ if (!q) throw new UsageError('search for what? plaiful docs search <words...>');
398
+ const { data } = await ctx.call('GET', docsRoute('', { q, limit: ctx.flags.limit }));
399
+ const lines = data.results.length ? [`"${q}" in the docs:`] : [`Nothing in the docs mentions all of: ${q}`];
400
+ for (const r of data.results) {
401
+ lines.push(` ${docName(r.key)} (${r.title})`);
402
+ for (const sct of r.sections) lines.push(` § ${sct.heading || r.title}: ${sct.snippet}`);
403
+ }
404
+ if (data.results.length) lines.push('plaiful docs read <doc> --section "<heading>" for the whole section');
405
+ ctx.out(lines.join('\n'), data);
406
+ return 0;
407
+ }
408
+
409
+ async function docsChanges(ctx) {
410
+ const since = ctx.flags.since || new Date(Date.now() - 7 * 864e5).toISOString().slice(0, 10);
411
+ const { data } = await ctx.call('GET', docsRoute('', { since }));
412
+ const lines = [data.docs.length ? `Changed since ${since}:` : `No doc changed since ${since}.`];
413
+ for (const d of data.docs) lines.push(` ${day(d.updated_at)} ${docName(d.key).padEnd(40)} ${d.title || ''}`);
414
+ ctx.out(lines.join('\n'), data);
415
+ return 0;
416
+ }
417
+
418
+ // client-config.md holds the product's keys and endpoints (the Firebase web key among them), so it never goes in git;
419
+ // nor do the older hand-made `<product>-client-config.md` copies.
420
+ const CLIENT_CONFIG_IGNORES = ['client-config.md', '*-client-config.md'];
421
+
422
+ function ignoreClientConfig(docsDir) {
423
+ const file = path.join(docsDir, '.gitignore');
424
+ const prev = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
425
+ const have = new Set(prev.split(/\r?\n/).map((l) => l.trim()));
426
+ const added = CLIENT_CONFIG_IGNORES.filter((p) => !have.has(p));
427
+ if (added.length) {
428
+ const head = prev ? `${prev.replace(/\s*$/, '')}\n` : '# Written by `plaiful docs pull`: these files hold your product\'s keys.\n';
429
+ fs.writeFileSync(file, `${head}${added.join('\n')}\n`);
430
+ }
431
+ // A .gitignore doesn't untrack what's already committed; say so rather than leave the keys in the repo.
432
+ const git = spawnSync('git', ['ls-files', '--', ...CLIENT_CONFIG_IGNORES], { cwd: docsDir, encoding: 'utf8' });
433
+ const tracked = git.status === 0 ? git.stdout.split('\n').map((l) => l.trim()).filter(Boolean) : [];
434
+ return { added, tracked };
435
+ }
436
+
437
+ function readDeclaration(ctx, r, file) {
438
+ const target = path.resolve(ctx.io.cwd(), file || path.join(r.docsDir, `${r.product}-ovid-declaration.json`));
439
+ if (!fs.existsSync(target)) throw new UsageError(`no declaration at ${target} (write it first: ovid-declaration.md)`);
440
+ try { return { target, declaration: JSON.parse(fs.readFileSync(target, 'utf8')) }; } catch (e) {
441
+ throw new UsageError(`${target} isn't valid JSON: ${e.message}`);
442
+ }
443
+ }
444
+
445
+ function findingsText(data) {
446
+ const lines = [];
447
+ const where = (x) => `${x.file ? `${x.file} ` : ''}${x.path || '(top level)'}`;
448
+ for (const e of data.errors || []) lines.push(` ✗ ${where(e)}: ${e.message} [${e.doc}]`);
449
+ for (const w of data.warnings || []) lines.push(` ! ${where(w)}: ${w.message} [${w.doc}]`);
450
+ for (const n of data.notes || []) lines.push(` · ${n}`);
451
+ return lines;
452
+ }
453
+
454
+ async function ovidCheck(ctx, [file]) {
455
+ const r = repo(ctx);
456
+ const { target, declaration } = readDeclaration(ctx, r, file);
457
+ const { data } = await ctx.call('POST', `/partner/${encodeURIComponent(r.product)}/ovid/declaration/check`, { declaration });
458
+ const head = data.ok
459
+ ? `${path.basename(target)} is valid${(data.warnings || []).length ? `, with ${data.warnings.length} warning(s)` : ''}. Publish it with: plaiful ovid publish`
460
+ : `${path.basename(target)} has ${data.errors.length} error(s); fix them and check again.`;
461
+ ctx.out([head, ...findingsText(data)].join('\n'), data);
462
+ return data.ok ? 0 : 1;
463
+ }
464
+
465
+ async function ovidPublish(ctx, [file]) {
466
+ const r = repo(ctx);
467
+ const { target, declaration } = readDeclaration(ctx, r, file);
468
+ const { data } = await ctx.call('PUT', `/partner/${encodeURIComponent(r.product)}/ovid/declaration`, { declaration });
469
+ if (!data.published) {
470
+ ctx.out([`Not published: ${data.error || `${path.basename(target)} has ${(data.errors || []).length} error(s)`}`, ...findingsText(data)].join('\n'), data);
471
+ return 1;
472
+ }
473
+ const lines = [`Published ${path.basename(target)} for ${r.product}; OVID reads it ${data.takes_effect}.`];
474
+ if (data.tabs && data.tabs.error) lines.push(` ! ${data.tabs.error}`);
475
+ lines.push(...findingsText(data));
476
+ lines.push('Check it took: GameMaster shows your tier labels, tracks and regions (plaiful ovid show prints what OVID has).');
477
+ ctx.out(lines.join('\n'), data);
478
+ return 0;
479
+ }
480
+
481
+ async function ovidShow(ctx) {
482
+ const r = repo(ctx);
483
+ const { data } = await ctx.call('GET', `/partner/${encodeURIComponent(r.product)}/ovid/declaration`);
484
+ if (ctx.flags.json) { ctx.out(data); return 0; }
485
+ if (!data.declaration) ctx.out(data.packaged ? `${r.product}'s declaration is packaged: ${data.packaged}` : `${r.product} has no OVID declaration yet (OVID uses its defaults).`);
486
+ else ctx.out(`Published ${data.updated_at || '(date unknown)'}${data.published_by ? ` by ${data.published_by}` : ''}:\n${JSON.stringify(data.declaration, null, 2)}`);
487
+ return 0;
488
+ }
489
+
490
+ // ── Seeding (phase 2) ──────────────────────────────────────────────────────────────────────────────────────────
491
+
492
+ const STORES = ['world', 'lore', 'map', 'personas'];
493
+ const SEED_ROUTE = { world: 'ovid/world', lore: 'ovid/lore', map: 'ovid/map', personas: 'thespis/personas' };
494
+ const MARK = { create: '+', update: '~', remove: '-', keep: '=' };
495
+
496
+ /** The JSON files to send: the paths given (files or folders), else resources/<store>/<product>/. */
497
+ function seedFiles(ctx, r, store, paths) {
498
+ const targets = paths.length ? paths.map((x) => path.resolve(ctx.io.cwd(), x)) : [path.join(r.root, 'resources', store, r.product)];
499
+ const files = [];
500
+ for (const t of targets) {
501
+ if (!fs.existsSync(t)) throw new UsageError(`${t} doesn't exist${paths.length ? '' : ` (put your ${store} files there, or pass their paths)`}`);
502
+ const list = fs.statSync(t).isDirectory()
503
+ ? fs.readdirSync(t).filter((n) => n.toLowerCase().endsWith('.json')).sort().map((n) => path.join(t, n))
504
+ : [t];
505
+ for (const file of list) {
506
+ let content;
507
+ try { content = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { throw new UsageError(`${file} isn't valid JSON: ${e.message}`); }
508
+ files.push({ name: path.relative(r.root, file).replace(/\\/g, '/'), content });
509
+ }
510
+ }
511
+ if (!files.length) throw new UsageError(`no .json files in ${targets.join(', ')}`);
512
+ return files;
513
+ }
514
+
515
+ async function seedStore(ctx, store, paths) {
516
+ if (!STORES.includes(store)) throw new UsageError(`seed what? world, lore, map or personas (plaiful seed ${STORES.join('|')})`);
517
+ const r = repo(ctx);
518
+ const files = seedFiles(ctx, r, store, paths);
519
+ const apply = !!ctx.flags.apply;
520
+ const reset = !!ctx.flags.reset;
521
+ const { data } = await ctx.call('POST', `/partner/${encodeURIComponent(r.product)}/${SEED_ROUTE[store]}/seed`, { files, apply, reset, rows: !!ctx.flags.rows });
522
+ if (ctx.flags.json) { ctx.out(data); return data.ok ? 0 : 1; }
523
+ const lines = [];
524
+ if (!data.ok) {
525
+ lines.push(`${files.length} ${store} file(s) have ${data.errors.length} error(s); nothing was ${apply ? 'written' : 'planned'}. Fix them and run it again.`);
526
+ lines.push(...findingsText(data));
527
+ ctx.out(lines.join('\n'));
528
+ return 1;
529
+ }
530
+ const s = data.summary;
531
+ const counts = Object.entries(data.counts || {}).map(([k, v]) => `${v} ${k}`).join(', ');
532
+ lines.push(`${store} for ${r.product} (dev, ${data.table}): ${counts}.`);
533
+ lines.push(`${apply ? 'Wrote' : 'Would write'}: ${s.create} new, ${s.update} changed, ${s.remove} removed, ${s.unchanged} unchanged${s.kept ? `, ${s.kept} kept as they are` : ''}.`);
534
+ if (data.unmanaged) lines.push(` · ${data.unmanaged} row(s) there weren't written by plaiful seed (${store === 'personas' ? 'the Tuning Studio\'s' : 'OVID\'s, the CMS\'s'}, or an older seeder's): left alone.`);
535
+ const shown = data.items.slice(0, 40);
536
+ for (const i of shown) lines.push(` ${MARK[i.action] || '?'} ${i.action.padEnd(6)} ${String(i.kind).padEnd(14)} ${i.id}${i.note ? ` (${i.note})` : ''}`);
537
+ if (data.items.length > shown.length) lines.push(` … and ${data.items.length - shown.length} more (--json lists them all)`);
538
+ lines.push(...findingsText(data));
539
+ if (ctx.flags.rows) lines.push(JSON.stringify(data.rows, null, 2));
540
+ if (!apply) lines.push(data.writes ? `Dry run: nothing written. Write it with: plaiful seed ${store}${paths.length ? ` ${paths.join(' ')}` : ''}${reset ? ' --reset' : ''} --apply` : 'Dry run: dev already matches your files.');
541
+ else if (data.writes) lines.push('Check it with: plaiful status');
542
+ ctx.out(lines.join('\n'));
543
+ return 0;
544
+ }
545
+
546
+ async function status(ctx) {
547
+ const r = repo(ctx);
548
+ const { data } = await ctx.call('GET', `/partner/${encodeURIComponent(r.product)}/status`);
549
+ if (ctx.flags.json) { ctx.out(data); return 0; }
550
+ const w = data.world || {};
551
+ const l = data.lore || {};
552
+ const m = data.map || {};
553
+ const d = data.declaration || {};
554
+ const err = (x) => (x.error ? ` ${x.error}` : null);
555
+ const lines = [`${r.product} in dev:`];
556
+ lines.push(` world ${err(w) || `${w.events} events (${w.macro} macro, ${w.meso} meso, ${w.micro} micro${w.state_events ? `, ${w.state_events} state events` : ''}), ${w.seeded} seeded`}`);
557
+ if (!w.error) lines.push(` clock: ${w.clock ? `${w.clock.mode}, at ${w.clock.currentMicro} (${w.clock.chapterTitle})` : 'not set (seed a worldClock, or set it in GameMaster)'}`);
558
+ lines.push(` lore ${err(l) || `${l.sets} sets, ${l.snippets} snippets (${l.known} known, ${l.hidden} hidden), ${l.seeded} rows seeded${l.without_product ? `; ${l.without_product} snippets lack "product" and never reach a character` : ''}`}`);
559
+ lines.push(` map ${err(m) || `${m.locations} locations, ${m.settlements} settlements (${m.settlements_with_npcs} with NPCs), ${m.seeded} seeded`}`);
560
+ const t = data.thespis || {};
561
+ lines.push(` thespis ${err(t) || `${t.personas} personas (${t.active_personas} active), ${t.situations} situations, ${t.seeded} seeded`}`);
562
+ lines.push(` declaration ${d.declared ? `published ${d.updated_at || ''}: tiers ${d.timeline ? [d.timeline.macro, d.timeline.meso, d.timeline.micro].join(' / ') : '(defaults)'}; regions ${(d.regions || []).join(', ') || 'none'}; tracks ${(d.tracks || []).join(', ') || '(default)'}` : 'none yet (plaiful ovid publish)'}`);
563
+ ctx.out(lines.join('\n'));
564
+ return 0;
565
+ }
566
+
567
+ // ── Lists and uploads (phase 3) ──────────────────────────────────────────────────────────────────────────────────
568
+
569
+ /** The route for a list: a name in the namespace goes in the path; a full /path goes in ?path=. */
570
+ function listRoute(r, name) {
571
+ const base = `/partner/${encodeURIComponent(r.product)}/lists`;
572
+ if (!name) return base;
573
+ if (name.startsWith('/')) return `${base}?path=${encodeURIComponent(name)}`;
574
+ return `${base}/${name.split('/').map(encodeURIComponent).join('/')}`;
575
+ }
576
+
577
+ async function lists(ctx, [sub, name, ...values]) {
578
+ const r = repo(ctx);
579
+ if (!sub) {
580
+ const { data } = await ctx.call('GET', listRoute(r));
581
+ const lines = [`${r.product}'s lists in dev (${data.namespace}):`];
582
+ if (!data.lists.length) lines.push(' none yet (plaiful lists set <name> <values...>)');
583
+ for (const l of data.lists) lines.push(` ${l.name}${l.type === 'String' ? ' (a setting)' : ''} ${l.values.join(', ')}`);
584
+ ctx.out(lines.join('\n'), data);
585
+ return 0;
586
+ }
587
+ if (sub === 'get') {
588
+ if (!name) throw new UsageError('which list? plaiful lists get <name>');
589
+ const { data } = await ctx.call('GET', listRoute(r, name));
590
+ ctx.out(`${data.name}: ${data.values.join(', ')}`, data);
591
+ return 0;
592
+ }
593
+ if (sub === 'set') {
594
+ if (!name || !values.length) throw new UsageError('plaiful lists set <name> <values...> (e.g. plaiful lists set shop_type tavern blacksmith healer)');
595
+ const parsed = (values.length === 1 ? values[0].split(',') : values).map((v) => v.trim()).filter(Boolean);
596
+ const { data } = await ctx.call('PUT', listRoute(r, name), { values: parsed });
597
+ const was = data.previous === null ? 'new' : `was: ${data.previous.join(', ')}`;
598
+ ctx.out(`${data.name} = ${data.values.join(', ')} (${was})`, data);
599
+ return 0;
600
+ }
601
+ throw new UsageError(`plaiful lists, lists get <name> or lists set <name> <values...> (not "${sub}")`);
602
+ }
603
+
604
+ // ── SmartBuilder agents ─────────────────────────────────────────────────────────────────────────────────────
605
+
606
+ const agentRoute = (r, rest = '') => `/partner/${encodeURIComponent(r.product)}/agents${rest}`;
607
+ const AGENT_NAME = /^[a-z0-9][a-z0-9-]{0,62}$/;
608
+
609
+ function readJsonFile(ctx, f) {
610
+ const file = path.resolve(ctx.io.cwd(), f);
611
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw new UsageError(`${file} isn't a file`);
612
+ try { return { file, json: JSON.parse(fs.readFileSync(file, 'utf8')) }; } catch (e) { throw new UsageError(`${file} isn't valid JSON (${e.message})`); }
613
+ }
614
+
615
+ /** The config files to deploy: the ones named, or every .json in resources/agents/<product>/. */
616
+ function agentFiles(ctx, r, files) {
617
+ if (files.length) return files;
618
+ const dir = path.join(ctx.io.cwd(), 'resources', 'agents', r.product);
619
+ if (!fs.existsSync(dir)) throw new UsageError(`no files named, and no ${path.relative(ctx.io.cwd(), dir)}/ folder: plaiful agents deploy <file.json>`);
620
+ const found = fs.readdirSync(dir).filter((n) => n.endsWith('.json')).map((n) => path.join(dir, n));
621
+ if (!found.length) throw new UsageError(`${path.relative(ctx.io.cwd(), dir)}/ has no .json agent configs`);
622
+ return found;
623
+ }
624
+
625
+ async function agents(ctx, [sub, name, ...rest]) {
626
+ const r = repo(ctx);
627
+ if (!sub) {
628
+ const { data } = await ctx.call('GET', agentRoute(r));
629
+ const list = data.agents || [];
630
+ const lines = [`${r.product}'s SmartBuilder agents in dev:`];
631
+ if (!list.length) lines.push(' none yet (plaiful agents deploy <file.json>, or SmartBuilder in the CMS)');
632
+ for (const a of list) lines.push(` ${a.name || a.agent_name}${a.display_name ? ` ${a.display_name}` : ''}${a.business_purpose ? ` (${a.business_purpose})` : ''}`);
633
+ ctx.out(lines.join('\n'), data);
634
+ return 0;
635
+ }
636
+ if (sub === 'show') {
637
+ if (!name) throw new UsageError('which agent? plaiful agents show <name>');
638
+ const { data } = await ctx.call('GET', agentRoute(r, `/${encodeURIComponent(name)}`));
639
+ const a = data.agent || {};
640
+ const lines = [`${a.agent_name || name}: ${a.display_name || ''}`.trim(),
641
+ ` table ${(a.storage || {}).table_name || '?'}, version ${(a.metadata || {}).version || '?'}, ${(a.metadata || {}).business_purpose || 'content'}`,
642
+ ` fields ${(a.output_fields || []).join(', ')}`,
643
+ ` lists ${Object.entries(a.ssm_parameters || {}).map(([k, v]) => `${k} ← ${listSource(v)}`).join('; ') || 'none'}`,
644
+ ` dedup ${a.duplicate_detection && a.duplicate_detection.enabled !== false ? `on ${[].concat(a.duplicate_detection.field || 'name').join(', ')}` : 'off'}`,
645
+ ' (--json prints the whole config)'];
646
+ ctx.out(lines.join('\n'), data);
647
+ return 0;
648
+ }
649
+ if (sub === 'deploy') {
650
+ const files = agentFiles(ctx, r, [name, ...rest].filter(Boolean));
651
+ const done = [];
652
+ for (const f of files) {
653
+ const { file, json } = readJsonFile(ctx, f);
654
+ const agentName = json.agent_name || path.basename(file, '.json');
655
+ if (!AGENT_NAME.test(agentName)) throw new UsageError(`${path.basename(file)}: "${agentName}" isn't an agent name (lowercase letters, digits, hyphens)`);
656
+ const { data } = await ctx.call('POST', agentRoute(r, `/${agentName}`), { config: json });
657
+ done.push(data);
658
+ if (!ctx.flags.json) ctx.out(`${data.redeployed ? 'redeployed' : 'deployed'} ${data.agent_name}: table ${data.table_name}${data.table === 'created' ? ' (new)' : ''}, version ${data.version}`);
659
+ }
660
+ if (ctx.flags.json) ctx.out('', { success: true, product: r.product, deployed: done });
661
+ return 0;
662
+ }
663
+ if (sub === 'run') {
664
+ if (!name) throw new UsageError('which agent? plaiful agents run <name> [key=value...]');
665
+ const body = {};
666
+ for (const kv of rest) {
667
+ const i = kv.indexOf('=');
668
+ if (i < 1) throw new UsageError(`"${kv}" isn't key=value`);
669
+ body[kv.slice(0, i)] = kv.slice(i + 1);
670
+ }
671
+ const { data } = await ctx.call('POST', agentRoute(r, `/${encodeURIComponent(name)}/run`), body);
672
+ const rec = data.item || data.record || data;
673
+ ctx.out(`made ${rec.uuid || 'a record'}${rec.name ? `: ${rec.name}` : ''}`, data);
674
+ return 0;
675
+ }
676
+ if (sub === 'batch') {
677
+ if (!name) throw new UsageError('which agent? plaiful agents batch <name> [batch-body.json] (or --count <n>)');
678
+ let body;
679
+ if (rest[0]) body = readJsonFile(ctx, rest[0]).json;
680
+ else if (ctx.flags.count) body = { count: Number(ctx.flags.count) };
681
+ else throw new UsageError('give a batch body file, or --count <n>');
682
+ const { data } = await ctx.call('POST', agentRoute(r, `/${encodeURIComponent(name)}/batch`), body);
683
+ ctx.out(`started batch ${data.job_id} (${data.total_items || '?'} records). plaiful agents status ${name} ${data.job_id}`, data);
684
+ return 0;
685
+ }
686
+ if (sub === 'status') {
687
+ const [jobId] = rest;
688
+ if (!name || !jobId) throw new UsageError('plaiful agents status <name> <jobId>');
689
+ const { data } = await ctx.call('GET', agentRoute(r, `/${encodeURIComponent(name)}/batch/${encodeURIComponent(jobId)}`));
690
+ ctx.out(`${data.status || '?'}: ${data.completed_items ?? '?'} done, ${data.failed_items ?? 0} failed of ${data.total_items ?? '?'}`, data);
691
+ return 0;
692
+ }
693
+ throw new UsageError(`plaiful agents, or agents show | deploy | run | batch | status (not "${sub}")`);
694
+ }
695
+
696
+ /** `plaiful records import <agent> [file]`: records written by hand into the agent's table, saved as the agent saves
697
+ * the ones it makes; a dry run unless --apply. The file: a list of records, or { "records": [...] }. */
698
+ async function records(ctx, [sub, name, file]) {
699
+ if (sub !== 'import') throw new UsageError(`plaiful records import <agent> [file] (not "${sub || ''}")`);
700
+ const r = repo(ctx);
701
+ if (!name) throw new UsageError('which agent? plaiful records import <agent> [file] (default file: resources/records/<product>/<agent>.json)');
702
+ if (!AGENT_NAME.test(name)) throw new UsageError(`"${name}" isn't an agent name (lowercase letters, digits, hyphens)`);
703
+ const f = file || path.join(path.relative(ctx.io.cwd(), r.root) || '.', 'resources', 'records', r.product, `${name}.json`);
704
+ const { json } = readJsonFile(ctx, f);
705
+ const list = Array.isArray(json) ? json : json && Array.isArray(json.records) ? json.records : null;
706
+ if (!list) throw new UsageError(`${f}: give a list of records, or { "records": [...] }`);
707
+ if (!list.length) throw new UsageError(`${f} has no records`);
708
+ const apply = !!ctx.flags.apply;
709
+ const { data } = await ctx.call('POST', agentRoute(r, `/${encodeURIComponent(name)}/import`), { records: list, apply, render: !ctx.flags['no-render'] });
710
+ if (ctx.flags.json) { ctx.out(data); return data.success ? 0 : 1; }
711
+ const lines = [];
712
+ if (!data.success) {
713
+ lines.push(`${data.error || 'the import was refused'}. Fix them and run it again.`);
714
+ for (const e of data.errors || []) lines.push(` ✗ ${e.error}`);
715
+ ctx.out(lines.join('\n'));
716
+ return 1;
717
+ }
718
+ const s = data.summary;
719
+ lines.push(`${name} for ${r.product} (dev, ${data.table_name})${data.key_field ? `, matched on ${data.key_field}` : ''}:`);
720
+ lines.push(`${data.applied ? 'Wrote' : 'Would write'}: ${s.create} new, ${s.update} changed, ${s.unchanged} unchanged.`);
721
+ const shown = data.records.filter((x) => x.action !== 'unchanged').slice(0, 40);
722
+ const label = (x) => (x.key !== null && x.key !== undefined ? x.key : x.uuid);
723
+ for (const x of shown) lines.push(` ${MARK[x.action]} ${x.action === 'create' ? 'new ' : 'change'} ${label(x)}${x.action === 'update' ? ` (${x.changed.join(', ')})` : ''}`);
724
+ const more = s.create + s.update - shown.length;
725
+ if (more > 0) lines.push(` … and ${more} more (--json lists them all)`);
726
+ for (const w of data.warnings || []) lines.push(` ! ${w}`);
727
+ const stale = data.records.filter((x) => x.stale_art).map(label);
728
+ if (stale.length) lines.push(` ! ${stale.length} changed record(s) keep the art or sound made from their old text (${stale.slice(0, 5).join(', ')}${stale.length > 5 ? ', …' : ''}): make it again in the CMS Library.`);
729
+ if (!data.applied) {
730
+ lines.push(s.create + s.update ? `Dry run: nothing written. Write it with: plaiful records import ${name}${file ? ` ${file}` : ''} --apply` : 'Dry run: the table already matches your file.');
731
+ } else if (data.rendering) lines.push(`Making the art or sound for ${data.rendering} new record(s): plaiful assets ${name}`);
732
+ ctx.out(lines.join('\n'));
733
+ return 0;
734
+ }
735
+
736
+ // ── What OVID has: quests, lore, the world ──────────────────────────────────────────────────────────────────────
737
+
738
+ const ovidRoute = (r, rest) => `/partner/${encodeURIComponent(r.product)}/ovid/${rest}`;
739
+ const priceText = (p) => (p && Object.keys(p).length ? Object.entries(p).map(([k, v]) => `${v} ${k}`).join(', ') : '');
740
+
741
+ async function quests(ctx, [sub, id]) {
742
+ const r = repo(ctx);
743
+ if (sub === 'show') {
744
+ if (!id) throw new UsageError('which quest? plaiful quests show <id>');
745
+ const { data } = await ctx.call('GET', ovidRoute(r, `quests/${encodeURIComponent(id)}`));
746
+ const q = data.quest || {};
747
+ const lines = [`${data.title || id} [${data.questType || '?'}] track ${data.quest_track || '?'}${data.series ? `, ${data.series.series_title || data.series.series_id} #${data.series.series_order}` : ''} (${data.status || '?'})`];
748
+ if (q.narrative_desc || q.description) lines.push(` ${q.narrative_desc || q.description}`);
749
+ for (const st of data.steps_detail || []) {
750
+ const n = (q.nodes || {})[st.id] || {};
751
+ const say = n.close || n.narrative_desc || (n.dialogue_tree && n.dialogue_tree.nodes && Object.values(n.dialogue_tree.nodes)[0] && Object.values(n.dialogue_tree.nodes)[0].text) || '';
752
+ lines.push(` ${st.unreached ? '(unreached) ' : ''}${st.id}: ${st.type}${st.count > 1 ? `×${st.count}` : ''}${say ? ` "${String(say).slice(0, 90)}${String(say).length > 90 ? '…' : ''}"` : ''}`);
753
+ }
754
+ lines.push(` pays: ${priceText(data.price) || (data.priced ? 'nothing (no step carries effort)' : 'not priced yet (plaiful midas pricing)')}${data.reward_hint ? `; hint: ${data.reward_hint.kinds.join(', ')}` : ''}`);
755
+ lines.push(' (--json prints the whole record)');
756
+ ctx.out(lines.join('\n'), data);
757
+ return 0;
758
+ }
759
+ if (sub) throw new UsageError(`plaiful quests, or quests show <id> (not "${sub}")`);
760
+ const qs = new URLSearchParams();
761
+ if (ctx.flags.track) qs.set('track', ctx.flags.track);
762
+ if (ctx.flags.series) qs.set('series', ctx.flags.series);
763
+ const { data } = await ctx.call('GET', `${ovidRoute(r, 'quests')}${qs.toString() ? `?${qs}` : ''}`);
764
+ const lines = [`${r.product}'s quests in dev: ${data.count}${data.priced ? '' : ' (not priced yet: plaiful midas pricing)'}`];
765
+ let group = null;
766
+ for (const q of data.quests) {
767
+ const g = `${q.quest_track || '?'}${q.series ? ` · ${q.series.series_title || q.series.series_id}` : ''}`;
768
+ if (g !== group) { lines.push(` ${g}`); group = g; }
769
+ const pays = priceText(q.price);
770
+ lines.push(` ${q.series ? `${q.series.series_order}. ` : ''}${q.title} [${q.questType || '?'}] ${q.steps.join(' → ')}${pays ? ` pays ${pays}` : ''} ${q.quest_id}`);
771
+ }
772
+ if (data.truncated) lines.push(' (cut off: more quests than one read returns)');
773
+ ctx.out(lines.join('\n'), data);
774
+ return 0;
775
+ }
776
+
777
+ async function lore(ctx, [sub, id]) {
778
+ const r = repo(ctx);
779
+ if (sub === 'show') {
780
+ if (!id) throw new UsageError('which set? plaiful lore show <setId>');
781
+ const { data } = await ctx.call('GET', ovidRoute(r, `lore/${encodeURIComponent(id)}`));
782
+ const lines = [`${data.title || id}${data.category ? ` (${data.category})` : ''}`];
783
+ for (const sn of data.snippets || []) lines.push(` ${sn.world_known ? 'known ' : 'hidden'} ${sn.title || sn.snippet_id}${sn.narrative ? `: ${String(sn.narrative).slice(0, 100)}${String(sn.narrative).length > 100 ? '…' : ''}` : ''}`);
784
+ ctx.out(lines.join('\n'), data);
785
+ return 0;
786
+ }
787
+ if (sub) throw new UsageError(`plaiful lore, or lore show <setId> (not "${sub}")`);
788
+ const { data } = await ctx.call('GET', ovidRoute(r, 'lore'));
789
+ const lines = [`${r.product}'s lore in dev: ${data.sets.length} sets`];
790
+ for (const st of data.sets) lines.push(` ${st.lore_set_id} ${st.title || ''} ${st.snippets} snippets (${st.known} known, ${st.hidden} hidden)${st.source === 'plaiful-seed' ? '' : st.source ? ` from ${st.source}` : ''}`);
791
+ ctx.out(lines.join('\n'), data);
792
+ return 0;
793
+ }
794
+
795
+ async function world(ctx) {
796
+ const r = repo(ctx);
797
+ const { data } = await ctx.call('GET', ovidRoute(r, 'world'));
798
+ const c = data.clock;
799
+ const lines = [`${r.product}'s world in dev: ${data.events.length} states and events; clock ${c ? `${c.mode || '?'}, at ${c.currentMicro || '?'}${c.chapterTitle ? ` (${c.chapterTitle})` : ''}` : 'not set'}`];
800
+ const indent = { macro: ' ', meso: ' ', micro: ' ' };
801
+ for (const e of data.events) {
802
+ const pad = e.kind === 'event' ? ' ' : (indent[e.scope] || ' ');
803
+ lines.push(`${pad}${e.kind === 'event' ? '· ' : ''}${e.title || e.event_id} ${e.scope || e.kind}${e.faction ? `, ${e.faction}` : ''}${e.advances ? ', advances' : ''}${c && e.event_id === c.currentMicro ? ' ← now' : ''} ${e.event_id}`);
804
+ }
805
+ if (data.truncated) lines.push(' (cut off: more rows than one read returns)');
806
+ ctx.out(lines.join('\n'), data);
807
+ return 0;
808
+ }
809
+
810
+ // ── Event scripts: OVID's cinematic for a state event ────────────────────────────────────────────────────────────
811
+
812
+ const SCRIPT_WAIT_MS = 5 * 60 * 1000;
813
+ const SCRIPT_POLL_MS = 5000;
814
+
815
+ function scriptHeader(data) {
816
+ const s = data.script;
817
+ const vs = (data.versions || []).map((v) => v.version);
818
+ const head = s
819
+ ? `${s.title || data.event_id}: v${s.version} ${s.status}, ${s.runtime_sec} s, ${(s.lines || []).length} lines${vs.length > 1 ? ` (versions ${vs.join(', ')})` : ''}`
820
+ : `${data.event_id}: no script yet`;
821
+ const j = data.job;
822
+ const lines = [head];
823
+ if (j && j.status !== 'done') lines.push(` last request: ${j.status}${j.requestedAt ? ` (${j.requestedAt})` : ''}${j.message ? `: ${j.message}` : ''}`);
824
+ if (j && j.status !== 'done' && (j.lastErrors || []).length) for (const e of j.lastErrors) lines.push(` - ${e}`);
825
+ if (s && s.soter && ((s.soter.changes || []).length || (s.soter.flags || []).length)) {
826
+ lines.push(` Soter (${s.soter.mode}): ${(s.soter.changes || []).length} change(s), ${(s.soter.flags || []).length} flag(s)${s.soter.mode === 'shadow' ? ' it would make; nothing was changed' : ''}`);
827
+ for (const f of s.soter.flags || []) lines.push(` flag ${f.beat || ''}: ${f.why}`);
828
+ }
829
+ return lines;
830
+ }
831
+
832
+ async function eventsScript(ctx, [sub, eventId, version]) {
833
+ const r = repo(ctx);
834
+ if (!['write', 'get', 'export'].includes(sub)) throw new UsageError(`plaiful events script write | get | export <eventId> (not "${sub || ''}")`);
835
+ if (!eventId) throw new UsageError(`which event? plaiful events script ${sub} <eventId> (plaiful world lists them)`);
836
+ if (version !== undefined && !/^\d+$/.test(version)) throw new UsageError(`the version is a number (not "${version}")`);
837
+ const route = ovidRoute(r, `events/${encodeURIComponent(eventId)}/script`);
838
+ const get = async (format) => {
839
+ const qs = new URLSearchParams();
840
+ if (format) qs.set('format', format);
841
+ if (version) qs.set('version', version);
842
+ return (await ctx.call('GET', `${route}${qs.toString() ? `?${qs}` : ''}`)).data;
843
+ };
844
+ if (sub === 'write') {
845
+ if (version !== undefined) throw new UsageError('write makes a new version; it takes no version number');
846
+ const { data } = await ctx.call('POST', route, { ...(ctx.flags.note ? { note: ctx.flags.note } : {}), ...(ctx.flags.force ? { force: true } : {}) });
847
+ const job = data.job || {};
848
+ if (!ctx.flags.wait) {
849
+ ctx.out(`${data.already ? 'OVID is already writing' : 'Asked OVID for'} a script for ${eventId} (job ${job.jobId}). It takes a minute or two: plaiful events script get ${eventId}`, data);
850
+ return 0;
851
+ }
852
+ const until = Date.now() + SCRIPT_WAIT_MS;
853
+ let now = null;
854
+ while (Date.now() < until) {
855
+ await ctx.io.sleep(SCRIPT_POLL_MS);
856
+ now = await get('fountain');
857
+ if (now.job && now.job.jobId === job.jobId && now.job.status !== 'running') break;
858
+ }
859
+ const done = now && now.job && now.job.jobId === job.jobId && now.job.status === 'done';
860
+ const lines = now ? scriptHeader(now) : [`${eventId}: no answer yet`];
861
+ if (!now || !now.job || now.job.status === 'running') lines.push(` still writing after ${SCRIPT_WAIT_MS / 60000} minutes: plaiful events script get ${eventId}`);
862
+ if (done && now.text) lines.push('', now.text);
863
+ ctx.out(lines.join('\n'), now || data);
864
+ return done ? 0 : 1;
865
+ }
866
+ if (sub === 'get') {
867
+ const data = await get('fountain');
868
+ const lines = scriptHeader(data);
869
+ if (data.text) lines.push('', data.text);
870
+ ctx.out(lines.join('\n'), data);
871
+ return 0;
872
+ }
873
+ const fmt = ctx.flags.vo ? 'vo' : ctx.flags.fountain ? 'fountain' : null;
874
+ if (!fmt || (ctx.flags.vo && ctx.flags.fountain)) throw new UsageError('export as --fountain (the screenplay) or --vo (the voice-over sheet)');
875
+ const data = await get(fmt);
876
+ if (!data.script) throw new ApiError(404, { error: `${eventId} has no script yet: plaiful events script write ${eventId}`, code: 'no_script' });
877
+ if (ctx.flags.out) {
878
+ const file = path.resolve(ctx.io.cwd(), ctx.flags.out);
879
+ fs.writeFileSync(file, data.text, 'utf8');
880
+ ctx.out(`wrote ${eventId} v${data.script.version} (${fmt === 'vo' ? 'voice-over sheet' : 'screenplay'}) to ${file}`, { ...data, file });
881
+ return 0;
882
+ }
883
+ if (ctx.flags.json) ctx.out('', data);
884
+ else ctx.io.stdout.write(data.text.endsWith('\n') ? data.text : `${data.text}\n`);
885
+ return 0;
886
+ }
887
+
888
+ // ── What the agents made ────────────────────────────────────────────────────────────────────────────────────────
889
+
890
+ const countsText = (a) => `${a.records} records: ${a.made} made, ${a.pending} pending, ${a.failed} failed, ${a.none} none yet${a.truncated ? ' (first 2000)' : ''}`;
891
+
892
+ async function assets(ctx, [agent]) {
893
+ const r = repo(ctx);
894
+ const base = `/partner/${encodeURIComponent(r.product)}/assets`;
895
+ if (!agent) {
896
+ const { data } = await ctx.call('GET', base);
897
+ const lines = [`${r.product}'s agents in dev${data.cdn ? ` (files on https://${data.cdn}/)` : ''}:`];
898
+ if (!data.agents.length) lines.push(' none yet (plaiful agents deploy)');
899
+ for (const a of data.agents) {
900
+ lines.push(` ${a.name.padEnd(24)} ${a.error ? `couldn't read: ${a.error}` : a.makes_art ? countsText(a) : '(makes no art)'}`);
901
+ }
902
+ ctx.out(lines.join('\n'), data);
903
+ return 0;
904
+ }
905
+ const qs = new URLSearchParams();
906
+ if (ctx.flags.state) qs.set('state', ctx.flags.state);
907
+ if (ctx.flags.limit) qs.set('limit', ctx.flags.limit);
908
+ const { data } = await ctx.call('GET', `${base}/${encodeURIComponent(agent)}${qs.toString() ? `?${qs}` : ''}`);
909
+ const lines = [`${agent}: ${countsText(data.counts)}${ctx.flags.state ? `; ${data.matching} ${ctx.flags.state}` : ''}${data.shown < data.matching ? `, showing ${data.shown} (--limit)` : ''}`];
910
+ for (const rec of data.records) {
911
+ const why = rec.render_error || Object.entries(rec.media || {}).filter(([, m]) => m.error).map(([k, m]) => `${k}: ${m.error}`).join('; ');
912
+ const files = [rec.files && `${rec.files.base}.{${rec.files.try.join('|')}}`, ...Object.values(rec.media_files || {})].filter(Boolean);
913
+ const where = rec.state === 'made' ? files.join(' ') : '';
914
+ lines.push(` ${rec.state.padEnd(8)} ${rec.name || '(unnamed)'} ${rec.uuid}${why ? ` ${why}` : ''}${where ? ` ${where}` : ''}`);
915
+ }
916
+ ctx.out(lines.join('\n'), data);
917
+ return 0;
918
+ }
919
+
920
+ // ── MIDAS quest pricing ─────────────────────────────────────────────────────────────────────────────────────────
921
+
922
+ const pricingRoute = (r) => `/partner/${encodeURIComponent(r.product)}/midas/pricing`;
923
+
924
+ function nonNegative(v, what) {
925
+ const n = Number(v);
926
+ if (v === undefined || v === true || !Number.isFinite(n) || n < 0) throw new UsageError(`${what} must be a number, 0 or more`);
927
+ return n;
928
+ }
929
+
930
+ function pricingLines(product, data) {
931
+ const qp = data.quest_pricing || {};
932
+ const kinds = qp.kinds || {};
933
+ const declared = ((data.rewards || {}).types || []).filter((k) => k !== 'lore');
934
+ const names = [...new Set([...declared, ...Object.keys(kinds)])];
935
+ const d = data.defaults || {};
936
+ const weights = { ...(d.objective_weights || {}), ...(qp.objective_weights || {}) };
937
+ const lines = [`${product}'s quest pricing in dev: price = base + per-effort × the quest's effort`];
938
+ if (!names.length) lines.push(' no reward kinds declared (settings.rewards.types in your OVID declaration)');
939
+ for (const k of names) {
940
+ const p = kinds[k];
941
+ lines.push(` ${k.padEnd(12)} ${p ? `base ${p.base ?? 0}, per effort ${p.per_objective ?? 0}` : 'not priced (plaiful midas pricing set ' + k + ' --base <n> --per-effort <n>)'}`);
942
+ }
943
+ lines.push(` effort: each step's weight, +${qp.count_effort ?? d.count_effort} of it per extra unit (units counted up to ${qp.count_cap ?? d.count_cap})`);
944
+ lines.push(` weights: ${Object.entries(weights).map(([t, w]) => `${t} ${w}`).join(', ')}`);
945
+ for (const w of data.warnings || []) lines.push(` note: ${w}`);
946
+ return lines;
947
+ }
948
+
949
+ async function midasPricing(ctx, [sub, name, value]) {
950
+ const r = repo(ctx);
951
+ if (!sub) {
952
+ const { data } = await ctx.call('GET', pricingRoute(r));
953
+ ctx.out(pricingLines(r.product, data).join('\n'), data);
954
+ return 0;
955
+ }
956
+ const save = async (qp) => {
957
+ const { data } = await ctx.call('PUT', pricingRoute(r), { quest_pricing: qp });
958
+ ctx.out([...pricingLines(r.product, data), ` ${data.note || 'saved'}`].join('\n'), data);
959
+ return 0;
960
+ };
961
+ if (sub === 'apply') {
962
+ const f = name || path.join('resources', 'midas', r.product, 'quest-pricing.json');
963
+ const { json } = readJsonFile(ctx, f);
964
+ return save(json.quest_pricing !== undefined ? json.quest_pricing : json);
965
+ }
966
+ if (!['set', 'unset', 'weight'].includes(sub)) throw new UsageError(`plaiful midas pricing, or pricing set | unset | weight | apply (not "${sub}")`);
967
+ if (!name) throw new UsageError(sub === 'weight' ? 'plaiful midas pricing weight <step> <n>' : `which kind? plaiful midas pricing ${sub} <kind>`);
968
+ const { data } = await ctx.call('GET', pricingRoute(r));
969
+ const qp = JSON.parse(JSON.stringify(data.quest_pricing || {}));
970
+ if (sub === 'weight') {
971
+ qp.objective_weights = { ...(qp.objective_weights || {}), [name]: nonNegative(value, 'the weight') };
972
+ } else if (sub === 'unset') {
973
+ if (!qp.kinds || !qp.kinds[name]) throw new UsageError(`${name} isn't priced`);
974
+ delete qp.kinds[name];
975
+ } else {
976
+ if (ctx.flags.base === undefined && ctx.flags['per-effort'] === undefined) throw new UsageError(`plaiful midas pricing set ${name} --base <n> --per-effort <n>`);
977
+ const cur = (qp.kinds && qp.kinds[name]) || { base: 0, per_objective: 0 };
978
+ qp.kinds = {
979
+ ...(qp.kinds || {}),
980
+ [name]: {
981
+ base: ctx.flags.base === undefined ? cur.base : nonNegative(ctx.flags.base, '--base'),
982
+ per_objective: ctx.flags['per-effort'] === undefined ? cur.per_objective : nonNegative(ctx.flags['per-effort'], '--per-effort'),
983
+ },
984
+ };
985
+ }
986
+ return save(qp);
987
+ }
988
+
989
+ // ── Animation sets (SPRITE_ANIMATION.md §5) ─────────────────────────────────────────────────────────────────────
990
+
991
+ const animationRoute = (r, rest = '') => `/partner/${encodeURIComponent(r.product)}/animation${rest}`;
992
+ const setLine = (x) => ` ${x.id.padEnd(22)} ${x.name}: ${x.states.length} states${x.builtin ? ' (built-in)' : x.yours ? ' (yours)' : ''}${x.style_ref ? `, style ${x.style_ref}` : ''}`;
993
+
994
+ async function animationSets(ctx, [sub, ...rest]) {
995
+ const r = repo(ctx);
996
+ if (!sub) {
997
+ const { data } = await ctx.call('GET', animationRoute(r, '/sets'));
998
+ const lines = [`Animation sets ${r.product} can use:`, ...data.sets.map(setLine),
999
+ `Sprite styles: ${data.sprite_styles.length ? data.sprite_styles.map((st) => st.id).join(', ') : 'none yet (make one in the CMS Styles tab, media Sprite animation)'}`];
1000
+ ctx.out(lines.join('\n'), data);
1001
+ return 0;
1002
+ }
1003
+ if (sub === 'show') {
1004
+ if (!rest[0]) throw new UsageError('plaiful animation sets show <id>');
1005
+ const { data } = await ctx.call('GET', animationRoute(r, `/sets/${encodeURIComponent(rest[0])}`));
1006
+ const x = data.set;
1007
+ const lines = [`${x.name} (${x.id})${x.description ? `: ${x.description}` : ''}`, ...x.states.map((st) => ` ${st.name.padEnd(14)} ${st.method.padEnd(6)} ${st.prompt || ''}`)];
1008
+ ctx.out(lines.join('\n'), data);
1009
+ return 0;
1010
+ }
1011
+ if (sub === 'delete') {
1012
+ if (!rest[0]) throw new UsageError('plaiful animation sets delete <id>');
1013
+ const { data } = await ctx.call('DELETE', animationRoute(r, `/sets/${encodeURIComponent(rest[0])}`));
1014
+ ctx.out(`Deleted ${rest[0]}. Records keep the sheets it made.`, data);
1015
+ return 0;
1016
+ }
1017
+ if (sub === 'save') {
1018
+ let files = rest;
1019
+ if (!files.length) {
1020
+ const dir = path.join(ctx.io.cwd(), 'resources', 'animation', r.product);
1021
+ if (!fs.existsSync(dir)) throw new UsageError(`no files named, and no ${path.relative(ctx.io.cwd(), dir)}/ folder: plaiful animation sets save <file.json>`);
1022
+ files = fs.readdirSync(dir).filter((n) => n.endsWith('.json')).map((n) => path.join(dir, n));
1023
+ if (!files.length) throw new UsageError(`${path.relative(ctx.io.cwd(), dir)}/ has no .json sets`);
1024
+ }
1025
+ for (const f of files) {
1026
+ const { file, json } = readJsonFile(ctx, f);
1027
+ if (!json.id) throw new UsageError(`${file}: a set needs an id (lowercase letters, digits and -)`);
1028
+ const { status, data } = await ctx.call('PUT', animationRoute(r, `/sets/${encodeURIComponent(json.id)}`), json);
1029
+ if (status >= 400) throw new ApiError(status, data);
1030
+ ctx.out(`Saved ${json.id}: ${(data.set && data.set.states.length) || 0} states.`, data);
1031
+ }
1032
+ return 0;
1033
+ }
1034
+ throw new UsageError(`plaiful animation sets, or sets show | save | delete (not "${sub}")`);
1035
+ }
1036
+
1037
+ async function animationRun(ctx, [setId, agent, ...uuids]) {
1038
+ const r = repo(ctx);
1039
+ if (!setId || !agent) throw new UsageError('plaiful animation run <set> <agent> [uuids...] (or --all)');
1040
+ if (!uuids.length && !ctx.flags.all) throw new UsageError('name the records (uuids), or --all for every record with its art made');
1041
+ const { data } = await ctx.call('POST', animationRoute(r, '/run'), {
1042
+ set: setId, agent, ...(ctx.flags.all ? { all: true } : { records: uuids }), ...(ctx.flags.style ? { style: ctx.flags.style } : {}), ...(ctx.flags.force ? { force: true } : {}),
1043
+ });
1044
+ const jobs = data.jobs || [];
1045
+ const lines = [`${setId} on ${agent} (style ${data.style}): ${jobs.length} sheet${jobs.length === 1 ? '' : 's'} started, ${(data.skipped || []).length} already made or running`];
1046
+ for (const x of (data.invalid || []).slice(0, 20)) lines.push(` skipped ${x.uuid || '?'}${x.state ? ` ${x.state}` : ''}: ${x.error}`);
1047
+ if (jobs.length) lines.push('They take a minute or two each; plaiful assets <agent> shows the records.');
1048
+ ctx.out(lines.join('\n'), data);
1049
+ return 0;
1050
+ }
1051
+
1052
+ async function upload(ctx, files) {
1053
+ const r = repo(ctx);
1054
+ if (!files.length) throw new UsageError('upload what? plaiful upload <files...> (map tiles: ovid-map-*.json)');
1055
+ const dest = ctx.flags.dest || 'map-data';
1056
+ const done = [];
1057
+ for (const f of files) {
1058
+ const file = path.resolve(ctx.io.cwd(), f);
1059
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw new UsageError(`${file} isn't a file`);
1060
+ const body = fs.readFileSync(file);
1061
+ const { data } = await ctx.call('POST', `/partner/${encodeURIComponent(r.product)}/uploads`, { dest, name: path.basename(file), size: body.length });
1062
+ let res;
1063
+ try {
1064
+ res = await ctx.io.fetch(data.url, { method: data.method || 'PUT', headers: data.headers, body });
1065
+ } catch (e) {
1066
+ throw new ApiError(0, { error: `the upload of ${path.basename(file)} didn't go through (${e.message})`, code: 'network' });
1067
+ }
1068
+ if (!res.ok) throw new ApiError(res.status, { error: `storage refused ${path.basename(file)} (${res.status}); run the upload again`, code: 'upload_failed' });
1069
+ done.push({ file: path.basename(file), bucket: data.bucket, key: data.key, size: body.length });
1070
+ }
1071
+ ctx.out([`Uploaded ${done.length} file(s) to ${r.product}'s dev assets:`, ...done.map((d) => ` ${d.file} → s3://${d.bucket}/${d.key} (${d.size} bytes)`)].join('\n'), { success: true, uploaded: done });
1072
+ return 0;
1073
+ }
1074
+
1075
+ // ── Clone and .env (the New-Game Flow) ───────────────────────────────────────────────────────────────────────────
1076
+
1077
+ /** The game template's .env variables (plaiful-kit packages/client config.ts ENV_KEYS) ← the client config. */
1078
+ const ENV_FROM_CONFIG = {
1079
+ VITE_PLAIFUL_PRODUCT: (c) => c.productId,
1080
+ VITE_PLAIFUL_ENV: (c) => c.environment,
1081
+ VITE_PLAIFUL_API_BASE: (c) => c.apiBaseUrl,
1082
+ VITE_PLAIFUL_CDN_BASE: (c) => c.assetCdnUrl,
1083
+ VITE_FIREBASE_PROJECT_ID: (c) => c.firebase && c.firebase.projectId,
1084
+ VITE_FIREBASE_API_KEY: (c) => c.firebase && c.firebase.webApiKey,
1085
+ VITE_FIREBASE_AUTH_DOMAIN: (c) => c.firebase && c.firebase.authDomain,
1086
+ VITE_PLAIFUL_OVID_BASE: (c) => c.ovidApiUrl,
1087
+ VITE_PLAIFUL_PRISM_WS_URL: (c) => c.prismWsUrl,
1088
+ VITE_PLAIFUL_ANALYTICS_INGEST: (c) => c.analyticsIngestUrl,
1089
+ VITE_PLAIFUL_ANALYTICS_KEY: (c, game) => game.analytics_ingest_key,
1090
+ };
1091
+ const ENV_FILE = '.env.development';
1092
+ // "(pending)", "(not deployed ...)" and "<...>" placeholders aren't values (the template's config.ts treats them as missing).
1093
+ const usable = (v) => typeof v === 'string' && v !== '' && !/^\(|not deployed|^</.test(v);
1094
+
1095
+ /**
1096
+ * Write .env.development in `root` from the game's dev client config: start from the file as it is (or the
1097
+ * template's .env.development.example), set the variables the platform knows, keep every other line.
1098
+ * → { file, set: [names], missing: [names] } or null when the repo has neither file (not the web template).
1099
+ */
1100
+ function writeEnv(root, game) {
1101
+ const file = path.join(root, ENV_FILE);
1102
+ const example = path.join(root, `${ENV_FILE}.example`);
1103
+ const base = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : fs.existsSync(example) ? fs.readFileSync(example, 'utf8') : null;
1104
+ if (base === null) return null;
1105
+ const set = [];
1106
+ const missing = [];
1107
+ const lines = base.split(/\r?\n/).map((line) => {
1108
+ const m = /^\s*([A-Z0-9_]+)\s*=(.*)$/.exec(line);
1109
+ if (!m || !ENV_FROM_CONFIG[m[1]]) return line;
1110
+ const v = ENV_FROM_CONFIG[m[1]](game.client_config || {}, game);
1111
+ if (!usable(v)) { if (!m[2].trim()) missing.push(m[1]); return line; }
1112
+ set.push(m[1]);
1113
+ return `${m[1]}=${v}`;
1114
+ });
1115
+ fs.writeFileSync(file, lines.join('\n'));
1116
+ return { file, set, missing };
1117
+ }
1118
+
1119
+ function envLines(env, game) {
1120
+ if (!env) return [` · no ${ENV_FILE}(.example) here: not the web game template, so no .env was written (the client config is in docs/plaiful/client-config.md)`];
1121
+ const out = [` ${ENV_FILE}: ${env.set.length} value(s) from your dev client config`];
1122
+ if (env.missing.length) {
1123
+ const why = game.analytics_ingest_key_note && env.missing.includes('VITE_PLAIFUL_ANALYTICS_KEY') ? ` (the analytics key: ${game.analytics_ingest_key_note})` : '';
1124
+ out.push(` ! still empty: ${env.missing.join(', ')}${why}`);
1125
+ }
1126
+ return out;
1127
+ }
1128
+
1129
+ async function envCmd(ctx) {
1130
+ const r = repo(ctx);
1131
+ const { data } = await ctx.call('GET', `/partner/${encodeURIComponent(r.product)}/game`);
1132
+ const env = writeEnv(r.root, data);
1133
+ if (!env) throw new UsageError(`no ${ENV_FILE} or ${ENV_FILE}.example in ${r.root}: this repo isn't the web game template`);
1134
+ ctx.out([`${r.product} (dev):`, ...envLines(env, data)].join('\n'), { success: true, ...env });
1135
+ return 0;
1136
+ }
1137
+
1138
+ async function clone(ctx, [productArg, dirArg]) {
1139
+ let product = productArg || ctx.flags.product;
1140
+ if (!product) {
1141
+ const { data } = await ctx.call('GET', '/partner/whoami');
1142
+ if (data.products.length !== 1) throw new UsageError(`which game? ${data.products.length ? `yours: ${data.products.map((p) => p.product_id).join(', ')}` : 'you have none yet'} (plaiful clone <product>)`);
1143
+ product = data.products[0].product_id;
1144
+ }
1145
+ const { data: game } = await ctx.call('GET', `/partner/${encodeURIComponent(product)}/game`);
1146
+ if (!game.clone_url) throw new ApiError(409, { error: `${product} has no repo to clone yet: ${game.summary}`, code: 'no_repo' });
1147
+ const repoLabel = (game.game_repo && game.game_repo.repo) || game.clone_url;
1148
+ const repoName = String((game.game_repo && game.game_repo.repo) || product).split('/').pop().replace(/\.git$/, '');
1149
+ const dir = path.resolve(ctx.io.cwd(), dirArg || repoName);
1150
+ if (fs.existsSync(dir) && fs.readdirSync(dir).length) throw new UsageError(`${dir} already exists and isn't empty; pass another folder: plaiful clone ${product} <dir>`);
1151
+ ctx.io.stderr.write(`Cloning ${game.clone_url} into ${dir}...\n`);
1152
+ const git = ctx.io.run('git', ['clone', game.clone_url, dir], { cwd: ctx.io.cwd() });
1153
+ if (git.status !== 0) {
1154
+ throw new ApiError(1, {
1155
+ error: `git couldn't clone ${repoLabel}. You need access to it on GitHub (ask the product's owner, or Plaiful, to add your account) and git signed in to GitHub (gh auth login, or Git Credential Manager).`,
1156
+ code: 'clone_failed',
1157
+ });
1158
+ }
1159
+ const rel = path.relative(ctx.io.cwd(), dir) || '.';
1160
+ const steps = [`Cloned ${repoLabel} into ${rel}.`];
1161
+ const existing = config.findRepoConfig(dir);
1162
+ const own = existing && existing.root === dir ? existing.config : null;
1163
+ if (!own) config.writeRepoConfig(dir, { product, env: 'dev', docsDir: config.DEFAULT_DOCS_DIR });
1164
+ const made = makeLayout(dir, product, (own && own.docsDir) || config.DEFAULT_DOCS_DIR);
1165
+ if (made.length) steps.push(`Made ${made.length} folder(s) your files go in: ${made.join(', ')}`);
1166
+ const r = { product, root: dir, docsDir: path.resolve(dir, (own && own.docsDir) || config.DEFAULT_DOCS_DIR) };
1167
+ steps.push(...envLines(writeEnv(dir, game), game));
1168
+ await docsPull({ ...ctx, out: () => {} }, r);
1169
+ steps.push(` ${path.relative(dir, r.docsDir).replace(/\\/g, '/')}: the onboarding docs and client-config.md`);
1170
+ if (fs.existsSync(path.join(dir, 'package.json')) && !ctx.flags['no-install']) {
1171
+ ctx.io.stderr.write('npm install...\n');
1172
+ const npm = ctx.io.run('npm', ['install'], { cwd: dir });
1173
+ steps.push(npm.status === 0 ? ' npm install: done'
1174
+ : ' ! npm install failed. The @plaiful packages need npm access to the plaiful org (npm login; ask Plaiful), then run npm install there.');
1175
+ }
1176
+ if (!ctx.flags['no-open']) {
1177
+ const zed = ctx.io.run('zed', [dir], { cwd: dir, detached: true });
1178
+ steps.push(zed.status === 0 ? ' opened in Zed' : ' open it in your editor (Zed isn\'t installed)');
1179
+ }
1180
+ steps.push(`Next: cd ${rel}, npm run dev. docs/plaiful/README.md is the guide.`);
1181
+ ctx.out(steps.join('\n'), { success: true, product, dir, clone_url: game.clone_url, game_repo: game.game_repo });
1182
+ return 0;
1183
+ }
1184
+
1185
+ const COMMANDS = {
1186
+ login: (ctx) => login(ctx),
1187
+ logout: (ctx) => logout(ctx),
1188
+ whoami: (ctx) => whoami(ctx),
1189
+ init: (ctx, rest) => init(ctx, rest),
1190
+ 'docs pull': (ctx) => docsPull(ctx),
1191
+ 'docs read': (ctx, rest) => docsRead(ctx, rest),
1192
+ 'docs search': (ctx, rest) => docsSearch(ctx, rest),
1193
+ 'docs changes': (ctx) => docsChanges(ctx),
1194
+ docs: (ctx, rest) => {
1195
+ if (rest.length) throw new UsageError(`plaiful docs, or docs read | search | changes | pull (not "${rest[0]}")`);
1196
+ return docsList(ctx);
1197
+ },
1198
+ mcp: (ctx) => require('./mcp').serve(ctx),
1199
+ 'ovid check': (ctx, rest) => ovidCheck(ctx, rest),
1200
+ 'ovid publish': (ctx, rest) => ovidPublish(ctx, rest),
1201
+ 'ovid show': (ctx) => ovidShow(ctx),
1202
+ seed: (ctx, [store, ...paths]) => seedStore(ctx, store, paths),
1203
+ status: (ctx) => status(ctx),
1204
+ lists: (ctx, rest) => lists(ctx, rest),
1205
+ agents: (ctx, rest) => agents(ctx, rest),
1206
+ records: (ctx, rest) => records(ctx, rest),
1207
+ 'midas pricing': (ctx, rest) => midasPricing(ctx, rest),
1208
+ quests: (ctx, rest) => quests(ctx, rest),
1209
+ assets: (ctx, rest) => assets(ctx, rest),
1210
+ lore: (ctx, rest) => lore(ctx, rest),
1211
+ world: (ctx) => world(ctx),
1212
+ 'events script': (ctx, rest) => eventsScript(ctx, rest),
1213
+ 'animation sets': (ctx, rest) => animationSets(ctx, rest),
1214
+ 'animation run': (ctx, rest) => animationRun(ctx, rest),
1215
+ upload: (ctx, files) => upload(ctx, files),
1216
+ clone: (ctx, rest) => clone(ctx, rest),
1217
+ env: (ctx) => envCmd(ctx),
1218
+ };
1219
+
1220
+ function defaultIo() {
1221
+ return {
1222
+ fetch: (...a) => fetch(...a),
1223
+ stdout: process.stdout,
1224
+ stderr: process.stderr,
1225
+ cwd: () => process.cwd(),
1226
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
1227
+ // git, npm and zed for `plaiful clone`, attached to the terminal so their output and prompts show. → { status }
1228
+ run: (cmd, args, { cwd, detached = false } = {}) => {
1229
+ const shell = process.platform === 'win32'; // npm and zed are .cmd shims on Windows
1230
+ try {
1231
+ if (detached) {
1232
+ const probe = spawnSync(cmd, ['--version'], { shell, stdio: 'ignore' });
1233
+ if (probe.status !== 0) return { status: probe.status === null ? 1 : probe.status };
1234
+ spawn(cmd, args, { cwd, shell, stdio: 'ignore', detached: true }).on('error', () => {}).unref();
1235
+ return { status: 0 };
1236
+ }
1237
+ const r = spawnSync(cmd, args, { cwd, shell, stdio: 'inherit' });
1238
+ return { status: r.status === null ? 1 : r.status };
1239
+ } catch { return { status: 1 }; }
1240
+ },
1241
+ openUrl: (url) => {
1242
+ const [cmd, args] = process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
1243
+ : process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];
1244
+ try { spawn(cmd, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref(); } catch { /* print-only */ }
1245
+ },
1246
+ };
1247
+ }
1248
+
1249
+ async function main(argv, io = defaultIo()) {
1250
+ let flags = {};
1251
+ try {
1252
+ const parsed = parse(argv);
1253
+ flags = parsed.flags;
1254
+ if (flags.version) { io.stdout.write(`${version}\n`); return 0; }
1255
+ const [a, b, ...rest] = parsed.args;
1256
+ if (flags.help || !a || a === 'help') { io.stdout.write(`${HELP}\n`); return 0; }
1257
+ const two = COMMANDS[`${a} ${b}`];
1258
+ const one = COMMANDS[a];
1259
+ const ctx = makeContext(io, flags);
1260
+ if (two) return await two(ctx, rest);
1261
+ if (one && !['ovid', 'midas', 'events', 'animation'].includes(a)) return await one(ctx, b === undefined ? rest : [b, ...rest]);
1262
+ throw new UsageError(`unknown command "${parsed.args.join(' ')}"`);
1263
+ } catch (e) {
1264
+ if (e instanceof UsageError) {
1265
+ io.stderr.write(`plaiful: ${e.message}\n(plaiful help lists the commands)\n`);
1266
+ return 2;
1267
+ }
1268
+ if (e instanceof ApiError) {
1269
+ if (flags.json) io.stdout.write(`${JSON.stringify({ success: false, status: e.status, ...(e.body || {}), error: e.message }, null, 2)}\n`);
1270
+ else io.stderr.write(`plaiful: ${e.message}\n`);
1271
+ return 1;
1272
+ }
1273
+ io.stderr.write(`plaiful: ${e.stack || e.message}\n`);
1274
+ return 1;
1275
+ }
1276
+ }
1277
+
1278
+ module.exports = { main, parse };