@promptctl/cc-candybar 1.29.0 → 1.31.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.
@@ -100,7 +100,17 @@ export function coercePersistValue(
100
100
  `coercePersistValue: "${key}" is not a valid persist target`,
101
101
  );
102
102
  }
103
- if (target.scope === "segment-palette") return raw;
103
+ // [LAW:one-type-per-behavior] Both non-globals scopes are always a NAME/
104
+ // TOKEN string — segment-palette's value is a palette name, preset-root-ops'
105
+ // is one op token appended by the daemon's apply-layout-op verb handler
106
+ // (never a bare `persist` write — see verbs/index.ts). Neither has a
107
+ // GLOBALS_FIELD_KIND row because neither is a Globals field.
108
+ if (
109
+ target.scope === "segment-palette" ||
110
+ target.scope === "preset-root-ops"
111
+ ) {
112
+ return raw;
113
+ }
104
114
  const kind = GLOBALS_FIELD_KIND[target.field];
105
115
  if (kind === "string") return raw;
106
116
  if (kind === "number") {
@@ -136,9 +146,7 @@ function isValidOverrides(
136
146
  const target = parsePersistTarget(key);
137
147
  if (target === null) return false;
138
148
  const kind =
139
- target.scope === "segment-palette"
140
- ? "string"
141
- : GLOBALS_FIELD_KIND[target.field];
149
+ target.scope === "globals" ? GLOBALS_FIELD_KIND[target.field] : "string";
142
150
  if (kind === "number" && typeof v !== "number") return false;
143
151
  if (kind === "boolean" && typeof v !== "boolean") return false;
144
152
  if (kind === "string" && typeof v !== "string") return false;
@@ -237,6 +245,46 @@ function projectSegmentPaletteOverrides(
237
245
  return out;
238
246
  }
239
247
 
248
+ // [LAW:one-source-of-truth] The preset-root-ops-scoped VIEW of the SAME raw
249
+ // dict — preset name -> the accumulated op-token LIST (brandon-layout-edit-
250
+ // 2gc.1's structural-edit log; see src/config/layout-ops.ts). This is a
251
+ // SHAPE check only (well-formed JSON array of strings) — decoding each
252
+ // token into a typed LayoutOp, and applying the ops to a tree, is presets.ts's
253
+ // job, not this storage-layer module's [LAW:decomposition]. A stored value
254
+ // that isn't a JSON array of strings drops for THAT preset only (a warn log,
255
+ // never a crash of the whole overrides file) — the identical "the world
256
+ // moved on since this was written" recovery projectSegmentPaletteOverrides
257
+ // already gets, one level narrower.
258
+ function projectPresetRootOpsOverrides(
259
+ raw: Readonly<Record<string, string | number | boolean>>,
260
+ logger: DaemonLogger,
261
+ ): Readonly<Record<string, readonly string[]>> {
262
+ const out: Record<string, readonly string[]> = Object.create(null) as Record<
263
+ string,
264
+ readonly string[]
265
+ >;
266
+ for (const [key, value] of Object.entries(raw)) {
267
+ const target = parsePersistTarget(key);
268
+ if (target?.scope !== "preset-root-ops" || typeof value !== "string") {
269
+ continue;
270
+ }
271
+ try {
272
+ const parsed: unknown = JSON.parse(value);
273
+ if (Array.isArray(parsed) && parsed.every((t) => typeof t === "string")) {
274
+ out[target.preset] = parsed;
275
+ continue;
276
+ }
277
+ } catch {
278
+ // fall through to the warn below
279
+ }
280
+ logger(
281
+ "warn",
282
+ `config-overrides: "${key}" is not a valid op-token list, dropping`,
283
+ );
284
+ }
285
+ return out;
286
+ }
287
+
240
288
  export function loadConfigOverrides(
241
289
  filePath: string,
242
290
  logger: DaemonLogger = quietLogger,
@@ -251,14 +299,15 @@ export function loadSegmentPaletteOverrides(
251
299
  return projectSegmentPaletteOverrides(loadRawOverrides(filePath, logger));
252
300
  }
253
301
 
254
- // [LAW:carrying-cost] RenderCache wants BOTH views on every reload
255
- // (buildState merges globals overrides, then overlays segment-palette
256
- // overrides) — calling loadConfigOverrides + loadSegmentPaletteOverrides
257
- // back to back would read, parse, and shape-validate the same tiny file
258
- // twice per reload for no reason. One read, two projections.
302
+ // [LAW:carrying-cost] RenderCache wants ALL THREE views on every reload
303
+ // (buildState merges globals overrides, overlays segment-palette overrides,
304
+ // then replays preset-root-ops overrides) — calling the scoped loaders back
305
+ // to back would read, parse, and shape-validate the same tiny file three
306
+ // times per reload for no reason. One read, three projections.
259
307
  export interface Overrides {
260
308
  readonly globals: Partial<Globals>;
261
309
  readonly segmentPalette: Readonly<Record<string, string>>;
310
+ readonly presetRootOps: Readonly<Record<string, readonly string[]>>;
262
311
  }
263
312
 
264
313
  export function loadOverrides(
@@ -269,46 +318,98 @@ export function loadOverrides(
269
318
  return {
270
319
  globals: projectGlobalsOverrides(raw),
271
320
  segmentPalette: projectSegmentPaletteOverrides(raw),
321
+ presetRootOps: projectPresetRootOpsOverrides(raw, logger),
272
322
  };
273
323
  }
274
324
 
275
- // [LAW:no-silent-failure] Atomic write shared by set/clear: read the current
276
- // overrides, apply one mutation, write-to-temp + rename. Owner-only mode,
277
- // matching every other daemon runtime file (session-state.json, pid, lease).
325
+ // [LAW:no-silent-failure] The atomic write/rename dance, generalized over ANY
326
+ // JSON-serializable value both this module's flat overrides dict and its
327
+ // history stack (below) go through this one primitive rather than each
328
+ // re-implementing mkdir+tmp+chmod+rename. Owner-only mode, matching every
329
+ // other daemon runtime file (session-state.json, pid, lease). `label` names
330
+ // the failure in the log/thrown message (the caller's own vocabulary —
331
+ // "config-overrides"/"config-overrides-history" — not derived from the path,
332
+ // so the wording a test might match on stays stable across either file).
278
333
  // Unlike session-state.json's debounced best-effort flush (no synchronous
279
- // caller waiting on it), a `persist` write is directly caused by a click that
280
- // expects a truthful ack — a swallowed failure here would let the verb
281
- // handler log "set-config: ..." as if it landed when nothing was written.
282
- // Logs at "error" for the daemon-log breadcrumb, then RETHROWS so the caller
283
- // (the click) fails loudly instead of claiming a success that didn't happen.
284
- function writeOverrides(
334
+ // caller waiting on it), a `persist`/`undo`/`redo` write is directly caused
335
+ // by a click that expects a truthful ack — a swallowed failure here would let
336
+ // the verb handler log success for a write that didn't land. Logs at "error"
337
+ // for the daemon-log breadcrumb, then RETHROWS so the caller (the click)
338
+ // fails loudly instead of claiming a success that didn't happen.
339
+ function writeJsonAtomic(
285
340
  filePath: string,
286
- overrides: Readonly<Record<string, string | number | boolean>>,
341
+ label: string,
342
+ value: unknown,
287
343
  logger: DaemonLogger,
288
344
  ): void {
289
345
  try {
290
346
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
291
347
  const tmp = `${filePath}.tmp`;
292
- fs.writeFileSync(tmp, JSON.stringify(overrides), { mode: 0o600 });
348
+ fs.writeFileSync(tmp, JSON.stringify(value), { mode: 0o600 });
293
349
  fs.chmodSync(tmp, 0o600);
294
350
  fs.renameSync(tmp, filePath);
295
351
  } catch (e) {
296
- const message = `config-overrides write failed: ${(e as Error).message}`;
352
+ const message = `${label} write failed: ${(e as Error).message}`;
297
353
  logger("error", message);
298
354
  throw new Error(message);
299
355
  }
300
356
  }
301
357
 
358
+ function writeOverrides(
359
+ filePath: string,
360
+ overrides: Readonly<Record<string, string | number | boolean>>,
361
+ logger: DaemonLogger,
362
+ ): void {
363
+ writeJsonAtomic(filePath, "config-overrides", overrides, logger);
364
+ }
365
+
366
+ // [LAW:one-source-of-truth] The one place a key's value in the flat dict
367
+ // changes (set-or-delete) — writeConfigOverride/clearConfigOverride/
368
+ // restoreConfigOverrideValue all fold through here, so "what was the value
369
+ // BEFORE this write" (the fact history needs) is captured at the one site
370
+ // that reads-then-writes it, never re-derived. `value: undefined` deletes;
371
+ // any other value sets. Returns the previous value (or undefined if the key
372
+ // was absent) — the caller decides whether that fact matters.
373
+ function mutateOverride(
374
+ filePath: string,
375
+ key: string,
376
+ value: string | number | boolean | undefined,
377
+ logger: DaemonLogger,
378
+ ): string | number | boolean | undefined {
379
+ const overrides = loadRawOverrides(filePath, logger);
380
+ const prev = overrides[key];
381
+ if (value === undefined) {
382
+ if (!(key in overrides)) return prev;
383
+ const next = { ...overrides };
384
+ delete next[key];
385
+ writeOverrides(filePath, next, logger);
386
+ } else {
387
+ writeOverrides(filePath, { ...overrides, [key]: value }, logger);
388
+ }
389
+ return prev;
390
+ }
391
+
392
+ // [LAW:one-source-of-truth] `persist`'s write, TRACKED: mutate the key, then
393
+ // record the transition on the SAME global history undo/redo step
394
+ // (brandon-layout-edit-2gc.2). This is the ONE enforcement point — every
395
+ // current and future caller of writeConfigOverride (setConfig, stepConfig,
396
+ // apply-layout-op's append) gets history for free, with zero edits to those
397
+ // verb handlers, because the recording lives here rather than at each call
398
+ // site. [LAW:locality-or-seam]
302
399
  export function writeConfigOverride(
303
400
  filePath: string,
304
401
  key: string,
305
402
  value: string | number | boolean,
306
403
  logger: DaemonLogger = quietLogger,
307
404
  ): void {
308
- const overrides = loadRawOverrides(filePath, logger);
309
- writeOverrides(filePath, { ...overrides, [key]: value }, logger);
405
+ const prev = mutateOverride(filePath, key, value, logger);
406
+ pushHistoryEntry(filePath, { key, from: prev ?? null, to: value }, logger);
310
407
  }
311
408
 
409
+ // [LAW:one-source-of-truth] `reset`'s write, TRACKED — mirrors
410
+ // writeConfigOverride above. A clear that touches nothing (the key was
411
+ // already absent) records no entry: nothing changed, so there is nothing to
412
+ // undo back to.
312
413
  export function clearConfigOverride(
313
414
  filePath: string,
314
415
  key: string,
@@ -316,7 +417,247 @@ export function clearConfigOverride(
316
417
  ): void {
317
418
  const overrides = loadRawOverrides(filePath, logger);
318
419
  if (!(key in overrides)) return;
319
- const next = { ...overrides };
320
- delete next[key];
321
- writeOverrides(filePath, next, logger);
420
+ const prev = mutateOverride(filePath, key, undefined, logger);
421
+ pushHistoryEntry(filePath, { key, from: prev ?? null, to: null }, logger);
422
+ }
423
+
424
+ // [LAW:one-source-of-truth] The UNTRACKED twin — restores a key to EXACTLY
425
+ // `value` (or clears it, for `null`) without recording a new history entry.
426
+ // The only legitimate callers are popPastEntry/popFutureEntry below: undo and
427
+ // redo already know they're moving an entry between the past/future stacks,
428
+ // so routing their own restoration back through the tracked writers would
429
+ // record the undo/redo AS a new forward edit — burying the entry it just
430
+ // popped and making the OTHER stack unreachable. This is a structurally
431
+ // distinct function, not a boolean flag on the tracked ones
432
+ // [LAW:no-mode-explosion] — its contract ("apply this exact value, no
433
+ // bookkeeping") is different from theirs ("write this value, remember how to
434
+ // undo it"), not a variant of the same one.
435
+ function restoreConfigOverrideValue(
436
+ filePath: string,
437
+ key: string,
438
+ value: string | number | boolean | null,
439
+ logger: DaemonLogger,
440
+ ): void {
441
+ mutateOverride(filePath, key, value === null ? undefined : value, logger);
442
+ }
443
+
444
+ // ─── Undo/redo history (brandon-layout-edit-2gc.2) ────────────────────────
445
+
446
+ // [LAW:types-are-the-program] ONE entry shape covers every scope the
447
+ // overrides file holds — a globals field's snapshot overwrite (setConfig), a
448
+ // segment-palette snapshot overwrite (same verb, different key shape), AND a
449
+ // preset-root-ops APPEND (apply-layout-op's read-current-append-write) —
450
+ // because at the STORAGE layer every one of those is indistinguishable from
451
+ // "the value at `key` changed from `from` to `to`". apply-layout-op computes
452
+ // its new array-of-tokens string by reading-then-appending one level up
453
+ // (verbs/index.ts); by the time that string reaches writeConfigOverride, it
454
+ // is just the next value at that key. Undo restoring `from` verbatim is
455
+ // therefore ALSO the correct "pop the last op token" behavior for a rootOps
456
+ // key, with no rootOps-specific code anywhere in this module — the ticket's
457
+ // "one history over the overrides layer, not a layout-specific feature" falls
458
+ // out of the shape, it isn't special-cased into it. `null` is the ABSENT
459
+ // sentinel (a key with no prior/no resulting value): safe because no real
460
+ // override value is ever `null` — see isValidOverrides's kind table.
461
+ export interface HistoryEntry {
462
+ readonly key: string;
463
+ readonly from: string | number | boolean | null;
464
+ readonly to: string | number | boolean | null;
465
+ }
466
+
467
+ interface HistoryState {
468
+ readonly past: readonly HistoryEntry[];
469
+ readonly future: readonly HistoryEntry[];
470
+ }
471
+
472
+ const EMPTY_HISTORY: HistoryState = { past: [], future: [] };
473
+
474
+ // [LAW:carrying-cost] Resolves the ticket's "depth of the ring" question:
475
+ // bounded so a long-running daemon's history file cannot grow without limit,
476
+ // generous enough that no realistic editing session bumps into it. Oldest
477
+ // entries fall off first (capPush below) — a silent, documented trim, not a
478
+ // failure.
479
+ const MAX_HISTORY_DEPTH = 50;
480
+
481
+ // [LAW:one-source-of-truth] Resolves the ticket's "where it lives relative to
482
+ // the overrides file" question: a SIBLING file in the same directory, derived
483
+ // as a pure function of the overrides path already passed in — no reach to
484
+ // paths.ts/global state, so every existing call site (and every existing
485
+ // test's XDG_STATE_HOME isolation, which already isolates configOverridesPath())
486
+ // isolates this file too, with zero additional test-harness surface. Kept
487
+ // SEPARATE from the overrides file itself (rather than nesting it inside a
488
+ // wrapper shape) so the overrides file's own on-disk shape — asserted by
489
+ // name in existing tests and callers — never changes
490
+ // [LAW:locality-or-seam]: a change to history storage must not ripple into
491
+ // every existing reader of the flat overrides dict.
492
+ function historyPathFor(overridesFilePath: string): string {
493
+ return path.join(
494
+ path.dirname(overridesFilePath),
495
+ "config-overrides-history.json",
496
+ );
497
+ }
498
+
499
+ function isValidHistoryValue(
500
+ v: unknown,
501
+ ): v is string | number | boolean | null {
502
+ return (
503
+ v === null ||
504
+ typeof v === "string" ||
505
+ typeof v === "number" ||
506
+ typeof v === "boolean"
507
+ );
508
+ }
509
+
510
+ function isValidHistoryEntry(v: unknown): v is HistoryEntry {
511
+ if (v === null || typeof v !== "object") return false;
512
+ const obj = v as Record<string, unknown>;
513
+ return (
514
+ typeof obj.key === "string" &&
515
+ isValidHistoryValue(obj.from) &&
516
+ isValidHistoryValue(obj.to)
517
+ );
518
+ }
519
+
520
+ // [LAW:no-silent-failure] Missing/corrupt/wrong-shape file → the empty
521
+ // history is the DEFINED recovery (mirrors isValidOverrides/loadRawOverrides'
522
+ // identical "first-ever boot" treatment for the sibling file) — a single
523
+ // malformed entry drops the WHOLE history, never a guess at which entries to
524
+ // salvage.
525
+ function isValidHistoryState(v: unknown): v is HistoryState {
526
+ if (v === null || typeof v !== "object" || Array.isArray(v)) return false;
527
+ const obj = v as Record<string, unknown>;
528
+ return (
529
+ Array.isArray(obj.past) &&
530
+ obj.past.every(isValidHistoryEntry) &&
531
+ Array.isArray(obj.future) &&
532
+ obj.future.every(isValidHistoryEntry)
533
+ );
534
+ }
535
+
536
+ function loadHistoryState(
537
+ overridesFilePath: string,
538
+ logger: DaemonLogger,
539
+ ): HistoryState {
540
+ const filePath = historyPathFor(overridesFilePath);
541
+ let raw: string;
542
+ try {
543
+ raw = fs.readFileSync(filePath, "utf8");
544
+ } catch (e) {
545
+ const code = (e as NodeJS.ErrnoException).code;
546
+ if (code !== "ENOENT") {
547
+ logger(
548
+ "warn",
549
+ `config-overrides-history read failed (${code}); starting empty`,
550
+ );
551
+ }
552
+ return EMPTY_HISTORY;
553
+ }
554
+ try {
555
+ const parsed: unknown = JSON.parse(raw);
556
+ if (isValidHistoryState(parsed)) return parsed;
557
+ logger(
558
+ "warn",
559
+ `config-overrides-history load: unexpected shape, starting empty`,
560
+ );
561
+ return EMPTY_HISTORY;
562
+ } catch {
563
+ logger(
564
+ "warn",
565
+ `config-overrides-history load: corrupt JSON, starting empty`,
566
+ );
567
+ return EMPTY_HISTORY;
568
+ }
569
+ }
570
+
571
+ function writeHistoryState(
572
+ overridesFilePath: string,
573
+ state: HistoryState,
574
+ logger: DaemonLogger,
575
+ ): void {
576
+ writeJsonAtomic(
577
+ historyPathFor(overridesFilePath),
578
+ "config-overrides-history",
579
+ state,
580
+ logger,
581
+ );
582
+ }
583
+
584
+ // [LAW:no-mode-explosion] Bounded push, oldest-drops-first, shared by both
585
+ // stacks (past grows on a fresh edit or a redo; future grows on an undo) —
586
+ // one shape, not two near-duplicate arms.
587
+ function capPush<T>(arr: readonly T[], entry: T, max: number): readonly T[] {
588
+ const next = [...arr, entry];
589
+ return next.length > max ? next.slice(next.length - max) : next;
590
+ }
591
+
592
+ // [LAW:one-source-of-truth] The ONLY caller is writeConfigOverride/
593
+ // clearConfigOverride above — every tracked write lands here, so recording
594
+ // cannot drift from mutation. A fresh edit TRUNCATES `future`: the classic
595
+ // undo/redo branch — diverging from history by doing something NEW abandons
596
+ // whatever was undone, rather than silently keeping it reachable from a
597
+ // history state the new edit has already invalidated.
598
+ function pushHistoryEntry(
599
+ overridesFilePath: string,
600
+ entry: HistoryEntry,
601
+ logger: DaemonLogger,
602
+ ): void {
603
+ const state = loadHistoryState(overridesFilePath, logger);
604
+ writeHistoryState(
605
+ overridesFilePath,
606
+ { past: capPush(state.past, entry, MAX_HISTORY_DEPTH), future: [] },
607
+ logger,
608
+ );
609
+ }
610
+
611
+ // [LAW:one-source-of-truth] The daemon-GLOBAL history is ONE stack, not
612
+ // per-session: config-overrides.json already has exactly one writer (the
613
+ // daemon) and no session-scoping (candybar-config-engine-71o's own binding
614
+ // guardrail — a `persist` write is daemon-global by design), so undo/redo
615
+ // stepping that SAME single-writer file inherits the same scope rather than
616
+ // inventing a session axis the storage layer doesn't otherwise have. Two
617
+ // sessions clicking undo do see each other's edits — a real, DELIBERATE
618
+ // consequence of there being one bar default, not a bug: the alternative
619
+ // (per-session history over daemon-global state) would let one session's
620
+ // "undo" silently fail to undo what another session's click actually did.
621
+ //
622
+ // [LAW:no-silent-failure] Returns `null` at the bottom of the stack — the
623
+ // verb handler (verbs/index.ts) turns that into a loud BadVerbArgs surfaced
624
+ // through click.error, never a silent no-op.
625
+ export function undoLastOverride(
626
+ overridesFilePath: string,
627
+ logger: DaemonLogger = quietLogger,
628
+ ): HistoryEntry | null {
629
+ const state = loadHistoryState(overridesFilePath, logger);
630
+ const entry = state.past[state.past.length - 1];
631
+ if (entry === undefined) return null;
632
+ restoreConfigOverrideValue(overridesFilePath, entry.key, entry.from, logger);
633
+ writeHistoryState(
634
+ overridesFilePath,
635
+ {
636
+ past: state.past.slice(0, -1),
637
+ future: capPush(state.future, entry, MAX_HISTORY_DEPTH),
638
+ },
639
+ logger,
640
+ );
641
+ return entry;
642
+ }
643
+
644
+ // [LAW:no-silent-failure] Redo's mirror of undo above — `null` at the top of
645
+ // the stack, same loud surfacing contract.
646
+ export function redoLastOverride(
647
+ overridesFilePath: string,
648
+ logger: DaemonLogger = quietLogger,
649
+ ): HistoryEntry | null {
650
+ const state = loadHistoryState(overridesFilePath, logger);
651
+ const entry = state.future[state.future.length - 1];
652
+ if (entry === undefined) return null;
653
+ restoreConfigOverrideValue(overridesFilePath, entry.key, entry.to, logger);
654
+ writeHistoryState(
655
+ overridesFilePath,
656
+ {
657
+ past: capPush(state.past, entry, MAX_HISTORY_DEPTH),
658
+ future: state.future.slice(0, -1),
659
+ },
660
+ logger,
661
+ );
662
+ return entry;
322
663
  }
@@ -17,6 +17,7 @@ import {
17
17
  } from "../../config/option-domain";
18
18
  import type { DslConfig } from "../../config/dsl-types";
19
19
  import { isGlobalsField } from "../config-overrides-store";
20
+ import { encodeLayoutOp } from "../../config/layout-ops";
20
21
  import {
21
22
  clampSeed,
22
23
  createValidatorRegistry,
@@ -73,6 +74,43 @@ function actionKeySpecs(
73
74
  if ("cycle" in a) {
74
75
  return [{ key: a.persist, spec: { kind: "allow-list", allowed: a.cycle } }];
75
76
  }
77
+ // [LAW:single-enforcer] brandon-layout-edit-2gc.1's structural-edit arms:
78
+ // the op is fully literal at config-author time (removeSegment's target,
79
+ // insertSegment's segment/anchor/relation), so — exactly like a literal
80
+ // `to` — there is exactly ONE legal value this declared action can ever
81
+ // request: its own encoded op token. Multiple layout actions targeting the
82
+ // same "presets.<name>.rootOps" key each contribute one allow-list member,
83
+ // unioned by mergeContributions below, same as multiple `to` actions on
84
+ // one key already do.
85
+ if ("removeSegment" in a) {
86
+ return [
87
+ {
88
+ key: a.persist,
89
+ spec: {
90
+ kind: "allow-list",
91
+ allowed: [encodeLayoutOp({ op: "remove", target: a.removeSegment })],
92
+ },
93
+ },
94
+ ];
95
+ }
96
+ if ("insertSegment" in a) {
97
+ return [
98
+ {
99
+ key: a.persist,
100
+ spec: {
101
+ kind: "allow-list",
102
+ allowed: [
103
+ encodeLayoutOp({
104
+ op: "insert",
105
+ segment: a.insertSegment,
106
+ anchor: a.anchor,
107
+ relation: a.relation,
108
+ }),
109
+ ],
110
+ },
111
+ },
112
+ ];
113
+ }
76
114
  return [
77
115
  {
78
116
  key: a.persist,
@@ -36,16 +36,22 @@ import {
36
36
  coercePersistValue,
37
37
  isGlobalsField,
38
38
  loadConfigOverrides,
39
+ loadOverrides,
40
+ redoLastOverride,
41
+ undoLastOverride,
39
42
  writeConfigOverride,
40
43
  } from "../config-overrides-store";
41
44
  import { configOverridesPath } from "../paths";
45
+ import { parsePersistTarget } from "../../config/loader/persist-target";
42
46
  import {
43
47
  decodeSegments,
44
48
  parseEffects,
49
+ VERB_APPLY_LAYOUT_OP,
45
50
  VERB_COPY,
46
51
  VERB_DISPATCH,
47
52
  VERB_OPEN_VSCODE,
48
53
  VERB_LOAD_CONFIG,
54
+ VERB_REDO,
49
55
  VERB_RESET_CONFIG,
50
56
  VERB_SET_CONFIG,
51
57
  VERB_SET_STATE,
@@ -54,6 +60,7 @@ import {
54
60
  VERB_SHOW_CONFIG_ERROR,
55
61
  VERB_SHOW_CONFIG_WARNING,
56
62
  VERB_TOOLBAR_TOGGLE,
63
+ VERB_UNDO,
57
64
  } from "../../click/wire";
58
65
 
59
66
  export interface VerbContext {
@@ -444,6 +451,77 @@ const resetConfig: VerbHandler = (value, ctx) => {
444
451
  ctx.dlog("info", `reset-config: ${key} (session=${sid})`);
445
452
  };
446
453
 
454
+ // [LAW:one-source-of-truth] brandon-layout-edit-2gc.1's structural-edit
455
+ // write: a THIRD config-overrides write shape beside setConfig's overwrite
456
+ // and stepConfig's numeric read-modify-write — read the current op-token
457
+ // list at `key`, append the validated op, write the whole list back. Gated
458
+ // by the SAME allow-list machinery setConfig uses (validateConfigWrite,
459
+ // derived from a config's declared removeSegment/insertSegment actions) —
460
+ // an op token no action declares is a loud BAD_REQUEST, never silently
461
+ // appended. `key` must resolve to the preset-root-ops scope specifically
462
+ // (never a globals/segment-palette key smuggled in through this verb) —
463
+ // checked here rather than trusted from the gate, since the gate only
464
+ // proves the VALUE is allowed for that key, not that the key's SCOPE
465
+ // matches this verb's read-modify-write shape.
466
+ const applyLayoutOp: VerbHandler = (rawValue, ctx) => {
467
+ const [sessionId = "", key = "", opToken = ""] = decodeWire(() =>
468
+ decodeSegments(rawValue),
469
+ );
470
+ const sid = requireSessionId(sessionId);
471
+ if (!key) {
472
+ throw new BadVerbArgs(
473
+ `apply-layout-op: <key>/<op> is required (have: ${listConfigKeys().join(", ")})`,
474
+ );
475
+ }
476
+ const result = validateConfigWrite(key, opToken);
477
+ if (!result.ok) throw new BadVerbArgs(`apply-layout-op: ${result.reason}`);
478
+ const target = parsePersistTarget(key);
479
+ if (target === null || target.scope !== "preset-root-ops") {
480
+ throw new BadVerbArgs(
481
+ `apply-layout-op: "${key}" is not a "presets.<name>.rootOps" target`,
482
+ );
483
+ }
484
+ const existing =
485
+ loadOverrides(configOverridesPath(), ctx.dlog).presetRootOps[
486
+ target.preset
487
+ ] ?? [];
488
+ const next = JSON.stringify([...existing, result.value]);
489
+ writeConfigOverride(configOverridesPath(), key, next, ctx.dlog);
490
+ ctx.dlog(
491
+ "info",
492
+ `apply-layout-op: ${key} += ${result.value} (session=${sid})`,
493
+ );
494
+ };
495
+
496
+ // [LAW:one-source-of-truth] `reset`'s fine-grained sibling: step the ONE
497
+ // global history over the overrides layer back one entry. No key, no value —
498
+ // the history store (config-overrides-store.ts) owns which entry moves and
499
+ // what it restores; this handler is pure plumbing between the wire and it.
500
+ // [LAW:no-silent-failure] An empty stack is a loud BAD_REQUEST (dispatch's
501
+ // aggregator turns it into a transient click.error), never a silent no-op —
502
+ // the ticket's own done-gate.
503
+ const undoConfig: VerbHandler = (value, ctx) => {
504
+ const [sessionId = ""] = decodeWire(() => decodeSegments(value));
505
+ const sid = requireSessionId(sessionId);
506
+ const entry = undoLastOverride(configOverridesPath(), ctx.dlog);
507
+ if (entry === null) {
508
+ throw new BadVerbArgs("undo: history is empty, nothing to undo");
509
+ }
510
+ ctx.dlog("info", `undo: ${entry.key} (session=${sid})`);
511
+ };
512
+
513
+ // [LAW:one-source-of-truth] undo's mirror — steps the same global history
514
+ // forward one entry.
515
+ const redoConfig: VerbHandler = (value, ctx) => {
516
+ const [sessionId = ""] = decodeWire(() => decodeSegments(value));
517
+ const sid = requireSessionId(sessionId);
518
+ const entry = redoLastOverride(configOverridesPath(), ctx.dlog);
519
+ if (entry === null) {
520
+ throw new BadVerbArgs("redo: nothing to redo");
521
+ }
522
+ ctx.dlog("info", `redo: ${entry.key} (session=${sid})`);
523
+ };
524
+
447
525
  // ─── Registry ───────────────────────────────────────────────────────────────
448
526
 
449
527
  // [LAW:one-source-of-truth] The LEAF verbs — every click effect that does real
@@ -505,6 +583,9 @@ const LEAF_VERBS = new Map<string, VerbHandler>([
505
583
  [VERB_SET_CONFIG, setConfig],
506
584
  [VERB_STEP_CONFIG, stepConfig],
507
585
  [VERB_RESET_CONFIG, resetConfig],
586
+ [VERB_APPLY_LAYOUT_OP, applyLayoutOp],
587
+ [VERB_UNDO, undoConfig],
588
+ [VERB_REDO, redoConfig],
508
589
  [VERB_SHOW_CONFIG_ERROR, showConfigError],
509
590
  [VERB_SHOW_CONFIG_WARNING, showConfigWarning],
510
591
  [VERB_TOOLBAR_TOGGLE, toolbarToggle],
@@ -536,9 +617,10 @@ const dispatch: VerbHandler = (rawValue, ctx) => {
536
617
  let sessionId: string | null = null;
537
618
  for (const { verb, value } of parseEffects(rawValue)) {
538
619
  // Extract session ID from the first session-bearing effect for error display.
539
- // set-state, step-state, set-config, step-config, reset-config, and
540
- // toolbar-toggle all carry the session id as their first segment, so a
541
- // failing step surfaces in the bar like any other.
620
+ // set-state, step-state, set-config, step-config, reset-config,
621
+ // apply-layout-op, undo, redo, and toolbar-toggle all carry the session id
622
+ // as their first segment, so a failing step surfaces in the bar like any
623
+ // other.
542
624
  if (
543
625
  !sessionId &&
544
626
  (verb === VERB_SET_STATE ||
@@ -546,6 +628,9 @@ const dispatch: VerbHandler = (rawValue, ctx) => {
546
628
  verb === VERB_SET_CONFIG ||
547
629
  verb === VERB_STEP_CONFIG ||
548
630
  verb === VERB_RESET_CONFIG ||
631
+ verb === VERB_APPLY_LAYOUT_OP ||
632
+ verb === VERB_UNDO ||
633
+ verb === VERB_REDO ||
549
634
  verb === VERB_TOOLBAR_TOGGLE)
550
635
  ) {
551
636
  const parts = decodeSegments(value);