Repository navigation
Expand file tree
/
Copy pathconfig.ts
More file actions
1279 lines (1183 loc) · 89.2 KB
/
Copy pathconfig.ts
File metadata and controls
1279 lines (1183 loc) · 89.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as path from 'node:path'
import { parse, stringify } from 'smol-toml'
import { KNOWN_HARNESS_NAMES } from './bridges/registry.js'
import { configPath, projectConfigPath } from './constants.js'
import { envBool, envInt, envStr, envStrList, TRUTHY_ENV_VALUES, FALSY_ENV_VALUES } from './env.js'
import { shortFingerprint } from './fingerprint.js'
import { SUPPORTED_OCR_LANG_CODES, isSupportedOcrLang } from './ocr_languages.js'
import { ownGet } from './own_lookup.js'
import { atomicWriteText, extractErrorMessage } from './util.js'
import { registerReset } from './reset.js'
import { COMPRESSION_PROFILE_SETTINGS } from './config_types.js'
export * from './config_types.js'
export * from './config_defaults.js'
export * from './config_project.js'
import type {
Config,
VisionTier,
NativeHooksMode,
ProjectConfigInfo,
ConfigKeyLayer,
CompactAssistConfig,
BashCompressConfig,
AgentReportConfig,
SkillPreservationConfig,
ImageShrinkConfig,
HintsConfig,
WorkerConfig,
RepomapConfig,
OverflowGuardConfig,
HooksConfig,
WebFetchConfig,
IndexingConfig,
CompressionConfig,
ContextConfig,
InjectionConfig,
GdriveConfig,
RedactionConfig,
NetworkConfig,
McpConfig,
HintStatsConfig,
SemanticConfig,
ScreenshotConfig,
BashDiffConfig,
SeverityLogConfig,
CodeCompressConfig,
SessionBriefConfig,
} from './config_types.js'
import { getDefaultConfig } from './config_defaults.js'
import {
stripLockedProjectKeys,
setLastProjectConfigLockedKeys,
resetLastProjectConfigLockedKeys,
readConfigToml,
readConfigText,
mergeRawConfig,
resolveConfigProjectRoot,
isAutoTriggerMultiplierExplicit,
PROJECT_LOCKED_SECTIONS,
PROJECT_LOCKED_KEYS,
} from './config_project.js'
import { echoedValue } from './hint_suggestion_guard.js'
// --------------------------------------------------------------------------- Helpers ---------------------------------------------------------------------------
function validatedBool(raw: unknown, def: boolean): boolean {
if (typeof raw === 'boolean') return raw
return def
}
function validatedInt(raw: unknown, def: number, min: number, max: number): number {
const n = typeof raw === 'number' ? Math.trunc(raw) : def
if (!Number.isFinite(n)) return def
return Math.max(min, Math.min(max, n))
}
function validatedFloat(raw: unknown, def: number, min: number, max: number): number {
const n = typeof raw === 'number' ? raw : def
if (!Number.isFinite(n)) return def
return Math.max(min, Math.min(max, n))
}
/** Accept only the two tier names. An unknown string is a typo or a stale config, and silently pricing every image on the wrong tier is worse than ignoring the key, so this falls back to the default rather than guessing which one was meant. */
function validatedVisionTier(raw: unknown, def: VisionTier): VisionTier {
return raw === 'standard' || raw === 'high' ? raw : def
}
/** Accept only a value listed for `key` in {@link ENUM_FIELD_VALUES}, exactly as written, falling back to the default for anything else, as {@link validatedVisionTier} does. The one table `config set` checks, so the loader, `config validate` and `config get` agree on what a value means. */
function validatedEnum<T extends string>(key: string, raw: unknown, def: T): T {
return typeof raw === 'string' && (ENUM_FIELD_VALUES[key] ?? []).includes(raw) ? (raw as T) : def
}
/** The environment's reading of an enum key: the variable's exact value if {@link validatedEnum} accepts it, else `def`. */
function envEnum<T extends string>(key: string, name: string, def: T): T {
return validatedEnum(key, process.env[name], def)
}
/** Accept only the two modes, falling back to the default for anything else, as {@link validatedVisionTier} does. */
function validatedNativeHooksMode(raw: unknown, def: NativeHooksMode): NativeHooksMode {
return raw === 'auto' || raw === 'off' ? raw : def
}
/** The mode TOKEN_GOAT_NATIVE_HOOKS sets: its value is a boolean spelling (env.ts), a false one meaning `off` and a true one `auto`; anything else, empty included, sets nothing. The one reading of the variable, shared by the loader, {@link nativeHooksEnabled} and `config validate` (through ENV_VALUE_COERCERS), so none of them can disagree about what a value means. */
function nativeHooksModeFromEnv(raw: string | undefined): NativeHooksMode | undefined {
const norm = raw?.trim().toLowerCase() ?? ''
if (TRUTHY_ENV_VALUES.has(norm)) return 'auto'
if (FALSY_ENV_VALUES.has(norm)) return 'off'
return undefined
}
/** Keys whose environment variable is not spelled like the value it sets, with the reading that turns one into the other. resolveConfigKeyLayer asks here before its type-based coercion, which would compare the raw `0` against `off` and call a working variable unusable. */
const ENV_VALUE_COERCERS: Readonly<Record<string, (raw: string) => unknown>> = {
'hooks.native': nativeHooksModeFromEnv,
}
function validatedOcrLang(raw: unknown, def: string): string {
if (typeof raw !== 'string') return def
const tokens = raw.split(/[+,;\s]+/).map((s) => s.trim().toLowerCase()).filter(Boolean)
const valid = tokens.filter((t) => isSupportedOcrLang(t))
return valid.length > 0 ? valid.join('+') : def
}
function validatedStr(raw: unknown, def: string): string {
return typeof raw === 'string' ? raw : def
}
function validatedStrList(raw: unknown, def: string[]): string[] {
if (!Array.isArray(raw)) return def
return raw.filter((x): x is string => typeof x === 'string')
}
function validatedIntList(raw: unknown, def: number[]): number[] {
if (!Array.isArray(raw)) return def
return raw.filter((x): x is number => typeof x === 'number' && Number.isFinite(x)).map(Math.trunc)
}
/** Like {@link validatedInt}, but a persisted value exactly equal to `sentinel` is treated as the stale pre-rewire default (see the three "Legacy-sentinel guard" call sites below) and falls through to `def` instead of being trusted, since a `config set` on any unrelated key used to resave every field including then-inert defaults that a later change wired up as a real gate. Any other persisted value, including one that happens to equal a *current* default, is validated and respected as-is. */
function validatedIntWithLegacySentinel(raw: unknown, def: number, sentinel: number, min: number, max: number): number {
return raw === sentinel ? def : validatedInt(raw, def, min, max)
}
function section(raw: Record<string, unknown>, key: string): Record<string, unknown> {
const val = raw[key]
return val !== null && typeof val === 'object' && !Array.isArray(val)
? (val as Record<string, unknown>)
: {}
}
// Numeric field bounds for targeted validation (config set on numbers). Extracted from _buildConfig.
const NUMERIC_FIELD_BOUNDS: Record<string, {min: number, max: number, clampTo?: string}> = {
'compact_assist.auto_trigger_multiplier': {min: 1.0, max: 10.0},
'compact_assist.max_manifest_chars': {min: 0, max: 16000},
'compact_assist.summary_budget_chars': {min: 0, max: 200_000},
'bash_compress.max_lines': {min: 50, max: 100_000},
'bash_compress.max_bytes': {min: 1024, max: 16 * 1024 * 1024},
'bash_compress.timeout_seconds': {min: 5, max: 7200},
'bash_compress.cache_min_bytes': {min: 0, max: 100 * 1024 * 1024},
'bash_compress.cache_max_file_count': {min: 1, max: 1_000_000},
'bash_compress.cache_max_bytes': {min: 1024, max: 4 * 1024 * 1024 * 1024},
'bash_compress.cache_max_bytes_per_output': {min: 1024, max: 4 * 1024 * 1024 * 1024, clampTo: 'bash_compress.cache_max_bytes'},
'bash_compress.min_net_savings_bytes': {min: 0, max: 1024 * 1024},
'agent_report.min_bytes': {min: 0, max: 100 * 1024 * 1024},
'agent_report.fence_collapse_min_lines': {min: 1, max: 100_000},
// Bounded below the min-lines floor's own minimum is NOT enforceable here (bounds are per-key), so the loader clamps keep_lines against min_lines after both are read -- see the clamp comment there.
'agent_report.fence_collapse_keep_lines': {min: 0, max: 100_000},
'bash_diff.max_hunks_per_file': {min: 1, max: 10000},
'bash_severity_log.context_lines': {min: 0, max: 100},
'bash_severity_log.score_threshold': {min: 0.0, max: 1.0},
'post_read_code_compress.min_lines': {min: 0, max: 1_000_000},
'skill_preservation.max_cache_bytes': {min: 64 * 1024, max: 512 * 1024 * 1024},
'skill_preservation.orphan_age_secs': {min: 1, max: 2_592_000},
'skill_preservation.truncation_budget_tokens': {min: 0, max: 8000},
'skill_preservation.compress_min_bytes': {min: 1024, max: 10 * 1024 * 1024},
'image_shrink.jpeg_quality': {min: 1, max: 100},
'image_shrink.max_image_pixels': {min: 0, max: 1_000_000_000},
'image_shrink.ocr_min_confidence': {min: 0, max: 100},
'repomap.compact_file_threshold': {min: 0, max: 100_000},
'overflow_guard.max_tokens': {min: 1000, max: 1_000_000},
'hints.min_file_lines_for_hint': {min: 0, max: 1_000_000},
'hints.bash_dedup_min_bytes': {min: 0, max: 100_000},
'hints.web_dedup_min_bytes': {min: 0, max: 100_000},
'hints.grep_dedup_min_matches': {min: 0, max: 100_000},
'hints.glob_dedup_min_matches': {min: 0, max: 100_000},
'hints.write_rewrite_min_lines': {min: 0, max: 1_000_000},
'hints.write_rewrite_unchanged_pct': {min: 0, max: 100},
'hints.git_hint_max_ms': {min: 0, max: 10000},
'hints.min_session_hint_savings_bytes': {min: 0, max: 1_000_000},
'hints.diff_hint_min_tokens_saved': {min: 0, max: 100_000},
'hints.large_read_redirect_bytes': {min: 0, max: 100_000_000},
'hints.first_read_symbol_bytes': {min: 0, max: 100_000_000},
'hints.reread_deny_min_bytes': {min: 0, max: 100_000_000},
'hints.truncated_read_min_lines': {min: 0, max: 1_000_000},
'hints.protect_recent_reads': {min: 0, max: 100},
'hints.cross_session_read_dedup_ttl_secs': {min: 1, max: 86400},
'hints.mcp_dedup_ttl_secs': {min: 1, max: 3600},
'hooks.latency_budget_ms': {min: 1, max: 600000},
'webfetch.max_file_count': {min: 0, max: 10_000_000},
'webfetch.max_bytes': {min: 0, max: 100 * 1024 * 1024 * 1024},
'webfetch.compress_min_bytes': {min: 1024, max: 10 * 1024 * 1024},
'worker.max_pool_workers': {min: 1, max: 8},
'worker.embed_threads': {min: 1, max: 16},
'indexing.large_file_symbol_only_kb': {min: 1, max: 1048576, clampTo: 'indexing.large_file_skip_kb'},
'indexing.large_file_skip_kb': {min: 1, max: 1048576},
'indexing.max_chunks_per_file': {min: 1, max: 1_000_000},
'indexing.max_db_size_mb': {min: 1, max: 100_000},
'context.model_window_tokens': {min: 10_000, max: 10_000_000},
'hint_stats.suppress_threshold_pct': {min: 0, max: 100},
'hint_stats.defiance_threshold_pct': {min: 0, max: 100},
'hint_stats.min_sample_size': {min: 1, max: 10000},
'semantic.archive_weight': {min: 0.05, max: 1},
'semantic.docs_weight': {min: 0.05, max: 1},
// Upper bound is DEFAULT_DISTANCE_THRESHOLD, not the metric's own ceiling of 2. An L2 distance between unit vectors cannot exceed 2, so 2 reads like 'admit everything' -- but this floor only ever narrows what searchSemantic already returned, and runSemantic lets that scan keep its own 1.2 bound (see the max_distance comment on SemanticConfig for why the scan is the wrong place for a relevance decision). Anything between 1.2 and 2 was therefore discarded inside the scan before the floor could see it: a user raising this to widen recall got the setting accepted, validated and persisted, and identical results, with no diagnostic able to say why. validatedFloat clamps rather than rejects, so an existing value above the new bound becomes 1.2 and behaves exactly as it already did. The lower bound is not 0: a floor of 0 admits only an exact vector match, which would disable the vector half entirely while `semantic` went on answering in the words it uses for a genuine absence.
'semantic.max_distance': {min: 0.05, max: 1.2},
// Same range as max_distance: both are L2 distances on the scan's own 1.2 ceiling, and a weak line above what the scan can return would never fire.
'semantic.weak_distance': {min: 0.05, max: 1.2},
}
/** Look up a field's [min, max] from NUMERIC_FIELD_BOUNDS for spreading into validatedInt/ validatedFloat/envInt -- _buildConfig's single source of truth for bounds, instead of restating each field's min/max a second time at its build-time validation call site. */
function boundsOf(key: string): [number, number] {
const b = ownGet(NUMERIC_FIELD_BOUNDS, key)
if (!b) throw new Error(`token-goat: no NUMERIC_FIELD_BOUNDS entry for ${echoedValue(key)}`)
return [b.min, b.max]
}
/** Validate a single numeric config field against its documented bounds and cross-field constraints. Used by config set to reject out-of-range values without rebuilding the entire config tree. Returns the clamped value if validation passes, or undefined if the field is not numeric/known. */
function walkGetNumeric(obj: Record<string, unknown>, parts: string[]): number | undefined {
let cur: unknown = obj
for (const part of parts) {
if (typeof cur !== 'object' || cur === null) return undefined
cur = (cur as Record<string, unknown>)[part]
if (cur === undefined) return undefined
}
return typeof cur === 'number' ? cur : undefined
}
export function validateNumericField(fieldKey: string, value: number, cfg: Record<string, unknown>): number | undefined {
const bounds = ownGet(NUMERIC_FIELD_BOUNDS, fieldKey)
if (!bounds) return undefined
// Apply simple min/max clamping (matching validatedInt/validatedFloat logic)
let clamped = Math.max(bounds.min, Math.min(bounds.max, value))
// Apply cross-field constraints if present
if (bounds.clampTo) {
const clampToValue = walkGetNumeric(cfg, bounds.clampTo.split('.'))
if (typeof clampToValue === 'number') {
clamped = Math.min(clamped, clampToValue)
}
}
return clamped
}
// String-valued config fields whose value must come from a fixed set. Compression profile and harness names use shared source lists, so a typo (e.g. `agressive` instead of `aggressive`) is rejected by `config set` instead of silently falling back to a default at runtime with no signal to the user.
const ENUM_FIELD_VALUES: Record<string, string[]> = {
'compression.profile': [...COMPRESSION_PROFILE_SETTINGS],
'compact_assist.harness': ['auto', ...KNOWN_HARNESS_NAMES],
'image_shrink.ocr_lang': [...SUPPORTED_OCR_LANG_CODES],
// Deliberately has no entry above `normal`. This table is what `config set` checks; a hand-edited TOML bypasses it, which is why resolveWorkerPriority (process_priority.ts) maps an unrecognized value back to the default rather than trusting whatever the file said.
'worker.priority': ['below_normal', 'low', 'normal'],
'hooks.native': ['auto', 'off'],
'hints.first_read_symbol_policy': ['warn', 'deny', 'off'],
'hints.write_blind_drop': ['deny', 'warn', 'off'],
}
/** Validate a single enum-valued string config field against its fixed set of allowed values. Used by config set to reject unrecognized values without rebuilding the entire config tree. Returns undefined if the field isn't enum-constrained (any string is fine) or the value is valid; returns the allowed-value list if the value is invalid. */
export function validateEnumField(fieldKey: string, value: string): string[] | undefined {
if (fieldKey === 'image_shrink.ocr_lang') {
const tokens = value.split(/[+,;\s]+/).map((s) => s.trim().toLowerCase()).filter(Boolean)
const allowed = [...SUPPORTED_OCR_LANG_CODES]
return tokens.length > 0 && tokens.every((t) => isSupportedOcrLang(t)) ? undefined : allowed
}
const allowed = ownGet(ENUM_FIELD_VALUES, fieldKey)
if (!allowed) return undefined
return allowed.includes(value) ? undefined : allowed
}
// --------------------------------------------------------------------------- Env fingerprint + mtime cache ---------------------------------------------------------------------------
const ENV_KEYS = [
'TOKEN_GOAT_COMPACT_ASSIST',
'TOKENWISE_COMPACT_ASSIST',
'TOKEN_GOAT_BASH_COMPRESS',
'TOKEN_GOAT_SESSION_BRIEF',
'TOKEN_GOAT_SKILL_PRESERVATION',
'TOKEN_GOAT_MAX_IMAGE_PIXELS',
'TOKEN_GOAT_OCR_LANG',
'TOKEN_GOAT_REPOMAP_COMPACT_THRESHOLD',
'TOKEN_GOAT_REPOMAP_EXCLUDE_TESTS',
'TOKEN_GOAT_OVERFLOW_GUARD',
'TOKEN_GOAT_OVERFLOW_MAX_TOKENS',
'TOKEN_GOAT_HINT_JSON_SIDECAR',
'TOKEN_GOAT_LARGE_READ_BYTES',
'TOKEN_GOAT_WEB_COMPRESS',
'TOKEN_GOAT_WORKER_WATCHDOG',
'TOKEN_GOAT_WORKER_MAX_POOL',
'TOKEN_GOAT_COMPRESS_PROFILE',
'TOKEN_GOAT_MODEL_WINDOW_TOKENS',
'TOKEN_GOAT_INJECTION_ENABLED',
'TOKEN_GOAT_MCP_CONFINE_READS',
'TOKEN_GOAT_SERVE_DIFF_ON_REREAD',
'TOKEN_GOAT_ELIDE_SERVED_LINES',
'TOKEN_GOAT_BASH_CACHE_MIN_BYTES',
'TOKEN_GOAT_BASH_CACHE_MAX_FILES',
'TOKEN_GOAT_BASH_CACHE_MAX_BYTES',
'TOKEN_GOAT_BASH_CACHE_MAX_BYTES_PER_OUTPUT',
'TOKEN_GOAT_SESSION_HINT_MIN_BYTES',
'TOKEN_GOAT_SKILL_COMPRESS',
'TOKEN_GOAT_PRE_SKILL',
'TOKEN_GOAT_ORPHAN_SWEEP',
'TOKEN_GOAT_WARN_UNBALANCED_SHELL_QUOTING',
'TOKEN_GOAT_DENY_BASH_DOUBLE_BACKSLASH',
'TOKEN_GOAT_LOG_LARGE_FILE_HINT_OUTCOMES',
'TOKEN_GOAT_CROSS_SESSION_READ_DEDUP',
'TOKEN_GOAT_CROSS_SESSION_READ_DEDUP_TTL_SECS',
'TOKEN_GOAT_MCP_DEDUP_TTL_SECS',
'TOKEN_GOAT_EMBEDDINGS_ENABLED',
'TOKEN_GOAT_BASH_DEDUP_MIN_BYTES',
'TOKEN_GOAT_WEB_DEDUP_MIN_BYTES',
'TOKEN_GOAT_GREP_DEDUP_MIN_MATCHES',
'TOKEN_GOAT_WEB_CACHE_MAX_FILES',
'TOKEN_GOAT_WEB_CACHE_MAX_BYTES',
'TOKEN_GOAT_WRITE_REWRITE_MIN_LINES',
'TOKEN_GOAT_WRITE_REWRITE_UNCHANGED_PCT',
'TOKEN_GOAT_INDEXING_MAX_DB_SIZE_MB',
'TOKEN_GOAT_INDEXING_AUTO_RECLAIM_EMBEDDINGS',
]
// Every env var actually consulted by _buildConfig's envInt/envBool/envStr calls is registered in CONFIG_KEY_ENV_OVERRIDES (below) as the per-field canonical source of truth. Fold those in here rather than relying solely on the hand-maintained ENV_KEYS list above: a var added only to CONFIG_KEY_ENV_OVERRIDES (as happened for TOKEN_GOAT_GLOB_DEDUP_MIN_MATCHES and the since-retired TOKEN_GOAT_OCR_ENABLED, both consumed in _buildConfig but omitted from ENV_KEYS) would otherwise silently drop out of the fingerprint, letting loadConfig()'s cache serve a stale config across a change to that var with no cache-invalidation signal at all.
function allEnvKeys(): string[] {
return [...new Set([...ENV_KEYS, ...Object.values(CONFIG_KEY_ENV_OVERRIDES).flat()])]
}
export function configEnvFingerprint(): string {
const snap: Record<string, string | undefined> = {}
for (const k of allEnvKeys()) {
snap[k] = process.env[k]
}
return JSON.stringify(snap)
}
interface CacheEntry {
config: Config
contentFp: string
envFp: string
projectRoot: string
projectContentFp: string
}
let _cached: CacheEntry | null = null
// Recursively freezes a config tree before it enters the cache. loadConfig() intentionally returns the SAME cached object reference on every hit within one mtime/env fingerprint window (see the "second call with unchanged file returns same object reference" test) -- without this, a caller that does `loadConfig().hints.foo = x` instead of reading it would silently corrupt that shared singleton for every other caller until the next cache invalidation. Object.freeze() throws on such a write in strict mode (ESM is always strict) instead of corrupting shared state, while leaving the returned reference itself unchanged.
function deepFreeze<T>(value: T): T {
if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
Object.freeze(value)
for (const v of Object.values(value as Record<string, unknown>)) {
deepFreeze(v)
}
}
return value
}
// Set by loadConfig()/loadPersistedConfig() whenever the on-disk config.toml exists but fails to parse (as opposed to being simply absent, which is not an error). Both loaders otherwise treat a parse failure identically to a missing file — silently falling back to defaults with no signal — so callers that need to warn the user (the CLI entry point, `config set`) check this after loading instead of duplicating TOML-read/error-classification logic themselves.
let _lastConfigParseError: string | null = null
/** The error message from the most recent config.toml parse failure, or `null` if the most recent load either succeeded or found no file at all. See {@link _lastConfigParseError}. */
export function getLastConfigParseError(): string | null {
return _lastConfigParseError
}
// Mirrors _lastConfigParseError, but for the per-project .token-goat.toml override read by loadConfig(). Set on every loadConfig() call; null when the file is absent or parsed cleanly.
let _lastProjectConfigParseError: string | null = null
/** The error message from the most recent `.token-goat.toml` parse/read failure, or `null` if the most recent {@link loadConfig} call found no per-project override file, or found one that parsed cleanly. Unlike {@link getLastConfigParseError}, a non-null result here never blocks config loading — the per-project layer fails open and loadConfig() always returns a valid global-only config in that case. Intended for a CLI entry point to optionally surface a warning, the same way {@link getLastConfigParseError} is surfaced for the global config.toml. */
export function getLastProjectConfigParseError(): string | null {
return _lastProjectConfigParseError
}
/** A field's declared numeric bounds, or `undefined` for keys with no declared constraint. Read-only accessor over NUMERIC_FIELD_BOUNDS so callers outside this module can name a violated range in a message without the table itself becoming mutable public API. */
export function numericFieldBounds(key: string): { min: number; max: number; clampTo?: string } | undefined {
const b = NUMERIC_FIELD_BOUNDS[key]
return b === undefined ? undefined : { min: b.min, max: b.max, ...(b.clampTo !== undefined ? { clampTo: b.clampTo } : {}) }
}
/** Structural equality for raw TOML leaf values (scalars plus the one `number[]` field, `hints.backoff_thresholds`). Deliberately not `===` (wrong for arrays) and not `JSON.stringify` (order-sensitive for objects, and silently equates `undefined` with absent). */
function rawValueEquals(a: unknown, b: unknown): boolean {
if (a === b) return true
if (Array.isArray(a) || Array.isArray(b)) {
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false
return a.every((el, i) => rawValueEquals(el, b[i]))
}
if (typeof a === 'object' && typeof b === 'object' && a !== null && b !== null) {
const ka = Object.keys(a as Record<string, unknown>)
const kb = Object.keys(b as Record<string, unknown>)
if (ka.length !== kb.length) return false
return ka.every((k) => Object.prototype.hasOwnProperty.call(b, k) && rawValueEquals((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]))
}
return false
}
/** Why `rawValue` could not be used as-is, stated from the field's own declared constraints where it has them, or `null` when nothing in this module can justify a specific cause. Never guesses. */
function rejectionReason(key: string, rawValue: unknown, effectiveValue: unknown, cfg: Record<string, unknown>): string | null {
if (typeof rawValue === 'number') {
const bounds = ownGet(NUMERIC_FIELD_BOUNDS, key)
if (bounds !== undefined) {
if (rawValue < bounds.min || rawValue > bounds.max) return `outside the allowed range ${bounds.min}-${bounds.max}`
if (!Number.isInteger(rawValue) && Number.isInteger(effectiveValue)) return 'not a whole number'
const clamped = validateNumericField(key, rawValue, cfg)
if (clamped !== undefined && clamped !== rawValue && bounds.clampTo !== undefined) return `above ${bounds.clampTo}, which caps it`
}
return null
}
if (typeof rawValue === 'string') {
const allowed = validateEnumField(key, rawValue)
if (allowed !== undefined) return `not one of: ${allowed.join(', ')}`
}
if (effectiveValue !== undefined && typeof rawValue !== typeof effectiveValue) {
return `expected ${Array.isArray(effectiveValue) ? 'a list' : `a ${typeof effectiveValue}`}, got ${Array.isArray(rawValue) ? 'a list' : `a ${typeof rawValue}`}`
}
return null
}
/** What an env var's string would become under the same coercion `_buildConfig` applies to it, BEFORE any bounds clamping — so the caller can compare what was asked for against what took effect and tell "clamped" from "in effect". Mirrors env.ts's envInt/envBool/envStr deliberately rather than calling them, because those return the fallback on a value they cannot use, which is indistinguishable from that value having been accepted. The three outcomes here keep that distinction: - `null` — this field's type has no env coercion this function can reproduce faithfully; the caller must not claim anything about whether the value took effect. - `'unusable'` — the helper would reject the string outright and fall back, so the variable contributes nothing at all despite being set. - `{ parsed }` — the pre-clamp value the helper would derive. Numeric fields assume the integer parse (envInt), which holds because every numeric key in CONFIG_KEY_ENV_OVERRIDES is integer-bounded; tests/guards/env_numeric_fields_are_integer.test.ts fails if a float-bounded field ever gains an env override, rather than letting this silently start calling valid floats unusable. */
function coerceEnvLike(rawStr: string, effectiveValue: unknown): { parsed: unknown } | 'unusable' | null {
const norm = rawStr.trim()
if (typeof effectiveValue === 'number') {
if (norm === '' || !/^[+-]?\d+$/.test(norm)) return 'unusable'
const val = parseInt(norm, 10)
return Number.isFinite(val) ? { parsed: val } : 'unusable'
}
if (typeof effectiveValue === 'boolean') {
const lower = norm.toLowerCase()
if (TRUTHY_ENV_VALUES.has(lower)) return { parsed: true }
if (FALSY_ENV_VALUES.has(lower)) return { parsed: false }
return 'unusable'
}
if (typeof effectiveValue === 'string') {
return norm === '' ? 'unusable' : { parsed: norm }
}
return null
}
/** Resolve which layer the effective value of `key` came from. Precedence mirrors the real load order (defaults -> config.toml -> .token-goat.toml -> env), highest-priority layer first, so the reported layer is the one that actually decided the value. Two consequences worth stating, because both were mis-modelled by the naive "project file lists the key, therefore the value came from it" rule this replaces: - An env var that is *set* wins outright, and is reported instead of the project file. Merely being registered in CONFIG_KEY_ENV_OVERRIDES is not being set — testing registration is the exact trap that made `config set` blame unset variables. - `project-invalid` is NOT "the global value won". _buildConfig merges the project raw tree over the global one and validates the merged result, so a project value that gets clamped or coerced still displaces the global file's value entirely; the effective value is whatever validation produced from the project's value. The project layer is still in force, which is why `config set` must keep warning about this state. */
export function resolveConfigKeyLayer(key: string, effectiveValue: unknown, cfg: Record<string, unknown>, projectInfo: ProjectConfigInfo | null): ConfigKeyLayer {
const envVar = (CONFIG_KEY_ENV_OVERRIDES[key] ?? []).find((name) => process.env[name] !== undefined)
if (envVar !== undefined) {
// Being set is not the same as being in effect -- the exact distinction this resolver exists to draw for the project layer, and the env layer needs it for the identical reason: an env var holding an out-of-range value is clamped, and reporting a bare "from $VAR" tells a reader who set 99999999 that 99999999 is what they got.
const rawStr = process.env[envVar] ?? ''
const coerce = ownGet(ENV_VALUE_COERCERS, key)
const special = coerce === undefined ? undefined : coerce(rawStr)
const judged = coerce === undefined ? coerceEnvLike(rawStr, effectiveValue) : special === undefined ? 'unusable' : { parsed: special }
// Type this function cannot coerce faithfully (today: the one number[] field). Claiming either "in effect" or "rejected" would be a guess, so report the layer and stop -- same policy as rejectionReason returning null rather than inventing a cause.
if (judged === null) return { layer: 'env', envVar }
if (judged === 'unusable') {
// Set but unparseable, so the variable contributed nothing and the effective value came from a lower layer. Reported as env rather than as that lower layer on purpose: "why is my variable not working" is the question this state exists to answer, and the lower layer is visible from the value itself.
return { layer: 'env-invalid', envVar, rawValue: rawStr, effectiveValue, reason: rawStr.trim() === '' ? 'empty' : rejectionReason(key, rawStr, effectiveValue, cfg) }
}
if (rawValueEquals(judged.parsed, effectiveValue)) return { layer: 'env', envVar }
return { layer: 'env-invalid', envVar, rawValue: judged.parsed, effectiveValue, reason: rejectionReason(key, judged.parsed, effectiveValue, cfg) }
}
if (projectInfo === null) return { layer: 'global' }
if (projectInfo.parseError !== null) return { layer: 'project-unparsed', path: projectInfo.path, parseError: projectInfo.parseError }
if (!Object.prototype.hasOwnProperty.call(projectInfo.values, key)) return { layer: 'global' }
const rawValue = projectInfo.values[key]
// loadConfig strips a locked key from the project file before merging (stripLockedProjectKeys), so its value never comes from there. A project value that happens to equal the effective one is a coincidence, not the source: crediting it would tell a reader the repository controls a security setting.
if (PROJECT_LOCKED_SECTIONS.includes(key.split('.')[0] ?? '') || PROJECT_LOCKED_KEYS.includes(key)) {
if (rawValueEquals(rawValue, effectiveValue)) return { layer: 'global' }
return { layer: 'project-invalid', path: projectInfo.path, rawValue, effectiveValue, reason: 'a security setting, which only the global config or the environment may set' }
}
if (rawValueEquals(rawValue, effectiveValue)) return { layer: 'project', path: projectInfo.path }
return { layer: 'project-invalid', path: projectInfo.path, rawValue, effectiveValue, reason: rejectionReason(key, rawValue, effectiveValue, cfg) }
}
/** Why config.toml's own `rawValue` for `key` did not survive loading, given `persistedCfg` built from that file alone (buildPersistedConfig: no env, no project file), or `null`. Reports only a cause rejectionReason can name: a value the loader replaces for its own reasons (a legacy-sentinel default, a normalized spelling) differs from what was written without being wrong, and calling it rejected would be a false alarm on every old full save. */
export function globalValueRejection(key: string, rawValue: unknown, persistedCfg: Record<string, unknown>): string | null {
let eff: unknown = persistedCfg
for (const part of key.split('.')) {
if (eff === null || typeof eff !== 'object' || !Object.prototype.hasOwnProperty.call(eff, part)) return null
eff = (eff as Record<string, unknown>)[part]
}
if (rawValueEquals(rawValue, eff)) return null
return rejectionReason(key, rawValue, eff, persistedCfg)
}
// --------------------------------------------------------------------------- load / save ---------------------------------------------------------------------------
export function loadConfig(projectRoot?: string): Config {
const p = configPath()
const root = projectRoot ?? resolveConfigProjectRoot()
const projPath = projectConfigPath(root)
// Content hash, not mtime: a `config set` immediately followed by another `config set` (or a concurrent writer) can land two different writes within the same mtime tick on some filesystems, which made the old mtime-only cache key silently keep serving the first write's config after the second landed. Reading the whole file is cheap (config.toml is always tiny) and this also skips the actual cost we care about avoiding on a hit -- re-parsing the TOML.
const { text, readError } = readConfigText(p)
const contentFp = text !== null ? shortFingerprint(text) : ''
// Same content-hash-not-mtime reasoning applies to the per-project override file, plus the resolved project root itself is part of the cache key -- an explicit projectRoot argument (or a cwd change between calls) can change which .token-goat.toml is in play even when neither the global file nor env vars changed.
const { text: projText, readError: projReadError } = readConfigText(projPath)
const projectContentFp = projText !== null ? shortFingerprint(projText) : ''
const envFp = configEnvFingerprint()
if (
_cached !== null &&
_cached.contentFp === contentFp &&
_cached.envFp === envFp &&
_cached.projectRoot === root &&
_cached.projectContentFp === projectContentFp
) {
return _cached.config
}
let raw: Record<string, unknown> = {}
if (text !== null) {
try {
raw = parse(text) as Record<string, unknown>
_lastConfigParseError = null
} catch (e) {
_lastConfigParseError = extractErrorMessage(e)
}
} else {
_lastConfigParseError = readError
}
// A malformed or unreadable .token-goat.toml fails open, exactly like a malformed global config.toml does above: the parse/read error is recorded for a CLI entry point to optionally surface (see getLastProjectConfigParseError()'s doc comment), but loadConfig() itself never throws and always falls through to the global-only config on failure.
let projectRaw: Record<string, unknown> = {}
if (projText !== null) {
try {
projectRaw = parse(projText) as Record<string, unknown>
_lastProjectConfigParseError = null
} catch (e) {
_lastProjectConfigParseError = extractErrorMessage(e)
}
} else {
_lastProjectConfigParseError = projReadError
}
const cfg = deepFreeze(_buildConfig(raw, projectRaw))
_cached = { config: cfg, contentFp, envFp, projectRoot: root, projectContentFp }
return cfg
}
export function invalidateConfigCache(): void {
_cached = null
resetLastProjectConfigLockedKeys()
}
registerReset(invalidateConfigCache)
/** Run `fn` with every config-affecting env var (the {@link allEnvKeys} registry, not just the hand-maintained {@link ENV_KEYS} list) temporarily cleared, then restore the original values. Safe because `_buildConfig` is fully synchronous — no other code can observe the env vars while they are unset. Using only ENV_KEYS here previously let a var missing from that list (e.g. TOKEN_GOAT_GLOB_DEDUP_MIN_MATCHES, the since-retired TOKEN_GOAT_OCR_ENABLED) survive the clear and leak into buildPersistedConfig()'s output, defeating this function's whole purpose for that var: a transient env override would get permanently written to config.toml by `config set` on any unrelated key instead of staying scoped to the current invocation. */
function withoutConfigEnv<T>(fn: () => T): T {
const keys = allEnvKeys()
const saved: Record<string, string | undefined> = {}
for (const k of keys) {
saved[k] = process.env[k]
delete process.env[k]
}
try {
return fn()
} finally {
for (const k of keys) {
const v = saved[k]
if (v === undefined) delete process.env[k]
else process.env[k] = v
}
}
}
/** Build a {@link Config} from `raw` TOML-shaped data with no env-var overlay — exactly what is (or would be) persisted to disk. Used by {@link loadPersistedConfig} and by `config set`'s write-time range check, so a transient TOKEN_GOAT_* env override active for one invocation never gets baked permanently into config.toml by a mutate-then-save command. */
export function buildPersistedConfig(raw: Record<string, unknown>): Config {
return withoutConfigEnv(() => _buildConfig(raw))
}
/** Like {@link loadConfig} but without env-var overlay — the config exactly as it exists on disk. `config set` / `project exclude` / `project prune` must load through this (not loadConfig()) before mutating and saving, or a TOKEN_GOAT_* env override active only for the current invocation would get written to config.toml permanently. */
export function loadPersistedConfig(): Config {
const p = configPath()
const { raw, parseError } = readConfigToml(p)
_lastConfigParseError = parseError
return buildPersistedConfig(raw)
}
/** Whether the resident hook server is on: `TOKEN_GOAT_HOOK_SERVER`, else `hooks.server` in the user's global config. Never a project's `.token-goat.toml`, whatever directory this runs in: one server answers every project on the machine, so one repository's file must not switch it for the others. */
export function hookServerEnabled(): boolean {
return envBool('TOKEN_GOAT_HOOK_SERVER', loadPersistedConfig().hooks.server)
}
/** Whether `install` may wire the native hook client: `TOKEN_GOAT_NATIVE_HOOKS` (false spellings turn it off, true ones restore `auto`), else `hooks.native` in the user's global config, else `auto`. Never a project's `.token-goat.toml` (the key is also in PROJECT_LOCKED_KEYS): the wiring it decides is written into user-scope harness configs that every project on the machine runs. */
export function nativeHooksEnabled(): boolean {
return (nativeHooksModeFromEnv(process.env['TOKEN_GOAT_NATIVE_HOOKS']) ?? loadPersistedConfig().hooks.native) !== 'off'
}
function _buildConfig(raw: Record<string, unknown>, projectRaw: Record<string, unknown> = {}): Config {
// Layer the per-project override (if any) on top of the global raw data before any field is read below, so every validatedInt/validatedBool/bounds-checked field, the legacy-sentinel guards, and the cross-field clamps all see one already-merged raw tree — the exact same validation path the global-only config always went through, with no divergent logic for the project layer.
const { cleaned: safeProjectRaw, dropped: lockedKeys } = stripLockedProjectKeys(projectRaw)
setLastProjectConfigLockedKeys(lockedKeys)
if (Object.keys(safeProjectRaw).length > 0) {
raw = mergeRawConfig(raw, safeProjectRaw)
}
const ca_raw = section(raw, 'compact_assist')
const ca = getDefaultConfig('compact_assist') as CompactAssistConfig
ca.enabled = validatedBool(ca_raw['enabled'], ca.enabled)
ca.auto_trigger_multiplier = validatedFloat(ca_raw['auto_trigger_multiplier'], ca.auto_trigger_multiplier, ...boundsOf('compact_assist.auto_trigger_multiplier'))
ca.max_manifest_chars = validatedInt(ca_raw['max_manifest_chars'], ca.max_manifest_chars, ...boundsOf('compact_assist.max_manifest_chars'))
ca.summary_budget_chars = validatedInt(ca_raw['summary_budget_chars'], ca.summary_budget_chars, ...boundsOf('compact_assist.summary_budget_chars'))
ca.harness = validatedStr(ca_raw['harness'], ca.harness)
// env overrides
ca.enabled = envBool('TOKEN_GOAT_COMPACT_ASSIST', envBool('TOKENWISE_COMPACT_ASSIST', ca.enabled))
const bc_raw = section(raw, 'bash_compress')
const bc = getDefaultConfig('bash_compress') as BashCompressConfig
bc.enabled = validatedBool(bc_raw['enabled'], bc.enabled)
bc.disabled_filters = validatedStrList(bc_raw['disabled_filters'], bc.disabled_filters)
bc.max_lines = validatedInt(bc_raw['max_lines'], bc.max_lines, ...boundsOf('bash_compress.max_lines'))
bc.max_bytes = validatedInt(bc_raw['max_bytes'], bc.max_bytes, ...boundsOf('bash_compress.max_bytes'))
bc.timeout_seconds = validatedInt(bc_raw['timeout_seconds'], bc.timeout_seconds, ...boundsOf('bash_compress.timeout_seconds'))
// Legacy-sentinel guard: config set on ANY key does a full load->mutate-one-field->save-all round trip (see saveConfig), so any pre-687758ae user who ran `config set` for an unrelated key got the then-in-memory default cache_min_bytes (0) permanently persisted, even though the field had zero consumers at the time and nobody could have deliberately chosen it. 687758ae wired this key up as the real cache minimum-size gate and bumped the in-code default to 512 -- but those stale 0s now load back in and silently disable caching. Treat an exactly-persisted 0 as that stale default and fall through to the current default instead of trusting it; any other persisted value (including a deliberate 0 set after upgrading) is respected as-is. Note: 0 is a more plausible value someone might deliberately choose post-upgrade (cache everything with no minimum size) than the other sentinel values were, so callers who really want 0 can work around this by setting 1 instead.
bc.cache_min_bytes = validatedIntWithLegacySentinel(bc_raw['cache_min_bytes'], bc.cache_min_bytes, 0, ...boundsOf('bash_compress.cache_min_bytes'))
bc.cache_max_file_count = validatedInt(bc_raw['cache_max_file_count'], bc.cache_max_file_count, ...boundsOf('bash_compress.cache_max_file_count'))
bc.cache_max_bytes = validatedInt(bc_raw['cache_max_bytes'], bc.cache_max_bytes, ...boundsOf('bash_compress.cache_max_bytes'))
bc.cache_max_bytes_per_output = validatedInt(bc_raw['cache_max_bytes_per_output'], bc.cache_max_bytes_per_output, ...boundsOf('bash_compress.cache_max_bytes_per_output'))
bc.min_net_savings_bytes = validatedInt(bc_raw['min_net_savings_bytes'], bc.min_net_savings_bytes, ...boundsOf('bash_compress.min_net_savings_bytes'))
bc.elide_served_shell_output = validatedBool(bc_raw['elide_served_shell_output'], bc.elide_served_shell_output)
bc.enabled = envBool('TOKEN_GOAT_BASH_COMPRESS', bc.enabled)
bc.cache_min_bytes = envInt('TOKEN_GOAT_BASH_CACHE_MIN_BYTES', bc.cache_min_bytes, ...boundsOf('bash_compress.cache_min_bytes'))
bc.cache_max_file_count = envInt('TOKEN_GOAT_BASH_CACHE_MAX_FILES', bc.cache_max_file_count, ...boundsOf('bash_compress.cache_max_file_count'))
bc.cache_max_bytes = envInt('TOKEN_GOAT_BASH_CACHE_MAX_BYTES', bc.cache_max_bytes, ...boundsOf('bash_compress.cache_max_bytes'))
bc.cache_max_bytes_per_output = envInt('TOKEN_GOAT_BASH_CACHE_MAX_BYTES_PER_OUTPUT', bc.cache_max_bytes_per_output, ...boundsOf('bash_compress.cache_max_bytes_per_output'))
bc.min_net_savings_bytes = envInt('TOKEN_GOAT_BASH_MIN_NET_SAVINGS_BYTES', bc.min_net_savings_bytes, ...boundsOf('bash_compress.min_net_savings_bytes'))
// A per-item cap larger than the total-directory budget is nonsensical: pruneBlobs() would otherwise evict a freshly-written item (and everything else) in the same storeBlob() call that just wrote it. Clamp it so the per-item cap can never exceed the total budget.
bc.cache_max_bytes_per_output = Math.min(bc.cache_max_bytes_per_output, bc.cache_max_bytes)
const ar_raw = section(raw, 'agent_report')
const ar = getDefaultConfig('agent_report') as AgentReportConfig
ar.min_bytes = validatedInt(ar_raw['min_bytes'], ar.min_bytes, ...boundsOf('agent_report.min_bytes'))
ar.fence_collapse_min_lines = validatedInt(ar_raw['fence_collapse_min_lines'], ar.fence_collapse_min_lines, ...boundsOf('agent_report.fence_collapse_min_lines'))
ar.fence_collapse_keep_lines = validatedInt(ar_raw['fence_collapse_keep_lines'], ar.fence_collapse_keep_lines, ...boundsOf('agent_report.fence_collapse_keep_lines'))
// Env overrides applied after the file values, matching bash_compress above. Without these the CONFIG_KEY_ENV_OVERRIDES entries would be dead config: listed by `config-get`/doctor, settable by a user, and silently ignored.
ar.min_bytes = envInt('TOKEN_GOAT_AGENT_REPORT_MIN_BYTES', ar.min_bytes, ...boundsOf('agent_report.min_bytes'))
ar.fence_collapse_min_lines = envInt('TOKEN_GOAT_AGENT_REPORT_FENCE_MIN_LINES', ar.fence_collapse_min_lines, ...boundsOf('agent_report.fence_collapse_min_lines'))
ar.fence_collapse_keep_lines = envInt('TOKEN_GOAT_AGENT_REPORT_FENCE_KEEP_LINES', ar.fence_collapse_keep_lines, ...boundsOf('agent_report.fence_collapse_keep_lines'))
// Two keep-ends plus the elision marker must be strictly smaller than the block they replace, or "collapsing" a block would emit MORE lines than it removed. Clamped rather than rejected so a hand-edited config degrades to "collapse less" instead of failing the hook.
ar.fence_collapse_keep_lines = Math.min(ar.fence_collapse_keep_lines, Math.floor((ar.fence_collapse_min_lines - 1) / 2))
const bd_raw = section(raw, 'bash_diff')
const bd = getDefaultConfig('bash_diff') as BashDiffConfig
bd.max_hunks_per_file = validatedInt(bd_raw['max_hunks_per_file'], bd.max_hunks_per_file, ...boundsOf('bash_diff.max_hunks_per_file'))
const sl_raw = section(raw, 'bash_severity_log')
const sl = getDefaultConfig('bash_severity_log') as SeverityLogConfig
sl.context_lines = validatedInt(sl_raw['context_lines'], sl.context_lines, ...boundsOf('bash_severity_log.context_lines'))
sl.score_threshold = validatedFloat(sl_raw['score_threshold'], sl.score_threshold, ...boundsOf('bash_severity_log.score_threshold'))
const cc_raw = section(raw, 'post_read_code_compress')
const cc = getDefaultConfig('post_read_code_compress') as CodeCompressConfig
cc.min_lines = validatedInt(cc_raw['min_lines'], cc.min_lines, ...boundsOf('post_read_code_compress.min_lines'))
const sb_raw = section(raw, 'session_brief')
const sb = getDefaultConfig('session_brief') as SessionBriefConfig
sb.enabled = validatedBool(sb_raw['enabled'], sb.enabled)
sb.enabled = envBool('TOKEN_GOAT_SESSION_BRIEF', sb.enabled)
const sp_raw = section(raw, 'skill_preservation')
const sp = getDefaultConfig('skill_preservation') as SkillPreservationConfig
sp.enabled = validatedBool(sp_raw['enabled'], sp.enabled)
sp.max_cache_bytes = validatedInt(sp_raw['max_cache_bytes'], sp.max_cache_bytes, ...boundsOf('skill_preservation.max_cache_bytes'))
sp.orphan_sweep_enabled = validatedBool(sp_raw['orphan_sweep_enabled'], sp.orphan_sweep_enabled)
sp.orphan_age_secs = validatedInt(sp_raw['orphan_age_secs'], sp.orphan_age_secs, ...boundsOf('skill_preservation.orphan_age_secs'))
sp.truncation_budget_tokens = validatedInt(sp_raw['truncation_budget_tokens'], sp.truncation_budget_tokens, ...boundsOf('skill_preservation.truncation_budget_tokens'))
sp.compress_bodies = validatedBool(sp_raw['compress_bodies'], sp.compress_bodies)
sp.compress_min_bytes = validatedInt(sp_raw['compress_min_bytes'], sp.compress_min_bytes, ...boundsOf('skill_preservation.compress_min_bytes'))
sp.inline_snippets = validatedBool(sp_raw['inline_snippets'], sp.inline_snippets)
sp.pre_skill_enabled = validatedBool(sp_raw['pre_skill_enabled'], sp.pre_skill_enabled)
sp.first_load_compact = validatedBool(sp_raw['first_load_compact'], sp.first_load_compact)
sp.post_compact_full_loads = validatedBool(sp_raw['post_compact_full_loads'], sp.post_compact_full_loads)
sp.enabled = envBool('TOKEN_GOAT_SKILL_PRESERVATION', sp.enabled)
sp.compress_bodies = envBool('TOKEN_GOAT_SKILL_COMPRESS', sp.compress_bodies)
sp.pre_skill_enabled = envBool('TOKEN_GOAT_PRE_SKILL', sp.pre_skill_enabled)
sp.orphan_sweep_enabled = envBool('TOKEN_GOAT_ORPHAN_SWEEP', sp.orphan_sweep_enabled)
const is_raw = section(raw, 'image_shrink')
const is_cfg = getDefaultConfig('image_shrink') as ImageShrinkConfig
is_cfg.enabled = validatedBool(is_raw['enabled'], is_cfg.enabled)
is_cfg.jpeg_quality = validatedInt(is_raw['jpeg_quality'], is_cfg.jpeg_quality, ...boundsOf('image_shrink.jpeg_quality'))
// Legacy-sentinel guard: a pre-cb2a1dfa full-snapshot save persisted the then-default 16_000_000, which now loads as the current default instead of pinning the old cap.
is_cfg.max_image_pixels = validatedIntWithLegacySentinel(is_raw['max_image_pixels'], is_cfg.max_image_pixels, 16_000_000, ...boundsOf('image_shrink.max_image_pixels'))
is_cfg.screenshot_redirect = validatedBool(is_raw['screenshot_redirect'], is_cfg.screenshot_redirect)
is_cfg.ocr_min_confidence = validatedInt(is_raw['ocr_min_confidence'], is_cfg.ocr_min_confidence, ...boundsOf('image_shrink.ocr_min_confidence'))
is_cfg.ocr_lang = validatedOcrLang(is_raw['ocr_lang'], is_cfg.ocr_lang)
is_cfg.vision_tier = validatedVisionTier(is_raw['vision_tier'], is_cfg.vision_tier)
is_cfg.max_image_pixels = envInt('TOKEN_GOAT_MAX_IMAGE_PIXELS', is_cfg.max_image_pixels, ...boundsOf('image_shrink.max_image_pixels'))
is_cfg.ocr_lang = validatedOcrLang(process.env['TOKEN_GOAT_OCR_LANG'], is_cfg.ocr_lang)
is_cfg.vision_tier = validatedVisionTier(process.env['TOKEN_GOAT_VISION_TIER'], is_cfg.vision_tier)
const sc_raw = section(raw, 'screenshot')
const sc_cfg = getDefaultConfig('screenshot') as ScreenshotConfig
sc_cfg.chrome_path = validatedStr(sc_raw['chrome_path'], sc_cfg.chrome_path)
sc_cfg.block_private_targets = validatedBool(sc_raw['block_private_targets'], sc_cfg.block_private_targets)
sc_cfg.block_private_targets = envBool('TOKEN_GOAT_SCREENSHOT_BLOCK_PRIVATE_TARGETS', sc_cfg.block_private_targets)
const rm_raw = section(raw, 'repomap')
const rm = getDefaultConfig('repomap') as RepomapConfig
rm.compact_file_threshold = validatedInt(rm_raw['compact_file_threshold'], rm.compact_file_threshold, ...boundsOf('repomap.compact_file_threshold'))
rm.exclude_tests = validatedBool(rm_raw['exclude_tests'], rm.exclude_tests)
rm.compact_file_threshold = envInt('TOKEN_GOAT_REPOMAP_COMPACT_THRESHOLD', rm.compact_file_threshold, ...boundsOf('repomap.compact_file_threshold'))
rm.exclude_tests = envBool('TOKEN_GOAT_REPOMAP_EXCLUDE_TESTS', rm.exclude_tests)
const og_raw = section(raw, 'overflow_guard')
const og = getDefaultConfig('overflow_guard') as OverflowGuardConfig
og.enabled = validatedBool(og_raw['enabled'], og.enabled)
og.max_tokens = validatedInt(og_raw['max_tokens'], og.max_tokens, ...boundsOf('overflow_guard.max_tokens'))
og.enabled = envBool('TOKEN_GOAT_OVERFLOW_GUARD', og.enabled)
og.max_tokens = envInt('TOKEN_GOAT_OVERFLOW_MAX_TOKENS', og.max_tokens, ...boundsOf('overflow_guard.max_tokens'))
const hi_raw = section(raw, 'hints')
const hi = getDefaultConfig('hints') as HintsConfig
hi.quiet_hours = validatedStr(hi_raw['quiet_hours'], hi.quiet_hours)
hi.json_sidecar = validatedBool(hi_raw['json_sidecar'], hi.json_sidecar)
hi.min_file_lines_for_hint = validatedInt(hi_raw['min_file_lines_for_hint'], hi.min_file_lines_for_hint, ...boundsOf('hints.min_file_lines_for_hint'))
hi.bash_dedup_min_bytes = validatedInt(hi_raw['bash_dedup_min_bytes'], hi.bash_dedup_min_bytes, ...boundsOf('hints.bash_dedup_min_bytes'))
hi.bash_dedup_min_bytes = envInt('TOKEN_GOAT_BASH_DEDUP_MIN_BYTES', hi.bash_dedup_min_bytes, ...boundsOf('hints.bash_dedup_min_bytes'))
hi.web_dedup_min_bytes = validatedInt(hi_raw['web_dedup_min_bytes'], hi.web_dedup_min_bytes, ...boundsOf('hints.web_dedup_min_bytes'))
hi.web_dedup_min_bytes = envInt('TOKEN_GOAT_WEB_DEDUP_MIN_BYTES', hi.web_dedup_min_bytes, ...boundsOf('hints.web_dedup_min_bytes'))
hi.grep_dedup_min_matches = validatedInt(hi_raw['grep_dedup_min_matches'], hi.grep_dedup_min_matches, ...boundsOf('hints.grep_dedup_min_matches'))
hi.grep_dedup_min_matches = envInt('TOKEN_GOAT_GREP_DEDUP_MIN_MATCHES', hi.grep_dedup_min_matches, ...boundsOf('hints.grep_dedup_min_matches'))
hi.glob_dedup_min_matches = validatedInt(hi_raw['glob_dedup_min_matches'], hi.glob_dedup_min_matches, ...boundsOf('hints.glob_dedup_min_matches'))
hi.glob_dedup_min_matches = envInt('TOKEN_GOAT_GLOB_DEDUP_MIN_MATCHES', hi.glob_dedup_min_matches, ...boundsOf('hints.glob_dedup_min_matches'))
hi.write_rewrite_min_lines = validatedInt(hi_raw['write_rewrite_min_lines'], hi.write_rewrite_min_lines, ...boundsOf('hints.write_rewrite_min_lines'))
hi.write_rewrite_min_lines = envInt('TOKEN_GOAT_WRITE_REWRITE_MIN_LINES', hi.write_rewrite_min_lines, ...boundsOf('hints.write_rewrite_min_lines'))
hi.write_rewrite_unchanged_pct = validatedInt(hi_raw['write_rewrite_unchanged_pct'], hi.write_rewrite_unchanged_pct, ...boundsOf('hints.write_rewrite_unchanged_pct'))
hi.write_rewrite_unchanged_pct = envInt('TOKEN_GOAT_WRITE_REWRITE_UNCHANGED_PCT', hi.write_rewrite_unchanged_pct, ...boundsOf('hints.write_rewrite_unchanged_pct'))
hi.serve_diff_on_reread = validatedBool(hi_raw['serve_diff_on_reread'], hi.serve_diff_on_reread)
hi.elide_served_lines = validatedBool(hi_raw['elide_served_lines'], hi.elide_served_lines)
hi.subagent_markdown_first_read_deny = validatedBool(hi_raw['subagent_markdown_first_read_deny'], hi.subagent_markdown_first_read_deny)
hi.agent_scoped_spawn_deny = validatedBool(hi_raw['agent_scoped_spawn_deny'], hi.agent_scoped_spawn_deny)
hi.inline_symbol_body = validatedBool(hi_raw['inline_symbol_body'], hi.inline_symbol_body)
hi.backoff_thresholds = validatedIntList(hi_raw['backoff_thresholds'], hi.backoff_thresholds)
hi.git_hint_max_ms = validatedInt(hi_raw['git_hint_max_ms'], hi.git_hint_max_ms, ...boundsOf('hints.git_hint_max_ms'))
hi.min_session_hint_savings_bytes = validatedInt(hi_raw['min_session_hint_savings_bytes'], hi.min_session_hint_savings_bytes, ...boundsOf('hints.min_session_hint_savings_bytes'))
hi.pre_skill_advisory = validatedBool(hi_raw['pre_skill_advisory'], hi.pre_skill_advisory)
hi.stop_verification_advisory = validatedBool(hi_raw['stop_verification_advisory'], hi.stop_verification_advisory)
hi.agent_receipt = validatedBool(hi_raw['agent_receipt'], hi.agent_receipt)
hi.context_threshold_advisory = validatedBool(hi_raw['context_threshold_advisory'], hi.context_threshold_advisory)
hi.diff_hint_min_tokens_saved = validatedInt(hi_raw['diff_hint_min_tokens_saved'], hi.diff_hint_min_tokens_saved, ...boundsOf('hints.diff_hint_min_tokens_saved'))
// Legacy-sentinel guard: config set on ANY key does a full load->mutate-one-field->save-all round trip (see saveConfig), so any pre-4b6f30dc user who ran `config set` for an unrelated key got the then-in-memory default large_read_redirect_bytes (45_000) permanently persisted, even though the field had zero consumers at the time and nobody could have deliberately chosen it. 4b6f30dc wired this key up as the real pressure-scaled first-read deny gate and bumped the in-code default to 512_000 -- but those stale 45_000s now load back in and silently make the gate ~11.4x more aggressive than intended. Treat an exactly-persisted 45_000 as that stale default and fall through to the current default instead of trusting it; any other persisted value (including a deliberate 45_000 set after upgrading) is respected as-is.
hi.large_read_redirect_bytes = validatedIntWithLegacySentinel(hi_raw['large_read_redirect_bytes'], hi.large_read_redirect_bytes, 45_000, ...boundsOf('hints.large_read_redirect_bytes'))
hi.first_read_symbol_bytes = validatedInt(hi_raw['first_read_symbol_bytes'], hi.first_read_symbol_bytes, ...boundsOf('hints.first_read_symbol_bytes'))
hi.first_read_symbol_policy = validatedEnum('hints.first_read_symbol_policy', hi_raw['first_read_symbol_policy'], hi.first_read_symbol_policy)
hi.write_blind_drop = validatedEnum('hints.write_blind_drop', hi_raw['write_blind_drop'], hi.write_blind_drop)
hi.write_sibling_copy = validatedBool(hi_raw['write_sibling_copy'], hi.write_sibling_copy)
hi.write_sibling_copy_allow = validatedStrList(hi_raw['write_sibling_copy_allow'], hi.write_sibling_copy_allow)
hi.reread_deny = validatedBool(hi_raw['reread_deny'], hi.reread_deny)
// Legacy-sentinel guard: config set on ANY key does a full load->mutate-one-field->save-all round trip (see saveConfig), so any pre-a1fad4c6 user who ran `config set` for an unrelated key got the then-in-memory default reread_deny_min_bytes (2048) permanently persisted, even though the field had zero consumers at the time and nobody could have deliberately chosen it. a1fad4c6 wired this key up as the real re-read-deny gate and bumped the in-code default to 51_200 -- but those stale 2048s now load back in and silently make the gate 25x more aggressive than intended. Treat an exactly-persisted 2048 as that stale default and fall through to the current default instead of trusting it; any other persisted value (including a deliberate 2048 set after upgrading) is respected as-is.
hi.reread_deny_min_bytes = validatedIntWithLegacySentinel(hi_raw['reread_deny_min_bytes'], hi.reread_deny_min_bytes, 2048, ...boundsOf('hints.reread_deny_min_bytes'))
hi.stable_doc_compacts = validatedBool(hi_raw['stable_doc_compacts'], hi.stable_doc_compacts)
hi.fold_code_bodies = validatedBool(hi_raw['fold_code_bodies'], hi.fold_code_bodies)
hi.fold_comment_blocks = validatedBool(hi_raw['fold_comment_blocks'], hi.fold_comment_blocks)
hi.fold_prose_paragraphs = validatedBool(hi_raw['fold_prose_paragraphs'], hi.fold_prose_paragraphs)
hi.outline_large_documents = validatedBool(hi_raw['outline_large_documents'], hi.outline_large_documents)
hi.skeleton_large_sources = validatedBool(hi_raw['skeleton_large_sources'], hi.skeleton_large_sources)
hi.truncated_read_min_lines = validatedInt(hi_raw['truncated_read_min_lines'], hi.truncated_read_min_lines, ...boundsOf('hints.truncated_read_min_lines'))
hi.protect_recent_reads = validatedInt(hi_raw['protect_recent_reads'], hi.protect_recent_reads, ...boundsOf('hints.protect_recent_reads'))
hi.warn_unbalanced_shell_quoting = validatedBool(hi_raw['warn_unbalanced_shell_quoting'], hi.warn_unbalanced_shell_quoting)
hi.deny_bash_double_backslash = validatedBool(hi_raw['deny_bash_double_backslash'], hi.deny_bash_double_backslash)
hi.log_large_file_hint_outcomes = validatedBool(hi_raw['log_large_file_hint_outcomes'], hi.log_large_file_hint_outcomes)
hi.warn_unbalanced_shell_quoting = envBool('TOKEN_GOAT_WARN_UNBALANCED_SHELL_QUOTING', hi.warn_unbalanced_shell_quoting)
hi.deny_bash_double_backslash = envBool('TOKEN_GOAT_DENY_BASH_DOUBLE_BACKSLASH', hi.deny_bash_double_backslash)
hi.serve_diff_on_reread = envBool('TOKEN_GOAT_SERVE_DIFF_ON_REREAD', hi.serve_diff_on_reread)
hi.elide_served_lines = envBool('TOKEN_GOAT_ELIDE_SERVED_LINES', hi.elide_served_lines)
hi.subagent_markdown_first_read_deny = envBool('TOKEN_GOAT_SUBAGENT_MARKDOWN_FIRST_READ_DENY', hi.subagent_markdown_first_read_deny)
hi.agent_scoped_spawn_deny = envBool('TOKEN_GOAT_AGENT_SCOPED_SPAWN_DENY', hi.agent_scoped_spawn_deny)
hi.inline_symbol_body = envBool('TOKEN_GOAT_INLINE_SYMBOL_BODY', hi.inline_symbol_body)
hi.log_large_file_hint_outcomes = envBool('TOKEN_GOAT_LOG_LARGE_FILE_HINT_OUTCOMES', hi.log_large_file_hint_outcomes)
hi.json_sidecar = envBool('TOKEN_GOAT_HINT_JSON_SIDECAR', hi.json_sidecar)
hi.large_read_redirect_bytes = envInt('TOKEN_GOAT_LARGE_READ_BYTES', hi.large_read_redirect_bytes, ...boundsOf('hints.large_read_redirect_bytes'))
hi.cross_session_read_dedup = validatedBool(hi_raw['cross_session_read_dedup'], hi.cross_session_read_dedup)
hi.cross_session_read_dedup_ttl_secs = validatedInt(hi_raw['cross_session_read_dedup_ttl_secs'], hi.cross_session_read_dedup_ttl_secs, ...boundsOf('hints.cross_session_read_dedup_ttl_secs'))
hi.cross_session_read_dedup = envBool('TOKEN_GOAT_CROSS_SESSION_READ_DEDUP', hi.cross_session_read_dedup)
hi.cross_session_read_dedup_ttl_secs = envInt('TOKEN_GOAT_CROSS_SESSION_READ_DEDUP_TTL_SECS', hi.cross_session_read_dedup_ttl_secs, ...boundsOf('hints.cross_session_read_dedup_ttl_secs'))
hi.mcp_dedup_ttl_secs = validatedInt(hi_raw['mcp_dedup_ttl_secs'], hi.mcp_dedup_ttl_secs, ...boundsOf('hints.mcp_dedup_ttl_secs'))
hi.mcp_dedup_ttl_secs = envInt('TOKEN_GOAT_MCP_DEDUP_TTL_SECS', hi.mcp_dedup_ttl_secs, ...boundsOf('hints.mcp_dedup_ttl_secs'))
hi.session_start_reminder = validatedBool(hi_raw['session_start_reminder'], hi.session_start_reminder)
hi.session_start_reminder = envBool('TOKEN_GOAT_SESSION_START_REMINDER', hi.session_start_reminder)
hi.min_session_hint_savings_bytes = envInt('TOKEN_GOAT_SESSION_HINT_MIN_BYTES', hi.min_session_hint_savings_bytes, ...boundsOf('hints.min_session_hint_savings_bytes'))
// Scalar hints fields that were readable from config.toml but had no env override, so the only way to change them for a single run (a dogfood check, a one-off CLI invocation, a test) was to write a config.toml into the data dir and remember to delete it. Every other scalar hints field already had one; these were the leftovers. Registered in CONFIG_KEY_ENV_OVERRIDES below too, which is what feeds allEnvKeys() -- so each is automatically covered by loadConfig()'s cache fingerprint and by withoutConfigEnv()'s transient-override strip, and cannot leak into a persisted config.toml. `backoff_thresholds` is deliberately excluded: it is the one non-scalar hints field (number[]), and there is no existing env helper that parses a list, so giving it one would mean inventing a serialization format rather than following the established pattern -- see the coverage guard in tests/guards/hints_env_override_coverage.test.ts, which pins that exemption.
hi.reread_deny = envBool('TOKEN_GOAT_REREAD_DENY', hi.reread_deny)
hi.reread_deny_min_bytes = envInt('TOKEN_GOAT_REREAD_DENY_MIN_BYTES', hi.reread_deny_min_bytes, ...boundsOf('hints.reread_deny_min_bytes'))
hi.first_read_symbol_bytes = envInt('TOKEN_GOAT_FIRST_READ_SYMBOL_BYTES', hi.first_read_symbol_bytes, ...boundsOf('hints.first_read_symbol_bytes'))
hi.first_read_symbol_policy = envEnum('hints.first_read_symbol_policy', 'TOKEN_GOAT_FIRST_READ_SYMBOL_POLICY', hi.first_read_symbol_policy)
hi.write_blind_drop = envEnum('hints.write_blind_drop', 'TOKEN_GOAT_WRITE_BLIND_DROP', hi.write_blind_drop)
hi.write_sibling_copy = envBool('TOKEN_GOAT_WRITE_SIBLING_COPY', hi.write_sibling_copy)
hi.protect_recent_reads = envInt('TOKEN_GOAT_PROTECT_RECENT_READS', hi.protect_recent_reads, ...boundsOf('hints.protect_recent_reads'))
hi.truncated_read_min_lines = envInt('TOKEN_GOAT_TRUNCATED_READ_MIN_LINES', hi.truncated_read_min_lines, ...boundsOf('hints.truncated_read_min_lines'))
hi.diff_hint_min_tokens_saved = envInt('TOKEN_GOAT_DIFF_HINT_MIN_TOKENS_SAVED', hi.diff_hint_min_tokens_saved, ...boundsOf('hints.diff_hint_min_tokens_saved'))
hi.min_file_lines_for_hint = envInt('TOKEN_GOAT_MIN_FILE_LINES_FOR_HINT', hi.min_file_lines_for_hint, ...boundsOf('hints.min_file_lines_for_hint'))
hi.git_hint_max_ms = envInt('TOKEN_GOAT_GIT_HINT_MAX_MS', hi.git_hint_max_ms, ...boundsOf('hints.git_hint_max_ms'))
hi.stable_doc_compacts = envBool('TOKEN_GOAT_STABLE_DOC_COMPACTS', hi.stable_doc_compacts)
hi.fold_code_bodies = envBool('TOKEN_GOAT_FOLD_CODE_BODIES', hi.fold_code_bodies)
hi.fold_comment_blocks = envBool('TOKEN_GOAT_FOLD_COMMENT_BLOCKS', hi.fold_comment_blocks)
hi.fold_prose_paragraphs = envBool('TOKEN_GOAT_FOLD_PROSE_PARAGRAPHS', hi.fold_prose_paragraphs)
hi.outline_large_documents = envBool('TOKEN_GOAT_OUTLINE_LARGE_DOCUMENTS', hi.outline_large_documents)
hi.skeleton_large_sources = envBool('TOKEN_GOAT_SKELETON_LARGE_SOURCES', hi.skeleton_large_sources)
hi.context_threshold_advisory = envBool('TOKEN_GOAT_CONTEXT_THRESHOLD_ADVISORY', hi.context_threshold_advisory)
hi.pre_skill_advisory = envBool('TOKEN_GOAT_PRE_SKILL_ADVISORY', hi.pre_skill_advisory)
hi.stop_verification_advisory = envBool('TOKEN_GOAT_STOP_VERIFICATION_ADVISORY', hi.stop_verification_advisory)
hi.agent_receipt = envBool('TOKEN_GOAT_AGENT_RECEIPT', hi.agent_receipt)
hi.quiet_hours = envStr('TOKEN_GOAT_QUIET_HOURS', hi.quiet_hours)
// parse prompt_triggers
const triggers_raw = hi_raw['prompt_triggers']
if (Array.isArray(triggers_raw)) {
hi.prompt_triggers = triggers_raw
.filter((t): t is Record<string, unknown> => t !== null && typeof t === 'object' && !Array.isArray(t))
.map((t) => ({
keywords: validatedStrList(t['keywords'], []),
hint: validatedStr(t['hint'], ''),
}))
.filter((t) => t.keywords.length > 0 && t.hint.length > 0)
}
const hk_raw = section(raw, 'hooks')
const hk = getDefaultConfig('hooks') as HooksConfig
hk.latency_budget_ms = validatedInt(hk_raw['latency_budget_ms'], hk.latency_budget_ms, ...boundsOf('hooks.latency_budget_ms'))
hk.latency_budget_ms = envInt('TOKEN_GOAT_HOOK_LATENCY_BUDGET_MS', hk.latency_budget_ms, ...boundsOf('hooks.latency_budget_ms'))
hk.server = validatedBool(hk_raw['server'], hk.server)
hk.server = envBool('TOKEN_GOAT_HOOK_SERVER', hk.server)
hk.native = validatedNativeHooksMode(hk_raw['native'], hk.native)
hk.native = nativeHooksModeFromEnv(process.env['TOKEN_GOAT_NATIVE_HOOKS']) ?? hk.native
const wf_raw = section(raw, 'webfetch')
const wf = getDefaultConfig('webfetch') as WebFetchConfig
wf.allow = validatedStrList(wf_raw['allow'], wf.allow)
wf.deny = validatedStrList(wf_raw['deny'], wf.deny)
// Comma-separated rather than path.delimiter: these are URL patterns, and on Windows the path delimiter is ';', which is a legal character in a URL. Every other list-valued setting gets an env override so a container or CI job can set policy without shipping a TOML, and an egress policy is the one an operator is most likely to want to pin that way.
wf.allow = envStrList('TOKEN_GOAT_WEBFETCH_ALLOW', wf.allow, ',')
wf.deny = envStrList('TOKEN_GOAT_WEBFETCH_DENY', wf.deny, ',')
wf.max_file_count = validatedInt(wf_raw['max_file_count'], wf.max_file_count, ...boundsOf('webfetch.max_file_count'))
wf.max_file_count = envInt('TOKEN_GOAT_WEB_CACHE_MAX_FILES', wf.max_file_count, ...boundsOf('webfetch.max_file_count'))
wf.max_bytes = validatedInt(wf_raw['max_bytes'], wf.max_bytes, ...boundsOf('webfetch.max_bytes'))
wf.max_bytes = envInt('TOKEN_GOAT_WEB_CACHE_MAX_BYTES', wf.max_bytes, ...boundsOf('webfetch.max_bytes'))
wf.compress_bodies = validatedBool(wf_raw['compress_bodies'], wf.compress_bodies)
wf.compress_min_bytes = validatedInt(wf_raw['compress_min_bytes'], wf.compress_min_bytes, ...boundsOf('webfetch.compress_min_bytes'))
wf.compress_bodies = envBool('TOKEN_GOAT_WEB_COMPRESS', wf.compress_bodies)
const wk_raw = section(raw, 'worker')
const wk = getDefaultConfig('worker') as WorkerConfig
wk.blocked_roots = validatedStrList(wk_raw['blocked_roots'], wk.blocked_roots)
wk.max_pool_workers = validatedInt(wk_raw['max_pool_workers'], wk.max_pool_workers, ...boundsOf('worker.max_pool_workers'))
wk.max_pool_workers = envInt('TOKEN_GOAT_WORKER_MAX_POOL', wk.max_pool_workers, ...boundsOf('worker.max_pool_workers'))
wk.embed_threads = validatedInt(wk_raw['embed_threads'], wk.embed_threads, ...boundsOf('worker.embed_threads'))
wk.embed_threads = envInt('TOKEN_GOAT_EMBED_THREADS', wk.embed_threads, ...boundsOf('worker.embed_threads'))
wk.priority = validatedStr(wk_raw['priority'], wk.priority)
wk.priority = envStr('TOKEN_GOAT_WORKER_PRIORITY', wk.priority)
const ix_raw = section(raw, 'indexing')
const ix = getDefaultConfig('indexing') as IndexingConfig
ix.large_file_symbol_only_kb = validatedInt(ix_raw['large_file_symbol_only_kb'], ix.large_file_symbol_only_kb, ...boundsOf('indexing.large_file_symbol_only_kb'))
ix.large_file_skip_kb = validatedInt(ix_raw['large_file_skip_kb'], ix.large_file_skip_kb, ...boundsOf('indexing.large_file_skip_kb'))
// A symbol-only threshold larger than the skip threshold is nonsensical: files would be skipped entirely before the symbol-only tier's condition could ever apply. Clamp symbol_only_kb so it never exceeds skip_kb.
ix.large_file_symbol_only_kb = Math.min(ix.large_file_symbol_only_kb, ix.large_file_skip_kb)
ix.max_chunks_per_file = validatedInt(ix_raw['max_chunks_per_file'], ix.max_chunks_per_file, ...boundsOf('indexing.max_chunks_per_file'))
ix.skip_dirs = validatedStrList(ix_raw['skip_dirs'], ix.skip_dirs)
ix.skip_files = validatedStrList(ix_raw['skip_files'], ix.skip_files)
ix.skip_minified = validatedBool(ix_raw['skip_minified'], ix.skip_minified)
ix.embeddings_enabled = validatedBool(ix_raw['embeddings_enabled'], ix.embeddings_enabled)
ix.embeddings_enabled = envBool('TOKEN_GOAT_EMBEDDINGS_ENABLED', ix.embeddings_enabled)
ix.cross_project_symbols = validatedBool(ix_raw['cross_project_symbols'], ix.cross_project_symbols)
ix.cross_project_symbols = envBool('TOKEN_GOAT_CROSS_PROJECT_SYMBOLS', ix.cross_project_symbols)
ix.max_db_size_mb = validatedInt(ix_raw['max_db_size_mb'], ix.max_db_size_mb, ...boundsOf('indexing.max_db_size_mb'))
ix.max_db_size_mb = envInt('TOKEN_GOAT_INDEXING_MAX_DB_SIZE_MB', ix.max_db_size_mb, ...boundsOf('indexing.max_db_size_mb'))
ix.auto_reclaim_embeddings = validatedBool(ix_raw['auto_reclaim_embeddings'], ix.auto_reclaim_embeddings)
ix.auto_reclaim_embeddings = envBool('TOKEN_GOAT_INDEXING_AUTO_RECLAIM_EMBEDDINGS', ix.auto_reclaim_embeddings)
const cpr_raw = section(raw, 'compression')
const cpr = getDefaultConfig('compression') as CompressionConfig
cpr.profile = validatedEnum('compression.profile', cpr_raw['profile'], cpr.profile)
cpr.profile = envEnum('compression.profile', 'TOKEN_GOAT_COMPRESS_PROFILE', cpr.profile)
const ctx_raw = section(raw, 'context')
const ctx = getDefaultConfig('context') as ContextConfig
ctx.model_window_tokens = validatedInt(ctx_raw['model_window_tokens'], ctx.model_window_tokens, ...boundsOf('context.model_window_tokens'))
ctx.model_window_tokens = envInt('TOKEN_GOAT_MODEL_WINDOW_TOKENS', ctx.model_window_tokens, ...boundsOf('context.model_window_tokens'))
const inj_raw = section(raw, 'injection')
const inj = getDefaultConfig('injection') as InjectionConfig
inj.enabled = validatedBool(inj_raw['enabled'], inj.enabled)
inj.enabled = envBool('TOKEN_GOAT_INJECTION_ENABLED', inj.enabled)
const gd_raw = section(raw, 'gdrive')
const gd = getDefaultConfig('gdrive') as GdriveConfig
gd.enabled = validatedBool(gd_raw['enabled'], gd.enabled)
gd.enabled = envBool('TOKEN_GOAT_GDRIVE_ENABLED', gd.enabled)
const red_raw = section(raw, 'redaction')
const red = getDefaultConfig('redaction') as RedactionConfig
red.custom_patterns = validatedStrList(red_raw['custom_patterns'], red.custom_patterns)
// Newline-separated, not comma-separated: a comma is how a regex writes a quantifier range, so splitting on it turned `EMP-[0-9]{4,8}` into `EMP-[0-9]{4` and `8}`. Both halves compile -- the braces degrade to literals -- so nothing failed and nothing was reported, and the operator's rule silently matched nothing. Found by an adversarial review.
red.custom_patterns = envStrList('TOKEN_GOAT_REDACTION_CUSTOM_PATTERNS', red.custom_patterns, '\n')
red.strict = validatedBool(red_raw['strict'], red.strict)
red.strict = envBool('TOKEN_GOAT_REDACTION_STRICT', red.strict)
const net_raw = section(raw, 'network')
const net = getDefaultConfig('network') as NetworkConfig
net.offline = validatedBool(net_raw['offline'], net.offline)
net.offline = envBool('TOKEN_GOAT_OFFLINE', net.offline)
const mcp_raw = section(raw, 'mcp')
const mcp = getDefaultConfig('mcp') as McpConfig
mcp.confine_reads_to_project_root = validatedBool(mcp_raw['confine_reads_to_project_root'], mcp.confine_reads_to_project_root)
mcp.confine_reads_to_project_root = envBool('TOKEN_GOAT_MCP_CONFINE_READS', mcp.confine_reads_to_project_root)
mcp.allowed_roots = validatedStrList(mcp_raw['allowed_roots'], mcp.allowed_roots)
// Delimiter-separated like PATH (';' on Windows, ':' elsewhere) so an operator writes the list the same way the platform already spells one. envStrList trims and drops blank entries, so a trailing or doubled delimiter cannot leave an empty-string root that matches nothing and reads as a silently broken allowlist.
mcp.allowed_roots = envStrList('TOKEN_GOAT_MCP_ALLOWED_ROOTS', mcp.allowed_roots, path.delimiter)
const hs_raw = section(raw, 'hint_stats')
const hs = getDefaultConfig('hint_stats') as HintStatsConfig
hs.suppress_threshold_pct = validatedInt(hs_raw['suppress_threshold_pct'], hs.suppress_threshold_pct, ...boundsOf('hint_stats.suppress_threshold_pct'))
// Absent from the file, the defiance ceiling is the complement of the suppress floor THIS file set, not the compiled 85. `pct < suppress_threshold_pct` and `100 - pct > 100 - suppress_threshold_pct` are the same predicate, so splitting one threshold into two leaves every operator's verdicts where they were, not only the shipped 15/85 pair. The complement of the default 15 is still 85, so nothing about the default moves. It has to be read after the line above: `hs.suppress_threshold_pct` is the compiled default until then. No extra clamp: 100 minus a 0..100 value is already in 0..100, and validatedInt bounds the result regardless.
hs.defiance_threshold_pct = validatedInt(hs_raw['defiance_threshold_pct'], 100 - hs.suppress_threshold_pct, ...boundsOf('hint_stats.defiance_threshold_pct'))
hs.defiance_threshold_pct = envInt('TOKEN_GOAT_HINT_DEFIANCE_THRESHOLD_PCT', hs.defiance_threshold_pct, ...boundsOf('hint_stats.defiance_threshold_pct'))
hs.min_sample_size = validatedInt(hs_raw['min_sample_size'], hs.min_sample_size, ...boundsOf('hint_stats.min_sample_size'))
const sem_raw = section(raw, 'semantic')
const sem = getDefaultConfig('semantic') as SemanticConfig
sem.archive_weight = validatedFloat(sem_raw['archive_weight'], sem.archive_weight, ...boundsOf('semantic.archive_weight'))
sem.docs_weight = validatedFloat(sem_raw['docs_weight'], sem.docs_weight, ...boundsOf('semantic.docs_weight'))
sem.max_distance = validatedFloat(sem_raw['max_distance'], sem.max_distance, ...boundsOf('semantic.max_distance'))
sem.weak_distance = validatedFloat(sem_raw['weak_distance'], sem.weak_distance, ...boundsOf('semantic.weak_distance'))
return {
compact_assist: ca,
bash_compress: bc,
agent_report: ar,
bash_diff: bd,
bash_severity_log: sl,
post_read_code_compress: cc,
session_brief: sb,
skill_preservation: sp,
image_shrink: is_cfg,
screenshot: sc_cfg,
repomap: rm,
overflow_guard: og,
hints: hi,
hooks: hk,
webfetch: wf,
worker: wk,
indexing: ix,
compression: cpr,
context: ctx,
injection: inj,
gdrive: gd,
redaction: red,
network: net,
mcp,
hint_stats: hs,
semantic: sem,
}
}
/** Maps each dotted config key that has an env-var override in {@link _buildConfig} to the TOKEN_GOAT_* env var name(s) that can override it, highest-precedence first. Used by `config set` (see cmdConfig in config_commands.ts) to warn when a value just written to config.toml is shadowed by an active env var. Keep in sync with the env-override assignments in _buildConfig. */
export const CONFIG_KEY_ENV_OVERRIDES: Readonly<Record<string, readonly string[]>> = {
'compact_assist.enabled': ['TOKEN_GOAT_COMPACT_ASSIST', 'TOKENWISE_COMPACT_ASSIST'],
'bash_compress.enabled': ['TOKEN_GOAT_BASH_COMPRESS'],
'bash_compress.cache_min_bytes': ['TOKEN_GOAT_BASH_CACHE_MIN_BYTES'],
'bash_compress.cache_max_file_count': ['TOKEN_GOAT_BASH_CACHE_MAX_FILES'],
'bash_compress.cache_max_bytes': ['TOKEN_GOAT_BASH_CACHE_MAX_BYTES'],
'bash_compress.cache_max_bytes_per_output': ['TOKEN_GOAT_BASH_CACHE_MAX_BYTES_PER_OUTPUT'],
'bash_compress.min_net_savings_bytes': ['TOKEN_GOAT_BASH_MIN_NET_SAVINGS_BYTES'],
'agent_report.min_bytes': ['TOKEN_GOAT_AGENT_REPORT_MIN_BYTES'],
'agent_report.fence_collapse_min_lines': ['TOKEN_GOAT_AGENT_REPORT_FENCE_MIN_LINES'],
'agent_report.fence_collapse_keep_lines': ['TOKEN_GOAT_AGENT_REPORT_FENCE_KEEP_LINES'],
'session_brief.enabled': ['TOKEN_GOAT_SESSION_BRIEF'],
'skill_preservation.enabled': ['TOKEN_GOAT_SKILL_PRESERVATION'],
'skill_preservation.compress_bodies': ['TOKEN_GOAT_SKILL_COMPRESS'],
'skill_preservation.pre_skill_enabled': ['TOKEN_GOAT_PRE_SKILL'],
'skill_preservation.orphan_sweep_enabled': ['TOKEN_GOAT_ORPHAN_SWEEP'],
'image_shrink.max_image_pixels': ['TOKEN_GOAT_MAX_IMAGE_PIXELS'],
'image_shrink.ocr_lang': ['TOKEN_GOAT_OCR_LANG'],
'image_shrink.vision_tier': ['TOKEN_GOAT_VISION_TIER'],
'screenshot.block_private_targets': ['TOKEN_GOAT_SCREENSHOT_BLOCK_PRIVATE_TARGETS'],
'repomap.compact_file_threshold': ['TOKEN_GOAT_REPOMAP_COMPACT_THRESHOLD'],
'repomap.exclude_tests': ['TOKEN_GOAT_REPOMAP_EXCLUDE_TESTS'],
'overflow_guard.enabled': ['TOKEN_GOAT_OVERFLOW_GUARD'],
'overflow_guard.max_tokens': ['TOKEN_GOAT_OVERFLOW_MAX_TOKENS'],
'hints.json_sidecar': ['TOKEN_GOAT_HINT_JSON_SIDECAR'],
'hints.bash_dedup_min_bytes': ['TOKEN_GOAT_BASH_DEDUP_MIN_BYTES'],
'hints.web_dedup_min_bytes': ['TOKEN_GOAT_WEB_DEDUP_MIN_BYTES'],
'hints.grep_dedup_min_matches': ['TOKEN_GOAT_GREP_DEDUP_MIN_MATCHES'],
'hints.glob_dedup_min_matches': ['TOKEN_GOAT_GLOB_DEDUP_MIN_MATCHES'],
'hints.write_rewrite_min_lines': ['TOKEN_GOAT_WRITE_REWRITE_MIN_LINES'],
'hints.write_rewrite_unchanged_pct': ['TOKEN_GOAT_WRITE_REWRITE_UNCHANGED_PCT'],
'hints.large_read_redirect_bytes': ['TOKEN_GOAT_LARGE_READ_BYTES'],
'hints.first_read_symbol_bytes': ['TOKEN_GOAT_FIRST_READ_SYMBOL_BYTES'],
'hints.first_read_symbol_policy': ['TOKEN_GOAT_FIRST_READ_SYMBOL_POLICY'],
'hints.write_blind_drop': ['TOKEN_GOAT_WRITE_BLIND_DROP'],
'hints.write_sibling_copy': ['TOKEN_GOAT_WRITE_SIBLING_COPY'],
'hints.warn_unbalanced_shell_quoting': ['TOKEN_GOAT_WARN_UNBALANCED_SHELL_QUOTING'],
'hints.deny_bash_double_backslash': ['TOKEN_GOAT_DENY_BASH_DOUBLE_BACKSLASH'],
'hints.serve_diff_on_reread': ['TOKEN_GOAT_SERVE_DIFF_ON_REREAD'],
'hints.elide_served_lines': ['TOKEN_GOAT_ELIDE_SERVED_LINES'],