@jjanczur/tyran 0.1.23 → 0.1.25

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,542 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * settings — the knobs an operator may turn, and what each one means.
4
+ *
5
+ * `.tyran/config.yaml` and `.tyran/policies/autonomy.yaml` were editable in
6
+ * exactly one way before this file existed: open them in an editor and know
7
+ * what you are doing. That is fine for the person who wrote them and useless
8
+ * for everyone else, and the board — the one screen an operator already has
9
+ * open — could not answer "where do I change this?" at all.
10
+ *
11
+ * So this module is the CATALOGUE: every knob, its type, its legal values, and
12
+ * a sentence of prose saying what turning it actually does. The board renders
13
+ * it; `applySetting` writes it back through `yaml-patch`, which keeps the
14
+ * file's comments; `schema.mjs` validates the result before anything lands.
15
+ *
16
+ * ## One answer in one place
17
+ *
18
+ * The legal values are IMPORTED, never restated: `PROFILES`, `AUTONOMY_CLASSES`,
19
+ * `TIER_KEYS`, `LIMITS_MODES`, `LIMITS_LONG_WAIT`, `ARTIFACT_CLASSES` all come
20
+ * from `schema.mjs`, which is the validator. A second list here would drift
21
+ * from the one that enforces it, and the UI would offer a choice the file
22
+ * rejects. The prose is the only thing this file owns.
23
+ *
24
+ * ## What is deliberately NOT here
25
+ *
26
+ * `pricing:` — a rate card is a table of numbers copied from a vendor's price
27
+ * list, which is a spreadsheet task, not a knob. It stays a hand edit.
28
+ *
29
+ * Adding and removing POLICY RULES. A rule is a path glob, a class and a
30
+ * written reason, and the reason is the load-bearing part: `docs/policy-gate.md`
31
+ * asks every boundary to say why it exists. Changing an existing rule's class
32
+ * is a decision the operator can make from a screen; authoring a new boundary
33
+ * with a one-line reason typed into a web form is how a policy file turns into
34
+ * a list of unexplained globs. Class changes are here; authoring is not.
35
+ */
36
+ import { existsSync, readFileSync } from 'node:fs';
37
+ import { join } from 'node:path';
38
+ import {
39
+ ARTIFACT_CLASSES,
40
+ AUTONOMY_CLASSES,
41
+ LIMITS_LONG_WAIT,
42
+ LIMITS_MODES,
43
+ MANDATORY_KERNEL_PATHS,
44
+ PROFILES,
45
+ TIER_KEYS,
46
+ validateConfig,
47
+ validatePolicy,
48
+ } from './schema.mjs';
49
+ import { parse, YamlLiteError } from './yaml-lite.mjs';
50
+ import { patch, YamlPatchError } from './yaml-patch.mjs';
51
+
52
+ export const SETTINGS_SCHEMA = 1;
53
+
54
+ export const CONFIG_FILE = 'config.yaml';
55
+ export const POLICY_FILE = join('policies', 'autonomy.yaml');
56
+
57
+ export class SettingsError extends Error {
58
+ constructor(message, detail = {}) {
59
+ super(message);
60
+ Object.assign(this, detail);
61
+ }
62
+ }
63
+
64
+ const choice = (values, describe) => ({ kind: 'choice', choices: values.map((v) => ({ value: v, describe: describe[v] })) });
65
+
66
+ /**
67
+ * Every editable knob in `config.yaml`, grouped the way an operator thinks
68
+ * about them rather than the way YAML nests them.
69
+ *
70
+ * `path` addresses the value inside the document. Fields that `schema.mjs`
71
+ * wraps in provenance (`profile`, `autonomy`, `validation` can each be either
72
+ * a bare value or `{value, source, confidence}`) are resolved at read time by
73
+ * `resolvePath` — the catalogue names the logical field, not the spelling a
74
+ * particular file happens to use.
75
+ */
76
+ export const GROUPS = Object.freeze([
77
+ {
78
+ id: 'work',
79
+ title: 'How work gets done',
80
+ blurb: 'What Tyran spends, and how far it may go on its own.',
81
+ settings: [
82
+ {
83
+ id: 'profile',
84
+ path: ['profile'],
85
+ label: 'Cost profile',
86
+ help: 'How much verification each piece of work carries. The cheaper profiles skip review passes, not tests.',
87
+ ...choice(PROFILES, {
88
+ eco: 'Fewest agents and fewest review passes. Good for small, well-understood changes.',
89
+ balanced: 'The default. Implementation plus an independent review on anything non-trivial.',
90
+ full: 'Every gate, every review, the strongest tier where it matters. Slow and thorough.',
91
+ }),
92
+ },
93
+ {
94
+ id: 'autonomy',
95
+ path: ['autonomy'],
96
+ label: 'Deployment autonomy',
97
+ help: 'How far a finished piece of work may travel without you. The gate enforces this downward — it will not stop someone who edits this file from raising it, which is why the policy below decides who may.',
98
+ ...choice(AUTONOMY_CLASSES, {
99
+ P1: 'Branch only. Agents commit and push a branch; you open and merge the PR.',
100
+ P2: 'Through to staging. Agents may merge and deploy to a non-production environment.',
101
+ P3: 'Merge to main. Agents may land work on the default branch by themselves.',
102
+ }),
103
+ },
104
+ ],
105
+ },
106
+ {
107
+ id: 'tiers',
108
+ title: 'Model tiers',
109
+ blurb:
110
+ 'The only place model names appear. Skills, agents and policies are all written in ROLE names, so a model deprecation is four lines here and nothing else moves.',
111
+ settings: TIER_KEYS.map((key) => ({
112
+ id: `tiers.${key}`,
113
+ path: ['tiers', key],
114
+ label: key,
115
+ kind: 'text',
116
+ help: {
117
+ cheap: 'Scouts, mechanical sweeps, ledger bookkeeping. Work where being fast beats being clever.',
118
+ work: 'The default tier: ordinary implementation and ordinary review. Most work lands here.',
119
+ deep: 'Root-cause diagnosis, hard implementation, risky review — where a wrong answer is expensive.',
120
+ top: 'Security review, arbitration, final acceptance. The last word, used sparingly.',
121
+ }[key],
122
+ placeholder: 'a model id or alias your CLI accepts',
123
+ })),
124
+ },
125
+ {
126
+ id: 'proof',
127
+ title: 'Proving it works',
128
+ blurb: 'What every agent must run before it is allowed to call anything done.',
129
+ settings: [
130
+ {
131
+ id: 'validation',
132
+ path: ['validation'],
133
+ label: 'Validation commands',
134
+ kind: 'list',
135
+ help: 'Run in order before any work is reported. Each must EXIT — a watch-mode test runner here hangs every agent you ever spawn, which is a real measured incident, not a hypothetical.',
136
+ placeholder: 'npm test',
137
+ },
138
+ {
139
+ id: 'shared_zones',
140
+ path: ['shared_zones'],
141
+ label: 'Shared zones',
142
+ kind: 'list',
143
+ help: 'Files more than one agent may touch in parallel. Writes to these are append-only and serialized by the conductor, so two agents cannot clobber each other.',
144
+ placeholder: 'src/registry.ts',
145
+ },
146
+ ],
147
+ },
148
+ {
149
+ id: 'overnight',
150
+ title: 'Overnight mode',
151
+ blurb:
152
+ 'Pause near the subscription usage limit and resume after the window resets. Needs the statusline helper installed — it is the only place the platform reports usage, and without it this whole section is inert and doctor says so.',
153
+ settings: [
154
+ {
155
+ id: 'limits.mode',
156
+ path: ['limits', 'mode'],
157
+ label: 'Mode',
158
+ ...choice(LIMITS_MODES, {
159
+ off: 'Nothing pauses. The usage gate never denies a tool call.',
160
+ warn: 'Surfaces how close you are, but never denies anything.',
161
+ pause: 'Winds work down at the threshold, checkpoints it, and schedules the resume.',
162
+ }),
163
+ help: 'What happens as the usage window fills up.',
164
+ },
165
+ {
166
+ id: 'limits.pause_at_percent',
167
+ path: ['limits', 'pause_at_percent'],
168
+ label: 'Pause at (5-hour window)',
169
+ kind: 'number',
170
+ min: 50,
171
+ max: 100,
172
+ unit: '%',
173
+ help: 'How full the five-hour window must be before work winds down. The floor of 50 exists to catch 0.97 pasted where 97 belongs.',
174
+ },
175
+ {
176
+ id: 'limits.weekly_pause_at_percent',
177
+ path: ['limits', 'weekly_pause_at_percent'],
178
+ label: 'Pause at (weekly window)',
179
+ kind: 'number',
180
+ min: 50,
181
+ max: 100,
182
+ unit: '%',
183
+ help: 'The same threshold for the seven-day window. Hitting this one means a much longer wait.',
184
+ },
185
+ {
186
+ id: 'limits.wait_max_hours',
187
+ path: ['limits', 'wait_max_hours'],
188
+ label: 'Longest silent wait',
189
+ kind: 'number',
190
+ min: 0.5,
191
+ max: 24,
192
+ unit: 'h',
193
+ help: 'A reset further away than this is a LONG pause: it gets announced rather than silently waited out. The weekly window can be days.',
194
+ },
195
+ {
196
+ id: 'limits.long_wait',
197
+ path: ['limits', 'long_wait'],
198
+ label: 'Beyond that',
199
+ ...choice(LIMITS_LONG_WAIT, {
200
+ hold: 'Stop and tell you. You decide when to pick it back up.',
201
+ resume: 'Schedule the resume anyway, however far out it is.',
202
+ }),
203
+ help: 'What the scheduler does when the reset is further away than the wait above.',
204
+ },
205
+ {
206
+ id: 'limits.resume_margin_minutes',
207
+ path: ['limits', 'resume_margin_minutes'],
208
+ label: 'Resume margin',
209
+ kind: 'number',
210
+ min: 1,
211
+ max: 240,
212
+ unit: 'min',
213
+ help: 'How long after the window resets before work restarts. A little slack absorbs clock skew between your machine and the platform.',
214
+ },
215
+ {
216
+ id: 'limits.keep_awake',
217
+ path: ['limits', 'keep_awake'],
218
+ label: 'Hold the machine awake',
219
+ kind: 'boolean',
220
+ help: 'A laptop that suspends takes the resume watcher down with it. This holds the SYSTEM awake while it waits — never the display, so your screen lock is untouched.',
221
+ },
222
+ ],
223
+ },
224
+ ]);
225
+
226
+ const BY_ID = new Map(GROUPS.flatMap((g) => g.settings.map((s) => [s.id, s])));
227
+
228
+ /**
229
+ * Which way is looser.
230
+ *
231
+ * Two changes on this screen are not like the others: lowering a path's class
232
+ * lets agents write something they previously had to ask about, and raising
233
+ * the deployment class lets finished work travel further without a human. A
234
+ * dropdown treats both as ordinary, and the shipped policy carries rules whose
235
+ * own stated reason is that they must not move — `.claude/settings.json`
236
+ * ("anything that can edit it can switch every gate off"), `.tyran/STOP` ("a
237
+ * loop that can clear its own stop signal has none"). None of those is in
238
+ * `MANDATORY_KERNEL_PATHS`, so the validator does not stop them and nothing
239
+ * else did either.
240
+ *
241
+ * The rule is strictly one-directional. TIGHTENING applies on one click,
242
+ * exactly like every other setting — friction on making a boundary stricter is
243
+ * how you teach people to stop making boundaries stricter. Loosening needs a
244
+ * second, deliberate act, and the page shows the rule's own reason first.
245
+ */
246
+ const LOOSER_FIRST = Object.freeze({
247
+ class: Object.freeze(['AUTO', 'GATED', 'KERNEL']),
248
+ autonomy: Object.freeze(['P3', 'P2', 'P1']),
249
+ });
250
+
251
+ function widens(scale, before, after) {
252
+ const order = LOOSER_FIRST[scale];
253
+ const from = order.indexOf(before);
254
+ const to = order.indexOf(after);
255
+ // An unknown value is treated as a widening: this guard exists for the case
256
+ // where something unexpected is happening, and a value nobody recognises is
257
+ // not the moment to wave a change through.
258
+ if (from === -1 || to === -1) return before !== after;
259
+ return to < from;
260
+ }
261
+
262
+ /**
263
+ * The confirmation a widening write must carry.
264
+ *
265
+ * It is the new value itself rather than a boolean, so a caller cannot satisfy
266
+ * it by sending `confirm: true` alongside whatever value it liked — the token
267
+ * only matches the change the operator was actually shown.
268
+ */
269
+ function requireConfirm(scale, before, after, confirm, consequence) {
270
+ if (!widens(scale, before, after)) return;
271
+ if (confirm === after) return;
272
+ throw new SettingsError(
273
+ `${before} -> ${after} loosens this boundary, so it needs a second, deliberate confirmation. ${consequence}`,
274
+ { widens: true, confirm_with: after },
275
+ );
276
+ }
277
+
278
+ /** Every setting, flat, in catalogue order. */
279
+ export function allSettings() {
280
+ return GROUPS.flatMap((g) => g.settings);
281
+ }
282
+
283
+ /**
284
+ * The real path to a value, allowing for provenance.
285
+ *
286
+ * `profile: balanced` and `profile: {value: balanced, source: ...}` are both
287
+ * legal and mean the same thing, so the catalogue names `profile` and this
288
+ * decides which of the two spellings the file in front of us is using.
289
+ */
290
+ function resolvePath(doc, path) {
291
+ let node = doc;
292
+ for (const segment of path) {
293
+ if (node === null || typeof node !== 'object') return null;
294
+ node = node[segment];
295
+ }
296
+ if (node !== null && typeof node === 'object' && !Array.isArray(node) && 'value' in node) {
297
+ return [...path, 'value'];
298
+ }
299
+ return path;
300
+ }
301
+
302
+ function readAt(doc, path) {
303
+ let node = doc;
304
+ for (const segment of path) {
305
+ if (node === null || typeof node !== 'object') return undefined;
306
+ node = node[segment];
307
+ }
308
+ return node;
309
+ }
310
+
311
+ /** Read a YAML file, reporting a parse failure as data rather than throwing. */
312
+ function loadFile(file) {
313
+ if (!existsSync(file)) return { present: false, doc: null, error: null, text: '' };
314
+ let text;
315
+ try {
316
+ text = readFileSync(file, 'utf8');
317
+ } catch (err) {
318
+ return { present: true, doc: null, error: String(err?.message ?? err), text: '' };
319
+ }
320
+ try {
321
+ return { present: true, doc: parse(text), error: null, text };
322
+ } catch (err) {
323
+ // A config that does not parse is exactly when an operator most wants to
324
+ // see this screen, so the failure is rendered rather than thrown.
325
+ return { present: true, doc: null, error: err instanceof YamlLiteError ? err.message : String(err?.message ?? err), text };
326
+ }
327
+ }
328
+
329
+ /**
330
+ * A rule may only be shown as editable if changing its class could ever be
331
+ * accepted. The kernel paths that protect the gate itself can be tightened but
332
+ * never lowered — `validatePolicy` enforces that and would refuse the write —
333
+ * so offering the choice would be offering a button that always fails.
334
+ */
335
+ function ruleLocked(rulePath) {
336
+ return MANDATORY_KERNEL_PATHS.includes(rulePath);
337
+ }
338
+
339
+ /** Everything the board needs to draw the Settings tab. */
340
+ export function readSettings(tyranDir) {
341
+ const configFile = join(tyranDir, CONFIG_FILE);
342
+ const policyFile = join(tyranDir, POLICY_FILE);
343
+ const config = loadFile(configFile);
344
+ const policy = loadFile(policyFile);
345
+
346
+ const groups = GROUPS.map((group) => ({
347
+ id: group.id,
348
+ title: group.title,
349
+ blurb: group.blurb,
350
+ settings: group.settings.map((setting) => {
351
+ const present = config.doc !== null && readAt(config.doc, resolvePath(config.doc, setting.path)) !== undefined;
352
+ return {
353
+ id: setting.id,
354
+ label: setting.label,
355
+ help: setting.help,
356
+ kind: setting.kind ?? 'choice',
357
+ choices: setting.choices ?? null,
358
+ min: setting.min ?? null,
359
+ max: setting.max ?? null,
360
+ unit: setting.unit ?? null,
361
+ placeholder: setting.placeholder ?? null,
362
+ present,
363
+ value: present ? readAt(config.doc, resolvePath(config.doc, setting.path)) : null,
364
+ };
365
+ }),
366
+ }));
367
+
368
+ const rules = Array.isArray(policy.doc?.rules)
369
+ ? policy.doc.rules
370
+ .filter((rule) => rule !== null && typeof rule === 'object' && typeof rule.path === 'string')
371
+ .map((rule) => ({
372
+ path: rule.path,
373
+ class: rule.class ?? null,
374
+ reason: typeof rule.reason === 'string' ? rule.reason : '',
375
+ locked: ruleLocked(rule.path),
376
+ }))
377
+ : [];
378
+
379
+ return {
380
+ schema: SETTINGS_SCHEMA,
381
+ files: {
382
+ config: { path: join(tyranDir, CONFIG_FILE), present: config.present, error: config.error },
383
+ policy: { path: join(tyranDir, POLICY_FILE), present: policy.present, error: policy.error },
384
+ },
385
+ groups,
386
+ policy: {
387
+ classes: [...ARTIFACT_CLASSES],
388
+ describe: {
389
+ AUTO: 'Agents write it themselves. Rollback is a git revert.',
390
+ GATED: 'Agents propose, you approve. Denied outright to a subagent.',
391
+ KERNEL: 'Humans only, by hand. Never autonomously, ever.',
392
+ },
393
+ default: policy.doc?.default ?? null,
394
+ rules,
395
+ },
396
+ };
397
+ }
398
+
399
+ /** Reject a value that the catalogue's own type says is wrong. */
400
+ function coerce(setting, raw) {
401
+ const kind = setting.kind ?? 'choice';
402
+ if (kind === 'choice') {
403
+ const legal = setting.choices.map((c) => c.value);
404
+ if (!legal.includes(raw)) throw new SettingsError(`${setting.id}: must be one of ${legal.join(' | ')}`);
405
+ return raw;
406
+ }
407
+ if (kind === 'boolean') {
408
+ if (typeof raw !== 'boolean') throw new SettingsError(`${setting.id}: must be true or false`);
409
+ return raw;
410
+ }
411
+ if (kind === 'number') {
412
+ if (typeof raw !== 'number' || !Number.isFinite(raw)) throw new SettingsError(`${setting.id}: must be a number`);
413
+ if (raw < setting.min || raw > setting.max) {
414
+ throw new SettingsError(`${setting.id}: must be between ${setting.min} and ${setting.max}`);
415
+ }
416
+ return raw;
417
+ }
418
+ if (kind === 'text') {
419
+ if (typeof raw !== 'string' || raw.trim() === '') throw new SettingsError(`${setting.id}: must not be empty`);
420
+ return raw.trim();
421
+ }
422
+ if (kind === 'list') {
423
+ if (!Array.isArray(raw)) throw new SettingsError(`${setting.id}: must be a list`);
424
+ const items = raw.map((item) => (typeof item === 'string' ? item.trim() : item)).filter((item) => item !== '');
425
+ for (const item of items) {
426
+ if (typeof item !== 'string') throw new SettingsError(`${setting.id}: every entry must be text`);
427
+ }
428
+ return items;
429
+ }
430
+ throw new SettingsError(`${setting.id}: no editor for this kind of value`);
431
+ }
432
+
433
+ /**
434
+ * Write one config setting, or refuse and change nothing.
435
+ *
436
+ * The order is the point: patch the TEXT, re-validate the RESULT with the same
437
+ * validator `schema.mjs validate` runs, and only then hand the caller
438
+ * something to write. A value that would produce a config the validator
439
+ * rejects never reaches the disk, so the board cannot leave a repo in a state
440
+ * its own tooling refuses to load.
441
+ */
442
+ export function applySetting(tyranDir, id, value, confirm = null) {
443
+ const setting = BY_ID.get(id);
444
+ if (!setting) throw new SettingsError(`unknown setting "${id}"`);
445
+ const file = join(tyranDir, CONFIG_FILE);
446
+ const loaded = loadFile(file);
447
+ if (!loaded.present) throw new SettingsError(`${file} does not exist — run /tyran:setup first`);
448
+ if (loaded.doc === null) throw new SettingsError(`${file} does not parse, so it cannot be edited safely: ${loaded.error}`);
449
+
450
+ const path = resolvePath(loaded.doc, setting.path);
451
+ const before = readAt(loaded.doc, path);
452
+ if (before === undefined) {
453
+ throw new SettingsError(
454
+ `"${setting.path.join('.')}" is not in ${file}. This screen edits values that are already there; ` +
455
+ 'add the key by hand once and it becomes editable here.',
456
+ );
457
+ }
458
+ const next = coerce(setting, value);
459
+ if (id === 'autonomy') {
460
+ requireConfirm('autonomy', before, next, confirm,
461
+ 'A higher deployment class lets finished work travel further without you — P2 reaches staging, P3 merges to the default branch.');
462
+ }
463
+
464
+ let text;
465
+ try {
466
+ text = patch(loaded.text, path, next);
467
+ } catch (err) {
468
+ if (err instanceof YamlPatchError) throw new SettingsError(err.message);
469
+ throw err;
470
+ }
471
+
472
+ const errors = validateConfig(parse(text));
473
+ if (errors.length > 0) {
474
+ throw new SettingsError(`that change makes the config invalid, so nothing was written:\n ${errors.join('\n ')}`);
475
+ }
476
+ return { file, path, before, after: next, text };
477
+ }
478
+
479
+ /**
480
+ * Change one policy rule's class, or the default class, and refuse anything
481
+ * that would weaken the boundary protecting the gate.
482
+ *
483
+ * The rule is addressed by its path GLOB, not by its position, and re-resolved
484
+ * against the file as it is right now. An index captured when the page loaded
485
+ * would point at a different rule if the file moved underneath it, and the
486
+ * write would land on the wrong boundary with no error at all.
487
+ */
488
+ export function applyPolicyClass(tyranDir, rulePath, klass, confirm = null) {
489
+ if (!ARTIFACT_CLASSES.includes(klass)) {
490
+ throw new SettingsError(`class must be one of ${ARTIFACT_CLASSES.join(' | ')}`);
491
+ }
492
+ const file = join(tyranDir, POLICY_FILE);
493
+ const loaded = loadFile(file);
494
+ if (!loaded.present) throw new SettingsError(`${file} does not exist — run /tyran:setup first`);
495
+ if (loaded.doc === null) throw new SettingsError(`${file} does not parse, so it cannot be edited safely: ${loaded.error}`);
496
+
497
+ let path;
498
+ let before;
499
+ let consequence;
500
+ if (rulePath === null) {
501
+ path = ['default'];
502
+ before = loaded.doc.default;
503
+ if (before === undefined) throw new SettingsError(`${file} has no "default" — add one by hand once and it becomes editable here`);
504
+ consequence = 'This is the class every path no rule matches gets, so it is the widest change available on this screen.';
505
+ } else {
506
+ if (ruleLocked(rulePath)) {
507
+ throw new SettingsError(
508
+ `"${rulePath}" is one of the paths that protect the gate itself, and it stays KERNEL. ` +
509
+ 'A system that can lower the class of its own enforcement has no boundary at all.',
510
+ );
511
+ }
512
+ const rules = Array.isArray(loaded.doc.rules) ? loaded.doc.rules : [];
513
+ const index = rules.findIndex((rule) => rule !== null && typeof rule === 'object' && rule.path === rulePath);
514
+ if (index === -1) throw new SettingsError(`no rule for "${rulePath}" in ${file}`);
515
+ path = ['rules', index, 'class'];
516
+ before = rules[index].class;
517
+ // The rule's own `reason:` is the consequence, verbatim. Every boundary in
518
+ // this file is required to say why it exists; that sentence was written by
519
+ // whoever put the boundary there, and it is a better warning than anything
520
+ // this module could compose about a path it has never seen.
521
+ consequence = typeof rules[index].reason === 'string' && rules[index].reason !== ''
522
+ ? `This rule exists because: ${rules[index].reason}`
523
+ : 'This rule records no reason, which is itself worth looking at before loosening it.';
524
+ }
525
+ requireConfirm('class', before, klass, confirm, consequence);
526
+
527
+ let text;
528
+ try {
529
+ text = patch(loaded.text, path, klass);
530
+ } catch (err) {
531
+ if (err instanceof YamlPatchError) throw new SettingsError(err.message);
532
+ throw err;
533
+ }
534
+
535
+ // The same validator `schema.mjs validate policy` runs — including the check
536
+ // that no rule, however spelled, can claim a kernel path at a lower class.
537
+ const errors = validatePolicy(parse(text));
538
+ if (errors.length > 0) {
539
+ throw new SettingsError(`that change makes the policy invalid, so nothing was written:\n ${errors.join('\n ')}`);
540
+ }
541
+ return { file, path, before, after: klass, text };
542
+ }
@@ -42,7 +42,18 @@ const REASON_BYTES = 2000;
42
42
  * be asked. A brake that releases itself when it is damaged is not a brake.
43
43
  */
44
44
  export function checkStop(repoDir) {
45
- const path = join(repoDir, STOP_PATH);
45
+ return checkStopAt(join(repoDir, STOP_PATH));
46
+ }
47
+
48
+ /**
49
+ * The same answer, for a caller that already knows where the file is.
50
+ *
51
+ * The board is given a `--dir` that need not be spelled `.tyran`, so it cannot
52
+ * reconstruct the path by joining a repo root to a constant. A second
53
+ * existsSync-and-read there would be a second spelling of the fail-CLOSED rule
54
+ * below, which is exactly the rule that must not have two spellings.
55
+ */
56
+ export function checkStopAt(path) {
46
57
  if (!existsSync(path)) return { stopped: false, reason: null, path };
47
58
  try {
48
59
  if (statSync(path).isDirectory()) {
@@ -115,7 +115,16 @@ function parseScalar(raw, lineNo, { allowFlow = true } = {}) {
115
115
  return value;
116
116
  }
117
117
 
118
- function stripComment(line, lineNo) {
118
+ /**
119
+ * Split a line into its code and its trailing comment.
120
+ *
121
+ * Exported because an EDITOR needs the half a parser throws away. Patching one
122
+ * value in a hand-written config means putting the operator's comment back
123
+ * afterwards, and a second `#`-finder written elsewhere would disagree with
124
+ * this one about `url: 'http://x/#frag'` on exactly the files where being
125
+ * wrong costs a comment.
126
+ */
127
+ export function splitInlineComment(line, lineNo) {
119
128
  // Comments start at ` #` outside quotes; a leading `#` is a full-line comment.
120
129
  let inSingle = false;
121
130
  let inDouble = false;
@@ -156,7 +165,11 @@ function stripComment(line, lineNo) {
156
165
  lineNo,
157
166
  );
158
167
  }
159
- return cut === -1 ? line : line.slice(0, cut);
168
+ return cut === -1 ? { code: line, comment: '' } : { code: line.slice(0, cut), comment: line.slice(cut) };
169
+ }
170
+
171
+ function stripComment(line, lineNo) {
172
+ return splitInlineComment(line, lineNo).code;
160
173
  }
161
174
 
162
175
  /** Parse a YAML-subset document into a plain JS object. */
@@ -377,7 +390,17 @@ function formatKey(key) {
377
390
  return s;
378
391
  }
379
392
 
380
- function formatScalar(value) {
393
+ /**
394
+ * Render one scalar as this subset spells it — quoting whenever an unquoted
395
+ * spelling would read back as something else.
396
+ *
397
+ * Exported for the same reason as `splitInlineComment`: an editor that writes
398
+ * a single value into an existing file must quote it by exactly the rules
399
+ * `parse` reads by. `mode: off` is the standing proof — bare `off` is the
400
+ * boolean false in YAML, so the string "off" has to come back quoted or the
401
+ * overnight gate silently changes meaning.
402
+ */
403
+ export function formatScalar(value) {
381
404
  if (value === null || value === undefined) return 'null';
382
405
  if (typeof value === 'boolean' || typeof value === 'number') return String(value);
383
406
  const s = String(value);