Add opt-in config sync scheduling

This commit is contained in:
Dandaedre 2026-10-16 13:54:56 +02:00
parent fefc22c3ac
commit b0f78e5154
6 changed files with 49 additions and 6 deletions

View File

@ -95,7 +95,7 @@ Complete the core CLI and manual workflow before optional automation or a TUI.
## Later, only when useful
- [x] Add an optional numbered terminal menu using existing CLI commands.
- [ ] Add opt-in scheduled user-context sync with a defined policy for operations
- [x] Add opt-in scheduled user-context sync with a defined policy for operations
requiring elevation.
- [ ] Add targeted application adapters or registry settings for concrete needs.
- [ ] Add explicit package removal or managed-file cleanup if requested.

4
cc.ps1
View File

@ -1,6 +1,6 @@
[CmdletBinding()]
param(
[Parameter(Position = 0)][ValidateSet('doctor', 'plan', 'apply', 'sync', 'status', 'restore', 'menu')][string]$Command = 'menu',
[Parameter(Position = 0)][ValidateSet('doctor', 'plan', 'apply', 'sync', 'status', 'restore', 'schedule', 'unschedule', 'menu')][string]$Command = 'menu',
[string]$Machine,
[string]$Config,
[switch]$ConfigsOnly,
@ -15,7 +15,7 @@ param(
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
foreach ($module in @('State', 'Manifest', 'Repository', 'Packages', 'Configs', 'Elevation', 'Core')) {
foreach ($module in @('State', 'Manifest', 'Repository', 'Packages', 'Configs', 'Elevation', 'Scheduling', 'Core')) {
$path = Join-Path $PSScriptRoot "src/$module.psm1"
if (Test-Path -LiteralPath $path) { Import-Module $path -Force }
}

View File

@ -41,6 +41,8 @@ cc apply [-Machine NAME] [-ConfigsOnly] [-ForceConfigs] [-Json]
cc sync [-Machine NAME] [-ConfigsOnly] [-ForceConfigs] [-Json]
cc status [-Machine NAME] [-Json]
cc restore -Config NAME [-Machine NAME] [-Json]
cc schedule [-Machine NAME]
cc unschedule [-Machine NAME]
cc menu [-Machine NAME]
```
@ -49,6 +51,10 @@ current checkout. `sync` fetches its configured remote and runs from a staged
snapshot of the resolved commit. Config conflicts require `-ForceConfigs`, which
always makes a backup first. Removing a manifest entry merely stops management.
`schedule` registers a limited, interactive-user task at logon. Scheduled runs
always use `sync -ConfigsOnly`; package installation and upgrades remain manual
so an unattended task never waits for UAC. `unschedule` removes that task.
Human output lists the action, item, and explanation. `-Json` emits one JSON
document suitable for automation. Exit codes are stable: `0` success/no drift,
`2` invalid command or manifest, `3` prerequisite failure, `4` conflicts or

View File

@ -125,6 +125,13 @@ function Invoke-ConfigCentral {
$restore = Restore-ConfigBackup -Name $Config -Paths $Paths -State $state
$result = New-BaseResult 'restore'; $result.operations = @($restore); return [pscustomobject]$result
}
if ($Command -in @('schedule', 'unschedule')) {
$operation = if ($Command -eq 'schedule') {
Register-ConfigCentralSchedule -RepositoryRoot $RepositoryRoot -Machine $Machine -Paths $Paths
}
else { Unregister-ConfigCentralSchedule }
$result = New-BaseResult $Command; $result.operations = @($operation); return [pscustomobject]$result
}
if ($Command -eq 'sync') {
if ($FromSnapshot) { throw 'Nested sync from a snapshot is not allowed.' }
$settings = Read-JsonState -Path $Paths.Settings -Default ([ordered]@{})
@ -163,9 +170,9 @@ function Write-ConfigCentralResult {
function Show-ConfigCentralMenu {
param([string]$Machine, [string]$DataRoot, [string]$RepositoryRoot)
Write-Host 'Config Central'
Write-Host '1. Plan 2. Sync 3. Status 4. Doctor Q. Quit'
Write-Host '1. Plan 2. Sync 3. Status 4. Doctor 5. Schedule Q. Quit'
$choice = Read-Host 'Select'
$command = switch ($choice.ToUpperInvariant()) { '1' { 'plan' } '2' { 'sync' } '3' { 'status' } '4' { 'doctor' } 'Q' { return } default { throw "Unknown menu choice '$choice'." } }
$command = switch ($choice.ToUpperInvariant()) { '1' { 'plan' } '2' { 'sync' } '3' { 'status' } '4' { 'doctor' } '5' { 'schedule' } 'Q' { return } default { throw "Unknown menu choice '$choice'." } }
$arguments = @($command, '-RepositoryRoot', $RepositoryRoot)
if ($Machine) { $arguments += @('-Machine', $Machine) }
if ($DataRoot) { $arguments += @('-DataRoot', $DataRoot) }

30
src/Scheduling.psm1 Normal file
View File

@ -0,0 +1,30 @@
Set-StrictMode -Version Latest
$script:TaskName = 'ConfigCentral-UserSync'
function Register-ConfigCentralSchedule {
param([Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)][string]$Machine, [Parameter(Mandatory)]$Paths)
if (-not $IsWindows) { throw 'Scheduled sync is available only on Windows.' }
$scriptPath = Join-Path $RepositoryRoot 'cc.ps1'
if (-not (Test-Path -LiteralPath $scriptPath -PathType Leaf)) { throw "CLI script is missing at '$scriptPath'." }
foreach ($value in @($scriptPath, $Machine, $Paths.Root, $RepositoryRoot)) {
if ($value.Contains('"')) { throw 'Scheduled task arguments contain unsupported quote characters.' }
}
$arguments = "-NoLogo -NoProfile -ExecutionPolicy Bypass -File `"$scriptPath`" sync -Machine `"$Machine`" -ConfigsOnly -DataRoot `"$($Paths.Root)`" -RepositoryRoot `"$RepositoryRoot`""
$action = New-ScheduledTaskAction -Execute 'pwsh.exe' -Argument $arguments
$trigger = New-ScheduledTaskTrigger -AtLogOn -User ([Security.Principal.WindowsIdentity]::GetCurrent().Name)
$principal = New-ScheduledTaskPrincipal -UserId ([Security.Principal.WindowsIdentity]::GetCurrent().Name) -LogonType Interactive -RunLevel Limited
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Hours 1) -MultipleInstances IgnoreNew
Register-ScheduledTask -TaskName $script:TaskName -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description 'Fetch and deploy Config Central user configuration at logon. Package operations remain manual.' -Force | Out-Null
[pscustomobject]@{ name = $script:TaskName; status = 'Scheduled'; message = 'Config-only sync will run at user logon.' }
}
function Unregister-ConfigCentralSchedule {
if (-not $IsWindows) { throw 'Scheduled sync is available only on Windows.' }
$task = Get-ScheduledTask -TaskName $script:TaskName -ErrorAction SilentlyContinue
if ($null -eq $task) { return [pscustomobject]@{ name = $script:TaskName; status = 'Unchanged'; message = 'Scheduled sync is not registered.' } }
Unregister-ScheduledTask -TaskName $script:TaskName -Confirm:$false
[pscustomobject]@{ name = $script:TaskName; status = 'Removed'; message = 'Scheduled sync was removed.' }
}
Export-ModuleMember -Function Register-ConfigCentralSchedule, Unregister-ConfigCentralSchedule

View File

@ -91,7 +91,7 @@ def main() -> int:
except json.JSONDecodeError as exc:
errors.append(f"{path.relative_to(ROOT)}: {exc}")
required_cli_markers = ("doctor", "plan", "apply", "sync", "status", "restore", "menu")
required_cli_markers = ("doctor", "plan", "apply", "sync", "status", "restore", "schedule", "unschedule", "menu")
cli = (ROOT / "cc.ps1").read_text(encoding="utf-8-sig")
for marker in required_cli_markers:
if not re.search(rf"['\"]{re.escape(marker)}['\"]", cli):