@codewizard-dt/bootstrap 2.17.0 → 2.18.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 (39) hide show
  1. package/lib/hooks/README.md +94 -3
  2. package/lib/hooks/absolute-path-guard.js +5 -0
  3. package/lib/hooks/claude-settings-guard.js +5 -0
  4. package/lib/hooks/env-content-read-guard.js +13 -3
  5. package/lib/hooks/env-file-guard.js +42 -0
  6. package/lib/hooks/interpreter-indirection-guard.js +7 -0
  7. package/lib/hooks/lib/command-parse.js +8 -0
  8. package/lib/hooks/lib/serena-languages.js +94 -1
  9. package/lib/hooks/lib/serena.js +228 -0
  10. package/lib/hooks/mv-absolute-path-block.js +84 -3
  11. package/lib/hooks/package-install-consent.js +11 -0
  12. package/lib/hooks/protected-write-guard.js +7 -0
  13. package/lib/hooks/serena-bash-grep-block.js +507 -44
  14. package/lib/hooks/serena-first-glob-guard.js +65 -20
  15. package/lib/hooks/serena-first-guard.js +98 -2
  16. package/lib/hooks/serena-first-read-guard.js +92 -2
  17. package/lib/hooks/serena-pre-delegation.js +123 -0
  18. package/lib/hooks/serena-write-guard.js +56 -3
  19. package/lib/scripts/README.md +296 -1
  20. package/lib/scripts/bootstrap-prefs.js +734 -0
  21. package/lib/scripts/install-global.sh +147 -18
  22. package/lib/scripts/install-mcps.sh +102 -14
  23. package/lib/scripts/lib.sh +581 -11
  24. package/lib/scripts/merge-gitignore.sh +201 -15
  25. package/lib/scripts/sync-wiki-scaffold.sh +33 -4
  26. package/lib/scripts/templates/CLAUDE-wiki.md +1 -1
  27. package/lib/scripts/templates/bootstrap-prefs-schema.json +175 -0
  28. package/lib/scripts/update-project.sh +42 -9
  29. package/lib/skills/README.md +2 -1
  30. package/lib/skills/bootstrap-config/SKILL.md +154 -0
  31. package/lib/skills/git-commit/SKILL.md +54 -1
  32. package/lib/skills/research/SKILL.md +34 -3
  33. package/lib/skills/simplify/SKILL.md +1 -1
  34. package/lib/skills/uat-auto/SKILL.md +9 -4
  35. package/lib/skills/uat-auto-plus/SKILL.md +6 -6
  36. package/lib/skills/uat-generate/SKILL.md +30 -3
  37. package/lib/skills/uat-walk/UAT-CORE.md +41 -6
  38. package/lib/skills/wiki-query/SKILL.md +48 -8
  39. package/package.json +1 -1
@@ -0,0 +1,734 @@
1
+ #!/usr/bin/env node
2
+ // Read and write the bootstrap preference store — the single binary every
3
+ // ROADMAP-005 consumer goes through (sticky shell prompts, skill consumers,
4
+ // /bootstrap-config).
5
+ //
6
+ // Two values files, both plain flat JSON objects:
7
+ // global ~/.claude/bootstrap-prefs.json
8
+ // project <project>/.claude/bootstrap-prefs.json
9
+ //
10
+ // Four states per key: `unset` / a settled value / `false` / `ask`.
11
+ // ABSENCE IS `unset`. `null` is never written and "unset" is never stored as a
12
+ // string — deleting a key is how you re-open a question.
13
+ //
14
+ // Exit codes encode WHOSE fault it is, because these calls run inside
15
+ // `set -euo pipefail` installers and inside a /git-commit run:
16
+ // exit 0 the world is in an unexpected state — missing file, malformed JSON,
17
+ // unknown key on read, key not set. A corrupt prefs file must never
18
+ // abort an install or block a commit. Every read path exits 0, so no
19
+ // call site needs `|| true`.
20
+ // exit 1 the caller is wrong — invalid --value for the key's grammar,
21
+ // unknown flag, --set without --value, a write with no layer
22
+ // selector. These are bugs in a calling script and must fail loudly:
23
+ // a typo'd value must never land in the file and read back as `unset`.
24
+ //
25
+ // Usage:
26
+ // bootstrap-prefs.js --get <key> [--project <dir>] [--global] [--target <path>]
27
+ // bootstrap-prefs.js --set <key> --value <v> (--global | --project <dir> | --target <path>)
28
+ // bootstrap-prefs.js --unset <key> (--global | --project <dir> | --target <path>)
29
+ // bootstrap-prefs.js --list [--project <dir>] [--target <path>]
30
+ // bootstrap-prefs.js --section-key <title>
31
+ // ... plus [--schema <path>] on any of the above.
32
+ //
33
+ // --global / --project <dir> are semantic LAYER SELECTORS.
34
+ // --target <path> is an explicit single file, bypassing layer resolution. It
35
+ // is the test seam (the repo's established name for one) and doubles as the
36
+ // escape hatch for touching exactly one layer.
37
+ //
38
+ // On --get, resolution is the DEFAULT, not a flag: forgetting a flag and
39
+ // silently getting `unset` would cause the re-prompt this store exists to
40
+ // remove.
41
+ // On --set/--unset a layer selector is MANDATORY: guessing which file to
42
+ // write is unrecoverable in a way that guessing which to read is not.
43
+ //
44
+ // --section-key turns a .gitignore banner title into its schema key
45
+ // (`gitignore.section.<slug>`). It lives here so the slug rule has exactly
46
+ // one implementation, and so it is Unicode-aware — the template's
47
+ // "Claude Code — machine-local MCP registration ..." title contains an em
48
+ // dash, which a byte-wise [^a-z0-9] slugifier expands into three dashes.
49
+ //
50
+ // Validation comes from the schema's `values` string — no second copy of any
51
+ // value list lives in this file; that is the whole reason the schema exists.
52
+
53
+ 'use strict';
54
+
55
+ const fs = require('fs');
56
+ const os = require('os');
57
+ const path = require('path');
58
+
59
+ const USAGE = [
60
+ 'Usage:',
61
+ ' bootstrap-prefs.js --get <key> [--project <dir>] [--global] [--target <path>]',
62
+ ' bootstrap-prefs.js --set <key> --value <v> (--global | --project <dir> | --target <path>)',
63
+ ' bootstrap-prefs.js --unset <key> (--global | --project <dir> | --target <path>)',
64
+ ' bootstrap-prefs.js --list [--project <dir>] [--target <path>]',
65
+ ' bootstrap-prefs.js --section-key <title>',
66
+ ' (any of the above may add --schema <path>)',
67
+ ].join('\n');
68
+
69
+ const FLAGS_WITH_OPERAND = new Set([
70
+ '--get',
71
+ '--set',
72
+ '--unset',
73
+ '--value',
74
+ '--project',
75
+ '--target',
76
+ '--schema',
77
+ '--section-key',
78
+ ]);
79
+
80
+ function usageError(message) {
81
+ console.error(`Error: ${message}`);
82
+ console.error(USAGE);
83
+ process.exit(1);
84
+ }
85
+
86
+ // Stop cleanly: the world is in a state we do not understand, and the caller is
87
+ // a `set -euo pipefail` script that must keep going. Mirrors merge-settings-deny.js.
88
+ function warnSkip(message) {
89
+ console.error(`Warning: ${message} — skipping ${operation}`);
90
+ process.exit(0);
91
+ }
92
+
93
+ // Degrade and continue: used where the correct answer is "treat it as unset"
94
+ // rather than "stop", so resolution can fall through to the next layer.
95
+ function warn(message) {
96
+ console.error(`Warning: ${message}`);
97
+ }
98
+
99
+ function isPlainObject(value) {
100
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
101
+ }
102
+
103
+ function parseArgs(argv) {
104
+ const opts = {
105
+ op: null,
106
+ key: null,
107
+ value: null,
108
+ title: null,
109
+ global: false,
110
+ projectDir: null,
111
+ target: null,
112
+ schema: path.join(__dirname, 'templates', 'bootstrap-prefs-schema.json'),
113
+ };
114
+
115
+ const setOp = (name) => {
116
+ if (opts.op !== null) {
117
+ usageError(`--${name} cannot be combined with --${opts.op}; pick one operation`);
118
+ }
119
+ opts.op = name;
120
+ };
121
+
122
+ for (let i = 0; i < argv.length; i++) {
123
+ const arg = argv[i];
124
+ if (FLAGS_WITH_OPERAND.has(arg) && argv[i + 1] === undefined) {
125
+ usageError(`${arg} requires an argument`);
126
+ }
127
+ if (arg === '--get') {
128
+ setOp('get');
129
+ opts.key = argv[++i];
130
+ } else if (arg === '--set') {
131
+ setOp('set');
132
+ opts.key = argv[++i];
133
+ } else if (arg === '--unset') {
134
+ setOp('unset');
135
+ opts.key = argv[++i];
136
+ } else if (arg === '--list') {
137
+ setOp('list');
138
+ } else if (arg === '--section-key') {
139
+ setOp('section-key');
140
+ opts.title = argv[++i];
141
+ } else if (arg === '--value') {
142
+ opts.value = argv[++i];
143
+ } else if (arg === '--global') {
144
+ opts.global = true;
145
+ } else if (arg === '--project') {
146
+ opts.projectDir = argv[++i];
147
+ } else if (arg === '--target') {
148
+ opts.target = argv[++i];
149
+ } else if (arg === '--schema') {
150
+ opts.schema = argv[++i];
151
+ } else {
152
+ usageError(`unrecognized argument "${arg}"`);
153
+ }
154
+ }
155
+
156
+ if (opts.op === null) {
157
+ usageError('one of --get, --set, --unset, --list, --section-key is required');
158
+ }
159
+ if (opts.value !== null && opts.op !== 'set') {
160
+ usageError('--value is only valid with --set');
161
+ }
162
+ if (opts.op === 'set' && opts.value === null) {
163
+ usageError(`--set ${opts.key} requires --value <v>`);
164
+ }
165
+ if (opts.op === 'set' || opts.op === 'unset') {
166
+ const selectors = [];
167
+ if (opts.global) selectors.push('--global');
168
+ if (opts.projectDir !== null) selectors.push('--project');
169
+ if (opts.target !== null) selectors.push('--target');
170
+ if (selectors.length === 0) {
171
+ usageError(`--${opts.op} requires exactly one of --global, --project <dir>, --target <path>`);
172
+ }
173
+ if (selectors.length > 1) {
174
+ usageError(`--${opts.op} takes exactly one layer selector, got ${selectors.join(' and ')}`);
175
+ }
176
+ }
177
+ return opts;
178
+ }
179
+
180
+ // os.homedir() follows a redirected HOME (proven by TASK-029 step 5), which is
181
+ // what makes hermetic testing possible. Never read process.env.HOME directly.
182
+ function globalFile() {
183
+ return path.join(os.homedir(), '.claude', 'bootstrap-prefs.json');
184
+ }
185
+
186
+ function projectFile(dir) {
187
+ return path.join(dir, '.claude', 'bootstrap-prefs.json');
188
+ }
189
+
190
+ // ---------------------------------------------------------------- schema ----
191
+
192
+ // A missing or malformed schema is a warning, not a crash, and not a stop: the
193
+ // schema ships in the tarball, but a partial install must not break a
194
+ // /git-commit. Without it there is no validation, no defaults, and no --list
195
+ // descriptions; --get still resolves from the files and --set still writes.
196
+ function loadSchema(file) {
197
+ let text;
198
+ try {
199
+ text = fs.readFileSync(file, 'utf8');
200
+ } catch (err) {
201
+ warn(
202
+ `preference schema not found at ${file} — continuing without validation, ` +
203
+ 'defaults, or descriptions (--get still resolves, --set still writes)'
204
+ );
205
+ return {};
206
+ }
207
+ let parsed;
208
+ try {
209
+ parsed = JSON.parse(text);
210
+ } catch (err) {
211
+ warn(
212
+ `preference schema at ${file} is not valid JSON (${err.message}) — continuing ` +
213
+ 'without validation, defaults, or descriptions (--get still resolves, --set still writes)'
214
+ );
215
+ return {};
216
+ }
217
+ if (!isPlainObject(parsed)) {
218
+ warn(
219
+ `preference schema at ${file} is not a JSON object — continuing without ` +
220
+ 'validation, defaults, or descriptions (--get still resolves, --set still writes)'
221
+ );
222
+ return {};
223
+ }
224
+ return parsed;
225
+ }
226
+
227
+ // Exact key first, then any `dynamic: true` entry whose key ends in `.*`,
228
+ // matched on the literal prefix. `guides.evals-framework.md` matches `guides.*`;
229
+ // `gitignore.section.node-typescript-javascript` matches `gitignore.section.*`.
230
+ function lookupSchema(schema, key) {
231
+ if (Object.prototype.hasOwnProperty.call(schema, key)) return schema[key];
232
+ for (const [pattern, entry] of Object.entries(schema)) {
233
+ if (!isPlainObject(entry) || entry.dynamic !== true) continue;
234
+ if (!pattern.endsWith('.*')) continue;
235
+ const prefix = pattern.slice(0, -1); // keep the trailing '.'
236
+ if (key.length > prefix.length && key.startsWith(prefix)) return entry;
237
+ }
238
+ return null;
239
+ }
240
+
241
+ function allowedValues(entry) {
242
+ if (!entry || typeof entry.values !== 'string') return null;
243
+ return entry.values
244
+ .split('|')
245
+ .map((s) => s.trim())
246
+ .filter((s) => s.length > 0);
247
+ }
248
+
249
+ // ----------------------------------------------------------------- files ----
250
+
251
+ const layerCache = new Map();
252
+
253
+ // Missing file -> {}. Unreadable or unparseable -> {} AFTER a stderr warning
254
+ // naming the file. Never throws: a corrupt layer degrades to `unset` and
255
+ // resolution continues to the next layer.
256
+ function readLayer(file) {
257
+ if (file === null) return {};
258
+ if (layerCache.has(file)) return layerCache.get(file);
259
+ let result = {};
260
+ if (fs.existsSync(file)) {
261
+ let text = null;
262
+ try {
263
+ text = fs.readFileSync(file, 'utf8');
264
+ } catch (err) {
265
+ warn(`could not read ${file} (${err.message}) — treating every key in it as unset`);
266
+ }
267
+ if (text !== null) {
268
+ try {
269
+ const parsed = JSON.parse(text);
270
+ if (isPlainObject(parsed)) {
271
+ result = parsed;
272
+ } else {
273
+ warn(`${file} is not a JSON object — treating every key in it as unset`);
274
+ }
275
+ } catch (err) {
276
+ warn(`could not parse ${file} (${err.message}) — treating every key in it as unset`);
277
+ }
278
+ }
279
+ }
280
+ layerCache.set(file, result);
281
+ return result;
282
+ }
283
+
284
+ // Distinguishes "absent" from "present but unreadable": writes must refuse on
285
+ // the second, so a hand-edited-into-invalidity file is never clobbered.
286
+ function readWritableTarget(file) {
287
+ if (!fs.existsSync(file)) return { text: null, data: {} };
288
+ let text;
289
+ try {
290
+ text = fs.readFileSync(file, 'utf8');
291
+ } catch (err) {
292
+ warnSkip(`could not read ${file} (${err.message}) — fix or delete it, then re-run`);
293
+ }
294
+ let parsed;
295
+ try {
296
+ parsed = JSON.parse(text);
297
+ } catch (err) {
298
+ warnSkip(
299
+ `${file} is not valid JSON (${err.message}) — fix or delete it, then re-run; ` +
300
+ 'refusing to overwrite a file that may hold hand-edited answers'
301
+ );
302
+ }
303
+ if (!isPlainObject(parsed)) {
304
+ warnSkip(
305
+ `${file} is not a JSON object — fix or delete it, then re-run; ` +
306
+ 'refusing to overwrite a file that may hold hand-edited answers'
307
+ );
308
+ }
309
+ return { text, data: parsed };
310
+ }
311
+
312
+ // Reuse the file's existing indentation (tabs or N spaces); default 2 spaces.
313
+ function detectIndent(text) {
314
+ if (text === null || text === undefined) return ' ';
315
+ if (text.match(/\n(\t+)"/)) return '\t';
316
+ const spaceMatch = text.match(/\n( +)"/);
317
+ return spaceMatch ? spaceMatch[1] : ' ';
318
+ }
319
+
320
+ function writeAtomic(file, contents) {
321
+ const tmp = `${file}.tmp-${process.pid}`;
322
+ try {
323
+ fs.mkdirSync(path.dirname(file), { recursive: true });
324
+ fs.writeFileSync(tmp, contents);
325
+ fs.renameSync(tmp, file);
326
+ } catch (err) {
327
+ try {
328
+ fs.unlinkSync(tmp);
329
+ } catch (_) {
330
+ /* nothing to clean up */
331
+ }
332
+ warnSkip(`could not write ${file} (${err.message})`);
333
+ }
334
+ }
335
+
336
+ function writeValues(file, data, indent) {
337
+ writeAtomic(file, JSON.stringify(data, null, indent) + '\n');
338
+ }
339
+
340
+ // ------------------------------------------------------------ resolution ----
341
+
342
+ function formatValue(value) {
343
+ if (value === true) return 'true';
344
+ if (value === false) return 'false';
345
+ return String(value);
346
+ }
347
+
348
+ // Resolution order is scope-constrained, not universal:
349
+ // either -> project -> global -> schema default -> unset
350
+ // global -> global -> schema default -> unset (NEVER reads the project file)
351
+ // project -> project -> schema default -> unset (NEVER reads the global file)
352
+ // A global-scope key sitting in a project file is not consulted: honouring it
353
+ // would make a machine-wide answer overridable per checkout.
354
+ function resolve(key, entry, opts) {
355
+ const files = [];
356
+ if (opts.target !== null) {
357
+ files.push({ layer: 'target', file: opts.target });
358
+ } else if (opts.global) {
359
+ files.push({ layer: 'global', file: globalFile() });
360
+ } else {
361
+ const scope = entry && typeof entry.scope === 'string' ? entry.scope : 'either';
362
+ if (scope !== 'global' && opts.projectDir !== null) {
363
+ files.push({ layer: 'project', file: projectFile(opts.projectDir) });
364
+ }
365
+ if (scope !== 'project') {
366
+ files.push({ layer: 'global', file: globalFile() });
367
+ }
368
+ }
369
+
370
+ for (const { layer, file } of files) {
371
+ const data = readLayer(file);
372
+ if (Object.prototype.hasOwnProperty.call(data, key) && data[key] !== null) {
373
+ return { value: data[key], layer };
374
+ }
375
+ }
376
+ if (entry && entry.default !== null && entry.default !== undefined) {
377
+ return { value: entry.default, layer: 'default' };
378
+ }
379
+ return { value: null, layer: 'unset' };
380
+ }
381
+
382
+ // ------------------------------------------------------------ slugifying ----
383
+
384
+ // Unicode-aware on purpose. The `u` flag makes the character class operate on
385
+ // code points, so the em dash in the template's
386
+ // "Claude Code — machine-local MCP registration ..." banner is one character
387
+ // inside one run of non-alphanumerics and collapses to a single '-'.
388
+ function slugifySectionTitle(title) {
389
+ return String(title)
390
+ .toLowerCase()
391
+ .replace(/[^a-z0-9]+/gu, '-')
392
+ .replace(/^-+|-+$/g, '');
393
+ }
394
+
395
+ // --------------------------------------------------------------- reports ----
396
+
397
+ function scopePermitsLayer(entry, layerName) {
398
+ if (layerName === 'target') return true;
399
+ const scope = entry && typeof entry.scope === 'string' ? entry.scope : 'either';
400
+ if (scope === 'either') return true;
401
+ return scope === layerName;
402
+ }
403
+
404
+ function escapeCell(text) {
405
+ return String(text === undefined || text === null ? '' : text).replace(/\|/g, '\\|');
406
+ }
407
+
408
+ function companionPath(valuesFile) {
409
+ return path.join(path.dirname(valuesFile), 'bootstrap-prefs.README.md');
410
+ }
411
+
412
+ // The companion is OUTPUT, never input. Regenerated on every successful write
413
+ // (including a no-op set — the schema may have changed since the last one).
414
+ function renderCompanion(valuesFile, layerName, schema, data) {
415
+ const rows = [];
416
+ for (const [key, entry] of Object.entries(schema)) {
417
+ if (!isPlainObject(entry)) continue;
418
+ if (!scopePermitsLayer(entry, layerName)) continue;
419
+
420
+ // Dynamic patterns describe a family; list the concrete keys this file
421
+ // actually holds instead of the `.*` placeholder.
422
+ if (entry.dynamic === true && key.endsWith('.*')) {
423
+ const prefix = key.slice(0, -1);
424
+ const concrete = Object.keys(data).filter((k) => k.length > prefix.length && k.startsWith(prefix));
425
+ if (concrete.length === 0) {
426
+ rows.push({ key, entry, value: null, layer: 'unset' });
427
+ } else {
428
+ for (const k of concrete.sort()) {
429
+ rows.push({ key: k, entry, value: data[k], layer: layerName });
430
+ }
431
+ }
432
+ continue;
433
+ }
434
+
435
+ if (Object.prototype.hasOwnProperty.call(data, key) && data[key] !== null) {
436
+ rows.push({ key, entry, value: data[key], layer: layerName });
437
+ } else if (entry.default !== null && entry.default !== undefined) {
438
+ rows.push({ key, entry, value: entry.default, layer: 'default' });
439
+ } else {
440
+ rows.push({ key, entry, value: null, layer: 'unset' });
441
+ }
442
+ }
443
+
444
+ // Anything in the values file that no row above explains is listed verbatim
445
+ // rather than dropped — including a key whose schema scope means THIS layer
446
+ // never consults it. A global-scope answer parked in a project file is inert,
447
+ // and silently hiding it would leave the user believing it took effect.
448
+ const documented = new Set(rows.map((r) => r.key));
449
+ const unrecognized = Object.keys(data)
450
+ .filter((k) => !documented.has(k))
451
+ .sort()
452
+ .map((key) => {
453
+ const entry = lookupSchema(schema, key);
454
+ const scope = entry && typeof entry.scope === 'string' ? entry.scope : null;
455
+ return {
456
+ key,
457
+ value: data[key],
458
+ reason:
459
+ entry === null
460
+ ? 'no entry in the preference schema'
461
+ : `scope is \`${scope}\` — this layer never consults it, so it has no effect here`,
462
+ };
463
+ });
464
+
465
+ const installerRows = rows.filter((r) => r.entry.consumer !== 'skill');
466
+ const skillRows = rows.filter((r) => r.entry.consumer === 'skill');
467
+
468
+ const header = (title) => [
469
+ '',
470
+ title,
471
+ '',
472
+ '| Key | Current value | Layer | What it does | Asked by |',
473
+ '| --- | --- | --- | --- | --- |',
474
+ ];
475
+ const line = (r) =>
476
+ `| \`${escapeCell(r.key)}\` | \`${escapeCell(r.layer === 'unset' ? 'unset' : formatValue(r.value))}\` | ` +
477
+ `${escapeCell(r.layer)} | ${escapeCell(r.entry.summary)} | ${escapeCell(r.entry.askedBy)} |`;
478
+
479
+ const out = [
480
+ '# bootstrap-prefs — stored answers',
481
+ '',
482
+ '**Generated file. Every `--set` and `--unset` rewrites it, and hand edits are',
483
+ 'overwritten without warning.** Edit the values file instead, or run',
484
+ '`/bootstrap-config`.',
485
+ '',
486
+ `- Describes: \`${path.basename(valuesFile)}\` in this directory (\`${valuesFile}\`)`,
487
+ `- Layer: **${layerName}**`,
488
+ `- Regenerated: ${new Date().toISOString()}`,
489
+ '',
490
+ 'A key that is absent from the values file is **unset** — that is the whole',
491
+ 'representation; `null` and the string `"unset"` are never written. Deleting a',
492
+ 'key is how you re-open a question.',
493
+ '',
494
+ '**No preference key ever holds a secret** — no API key, token, or password',
495
+ 'belongs in the values file or in this companion. Keep it that way when adding',
496
+ 'a key.',
497
+ ];
498
+
499
+ if (installerRows.length > 0) {
500
+ out.push(...header('## Installer preferences'));
501
+ out.push(...installerRows.map(line));
502
+ }
503
+ if (skillRows.length > 0) {
504
+ out.push(...header('## Skill preferences — changing these changes what a command does'));
505
+ out.push(...skillRows.map(line));
506
+ out.push('');
507
+ out.push('These keys are read by slash commands at run time. Changing one changes the');
508
+ out.push('behaviour of that command everywhere it runs from this layer.');
509
+ }
510
+
511
+ out.push('');
512
+ out.push('## Unrecognized keys');
513
+ out.push('');
514
+ if (unrecognized.length === 0) {
515
+ out.push('None — every key in the values file is described above.');
516
+ } else {
517
+ out.push('Present in the values file but not explained by the tables above. They are');
518
+ out.push('kept untouched so a file written by a newer bootstrap round-trips unchanged.');
519
+ out.push('');
520
+ for (const row of unrecognized) {
521
+ out.push(`- \`${row.key}\` = \`${formatValue(row.value)}\` — ${row.reason}`);
522
+ }
523
+ }
524
+
525
+ const selector =
526
+ layerName === 'global' ? '--global' : layerName === 'project' ? '--project <dir>' : `--target ${valuesFile}`;
527
+ out.push('');
528
+ out.push('## Changing your mind');
529
+ out.push('');
530
+ out.push('Re-open a question (removes the key, so the next run asks again):');
531
+ out.push('');
532
+ out.push('```');
533
+ out.push(`node lib/scripts/bootstrap-prefs.js --unset <key> ${selector}`);
534
+ out.push('```');
535
+ out.push('');
536
+ out.push('Or run `/bootstrap-config` to view, edit, and reset every stored answer.');
537
+ out.push('');
538
+
539
+ return out.join('\n');
540
+ }
541
+
542
+ function writeCompanion(valuesFile, layerName, schema, data) {
543
+ writeAtomic(companionPath(valuesFile), renderCompanion(valuesFile, layerName, schema, data));
544
+ }
545
+
546
+ // ------------------------------------------------------------------ main ----
547
+
548
+ const opts = parseArgs(process.argv.slice(2));
549
+ const operation =
550
+ opts.op === 'list' || opts.op === 'section-key' ? `--${opts.op}` : `--${opts.op} ${opts.key}`;
551
+
552
+ if (opts.op === 'section-key') {
553
+ const slug = slugifySectionTitle(opts.title);
554
+ if (slug === '') {
555
+ console.error(`Error: "${opts.title}" slugifies to an empty string; it cannot name a preference key`);
556
+ process.exit(1);
557
+ }
558
+ console.log(`gitignore.section.${slug}`);
559
+ process.exit(0);
560
+ }
561
+
562
+ const schema = loadSchema(opts.schema);
563
+
564
+ if (opts.op === 'get') {
565
+ const entry = lookupSchema(schema, opts.key);
566
+ const { value, layer } = resolve(opts.key, entry, opts);
567
+ // Print the literal word `unset`, never an empty line: an empty capture is
568
+ // indistinguishable from a crashed script and a shell caller would read it
569
+ // as a decline.
570
+ console.log(layer === 'unset' ? 'unset' : formatValue(value));
571
+ process.exit(0);
572
+ }
573
+
574
+ if (opts.op === 'list') {
575
+ const consulted = [];
576
+ if (opts.target !== null) {
577
+ consulted.push({ layer: 'target', file: opts.target });
578
+ } else {
579
+ if (opts.projectDir !== null) consulted.push({ layer: 'project', file: projectFile(opts.projectDir) });
580
+ consulted.push({ layer: 'global', file: globalFile() });
581
+ }
582
+
583
+ const groups = new Map();
584
+ const dynamicPrefixes = [];
585
+ const add = (consumer, row) => {
586
+ if (!groups.has(consumer)) groups.set(consumer, []);
587
+ groups.get(consumer).push(row);
588
+ };
589
+ for (const [key, entry] of Object.entries(schema)) {
590
+ if (!isPlainObject(entry)) continue;
591
+ const consumer = typeof entry.consumer === 'string' ? entry.consumer : 'other';
592
+
593
+ // A `dynamic: true` pattern names a family, not a key. Show the concrete
594
+ // keys the consulted files actually hold; fall back to the pattern itself
595
+ // so the family is still documented when nothing has been answered.
596
+ if (entry.dynamic === true && key.endsWith('.*')) {
597
+ const prefix = key.slice(0, -1);
598
+ dynamicPrefixes.push(prefix);
599
+ const concrete = new Set();
600
+ for (const { file } of consulted) {
601
+ for (const k of Object.keys(readLayer(file))) {
602
+ if (k.length > prefix.length && k.startsWith(prefix)) concrete.add(k);
603
+ }
604
+ }
605
+ if (concrete.size === 0) {
606
+ add(consumer, { key, entry, value: null, layer: 'unset' });
607
+ } else {
608
+ for (const k of [...concrete].sort()) {
609
+ const r = resolve(k, entry, opts);
610
+ add(consumer, { key: k, entry, value: r.value, layer: r.layer });
611
+ }
612
+ }
613
+ continue;
614
+ }
615
+
616
+ const { value, layer } = resolve(key, entry, opts);
617
+ add(consumer, { key, entry, value, layer });
618
+ }
619
+
620
+ const order = ['installer', 'skill'];
621
+ const consumers = [
622
+ ...order.filter((c) => groups.has(c)),
623
+ ...[...groups.keys()].filter((c) => !order.includes(c)).sort(),
624
+ ];
625
+
626
+ for (const consumer of consumers) {
627
+ console.log('');
628
+ console.log(
629
+ consumer === 'skill'
630
+ ? 'skill — read by slash commands at run time; changing these changes what a command does'
631
+ : `${consumer} — read by the setup/update scripts`
632
+ );
633
+ for (const row of groups.get(consumer)) {
634
+ const shown = row.layer === 'unset' ? 'unset' : formatValue(row.value);
635
+ console.log(` ${row.key} = ${shown} [${row.layer}]`);
636
+ if (row.entry.summary) console.log(` ${row.entry.summary}`);
637
+ }
638
+ }
639
+
640
+ const seen = new Map();
641
+ for (const { layer, file } of consulted) {
642
+ for (const key of Object.keys(readLayer(file))) {
643
+ if (Object.prototype.hasOwnProperty.call(schema, key)) continue;
644
+ if (dynamicPrefixes.some((p) => key.length > p.length && key.startsWith(p))) continue;
645
+ if (!seen.has(key)) seen.set(key, { layer, value: readLayer(file)[key] });
646
+ }
647
+ }
648
+ if (seen.size > 0) {
649
+ console.log('');
650
+ console.log('unrecognized — present in a values file, absent from the schema (kept untouched)');
651
+ for (const [key, info] of [...seen.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
652
+ console.log(` ${key} = ${formatValue(info.value)} [${info.layer}]`);
653
+ }
654
+ }
655
+
656
+ console.log('');
657
+ if (opts.target !== null) {
658
+ console.log(`Showing ${opts.target} only (--target bypasses layer resolution).`);
659
+ } else if (opts.projectDir === null) {
660
+ console.log('No --project given: the project layer was not consulted; showing the global layer only.');
661
+ } else {
662
+ console.log(`Layers: project (${projectFile(opts.projectDir)}) then global (${globalFile()}).`);
663
+ }
664
+ process.exit(0);
665
+ }
666
+
667
+ // ------------------------------------------------------------- write ops ----
668
+
669
+ const targetFile =
670
+ opts.target !== null ? opts.target : opts.global ? globalFile() : projectFile(opts.projectDir);
671
+ const targetLayer = opts.target !== null ? 'target' : opts.global ? 'global' : 'project';
672
+
673
+ if (opts.op === 'set') {
674
+ if (opts.value === 'unset' || opts.value === 'null') {
675
+ console.error(
676
+ `Error: "${opts.value}" is not a storable value — absence is how a key is unset. ` +
677
+ `Use: --unset ${opts.key}`
678
+ );
679
+ process.exit(1);
680
+ }
681
+
682
+ const entry = lookupSchema(schema, opts.key);
683
+ if (entry === null) {
684
+ // Forward compatibility: a values file written by a newer bootstrap must
685
+ // round-trip through an older helper unchanged. Unfamiliar KEYS are fine;
686
+ // invalid VALUES are the thing that must hard-fail.
687
+ warn(`"${opts.key}" is not in the preference schema — writing it anyway`);
688
+ } else {
689
+ const allowed = allowedValues(entry);
690
+ if (allowed !== null && !allowed.includes(opts.value)) {
691
+ console.error(
692
+ `Error: "${opts.value}" is not a legal value for ${opts.key} — expected one of: ${allowed.join(', ')}`
693
+ );
694
+ process.exit(1);
695
+ }
696
+ }
697
+
698
+ // 'true'/'false' become JSON booleans; everything else is a JSON string.
699
+ // Storing "false" as a string would be truthy in every shell test and would
700
+ // read back as a settled true.
701
+ const coerced = opts.value === 'true' ? true : opts.value === 'false' ? false : opts.value;
702
+
703
+ const { text, data } = readWritableTarget(targetFile);
704
+ const unchanged = Object.prototype.hasOwnProperty.call(data, opts.key) && data[opts.key] === coerced;
705
+ data[opts.key] = coerced;
706
+ writeValues(targetFile, data, detectIndent(text));
707
+ writeCompanion(targetFile, targetLayer, schema, data);
708
+ console.log(
709
+ unchanged
710
+ ? `${targetLayer}: ${opts.key} already ${formatValue(coerced)}`
711
+ : `${targetLayer}: ${opts.key} = ${formatValue(coerced)}`
712
+ );
713
+ process.exit(0);
714
+ }
715
+
716
+ if (opts.op === 'unset') {
717
+ if (!fs.existsSync(targetFile)) {
718
+ console.log(`${targetLayer}: ${opts.key} was already unset (no preferences file at ${targetFile})`);
719
+ process.exit(0);
720
+ }
721
+ const { text, data } = readWritableTarget(targetFile);
722
+ const present = Object.prototype.hasOwnProperty.call(data, opts.key);
723
+ if (present) {
724
+ delete data[opts.key];
725
+ writeValues(targetFile, data, detectIndent(text));
726
+ }
727
+ writeCompanion(targetFile, targetLayer, schema, data);
728
+ console.log(
729
+ present
730
+ ? `${targetLayer}: ${opts.key} unset — the question is re-opened`
731
+ : `${targetLayer}: ${opts.key} was already unset`
732
+ );
733
+ process.exit(0);
734
+ }