- 1417
pub classify_model: Option<String>, - 1418
pub max_classify_usd: f64, - 1419
pub classify_timeout_secs: u64, - 1420
/// Standing delegation for this workspace. - 1421
pub autonomy: String, - 1422
pub evidence_max_age_secs: i64, - 1423
} - 1424
- 1425
/// Resolved durable-commitment policy. - 1426
#[derive(Debug, Clone, PartialEq)] - 1427
pub struct CommitmentResolved { - 1428
pub enabled: bool, - 1429
pub lifetime_budget_usd: Option<f64>, - 1430
pub stall_limit: u32, - 1431
pub review_every_hours: Option<u32>, - 1432
pub default_ttl_days: Option<u32>, - 1433
} - 1434
- 1435
#[derive(Debug, Clone, PartialEq, Eq)] - 1436
pub struct UiResolved { - 1437
/// Built-in theme name, or any name defined in `ui.themes`; unknown - 1438
/// values normalize to "dark". - 1439
pub theme: String, - 1440
pub bell: bool, - 1441
/// Keymap overrides merged project-over-user. - 1442
pub keymap: std::collections::BTreeMap<String, String>, - 1443
pub composer: String, - 1444
pub osc52: bool, - 1445
pub accessibility: AccessibilityResolved, - 1446
/// Custom theme definitions passed through to the UI layer. - 1447
pub themes: std::collections::BTreeMap<String, std::collections::BTreeMap<String, String>>, - 1448
} - 1449
- 1450
#[derive(Debug, Clone, PartialEq, Eq)] - 1451
pub struct AccessibilityResolved { - 1452
pub plain: bool, - 1453
pub reduced_motion: bool, - 1454
pub screen_reader: bool, - 1455
} - 1456
- 1457
/// Built-in premature-completion gate. On by default; conservative. - 1458
#[derive(Debug, Clone, PartialEq, Eq)] - 1459
pub struct StopPolicyResolved { - 1460
pub enabled: bool, - 1461
pub marker_gate: bool, - 1462
pub verify_gate: bool, - 1463
pub max_blocks: u32, - 1464
} - 1465
- 1466
/// Resolved gateway policy (docs/design/22-gateway.md). - 1467
#[derive(Debug, Clone, PartialEq, Eq)] - 1468
pub struct GatewayResolved { - 1469
pub enabled: bool, - 1470
pub approvals: String, - 1471
pub approver: Option<String>, - 1472
pub approval_timeout_secs: u64, - 1473
pub webhooks: std::collections::BTreeMap<String, WebhookResolved>, - 1474
pub rate_limit: Option<RateLimitSettings>, - 1475
/// Allowed inbound chat keys. Empty fails closed unless `chat_allowlist_open`. - 1476
pub chat_allowlist: Vec<String>, - 1477
/// Empty `chat_allowlist` was explicitly opted into staying open. - 1478
pub chat_allowlist_open: bool, - 1479
/// Process-wide cap on concurrently pooled per-workspace `Core` - 1480
/// instances (docs/design/34 Phase 2). Default 8. - 1481
pub core_pool_max: usize, - 1482
/// Idle duration after which a pooled non-default-workspace `Core` is - 1483
/// evicted. Default 1800s (30 minutes). - 1484
pub core_pool_idle_secs: u64, - 1485
/// Days a `pending` allowlist entry may sit unreviewed before it is - 1486
/// flagged by doctor and auto-denied by `--repair`. Default 7. - 1487
pub pending_expiry_days: u64, - 1488
} - 1489
- 1490
#[derive(Debug, Clone, PartialEq, Eq)] - 1491
pub struct SandboxResolved { - 1492
pub backend: String, - 1493
pub image: Option<String>, - 1494
} - 1495
- 1496
#[derive(Debug, Clone, PartialEq, Eq)] - 1497
pub struct WebhookResolved { - 1498
pub url: String, - 1499
pub token_env: Option<String>, - 1500
} - 1501
- 1502
/// Resolved memory policy (docs/design/23-memory.md). - 1503
#[derive(Debug, Clone, PartialEq, Eq)] - 1504
pub struct MemoryResolved { - 1505
pub search_enabled: bool, - 1506
pub write_enabled: bool, - 1507
pub skill_proposals: bool, - 1508
pub reflection: bool, - 1509
} - 1510
- 1511
/// Resolved scheduled-task behavior (docs/design/29-personal-os.md P2). - 1512
#[derive(Debug, Clone, PartialEq, Eq)] - 1513
pub struct AutomationResolved { - 1514
pub catch_up_missed: bool, - 1515
} - 1516
- 1517
/// Resolved update-check policy (docs/design/29-personal-os.md P3). - 1518
#[derive(Debug, Clone, PartialEq, Eq)] - 1519
pub struct UpdateResolved { - 1520
pub url: Option<String>, - 1521
pub interval_hours: u64, - 1522
} - 1523
- 1524
/// Resolved optional-tool registration policy. - 1525
#[derive(Debug, Clone, PartialEq, Eq)] - 1526
pub struct ToolsResolved { - 1527
pub web_fetch: bool, - 1528
pub browse: bool, - 1529
} - 1530
- 1531
/// Resolved native-Ollama tuning (docs/design/68-context-engine.md §8). - 1532
#[derive(Debug, Clone, PartialEq, Eq)] - 1533
pub struct OllamaResolved { - 1534
pub keep_alive: String, - 1535
pub num_ctx: Option<u64>, - 1536
} - 1537
- 1538
/// Resolved Anthropic tuning (docs/design/68-context-engine.md §11). - 1539
#[derive(Debug, Clone, PartialEq, Eq)] - 1540
pub struct AnthropicResolved { - 1541
pub fast_mode: bool, - 1542
} - 1543
- 1544
impl Default for Config { - 1545
fn default() -> Self { - 1546
Config { - 1547
provider: "anthropic".into(), - 1548
model: "claude-sonnet-4-5".into(), - 1549
max_tokens: 8192, - 1550
max_turns: 40, - 1551
permission_mode: PermissionMode::WorkspaceWrite, - 1552
approval_mode: ApprovalMode::Ask, - 1553
anthropic_base_url: None, - 1554
allow: Vec::new(), - 1555
ask: Vec::new(), - 1556
deny: Vec::new(), - 1557
workers: true, - 1558
hooks: Vec::new(), - 1559
max_retries: 3, - 1560
retry_base_backoff_ms: 500, - 1561
request_timeout_secs: 600, - 1562
run_retry_attempts: 6, - 1563
run_retry_base_backoff_ms: 2_000, - 1564
circuit_breaker_threshold: 5, - 1565
circuit_breaker_cooldown_secs: 60, - 1566
context_window: 128_000, - 1567
mcp: McpConfig::default(), - 1568
capabilities: CapabilityInheritanceResolved { - 1569
inherit_mcp: true, - 1570
inherit_hooks: true, - 1571
inherit_skills: true, - 1572
inherit_commands: true, - 1573
inherit_plugins: true, - 1574
}, - 1575
ui: UiResolved { - 1576
theme: "dark".into(), - 1577
bell: true, - 1578
keymap: std::collections::BTreeMap::new(), - 1579
composer: "emacs".into(), - 1580
osc52: false, - 1581
accessibility: AccessibilityResolved { - 1582
plain: false, - 1583
reduced_motion: false, - 1584
screen_reader: false, - 1585
}, - 1586
themes: std::collections::BTreeMap::new(), - 1587
}, - 1588
stop_policy: StopPolicyResolved { - 1589
enabled: true, - 1590
marker_gate: true, - 1591
verify_gate: true, - 1592
max_blocks: 2, - 1593
}, - 1594
finops: FinopsResolved::default(), - 1595
goal: GoalResolved { - 1596
handoff_reset: true, - 1597
max_audit_blocks: 2, - 1598
}, - 1599
work: WorkResolved { - 1600
enabled: true, - 1601
default_mode: "direct".into(), - 1602
max_items: 20, - 1603
max_revisions: 8, - 1604
max_parallel: 4, - 1605
confirmation: "risk-based".into(), - 1606
}, - 1607
route: RouteResolved { - 1608
objective: "auto".into(), - 1609
fallback_models: Vec::new(), - 1610
max_fallbacks: 4, - 1611
quality_hints: Vec::new(), - 1612
modality_hints: Vec::new(), - 1613
}, - 1614
probe: ProbeResolved { - 1615
hosted: "none".into(), - 1616
}, - 1617
intent: IntentResolved { - 1618
enabled: true, - 1619
accept_confidence: 0.75, - 1620
provisional_confidence: 0.45, - 1621
slice_capabilities: true, - 1622
posture: true, - 1623
// Deterministic tiers only by default. A paid classification - 1624
// before the run the user actually asked for is a real cost - 1625
// and a real latency, so it is opt-in. - 1626
escalate: "none".into(), - 1627
classify_model: None, - 1628
max_classify_usd: 0.01, - 1629
classify_timeout_secs: 10, - 1630
autonomy: "assisted".into(), - 1631
evidence_max_age_secs: 86_400, - 1632
}, - 1633
commitment: CommitmentResolved { - 1634
enabled: true, - 1635
lifetime_budget_usd: None, - 1636
stall_limit: 3, - 1637
review_every_hours: None, - 1638
default_ttl_days: None, - 1639
}, - 1640
automation: AutomationResolved { - 1641
catch_up_missed: true, - 1642
}, - 1643
update: UpdateResolved { - 1644
url: None, - 1645
interval_hours: 24, - 1646
}, - 1647
tools: ToolsResolved { - 1648
web_fetch: true, - 1649
browse: true, - 1650
}, - 1651
heartbeat: HeartbeatResolved { - 1652
enabled: false, - 1653
interval_secs: 1800, - 1654
model: None, - 1655
quiet_hours: None, - 1656
max_findings: 3, - 1657
}, - 1658
gateway: GatewayResolved { - 1659
enabled: false, - 1660
approvals: "deny".into(), - 1661
approver: None, - 1662
approval_timeout_secs: 300, - 1663
webhooks: std::collections::BTreeMap::new(), - 1664
rate_limit: None, - 1665
chat_allowlist: Vec::new(), - 1666
chat_allowlist_open: false, - 1667
core_pool_max: 8, - 1668
core_pool_idle_secs: 1800, - 1669
pending_expiry_days: 7, - 1670
}, - 1671
memory: MemoryResolved { - 1672
search_enabled: true, - 1673
write_enabled: true, - 1674
skill_proposals: true, - 1675
reflection: false, - 1676
}, - 1677
sandbox: SandboxResolved { - 1678
backend: "auto".into(), - 1679
image: None, - 1680
}, - 1681
feeds: FeedResolved { - 1682
enabled: false, - 1683
config_path: None, - 1684
db_path: None, - 1685
default_check_interval: "30m".into(), - 1686
max_items_per_feed: 500, - 1687
dedup_window_days: 90, - 1688
}, - 1689
server: ServerResolved { - 1690
// Loopback, no trusted hosts, no terminal over the web: a - 1691
// default install is reachable only from the machine it runs - 1692
// on, and every step away from that is deliberate. - 1693
bind: "127.0.0.1".into(), - 1694
trusted_hosts: Vec::new(), - 1695
public_url: None, - 1696
session_ttl_hours: 168, - 1697
loopback_auto_login: true, - 1698
workspace_roots: Vec::new(), - 1699
web_terminal: false, - 1700
web_terminal_requires_loopback: true, - 1701
bus: BusResolved::default(), - 1702
}, - 1703
plugins: PluginResolved::default(), - 1704
voice: VoiceSettings::default(), - 1705
ollama: OllamaResolved { - 1706
keep_alive: "30m".into(), - 1707
num_ctx: None, - 1708
}, - 1709
anthropic: AnthropicResolved { fast_mode: false }, - 1710
warnings: Vec::new(), - 1711
} - 1712
} - 1713
} - 1714
- 1715
#[derive(Debug, thiserror::Error)] - 1716
pub enum ConfigError { - 1717
#[error("cannot read config file {path}: {source}")] - 1718
Read { - 1719
path: PathBuf, - 1720
source: std::io::Error, - 1721
}, - 1722
#[error("cannot parse config file {path}: {source}")] - 1723
Parse { - 1724
path: PathBuf, - 1725
source: toml::de::Error, - 1726
}, - 1727
#[error("cannot write config file {path}: {source}")] - 1728
Write { - 1729
path: PathBuf, - 1730
source: std::io::Error, - 1731
}, - 1732
} - 1733
- 1734
/// The topmost editable configuration layer. `vak-home` is deliberately a - 1735
/// normal workspace people can inspect, and every other workspace inherits - 1736
/// this file without copying it. - 1737
pub fn global_path() -> Option<PathBuf> { - 1738
Some(crate::paths::default_workspace().join(".vak/config.toml")) - 1739
} - 1740
- 1741
pub fn project_path(cwd: &Path) -> PathBuf { - 1742
cwd.join(".vak/config.toml") - 1743
} - 1744
- 1745
/// Cheap, stat-only "has anything changed" signal for the global + project - 1746
/// config layers. Callers that hold a resolved value derived from these - 1747
/// files (e.g. `Core`'s cached `RouteSelection`) can compare fingerprints on - 1748
/// every access instead of re-parsing TOML, and only pay for a full re-load - 1749
/// when this value actually moves (docs/design/44-shared-config.md, - 1750
/// "Liveness"). - 1751
pub fn config_fingerprint(cwd: &Path) -> u64 { - 1752
let mut hash = 0xcbf29ce484222325_u64; - 1753
for path in [global_path(), Some(project_path(cwd))] - 1754
.into_iter() - 1755
.flatten() - 1756
{ - 1757
let (mtime_nanos, len) = std::fs::metadata(&path) - 1758
.and_then(|m| m.modified().map(|t| (t, m.len()))) - 1759
.map(|(t, len)| { - 1760
let nanos = t - 1761
.duration_since(std::time::UNIX_EPOCH) - 1762
.map(|d| d.as_nanos() as u64) - 1763
.unwrap_or(0); - 1764
(nanos, len) - 1765
}) - 1766
.unwrap_or((0, 0)); - 1767
for byte in mtime_nanos - 1768
.to_le_bytes() - 1769
.into_iter() - 1770
.chain(len.to_le_bytes()) - 1771
{ - 1772
hash ^= u64::from(byte); - 1773
hash = hash.wrapping_mul(0x100000001b3); - 1774
} - 1775
} - 1776
hash - 1777
} - 1778
- 1779
/// Initialize the project layer used by interactive clients. - 1780
/// - 1781
/// The file intentionally contains no copied global values. An empty project - 1782
/// layer inherits the user's global configuration through [`load_with_trust`], - 1783
/// so later changes to shared defaults reach projects that have not opted into - 1784
/// a local override. `create_new` also keeps two desktop launches from - 1785
/// overwriting a project config created by the other launch. - 1786
pub fn ensure_project_config(cwd: &Path) -> Result<PathBuf, ConfigError> { - 1787
let dir = cwd.join(".vak"); - 1788
std::fs::create_dir_all(&dir).map_err(|source| ConfigError::Write { - 1789
path: dir.clone(), - 1790
source, - 1791
})?; - 1792
let path = project_path(cwd); - 1793
let _guard = lock_config_files(); - 1794
match std::fs::OpenOptions::new() - 1795
.write(true) - 1796
.create_new(true) - 1797
.open(&path) - 1798
{ - 1799
Ok(mut file) => { - 1800
use std::io::Write; - 1801
file.write_all( - 1802
b"# Project-local overrides. Unset values inherit from the user config.\n", - 1803
) - 1804
.map_err(|source| ConfigError::Write { - 1805
path: path.clone(), - 1806
source, - 1807
})?; - 1808
} - 1809
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} - 1810
Err(source) => { - 1811
return Err(ConfigError::Write { - 1812
path: path.clone(), - 1813
source, - 1814
}); - 1815
} - 1816
} - 1817
Ok(path) - 1818
} - 1819
- 1820
/// Atomically replace the set of MCP servers at one explicit configuration - 1821
/// scope. The caller selects either [`global_path`] or [`project_path`]; no - 1822
/// values are inferred from the process directory. A server missing from - 1823
/// `servers` is removed; a server that stays keeps every key the management - 1824
/// API does not own, and every other key in the file is preserved. - 1825
pub fn persist_mcp_servers( - 1826
path: &Path, - 1827
servers: &std::collections::BTreeMap<String, McpServerConfig>, - 1828
) -> Result<(), ConfigError> { - 1829
update_config_file(path, |document| { - 1830
let mcp = child_table(document, "mcp", path)?; - 1831
let mut existing = match mcp.remove("servers") { - 1832
Some(toml::Value::Table(existing)) => existing, - 1833
_ => toml::Table::new(), - 1834
}; - 1835
let entries = servers - 1836
.iter() - 1837
.map(|(name, server)| { - 1838
let mut entry = match existing.remove(name) { - 1839
Some(toml::Value::Table(entry)) => entry, - 1840
_ => toml::Table::new(), - 1841
}; - 1842
write_mcp_server(&mut entry, server); - 1843
(name.clone(), toml::Value::Table(entry)) - 1844
}) - 1845
.collect(); - 1846
mcp.insert("servers".into(), toml::Value::Table(entries)); - 1847
Ok(()) - 1848
}) - 1849
} - 1850
- 1851
/// Add, replace (`Some`) or remove (`None`) the one MCP server `name` at one - 1852
/// explicit configuration scope, leaving every other server as the file has - 1853
/// it. The read happens under the same lock as the write, so a change made - 1854
/// to another server in the meantime is not lost to a stale copy. - 1855
pub fn persist_mcp_server( - 1856
path: &Path, - 1857
name: &str, - 1858
server: Option<&McpServerConfig>, - 1859
) -> Result<(), ConfigError> { - 1860
update_config_file(path, |document| { - 1861
match server { - 1862
Some(server) => { - 1863
let servers = child_table(child_table(document, "mcp", path)?, "servers", path)?; - 1864
write_mcp_server(child_table(servers, name, path)?, server); - 1865
} - 1866
None => { - 1867
if let Some(servers) = document - 1868
.get_mut("mcp") - 1869
.and_then(toml::Value::as_table_mut) - 1870
.and_then(|mcp| mcp.get_mut("servers")) - 1871
.and_then(toml::Value::as_table_mut) - 1872
{ - 1873
servers.remove(name); - 1874
} - 1875
} - 1876
} - 1877
Ok(()) - 1878
}) - 1879
} - 1880
- 1881
/// Write the keys the management API owns onto one `[mcp.servers.<name>]` - 1882
/// entry. Any other key there — `serves`, which no API sets, or one this - 1883
/// version does not know — stays as the file had it; `serves` is written - 1884
/// only when the caller declares it. - 1885
fn write_mcp_server(entry: &mut toml::Table, server: &McpServerConfig) { - 1886
let strings = |values: &[String]| { - 1887
toml::Value::Array(values.iter().cloned().map(toml::Value::String).collect()) - 1888
}; - 1889
entry.insert( - 1890
"command".into(), - 1891
toml::Value::String(server.command.clone()), - 1892
); - 1893
entry.insert("args".into(), strings(&server.args)); - 1894
if server.env.is_empty() { - 1895
entry.remove("env"); - 1896
} else { - 1897
entry.insert( - 1898
"env".into(), - 1899
toml::Value::Table( - 1900
server - 1901
.env - 1902
.iter() - 1903
.map(|(key, value)| (key.clone(), toml::Value::String(value.clone()))) - 1904
.collect(), - 1905
), - 1906
); - 1907
} - 1908
if server.network { - 1909
entry.insert("network".into(), toml::Value::Boolean(true)); - 1910
} else { - 1911
entry.remove("network"); - 1912
} - 1913
if !server.serves.is_empty() { - 1914
entry.insert("serves".into(), strings(&server.serves)); - 1915
} - 1916
} - 1917
- 1918
/// Persist project capability inheritance switches without materializing any - 1919
/// inherited definitions into the project file. - 1920
pub fn persist_capability_inheritance( - 1921
path: &Path, - 1922
inherit_mcp: Option<bool>, - 1923
inherit_hooks: Option<bool>, - 1924
inherit_skills: Option<bool>, - 1925
inherit_commands: Option<bool>, - 1926
inherit_plugins: Option<bool>, - 1927
) -> Result<(), ConfigError> { - 1928
update_config_file(path, |document| { - 1929
let capabilities = child_table(document, "capabilities", path)?; - 1930
for (name, value) in [ - 1931
("inherit_mcp", inherit_mcp), - 1932
("inherit_hooks", inherit_hooks), - 1933
("inherit_skills", inherit_skills), - 1934
("inherit_commands", inherit_commands), - 1935
("inherit_plugins", inherit_plugins), - 1936
] { - 1937
if let Some(value) = value { - 1938
capabilities.insert(name.into(), toml::Value::Boolean(value)); - 1939
} - 1940
} - 1941
Ok(()) - 1942
}) - 1943
} - 1944
- 1945
/// Persist user-selected agent preferences without disturbing unrelated - 1946
/// project configuration. The write is atomic so every client sees either - 1947
/// the old or the new complete document, never a partial TOML file. - 1948
pub fn persist_project_preferences( - 1949
cwd: &Path, - 1950
provider: Option<&str>, - 1951
model: Option<&str>, - 1952
max_turns: Option<usize>, - 1953
permission_mode: Option<PermissionMode>, - 1954
approval_mode: Option<ApprovalMode>, - 1955
theme: Option<&str>, - 1956
) -> Result<(), ConfigError> { - 1957
persist_preferences_at( - 1958
project_path(cwd), - 1959
provider, - 1960
model, - 1961
max_turns, - 1962
permission_mode, - 1963
approval_mode, - 1964
theme, - 1965
) - 1966
} - 1967
- 1968
/// Persist user-level defaults. Project configurations inherit these values - 1969
/// through [`load_with_trust`] until they set their own scoped override. - 1970
pub fn persist_global_preferences( - 1971
provider: Option<&str>, - 1972
model: Option<&str>, - 1973
max_turns: Option<usize>, - 1974
permission_mode: Option<PermissionMode>, - 1975
approval_mode: Option<ApprovalMode>, - 1976
theme: Option<&str>, - 1977
) -> Result<(), ConfigError> { - 1978
let path = global_path().ok_or_else(|| ConfigError::Write { - 1979
path: PathBuf::from("<user-config>"), - 1980
source: std::io::Error::other("user home is unavailable"), - 1981
})?; - 1982
persist_preferences_at( - 1983
path, - 1984
provider, - 1985
model, - 1986
max_turns, - 1987
permission_mode, - 1988
approval_mode, - 1989
theme, - 1990
) - 1991
} - 1992
- 1993
/// Persist preferences to an explicitly chosen layer file. - 1994
/// - 1995
/// The project and global wrappers above cover the two named scopes; this - 1996
/// takes the path directly, for a caller that has already resolved which - 1997
/// layer it means (`vak config set-mode --scope`). - 1998
pub fn persist_preferences_to( - 1999
path: PathBuf, - 2000
provider: Option<&str>, - 2001
model: Option<&str>, - 2002
max_turns: Option<usize>, - 2003
permission_mode: Option<PermissionMode>, - 2004
approval_mode: Option<ApprovalMode>, - 2005
theme: Option<&str>, - 2006
) -> Result<(), ConfigError> { - 2007
persist_preferences_at( - 2008
path, - 2009
provider, - 2010
model, - 2011
max_turns, - 2012
permission_mode, - 2013
approval_mode, - 2014
theme, - 2015
) - 2016
} - 2017
- 2018
fn persist_preferences_at( - 2019
path: PathBuf, - 2020
provider: Option<&str>, - 2021
model: Option<&str>, - 2022
max_turns: Option<usize>, - 2023
permission_mode: Option<PermissionMode>, - 2024
approval_mode: Option<ApprovalMode>, - 2025
theme: Option<&str>, - 2026
) -> Result<(), ConfigError> { - 2027
update_config_file(&path, |document| { - 2028
if let Some(value) = provider { - 2029
document.insert("provider".into(), toml::Value::String(value.into())); - 2030
} - 2031
if let Some(value) = model { - 2032
document.insert("model".into(), toml::Value::String(value.into())); - 2033
} - 2034
if let Some(value) = max_turns { - 2035
document.insert("max_turns".into(), toml::Value::Integer(value as i64)); - 2036
} - 2037
if let Some(value) = permission_mode { - 2038
document.insert( - 2039
"permission_mode".into(), - 2040
toml::Value::String(value.as_str().into()), - 2041
); - 2042
} - 2043
if let Some(value) = approval_mode { - 2044
document.insert( - 2045
"approval_mode".into(), - 2046
toml::Value::String(value.as_str().into()), - 2047
); - 2048
} - 2049
if let Some(value) = theme { - 2050
child_table(document, "ui", &path)? - 2051
.insert("theme".into(), toml::Value::String(value.into())); - 2052
} - 2053
Ok(()) - 2054
}) - 2055
} - 2056
- 2057
/// Persist the evidence freshness policy in exactly one configuration layer. - 2058
pub fn persist_evidence_max_age(path: PathBuf, seconds: i64) -> Result<(), ConfigError> { - 2059
update_config_file(&path, |document| { - 2060
child_table(document, "intent", &path)?.insert( - 2061
"evidence_max_age_secs".into(), - 2062
toml::Value::Integer(seconds.max(0)), - 2063
); - 2064
Ok(()) - 2065
}) - 2066
} - 2067
- 2068
/// Changes the project's `[server.bus]` settings (the NATS URL and the name - 2069
/// of the workspace-secret variable), leaving the rest of the file as it - 2070
/// was: `None` leaves a key alone, `Some(None)` or an empty value removes - 2071
/// it, `Some(Some(value))` sets it. The bus's secrets never go here. - 2072
pub fn persist_bus_settings( - 2073
path: PathBuf, - 2074
nats_url: Option<Option<&str>>, - 2075
workspace_secret_env: Option<Option<&str>>, - 2076
) -> Result<(), ConfigError> { - 2077
update_config_file(&path, |document| { - 2078
let bus = child_table(child_table(document, "server", &path)?, "bus", &path)?; - 2079
for (key, change) in [ - 2080
("nats_url", nats_url), - 2081
("workspace_secret_env", workspace_secret_env), - 2082
] { - 2083
let Some(value) = change else { - 2084
continue; - 2085
}; - 2086
match value.map(str::trim).filter(|value| !value.is_empty()) { - 2087
Some(value) => { - 2088
bus.insert(key.into(), toml::Value::String(value.to_string())); - 2089
} - 2090
None => { - 2091
bus.remove(key); - 2092
} - 2093
} - 2094
} - 2095
Ok(()) - 2096
}) - 2097
} - 2098
- 2099
/// Persist `[memory]` toggles for the current project without disturbing - 2100
/// unrelated config (docs/design/23-memory.md). Mirrors - 2101
/// [`persist_project_preferences`]'s atomic-write shape exactly. - 2102
pub fn persist_project_memory_prefs( - 2103
cwd: &Path, - 2104
search_enabled: Option<bool>, - 2105
write_enabled: Option<bool>, - 2106
reflection: Option<bool>, - 2107
skill_proposals: Option<bool>, - 2108
) -> Result<(), ConfigError> { - 2109
persist_memory_prefs_at( - 2110
project_path(cwd), - 2111
search_enabled, - 2112
write_enabled, - 2113
reflection, - 2114
skill_proposals, - 2115
) - 2116
} - 2117
- 2118
/// Persist user-level `[memory]` defaults, inherited by project configs - 2119
/// through [`load_with_trust`] until they set their own scoped override. - 2120
pub fn persist_global_memory_prefs( - 2121
search_enabled: Option<bool>, - 2122
write_enabled: Option<bool>, - 2123
reflection: Option<bool>, - 2124
skill_proposals: Option<bool>, - 2125
) -> Result<(), ConfigError> { - 2126
let path = global_path().ok_or_else(|| ConfigError::Write { - 2127
path: PathBuf::from("<user-config>"), - 2128
source: std::io::Error::other("user home is unavailable"), - 2129
})?; - 2130
persist_memory_prefs_at( - 2131
path, - 2132
search_enabled, - 2133
write_enabled, - 2134
reflection, - 2135
skill_proposals, - 2136
) - 2137
} - 2138
- 2139
fn persist_memory_prefs_at( - 2140
path: PathBuf, - 2141
search_enabled: Option<bool>, - 2142
write_enabled: Option<bool>, - 2143
reflection: Option<bool>, - 2144
skill_proposals: Option<bool>, - 2145
) -> Result<(), ConfigError> { - 2146
update_config_file(&path, |document| { - 2147
if search_enabled.is_some() - 2148
|| write_enabled.is_some() - 2149
|| reflection.is_some() - 2150
|| skill_proposals.is_some() - 2151
{ - 2152
let memory = child_table(document, "memory", &path)?; - 2153
if let Some(value) = search_enabled { - 2154
memory.insert("search_enabled".into(), toml::Value::Boolean(value)); - 2155
} - 2156
if let Some(value) = write_enabled { - 2157
memory.insert("write_enabled".into(), toml::Value::Boolean(value)); - 2158
} - 2159
if let Some(value) = reflection { - 2160
memory.insert("reflection".into(), toml::Value::Boolean(value)); - 2161
} - 2162
if let Some(value) = skill_proposals { - 2163
memory.insert("skill_proposals".into(), toml::Value::Boolean(value)); - 2164
} - 2165
} - 2166
Ok(()) - 2167
}) - 2168
} - 2169
- 2170
/// Persist `[gateway] approvals` / `approver` without disturbing unrelated - 2171
/// config keys. - 2172
/// - 2173
/// This is the one setting that decides whether an `Ask` raised on an - 2174
/// unattended chat surface reaches a human at all: with `approvals = - 2175
/// "deny"` every gate is a foregone denial, `GatewayApprover::answerable()` - 2176
/// is false, and `vak_core::reach` correctly strips every gated capability - 2177
/// from the turn before the prompt is composed. It had no writer on any - 2178
/// surface — the remedy `reach` prints named an action nothing could - 2179
/// perform — so an operator's only route was editing this file by hand. - 2180
/// - 2181
/// `approver` is `Option<Option<String>>`: absent leaves it alone, `Some(None)` - 2182
/// clears it back to unset, `Some(Some(t))` pins the target. The - 2183
/// forward-requires-an-approver rule is NOT enforced here; it lives in - 2184
/// [`load_with_trust`], which is what every reader goes through, and - 2185
/// duplicating it would be a second contract that must agree forever. - 2186
/// Callers that want to reject the combination up front should check it - 2187
/// themselves and say so — writing a `forward` with no target simply - 2188
/// resolves back to `deny` with a warning, which is safe. - 2189
pub fn persist_gateway_approvals( - 2190
path: PathBuf, - 2191
approvals: Option<&str>, - 2192
approver: Option<Option<&str>>, - 2193
approval_timeout_secs: Option<u64>, - 2194
) -> Result<(), ConfigError> { - 2195
persist_gateway_approvals_at(path, approvals, approver, approval_timeout_secs) - 2196
} - 2197
- 2198
fn persist_gateway_approvals_at( - 2199
path: PathBuf, - 2200
approvals: Option<&str>, - 2201
approver: Option<Option<&str>>, - 2202
approval_timeout_secs: Option<u64>, - 2203
) -> Result<(), ConfigError> { - 2204
update_config_file(&path, |document| { - 2205
if approvals.is_some() || approver.is_some() || approval_timeout_secs.is_some() { - 2206
let gateway = child_table(document, "gateway", &path)?; - 2207
if let Some(value) = approvals { - 2208
gateway.insert("approvals".into(), toml::Value::String(value.into())); - 2209
} - 2210
match approver { - 2211
None => {} - 2212
Some(None) => { - 2213
gateway.remove("approver"); - 2214
} - 2215
Some(Some(target)) => { - 2216
gateway.insert("approver".into(), toml::Value::String(target.into())); - 2217
} - 2218
} - 2219
if let Some(value) = approval_timeout_secs { - 2220
gateway.insert( - 2221
"approval_timeout_secs".into(), - 2222
toml::Value::Integer(value as i64), - 2223
); - 2224
} - 2225
} - 2226
Ok(()) - 2227
}) - 2228
} - 2229
- 2230
/// Held by every write to a configuration file in this process, from the - 2231
/// read to the rename. One lock for every path rather than one per path: - 2232
/// the same file is reachable under more than one spelling (the default - 2233
/// workspace's project layer *is* the Shared layer), and a per-path lock - 2234
/// would first have to agree which spellings name one file. Configuration - 2235
/// writes are rare and small, so nothing waits on it for long. - 2236
static CONFIG_FILE_LOCK: Mutex<()> = Mutex::new(()); - 2237
- 2238
fn lock_config_files() -> MutexGuard<'static, ()> { - 2239
CONFIG_FILE_LOCK - 2240
.lock() - 2241
.unwrap_or_else(std::sync::PoisonError::into_inner) - 2242
} - 2243
- 2244
/// The one way a configuration file is rewritten: under - 2245
/// [`CONFIG_FILE_LOCK`], read the document at `path` (a missing file is an - 2246
/// empty one), let `edit` change it, and atomically replace the file with - 2247
/// the result. - 2248
/// - 2249
/// Holding the lock from the read to the rename is what stops two settings - 2250
/// saved at the same moment from each rewriting the file from a read taken - 2251
/// before the other one landed. The document is edited as a raw TOML table, - 2252
/// so a key this version does not know is written back as it was read - 2253
/// (invariant 29). An edit that changes nothing writes nothing. `edit` must - 2254
/// not call another configuration writer: the lock is not reentrant. - 2255
fn update_config_file<T>( - 2256
path: &Path, - 2257
edit: impl FnOnce(&mut toml::Table) -> Result<T, ConfigError>, - 2258
) -> Result<T, ConfigError> { - 2259
let _guard = lock_config_files(); - 2260
let before = match std::fs::read_to_string(path) { - 2261
Ok(text) => toml::from_str::<toml::Table>(&text).map_err(|source| ConfigError::Parse { - 2262
path: path.to_path_buf(), - 2263
source, - 2264
})?, - 2265
Err(error) if error.kind() == std::io::ErrorKind::NotFound => toml::Table::new(), - 2266
Err(source) => { - 2267
return Err(ConfigError::Read { - 2268
path: path.to_path_buf(), - 2269
source, - 2270
}); - 2271
} - 2272
}; - 2273
let mut document = before.clone(); - 2274
let outcome = edit(&mut document)?; - 2275
if document != before { - 2276
let text = toml::to_string_pretty(&document).map_err(|error| ConfigError::Write { - 2277
path: path.to_path_buf(), - 2278
source: std::io::Error::other(error.to_string()), - 2279
})?; - 2280
replace_file(path, &text)?; - 2281
} - 2282
Ok(outcome) - 2283
} - 2284
- 2285
/// Write `contents` to a new sibling of `path` and rename it over `path`, so - 2286
/// a reader sees the whole old document or the whole new one. The temporary - 2287
/// name carries the process id and a per-process sequence number, and is - 2288
/// created exclusively, so no two writes ever share one. - 2289
fn replace_file(path: &Path, contents: &str) -> Result<(), ConfigError> { - 2290
static SEQUENCE: AtomicU64 = AtomicU64::new(0); - 2291
let write_error = |source| ConfigError::Write { - 2292
path: path.to_path_buf(), - 2293
source, - 2294
}; - 2295
let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else { - 2296
return Err(write_error(std::io::Error::other( - 2297
"config path has no parent directory", - 2298
))); - 2299
}; - 2300
std::fs::create_dir_all(parent).map_err(|source| ConfigError::Write { - 2301
path: parent.to_path_buf(), - 2302
source, - 2303
})?; - 2304
let mut attempts = 0; - 2305
let (temp, mut file) = loop { - 2306
let temp = parent.join(format!( - 2307
".{}.{}.{}.tmp", - 2308
name.to_string_lossy(), - 2309
std::process::id(), - 2310
SEQUENCE.fetch_add(1, Ordering::Relaxed) - 2311
)); - 2312
match std::fs::OpenOptions::new() - 2313
.write(true) - 2314
.create_new(true) - 2315
.open(&temp) - 2316
{ - 2317
Ok(file) => break (temp, file), - 2318
// Only another process that had this pid can hold a fresh name; - 2319
// step past its file rather than write into it. - 2320
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists && attempts < 8 => { - 2321
attempts += 1; - 2322
} - 2323
Err(source) => return Err(write_error(source)), - 2324
} - 2325
}; - 2326
let written = std::io::Write::write_all(&mut file, contents.as_bytes()); - 2327
drop(file); - 2328
written - 2329
.and_then(|()| std::fs::rename(&temp, path)) - 2330
.map_err(|source| { - 2331
let _ = std::fs::remove_file(&temp); - 2332
write_error(source) - 2333
}) - 2334
} - 2335
- 2336
/// The table under `key`, created empty when absent. A key that holds some - 2337
/// other kind of value is refused rather than overwritten. - 2338
fn child_table<'a>( - 2339
parent: &'a mut toml::Table, - 2340
key: &str, - 2341
path: &Path, - 2342
) -> Result<&'a mut toml::Table, ConfigError> { - 2343
parent - 2344
.entry(key) - 2345
.or_insert_with(|| toml::Value::Table(toml::Table::new())) - 2346
.as_table_mut() - 2347
.ok_or_else(|| ConfigError::Write { - 2348
path: path.to_path_buf(), - 2349
source: std::io::Error::other(format!("`{key}` config must be a TOML table")), - 2350
}) - 2351
} - 2352
- 2353
/// Persist the three permission rule lists (`allow` / `ask` / `deny`) as - 2354
/// the engine reads them, without disturbing unrelated config keys. - 2355
/// - 2356
/// Each list is `Option`: absent leaves that list alone, `Some(vec)` - 2357
/// replaces it wholesale (an empty vec clears it). - 2358
/// - 2359
/// Rule SYNTAX is not validated here on purpose: the grammar lives in - 2360
/// `vak_permission::Rule::parse`, which this crate sits below and must not - 2361
/// depend on. Callers parse every spec before calling — a second grammar - 2362
/// here would be two definitions of a rule that must agree forever. - 2363
pub fn persist_permission_rules( - 2364
path: PathBuf, - 2365
allow: Option<&[String]>, - 2366
ask: Option<&[String]>, - 2367
deny: Option<&[String]>, - 2368
) -> Result<(), ConfigError> { - 2369
update_config_file(&path, |document| { - 2370
for (key, list) in [("allow", allow), ("ask", ask), ("deny", deny)] { - 2371
let Some(list) = list else { continue }; - 2372
document.insert( - 2373
key.into(), - 2374
toml::Value::Array( - 2375
list.iter() - 2376
.map(|spec| toml::Value::String(spec.clone())) - 2377
.collect(), - 2378
), - 2379
); - 2380
} - 2381
Ok(()) - 2382
}) - 2383
} - 2384
- 2385
/// Persist the top-level `workers` toggle for the current project. - 2386
/// Mirrors [`persist_project_preferences`]'s atomic-write shape exactly. - 2387
pub fn persist_project_workers(cwd: &Path, enabled: bool) -> Result<(), ConfigError> { - 2388
persist_workers_at(project_path(cwd), enabled) - 2389
} - 2390
- 2391
/// Persist the user-level `workers` default, inherited by project - 2392
/// configs through [`load_with_trust`] until they set their own override. - 2393
pub fn persist_global_workers(enabled: bool) -> Result<(), ConfigError> { - 2394
let path = global_path().ok_or_else(|| ConfigError::Write { - 2395
path: PathBuf::from("<user-config>"), - 2396
source: std::io::Error::other("user home is unavailable"), - 2397
})?; - 2398
persist_workers_at(path, enabled) - 2399
} - 2400
- 2401
/// Persist the optional `[work]` policy fields without disturbing unrelated - 2402
/// config keys. The whole document is rewritten through the same atomic - 2403
/// rename boundary as the other authenticated preference endpoints. - 2404
pub fn persist_work_preferences( - 2405
path: PathBuf, - 2406
enabled: Option<bool>, - 2407
default_mode: Option<&str>, - 2408
max_items: Option<usize>, - 2409
max_revisions: Option<u32>, - 2410
max_parallel: Option<usize>, - 2411
confirmation: Option<&str>, - 2412
) -> Result<(), ConfigError> { - 2413
if [default_mode, confirmation] - 2414
.into_iter() - 2415
.flatten() - 2416
.any(|value| value.trim().is_empty())
Indexing the workspace…
Vakyartha documentation is discovering safe artifacts, anchors, and source references.