gcf-aif-ext 0.16.1 → 0.18.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,787 @@
1
+ // The design as parts a board edits field by field (Board-PRD §5.24): PILLARS.md, game.md,
2
+ // glossary.md, a subsystem's purpose, a unit. A part reads as the fields its CNL-P profile
3
+ // declares; a save writes the edited fields back into the part's text and brings it in as a
4
+ // one-part bundle (lib/bundle.js), so a form edit passes the same three-way check and the same
5
+ // design check a designer's import does. The board writes no file of gcf/ itself.
6
+ import { readFile, readdir, rm } from 'node:fs/promises';
7
+ import { existsSync } from 'node:fs';
8
+ import { spawnSync } from 'node:child_process';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { parseBlocks, itemsOf, readRecords } from 'cnlp-kit';
12
+ import {
13
+ HEADER_KEYS,
14
+ SLUG_RE,
15
+ UNIT_TYPES,
16
+ CARD_TYPES,
17
+ loadDocProfile,
18
+ parseDesign,
19
+ provenanceOf,
20
+ readDesign,
21
+ slotValues,
22
+ listOf,
23
+ } from './design.js';
24
+ import { DOC_FILES, hashOf, importBundle, parseBundle, purposeOf, unitText } from './bundle.js';
25
+ import {
26
+ REQUIRED_HEADER,
27
+ designCheck,
28
+ gameMilestones,
29
+ recordsIn,
30
+ uncovered,
31
+ } from './design-check.js';
32
+ import { commitMove } from './unit-ops.js';
33
+ import { locked } from './main-lock.js';
34
+ import { buildLedger } from './ledger.js';
35
+ import { deriveId } from './id.js';
36
+ import { renamePillar } from './pillars.js';
37
+ import { dirtyPaths } from './git.js';
38
+
39
+ const PROFILES_DIR = fileURLToPath(new URL('../profiles/', import.meta.url));
40
+ // The work stage writes these blocks: a unit in design/ has not reached them.
41
+ const WORK_ONLY = ['contract', 'interactions', 'tuning', 'notes'];
42
+ // What a unit's header field takes, for the form's help.
43
+ const HEADER_NOTES = {
44
+ type: UNIT_TYPES.join(' | '),
45
+ title: 'one line: what it gives',
46
+ route: 'soft|hard (<why, one line>): mechanic and resource are soft, the rest hard',
47
+ system: '[subsystems]: the first is the file it lives in',
48
+ milestone: 'a milestone of game.md, later or TBD',
49
+ pillars: '[pillar ids] or TBD',
50
+ depends: '[ids it waits for] or none',
51
+ source: 'GDD#<anchor> or manual',
52
+ flags: 'src-changed, orphan, impl?',
53
+ reopens: 'the ended id it reopens',
54
+ };
55
+ const PURPOSE = {
56
+ key: 'purpose',
57
+ form: 'bullet-list',
58
+ required: true,
59
+ recordKeys: [],
60
+ optionalRecordKeys: [],
61
+ note: 'why the subsystem exists',
62
+ };
63
+
64
+ const readIf = async (file) => (existsSync(file) ? readFile(file, 'utf8') : null);
65
+ const lf = (t) => String(t ?? '').replace(/\r\n/g, '\n');
66
+
67
+ /** The `note:` of each section a profile declares: the help a form shows beside its field. */
68
+ async function notesOf(name) {
69
+ const raw = await readFile(path.join(PROFILES_DIR, `${name}.md`), 'utf8');
70
+
71
+ return new Map(recordsIn(raw, 'sections').map((r) => [r.key, r.note ?? null]));
72
+ }
73
+
74
+ /** The fields of a part: a unit's header, then the blocks of its profile, in their order. */
75
+ async function specsOf(kind, name, type) {
76
+ if (kind === 'system') return [PURPOSE];
77
+ const profile = kind === 'doc' ? name : `unit-${type}`;
78
+ const notes = await notesOf(profile);
79
+ const blocks = (await loadDocProfile(profile)).sections
80
+ .filter((s) => s.key !== 'provenance' && !(kind === 'unit' && WORK_ONLY.includes(s.key)))
81
+ .map((s) => ({ ...s, note: notes.get(s.key) ?? null }));
82
+ if (kind !== 'unit') return blocks;
83
+ const header = HEADER_KEYS.map((key) => ({
84
+ key,
85
+ form: 'scalar',
86
+ required: REQUIRED_HEADER.includes(key),
87
+ header: true,
88
+ recordKeys: [],
89
+ optionalRecordKeys: [],
90
+ note: HEADER_NOTES[key],
91
+ }));
92
+
93
+ return [...header, ...blocks];
94
+ }
95
+
96
+ /**
97
+ * The top-level blocks of a text: key, value on its line, and its lines (1-based, `end`
98
+ * inclusive) up to the next block or `##` heading, trailing blank lines left out.
99
+ */
100
+ function blocksOf(text) {
101
+ const { lines, sections } = parseBlocks(text);
102
+
103
+ return sections.map((s, i) => {
104
+ let end = (sections[i + 1]?.line ?? lines.length + 1) - 1;
105
+ const heading = lines.slice(s.line, end).findIndex((l) => /^##\s/.test(l));
106
+ if (heading >= 0) end = s.line + heading;
107
+ while (end > s.line && !lines[end - 1].trim()) end--;
108
+
109
+ return { key: s.key, value: s.value, start: s.line, end };
110
+ });
111
+ }
112
+
113
+ const oneLine = (v) =>
114
+ String(v ?? '')
115
+ .replace(/\s+/g, ' ')
116
+ .trim();
117
+
118
+ /** The lines a field's value writes: `key: TBD` for a required one left empty, none to drop. */
119
+ export function renderField(spec, value) {
120
+ if (value === 'TBD') return [`${spec.key}: TBD`];
121
+ const lines = linesOf(spec, value);
122
+ if (lines.length) return lines;
123
+
124
+ return spec.required ? [`${spec.key}: TBD`] : [];
125
+ }
126
+
127
+ function linesOf(spec, value) {
128
+ if (value === null || value === undefined) return [];
129
+ if (spec.form === 'scalar') {
130
+ if (typeof value !== 'string') throw new Error(`${spec.key}: its value is one line of text`);
131
+
132
+ return oneLine(value) ? [`${spec.key}: ${oneLine(value)}`] : [];
133
+ }
134
+
135
+ if (!Array.isArray(value)) throw new Error(`${spec.key}: its value is a list`);
136
+ if (spec.form !== 'record-list') {
137
+ if (value.some((v) => typeof v !== 'string'))
138
+ throw new Error(`${spec.key}: its value is a list of lines`);
139
+ const items = value.map(oneLine).filter(Boolean);
140
+
141
+ return items.length ? [`${spec.key}:`, ...items.map((v) => `- ${v}`)] : [];
142
+ }
143
+
144
+ const declared = [...spec.recordKeys, ...spec.optionalRecordKeys];
145
+ const records = value.flatMap((r) => {
146
+ if (!r || typeof r !== 'object' || Array.isArray(r))
147
+ throw new Error(`${spec.key}: a record is an object of its keys`);
148
+ // The record's own key order stays: a form writes back what it read in the same order. Its
149
+ // first key opens it (CNL-P), wherever a form put it.
150
+ const keys = [...new Set([...spec.recordKeys.slice(0, 1), ...Object.keys(r), ...declared])];
151
+ if (keys.every((k) => !oneLine(r[k]))) return [];
152
+
153
+ return [
154
+ keys.flatMap((k) => {
155
+ const v = oneLine(r[k]);
156
+ if (v) return [[k, v]];
157
+
158
+ return spec.recordKeys.includes(k) ? [[k, 'TBD']] : [];
159
+ }),
160
+ ];
161
+ });
162
+ if (!records.length) return [];
163
+ const out = records.map((r) => r.map(([k, v], i) => `${i ? ' ' : '- '}${k}: ${v}`));
164
+ // CNL-P §3: records of two lines or more stand apart; one-line records stay tight.
165
+ const spaced = out.length > 1 && out.every((r) => r.length > 1);
166
+
167
+ return [`${spec.key}:`, ...out.flatMap((r, i) => (spaced && i ? ['', ...r] : r))];
168
+ }
169
+
170
+ /** A block's value as a form holds it: a string, a list of lines, a list of records, or TBD. */
171
+ function valueOf(spec, block, lines) {
172
+ if (!block) return null;
173
+ if (block.value === 'TBD') return 'TBD';
174
+ if (spec.form === 'scalar') return block.value;
175
+ const items = itemsOf(lines, block.start);
176
+ if (spec.form === 'record-list') return readRecords(items).records.map((r) => r.values);
177
+
178
+ return items.map((i) => i.text.replace(/^- /, ''));
179
+ }
180
+
181
+ /**
182
+ * Whether the form holds a block whole: writing back what it read gives the same lines. A block
183
+ * with a comment, prose or a line the form has no field for does not, and its field is
184
+ * read-only: a save would drop that text silently.
185
+ */
186
+ function exact(spec, block, raw, value) {
187
+ if (!block) return true;
188
+ const shown = raw.slice(block.start - 1, block.end).filter((l) => l.trim());
189
+ let back;
190
+ try {
191
+ back = renderField(spec, value).filter((l) => l.trim());
192
+ } catch {
193
+ return false;
194
+ }
195
+
196
+ return shown.length === back.length && shown.every((l, i) => l.trimEnd() === back[i]);
197
+ }
198
+
199
+ /** Where a part lives and its text now: null text for a part not written yet. */
200
+ async function locate(root, kind, name, type) {
201
+ if (kind === 'doc') {
202
+ if (!Object.hasOwn(DOC_FILES, name))
203
+ throw new Error(`${name} is not a design doc: ${Object.keys(DOC_FILES).join(', ')}`);
204
+ const text = await readIf(path.join(root, DOC_FILES[name]));
205
+
206
+ return { file: `gcf/${DOC_FILES[name]}`, text: text === null ? null : text.trim() };
207
+ }
208
+
209
+ const design = await readDesign(root);
210
+ if (kind === 'system') {
211
+ const d = design.find((x) => x.system === name);
212
+ if (!d) throw new Error(`${name} is not a subsystem of gcf/design/`);
213
+
214
+ return { file: `gcf/${d.file}`, system: name, text: purposeOf(d.preamble) };
215
+ }
216
+
217
+ if (kind !== 'unit') throw new Error(`${kind}: a part is a doc, a system or a unit`);
218
+ const u = design.flatMap((d) => d.units).find((x) => x.id === name);
219
+ if (u) return { file: `gcf/${u.file}`, system: u.system, type: u.header.type, text: unitText(u) };
220
+ if (!UNIT_TYPES.includes(type))
221
+ throw new Error(`${name} is not a unit of gcf/design/ (a new one needs its type)`);
222
+
223
+ return { file: null, system: null, type, text: null };
224
+ }
225
+
226
+ /**
227
+ * `gcf design part <kind> <name>`: one part as a form shows it. `base` is the hash a save sends
228
+ * back, so an edit made meanwhile is reported, not overwritten. `type` gives the fields of a
229
+ * unit not written yet.
230
+ */
231
+ export async function designPart(projectDir, kind, name, { type = null } = {}) {
232
+ const root = path.join(path.resolve(projectDir), 'gcf');
233
+ const at = await locate(root, kind, name, type);
234
+ const text = lf(at.text);
235
+ const raw = text.split('\n');
236
+ const { lines } = parseBlocks(text);
237
+ const blocks = blocksOf(text);
238
+ const specs = await specsOf(kind, name, at.type);
239
+
240
+ return {
241
+ kind,
242
+ name,
243
+ system: at.system ?? null,
244
+ type: at.type ?? null,
245
+ file: at.file,
246
+ exists: at.text !== null,
247
+ base: at.text === null ? null : hashOf(at.text),
248
+ text,
249
+ fields: specs.map((spec) => {
250
+ const own = blocks.filter((b) => b.key === spec.key);
251
+ const value = valueOf(spec, own[0], lines);
252
+
253
+ return {
254
+ key: spec.key,
255
+ form: spec.form,
256
+ required: spec.required,
257
+ ...(spec.header && { header: true }),
258
+ record_keys: spec.recordKeys,
259
+ optional_record_keys: spec.optionalRecordKeys,
260
+ note: spec.note,
261
+ value,
262
+ exact: own.length <= 1 && exact(spec, own[0], raw, value),
263
+ };
264
+ }),
265
+ };
266
+ }
267
+
268
+ /** `lines` with block `spec` set to `rendered`: in place, or where the field order puts it. */
269
+ function putBlock(lines, specs, spec, rendered) {
270
+ const blocks = blocksOf(lines.join('\n'));
271
+ const at = blocks.find((b) => b.key === spec.key);
272
+ if (at) {
273
+ // A dropped block takes one of the blank lines around it along.
274
+ const drop = !rendered.length && !lines[at.start - 2]?.trim() && !lines[at.end]?.trim();
275
+
276
+ return [...lines.slice(0, at.start - 1), ...rendered, ...lines.slice(at.end + (drop ? 1 : 0))];
277
+ }
278
+
279
+ if (!rendered.length) return lines;
280
+ const order = specs.map((s) => s.key);
281
+ const header = (b) => Boolean(specs.find((s) => s.key === b?.key)?.header);
282
+ // Header fields stand line under line; a block stands apart from its neighbours.
283
+ const tight = (b) => Boolean(spec.header && header(b));
284
+ const prev = blocks.filter((b) => order.indexOf(b.key) < order.indexOf(spec.key)).at(-1);
285
+ if (!prev)
286
+ return blocks.length ? [...rendered, ...(tight(blocks[0]) ? [] : ['']), ...lines] : rendered;
287
+ const tail = lines.slice(prev.end);
288
+ const gap = tight(prev) ? [] : [''];
289
+ const after = !tight(prev) && tail[0]?.trim() ? [''] : [];
290
+
291
+ return [...lines.slice(0, prev.end), ...gap, ...rendered, ...after, ...tail];
292
+ }
293
+
294
+ /** A unit nobody wrote yet: its header, every block it owes as TBD. */
295
+ function skeleton(specs, { id, type, system, title }) {
296
+ const soft = CARD_TYPES.includes(type);
297
+ const header = {
298
+ type,
299
+ ...(oneLine(title) && { title: oneLine(title) }),
300
+ route: `${soft ? 'soft' : 'hard'} (TBD)`,
301
+ system: `[${system}]`,
302
+ milestone: 'TBD',
303
+ pillars: 'TBD',
304
+ depends: 'none',
305
+ source: 'manual',
306
+ };
307
+ const head = HEADER_KEYS.filter((k) => header[k]).map((k) => `${k}: ${header[k]}`);
308
+ const body = specs.filter((s) => !s.header && s.required).map((s) => `${s.key}: TBD`);
309
+ if (!SLUG_RE.test(id)) throw new Error(`${id}: a unit id is a lowercase hyphen slug`);
310
+
311
+ return [...head, '', ...body.flatMap((l, i) => (i ? ['', l] : [l]))].join('\n');
312
+ }
313
+
314
+ /**
315
+ * The slots an edit wrote that a GDD-sourced unit backs by nothing yet: the human's own words,
316
+ * recorded as `answer: manual` (the record gcf-debate writes), so the design check's M9 does
317
+ * not refuse a hand-filled TBD.
318
+ */
319
+ async function withManualAnswers(text, edited, type) {
320
+ const u = parseDesign(`## x\n${text}`, '').units[0];
321
+ if (!String(u?.header.source ?? '').startsWith('GDD#')) return text;
322
+ const profile = await loadDocProfile(`unit-${type}`);
323
+ const owed = uncovered(slotValues(u.body, profile), provenanceOf(u.body))
324
+ .map(([slot]) => slot)
325
+ .filter((slot) => edited.includes(slot.split('.')[0]));
326
+ if (!owed.length) return text;
327
+ const lines = text.split('\n');
328
+ const at = blocksOf(text).find((b) => b.key === 'provenance');
329
+ // CNL-P §3: records of two lines stand apart, each new one after a blank line.
330
+ const records = owed.flatMap((slot, i) => [
331
+ ...(at || i ? [''] : []),
332
+ `- slot: ${slot}`,
333
+ ' answer: manual',
334
+ ]);
335
+ if (!at) return [...lines, '', 'provenance:', ...records].join('\n');
336
+
337
+ return [...lines.slice(0, at.end), ...records, ...lines.slice(at.end)].join('\n');
338
+ }
339
+
340
+ /** The keys whose blocks differ between two texts of a part. */
341
+ function changedKeys(before, after) {
342
+ const read = (t) => {
343
+ const raw = lf(t).split('\n');
344
+
345
+ return new Map(blocksOf(lf(t)).map((b) => [b.key, raw.slice(b.start - 1, b.end).join('\n')]));
346
+ };
347
+ const a = read(before);
348
+ const b = read(after);
349
+
350
+ return [...new Set([...a.keys(), ...b.keys()])].filter((k) => a.get(k) !== b.get(k));
351
+ }
352
+
353
+ /**
354
+ * `gcf design save`: one part from a form (`fields`: key → value, only the fields edited) or as
355
+ * text (`text`). An existing part needs the `base` its read gave. The edit comes in as a one-part
356
+ * bundle: a part changed meanwhile, a pillar id lost, or a new blocking finding of the design
357
+ * check refuses it whole, with the reason. Commits `gcf(design): <kind> <name>`.
358
+ * @type {typeof saveUnlocked}
359
+ */
360
+ export const saveDesignPart = (projectDir, kind, name, opts = {}) =>
361
+ locked(projectDir, opts.commit ?? true, () => saveUnlocked(projectDir, kind, name, opts));
362
+
363
+ /**
364
+ * The pillars a form saves, each with its id (Board-PRD decision 34): a new one's from its name,
365
+ * which it needs, an id never taken twice. A pillar whose name changed keeps its
366
+ * id in this save and is renamed after it: `renames`, [from, to]. A name given for the first
367
+ * time renames nothing, nor does a reworded statement.
368
+ */
369
+ function pillarIds(part, given) {
370
+ const now = part.fields.find((f) => f.key === 'pillars')?.value ?? [];
371
+ const before = Array.isArray(now) ? now : [];
372
+ const taken = new Set([...before, ...given].map((p) => p?.id).filter(Boolean));
373
+ const renames = [];
374
+ const records = given.map((p) => {
375
+ if (!p || typeof p !== 'object') return p;
376
+ if (!p.id) {
377
+ if (!oneLine(p.name)) throw new Error('a new pillar needs a name: its id comes from it');
378
+ const id = deriveId(oneLine(p.name), (x) => taken.has(x), 'pillar');
379
+ taken.add(id);
380
+
381
+ return { ...p, id };
382
+ }
383
+ const was = before.find((b) => b.id === p.id);
384
+ if (oneLine(was?.name) && oneLine(p.name) && oneLine(was.name) !== oneLine(p.name)) {
385
+ const to = deriveId(oneLine(p.name), (x) => x !== p.id && taken.has(x), 'pillar');
386
+ if (to !== p.id) {
387
+ taken.add(to);
388
+ renames.push([p.id, to]);
389
+ }
390
+ }
391
+
392
+ return p;
393
+ });
394
+
395
+ return { records, renames };
396
+ }
397
+
398
+ /**
399
+ * Refuse a save whose new pillar names rename ids while a file the rename writes holds changes
400
+ * not recorded: the save would commit the name, and the rename then refuse, name and id apart.
401
+ */
402
+ async function refuseLooseForRename(projectDir, renames) {
403
+ const from = new Set(renames.map(([f]) => f));
404
+ const ledger = await buildLedger(projectDir);
405
+ const items = ledger.items
406
+ .filter((c) => (c.data.pillars ?? []).some((p) => from.has(p)))
407
+ .map((c) => path.relative(path.resolve(projectDir), c.file).replaceAll('\\', '/'));
408
+ const loose = [
409
+ ...unrecordedDesign(projectDir).filter((f) => f.startsWith('gcf/design/')),
410
+ ...dirtyPaths(projectDir, items).map((l) => l.slice(3)),
411
+ ];
412
+ if (loose.length)
413
+ throw new Error(
414
+ `a new pillar name renames its id where it is cited: record or discard ${loose.join(', ')} first`,
415
+ );
416
+ }
417
+
418
+ /**
419
+ * A new unit's id, the system's (Board-PRD decision 34): from its title, under the lock the
420
+ * save holds, never one the ledger knows.
421
+ */
422
+ async function newUnitId(projectDir, kind, title, type) {
423
+ if (kind !== 'unit') throw new Error(`a ${kind} is saved by its name`);
424
+ if (!oneLine(title)) throw new Error('a new unit needs --title: its id comes from it');
425
+ if (!UNIT_TYPES.includes(type))
426
+ throw new Error(`a new unit needs --type: ${UNIT_TYPES.join(' | ')}`);
427
+
428
+ return deriveId(oneLine(title), (await buildLedger(projectDir)).known, type);
429
+ }
430
+
431
+ async function saveUnlocked(
432
+ projectDir,
433
+ kind,
434
+ given,
435
+ {
436
+ fields = null,
437
+ text = null,
438
+ base = null,
439
+ system = null,
440
+ type = null,
441
+ title = null,
442
+ commit = true,
443
+ },
444
+ ) {
445
+ if ((fields === null) === (text === null))
446
+ throw new Error('give the part once: its fields or its text');
447
+ const name = given || (await newUnitId(projectDir, kind, title, type));
448
+ let part = await designPart(projectDir, kind, name, { type });
449
+ if (part.exists && !base)
450
+ throw new Error(
451
+ `${kind} ${name} exists: pass --base from gcf design part, so an edit made since is not overwritten`,
452
+ );
453
+ const owner = part.system ?? system;
454
+ if (kind === 'unit' && !part.exists && !SLUG_RE.test(String(owner ?? '')))
455
+ throw new Error('a new unit needs --system: the subsystem file it goes into');
456
+ const specs = await specsOf(kind, name, part.type);
457
+ const pillars = kind === 'doc' && name === 'pillars' && Array.isArray(fields?.pillars);
458
+ const { records, renames } = pillars ? pillarIds(part, fields.pillars) : {};
459
+ let edits = pillars ? { ...fields, pillars: records } : fields;
460
+ let hash = null;
461
+ if (renames?.length) {
462
+ // The rename goes first, on the part the operator read: changed since, nothing moves.
463
+ if (part.base !== base)
464
+ throw new Error(`conflict doc:pillars: ${noteOf({ outcome: 'conflict' })}`);
465
+ if (commit) await refuseLooseForRename(projectDir, renames);
466
+ for (const [from, to] of renames)
467
+ hash = (await renamePillar(projectDir, from, to, { commit })).hash;
468
+ const moved = new Map(renames);
469
+ edits = {
470
+ ...edits,
471
+ pillars: records.map((p) => (moved.has(p?.id) ? { ...p, id: moved.get(p.id) } : p)),
472
+ };
473
+ part = await designPart(projectDir, kind, name, { type });
474
+ base = part.base;
475
+ }
476
+ let next = text === null ? null : lf(text).trim();
477
+ if (next === null) {
478
+ const start = part.exists
479
+ ? part.text
480
+ : kind === 'unit'
481
+ ? skeleton(specs, { id: name, type: part.type, system: owner, title })
482
+ : '';
483
+ let lines = start ? start.split('\n') : [];
484
+ for (const [key, value] of Object.entries(edits)) {
485
+ const spec = specs.find((s) => s.key === key);
486
+ if (!spec) throw new Error(`${key} is not a field of ${kind} ${name}`);
487
+ const field = part.fields.find((f) => f.key === key);
488
+ if (part.exists && field && !field.exact)
489
+ throw new Error(`${key} holds text a form cannot keep: edit the part as text`);
490
+ lines = putBlock(lines, specs, spec, renderField(spec, value));
491
+ }
492
+
493
+ next = lines.join('\n').trim();
494
+ }
495
+
496
+ if (kind === 'unit')
497
+ next = await withManualAnswers(next, changedKeys(part.text, next), part.type);
498
+ if (part.exists && hashOf(next) === part.base) return { applied: [], hash: null };
499
+ // The base goes into the marker line: anything but a hash would break the bundle's shape.
500
+ if (part.exists && !/^[0-9a-f]{8}$/.test(base))
501
+ throw new Error(`--base is the 8-hex hash gcf design part gave: ${base}`);
502
+ const marker = [
503
+ `<!-- gcf:part ${kind} ${name}`,
504
+ ...(kind === 'unit' ? [`system=${owner}`] : []),
505
+ ...(part.exists ? [`base=${base}`] : []),
506
+ ].join(' ');
507
+ const r = await bundleMove(
508
+ projectDir,
509
+ `gcf(design): ${kind} ${name}`,
510
+ `${marker} -->\n${next}\n`,
511
+ {
512
+ key: 'design-save',
513
+ items: kind === 'unit' ? [name] : [],
514
+ strict: true,
515
+ draft: true,
516
+ commit,
517
+ },
518
+ );
519
+
520
+ return { id: name, applied: r.applied, hash: r.hash ?? hash, renamed: renames ?? [] };
521
+ }
522
+
523
+ /**
524
+ * `gcf design import --commit`: a designer's bundle, what applies of it committed in one move
525
+ * `gcf(design): import a bundle`; what it reports (a conflict, a gone unit) stays unwritten.
526
+ * @param {string} projectDir
527
+ * @param {string} text
528
+ */
529
+ export const importDesign = (projectDir, text) =>
530
+ locked(projectDir, true, () =>
531
+ bundleMove(projectDir, 'gcf(design): import a bundle', text, { key: 'design-import' }),
532
+ );
533
+
534
+ /** A refused part as a form's save hears it: a conflict is a part read before a change. */
535
+ const noteOf = (p) =>
536
+ p.outcome === 'conflict'
537
+ ? 'it changed since you read it: read it again, and make the edit on what it holds now'
538
+ : p.note;
539
+
540
+ // Nothing of the bundle applied: no commit to make.
541
+ class NothingApplied extends Error {}
542
+
543
+ /**
544
+ * Bring `text` in through the import and commit what it wrote. `strict`: a part the import
545
+ * reports refuses the whole move. Files with changes not recorded yet refuse it up front: the
546
+ * commit would carry them under the edit's name.
547
+ */
548
+ async function bundleMove(
549
+ projectDir,
550
+ message,
551
+ text,
552
+ { key, items = [], strict = false, draft = false, commit = true },
553
+ ) {
554
+ const root = path.join(path.resolve(projectDir), 'gcf');
555
+ // Only the names a write may take (bundle.js validName): no other path gets staged.
556
+ const files = parseBundle(text).parts.flatMap((p) => {
557
+ if (p.kind === 'doc')
558
+ return Object.hasOwn(DOC_FILES, p.name) ? [path.join(root, DOC_FILES[p.name])] : [];
559
+ const sys = p.kind === 'system' ? p.name : p.system;
560
+
561
+ return SLUG_RE.test(p.name) && SLUG_RE.test(String(sys ?? ''))
562
+ ? [path.join(root, 'design', `${sys}.md`)]
563
+ : [];
564
+ });
565
+ const touched = [...new Set([...files, path.join(root, 'backlog.md')])];
566
+ const rel = (f) => path.relative(path.resolve(projectDir), f).replaceAll('\\', '/');
567
+ // A form's save over an agent's draft of its own file takes the draft along (decision 35): the
568
+ // operator saw it in the form. Another file's changes would ride along unseen.
569
+ const own = draft ? files.map(rel) : [];
570
+ const unrecorded = unrecordedDesign(projectDir).filter((f) => touched.map(rel).includes(f));
571
+ const loose = unrecorded.filter((f) => !own.includes(f));
572
+ const drafts = unrecorded.filter((f) => own.includes(f));
573
+ if (commit && loose.length)
574
+ throw new Error(
575
+ `${loose.join(', ')} holds changes not recorded yet: record the design first (gcf design commit)`,
576
+ );
577
+ let result = { applied: [], report: [] };
578
+ try {
579
+ const hash = await commitMove(projectDir, message, {
580
+ files: touched,
581
+ inputs: drafts.map((f) => path.join(path.resolve(projectDir), f)),
582
+ commit,
583
+ key,
584
+ items,
585
+ mutate: async () => {
586
+ result = await importBundle(projectDir, text);
587
+ const refused = result.report.filter((p) => p.outcome !== 'deleted');
588
+ if (strict && refused.length)
589
+ throw new Error(refused.map((p) => `${p.outcome} ${p.part}: ${noteOf(p)}`).join('\n'));
590
+ if (!result.applied.length) throw new NothingApplied();
591
+ },
592
+ });
593
+
594
+ return { ...result, hash };
595
+ } catch (e) {
596
+ if (e instanceof NothingApplied) return { ...result, hash: null };
597
+ throw e;
598
+ }
599
+ }
600
+
601
+ // What the design is made of: what `design commit` records and the board counts as unrecorded.
602
+ const DESIGN_PATHS = [
603
+ 'PILLARS.md',
604
+ 'game.md',
605
+ 'glossary.md',
606
+ 'backlog.md',
607
+ 'open-questions.md',
608
+ 'design',
609
+ 'source',
610
+ ].map((p) => `gcf/${p}`);
611
+
612
+ /**
613
+ * The design files with changes git has not recorded, project-relative. An import's held map
614
+ * (`*.import.json`) is its working file, not design: it goes when the import finishes.
615
+ */
616
+ export function unrecordedDesign(projectDir, { renamed = false } = {}) {
617
+ const res = spawnSync(
618
+ 'git',
619
+ ['status', '--porcelain', '-z', '--untracked-files=all', '--', ...DESIGN_PATHS],
620
+ { cwd: projectDir, encoding: 'utf8' },
621
+ );
622
+ if (res.status !== 0) return [];
623
+ // git prints paths from the repository's root: a project in a subfolder strips its prefix.
624
+ const prefix = spawnSync('git', ['rev-parse', '--show-prefix'], {
625
+ cwd: projectDir,
626
+ encoding: 'utf8',
627
+ }).stdout.trim();
628
+ const out = [];
629
+ const fields = res.stdout.split('\0').filter(Boolean);
630
+ for (let i = 0; i < fields.length; i++) {
631
+ const status = fields[i].slice(0, 2);
632
+ const file = fields[i].slice(3);
633
+ out.push(file.startsWith(prefix) ? file.slice(prefix.length) : file);
634
+ // A rename or a copy names its old path in the next field: a discard takes it back too.
635
+ if (/[RC]/.test(status)) {
636
+ i++;
637
+ const old = fields[i] ?? '';
638
+ if (renamed && status.includes('R'))
639
+ out.push(old.startsWith(prefix) ? old.slice(prefix.length) : old);
640
+ }
641
+ }
642
+
643
+ return out.filter((f) => !f.endsWith('.import.json'));
644
+ }
645
+
646
+ /**
647
+ * `gcf design commit`: record what a design session wrote (a vision interview, an import, the
648
+ * pillars interview), in one commit `gcf(design): <message>`. Refused while the design check
649
+ * has a blocking finding: the commit hook would refuse it the same way.
650
+ * @type {typeof commitUnlocked}
651
+ */
652
+ export const commitDesign = (projectDir, opts = {}) =>
653
+ locked(projectDir, opts.commit ?? true, () => commitUnlocked(projectDir, opts));
654
+
655
+ async function commitUnlocked(projectDir, { message = null, commit = true } = {}) {
656
+ const files = unrecordedDesign(projectDir);
657
+ if (!files.length) return { files, hash: null };
658
+ const blocking = (await designCheck(projectDir)).issues.filter((i) => i.severity === 'block');
659
+ if (blocking.length) {
660
+ const first = blocking.slice(0, 3).map((i) => `${i.file}:${i.line} ${i.check} ${i.message}`);
661
+ throw new Error(
662
+ `the design check has ${blocking.length} blocking finding(s), fix them first:\n${first.join('\n')}`,
663
+ );
664
+ }
665
+
666
+ const abs = files.map((f) => path.join(path.resolve(projectDir), f));
667
+ const why = oneLine(message) || 'record the design';
668
+ const hash = await commitMove(projectDir, `gcf(design): ${why}`, {
669
+ files: abs,
670
+ inputs: abs,
671
+ mutate: async () => {},
672
+ commit,
673
+ key: 'design-commit',
674
+ });
675
+
676
+ return { files, hash };
677
+ }
678
+
679
+ // What an agent's draft writes (decision 35), and so what `design discard` may take back: not an
680
+ // uploaded GDD, the backlog or the questions, which an import writes.
681
+ const DRAFT_PATHS = ['gcf/PILLARS.md', 'gcf/game.md', 'gcf/glossary.md'];
682
+ const isDraftPath = (f) => DRAFT_PATHS.includes(f) || f.startsWith('gcf/design/');
683
+
684
+ /**
685
+ * `gcf design discard [file…]`: an agent's draft not recorded taken back, its files as the last
686
+ * commit has them (a new one deleted). Only the draft's files: the vision, the glossary, the
687
+ * pillars, design/. None named: every one with changes. Nothing to commit.
688
+ * @param {string} projectDir
689
+ * @param {string[]} [only]
690
+ */
691
+ export const discardDesign = (projectDir, only = []) =>
692
+ locked(projectDir, true, async () => {
693
+ const drafts = unrecordedDesign(projectDir, { renamed: true }).filter(isDraftPath);
694
+ const off = only.filter((f) => !drafts.includes(f));
695
+ if (off.length)
696
+ throw new Error(`${off.join(', ')}: no draft to discard (${drafts.join(', ') || 'none'})`);
697
+ const files = only.length ? only : drafts;
698
+ const git = (...args) => spawnSync('git', args, { cwd: projectDir, encoding: 'utf8' });
699
+ const must = (...args) => {
700
+ const r = git(...args);
701
+ if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr.trim()}`);
702
+ };
703
+ for (const f of files) {
704
+ if (git('cat-file', '-e', `HEAD:./${f}`).status === 0) {
705
+ must('checkout', 'HEAD', '--', f);
706
+ continue;
707
+ }
708
+ must('rm', '--cached', '-q', '--ignore-unmatch', '--', f);
709
+ await rm(path.join(projectDir, f), { force: true });
710
+ }
711
+
712
+ return { files };
713
+ });
714
+
715
+ /** The GDD files in gcf/source/, each with whether its import is still unfinished. */
716
+ async function sourcesOf(root) {
717
+ const dir = path.join(root, 'source');
718
+ if (!existsSync(dir)) return [];
719
+ const names = (await readdir(dir)).filter((n) => n.endsWith('.md')).sort();
720
+
721
+ return names.map((n) => ({
722
+ file: `gcf/source/${n}`,
723
+ importing: existsSync(path.join(dir, `${n}.import.json`)),
724
+ }));
725
+ }
726
+
727
+ /**
728
+ * A question about the design rather than about a run: an import's (its lens, its GDD
729
+ * sections) or one that holds a unit of design/.
730
+ */
731
+ const isDesignQuestion = (q, units) =>
732
+ Boolean(q.lens) ||
733
+ /GDD#/.test(q.sections ?? '') ||
734
+ [listOf(q.blocks)].flat().some((id) => units.has(id));
735
+
736
+ /**
737
+ * The design block of the board read: where the game's design stands, from the design check's
738
+ * report. `steps` are the way from an empty project to the first work, each done or not; the
739
+ * domain names and explains them.
740
+ */
741
+ export async function designState(projectDir, { report, questions, items }) {
742
+ const root = path.join(path.resolve(projectDir), 'gcf');
743
+ const pillarsText = await readIf(path.join(root, 'PILLARS.md'));
744
+ const glossaryText = await readIf(path.join(root, 'glossary.md'));
745
+ const game = existsSync(path.join(root, 'game.md'));
746
+ const units = new Set(report.units.map((u) => u.id));
747
+ const sources = await sourcesOf(root);
748
+ const asked = questions.filter((q) => isDesignQuestion(q, units));
749
+ const open = asked.filter((q) => /^D1\b/.test(q.class ?? '') && !q.answer);
750
+ const pillars = recordsIn(pillarsText, 'pillars').map((p) => ({
751
+ id: p.id ?? null,
752
+ // The few words the operator knows it by (decision 34); an old file has none.
753
+ name: p.name ?? null,
754
+ statement: p.statement ?? null,
755
+ units: p.id ? (report.pillars.refs[p.id] ?? 0) : 0,
756
+ }));
757
+
758
+ return {
759
+ pillars,
760
+ game,
761
+ // The new item form's milestone choices; null without game.md (a free field then).
762
+ milestones: await gameMilestones(root),
763
+ glossary: glossaryText === null ? null : recordsIn(glossaryText, 'terms').length,
764
+ systems: report.systems,
765
+ sources,
766
+ questions: asked.map((q) => q.id),
767
+ blocking: report.blocking,
768
+ // What blocks a commit, as the check says it: the operator fixes it without a terminal.
769
+ findings: (report.issues ?? [])
770
+ .filter((i) => i.severity === 'block')
771
+ .map(({ check, file, line, id, message }) => ({
772
+ check,
773
+ // The check names files inside gcf/; the read names them from the project, as units do.
774
+ file: `gcf/${file}`,
775
+ line: line ?? null,
776
+ id: id ?? null,
777
+ message,
778
+ })),
779
+ unrecorded: unrecordedDesign(projectDir),
780
+ steps: [
781
+ { id: 'design', done: (units.size > 0 || game) && !sources.some((s) => s.importing) },
782
+ { id: 'pillars', done: pillars.length > 0 },
783
+ { id: 'questions', done: open.length === 0 },
784
+ { id: 'work', done: items > 0 || report.units.some((u) => u.ready) },
785
+ ],
786
+ };
787
+ }