diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7b2da78e2..84d5fa372 100755 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -155,6 +155,15 @@ jobs: - name: Frontend action set guard run: python3 scripts/check_frontend_action_set.py + # The notification surface: every toast-emitting call site carries a + # recorded disposition, and a stale record fails as loudly as an + # unrecorded site. + - name: Toast disposition guard (self-test) + run: python3 scripts/check_toast_disposition.py --self-test + + - name: Toast disposition guard + run: python3 scripts/check_toast_disposition.py + - name: Storage catalog guard (self-test) run: python3 scripts/check_storage_catalog.py --self-test @@ -170,6 +179,18 @@ jobs: - name: Project catalog invariants guard run: python3 scripts/check_project_catalog_invariants.py + - name: Planning corpus read-authority guard (self-test) + run: python3 scripts/check_plan_corpus_read_authority.py --self-test + + - name: Planning corpus read-authority guard + run: python3 scripts/check_plan_corpus_read_authority.py + + - name: Planning corpus disposition guard (self-test) + run: python3 scripts/check_planning_corpus_authority.py --self-test + + - name: Planning corpus disposition guard + run: python3 scripts/check_planning_corpus_authority.py + - name: ADR identity and link guard run: python3 scripts/check_adr_integrity.py @@ -181,6 +202,24 @@ jobs: - name: Tool broker boundary guard run: python3 scripts/check_tool_broker_boundary.py + + - name: Advisor consultation isolation guard (self-test) + run: python3 scripts/check_advisor_consultation.py --self-test + + - name: Advisor consultation isolation guard + run: python3 scripts/check_advisor_consultation.py + + - name: Agent roster consistency guard (self-test) + run: python3 scripts/check_agent_roster_consistency.py --self-test + + - name: Agent roster consistency guard + run: python3 scripts/check_agent_roster_consistency.py + - name: Agent identity literal guard (self-test) + run: python3 scripts/check_agent_identity_literals.py --self-test + + - name: Agent identity literal guard + run: python3 scripts/check_agent_identity_literals.py + # The daemon's turn code resolves its workspace root from the # execution context, never from the process working directory. The # guard covers `src/core/**` and the turn-code surfaces, plus the diff --git a/.github/workflows/command-authorization-macos-compile.yml b/.github/workflows/command-authorization-macos-compile.yml deleted file mode 100644 index c6d86b7da..000000000 --- a/.github/workflows/command-authorization-macos-compile.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: Command authorization macOS target compile (one-shot) - -on: - workflow_dispatch: - push: - branches: - - planning/linux-sandbox-next-admission-and-adr-cleanup - - planning/linux-execution-isolation - paths: - - '.github/workflows/command-authorization-macos-compile.yml' - - 'Cargo.toml' - - 'Cargo.lock' - - 'src/**' - - 'crates/**' - -permissions: - contents: read - -jobs: - macos-target-compile: - # M003 requires an Apple SDK/sysroot for the x86_64 Apple target check. - runs-on: macos-15 - timeout-minutes: 45 - env: - CARGO_TERM_COLOR: always - CARGO_BUILD_JOBS: 3 - steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - with: - targets: x86_64-apple-darwin - - uses: Swatinem/rust-cache@v2 - - name: Record Apple runner and SDK - run: | - sw_vers - uname -a - uname -m - xcrun --show-sdk-path - rustc --version --verbose - - name: Compile CodeGG for x86_64 macOS - run: cargo check -p codegg --lib --target x86_64-apple-darwin --locked diff --git a/.github/workflows/desktop-e2e.yml b/.github/workflows/desktop-e2e.yml index 6cb498cff..ffc8c4fc2 100644 --- a/.github/workflows/desktop-e2e.yml +++ b/.github/workflows/desktop-e2e.yml @@ -1,45 +1,63 @@ -name: Desktop E2E +name: Desktop compile and lint gate -# Built-app visible-window qualification for the desktop foundation (C003). -# Runs the real Tauri window (embedded WebDriver provider) against an -# isolated daemon: rendered state, real IPC Channel invalidation, visible -# reconnect, renderer reload, native close, TUI coexistence, explicit -# autostart, and daemon survival. +# Compile-and-lint gate for the desktop host while the desktop line is paused +# (owner-directed 2026-12-01). # -# Root `CI / verify` intentionally has no Tauri/Node/WebKit dependency; this -# path-gated workflow owns the display-backed qualification instead. Linux -# (WebKitGTK + xvfb) is the routine hosted qualification. Windows remains -# M002-gated; macOS runs stay valuable local evidence. +# This workflow used to run the whole desktop gate: the production boundary +# guard, the renderer (npm) checks, the host's own test/fmt/clippy suite, and +# the built-app visible-window trajectory under xvfb. The desktop product's +# development is paused, so the lane was reduced rather than spending ~20 +# minutes of runner time per pull request on a product nobody is changing. +# Measured on run 46534026619: 1190 s total, of which 375 s was the root daemon +# build, 718 s the host step (which failed) and 34 s the renderer; the +# visible-window trajectory itself was *skipped* because the host step failed +# first, so it had not run on any recent push. # -# ── RESTORED 2026-10-24 ───────────────────────────────────────────────────── -# The lane was paused on 2026-10-23 because it was red on `main`: run -# 39679968444 at 53d9fc9fd failed with +# Measured again on run 46590280230, this reduced lane's first green run: 596 s +# total, of which 280 s the root daemon build, 205 s the host lint, 26 s the +# Tauri system dependencies, 22 s the renderer and 1 s the boundary guard. # -# element ("[data-testid="permission-list"]") still not existing after 120000ms -# at apps/desktop/e2e/specs/m004-session.e2e.ts:169:5 +# ── What still runs, and why it is not nothing ───────────────────────────── # -# The cause was a stale *fixture* premise, not a product defect. The desktop -# fixture's mock model answered the first `write` call with its final text, -# but since 39e1445b6 the daemon answers a temp-root write with an actionable -# scratch-path redirect *before* asking the human, and only reaches the human -# when the model repeats the same restricted path. The fixture therefore never -# produced the `PermissionPending` the spec asserts, so the spec waited out -# its timeout on a permission that was never going to arrive. +# - the production boundary guard, which the desktop's authority split rests +# on, and which costs no build; +# - the renderer checks (`verify-desktop.sh renderer`: npm ci, typecheck, +# unit tests, bindings:check, build). They are **not** optional here even +# though the renderer is not what the lint checks: `tauri.conf.json` sets +# `frontendDist: "../dist"`, and `tauri::generate_context!()` embeds that +# directory at compile time — `dist/` is gitignored, so without the +# renderer build the desktop host does not compile at all. Measured at +# 34 s, and it keeps the renderer's own typecheck/tests/bindings checks; +# - `cargo clippy --all-targets` against `apps/desktop/src-tauri` in the +# pinned 1.90.0 toolchain. The desktop is a separate Cargo workspace that +# the root `cargo check` never compiles, and it consumes +# `codegg-client`, `codegg-protocol` and `codegg-core` storage and +# projection, all of which keep changing. This is the one check that will +# notice the desktop no longer building against them. `--all-targets` +# keeps the host's test and bench code compiling even though nothing runs +# it. # -# The fixture now repeats the same denied write on its second request, which -# exercises the intended one-offer-per-target rule: the first attempt is -# answered with the redirect, the repeat reaches the human, and the spec's -# `permission-list` assertion holds. The product behaviour is unchanged. +# ── What deliberately does not run any more, with the loss stated ────────── # -# The triggers are restored with the path filters preserved at the pause. +# - the host test suite (`verify-desktop.sh host` runs `cargo test --lib`, +# `fmt --check`, and the same clippy this file states literally); +# - the built-app WebDriver trajectory (`verify-desktop.sh e2e`) and the +# xvfb display it needed. # -# The checks below run through apps/desktop/scripts/verify-desktop.sh — the -# one local entry point that owns the desktop step list — so the hosted lane -# and the maintainer's machine cannot drift. The script is what a contributor -# runs before pushing; this workflow is what runs it for them. The lane's -# lint gate is also stated literally in the host-checks step, because that -# is where the gate guard reads it from; the script proves the two copies -# still agree. +# The desktop's +# `tests::production_tui_and_desktop_adapters_share_one_live_lsp_service` +# (`apps/desktop/src-tauri/src/lib.rs:1712`, "opening a Rust document must +# warm the configured fixture server") is red on this repository — inherited, +# and red on `main` as well — and it is now executed by nothing. That is +# recorded in `architecture/desktop.md` §"The hosted lane is reduced while the +# desktop is paused", not hidden here. +# +# `apps/desktop/scripts/verify-desktop.sh` still owns every phase, so +# restoring the lane means calling `renderer`, `host` and `e2e` again, not +# rewriting tests. `scripts/check_desktop_gate_wiring.py` fails closed if this +# workflow stops existing, loses its push/pull_request path filters, loses the +# host lint, or stops calling the entry point; the reduced lane keeps all four, +# which is why the guard is not weakened by the pause. on: push: @@ -82,12 +100,14 @@ env: CARGO_TERM_COLOR: always jobs: - e2e: + gate: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 - # Node is pinned to a currently supported LTS, not inherited ambient. + # Node is pinned to a currently supported LTS, not inherited ambient. The + # renderer build below is what produces `apps/desktop/dist`, which the + # Tauri build script embeds. - name: Node 24 uses: actions/setup-node@v4 with: @@ -100,6 +120,13 @@ jobs: with: toolchain: 1.90.0 + # The system libraries the Tauri host links against, plus `ripgrep`: the + # production boundary guard is a shell script that greps the desktop tree + # with `rg`, so the lane does not run at all without it. (`xvfb` went with + # the trajectory: nothing left in this lane opens a display.) Removing + # `ripgrep` here failed the lane in 49 s on 2026-12-01 with + # `rg: command not found`, which is why the list is commented rather than + # assumed. - name: Tauri Linux dependencies run: | sudo apt-get update @@ -113,7 +140,6 @@ jobs: libssl-dev \ libayatana-appindicator3-dev \ librsvg2-dev \ - xvfb \ ripgrep - uses: Swatinem/rust-cache@v2 @@ -122,64 +148,39 @@ jobs: . -> target apps/desktop/src-tauri -> target - - name: Configure git identity for tests - run: | - git config --global user.name "CI Test" - git config --global user.email "ci@test.example.com" - - # ── The desktop gate ──────────────────────────────────────────────── - # The checks below run through apps/desktop/scripts/verify-desktop.sh: - # one entry point owns the step list, so the hosted lane and the - # maintainer's machine (the same script, run locally) cannot drift. - # The script prints its own step-by-step log and says which steps it - # skipped and why. - + # The production boundary guard is cheap and answers its question + # without a build, so it runs first: a boundary violation should fail in + # seconds rather than after compiling the Tauri stack. - name: Desktop production boundary guard run: apps/desktop/scripts/verify-desktop.sh boundary - - name: Build root daemon binary - # The root workspace strips debuginfo in BOTH the dev and test cargo - # profiles so the two resolve identically and the dependency graph is - # compiled once (scripts/check_cargo_profile_alignment.py). This binary - # is bundled into the desktop app, so keep its debug info for crash - # symbolication: override the profile for this one invocation. - run: cargo build --locked --config 'profile.dev.strip="none"' - - name: Desktop renderer checks run: apps/desktop/scripts/verify-desktop.sh renderer - # tauri.conf.json bundles binaries/codegg as a resource; the Tauri - # build script requires it to exist. Stage this revision's binary - # (gitignored; C001 operator contract). + - name: Build root daemon binary + # The Tauri build script requires the bundled daemon resource to exist + # before the host compiles (`tauri.conf.json` bundles binaries/codegg), + # so even a lint-only gate needs this binary. The root workspace strips + # debuginfo in both the dev and test profiles so the two resolve + # identically (scripts/check_cargo_profile_alignment.py); this binary is + # shipped inside the desktop app, so keep its debug info for crash + # symbolication by overriding the profile for this one invocation. + run: cargo build --locked --config 'profile.dev.strip="none"' + - name: Stage daemon resource for the desktop bundle env: CODEGG_DAEMON_EXECUTABLE: ${{ github.workspace }}/target/debug/codegg run: apps/desktop/scripts/verify-desktop.sh stage-daemon - - name: Desktop host checks (production configuration) - run: | - # This lane's lint gate, in the pinned toolchain. The script's - # `host` phase runs the same three host commands (test, fmt and - # this lint) and proves they still agree with this file, so the - # local gate and this lane cannot drift. - rustup run 1.90.0 cargo clippy --manifest-path apps/desktop/src-tauri/Cargo.toml --all-targets --locked -- -D warnings - apps/desktop/scripts/verify-desktop.sh host - - # Builds the fixture helper plus the desktop-e2e feature app binary - # (the only configuration containing the embedded WebDriver server), - # then runs the visible-window trajectory under a fake display (the - # script uses xvfb when the runner has no display of its own, and - # skips the step with the reason when it has none at all). - # CODEGG_DAEMON_EXECUTABLE pins the daemon to this revision. - - name: Built-app WebDriver trajectory - env: - CODEGG_DAEMON_EXECUTABLE: ${{ github.workspace }}/target/debug/codegg - run: apps/desktop/scripts/verify-desktop.sh e2e - - - name: Upload E2E logs - if: always() - uses: actions/upload-artifact@v4 - with: - name: desktop-e2e-logs - path: apps/desktop/e2e/logs/ - if-no-files-found: warn + # Formatting needs no build and no daemon resource, so it costs seconds + # and survives the reduction even though the rest of the host phase does + # not. + - name: Desktop host formatting + run: rustup run 1.90.0 cargo fmt --manifest-path apps/desktop/src-tauri/Cargo.toml -- --check + + # This lane's lint gate, in the pinned toolchain. It is stated literally + # here because that is where scripts/check_desktop_gate_wiring.py reads it + # from, and because a local `verify-desktop.sh host` run must agree with + # it (the script proves the two copies still match). + - name: Desktop host lint + run: rustup run 1.90.0 cargo clippy --manifest-path apps/desktop/src-tauri/Cargo.toml --all-targets --locked -- -D warnings diff --git a/.github/workflows/linux-m004-native.yml b/.github/workflows/linux-m004-native.yml index 85a6bd018..e95afec69 100644 --- a/.github/workflows/linux-m004-native.yml +++ b/.github/workflows/linux-m004-native.yml @@ -151,14 +151,14 @@ jobs: CARGO_BUILD_JOBS: 4 CODEGG_RUN_M004_BWRAP_NATIVE: '1' CODEGG_RUN_C009_BWRAP_NATIVE: '1' - # The "Protected mount and Git regressions" step runs the - # `protected_mount_` filter, which also selects the two protected-mount - # regressions gated on the C006 native qualification — the real managed - # process handoff and the PTY first hop. Without this gate those two - # tests skipped here, and one of them skipped *silently*, so the step - # reported a green run that had qualified only 9 of its 11 selected - # tests. This job installs Bubblewrap and enables user namespaces, the - # same setup the C006 job has, so the gate's preconditions hold. + # The C006/C009 gates stay even though the "Protected mount and Git + # regressions" step that motivated them moved out on 2026-12-01 (C006's + # own lane runs those three commands under the same gates). Tests inside + # this job's other steps are gated on them too, and a selected test whose + # gate is missing self-skips — one of them silently — so a step can + # otherwise report green over fewer tests than its filter selected. This + # job installs Bubblewrap and enables user namespaces, the same setup the + # C006 job has, so the gates' preconditions hold. CODEGG_RUN_C006_BWRAP_NATIVE: '1' CODEGG_RUN_M004_CARGO_NATIVE: '1' CODEGG_RUN_M004_PTY_NATIVE: '1' @@ -252,11 +252,17 @@ jobs: - name: M004 daemon-owned constrained LSP duplex and procfs qualification run: python3 scripts/check_test_filter_execution.py --run -- cargo test --locked -p codegg --lib lsp::m004::tests::constrained_lsp_process_is_owned_by_m004_scope --features lsp-test-support -- --test-threads=1 --nocapture - - name: Protected mount and Git regressions - run: | - python3 scripts/check_test_filter_execution.py --run -- cargo test --locked -p codegg --lib protected_mount_ -- --nocapture - python3 scripts/check_test_filter_execution.py --run -- cargo test --locked -p codegg-sandbox --lib protected_mount_refuses_bare_repository_as_workspace -- --nocapture - python3 scripts/check_test_filter_execution.py --run -- cargo test -p egggit --locked trusted_git -- --test-threads=1 + # The "Protected mount and Git regressions" step that used to sit here ran + # three commands — `protected_mount_` in codegg, the bare-repository + # guard in codegg-sandbox, and `trusted_git` in egggit — under + # CODEGG_RUN_C006_BWRAP_NATIVE/CODEGG_RUN_C009_BWRAP_NATIVE. It was + # removed on 2026-12-01 because `linux-c006-native.yml` runs exactly + # those three commands under exactly those gates in its + # "ManagedProcessService protected-mount qualification" and "Trusted Git + # repository-config qualification" steps, and that lane was green + # (46534026556, 359 s) on the same head. Running them twice per push + # bought no coverage. The env gates above stay: other tests in this job's + # suites are gated on them too. restricted-userns-fails-closed: if: ${{ github.event_name != 'workflow_dispatch' || github.ref_name != 'planning/linux-sandbox-next-admission-and-adr-cleanup' }} diff --git a/.github/workflows/shared-checkout-macos-qualification.yml b/.github/workflows/shared-checkout-macos-qualification.yml index 3284c5a5c..ba6e47ef4 100644 --- a/.github/workflows/shared-checkout-macos-qualification.yml +++ b/.github/workflows/shared-checkout-macos-qualification.yml @@ -25,7 +25,6 @@ on: push: branches: - main - - work/agent-workstream-m005-writer-audit paths: - '.github/workflows/shared-checkout-macos-qualification.yml' - 'Cargo.toml' diff --git a/.github/workflows/windows-c044-two-hop-native.yml b/.github/workflows/windows-c044-two-hop-native.yml deleted file mode 100644 index d4e1117e5..000000000 --- a/.github/workflows/windows-c044-two-hop-native.yml +++ /dev/null @@ -1,114 +0,0 @@ -name: Windows C044 native two-hop diagnostic (test only) - -on: - workflow_dispatch: - push: - paths: - - '.github/workflows/windows-c044-two-hop-native.yml' - - 'scripts/windows_c044_two_hop_native.ps1' - - 'research/windows-native-sandbox/two-hop-native-diagnostic/**' - - 'plans/implementation/windows-native-sandbox/044-compiled-native-two-hop-launch-diagnostic.md' - -permissions: - contents: read - -jobs: - two-hop-native: - runs-on: windows-latest - timeout-minutes: 30 - steps: - - uses: actions/checkout@v4 - - - name: Record Windows runner metadata - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $os = Get-CimInstance Win32_OperatingSystem - $current = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' - $evidence = [ordered]@{ - edition = $os.Caption - version = $os.Version - build = [int]$current.CurrentBuild - ubr = [int]$current.UBR - architecture = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() - git_sha = '${{ github.sha }}' - workflow_run_id = '${{ github.run_id }}' - qualification = 'Hosted disposable-runner diagnostic only; not an independent security admission.' - } - $json = $evidence | ConvertTo-Json -Compress - "C044_HOST=$json" - $json | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - - - name: Record disposable runner privilege evidence - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $identity = [Security.Principal.WindowsIdentity]::GetCurrent() - $principal = [Security.Principal.WindowsPrincipal]::new($identity) - $isAdministrator = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) - $groups = whoami /groups - $highIntegrity = [bool]($groups | Select-String 'S-1-16-12288') - if (-not $isAdministrator -or -not $highIntegrity) { - throw 'C044 requires an elevated administrator token on its disposable Windows runner.' - } - "C044 admin consent: Administrator=$isAdministrator HighIntegrity=$highIntegrity" | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - - - uses: ilammy/msvc-dev-cmd@v1 - - - uses: dtolnay/rust-toolchain@1.89.0 - - - name: Build native first-instruction probe and record provenance - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $source = 'research/windows-native-sandbox/two-hop-native-diagnostic/native_probe.c' - $probe = Join-Path $env:RUNNER_TEMP 'codegg-c044-native-probe.exe' - # /MT statically links the CRT so the restricted child loads only - # the probe file (explicit limiting-SID grant) plus KnownDLLs - # (kernel32/advapi32); no system32/WinSxS CRT file opens that the - # restricting SID is not granted. - cl.exe /nologo /MT /O1 /GS /sdl /W4 /DUNICODE /D_UNICODE /Fe:$probe $source advapi32.lib - if ($LASTEXITCODE -ne 0) { throw "cl.exe failed: $LASTEXITCODE" } - $hash = (Get-FileHash -Algorithm SHA256 $probe).Hash - $object = Join-Path $env:RUNNER_TEMP 'c044-version.obj' - # cl.exe /Bv prints multiple lines; GITHUB_ENV accepts only - # single-line NAME=VALUE entries, so flatten to one line. - $compilerLines = (& cl.exe /Bv /nologo /c $source "/Fo:$object" 2>&1 | Out-String).Split("`n") | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' } - $compiler = ($compilerLines -join ' / ') - if ([string]::IsNullOrWhiteSpace($compiler)) { throw 'Compiler version evidence is missing.' } - "C044_NATIVE_PROBE=$probe" | Add-Content -LiteralPath $env:GITHUB_ENV - "C044_PROBE_SHA256=$hash" | Add-Content -LiteralPath $env:GITHUB_ENV - "C044_PROBE_COMPILER=$compiler" | Add-Content -LiteralPath $env:GITHUB_ENV - "C044 probe SHA256=$hash compiler=$compiler" | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - - - name: Build and test portable harness logic - shell: pwsh - run: | - cargo test --locked --manifest-path research/windows-native-sandbox/two-hop-native-diagnostic/Cargo.toml -- --nocapture - - - name: Run bounded native two-hop synthetic fixture - shell: pwsh - run: | - $console = Join-Path $env:RUNNER_TEMP 'codegg-c044-console.txt' - ./scripts/windows_c044_two_hop_native.ps1 2>&1 | Tee-Object -FilePath $console - # NOTE: no $LASTEXITCODE guard here — in a fresh step shell it is - # $null (which wrongly compares -ne 0); a script terminating error - # already fails the step, and a missing report throws below. - $line = Get-Content $console | Where-Object { $_ -like 'C044_REPORT=*' } | Select-Object -Last 1 - if (-not $line) { throw 'C044 produced no machine-readable report.' } - $report = $line.Substring('C044_REPORT='.Length) | ConvertFrom-Json - $report | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $env:RUNNER_TEMP 'codegg-c044-report.json') - $outcome = [string]$report.outcome - "C044 outcome: $outcome" | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - if ($outcome -eq 'control-failed') { throw 'C044 first-hop control read failed; the run is invalid, not a denial result.' } - - - name: Upload redacted C044 evidence - if: always() - uses: actions/upload-artifact@v4 - with: - name: windows-c044-two-hop-native-${{ github.run_id }} - path: | - ${{ runner.temp }}/codegg-c044-report.json - ${{ runner.temp }}/codegg-c044-console.txt - if-no-files-found: warn - retention-days: 30 diff --git a/.github/workflows/windows-dedicated-user-feasibility.yml b/.github/workflows/windows-dedicated-user-feasibility.yml deleted file mode 100644 index 3a281f753..000000000 --- a/.github/workflows/windows-dedicated-user-feasibility.yml +++ /dev/null @@ -1,90 +0,0 @@ -name: Windows dedicated principal feasibility - -on: - push: - paths: - - '.github/workflows/windows-dedicated-user-feasibility.yml' - - 'scripts/windows_dedicated_user_feasibility.ps1' - - 'plans/implementation/windows-native-sandbox/021-dedicated-user-native-feasibility.md' - - 'scripts/windows_dedicated_user_read_boundary.ps1' - - 'scripts/windows_restricted_primary_token_feasibility.ps1' - - 'scripts/windows_restricted_primary_token_probe.c' - - 'plans/implementation/windows-native-sandbox/024-dedicated-principal-token-and-host-read-boundary.md' - - 'plans/implementation/windows-native-sandbox/027-restricted-primary-token-win32-interop-corrective.md' - - 'scripts/windows_token_initialization_trace.ps1' - - 'scripts/windows_token_initialization_marker.c' - - 'plans/implementation/windows-native-sandbox/028-token-launch-initialization-diagnostic.md' - pull_request: - paths: - - '.github/workflows/windows-dedicated-user-feasibility.yml' - - 'scripts/windows_dedicated_user_feasibility.ps1' - - 'plans/implementation/windows-native-sandbox/021-dedicated-user-native-feasibility.md' - - 'scripts/windows_dedicated_user_read_boundary.ps1' - - 'scripts/windows_restricted_primary_token_feasibility.ps1' - - 'scripts/windows_restricted_primary_token_probe.c' - - 'plans/implementation/windows-native-sandbox/024-dedicated-principal-token-and-host-read-boundary.md' - - 'plans/implementation/windows-native-sandbox/027-restricted-primary-token-win32-interop-corrective.md' - - 'scripts/windows_token_initialization_trace.ps1' - - 'scripts/windows_token_initialization_marker.c' - - 'plans/implementation/windows-native-sandbox/028-token-launch-initialization-diagnostic.md' - workflow_dispatch: - inputs: - run_read_boundary: - description: Run the C027 primary-token interop and same-file read-boundary probe - type: boolean - required: false - default: false - run_token_trace: - description: Run the bounded C028 token initialization phase trace - type: boolean - required: false - default: false - -permissions: - contents: read - -jobs: - dedicated-principal: - runs-on: windows-latest - timeout-minutes: 20 - steps: - - uses: actions/checkout@v4 - - - name: Create and exercise one disposable standard principal - shell: pwsh - run: ./scripts/windows_dedicated_user_feasibility.ps1 - - read-boundary: - if: github.event_name != 'workflow_dispatch' || inputs.run_read_boundary - runs-on: windows-latest - timeout-minutes: 30 - steps: - - uses: actions/checkout@v4 - - - name: Record C027 test runner metadata - shell: pwsh - run: | - $os = Get-CimInstance Win32_OperatingSystem - "OS: $($os.Caption)" - "Version: $($os.Version)" - "Build: $($os.BuildNumber)" - $identity = [Security.Principal.WindowsIdentity]::GetCurrent() - $principal = [Security.Principal.WindowsPrincipal]::new($identity) - "Runner identity: $($identity.Name)" - "Administrator role: $($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))" - whoami /priv - - - name: Run bounded C027 primary-token interop and read comparison - shell: pwsh - run: ./scripts/windows_restricted_primary_token_feasibility.ps1 - - token-initialization-trace: - if: github.event_name != 'workflow_dispatch' || inputs.run_token_trace - runs-on: windows-latest - timeout-minutes: 20 - steps: - - uses: actions/checkout@v4 - - - name: Run bounded C028 token initialization phase trace - shell: pwsh - run: ./scripts/windows_token_initialization_trace.ps1 diff --git a/.github/workflows/windows-mxc-c033-requalification.yml b/.github/workflows/windows-mxc-c033-requalification.yml deleted file mode 100644 index 060c6f4c8..000000000 --- a/.github/workflows/windows-mxc-c033-requalification.yml +++ /dev/null @@ -1,49 +0,0 @@ -name: Windows MXC C033 denial and toolchain requalification (test only) - -on: - workflow_dispatch: - push: - paths: - - '.github/workflows/windows-mxc-c033-requalification.yml' - - 'research/windows-native-sandbox/mxc-c033-harness/**' - - 'plans/implementation/windows-native-sandbox/033-mxc-denial-telemetry-and-toolchain-requalification.md' - -permissions: - contents: read - -jobs: - mxc-requalification: - runs-on: windows-11-arm - timeout-minutes: 30 - steps: - - uses: actions/checkout@v4 - - - name: Record serviced Windows 11 host inventory - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $os = Get-CimInstance Win32_OperatingSystem - $current = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' - $arch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() - $evidence = [ordered]@{ - edition = $os.Caption - version = $os.Version - build = [int]$current.CurrentBuild - ubr = [int]$current.UBR - display_version = $current.DisplayVersion - architecture = $arch - processmodel_dll = Test-Path (Join-Path $env:SystemRoot 'System32\processmodel.dll') - mxc_sdk = '1.0.0 (Cargo.toml and Cargo.lock pinned)' - capture_mode = 'block (deny-and-record)' - qualification = 'Test-only synthetic fixture; no production admission claim.' - } - $json = $evidence | ConvertTo-Json -Compress - "C033_HOST=$json" - $json | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - - - name: Install isolated MXC Rust toolchain - uses: dtolnay/rust-toolchain@1.93.1 - - - name: Run pinned MXC v1.0.0 C033 synthetic denial and toolchain matrix - shell: pwsh - run: cargo run --locked --manifest-path research/windows-native-sandbox/mxc-c033-harness/Cargo.toml diff --git a/.github/workflows/windows-mxc-c035-helper-corrective.yml b/.github/workflows/windows-mxc-c035-helper-corrective.yml deleted file mode 100644 index 3eea381ba..000000000 --- a/.github/workflows/windows-mxc-c035-helper-corrective.yml +++ /dev/null @@ -1,121 +0,0 @@ -name: Windows MXC C035 native-helper corrective (test only) - -on: - workflow_dispatch: - push: - paths: - - '.github/workflows/windows-mxc-c035-helper-corrective.yml' - - 'research/windows-native-sandbox/mxc-c035-harness/**' - - 'research/windows-native-sandbox/mxc-c033-harness/**' - - 'plans/implementation/windows-native-sandbox/035-mxc-native-helper-and-handle-boundary-corrective.md' - -permissions: - contents: read - -jobs: - mxc-c035-corrective: - runs-on: windows-11-arm - timeout-minutes: 45 - steps: - - uses: actions/checkout@v4 - - - name: Record Windows host inventory - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $os = Get-CimInstance Win32_OperatingSystem - $current = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' - $evidence = [ordered]@{ - edition = $os.Caption - version = $os.Version - build = [int]$current.CurrentBuild - ubr = [int]$current.UBR - display_version = $current.DisplayVersion - architecture = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() - mxc_sdk = '1.0.0' - rust = '1.93.1 (isolated test-only toolchain)' - git_sha = '${{ github.sha }}' - workflow_run_id = '${{ github.run_id }}' - qualification = 'Evidence collection only; no production admission claim.' - } - $json = $evidence | ConvertTo-Json -Compress - "C035_HOST=$json" - $json | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - - - uses: ilammy/msvc-dev-cmd@v1 - with: - arch: arm64 - - - uses: dtolnay/rust-toolchain@1.93.1 - - - name: Build minimal ARM64 native helper and record PE provenance - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $source = 'research/windows-native-sandbox/mxc-c035-harness/native_probe.c' - $helper = Join-Path $env:RUNNER_TEMP 'codegg-mxc-c035-native-probe.exe' - cl.exe /nologo /O2 /W4 /DUNICODE /D_UNICODE /Fe:$helper $source advapi32.lib - if ($LASTEXITCODE -ne 0) { throw "cl.exe failed: $LASTEXITCODE" } - $machine = (& dumpbin.exe /headers $helper | Select-String 'machine \(' | Select-Object -First 1).ToString().Trim() - $imports = (& dumpbin.exe /imports $helper | Out-String).Trim() - $hash = (Get-FileHash -Algorithm SHA256 $helper).Hash - $object = Join-Path $env:RUNNER_TEMP 'c035-version.obj' - $compiler = (& cl.exe /Bv /nologo /c $source "/Fo:$object" 2>&1 | Out-String).Trim() - if ($machine -notmatch 'ARM64' -or [string]::IsNullOrWhiteSpace($imports) -or [string]::IsNullOrWhiteSpace($compiler)) { throw 'ARM64 PE machine, import table, or compiler version evidence is missing.' } - $evidence = [ordered]@{ helper_sha256=$hash; machine=$machine; imports=$imports; compiler=$compiler } - $json = $evidence | ConvertTo-Json -Compress - "C035_HELPER=$json" - $json | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - "C035_NATIVE_HELPER=$helper" | Add-Content -LiteralPath $env:GITHUB_ENV - - - name: Preserve C033 baseline on this runner - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $console = Join-Path $env:RUNNER_TEMP 'codegg-mxc-c033-console.txt' - cargo run --locked --manifest-path research/windows-native-sandbox/mxc-c033-harness/Cargo.toml 2>&1 | Tee-Object -FilePath $console - if ($LASTEXITCODE -ne 0) { throw "C033 baseline runner failed: $LASTEXITCODE" } - $line = Get-Content $console | Where-Object { $_ -like 'C033_REPORT=*' } | Select-Object -Last 1 - $ok = $false - if ($line) { - $report = $line.Substring('C033_REPORT='.Length) | ConvertFrom-Json - $required = @('direct_read=denied','junction_read=denied','case_alias_read=denied','hardlink_read=denied','ads_read=denied','outside_write=denied','pipe=denied') - $stdout = [string]$report.stdout - $ok = $report.result -eq 'Exited(0)' -and $report.same_file_normal_child_baseline -eq 'allowed' -and $report.host_acl_unchanged -and $report.secret_acl_unchanged -and $report.secret_unchanged -and $report.denial_capture.document_present -and @($required | Where-Object { $stdout -notlike "*$_*" }).Count -eq 0 - $report | ConvertTo-Json -Depth 50 | Set-Content -LiteralPath (Join-Path $env:RUNNER_TEMP 'codegg-c033-baseline.json') - } - "C035_C033_BASELINE_OK=$ok" - "C035_C033_BASELINE_OK=$ok" | Add-Content -LiteralPath $env:GITHUB_ENV - if (-not $ok) { 'C033 regression baseline: INCOMPLETE OR FAILED.' | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY } - else { 'C033 regression baseline: preserved for tested read, alias, outside-write, pipe, positive-read, and ACL observations.' | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY } - - - name: Run C035 native startup, inheritance and stage probes - shell: pwsh - run: | - $ErrorActionPreference = 'Continue' - $reportPath = Join-Path $env:RUNNER_TEMP 'codegg-mxc-c035-report.json' - $env:C035_NATIVE_HELPER = $env:C035_NATIVE_HELPER - $env:C035_REPORT_JSON = $reportPath - cargo run --locked --manifest-path research/windows-native-sandbox/mxc-c035-harness/Cargo.toml --bin codegg-mxc-c035-corrective 2>&1 | Tee-Object -FilePath (Join-Path $env:RUNNER_TEMP 'codegg-mxc-c035-console.txt') - if ($LASTEXITCODE -ne 0) { throw "C035 evidence runner failed: $LASTEXITCODE" } - if (Test-Path $reportPath) { - $report = Get-Content -Raw $reportPath | ConvertFrom-Json - $summary = if ($report.qualified) { 'Native security qualification: SUCCEEDED (test-only).' } else { 'Native security qualification: FAILED OR INCOMPLETE. This workflow records evidence only; job success is not admission.' } - $summary | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - } else { - 'Native security qualification: FAILED OR INCOMPLETE. No machine-readable report was produced.' | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - throw 'C035 report missing' - } - - - name: Upload redacted C035 evidence - if: always() - uses: actions/upload-artifact@v4 - with: - name: windows-mxc-c035-${{ github.run_id }} - path: | - ${{ runner.temp }}/codegg-mxc-c035-report.json - ${{ runner.temp }}/codegg-mxc-c035-console.txt - ${{ runner.temp }}/codegg-mxc-c033-console.txt - ${{ runner.temp }}/codegg-c033-baseline.json - if-no-files-found: warn - retention-days: 7 diff --git a/.github/workflows/windows-mxc-c036-capture.yml b/.github/workflows/windows-mxc-c036-capture.yml deleted file mode 100644 index fc005f6f0..000000000 --- a/.github/workflows/windows-mxc-c036-capture.yml +++ /dev/null @@ -1,115 +0,0 @@ -name: Windows MXC C036 denial capture provenance (test only) - -on: - workflow_dispatch: - push: - paths: - - '.github/workflows/windows-mxc-c036-capture.yml' - - 'research/windows-native-sandbox/mxc-c035-harness/**' - - 'plans/implementation/windows-native-sandbox/036-mxc-denial-capture-provenance-corrective.md' - -permissions: - contents: read - -jobs: - mxc-c036-capture: - runs-on: windows-11-arm - timeout-minutes: 45 - steps: - - uses: actions/checkout@v4 - - - name: Record eligible host inventory - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $os = Get-CimInstance Win32_OperatingSystem - $current = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' - $evidence = [ordered]@{ - edition = $os.Caption - version = $os.Version - build = [int]$current.CurrentBuild - ubr = [int]$current.UBR - display_version = $current.DisplayVersion - architecture = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() - mxc_sdk = '1.0.0' - rust = '1.93.1 (isolated test-only toolchain)' - git_sha = '${{ github.sha }}' - workflow_run_id = '${{ github.run_id }}' - qualification = 'Evidence collection only; no production admission claim.' - } - $json = $evidence | ConvertTo-Json -Compress - "C036_HOST=$json" - $json | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - - - uses: ilammy/msvc-dev-cmd@v1 - with: - arch: arm64 - - - uses: dtolnay/rust-toolchain@1.93.1 - with: - components: rustfmt - targets: aarch64-pc-windows-msvc - - - name: Test pinned API contract and cross-check ARM64 harness - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - cargo test --locked --manifest-path research/windows-native-sandbox/mxc-c035-harness/Cargo.toml --bin c036 - if ($LASTEXITCODE -ne 0) { throw "C036 contract tests failed: $LASTEXITCODE" } - cargo check --locked --target aarch64-pc-windows-msvc --manifest-path research/windows-native-sandbox/mxc-c035-harness/Cargo.toml --bin c036 - if ($LASTEXITCODE -ne 0) { throw "ARM64 C036 check failed: $LASTEXITCODE" } - - - name: Build native ARM64 helper and record PE provenance - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $source = 'research/windows-native-sandbox/mxc-c035-harness/native_probe.c' - $helper = Join-Path $env:RUNNER_TEMP 'codegg-mxc-c036-native-probe.exe' - cl.exe /nologo /O2 /W4 /DUNICODE /D_UNICODE /Fe:$helper $source advapi32.lib - if ($LASTEXITCODE -ne 0) { throw "cl.exe failed: $LASTEXITCODE" } - $machine = (& dumpbin.exe /headers $helper | Select-String 'machine \(' | Select-Object -First 1).ToString().Trim() - $imports = (& dumpbin.exe /imports $helper | Out-String).Trim() - $hash = (Get-FileHash -Algorithm SHA256 $helper).Hash - $object = Join-Path $env:RUNNER_TEMP 'c036-version.obj' - $compiler = (& cl.exe /Bv /nologo /c $source "/Fo:$object" 2>&1 | Out-String).Trim() - if ($machine -notmatch 'ARM64' -or [string]::IsNullOrWhiteSpace($imports) -or [string]::IsNullOrWhiteSpace($compiler)) { throw 'ARM64 PE machine, import table, or compiler version evidence is missing.' } - $json = [ordered]@{ helper_sha256=$hash; machine=$machine; imports=$imports; compiler=$compiler } | ConvertTo-Json -Compress - "C036_HELPER=$json" - $json | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - "C036_NATIVE_HELPER=$helper" | Add-Content -LiteralPath $env:GITHUB_ENV - - - name: Run C036 real-child capture and negative controls - shell: pwsh - run: | - $ErrorActionPreference = 'Continue' - $reportPath = Join-Path $env:RUNNER_TEMP 'codegg-mxc-c036-report.json' - $env:C036_NATIVE_HELPER = $env:C036_NATIVE_HELPER - $env:C036_REPORT_JSON = $reportPath - cargo run --locked --manifest-path research/windows-native-sandbox/mxc-c035-harness/Cargo.toml --bin c036 2>&1 | Tee-Object -FilePath (Join-Path $env:RUNNER_TEMP 'codegg-mxc-c036-console.txt') - if ($LASTEXITCODE -ne 0) { throw "C036 evidence runner failed: $LASTEXITCODE" } - if (-not (Test-Path $reportPath)) { throw 'C036 machine-readable report missing' } - $report = Get-Content -Raw $reportPath | ConvertFrom-Json - $summary = if ($report.qualified_test_only) { 'C036 result: bounded positive test-only evidence; not production admission.' } else { 'C036 result: negative or incomplete evidence. Workflow success records collection only and is not admission.' } - $summary | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - "C036_QUALIFIED_TEST_ONLY=$($report.qualified_test_only)" - - - name: Stage synthetic capture artifacts - if: always() - shell: pwsh - run: | - $ErrorActionPreference = 'Continue' - $artifactRoot = Join-Path $env:RUNNER_TEMP 'codegg-c036-artifacts' - New-Item -ItemType Directory -Force -Path $artifactRoot | Out-Null - Copy-Item -Path (Join-Path $env:RUNNER_TEMP 'codegg-mxc-c036-report.json') -Destination $artifactRoot -ErrorAction SilentlyContinue - Copy-Item -Path (Join-Path $env:RUNNER_TEMP 'codegg-mxc-c036-console.txt') -Destination $artifactRoot -ErrorAction SilentlyContinue - Get-ChildItem -Path $env:RUNNER_TEMP -Directory -Filter 'codegg-mxc-c036-*' -ErrorAction SilentlyContinue | - ForEach-Object { Get-ChildItem -LiteralPath $_.FullName -Filter 'denials.*.json' -File -Recurse -ErrorAction SilentlyContinue | Copy-Item -Destination $artifactRoot -ErrorAction SilentlyContinue } - - - name: Upload synthetic C036 report and denial documents - if: always() - uses: actions/upload-artifact@v4 - with: - name: windows-mxc-c036-${{ github.run_id }} - path: ${{ runner.temp }}/codegg-c036-artifacts/** - if-no-files-found: warn - retention-days: 7 diff --git a/.github/workflows/windows-mxc-c037-handle-boundary.yml b/.github/workflows/windows-mxc-c037-handle-boundary.yml deleted file mode 100644 index a02427671..000000000 --- a/.github/workflows/windows-mxc-c037-handle-boundary.yml +++ /dev/null @@ -1,112 +0,0 @@ -name: Windows MXC C037 handle boundary (test only) - -on: - workflow_dispatch: - push: - paths: - - '.github/workflows/windows-mxc-c037-handle-boundary.yml' - - 'research/windows-native-sandbox/mxc-c035-harness/**' - - 'plans/implementation/windows-native-sandbox/037-mxc-handle-propagation-semantics-and-bypass-matrix.md' - -permissions: - contents: read - -jobs: - mxc-c037-handle-boundary: - runs-on: windows-11-arm - timeout-minutes: 45 - steps: - - uses: actions/checkout@v4 - - - name: Record eligible host inventory - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $os = Get-CimInstance Win32_OperatingSystem - $current = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' - $evidence = [ordered]@{ - edition = $os.Caption - version = $os.Version - build = [int]$current.CurrentBuild - ubr = [int]$current.UBR - display_version = $current.DisplayVersion - architecture = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() - mxc_sdk = '1.0.0' - rust = '1.93.1 (isolated test-only toolchain)' - git_sha = '${{ github.sha }}' - workflow_run_id = '${{ github.run_id }}' - qualification = 'Evidence collection only; no production admission claim.' - } - $json = $evidence | ConvertTo-Json -Compress - "C037_HOST=$json" - $json | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - - - uses: ilammy/msvc-dev-cmd@v1 - with: - arch: arm64 - - - uses: dtolnay/rust-toolchain@1.93.1 - with: - components: rustfmt - targets: aarch64-pc-windows-msvc - - - name: Test pinned contract and cross-check ARM64 runner - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - cargo test --locked --manifest-path research/windows-native-sandbox/mxc-c035-harness/Cargo.toml --bin c036 --bin c037 - if ($LASTEXITCODE -ne 0) { throw "C036/C037 contract tests failed: $LASTEXITCODE" } - cargo check --locked --target aarch64-pc-windows-msvc --manifest-path research/windows-native-sandbox/mxc-c035-harness/Cargo.toml --bin c037 - if ($LASTEXITCODE -ne 0) { throw "ARM64 C037 check failed: $LASTEXITCODE" } - - - name: Build native ARM64 helper and record PE provenance - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $source = 'research/windows-native-sandbox/mxc-c035-harness/native_probe.c' - $helper = Join-Path $env:RUNNER_TEMP 'codegg-mxc-c037-native-probe.exe' - cl.exe /nologo /O2 /W4 /DUNICODE /D_UNICODE /Fe:$helper $source advapi32.lib - if ($LASTEXITCODE -ne 0) { throw "cl.exe failed: $LASTEXITCODE" } - $machine = (& dumpbin.exe /headers $helper | Select-String 'machine \(' | Select-Object -First 1).ToString().Trim() - $imports = (& dumpbin.exe /imports $helper | Out-String).Trim() - $hash = (Get-FileHash -Algorithm SHA256 $helper).Hash - $object = Join-Path $env:RUNNER_TEMP 'c037-version.obj' - $compiler = (& cl.exe /Bv /nologo /c $source "/Fo:$object" 2>&1 | Out-String).Trim() - if ($machine -notmatch 'ARM64' -or [string]::IsNullOrWhiteSpace($imports) -or [string]::IsNullOrWhiteSpace($compiler)) { throw 'ARM64 PE machine, import table, or compiler version evidence is missing.' } - $json = [ordered]@{ helper_sha256=$hash; machine=$machine; imports=$imports; compiler=$compiler } | ConvertTo-Json -Compress - "C037_HELPER=$json" - $json | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - "C037_NATIVE_HELPER=$helper" | Add-Content -LiteralPath $env:GITHUB_ENV - - - name: Run C037 native handle and stream matrix - shell: pwsh - run: | - $ErrorActionPreference = 'Continue' - $reportPath = Join-Path $env:RUNNER_TEMP 'codegg-mxc-c037-report.json' - $env:C037_REPORT_JSON = $reportPath - cargo run --locked --manifest-path research/windows-native-sandbox/mxc-c035-harness/Cargo.toml --bin c037 2>&1 | Tee-Object -FilePath (Join-Path $env:RUNNER_TEMP 'codegg-mxc-c037-console.txt') - if ($LASTEXITCODE -ne 0) { throw "C037 evidence runner failed: $LASTEXITCODE" } - if (-not (Test-Path $reportPath)) { throw 'C037 machine-readable report missing' } - $report = Get-Content -Raw $reportPath | ConvertFrom-Json - $summary = if ($report.qualified_test_only) { 'C037 result: bounded positive test-only evidence; not production admission.' } else { 'C037 result: negative or incomplete evidence. Workflow success records collection only and is not admission.' } - $summary | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - "C037_QUALIFIED_TEST_ONLY=$($report.qualified_test_only)" - - - name: Stage synthetic C037 evidence - if: always() - shell: pwsh - run: | - $ErrorActionPreference = 'Continue' - $artifactRoot = Join-Path $env:RUNNER_TEMP 'codegg-c037-artifacts' - New-Item -ItemType Directory -Force -Path $artifactRoot | Out-Null - Copy-Item -Path (Join-Path $env:RUNNER_TEMP 'codegg-mxc-c037-report.json') -Destination $artifactRoot -ErrorAction SilentlyContinue - Copy-Item -Path (Join-Path $env:RUNNER_TEMP 'codegg-mxc-c037-console.txt') -Destination $artifactRoot -ErrorAction SilentlyContinue - - - name: Upload synthetic C037 report - if: always() - uses: actions/upload-artifact@v4 - with: - name: windows-mxc-c037-${{ github.run_id }} - path: ${{ runner.temp }}/codegg-c037-artifacts/** - if-no-files-found: warn - retention-days: 7 diff --git a/.github/workflows/windows-mxc-v1-host-eligibility.yml b/.github/workflows/windows-mxc-v1-host-eligibility.yml deleted file mode 100644 index d3a96eaef..000000000 --- a/.github/workflows/windows-mxc-v1-host-eligibility.yml +++ /dev/null @@ -1,96 +0,0 @@ -name: Windows MXC v1 host eligibility - -on: - push: - paths: - - '.github/workflows/windows-mxc-v1-host-eligibility.yml' - - 'plans/implementation/windows-native-sandbox/020-mxc-v1-native-process-isolation-feasibility.md' - - 'research/windows-native-sandbox/mxc-v1-harness/**' - pull_request: - paths: - - '.github/workflows/windows-mxc-v1-host-eligibility.yml' - - 'plans/implementation/windows-native-sandbox/020-mxc-v1-native-process-isolation-feasibility.md' - - 'research/windows-native-sandbox/mxc-v1-harness/**' - workflow_dispatch: - -permissions: - contents: read - -jobs: - host-eligibility: - runs-on: windows-11-arm - timeout-minutes: 10 - steps: - - uses: actions/checkout@v4 - - - name: Record serviced Windows 11 native process-isolation prerequisites - shell: pwsh - run: | - $ErrorActionPreference = 'Stop' - $os = Get-CimInstance Win32_OperatingSystem - $current = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' - $arch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() - $dllPath = Join-Path $env:SystemRoot 'System32\processmodel.dll' - $dllExists = Test-Path -LiteralPath $dllPath - $moduleLoaded = $false - $psecExport = $false - if ($dllExists) { - Add-Type -TypeDefinition @' - using System; - using System.Runtime.InteropServices; - public static class C020NativeProbe { - [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - public static extern IntPtr LoadLibrary(string name); - [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)] - public static extern IntPtr GetProcAddress(IntPtr module, string name); - [DllImport("kernel32.dll", SetLastError = true)] - public static extern bool FreeLibrary(IntPtr module); - } - '@ - $module = [C020NativeProbe]::LoadLibrary($dllPath) - $moduleLoaded = $module -ne [IntPtr]::Zero - if ($moduleLoaded) { - $psecExport = [C020NativeProbe]::GetProcAddress($module, 'CreateProcessSecurityEnvironment') -ne [IntPtr]::Zero - [void][C020NativeProbe]::FreeLibrary($module) - } - } - $hotfixes = @(Get-HotFix | Sort-Object InstalledOn | Select-Object -Last 12 | ForEach-Object { "$($_.HotFixID):$($_.InstalledOn.ToString('yyyy-MM-dd'))" }) - $nativeEligible = $os.Caption -match '^Microsoft Windows 11' -and - [int]$current.CurrentBuild -ge 26200 -and [int]$current.UBR -ge 9278 -and - $dllExists -and $moduleLoaded -and $psecExport - $evidence = [ordered]@{ - host_edition = $os.Caption - version = $os.Version - build = [int]$current.CurrentBuild - ubr = [int]$current.UBR - display_version = $current.DisplayVersion - architecture = $arch - hotfixes = $hotfixes - processmodel_dll = $dllPath - processmodel_dll_exists = $dllExists - processmodel_dll_loads = $moduleLoaded - psec_export_present = $psecExport - native_candidate_host_eligible = $nativeEligible - mxc_release = 'Microsoft MXC v1.0.0; pinned release binary SHA256 0bb483b3592d0f663f2c5a7a2ae17db89cc04b82238684b0a1a9384b0fe828ed' - qualification = 'Host prerequisite inventory only; no MXC policy or containment claim is made by this probe.' - } - $json = $evidence | ConvertTo-Json -Depth 5 -Compress - "C020_HOST=$json" - "C020 host evidence: $json" | Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY - if (-not $nativeEligible) { - Write-Output 'C020 disposition: blocked; GitHub hosted Windows 11 ARM runner does not expose the pinned serviced Windows 11 PSEC prerequisite set.' - } else { - Write-Output 'C020 disposition: host prerequisite set present; native MXC policy qualification remains mandatory.' - } - - - name: Install isolated MXC Rust toolchain - uses: dtolnay/rust-toolchain@1.93.1 - - - name: Build and run pinned MXC v1 native policy fixture - shell: pwsh - run: | - $manifest = Join-Path $env:GITHUB_WORKSPACE 'research/windows-native-sandbox/mxc-v1-harness/Cargo.toml' - if (-not (Test-Path -LiteralPath $manifest)) { - throw "Pinned MXC harness manifest is missing from the checked out workspace: $manifest" - } - cargo run --locked --manifest-path $manifest diff --git a/.github/workflows/windows-process-launcher.yml b/.github/workflows/windows-process-launcher.yml index 7161f6f16..d234234bb 100644 --- a/.github/workflows/windows-process-launcher.yml +++ b/.github/workflows/windows-process-launcher.yml @@ -199,11 +199,10 @@ jobs: & $py scripts/check_test_filter_execution.py --run -- cargo test --locked -p codegg-sandbox --lib status_decoder_rejects_malformed_duplicate_and_oversized_frames -- --nocapture if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - - name: Test-only restricted managed process integration - if: github.event_name != 'workflow_dispatch' || !inputs.run_bounded_successor_probes - run: cargo test --locked -p codegg --features windows-sandbox-test-support --test windows_sandbox_test_support -- --nocapture --test-threads=1 - - - name: Journaled Windows ACL lease and recovery tests + # One invocation, not two. This suite used to run in two identically + # configured steps; that pair was an always-on retry, and the second run + # is what a first-run failure has to surface as instead. + - name: Windows restricted managed process, journaled ACL lease and recovery integration if: github.event_name != 'workflow_dispatch' || !inputs.run_bounded_successor_probes run: cargo test --locked -p codegg --features windows-sandbox-test-support --test windows_sandbox_test_support -- --nocapture --test-threads=1 diff --git a/.github/workflows/windows-two-hop-feasibility.yml b/.github/workflows/windows-two-hop-feasibility.yml deleted file mode 100644 index 635316b15..000000000 --- a/.github/workflows/windows-two-hop-feasibility.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: Windows two-hop feasibility (test only) - -on: - workflow_dispatch: - push: - paths: - - '.github/workflows/windows-two-hop-feasibility.yml' - - 'scripts/windows_two_hop_feasibility.ps1' - - 'plans/implementation/windows-native-sandbox/032-two-stage-dedicated-principal-read-confinement-feasibility.md' - -permissions: - contents: read - -jobs: - two-hop-diagnostic: - runs-on: windows-latest - timeout-minutes: 20 - steps: - - uses: actions/checkout@v4 - - - name: Run bounded two-hop synthetic fixture - shell: pwsh - run: ./scripts/windows_two_hop_feasibility.ps1 diff --git a/.opencode/skills/planning/SKILL.md b/.opencode/skills/planning/SKILL.md index b9e8d60fa..fab3032a9 100644 --- a/.opencode/skills/planning/SKILL.md +++ b/.opencode/skills/planning/SKILL.md @@ -24,8 +24,8 @@ roadmap state; this skill deliberately does not restate milestone status. Canonical map: `goal` = session intent, `work_plan` = actionable slice + revision, `work_order` = future-session queue, `todowrite` = in-turn steps, -`task` = live subagent runs. Each tool description carries a one-line -router pointing back to this table; this table is the single canonical copy. +`task` = live subagent runs. This table is the single canonical copy; tool +descriptions provide concise routing guidance and point here where useful. | Tool | Use when | Not for | |---|---|---| diff --git a/AGENTS.md b/AGENTS.md index 310a4a924..5e5bc2f43 100755 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ Rust 1.89+, edition 2021. ```bash scripts/verify.sh quick # canonical sanity: rustfmt, the generated-asset - # checks, 94 guard scripts, and a workspace check + # checks, 99 guard scripts, and a workspace check scripts/verify.sh full # quick + clippy (-D warnings) + the trusted sandbox # helper build (the sandboxed integration tests load it # from the profile directory) + nextest workspace sweep @@ -117,9 +117,9 @@ scripts/verify.sh scoped [base-ref] # quick's guards + only the tests the chang ## Change-triggered guards `verify.sh quick` runs the routine subset: rustfmt, the two generated-asset -checks, 94 guard scripts, and a workspace `cargo check`. CI +checks, 99 guard scripts, and a workspace `cargo check`. CI (`.github/workflows/ci.yml`) is one bounded `verify` job: the same generated-asset -checks, 80 guard scripts, fmt, clippy, and the workspace test sweep. +checks, 85 guard scripts, fmt, clippy, and the workspace test sweep. CI is a strict **subset** of `quick` — it runs nothing that quick does not. As measured on 2026-11-11, quick runs **14 guards CI omits**: the client and @@ -296,6 +296,17 @@ injects the defect and proves the guard rejects it: finite, closed over the catalog's frontend-effect forms, and carries no mutating disposition. A frontend that dispatches an undeclared action is a defect, and the guard catches it. +- `check_toast_disposition.py` — every toast-emitting call site in + `crates/codegg-tui/src` carries a recorded disposition in + `docs/toast-disposition.toml`, keyed by `path` + `symbol` + constructor, never + by line number. It fails on an unrecorded site **and** on a stale entry — the + half most manifests omit — and a `removed` tombstone fails if its call comes + back. The scanner blanks comments and string/char literals before matching, + because 641 of the tree's 1,142 calls put `.toasts` and the level call on + separate lines: a single-line grep finds 501 of them and reports success. + The manifest's `allowed-constructors` is the set the tree may use — a + constructor outside it fails at the site — and what each constructor may + express is stated on the constructor itself in `components/toast.rs`. - `check_existing_worktree_read_only.py` — a selected managed checkout remains an exclusive read-only child profile: the scheduler arms the sentinel, the worker narrows sandbox authority and keeps only `read`/`list`/`glob`, and @@ -603,7 +614,7 @@ Rules that keep the surfaces honest: | User guides (linked from the README) | `install.md`, `cli.md`, `configuration.md`, `providers.md`, `daemon.md`, `tui.md`, `agents-skills.md`, `tools.md` | | Integration notes | `LSP.md`, `MCP.md`, `PLUGINS.md`, `themes.md`, `playwright.md`, `repository-init.md` | | Reference | `security-semantics.md`, `TROUBLESHOOTING.md`, `execution-ownership.md` (+ `execution-ownership.toml` manifest), `dependency-maintenance.md`, `windows-acl-leases.md` | -| Guard manifests (machine-read; do not hand-edit) | `test-ownership.toml`, `test-assertion-quality.toml`, `test-duplication.toml`, `security-test-filters.toml`, `writer-disposition.toml`, `comment-budget.toml` | +| Guard manifests (machine-read; do not hand-edit) | `test-ownership.toml`, `test-assertion-quality.toml`, `test-duplication.toml`, `security-test-filters.toml`, `writer-disposition.toml`, `toast-disposition.toml`, `comment-budget.toml` | | Historical evidence | `validation/` (closure records; line numbers are pinned to old SHAs by design — do not "refresh" them) | `codegg.example.jsonc` is the annotated config example; validate it with diff --git a/Cargo.lock b/Cargo.lock index 1338e92f0..bbd7d0cf5 100755 --- a/Cargo.lock +++ b/Cargo.lock @@ -831,6 +831,7 @@ dependencies = [ "codegg-document", "codegg-git", "codegg-host-protocol", + "codegg-node-protocol", "codegg-protocol", "codegg-providers", "codegg-sandbox", @@ -1042,6 +1043,15 @@ dependencies = [ "serde_json", ] +[[package]] +name = "codegg-node-protocol" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.18", +] + [[package]] name = "codegg-protocol" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 8236c1763..0c01d9eef 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = [".", "crates/codegg-core", "crates/codegg-config", "crates/codegg-protocol", "crates/codegg-host-protocol", "crates/codegg-sdk", "crates/codegg-client", "crates/codegg-providers", "crates/eggsentry", "crates/eggcontext", "crates/egggit", "crates/egglsp", "crates/codegg-git", "crates/codegg-document", "crates/codegg-sandbox", "crates/codegg-sandbox-helper", "crates/codegg-tui", "crates/codegg-cli"] +members = [".", "crates/codegg-core", "crates/codegg-config", "crates/codegg-protocol", "crates/codegg-host-protocol", "crates/codegg-sdk", "crates/codegg-client", "crates/codegg-providers", "crates/eggsentry", "crates/eggcontext", "crates/egggit", "crates/egglsp", "crates/codegg-git", "crates/codegg-document", "crates/codegg-sandbox", "crates/codegg-sandbox-helper", "crates/codegg-tui", "crates/codegg-cli", "crates/codegg-node-protocol"] # The product bin lives in `codegg-cli`. It stays a default member so # `cargo build --bin codegg` still resolves. `cargo build -p codegg --bin codegg` # does not, and a root shim must not restore it. @@ -30,6 +30,7 @@ homepage = "https://github.com/dbowm91/codegg" codegg-config = { version = "=0.1.0", path = "crates/codegg-config" } codegg-protocol = { version = "=0.1.0", path = "crates/codegg-protocol" } codegg-host-protocol = { version = "=0.1.0", path = "crates/codegg-host-protocol" } +codegg-node-protocol = { version = "=0.1.0", path = "crates/codegg-node-protocol" } codegg-sdk = { version = "=0.1.0", path = "crates/codegg-sdk" } codegg-document = { version = "=0.1.0", path = "crates/codegg-document" } codegg-client = { version = "=0.1.0", path = "crates/codegg-client" } @@ -255,6 +256,7 @@ once_cell.workspace = true codegg-config.workspace = true codegg-protocol.workspace = true codegg-host-protocol.workspace = true +codegg-node-protocol.workspace = true codegg-document.workspace = true codegg-client.workspace = true codegg-providers.workspace = true @@ -304,7 +306,7 @@ sdm-runtime = { git = "https://github.com/dbowm91/sdm.git", rev = "8139b064bdcf3 # Process group management (Unix only) [target.'cfg(unix)'.dependencies] -nix = { version = "0.29", features = ["signal", "process", "fs"] } +nix = { version = "0.29", features = ["signal", "process", "fs", "socket", "user"] } [dev-dependencies] # Virtual time, for `tool_batch::batch_admission_tests::admission_deadline_edge_*`: @@ -508,6 +510,10 @@ path = "tests/projection_replay/mod.rs" name = "session_family" path = "tests/session_family/mod.rs" +[[test]] +name = "remote_workspace" +path = "tests/remote_workspace.rs" + [profile.release] lto = "thin" strip = true diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 4952d0475..6b195661d 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -29,6 +29,17 @@ It prints which steps it skipped and why, and the hosted lane calls the same script, so the local gate and the hosted lane cannot drift. Individual phases are invocable: `boundary`, `renderer`, `stage-daemon`, `host`, `e2e`. +**The hosted lane currently runs `boundary`, `renderer`, the root daemon +build, `stage-daemon`, formatting and the host lint.** Desktop development is +paused, so `.github/workflows/desktop-e2e.yml` was reduced to a +compile-and-lint gate on 2026-12-01: 596 s on its first green run, down from +1190 s. The renderer phase stays because `tauri.conf.json`'s `frontendDist` +is embedded at compile time, so the host would not build without it. The host +test suite and the built-app trajectory do not run there until the lane is +restored; the local entry point above is unchanged and still runs every phase, +so it remains the way to exercise them. See `architecture/desktop.md` §"The +hosted lane is reduced while the desktop is paused (2026-12-01)". + For local Tauri development, set `CODEGG_DAEMON_EXECUTABLE` to a built root `codegg` executable and run `npm run tauri dev`. The host uses that explicit binary path for daemon autostart. To package the existing executable as a diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 18e084e5b..1eeefd858 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -199,129 +199,9 @@ dependencies = [ [[package]] name = "arrayvec" -version = "0.7.8" +version = "0.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" - -[[package]] -name = "async-broadcast" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" -dependencies = [ - "event-listener", - "event-listener-strategy", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-channel" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" -dependencies = [ - "concurrent-queue", - "event-listener-strategy", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-executor" -version = "1.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" -dependencies = [ - "async-task", - "concurrent-queue", - "fastrand", - "futures-lite", - "pin-project-lite", - "slab", -] - -[[package]] -name = "async-io" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" -dependencies = [ - "autocfg", - "cfg-if", - "concurrent-queue", - "futures-io", - "futures-lite", - "parking", - "polling", - "rustix", - "slab", - "windows-sys 0.61.2", -] - -[[package]] -name = "async-lock" -version = "3.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" -dependencies = [ - "event-listener", - "event-listener-strategy", - "pin-project-lite", -] - -[[package]] -name = "async-process" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" -dependencies = [ - "async-channel", - "async-io", - "async-lock", - "async-signal", - "async-task", - "blocking", - "cfg-if", - "event-listener", - "futures-lite", - "rustix", -] - -[[package]] -name = "async-recursion" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "async-signal" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" -dependencies = [ - "async-io", - "async-lock", - "atomic-waker", - "cfg-if", - "futures-core", - "futures-io", - "rustix", - "signal-hook-registry", - "slab", - "windows-sys 0.61.2", -] - -[[package]] -name = "async-task" -version = "4.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" +checksum = "47a64a0fd06e123e9e3cf3ad01432af17dcab8185e8023edcf184fe696f9675d" [[package]] name = "async-trait" @@ -544,19 +424,6 @@ dependencies = [ "objc2", ] -[[package]] -name = "blocking" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" -dependencies = [ - "async-channel", - "async-task", - "futures-io", - "futures-lite", - "piper", -] - [[package]] name = "brotli" version = "9.0.0" @@ -843,15 +710,6 @@ dependencies = [ "strsim", ] -[[package]] -name = "clap_complete" -version = "4.6.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f" -dependencies = [ - "clap", -] - [[package]] name = "clap_derive" version = "4.6.7" @@ -892,17 +750,16 @@ dependencies = [ "bytes", "chrono", "clap", - "clap_complete", "codegg-client", "codegg-config", "codegg-core", "codegg-document", "codegg-git", "codegg-host-protocol", + "codegg-node-protocol", "codegg-protocol", "codegg-providers", - "comrak", - "crossterm", + "codegg-sandbox", "dashmap", "dirs 6.0.0", "eggcontext", @@ -928,17 +785,12 @@ dependencies = [ "hmac", "html2text", "ignore", - "landlock", "libc", "nix 0.29.0", - "notify-rust", "once_cell", "parking_lot", - "qrcode", "rand 0.9.5", - "ratatui", "regex", - "seccompiler", "semver", "serde", "serde_json", @@ -948,7 +800,6 @@ dependencies = [ "strsim", "strum 0.26.3", "subtle", - "syntect", "tar", "tempfile", "thiserror 2.0.21", @@ -956,12 +807,9 @@ dependencies = [ "tokio-util", "toml 0.8.2", "tracing", - "tracing-subscriber", "unicode-normalization", - "unicode-width", "url", "uuid", - "vt100", "walkdir", "windows-sys 0.61.2", ] @@ -1054,6 +902,7 @@ dependencies = [ "codegg-client", "codegg-document", "codegg-protocol", + "codegg-tui", "crossterm", "serde", "serde_json", @@ -1092,6 +941,15 @@ dependencies = [ "serde_json", ] +[[package]] +name = "codegg-node-protocol" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "codegg-protocol" version = "0.1.0" @@ -1134,6 +992,65 @@ dependencies = [ "uuid", ] +[[package]] +name = "codegg-sandbox" +version = "0.1.0" +dependencies = [ + "codegg-core", + "dirs 6.0.0", + "landlock", + "libc", + "seccompiler", + "serde", + "serde_json", + "tracing", +] + +[[package]] +name = "codegg-tui" +version = "0.1.0" +dependencies = [ + "anyhow", + "arboard", + "async-trait", + "base64 0.22.1", + "chrono", + "codegg", + "codegg-client", + "codegg-core", + "codegg-document", + "codegg-protocol", + "comrak", + "crossterm", + "dirs 6.0.0", + "egggit", + "egglsp", + "eggsact", + "futures-executor", + "futures-util", + "notify-rust", + "once_cell", + "parking_lot", + "qrcode", + "rand 0.9.5", + "ratatui", + "regex", + "serde", + "serde_json", + "sha2", + "similar", + "strsim", + "syntect", + "tokio", + "tokio-util", + "tracing", + "unicode-normalization", + "unicode-width", + "url", + "uuid", + "vt100", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -1178,15 +1095,6 @@ dependencies = [ "unicode_categories", ] -[[package]] -name = "concurrent-queue" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" -dependencies = [ - "crossbeam-utils", -] - [[package]] name = "const-oid" version = "0.9.6" @@ -2128,7 +2036,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" dependencies = [ "enumflags2_derive", - "serde", ] [[package]] @@ -2211,16 +2118,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "event-listener-strategy" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" -dependencies = [ - "event-listener", - "pin-project-lite", -] - [[package]] name = "fancy-regex" version = "0.11.0" @@ -2296,9 +2193,9 @@ checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" [[package]] name = "finl_unicode" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80bb028c8b4148c9ee0cca68fcd9add6044e81d3619f48577ddf13a263d047a2" +checksum = "09ded33109e99472f809cb7495544506eea45e366725dacf2a383e184f660456" [[package]] name = "fixedbitset" @@ -3027,12 +2924,6 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" -[[package]] -name = "hermit-abi" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" - [[package]] name = "hex" version = "0.4.3" @@ -3975,7 +3866,7 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3d0581a75c45969c63afd2bb87b1d8b25cfcc556c7a918cf9bb13b0fe8d2381" dependencies = [ - "nix 0.31.3", + "nix 0.31.4", "windows-sys 0.61.2", ] @@ -4073,15 +3964,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "matchers" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" -dependencies = [ - "regex-automata", -] - [[package]] name = "matchit" version = "0.8.4" @@ -4257,13 +4139,14 @@ dependencies = [ "cfg-if", "cfg_aliases", "libc", + "memoffset", ] [[package]] name = "nix" -version = "0.31.3" +version = "0.31.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +checksum = "2bc81ce8148d3b4f3274da811f11cdd824ae661ee4ef732cdb229825cf5be7f7" dependencies = [ "bitflags 2.13.2", "cfg-if", @@ -4303,9 +4186,9 @@ dependencies = [ [[package]] name = "notify-rust" -version = "4.18.2" +version = "4.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4587364a9a0074333429b3df75a30a205340c56a536ca3eb6ca0e59b87bbf8af" +checksum = "57da5b5d3b7809bf71858da5a2818c3404ca4688c02c8abecdda0fcdec235df3" dependencies = [ "futures-lite", "log", @@ -4324,15 +4207,6 @@ dependencies = [ "instant", ] -[[package]] -name = "nu-ansi-term" -version = "0.50.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "num-bigint-dig" version = "0.8.6" @@ -5040,17 +4914,6 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" -[[package]] -name = "piper" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" -dependencies = [ - "atomic-waker", - "fastrand", - "futures-io", -] - [[package]] name = "pkcs1" version = "0.7.5" @@ -5123,20 +4986,6 @@ dependencies = [ "miniz_oxide 0.8.9", ] -[[package]] -name = "polling" -version = "3.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" -dependencies = [ - "cfg-if", - "concurrent-queue", - "hermit-abi", - "pin-project-lite", - "rustix", - "windows-sys 0.61.2", -] - [[package]] name = "polyval" version = "0.6.2" @@ -6123,15 +5972,6 @@ dependencies = [ "digest", ] -[[package]] -name = "sharded-slab" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" -dependencies = [ - "lazy_static", -] - [[package]] name = "shlex" version = "2.0.1" @@ -7255,15 +7095,6 @@ dependencies = [ "syn 3.0.6", ] -[[package]] -name = "thread_local" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" -dependencies = [ - "cfg-if", -] - [[package]] name = "tiktoken" version = "3.8.3" @@ -7610,36 +7441,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", - "valuable", -] - -[[package]] -name = "tracing-log" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" -dependencies = [ - "log", - "once_cell", - "tracing-core", -] - -[[package]] -name = "tracing-subscriber" -version = "0.3.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" -dependencies = [ - "matchers", - "nu-ansi-term", - "once_cell", - "regex-automata", - "sharded-slab", - "smallvec", - "thread_local", - "tracing", - "tracing-core", - "tracing-log", ] [[package]] @@ -7957,12 +7758,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "valuable" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" - [[package]] name = "vcpkg" version = "0.2.15" @@ -9055,70 +8850,61 @@ dependencies = [ [[package]] name = "zbus" -version = "5.19.0" +version = "6.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +checksum = "9a7f9f5dd97fa527c1202ba1cb35d48e07f77d4de8542317c854f7aef22b0668" dependencies = [ - "async-broadcast", - "async-executor", - "async-io", - "async-lock", - "async-process", - "async-recursion", - "async-task", "async-trait", - "blocking", - "enumflags2", - "event-listener", + "bitflags 2.13.2", + "endi", "futures-core", - "futures-lite", "hex", "libc", "ordered-stream", "rustix", "serde", "serde_repr", - "tracing", + "socket2", "uds_windows", "uuid", "windows-sys 0.61.2", "winnow 1.0.4", "zbus_macros", - "zbus_names", - "zvariant", + "zbus_utils", + "zcheapstr", + "zruntime", ] [[package]] name = "zbus_macros" -version = "5.19.0" +version = "6.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +checksum = "2f5aa7f2c4ea81b7ccfb26bafefdb4d1a44dd9d4f82c8426173a3727311743e4" dependencies = [ - "proc-macro-crate 3.5.0", "proc-macro2", "quote", "syn 3.0.6", - "zbus_names", - "zvariant", - "zvariant_utils", + "zbus_utils", ] [[package]] -name = "zbus_names" -version = "4.3.5" +name = "zbus_utils" +version = "6.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7" dependencies = [ + "proc-macro2", + "quote", "serde", + "syn 3.0.6", "winnow 1.0.4", - "zvariant", ] [[package]] name = "zcheapstr" -version = "1.1.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +checksum = "2da34e7164b75d803c3197b86e6cf61b874106fbd472c5082575a8bc5fbd0907" dependencies = [ "serde", ] @@ -9269,6 +9055,19 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "zruntime" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac67096b97c00742108c4674db6bb6178adb78c4b66a506b0e4a7a9593aa5d9e" +dependencies = [ + "futures-core", + "futures-io", + "rustix", + "socket2", + "windows-sys 0.61.2", +] + [[package]] name = "zstd" version = "0.13.3" @@ -9296,44 +9095,3 @@ dependencies = [ "cc", "pkg-config", ] - -[[package]] -name = "zvariant" -version = "5.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" -dependencies = [ - "endi", - "enumflags2", - "serde", - "winnow 1.0.4", - "zcheapstr", - "zvariant_derive", - "zvariant_utils", -] - -[[package]] -name = "zvariant_derive" -version = "5.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" -dependencies = [ - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 3.0.6", - "zvariant_utils", -] - -[[package]] -name = "zvariant_utils" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" -dependencies = [ - "proc-macro2", - "quote", - "serde", - "syn 3.0.6", - "winnow 1.0.4", -] diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index fc8bdf129..fee69f893 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -35,6 +35,9 @@ desktop-e2e = ["tauri-plugin-wdio-webdriver"] [dev-dependencies] async-trait = "0.1" codegg = { path = "../../..", features = ["lsp-test-support"] } +# The TUI is its own crate since the extraction; the host checks below reach +# its App and document session directly. +codegg-tui = { path = "../../../crates/codegg-tui" } crossterm = "0.29" sqlx = { version = "0.8", features = ["sqlite", "runtime-tokio-rustls"] } tempfile = "3" diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 6201569c2..90d2366ec 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -1693,7 +1693,7 @@ while True: .await .expect("production TUI socket attachment"), ); - let tui_session = codegg::tui::document_session::TuiDocumentSession::new(tui.clone()); + let tui_session = codegg_tui::document_session::TuiDocumentSession::new(tui.clone()); tui_session .controller() .open( @@ -1714,7 +1714,7 @@ while True: "opening a Rust document must warm the configured fixture server" ); - let mut app = codegg::tui::app::App::new_for_testing(root.to_string_lossy().into_owned()); + let mut app = codegg_tui::app::App::new_for_testing(root.to_string_lossy().into_owned()); let tab = app.active_tab_mut().expect("default project tab"); tab.project_id = Some(project_id.clone()); tab.workspace_id = Some(workspace_id.clone()); @@ -1722,13 +1722,13 @@ while True: tab.session_id = Some(session_id); app.ui_state .routes - .navigate_to(codegg::tui::route::Route::Editor); - app.ui_state.input_mode = codegg::tui::input::InputMode::Normal; + .navigate_to(codegg_tui::route::Route::Editor); + app.ui_state.input_mode = codegg_tui::input::InputMode::Normal; let mut session = tui_session; - session.presentation_mut().mode = codegg::tui::editor::EditorMode::Normal; + session.presentation_mut().mode = codegg_tui::editor::EditorMode::Normal; app.editor_state.session = Some(session); app.editor_state.path = Some("src/lib.rs".into()); - app.editor_state.status = codegg::tui::app::state::editor::EditorStatus::Synced; + app.editor_state.status = codegg_tui::app::state::editor::EditorStatus::Synced; app.set_core_client(tui.clone()); let (tx, mut tui_results) = tokio::sync::mpsc::channel(8); app.tui_cmd_tx = Some(tx); @@ -1757,7 +1757,7 @@ while True: .expect("production TUI hover completes") .expect("TUI command channel remains open") { - codegg::tui::app::TuiCommand::EditorLspReadFinished { + codegg_tui::app::TuiCommand::EditorLspReadFinished { operation, result: Some(result), error: None, diff --git a/architecture/agent.md b/architecture/agent.md index 375e0b396..4f4138a62 100644 --- a/architecture/agent.md +++ b/architecture/agent.md @@ -159,6 +159,43 @@ foreground scheduler-backed test calls request cancellation for their exact job and wait for its terminal state. Explicit background jobs keep their durable lifetime beyond the submitting turn. +### Bounded advisor consultation (advisor M001) + +`advisor` is the loop's third one-shot helper call, alongside the bounded +provider reviewer (`src/permission/reviewer.rs`) and title runtime +(`src/agent/title.rs`). `advisor_tool_available` in +`src/agent/request_preparation.rs` advertises it only after `[advisor].model` +resolves through the configured `ProviderRegistry`; `advisor_batch_context` +projects the provider-visible messages and pins `original_user_prompt`. The +refusing `AdvisorTool` stub is registered only by the owning session's +`src/tool/factory.rs`; child registries do not register it. + +`execute_tool_calls_impl` in `src/agent/tool_batch.rs` intercepts the call +before generic registry dispatch. The turn-scoped `AdvisorBatchContext` +enforces one in-flight consultation and no per-turn count (ADR-0070): a run is bounded by the +turn's `ExecutionLimits`, the per-call deadline and that one-in-flight guard, and a consultation +whose advice changed is progress rather than a repeat. +`crate::advisor::build_request` uses the resolved second model and its own +reasoning selections, with `tools: None`; the advisor has no tool, permission, +scheduler, writer, or configuration authority. `run_advisor_consultation` +races the provider future against turn cancellation, a new operator message, +and the deadline; timeout, cancellation, provider failure, empty output, and +malformed output return explicit tool results without retrying or failing the +main turn. Streaming output is bounded and a truncation note is appended when +the cap is reached. + +`AdvisorConfig` in `crates/codegg-config/src/schema.rs` defaults the deadline +to 300,000 ms (clamped to 30,000..=300,000), and output to 6,000 characters +(clamped to 1,000..=16,384); it holds no consultation count. `account_advisor_usage` adds reported usage to in-memory turn totals +and goal-accounting deltas. It writes no request-ledger row: +`ProviderTurnAdapter::ledger_open_attempt` in +`src/agent/provider_turn.rs` records a `TurnRequestAttempt` only for a +turn-owned provider request, and the advisor call does not enter that seam; +adding a non-turn ledger row would require a schema change. Logs contain only +bounded metadata (provider/model ids, elapsed time, outcome class, and output +character count). M001 does not supply the forwarding-disclosure surface; +ADR-0067 assigns that point-of-selection disclosure to M002. + ### Provider-turn attempt safety (execution-reliability M001) Each logical turn runs at most 3 attempts under one UUID-scoped attempt @@ -217,6 +254,58 @@ full replacement; `disable = true` removes an agent. TOML files support agents. The safety envelope (`apply_safety_envelope`) bounds permissions by the most restrictive across agent, session, config, and hard-deny. +### Agent roster axes + +Each resolved agent has three independent boolean axes: `selectable` controls +user choice as a session agent, `subagent` controls whether the model may spawn +it through `task`, and `default` selects the initial session agent. +`Agent::resolved_axes()` is the common projection: legacy `mode` values supply +`selectable`/`subagent` only when those fields are absent, while explicitly +declared axes win, including in an `extends` overlay. `default` is independent +of `mode`; a non-selectable agent may be the startup default. If no default is +declared, startup falls back to the first selectable agent (or first resolved +agent if none is selectable). Multiple declared defaults produce a diagnostic +and the alphabetically first name wins deterministically. + +Enforcement follows the axis owner: the TUI cycle and agent picker, mention +picker, `headless --agent`, and `exec --agent` use `selectable`; +`AgentRegistry::list_spawnable()` supplies the one spawnable set to the task +schema, prompt roster, and pre-creation refusal. `/agents` browsing continues to +use `!hidden`; `hidden` changes presentation only and grants or removes no +authority. Roster axes do not change tool permissions. + +The spawn refusal is a `TaskTool` boundary, not a daemon-wide one. A job the +scheduler dispatches directly (`src/scheduler/executors.rs`) and a collaboration +route's agent reference (`src/core/daemon.rs`, shape validation in +`crates/codegg-core/src/collaboration/validation.rs`) are built from an +already-resolved agent name and never pass through `TaskTool::execute`, so +`subagent` is not re-checked there. Those paths are host- or operator-initiated +rather than model-initiated, and the axis bounds what a *model* may spawn. +Validating a scheduled job's agent at schedule-creation time is a named +follow-up; it is a record of the boundary, not an exemption from it. + +### Delegated specialized runtimes + +A `research` or `security-review` child runs host preparation before the model +is called: `prepare_delegated` builds the plan or bundle, `coordinate_research` +submits the evidence children through the pool the worker already holds, and +`finalize` maps the terminal outcome into the child's result. The ledger is +host-supplied and reaches the child's prompt as evidence, not as instructions, +so a model does not re-derive what the host already validated. The finalized +validation evidence and artifacts travel on `SubAgentResult` and are recorded by +the durable subagent executor (`src/scheduler/executors.rs`), so a parent reads a +validated result rather than model prose. + +Preparation runs only on the **scheduler-admitted** route. An unscheduled worker +holds a `SubAgentPool` semaphore permit for the whole of its run, and the +coordinator's evidence children need permits from that same pool, so +coordination there can deadlock under saturation. The specialized path therefore +refuses an unscheduled run with a `SpecializedRuntimeStageError` naming the +runtime and the stage, before provider entry; it never falls back to an ordinary +loop. Machine-capacity ownership for the unscheduled route — `send_and_wait` +against `send_and_wait_scheduled` — stays an open decision of its own, and this +refusal records the boundary rather than exempting anything from it. + ### Canonical Prompt Compilation `PromptCompiler` is the sole production entry point for system prompts. @@ -280,6 +369,33 @@ read-only tools and distinguish source-established behavior from inference or unverified claims. This is an evidence-quality rule, not additional tool authority. +Prompt compilation names its **subject**. `PromptSubject::Primary` is the +principal that reads results — the session turn (`src/agent/turn_runtime.rs`) +and the CLI's single-shot run (`crates/codegg-cli/src/main.rs`). +`PromptSubject::Delegated` is the child run that returns one +(`src/agent/worker.rs`). The subject is a required field on `PromptCompilerInput` +and `PromptContext` with no `Default` and no `Option` form, so a new construction +site fails to compile rather than inheriting a subject: a delegated contract +reaching the session agent, and a contract vanishing from a child, are both +silent failures otherwise. + +Exactly one block is gated on it: `agent:output:{role}` +(`subagent_output_contract`), which is written for a run that *returns* a result +and is now emitted only for `Delegated`. A declared `role` therefore buys an +output contract only on the delegated path — the session agent is not told to +return a summary to a parent it does not have. The adjacent follow-up contract +(`agent:follow-up-output-precedence`) keeps its `role.is_some()` gate: "treat a +follow-up as the current task direction" is true for any agent, and gating it on +the subject would drop guidance from every primary turn. + +A literal that is really a property is not a name. Plan mode is +`Agent::is_planner()` (`role == "planner"`), the session default is +`file_agents::find_default_agent` (the declared `default` axis), and the few +places that hold a name and nothing else — raw tool arguments, where no roster is +in scope to resolve one against — read it from `src/agent/names.rs`. +`scripts/check_agent_identity_literals.py` enforces both halves: no production +comparison against a builtin name outside that module, and no prompt asset that +nothing reads. ### Per-Turn Reasoning Capability The resolved model profile carries a per-model **reasoning capability @@ -572,6 +688,9 @@ pub struct Agent { pub permissions: HashMap, pub git_read_only: bool, pub hidden: bool, + pub selectable: bool, + pub subagent: bool, + pub default: bool, pub thinking_budget: Option, pub reasoning_effort: Option, pub runtime_kind: Option, @@ -1054,8 +1173,11 @@ monotonic and supports intersection for parent ceiling enforcement. Central registry separating declarative sources from resolved runtime agents. API: `load_for_context()`, `get()`, `list()`, `list_visible()`, -`list_primary()`, `list_spawnable()`, `diagnostics()`, `source_stack()`. -Uses `BTreeMap` for deterministic iteration order. +`list_primary()` (the selectable session-agent set), `list_spawnable()` (the +model-spawnable set), `diagnostics()`, and `source_stack()`. The default +startup agent is resolved by `find_default_agent()`. `list_visible()` remains +a browse-only `!hidden` filter. Uses `BTreeMap` for deterministic iteration +order. ## Configuration Surface @@ -1066,6 +1188,7 @@ Uses `BTreeMap` for deterministic iteration order. | `medium_model` | ModelRouter medium-tier model | | `auto_route_models` | Enable ModelRouter (default: false) | | `agent.` | Per-agent overrides (model, prompt, permissions, etc.) | +| `[advisor]` | Optional bounded second-model consultation; distinct from local `[tool_advisor]` ranking | | `mode.` | Mode definitions applied to matching agents | | `compaction.*` | Compaction settings (mode, policy, thresholds) | | `server.max_parallel_tools` | Override max parallel tool executions | diff --git a/architecture/blackboard_contract_matrix.md b/architecture/blackboard_contract_matrix.md index f7e0bfbe6..c711f6fde 100644 --- a/architecture/blackboard_contract_matrix.md +++ b/architecture/blackboard_contract_matrix.md @@ -57,7 +57,7 @@ belong. | Capability | Authority | Production consumer | User-reachable path | Evidence | |---|---|---|---|---| | group join | `crates/codegg-core/src/agent_run_group.rs` — `AgentRunGroupService` | `src/tool/task.rs` — `.create(NewAgentRunGroup {` | agent → `task` tool, `action=create_group` | `tests/core_daemon/workstream_claim_m003.inc`; closure `001-status.md` | -| blackboard claim | `crates/codegg-core/src/workstream_claim.rs` — `WorkstreamClaimStore` | `src/tool/task.rs` — `.claim(codegg_core::workstream_claim::NewWorkstreamClaim {` | agent → `task` tool, `action=claim` | `tests/core_daemon/workstream_claim_m003.inc`; closure `003-status.md` | +| blackboard claim | `crates/codegg-core/src/workstream_claim.rs` — `WorkstreamClaimStore` | `src/tool/task.rs` — `claims.claim(claim_input).await` | agent → `task` tool, `action=claim` | `tests/core_daemon/workstream_claim_m003.inc`; closure `003-status.md` | | peer event | `crates/codegg-core/src/bus/events.rs` — `AppEvent::AgentRunGroupUpdated` | `src/agent/follow_up.rs` — `fn inject_peer_observations` | agent turn → peer hint injected at a provider boundary | `src/agent/follow_up.rs` (`inject_peer_observations`); closure `009-status.md` | | session-worktree launch | `crates/codegg-core/src/session_launch.rs` — `SessionLaunchService` | `src/core/session_launch.rs` — `pub async fn launch(` | `codegg launch` (CLI `crates/codegg-cli/src/main.rs:2281`) and the TUI worktree actions | `tests/core_daemon/session_launch_service.inc`; closure `006-status.md` | | group lease | `crates/codegg-core/src/worktree_service.rs` — `WorktreeService::acquire_lease` | `src/core/writer_fence.rs` — `async fn shared_group(` | agent → `task` tool, `placement=serialized_shared` | `tests/shared_checkout_c006.rs`; closure `006-status.md` (C006) | diff --git a/architecture/command.md b/architecture/command.md index 1f24a1483..3f925a4c1 100644 --- a/architecture/command.md +++ b/architecture/command.md @@ -70,7 +70,7 @@ each entry. (`serves_form()`, `:638`), and the audit as a canonical `Run`. - `src/command/` — Core `Command` struct, file loading, template processing - `crates/codegg-tui/src/command.rs` — TUI `CommandRegistry`: a **cache** of the daemon's - catalog with 88 built-in rows, plus the TUI's own local dynamic sources + catalog with 90 built-in rows, plus the TUI's own local dynamic sources - `crates/codegg-config/src/schema.rs` — `CommandConfig` for config-file commands (re-exported as `crate::config::schema`) @@ -78,7 +78,7 @@ each entry. ### Command Loading (priority order) -1. **Built-in commands**: 88 rows cached from the daemon's catalog (highest +1. **Built-in commands**: 90 rows cached from the daemon's catalog (highest priority) 2. **Config commands**: From the `commands` section of the config file (`codegg.jsonc` / `codegg.json` / `config.json`)3. **Project commands**: From `command/` or `commands/` directories under the @@ -267,7 +267,7 @@ pub enum CommandAction { ``` `BuiltinSlashAction` is an exhaustive enum with one variant per -built-in executable operation (82 variants, `crates/codegg-tui/src/command.rs:112`). +built-in executable operation (84 variants, `crates/codegg-tui/src/command.rs:112`). Adding a new built-in command requires touching this one typed registry/action authority; the compiler (exhaustive match in `dispatch_builtin_command`) and the @@ -356,13 +356,16 @@ cwd. Dynamic commands cannot change daemon authorization or execution scope. They are also **outside** the daemon's catalog: a dynamic source is a separate trust class, and the desktop does not expose it. -### Built-in Commands (88 total) +### Built-in Commands (90 total) -The **88** is the length of the TUI's cached built-in rows, one row per -catalog identity. The daemon's catalog is the definition and carries **88** -command identities over **147** argument forms — **86** daemon-effect forms -and **61** frontend-effect forms — served by **82** `BuiltinSlashAction` +The **90** is the length of the TUI's cached built-in rows, one row per +catalog identity. The daemon's catalog is the definition and carries **90** +command identities over **149** argument forms — **87** daemon-effect forms +and **62** frontend-effect forms — served by **84** `BuiltinSlashAction` variants. The census guards the catalog, composer rows and effect routes. +The two rows the reconciliation restores are `/advisor`, a daemon effect on +the shared advisor resolver, and `/toast`, a frontend effect that reads the +retained notification history. M003 retired twenty leaf command identities by folding their operations into eight families. Their forms are `/memory` (`list`, `forget`, `consolidate`, @@ -439,6 +442,7 @@ Representative built-ins: | `/edit-checkpoints` | `/checkpoints`, `/history` | List durable edit checkpoints | | `/tool-contracts` | | Show tool contract diagnostics | | `/logs` | | Show recent daemon log lines and past toast notifications | +| `/toast` | | Show the retained notification history without the daemon log lines | | `/nodes` | | Eggwork M002: show the configured remote nodes' host telemetry | | `/worktree` | | Open a workspace or worktree in the workspace view | | `/pr` | | GitHub pull requests | @@ -540,7 +544,7 @@ supports: `description`, `agent`, `model`, `template`, `runtime`, handler that action dispatches** — a declared action nothing dispatches is the same defect wearing the other hat, which is why a reclassified form is wired to its handler rather than merely declared. -- **Built-in count is 88**: Guarded by +- **Built-in count is 90**: Guarded by `built_in_command_count_matches_release_docs` and `command_docs_count_matches_registry` in `crates/codegg-tui/src/command.rs`. The docs test parses this file and fails on drift, so update the test @@ -574,7 +578,7 @@ cargo test -p codegg -- every_builtin_entry_has_coherent_action ``` The `built_in_command_count_matches_release_docs` test ensures the -88 count stays in sync with this documentation. The two +90 count stays in sync with this documentation. The two `command_docs_*` tests parse **this file** and fail on drift, so a count bump means updating this document and the registry pin together. The `command_docs_*` pair also guards the `BuiltinSlashAction` variant count @@ -722,8 +726,10 @@ two `N variants` claims in this document were corrected to 159 against the enum. The lesson repeats the one above — a count that is only asserted against a *different* count is not a count that is checked. -Re-verified 2026-10-21 after this branch was rebased onto `main`. The merged -tree holds **168** built-in commands and **160** `BuiltinSlashAction` variants, +Re-verified 2026-10-21 after this branch was rebased onto `main`; the totals +below are the ones that rebase produced, and `/toast` has since moved them to +169 and 161 (§ the count note below). The merged +tree held **168** built-in commands and **160** `BuiltinSlashAction` variants, one more than either side alone: `main` registered `/nodes` and this branch registered `/network`, and each side's pin had reached 167 commands and 159 variants on its own. The two `N variants` claims in this document are therefore @@ -818,3 +824,13 @@ Re-verified 2026-11-29 for command-hierarchy M004: the catalog still carries **88** identities over **147** forms — **86** daemon-effect and **61** frontend-effect forms — and advances to version **13** for the seven LSP path re-spellings. + +Re-verified 2026-11-30 for the reconciliation with `main`'s command-hierarchy +closeout: the cached built-in rows number **90** over **84** +`BuiltinSlashAction` variants, and the daemon catalog carries **90** identities +over **149** forms — **87** daemon-effect and **62** frontend-effect — at +catalog version **14**. The delta from M003's final measurement is exactly the +two commands the fold could not see, because they landed on the feature branch +after its fork point: `/advisor` (a daemon effect on the shared advisor +resolver) and `/toast` (a frontend effect over the retained notification +history). diff --git a/architecture/config-catalog.md b/architecture/config-catalog.md index a2d45b19f..6a617063a 100644 --- a/architecture/config-catalog.md +++ b/architecture/config-catalog.md @@ -43,6 +43,7 @@ document. Do not edit this file by hand. | Key | Merge shape | Attribution | Combine depth | Default | Note | |---|---|---|---|---|---| | `$schema` | whole-value | last-containing | 0 | `—` | | +| `advisor` | field-by-field | last-containing | 1 | `—` | | | `agent` | union-of-keys | last-containing | 1 | `—` | | | `approval_reviewer` | field-by-field | last-containing | 1 | `—` | | | `auto_route_models` | whole-value | last-containing | 0 | `—` | | @@ -114,4 +115,4 @@ document. Do not edit this file by hand. | `vim_mode` | whole-value | last-containing | 0 | `—` | | | `watcher` | field-by-field | last-containing | 1 | `—` | | -71 sections, 2 of them declared with an exception note. +72 sections, 2 of them declared with an exception note. diff --git a/architecture/config.md b/architecture/config.md index e617c20a4..200b1325e 100644 --- a/architecture/config.md +++ b/architecture/config.md @@ -209,6 +209,50 @@ current System One profile reports Rank unsupported and tool advice falls back deterministically. The effective policy/backend split is available from `codegg tool-advisor status`. +The separate `[advisor]` section configures the bounded second-model consultation, not +tool ranking. `/advisor` is its read-only TUI status surface; it reports the resolved +provider/model, bounds, forwarding disclosure, or the off/unresolvable state. + +Minimal configuration — one key. The model is `provider/model`, and that provider must be +resolvable: either an entry in this file's `provider` map, or a built-in provider that already +holds a credential (`codegg providers` lists what is resolvable). The advisor adds no credential +path of its own: + +```jsonc +{ + "provider": { + "second-vendor": { "api_key": "..." } // or use a built-in provider with a stored credential + }, + "advisor": { + "model": "second-vendor/model-id" // a bare id resolves only against the turn provider + } +} +``` + +Everything else has a default and is **clamped rather than refused**: `deadline_ms` +(300000, clamped 30000..=300000) and `max_output_chars` (6000, 1000..=16384), plus optional +`reasoning_effort` and `thinking_budget`, which are passed through to the advisor request. +`advisor` merges field by field across layers, so a project config can override `model` and +inherit the bounds. There is **no per-turn consultation count** (ADR-0070): a request that still +sets `max_consultations_per_turn` loads and the key is ignored, and a run is bounded by the +turn's own execution limits, the per-call deadline and one consultation in flight. + +Three properties to expect: + +- **Absent or invalid is off, silently.** Without a resolvable `model` the `advisor` tool is + not advertised at all and requests are byte-identical to a build without the feature. A + model that does not resolve — unknown provider, or an id absent from that provider's + catalogue — also omits the tool for that turn, with no error shown to the model. `/advisor` + is the only surface that separates "off" from "broken", and it names the reason + (`advisor provider 'x' is not configured`, `advisor model 'y' is not available from + configured provider 'z'`). +- **Resolution is per turn** against the live provider registry, so a config edit applies on + the next turn without a restart. +- **The consultation forwards the transcript.** The status surface says so: the entire + conversation, including tool results, is sent to the configured advisor provider. Both + `advisor` and `provider` merge from the project layer, so a repository can contribute either + one; review both in a repository you did not write. + Example remote configuration: ```jsonc @@ -755,6 +799,12 @@ throwaway crate built against `codegg-config`: - **`Config` struct listing was incomplete**: omitted `approval_reviewer`, `tool_advisor`, `decision_engine`, `orchestration`, `eggwork`. All five type names verified against `schema.rs`. +- **`[advisor]` gained its documented minimum** (2026-11-29): the stanza, the provider-resolution + requirement (map entry *or* built-in with a credential), the clamps and the off/invalid-silent + rule verified against `AdvisorConfig` + (`schema.rs:1970`) and its `resolved_*` accessors (`:1985`), `advisor::resolve` + (`src/advisor.rs:196`), the per-turn gate (`src/agent/request_preparation.rs:920`) and the + `/advisor` line set (`src/core/daemon_commands.rs:1008`). - Confirmed accurate as written: `merge_configs` (`paths.rs:164`), `ConfigWatcher` (`watcher.rs:12`), `Config::migrate` (`schema.rs:3587`), `CONFIG_VERSION` (`schema.rs:5`), `AuthConfig` (`schema.rs:16`), diff --git a/architecture/desktop.md b/architecture/desktop.md index a5a7b6e29..5764e1c2a 100644 --- a/architecture/desktop.md +++ b/architecture/desktop.md @@ -308,6 +308,56 @@ plus the local `apps/desktop` host and renderer checks — which the root workspace's gate does not compile, so they were run by hand. The hosted `e2e` job is now part of the lane's own evidence. +### The hosted lane is reduced while the desktop is paused (2026-12-01) + +The desktop product's development is paused, and the owner directed that the +hosted lane stop spending its full cost on work nothing is changing. Measured +on run `46534026619`: **1190 s**, of which 375 s was the root daemon build, +718 s the desktop host step, 34 s the renderer and 23 s the Tauri system +dependencies. The visible-window trajectory itself had been **skipped** in that +run, because the host step failed first, so the lane's red was never in the +trajectory. + +The lane is now a **compile-and-lint gate**: the production boundary guard, +`cargo fmt --check` and `cargo clippy --all-targets` against +`apps/desktop/src-tauri` in the pinned 1.90.0 toolchain, plus the renderer +build, the root daemon build, and the daemon staging the Tauri build script +requires. Measured on run `46590280230`, the reduced lane's first green run: +**596 s**, being 280 s the root daemon build, 205 s the host lint, 26 s the +Tauri system dependencies, 22 s the renderer, 21 s the rust-cache save, and 1 s +each for the boundary guard and the formatting check. The reduction therefore +halved the lane and, more to the point, turned it green: the 718 s host step +was the failing one, no step that remains depends on it, and the one that did — +the visible-window trajectory, which the reduction removed — had been skipping +behind that failure anyway. + +The renderer checks stay even though the renderer is not what the lint checks: +`tauri.conf.json` sets `frontendDist: "../dist"` and +`tauri::generate_context!()` embeds that directory at compile time, and +`dist/` is gitignored — so without `verify-desktop.sh renderer` the desktop +host does not compile at all, and the lint has nothing to lint. + +What stops running, with the loss stated: + +- the host test suite (`cargo test --lib`); +- the built-app visible-window trajectory and the xvfb display it needed. + +The host's +`tests::production_tui_and_desktop_adapters_share_one_live_lsp_service` +(`apps/desktop/src-tauri/src/lib.rs:1712`, "opening a Rust document must warm +the configured fixture server") is **red**, inherited (`main`'s run +`46478456148` fails the same job and step), and is now **executed by +nothing** until the lane is restored. That is the cost of the pause, recorded +here rather than absorbed into a green claim. + +`apps/desktop/scripts/verify-desktop.sh` still owns every phase, so restoring +the lane is calling `renderer`, `host` and `e2e` again, not rewriting tests. +`scripts/check_desktop_gate_wiring.py` still holds the lane to its four +controls — the workflow exists, keeps its push/pull_request path filters, lints +the host, and calls the entry point — so this pause cannot repeat the +2026-10-23 shape, where a paused lane left the desktop Rust tree compiled by no +automated gate at all. + Test instrumentation never widens production authority: - the embedded WebDriver server (`tauri-plugin-wdio-webdriver` 1.x) is an diff --git a/architecture/git.md b/architecture/git.md index df66af715..b9bda2701 100644 --- a/architecture/git.md +++ b/architecture/git.md @@ -79,7 +79,10 @@ with Git `-c` options: hooks, fsmonitor, external diff, credential helpers, SSH command overrides, signing programs and pagers are disabled; diff/show/log also receive `--no-ext-diff --no-textconv`. The environment additionally sets `GIT_NO_REPLACE_OBJECTS=1`, so a repository-declared `refs/replace/*` cannot -substitute one object for another on a read. `classify_git_request` returns a +substitute one object for another on a read, and `GIT_ATTR_NOSYSTEM=1`, so the +system-wide attributes file cannot select a filter driver — it is a separate +authority from the system config file, and `GIT_CONFIG_NOSYSTEM` does not +disable it. `classify_git_request` returns a typed `GitExecutionPolicyOutcome` before command construction. It distinguishes trusted non-executable requests, requests requiring contained execution or additional authorization, explicit authority changes, and malformed requests. @@ -117,15 +120,53 @@ surface declares something it cannot neutralise: | `diff..command` | refused — a repository-chosen diff driver | | an inspection that was truncated | refused — "we could not check" is not "we checked and found nothing" | | `core.attributesFile`, `core.alternateRefsCommand`, `core.gitProxy`, `core.pager`, `core.editor`, `sequence.editor` | neutralised by the pinned override table | +| the system-wide attributes file (`$(prefix)/etc/gitattributes`) | pinned off with `GIT_ATTR_NOSYSTEM=1` — `core.attributesFile` does not name it, and `GIT_CONFIG_NOSYSTEM` does not disable it | | `url.*.insteadOf`, `credential..helper`, `core.sshCommand` | reachable only from a remote operation, which the trusted route refuses | | `merge..driver` | reachable only from a merge operation, which the trusted route refuses | The refusal reuses the existing typed vocabulary (`RequiresContainedExecution` with `CleanSmudgeFilter` or `ExternalDiffOrTextconv`, which the route's gate turns into -`BackendUnavailable`). No new outcome shape was invented and **no Git -authorization was widened**: the trusted read route can now do less, not -more. +`BackendUnavailable`). No new outcome shape was invented. + +**Staging is the one operation the certificate discharges, and only for a +caller that opts in.** `git add` asks for `CleanSmudgeFilter` because staging +can execute a repository-configured clean filter, and the route used to refuse +it unconditionally. That refusal was a proxy for a question the detector can +now answer: the only authority that can *name* a filter driver is the +repository's own configuration, and every configuration file the child will +read is either pinned off (`GIT_CONFIG_GLOBAL=/dev/null`, +`GIT_CONFIG_NOSYSTEM=1`, the `GIT_CONFIG_*` variables stripped) or inspected +by the detector. So when the report yields **no** capability-bearing surface +at all, staging cannot execute a filter and the requirement is already met. + +The admission is narrow on purpose: + +* it is **opt-in**. `GitEnvPolicy::admit_certified_staging` is `false` by + default, and the default is the model-facing contract: there, `git add` + requires the contained-execution tier, the trusted route cannot provide it, + and the `Add` arm's preflight refuses before any publisher is consulted. A + daemon-owned caller whose root no model can reach — the planning corpus — + opts in explicitly with `GitEnvPolicy::with_certified_staging()`; +* it applies to `add` alone — `checkout`, `restore`, `switch`, `merge`, + `stash` and the rest keep their containment requirement; +* it requires the **whole** report to be free of capability-bearing surfaces, + so a truncated inspection proves nothing and refuses; +* the classifier is unchanged and stays argv-only: `classify_git_request` + still reports `RequiresContainedExecution [CleanSmudgeFilter]` for `add`, + and a caller-supplied `-c`, `--git-dir`, `--work-tree` or `-C` is still + refused before anything is inspected; +* the model-facing write path is untouched. C007 publishes a *private* index + for the `Add` arm of `GitMutationExecutor`, and that arm's preflight still + refuses under the default policy. + +Two residuals are recorded rather than papered over. The discharge carries the +detector's pre-flight window: the repository's configuration can change between +the inspection and the spawn, exactly as it can for the reads the route +already admits. And `filter..required = true` on a driver with no +command is deliberately not a surface — it cannot execute anything — but it +makes the repository permanently unstaging, so a corpus that declares one +cannot be committed at all. Two limits of the inspection are recorded rather than papered over. It is a pre-flight, so it cannot close the window between the check and the spawn. @@ -352,6 +393,37 @@ contained route is a separate, explicitly named path, not a change to what the ordinary process boundary allows. ADR-0044 remains proposed and owns the mutable object-read and metadata-promotion classes; neither is granted here. +### Managed repository creation + +`egggit::process::init_managed_repository` (and its `_with_timeout` form) is +the only way CodeGG creates a repository. The argv is built inside `egggit` — +`git init --initial-branch=main` — and is not a parameter, so nothing can reach +`--template`, `--separate-git-dir`, `--bare`, `--object-format` or a +`` operand. ADR-0071 owns the decision. + +Creation is an argv *shape*, not a caller option. The public `apply`/`apply_sync` +always build the repository shape and pin `--work-tree`; only the creation shape +omits the pin, because Git rejects it there (`--work-tree` without `--git-dir` is +a fatal error, and `git init --work-tree=X` is an unknown option). So +`apply(["git", "init"])` still pins and still fails — asserted by a test, not +assumed. + +The shape is safe only because creation is refused before any child is spawned +when the root is not an existing real directory, is a symbolic link, holds any +`.git` entry (the directory, or the file a linked worktree and a submodule use), +holds the bare layout (`HEAD` plus `objects`), or lies inside another +repository. That last case is decided by a bounded walk over the path's +ancestors using **filesystem metadata**, never a Git invocation: +`GIT_CEILING_DIRECTORIES` hides an enclosing repository from Git, so a Git answer +would be truncated by this module's own environment policy. A refusal returns +`InvalidRequest` and creates nothing. + +The corpus binding turns this into a lifecycle step rather than a status read: +`check_repository` stays pure, and `PlanCorpusRepositoryBinding::ensure_available` +(which `commit_if_dirty` already calls) creates the repository when the status is +not `Available`. A refusal or a failed `init` reports `Unavailable`; neither fails +a turn. + ### Mutation path `GitMutationExecutor::execute` runs the full 8-step pipeline: @@ -618,7 +690,9 @@ action regardless of routing mode. `GIT_PAGER=cat`, `PAGER=cat`, `GPG_TTY=""`; adds fixed Git config overrides for executable repository settings; pins `--work-tree` to the canonical root supplied by the daemon, caps upward repository discovery at - its parent, and disables system/global Git configuration; returns typed outcomes for + its parent, and disables system/global Git configuration; the pin is omitted + for the one creation shape, which has no repository to pin (see "Managed + repository creation"); returns typed outcomes for caller-supplied global config/repository redirects and capability needs before spawn. An unknown Git subcommand is classified as a contained repository-alias capability rather than sent to Git. diff --git a/architecture/overview.md b/architecture/overview.md index 587d97760..4762f6b06 100644 --- a/architecture/overview.md +++ b/architecture/overview.md @@ -596,16 +596,17 @@ fifth reconciliations recorded. The full reconciliation is in | Git operation variants | 54 | `crates/codegg-git/src/operation.rs` | | Git risk classes | 11 | `crates/codegg-git/src/risk.rs` | | Workspace member crates | 17 (+ root) | root `Cargo.toml` | -| Integration test files | 299 | `tests/*.rs` + `tests/*/*.inc` — the root integration test *modules*, with the `tests/common/` helper tree excluded. TUI families now live under `crates/codegg-tui/tests/` and are not in this root count | +| Integration test files | 301 | `tests/*.rs` + `tests/*/*.inc` — the root integration test *modules*, with the `tests/common/` helper tree excluded. TUI families now live under `crates/codegg-tui/tests/` and are not in this root count | | Guard scripts (all) | 105 | `scripts/check_*` — every guard the repository ships | | CI guard scripts | 71 | `.github/workflows/ci.yml` — a strict subset of the above; quick runs guards CI does not | ### Count reconciliation — TUI dependency inversion (2026-11-21) Milestone 002 moved the TUI integration families out of the root `tests/` tree. -*Integration test files* is **299** after the TUI editor IDE-presence line added -`tests/core_daemon/document_open_deadline_m001.inc`; it was **298** before that -member. This is the root-module measure +*Integration test files* is **301** in the merged tree: the base carried **299**, the ssh +transport foundation (R002) added `tests/remote_workspace.rs`, and the advisor M003 line added +`tests/agent_loop/advisor_consultation_m003.inc` — each line counted **300** because it saw only +its own addition. This is the root-module measure `scripts/check_test_target_references.py` checks. The families were moved, not deleted: they live under `crates/codegg-tui/tests/` and `crates/codegg-cli/tests/`. Workspace member crates is **17** (+ root), from the root `Cargo.toml` members list. diff --git a/architecture/project_catalog.md b/architecture/project_catalog.md index a1fd1e6de..39b4936a8 100644 --- a/architecture/project_catalog.md +++ b/architecture/project_catalog.md @@ -77,9 +77,15 @@ remote execution. | `LinkedNode` | `node_id`, `alias`, `path_hint` | `node:id (alias) [hint]` | `attach_locator` validates workspace binding only for `Local` -variants. `Ssh` and `LinkedNode` arms extract `None` for all local -path fields — no code path calls `.canonical_root` or `.as_path()` -on remote locators. +variants. `Ssh` and `LinkedNode` locators remain inert catalog metadata; +they are separate from the execution target on `WorkspaceRecord`. + +A remote root is never exposed as a local path: `TargetRoot` is bounded, +validated text, and remote locator/target types provide no `Path` or +`PathBuf` accessor or conversion. The successor checks in +`scripts/check_project_catalog_invariants.py` cover both `Locator` and +`TargetRoot`, including a self-test that injects path accessors and +conversions. R001 keeps remote registration unavailable. `Locator::validate()` enforces: - Non-empty, bounded fields (max `MAX_LOCATOR_FIELD_LENGTH = 512`). diff --git a/architecture/provider.md b/architecture/provider.md index 452bad0c3..ee333c387 100644 --- a/architecture/provider.md +++ b/architecture/provider.md @@ -682,9 +682,14 @@ derives its `ProviderInfo` from the target connection's `provider_kind` its `display_name`. It used to construct a fixed `eggpool`/`Eggpool` row, so rotating an OpenCode Go credential prompted for an Eggpool one — the correct action against the wrong subject, with nothing on screen to contradict it. -`App::rotation_provider_label` applies the same derivation to the "Rotating -`` credential (probe in progress)…" toast, which was left hardcoded to -Eggpool after the dialog label was fixed. +The subject is named on the dialog and nowhere else. The same paragraph used to +reach the operator twice: a toast repeated it as "Rotating `` credential +(probe in progress)…", from a second copy of the derivation +(`App::rotation_provider_label`) that was itself left hardcoded to Eggpool for a +while after the dialog row was fixed. The toast is gone — it was an echo of the +operator's own submit — and the wait it used to announce is now a line the +dialog's Review step renders while `operation_id` is set, so a probe in flight +is still visible without a second surface claiming the same state. **A failed rotation says so.** The completion arm clears the failed credential (out of memory hygiene) and sets a dialog error naming the failure and the now diff --git a/architecture/remote-workspace.md b/architecture/remote-workspace.md new file mode 100644 index 000000000..32f34a558 --- /dev/null +++ b/architecture/remote-workspace.md @@ -0,0 +1,22 @@ +# Local execution node (R003a) + +`codegg node` is a Unix-only, local execution-node role with two modes: + +- `codegg node --run [--socket ABSOLUTE_PATH]` serves a private local Unix socket. +- `codegg node --proxy [--socket ABSOLUTE_PATH] [--no-start]` bridges raw stdin/stdout bytes to the socket. Unless `--no-start` is set, a missing listener is started from the same installed `codegg` executable and the proxy waits for a bounded startup interval. + +The default socket is `~/.codegg/node/node.sock`. The default data directory and node directory are created owner-only (`0700`); the socket is `0600`. An explicit socket path must be absolute, have no `..` component, and name a file under an existing same-UID `0700` parent directory. A symlinked socket, non-socket collision, live listener, or lock contention is refused. Proven stale socket files are removed. The listener is Unix-only: it uses Linux `SO_PEERCRED` or macOS `LOCAL_PEERCRED`, rejects an unverifiable or different-UID peer, and never opens TCP. + +## Wire and lifecycle + +The private JSON-RPC 2.0 wire is newline-delimited UTF-8 JSON, with a 1 MiB maximum frame. `initialize` accepts API version 1 and only the `lifecycle` capability. A successful connection may then call `attach`, `detach`, `health`, or `shutdown`. Invalid framing and parameters return typed errors; unknown capabilities and methods are refused. `attach` canonicalizes the workspace and optional working directory, constructs the canonical session tool registry for that root, and reports the count and requested isolation profile. Multiple roots may be attached; the coordinator, not the node, owns workspace arbitration. + +The real registry factory is reused. The node passes `/scratch/` as the RunStore root instead of creating `/.codegg/runs/`. This scratch is node-local disposable working state, not a session artifact store. Registry construction grants no new authority and performs no invocation. + +## Isolation and authority boundary + +Startup probes registered filesystem sandbox backends and validates the installation-owned sandbox-helper sibling. If no backend or helper is available, the node refuses with `isolation_not_obtained`, including the backend probe reasons. The attach response's isolation facts name the backend availability and validated helper; they do **not** claim a policy was applied to a process. R003a implements no `invoke` method, so per-process enforcement is not exercised and no tool is executed. A requested profile is retained separately from those observed facts. + +The node holds no approval or policy decision, audit authorship, session, project, scheduler, or job authority. The registry is constructed only to bind the canonical root and report its actual size. `invoke`, cancellation, and tool dispatch belong to later milestones. Proxy death closes one connection but leaves the node serving; `shutdown` is graceful and bounded, and an idle listener exits after its timeout. + +The socket and scratch live below the user-scoped `.codegg` tree and are an explicit sandbox deny root. A workspace process must not be able to replace the local node listener, send it lifecycle requests, or tamper with its disposable RunStore. diff --git a/architecture/security.md b/architecture/security.md index 1e60f86d5..8b51ba679 100644 --- a/architecture/security.md +++ b/architecture/security.md @@ -778,12 +778,12 @@ evidence. **Descriptor hygiene and grant-path pinning (C006).** Descriptor closure is part of the containment boundary on **every** contained launch, not only the opt-in process-isolation tier. `managed_process::configure_status_fds` runs in -`pre_exec`, duplicates `SANDBOX_STATUS_FD` and `SANDBOX_ACK_FD` to temporary -numbers, restores them to their fixed numbers, and only then closes what the -launch does not hand the helper: `close_range` on Linux, a scan bounded by the -process's own `RLIMIT_NOFILE` on macOS (Darwin has neither `close_range` nor -`closefrom`). The hook allocates nothing, takes no lock, and logs nothing, so -the `fork`→`exec` contract holds. The process-isolation tier keeps the closure +`pre_exec`, duplicates the Unix-only `SANDBOX_STATUS_FD` and `SANDBOX_ACK_FD` +to temporary numbers, restores them to their fixed numbers, and only then closes +what the launch does not hand the helper: `close_range` on Linux, a scan bounded +by the process's own `RLIMIT_NOFILE` on macOS (Darwin has neither `close_range` +nor `closefrom`). The hook allocates nothing, takes no lock, and logs nothing, +so the `fork`→`exec` contract holds. The process-isolation tier keeps the closure it already had; the mount-view and default Landlock tiers and macOS now get the same one. The evidence is `a_contained_child_cannot_read_an_inherited_descriptor` (fixture member in diff --git a/architecture/storage-catalog.md b/architecture/storage-catalog.md index 8a463b59d..6e9a447fc 100644 --- a/architecture/storage-catalog.md +++ b/architecture/storage-catalog.md @@ -13,10 +13,10 @@ Each table names the module that owns it in `docs/storage-table-owners.toml` — the one hand-maintained input. A table with no entry there fails generation and `scripts/check_storage_catalog.py`. -- Layout version: **95** -- Migrations: **95** -- Tables: **122** -- Indexes: **223** +- Layout version: **99** +- Migrations: **99** +- Tables: **123** +- Indexes: **225** ## Migrations @@ -117,6 +117,10 @@ with no entry there fails generation and `scripts/check_storage_catalog.py`. | v93 | none | | v94 | 1 table, 1 index | | v95 | 1 table, 1 index | +| v96 | 1 index | +| v97 | 1 index | +| v98 | 1 table | +| v99 | none | ## Tables @@ -1677,6 +1681,24 @@ with no entry there fails generation and `scripts/check_storage_catalog.py`. | `idx_personal_auth_token_principal` | v52 | | `idx_personal_auth_token_revoked` | v52 | +### `plan_corpus_binding` + +- Owner: `src/plan_corpus_repository_binding.rs` +- Introduced: v98 +- Columns: + +| Column | Type | Nullable | Primary key | Notes | +| --- | --- | --- | --- | --- | +| `corpus_root` | TEXT | NOT NULL | 0 | - | +| `created_at` | INTEGER | NOT NULL | 0 | - | +| `head_commit` | TEXT | NULL | 0 | - | +| `last_observed_digest` | TEXT | NULL | 0 | - | +| `project_identity` | TEXT | NULL | 1 | - | +| `repository_identity` | TEXT | NOT NULL | 0 | - | +| `updated_at` | INTEGER | NOT NULL | 0 | - | + +- Indexes: none + ### `principal` - Owner: `crates/codegg-core/src/team.rs` @@ -2620,7 +2642,11 @@ with no entry there fails generation and `scripts/check_storage_catalog.py`. | Column | Type | Nullable | Primary key | Notes | | --- | --- | --- | --- | --- | +| `blocker` | TEXT | NULL | 0 | - | | `content` | TEXT | NOT NULL | 0 | - | +| `id` | TEXT | NULL | 0 | - | +| `plan_digest` | TEXT | NULL | 0 | - | +| `plan_ref_json` | TEXT | NULL | 0 | - | | `position` | INTEGER | NOT NULL | 2 | - | | `priority` | TEXT | NOT NULL | 0 | - | | `session_id` | TEXT | NOT NULL | 1 | - | @@ -2632,6 +2658,7 @@ with no entry there fails generation and `scripts/check_storage_catalog.py`. | Index | Introduced | | --- | --- | +| `idx_todo_session_id` | v97 | | `todo_session_idx` | v1 | ### `tool_program` @@ -3100,7 +3127,9 @@ with no entry there fails generation and `scripts/check_storage_catalog.py`. | --- | --- | --- | --- | --- | | `canonical_root` | TEXT | NOT NULL | 0 | - | | `display_name` | TEXT | NOT NULL | 0 | - | +| `host_ref` | TEXT | NOT NULL | 0 | - | | `id` | TEXT | NULL | 1 | - | +| `target_kind` | TEXT | NOT NULL | 0 | - | | `time_archived` | INTEGER | NULL | 0 | - | | `time_created` | INTEGER | NOT NULL | 0 | - | | `time_last_opened` | INTEGER | NOT NULL | 0 | - | @@ -3110,6 +3139,7 @@ with no entry there fails generation and `scripts/check_storage_catalog.py`. | Index | Introduced | | --- | --- | | `idx_workspace_archived` | v22 | +| `idx_workspace_target_root_unique` | v96 | ### `workspace_project_binding` @@ -3152,8 +3182,10 @@ with no entry there fails generation and `scripts/check_storage_catalog.py`. | `created_at` | INTEGER | NOT NULL | 0 | - | | `group_id` | TEXT | NOT NULL | 0 | - | | `idempotency_key` | TEXT | NOT NULL | 0 | - | +| `instruction_ref_json` | TEXT | NULL | 0 | - | | `lease_expires_at` | INTEGER | NULL | 0 | - | | `lease_generation` | INTEGER | NOT NULL | 0 | - | +| `note` | TEXT | NULL | 0 | - | | `owner_id` | TEXT | NOT NULL | 0 | - | | `owner_kind` | TEXT | NOT NULL | 0 | - | | `project_id` | TEXT | NOT NULL | 0 | - | diff --git a/architecture/testing.md b/architecture/testing.md index ac05e7a28..8fbdf1acc 100644 --- a/architecture/testing.md +++ b/architecture/testing.md @@ -1100,12 +1100,17 @@ replaces the profile setting itself. The one place that needs the unstripped binary is the desktop bundle, which ships the root daemon: `.github/workflows/desktop-e2e.yml` builds it with `--config 'profile.dev.strip="none"'` so crash symbolication is preserved. -That workflow runs no test suite, so it has no double compile to reclaim. -**That workflow is manual dispatch only since 2026-10-23** — the desktop -foundation's development is paused, so the hosted visible-window qualification -no longer runs on push or on pull requests. See `desktop.md` §"The hosted -qualification is paused (2026-10-23)" for the evidence and for what restoring -it costs. +That workflow builds the root workspace's binary and runs no suite of it, so +it has no double compile to reclaim. **Since 2026-12-01 it is a +compile-and-lint gate**, because the desktop line's development is paused: it +runs the production boundary guard, the renderer build (`tauri.conf.json`'s +`frontendDist` is embedded at compile time, so the host does not build without +it), the root daemon build, the daemon staging, `cargo fmt --check` and +`cargo clippy --all-targets` against `apps/desktop/src-tauri` in the pinned +1.90.0 toolchain. The host test suite and the built-app visible-window +trajectory no longer run there; see `desktop.md` §"The hosted lane is reduced +while the desktop is paused (2026-12-01)" for what the loss is, what the +reduced lane measured, and how to restore it. Release artifacts are unaffected: `[profile.release]` already had `strip = true`, and it is a separate profile. diff --git a/architecture/tool-catalog.md b/architecture/tool-catalog.md index bbaf29ae6..0fb9d546e 100644 --- a/architecture/tool-catalog.md +++ b/architecture/tool-catalog.md @@ -99,6 +99,7 @@ An ordinary session: `ToolRegistryOptions::default()` with a resolved workspace | `text_inspect` | ReadOnly | read_only | yes | visible | | `text_replace_check` | ReadOnly | read_only | no | visible | | `text_security_inspect` | ReadOnly | read_only | no | visible | +| `todoread` | ReadOnly | non_idempotent | no | visible | | `todowrite` | SafeMutating | non_idempotent | no | visible | | `tool_program` | ReadOnly | read_only | yes | visible | | `tool_search` | ReadOnly | non_idempotent | no | visible | @@ -128,6 +129,7 @@ Plan mode's advertised surface: the same registry narrowed to the disclosure own | `read` | ReadOnly | read_only | no | visible | | `repo_search` | ReadOnly | read_only | no | visible | | `skill` | ReadOnly | non_idempotent | no | visible | +| `todoread` | ReadOnly | non_idempotent | no | visible | | `todowrite` | SafeMutating | non_idempotent | no | visible | | `tool_search` | ReadOnly | non_idempotent | no | visible | | `webfetch` | ReadOnly | non_idempotent | no | visible | @@ -201,6 +203,7 @@ The same session with the `lsp` and `security` domains configured as `disabled` | `text_inspect` | ReadOnly | read_only | yes | visible | | `text_replace_check` | ReadOnly | read_only | no | visible | | `text_security_inspect` | ReadOnly | read_only | no | visible | +| `todoread` | ReadOnly | non_idempotent | no | visible | | `todowrite` | SafeMutating | non_idempotent | no | visible | | `tool_program` | ReadOnly | read_only | yes | visible | | `tool_search` | ReadOnly | non_idempotent | no | visible | @@ -212,7 +215,7 @@ The same session with the `lsp` and `security` domains configured as `disabled` | `websearch` | ReadOnly | non_idempotent | no | visible | | `write` | Mutating | non_idempotent | no | visible | -144 rows across 4 surfaces, 12 of them hidden. +147 rows across 4 surfaces, 12 of them hidden. ## Non-claims diff --git a/architecture/tool.md b/architecture/tool.md index c80e38bbb..948b898cd 100644 --- a/architecture/tool.md +++ b/architecture/tool.md @@ -78,6 +78,18 @@ and deterministic joins. New callers should prefer typed `AgentRunId` values, inspection paths for older clients. Child completion still requires explicit parent-side integration when a worktree produced a commit. +The `task` tool also exposes the group-scoped workstream claim lifecycle. A +parent uses `claim` for an advisory responsibility label (default one-hour +lease, maximum 24 hours) and may attach up to 32 same-group claim/run +prerequisites in the same transaction. Version/generation-fenced claim actions +release or adjust it. A child can complete, block, or unblock only the +claim owned by its bound run; `board` may use `mine_only: true` to return +only that actor's claims. A short note (maximum 512 characters) records status +only: it is not instruction text. An optional document-path/anchor reference +is stored opaquely and is not resolved by the claim tool. Expiry never +automatically reaps a claim while its owning run is live; instructions remain +in the linked corpus document rather than in a claim note. + ## Where It Lives ``` diff --git a/architecture/tui.md b/architecture/tui.md index 9a379188d..72a01883e 100644 --- a/architecture/tui.md +++ b/architecture/tui.md @@ -1981,6 +1981,23 @@ Two exceptions to the one-row header, and both are deliberate: the summary (duration, exit code) is dropped so the name, the counter and the affordance survive. The affordance is never clipped. +### Advisor consultation row (M002) + +`/advisor` is a daemon-catalog-owned status read. The daemon resolves `[advisor]` +through the shared `crate::advisor::resolve` path with the selected session's provider +context, bounded to five seconds. The status distinguishes off, resolved, and configured +but unresolvable, and includes the deadline and the forwarding disclosure. +Model changes remain configuration edits because the session selection is for the turn's +provider/model, not an independent advisor selection. + +The consultation itself uses the ordinary tool-call disclosure. The call takes **no +arguments** — the conversation is its input — so the row shows the tool's identity alone and +never a target, and completed advice stays collapsed until expanded. While running, the row shows elapsed +time measured locally from the observed `ToolStarted`; the existing render cadence +refreshes it, and the matching `ToolCompleted` freezes the value. Neither event publishes +the advisor model or elapsed duration, so the row does not claim a model. Its guidance +points to `/stop`, which stops the turn; there is no per-consultation cancel action. + ### A row resolves to its part, not to its message `crates/codegg-tui/src/components/messages/layout.rs` records the **part boundaries** @@ -2043,8 +2060,13 @@ keybind editor. - `Ctrl+O` still opens the workspace dashboard in **both** maps. The new chord is additive; it does not take the dashboard's key. - The palette command is **`/expand-all`** (aliases `expand-disclosures` and - `collapse-all`), dispatched to the same handler, so the toast is identical. -- The toast reads **"all details expanded"** or **"all details collapsed"**. + `collapse-all`), dispatched to the same handler. +- **Neither press announces itself.** The transcript shows which way the + disclosure went, so the gesture is not a toast: it reported what the + operator had just done and could see. This supersedes the acceptance + criterion in + `plans/implementation/tui-main-buffer-text-rendering/004-row-precise-disclosure-and-expand-all.md` + (notification-surface M002, 2026-11-29). Expansion covers every tool call and every reasoning block. Model prose is untouched — it is never collapsed, so there is nothing to expand. @@ -2066,6 +2088,42 @@ added.** `App::show_short_or_info(info_type, lines)` routes output to short toast (≤3 lines) or scrollable `InfoDialog`. Dialog reused if already open. +### The notification surface + +`ToastManager` (`crates/codegg-tui/src/components/toast.rs`) is the only toast surface: four +`ToastLevel` values (`Info`, `Success`, `Warning`, `Error`), at most ten live, three painted, and a +50-record retained history that `tick` never shrinks. + +What may become a toast is recorded, not remembered. `docs/toast-disposition.toml` carries one +entry per `path` + `symbol` + constructor with its disposition — `alert`, `result`, `echo`, +`duplicate`, `repeated`, `test`, `unclassified`, or a `removed` tombstone — and +`scripts/check_toast_disposition.py` fails on an unrecorded site **and** on an entry whose calls are +gone. The four rules the dispositions encode: a toast announces something the operator may have +missed; it is never the only place a message is seen; it never repeats text the destination surface +renders; and it is never generated by a direct action. + +The constructor set is the alert vocabulary, and each constructor states its class where it is +declared (`crates/codegg-tui/src/components/toast.rs`): `error` and `warning` are the alert class +(a failure the operator may have to report; a condition they may have to act on), `success` is an +asynchronous completion they may have navigated away from, `info` is a missable outcome that is +neither — the refusal that explains why a key did nothing, a neutral completion, a next step — +and `add` is the single funnel, for a call site that builds the `Toast` itself. Every one of them +carries the I2 obligation: the same information must also reach a surface that outlives the box. + +M006 set out to remove `info` on the audit's expectation that every `info` site was an echo, a +duplicate, or a result. The measured surviving set did not support that: 56 sites remain on `info`, +49 of them missable outcomes. Removing it would have relabelled those as `warning` — the wrong +class, and a longer life for text that is not a fault. The set stays, and +`docs/toast-disposition.toml` is what makes an echo impossible to ship quietly: every site is +recorded with its class, so the constructor choice is written down and reviewed, not inferred. + +The retained history is one body with two views. + `/logs` shows the daemon log tail followed by the +notifications; `/toast` shows the notifications alone. `App::open_logs_window` takes a +`LogsView` (`All` or `Notifications`) and a one-shot `pending_logs_view` lets `/toast` open the +docked Logs panel at the notification view without changing what the panel shows to anyone else. +One builder formats the records, so the two views cannot disagree about a record's shape. + ### Interactive Terminals (M003) Reference TUI experience over the M002 attach/resume protocol. The diff --git a/architecture/workspace.md b/architecture/workspace.md index 9eb00e4b3..10478d272 100644 --- a/architecture/workspace.md +++ b/architecture/workspace.md @@ -27,47 +27,47 @@ every daemon-owned execution path. - `WorkspaceId` — typed `String` newtype identifying a registered workspace. Generated by the registry at registration time; never derived from path text so renames and host moves do not rename identifiers. -- `WorkspaceRecord` — persisted registry entry (`id`, `canonical_root`, - `display_name`, `created_at`, `last_opened_at`, `archived_at`). -- `WorkspaceRegistry` — daemon-owned registry. Deduplicates canonical roots - via `get_or_register`; requires an absolute root path and rejects - nonexistent paths, file paths, and a symlink at the selected root. - Hydrates from a `WorkspaceStore` and serves - subsequent reads from an in-memory `DashMap` index. +- `WorkspaceRecord` — persisted identity plus `WorkspaceTarget`. A local + target keeps its canonical filesystem root in `canonical_root: PathBuf`; + an SSH target stores an opaque `RemoteHostRef` and validated text-only + `TargetRoot`, while the compatibility path field stays empty. +- `WorkspaceRegistry` — daemon-owned registry. Local registration still + canonicalizes existing filesystem directories and deduplicates by canonical + root. The typed remote-registration sibling refuses until a later milestone + supplies an authenticated, host-canonicalized entry point. Hydration serves + records from the `WorkspaceStore` and an in-memory `DashMap` index. - `WorkspaceStore` — persistence trait. Two implementations: `SqliteWorkspaceStore` (the production path) and `InMemoryWorkspaceStore` (tests). -- `ExecutionContext` — immutable, `Arc`-wrapped context carrying - `workspace_id`, `workspace_root`, `session_id`, `allowed_read_roots`, - `allowed_write_roots`, and a `CancellationToken`. Every daemon-owned - execution path receives one of these through `TurnRunInput.execution`. +- `ExecutionContext` — immutable, `Arc`-wrapped context carrying the + workspace target and target-scoped read/write roots. Local grants remain + `PathBuf`; remote roots remain validated text and cannot be materialized + as local paths. Every daemon-owned execution path receives one through + `TurnRunInput.execution`. ## Path policy -`ExecutionContext` exposes three helpers that should be the only way tools -and subsystems materialize a path: +`ExecutionContext` exposes three target-aware resolvers: -- `resolve_relative_cwd(requested).await` — picks a working directory. `None` and - empty strings resolve to the workspace root; relative paths join the - workspace root and canonicalize; absolute paths must lie under an - explicitly allowed root. -- `resolve_read_path(requested).await` — verifies and canonicalizes a read - target. Existing paths canonicalize directly; paths that don't yet - exist canonicalize the nearest existing ancestor and append the missing - suffix. Relative paths must resolve under the workspace root. -- `resolve_write_path(requested).await` — same rules as read, plus the - destination must lie under `allowed_write_roots`. +- `resolve_relative_cwd(requested).await` — resolves a local request by + canonical filesystem paths, or a remote request by bounded POSIX text join + and containment against the same target's allowed roots. +- `resolve_read_path(requested).await` and `resolve_write_path(requested).await` + apply that target's read/write policy. Local results are `PathBuf`; remote + results are `ResolvedWorkspacePath::Remote { host, root }` and expose no + local path conversion. Remote registration remains refused in R001, so no + existing request can use these resolvers for remote execution. -`PathPolicyError` distinguishes `OutsideWorkspace`, `OutsideAllowedRoots`, -`UnsupportedAlias`, `CanonicalizationFailed`, `EmptyPath`, and `ContainsNul` -so callers can render precise diagnostics. +`PathPolicyError` distinguishes local and target-scoped escape, invalid +encoding, control-character, length, canonicalization, and NUL failures so +callers can render precise diagnostics. ## Session binding The authoritative relation is: ```text -Session -> ProjectId + WorkspaceId -> canonical root +Session -> ProjectId + WorkspaceId -> target-scoped workspace root Project discovery may register an observed canonical root through the existing workspace registry, but it does not activate a workspace service bundle. A @@ -108,6 +108,12 @@ CREATE INDEX idx_workspace_archived ON workspace(time_archived); CREATE INDEX idx_session_workspace_repair ON session(workspace_id); ``` +Migration v96 rebuilds `workspace` to replace the inline local-root unique +constraint with `UNIQUE(target_kind, host_ref, canonical_root)`. Existing +rows are backfilled as `('local', '', canonical_root)`; SSH roots are stored +only as bounded absolute text with an opaque host reference. The local +registry remains the only successful registration path in R001. + The `session.workspace_id` column itself exists since the initial session schema; v22 only creates the workspace registry table and an index to accelerate workspace-based session lookups. Existing sessions are lazily diff --git a/architecture/workstream_claims.md b/architecture/workstream_claims.md index 16914e811..320fe8d53 100644 --- a/architecture/workstream_claims.md +++ b/architecture/workstream_claims.md @@ -9,10 +9,9 @@ Git policy, sandbox grants, scheduler admission, or run creation. - `crates/codegg-core/src/workstream_claim.rs` owns typed claim, actor, prerequisite, state, CAS, target-normalization, and SQLite store contracts. -- `crates/codegg-core/src/session/schema.rs::migrate_v79` owns the additive - schema. That migration is **version 79 of the chain**, not the current - layout: `STORAGE_LAYOUT_VERSION` is **87**, because the writer permit (v86) - and the session launch (v87) landed after it. +- `crates/codegg-core/src/session/schema.rs::migrate_v79` owns the original + claim schema. P002's nullable note and instruction-reference columns are + additive in `migrate_v99`; `STORAGE_LAYOUT_VERSION` is **99**. - `crates/codegg-protocol/src/projection/workstream.rs` joins authorized claim summaries to the existing session projection. It does not access storage or authorize a caller. @@ -45,6 +44,32 @@ junctions and cannot establish filesystem case-fold behavior; such labels stay advisory and all actual access remains subject to existing execution containment and permission reductions. +## P002 claim lifecycle surface + +The `task` tool keeps the existing claim, release, and handoff-request +actions and adds `complete_claim`, `block_claim`, and `unblock_claim`. +Each transition is compare-and-swap fenced by the current version and lease +generation; a stale call returns a typed conflict that names the current +version. The execution actor comes from the bound orchestration context, not +from tool input. A group owner may release or adjust a member's claim; a child +may transition only its own claim. + +A new claim defaults to a 3600-second lease and accepts 1–86400 seconds. The +existing `claim` action accepts up to 32 typed claim/run prerequisites and +persists them atomically with the claim; idempotent retries must supply the +same edges. A lease expiry makes a claim replaceable only after its owning run +is terminal; +an expired lease is not automatically reaped while the run remains live. The +parent may explicitly release a live or expired claim through the existing +CAS action. + +Notes are optional status text capped at 512 Unicode scalar values. They are +not instructions and never become task prose. An optional instruction +reference stores only a bounded relative document path and anchor; it is +opaque here and is not resolved. The `board` action's `mine_only` flag +filters claims, dependency edges, and handoff notices to the calling actor's +own claims. + ## Transactions and recovery Claim creation, lifecycle changes, dependency insertion, and corresponding @@ -60,8 +85,11 @@ available through the bounded group inspection API. Dependencies reference a claim or an existing group-member run, never both. The store rejects self-edges, cross-group/project/workspace references, -duplicate edges, cycles, and fanout above 32. Adding an edge is revision-CAS -guarded. These edges do not auto-submit work or assert that a prerequisite's +duplicate edges, cycles, and fanout above 32. Adding an edge through the +existing adjustment API is revision-CAS guarded; claim-time prerequisites are +validated under the claim's creation transaction. The board exposes claim +states and edges together so a caller can see whether a prerequisite is still +pending. These edges do not auto-submit work or assert that a prerequisite's agent-authored report is true. ## Projection and audit diff --git a/assets/agents/build.toml b/assets/agents/build.toml index 85043dec5..58c5bdb6f 100644 --- a/assets/agents/build.toml +++ b/assets/agents/build.toml @@ -1,8 +1,12 @@ [agent] name = "build" role = "executor" -description = "Default agent with full permissions" +capability = "full" +description = "Default session agent" mode = "Primary" +selectable = false +subagent = false +default = true [agent.permissions] # Dispatching a job, task, or subagent is part of this agent's own scope, not diff --git a/assets/agents/compaction.toml b/assets/agents/compaction.toml index 1c3b92893..7da48699f 100644 --- a/assets/agents/compaction.toml +++ b/assets/agents/compaction.toml @@ -1,8 +1,12 @@ [agent] name = "compaction" role = "compactor" +capability = "read" description = "Context compaction agent" mode = "Subagent" +selectable = false +subagent = false +default = false hidden = true runtime_kind = "compaction" diff --git a/assets/agents/explore.toml b/assets/agents/explore.toml index a383ea558..eb8320f6f 100644 --- a/assets/agents/explore.toml +++ b/assets/agents/explore.toml @@ -1,8 +1,12 @@ [agent] name = "explore" role = "explorer" +capability = "read" description = "Read-only exploration agent" mode = "All" +selectable = false +subagent = true +default = false # Read-only git inspection. `[agent.permissions]` is per tool, so `git = # "allow"` would also authorize `git push` and `git = "deny"` would cost this diff --git a/assets/agents/general.toml b/assets/agents/general.toml index 0c0a7c7c0..0d92ef43c 100644 --- a/assets/agents/general.toml +++ b/assets/agents/general.toml @@ -1,8 +1,12 @@ [agent] name = "general" role = "executor" +capability = "full" description = "Subagent without todo/goal management" mode = "Subagent" +selectable = true +subagent = true +default = false [agent.permissions] todowrite = "deny" diff --git a/assets/agents/plan.toml b/assets/agents/plan.toml index c3d3dc06b..096015f97 100644 --- a/assets/agents/plan.toml +++ b/assets/agents/plan.toml @@ -1,8 +1,12 @@ [agent] name = "plan" role = "planner" +capability = "read" description = "Read-only agent for planning" mode = "Primary" +selectable = true +subagent = false +default = false # Read-only git inspection. `[agent.permissions]` is per tool, so `git = # "allow"` would also authorize `git push` and `git = "deny"` would cost this diff --git a/assets/agents/research.toml b/assets/agents/research.toml index b065d2986..40d493be2 100644 --- a/assets/agents/research.toml +++ b/assets/agents/research.toml @@ -1,8 +1,12 @@ [agent] name = "research" role = "researcher" +capability = "read" description = "Long-horizon research agent. Uses the `research` tool for structured multi-source answers and the `websearch` tool for quick lookups." mode = "All" +selectable = true +subagent = true +default = false color = "magenta" runtime_kind = "research" prompt_file = "prompts/agents/research.md" diff --git a/assets/agents/security-review.toml b/assets/agents/security-review.toml index 4af1811da..7d19ae3db 100644 --- a/assets/agents/security-review.toml +++ b/assets/agents/security-review.toml @@ -1,8 +1,12 @@ [agent] name = "security-review" role = "security_reviewer" +capability = "full" description = "Defensive security review of changed code. Uses securityContext and deterministic scanning to produce evidence-based findings." mode = "Subagent" +selectable = true +subagent = true +default = false runtime_kind = "security_review" [agent.permissions] diff --git a/assets/agents/summary.toml b/assets/agents/summary.toml index 94633a4c5..414598123 100644 --- a/assets/agents/summary.toml +++ b/assets/agents/summary.toml @@ -1,8 +1,12 @@ [agent] name = "summary" role = "summarizer" +capability = "read" description = "Generates session summaries" mode = "Subagent" +selectable = false +subagent = false +default = false hidden = true runtime_kind = "summary" diff --git a/assets/agents/title.toml b/assets/agents/title.toml index f7d6ede3c..cc833b311 100644 --- a/assets/agents/title.toml +++ b/assets/agents/title.toml @@ -1,8 +1,12 @@ [agent] name = "title" role = "title" +capability = "read" description = "Generates session titles" mode = "Subagent" +selectable = false +subagent = false +default = false hidden = true runtime_kind = "title" diff --git a/assets/agents/verifier.toml b/assets/agents/verifier.toml index 32e764357..e4a390772 100644 --- a/assets/agents/verifier.toml +++ b/assets/agents/verifier.toml @@ -3,8 +3,15 @@ name = "verifier" role = "semantic_verifier" description = "Independent, read-only semantic verification of a producer result." mode = "Subagent" +selectable = false +subagent = true +default = false hidden = true prompt_file = "prompts/agents/verifier.md" +# Read-only inspection plus non-mutating execution: `bash` and `test` come from +# the class, `bash` bounded by the read-only classifier. Non-mutating means not +# *source*-mutating; `cargo test` still writes `target/`. +capability = "verify" [agent.permissions] read = "allow" @@ -19,7 +26,9 @@ edit = "deny" replace = "deny" apply_patch = "deny" lsp_preview_apply = "deny" -bash = "deny" +# `bash` is supplied by the `verify` class and bounded by the read-only command +# classifier. It is not denied here: an explicit deny wins over the class, which +# would leave the verifier unable to run the checks it exists to verify. terminal = "deny" # The Python tool is `python_script` (`src/python_script/tool.rs`). There is no # tool named `python`; an earlier `python = "deny"` entry denied nothing and @@ -35,7 +44,9 @@ question = "deny" # There is no tool named `permission`; the human-interaction tool is # `question`, denied above. The earlier `permission = "deny"` entry denied # nothing and read as though it did. -test = "deny" +# `test` is supplied by the `verify` class. It is a modelled surface — its argv is +# either host-constructed or validated against the custom-command allowlist — so it +# needs no additional binding here. repo_fetch = "deny" research = "deny" webfetch = "deny" diff --git a/assets/prompts/contracts/primary.md b/assets/prompts/contracts/primary.md deleted file mode 100644 index 9391b2c63..000000000 --- a/assets/prompts/contracts/primary.md +++ /dev/null @@ -1,35 +0,0 @@ -# Primary Agent Contract - -Primary agents are the top-level agent the user interacts with directly. - -## Capabilities -- Full tool access (subject to permission overrides) -- Can spawn subagents via the `task` tool -- Has access to plan_enter/plan_exit for goal management -- Has access to todowrite/todoread for task tracking - -## Constraints -- Must produce a final response (not just tool calls) -- Should delegate deep exploration to subagents when appropriate -- Should respect user intent and avoid unnecessary file mutations - -## Tool Programs (direct vs programmatic) - -Use the `tool_program` tool for predictable, bounded, multi-step read-only -workflows where intermediate outputs do not need semantic judgment: - -- **Use tool_program** for: parallel file reads, grep/filter pipelines, - repository map aggregation, mechanical argument chaining, deterministic - validation across many files, batch metadata collection. -- **Use direct tools** for: semantic judgment, approvals, mutation, - final source/citation validation, uncertain next steps, single reads - where the model needs to inspect and reason about the output. - -When using tool_program: -- Declare a finite stopping condition and result schema. -- Only call tools in the read-only palette (read, glob, grep, list). -- Do not use tool_program for write, edit, bash, git mutation, or - any tool with side effects. -- Intermediate tool call outputs stay in the program artifact ledger - and do NOT enter the parent transcript. Only the final program - result is projected. diff --git a/assets/prompts/contracts/subagent.md b/assets/prompts/contracts/subagent.md deleted file mode 100644 index d942a4aee..000000000 --- a/assets/prompts/contracts/subagent.md +++ /dev/null @@ -1,25 +0,0 @@ -# Subagent Contract - -Subagents are spawned by primary agents to perform focused tasks. - -## Capabilities -- Access to tools permitted by their permission set -- Can read files, search code, and perform allowed operations -- Return structured results to the spawning agent - -## Constraints -- Cannot spawn further subagents (depth limit enforced) -- Should focus on the specific task assigned -- Should not modify files unless explicitly permitted -- Must complete within step budget - -## Tool Programs (direct vs programmatic) - -Subagents may use `tool_program` for multi-step read-only workflows. -Use tool_program when a task requires 3+ sequential or parallel -read-only tool calls with deterministic logic (filtering, aggregation, -formatting). Use direct tools when the task requires semantic reasoning -about each result or when mutation is needed. - -Intermediate outputs stay in the program artifact ledger and do not -enter the subagent transcript. Only the final result is projected. diff --git a/codegg.example.jsonc b/codegg.example.jsonc index 123486221..2b4fa5853 100755 --- a/codegg.example.jsonc +++ b/codegg.example.jsonc @@ -374,10 +374,15 @@ // ActionKey enum (send, newline, cancel, clear_session, new_session, // toggle_sidebar, switch_agent, select_model, navigate_up, ...). // An unparseable key or an unknown action is silently ignored. + // Session-agent selection uses the declared `selectable` axis. Agent entries may + // independently declare `selectable`, `subagent`, and `default`; legacy `mode` + // values project onto the first two when explicit axes are absent. + // Example agent override: `"agent": {"custom": { + // "selectable": true, "subagent": false, "default": false}}`. "keybinds": { "ctrl+enter": "send", "ctrl+l": "clear_session", - "ctrl+p": "switch_agent" + "ctrl+a": "switch_agent" }, // Saved side-panel hotkeys: digit -> panel type. Assign these in the TUI diff --git a/crates/codegg-cli/src/main.rs b/crates/codegg-cli/src/main.rs index 87047a808..39f39271c 100755 --- a/crates/codegg-cli/src/main.rs +++ b/crates/codegg-cli/src/main.rs @@ -455,6 +455,11 @@ enum Commands { #[command(subcommand)] command: mcp::cli::McpCommand, }, + /// Diagnose or explicitly trust an SSH host (local only; no remote CodeGG process) + Remote { + #[command(subcommand)] + command: RemoteCommand, + }, /// Run a deep research query Research { /// The research question @@ -537,6 +542,104 @@ enum Commands { )] stdio: bool, }, + #[command(about = "Start or proxy to the local Unix-socket execution node")] + Node { + #[arg( + long, + help = "Run the private node listener", + conflicts_with = "proxy", + required_unless_present = "proxy" + )] + run: bool, + #[arg( + long, + help = "Bridge stdio to the node socket, auto-starting the listener if absent", + conflicts_with = "run", + required_unless_present = "run" + )] + proxy: bool, + #[arg(long, help = "Explicit absolute Unix-socket path")] + socket: Option, + #[arg( + long, + help = "Refuse rather than start a missing node (proxy mode only)", + requires = "proxy", + conflicts_with = "run" + )] + no_start: bool, + }, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)] +#[value(rename_all = "lowercase")] +enum RemoteConfigSource { + #[default] + Codegg, + System, +} + +#[derive(Args, Clone, Debug)] +struct RemoteHostArgs { + /// SSH host name or address (never a command-line option). + host: String, + /// SSH port. + #[arg(long, default_value_t = 22)] + port: u16, + /// Optional SSH user. + #[arg(long)] + user: Option, + /// Reference a private-key file; key material is never read by CodeGG. + #[arg(long, conflicts_with = "identity_agent")] + identity_file: Option, + /// Reference an SSH agent socket; the socket is not copied or logged. + #[arg(long, conflicts_with = "identity_file")] + identity_agent: Option, + /// Configuration source. System mode may execute commands from SSH config. + #[arg(long, value_enum, default_value_t = RemoteConfigSource::Codegg)] + config_source: RemoteConfigSource, + /// Acknowledge that system SSH config can execute local commands on this machine. + #[arg(long)] + confirm_system_config_risk: bool, +} + +impl RemoteHostArgs { + fn descriptor(&self) -> codegg::remote::HostDescriptor { + use codegg::remote::{ConfigSource, HostDescriptor, IdentityReference}; + let mut host = HostDescriptor::new(self.host.clone()); + host.port = self.port; + host.user = self.user.clone(); + host.identity = self + .identity_file + .clone() + .map(IdentityReference::File) + .or_else(|| { + self.identity_agent + .clone() + .map(IdentityReference::AgentSocket) + }); + host.config_source = match self.config_source { + RemoteConfigSource::Codegg => ConfigSource::Codegg, + RemoteConfigSource::System => ConfigSource::System, + }; + host + } +} + +#[derive(Subcommand, Clone, Debug)] +enum RemoteCommand { + /// Read-only SSH host facts; does not register a workspace. + Probe { + #[command(flatten)] + host: RemoteHostArgs, + /// Remote directory to inspect; interpreted only by the fixed remote probe. + #[arg(long, default_value = ".")] + path: String, + }, + /// Review an unauthenticated fingerprint and explicitly add host trust. + Trust { + #[command(flatten)] + host: RemoteHostArgs, + }, } #[derive(Subcommand, Clone, Debug)] @@ -1756,6 +1859,32 @@ mod cli_surface_tests { assert!(matches!(cli.command, Some(Commands::Host { stdio: false }))); } + #[test] + fn node_cli_requires_one_mode_and_parses_proxy_flags() { + assert!(Cli::try_parse_from(["codegg", "node"]).is_err()); + assert!(Cli::try_parse_from(["codegg", "node", "--run", "--proxy"]).is_err()); + assert!(Cli::try_parse_from(["codegg", "node", "--run", "--no-start"]).is_err()); + + let cli = Cli::try_parse_from([ + "codegg", + "node", + "--proxy", + "--socket", + "/tmp/codegg-node.sock", + "--no-start", + ]) + .expect("proxy flags parse"); + assert!(matches!( + cli.command, + Some(Commands::Node { + run: false, + proxy: true, + socket: Some(path), + no_start: true, + }) if path == std::path::Path::new("/tmp/codegg-node.sock") + )); + } + #[test] fn internal_transports_stay_parseable_but_hidden() { for args in [ @@ -2116,6 +2245,21 @@ async fn main() -> Result<(), AppError> { } } } + Commands::Node { + run, + proxy, + socket, + no_start, + } => { + if *run { + codegg::node::run(socket.clone()) + .map_err(|error| AppError::Other(anyhow::anyhow!(error)))?; + } else if *proxy { + codegg::node::proxy(socket.clone(), *no_start) + .await + .map_err(|error| AppError::Other(anyhow::anyhow!(error)))?; + } + } Commands::Validate { config } => { cmd_validate(config.as_deref()).await?; } @@ -2154,6 +2298,7 @@ async fn main() -> Result<(), AppError> { Commands::Mcp { command } => { mcp::cli::exec_mcp_command(command.clone())?; } + Commands::Remote { command } => cmd_remote(command).await?, Commands::Research { question, mode, @@ -3641,6 +3786,69 @@ fn cmd_config(command: ConfigSubcommand) -> Result<(), AppError> { } } +async fn cmd_remote(command: &RemoteCommand) -> Result<(), AppError> { + let (host_args, path) = match command { + RemoteCommand::Probe { host, path } => (host, Some(path.as_str())), + RemoteCommand::Trust { host } => (host, None), + }; + let descriptor = host_args.descriptor(); + let data_dir = codegg::storage::paths::DaemonPaths::default_data_root(); + let manager = codegg::remote::RemoteConnectionManager::new(data_dir); + if descriptor.config_source == codegg::remote::ConfigSource::System + && host_args.confirm_system_config_risk + { + eprintln!("Risk acknowledged: resolving system SSH config may execute local commands on this machine."); + } + let result = match path { + Some(path) => { + let facts = manager + .probe(&descriptor, path, host_args.confirm_system_config_risk) + .await + .map_err(|error| AppError::Other(anyhow::anyhow!(error)))?; + println!("host: {}:{}", descriptor.host, descriptor.port); + println!("os: {}", facts.os); + println!("architecture: {}", facts.arch); + println!("libc: {}", facts.libc); + println!("home: {} (writable: {})", facts.home, facts.home_writable); + println!( + "exec-capable (real ELF copy): {}", + facts + .exec_capable + .map_or("unknown", |value| if value { "yes" } else { "no" }) + ); + println!("disk (KiB total, used, available): {}", facts.disk); + println!("shell: {}", facts.shell); + println!( + "CodeGG: {}", + facts.codegg_version.as_deref().unwrap_or("not present") + ); + println!( + "Landlock: {}", + if facts.landlock { + "present" + } else { + "not detected" + } + ); + println!( + "bubblewrap: {}", + if facts.bubblewrap { + "present" + } else { + "not detected" + } + ); + println!("target directory: {}", facts.target_canonical); + Ok(()) + } + None => manager + .trust_interactively(&descriptor, host_args.confirm_system_config_risk) + .await + .map_err(|error| AppError::Other(anyhow::anyhow!(error))), + }; + result +} + fn cmd_auth(command: AuthSubcommand) -> Result<(), AppError> { let cli = AuthCli::new(); match command { @@ -4070,6 +4278,7 @@ async fn run_single_shot(prompt: &str, cli: &Cli) -> Result<(), AppError> { } let compiled_prompt = codegg::agent::prompt::PromptCompiler::compile( codegg::agent::prompt::PromptCompilerInput { + subject: codegg::agent::prompt::PromptSubject::Primary, agent: &safe_agent, model_profile: &resolved_profile, config: &config, @@ -5523,6 +5732,7 @@ mod single_shot_ledger_tests { codegg::model_profile::ModelProfileResolver::new(&config).resolve("single-shot-model"); let adapter = codegg::model_profile::resolve_adapter(None, "single-shot-model"); PromptCompiler::compile(PromptCompilerInput { + subject: codegg::agent::prompt::PromptSubject::Primary, agent, model_profile: &model_profile, config: &config, diff --git a/crates/codegg-cli/tests/exec_workspace_path_policy.rs b/crates/codegg-cli/tests/exec_workspace_path_policy.rs index 4cee023b1..03e2672bf 100644 --- a/crates/codegg-cli/tests/exec_workspace_path_policy.rs +++ b/crates/codegg-cli/tests/exec_workspace_path_policy.rs @@ -424,10 +424,12 @@ fn workspace_scoped_tool_call_is_authorized_by_a_workspace_path_policy(mode: Hea let stop = Arc::new(AtomicBool::new(false)); let server = spawn_scripted_openai(listener, Arc::clone(&requests), Arc::clone(&stop)); + // `general`, not `build`: the roster's default agent is deliberately not + // selectable by name (ADR-0068), so naming it is refused. let json_input = serde_json::json!({ "prompt": "Read the marker file in the workspace and report its contents.", "model": format!("{PROVIDER_ID}/{MODEL_ID}"), - "agent": "build", + "agent": "general", }) .to_string(); diff --git a/crates/codegg-cli/tests/node.rs b/crates/codegg-cli/tests/node.rs new file mode 100644 index 000000000..5ec10e31a --- /dev/null +++ b/crates/codegg-cli/tests/node.rs @@ -0,0 +1,334 @@ +#![cfg(unix)] + +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::process::Stdio; +use std::time::Duration; + +use serde_json::{json, Value}; +use tempfile::tempdir; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::process::{Child, ChildStdin, ChildStdout, Command}; +use tokio::time::timeout; + +struct Proxy { + child: Child, + stdin: ChildStdin, + stdout: BufReader, +} + +impl Proxy { + async fn spawn(socket: &Path, home: &Path, no_start: bool) -> Self { + let mut command = Command::new(env!("CARGO_BIN_EXE_codegg")); + command + .arg("node") + .arg("--proxy") + .arg("--socket") + .arg(socket) + .env_clear() + .env("HOME", home) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()); + if no_start { + command.arg("--no-start"); + } + let mut child = command.spawn().expect("spawn node proxy"); + let stdin = child.stdin.take().expect("proxy stdin"); + let stdout = BufReader::new(child.stdout.take().expect("proxy stdout")); + Self { + child, + stdin, + stdout, + } + } + + async fn request(&mut self, request: Value) -> Value { + let mut bytes = serde_json::to_vec(&request).expect("encode request"); + bytes.push(b'\n'); + self.stdin + .write_all(&bytes) + .await + .expect("write proxy request"); + self.stdin.flush().await.expect("flush proxy request"); + let mut line = String::new(); + let read = timeout(Duration::from_secs(8), self.stdout.read_line(&mut line)) + .await + .expect("proxy response deadline") + .expect("read proxy response"); + assert!(read > 0, "proxy closed before a complete response"); + let response: Value = serde_json::from_str(&line).expect("JSON-RPC response"); + if std::env::var_os("CODEGG_NODE_TEST_TRANSCRIPT").is_some() { + eprintln!("node transcript: {request} => {response}"); + } + response + } + + async fn kill(&mut self) { + let _ = self.child.start_kill(); + let _ = timeout(Duration::from_secs(3), self.child.wait()).await; + } +} + +fn spawn_daemon(socket: &Path, home: &Path) -> Child { + Command::new(env!("CARGO_BIN_EXE_codegg")) + .arg("node") + .arg("--run") + .arg("--socket") + .arg(socket) + .env_clear() + .env("HOME", home) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::inherit()) + .spawn() + .expect("spawn node daemon") +} + +async fn wait_for_socket(socket: &Path) { + timeout(Duration::from_secs(10), async { + while !socket.exists() { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("node socket startup deadline"); +} + +impl Drop for Proxy { + fn drop(&mut self) { + let _ = self.child.start_kill(); + } +} + +fn initialize(id: u64) -> Value { + json!({ + "jsonrpc": "2.0", + "id": id, + "method": "initialize", + "params": { "apiVersion": 1, "buildId": "integration-test", "capabilities": ["lifecycle"] } + }) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn proxy_auto_start_private_node_runs_lifecycle_and_survives_proxy_death() { + let home = tempdir().expect("private test home"); + let node_dir = home.path().join("node"); + std::fs::create_dir(&node_dir).expect("node directory"); + std::fs::set_permissions(&node_dir, std::fs::Permissions::from_mode(0o700)) + .expect("private node directory mode"); + let socket = node_dir.join("node.sock"); + + let mut refused = Proxy::spawn(&socket, home.path(), true).await; + refused.stdin.shutdown().await.expect("close proxy input"); + let status = timeout(Duration::from_secs(10), refused.child.wait()) + .await + .expect("--no-start refusal deadline") + .expect("--no-start process status"); + assert!( + !status.success(), + "--no-start must refuse when the socket is absent" + ); + drop(refused); + assert!(!socket.exists(), "--no-start must not create a node"); + + let mut first = Proxy::spawn(&socket, home.path(), false).await; + let init = first.request(initialize(1)).await; + assert_eq!(init["result"]["apiVersion"], 1); + assert_eq!(init["result"]["capabilities"], json!(["lifecycle"])); + assert_eq!( + std::fs::metadata(&node_dir).unwrap().permissions().mode() & 0o777, + 0o700 + ); + assert_eq!( + std::fs::symlink_metadata(&socket) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o600 + ); + + let mut second = Proxy::spawn(&socket, home.path(), true).await; + let second_init = second.request(initialize(2)).await; + assert_eq!(second_init["result"]["apiVersion"], 1); + let health = second + .request(json!({ "jsonrpc": "2.0", "id": 3, "method": "health", "params": null })) + .await; + assert_eq!(health["result"]["healthy"], true); + + first.kill().await; + drop(first); + let health_after_proxy_death = second + .request(json!({ "jsonrpc": "2.0", "id": 4, "method": "health", "params": null })) + .await; + assert_eq!(health_after_proxy_death["result"]["healthy"], true); + + let third = Proxy::spawn(&socket, home.path(), true).await; + let mut third = third; + let third_init = third.request(initialize(5)).await; + assert_eq!(third_init["result"]["apiVersion"], 1); + let third_health = third + .request(json!({ "jsonrpc": "2.0", "id": 6, "method": "health", "params": null })) + .await; + assert_eq!(third_health["result"]["healthy"], true); + third.kill().await; + drop(third); + + let workspace = home.path().join("workspace"); + std::fs::create_dir(&workspace).expect("workspace"); + let attach = second + .request(json!({ + "jsonrpc": "2.0", + "id": 7, + "method": "attach", + "params": { "root": workspace.to_string_lossy(), "requestedIsolation": "read_only" } + })) + .await; + assert_eq!( + attach["result"]["canonicalRoot"], + workspace.canonicalize().unwrap().to_string_lossy().as_ref() + ); + assert!(attach["result"]["toolCount"].as_u64().unwrap_or_default() > 0); + assert_eq!(attach["result"]["requestedIsolation"], "read_only"); + assert!(attach["result"]["obtainedIsolation"]["backend"] + .as_str() + .is_some()); + assert!( + !workspace.join(".codegg/runs").exists(), + "the registry RunStore must remain under node scratch" + ); + let scratch = node_dir.join("scratch"); + assert!(scratch.is_dir(), "the node-local scratch root must exist"); + assert_eq!( + std::fs::metadata(&scratch).unwrap().permissions().mode() & 0o777, + 0o700 + ); + if std::env::var_os("CODEGG_NODE_TEST_TRANSCRIPT").is_some() { + eprintln!( + "node runtime evidence: tool_count={} requested_isolation={} obtained={} scratch={} directory_mode=0700 socket_mode=0600", + attach["result"]["toolCount"], + attach["result"]["requestedIsolation"], + attach["result"]["obtainedIsolation"], + scratch.display() + ); + } + let canonical_root = attach["result"]["canonicalRoot"].as_str().unwrap(); + + let detached = second + .request(json!({ + "jsonrpc": "2.0", + "id": 8, + "method": "detach", + "params": { "root": canonical_root } + })) + .await; + assert_eq!(detached["result"]["detached"], true); + + let attached_again = second + .request(json!({ + "jsonrpc": "2.0", + "id": 10, + "method": "attach", + "params": { "root": workspace.to_string_lossy(), "requestedIsolation": "read_only" } + })) + .await; + assert_eq!(attached_again["result"]["canonicalRoot"], canonical_root); + let detached_again = second + .request(json!({ + "jsonrpc": "2.0", + "id": 11, + "method": "detach", + "params": { "root": canonical_root } + })) + .await; + assert_eq!(detached_again["result"]["detached"], true); + let empty_health = second + .request(json!({ "jsonrpc": "2.0", "id": 12, "method": "health", "params": null })) + .await; + assert_eq!(empty_health["result"]["attachedWorkspaces"], 0); + + let shutdown = second + .request(json!({ "jsonrpc": "2.0", "id": 13, "method": "shutdown", "params": null })) + .await; + assert_eq!(shutdown["result"]["shuttingDown"], true); + let mut trailing_output = String::new(); + let trailing_bytes = timeout( + Duration::from_secs(5), + second.stdout.read_line(&mut trailing_output), + ) + .await + .expect("proxy stdout EOF after graceful node shutdown") + .expect("read proxy stdout after shutdown"); + assert_eq!( + trailing_bytes, 0, + "proxy must not emit data after shutdown response" + ); + let status = timeout(Duration::from_secs(5), second.child.wait()) + .await + .expect("proxy should close after graceful node shutdown") + .expect("proxy child status"); + assert!(status.success()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn proxy_recovers_stale_socket_after_daemon_crash() { + let home = tempdir().expect("private test home"); + let node_dir = home.path().join("node"); + std::fs::create_dir(&node_dir).expect("node directory"); + std::fs::set_permissions(&node_dir, std::fs::Permissions::from_mode(0o700)) + .expect("private node directory mode"); + let socket = node_dir.join("node.sock"); + + let mut daemon = spawn_daemon(&socket, home.path()); + wait_for_socket(&socket).await; + let mut attached_proxy = Proxy::spawn(&socket, home.path(), true).await; + let init = attached_proxy.request(initialize(1)).await; + assert_eq!(init["result"]["apiVersion"], 1); + + daemon.start_kill().expect("kill node daemon"); + let daemon_status = timeout(Duration::from_secs(3), daemon.wait()) + .await + .expect("crashed daemon exit deadline") + .expect("crashed daemon status"); + assert!(!daemon_status.success()); + assert!(socket.exists(), "SIGKILL should leave a stale socket path"); + + let mut trailing = String::new(); + let bytes = timeout( + Duration::from_secs(5), + attached_proxy.stdout.read_line(&mut trailing), + ) + .await + .expect("proxy observes daemon death promptly") + .expect("read proxy output after daemon death"); + assert_eq!(bytes, 0, "proxy must close when its daemon dies"); + let proxy_status = timeout(Duration::from_secs(5), attached_proxy.child.wait()) + .await + .expect("proxy exits after daemon death") + .expect("proxy status after daemon death"); + assert!(proxy_status.success()); + drop(attached_proxy); + + let mut recovered = Proxy::spawn(&socket, home.path(), false).await; + let recovered_init = recovered.request(initialize(2)).await; + assert_eq!(recovered_init["result"]["apiVersion"], 1); + let shutdown = recovered + .request(json!({ "jsonrpc": "2.0", "id": 3, "method": "shutdown", "params": null })) + .await; + assert_eq!(shutdown["result"]["shuttingDown"], true); + let mut trailing = String::new(); + let bytes = timeout( + Duration::from_secs(5), + recovered.stdout.read_line(&mut trailing), + ) + .await + .expect("recovered proxy shutdown EOF") + .expect("read recovered proxy EOF"); + assert_eq!(bytes, 0); + let status = timeout(Duration::from_secs(5), recovered.child.wait()) + .await + .expect("recovered proxy exits") + .expect("recovered proxy status"); + assert!(status.success()); +} diff --git a/crates/codegg-config/src/config_catalog.rs b/crates/codegg-config/src/config_catalog.rs index 0c1b508d3..8625a66a5 100644 --- a/crates/codegg-config/src/config_catalog.rs +++ b/crates/codegg-config/src/config_catalog.rs @@ -48,6 +48,7 @@ pub(crate) fn sentinel_config() -> Config { mcp: Some(HashMap::new()), permission: Some(PermissionConfig::default()), approval_reviewer: Some(ApprovalReviewerConfig::default()), + advisor: Some(AdvisorConfig::default()), compaction: Some(CompactionConfig::default()), subagent: Some(SubagentConfig::default()), skills: Some(SkillsConfig::default()), diff --git a/crates/codegg-config/src/paths.rs b/crates/codegg-config/src/paths.rs index 279978b15..7640c7fa5 100644 --- a/crates/codegg-config/src/paths.rs +++ b/crates/codegg-config/src/paths.rs @@ -506,6 +506,12 @@ pub fn merge_configs(configs: &[Config]) -> Config { None => merged.approval_reviewer = Some(v.clone()), } } + if let Some(ref v) = config.advisor { + match &mut merged.advisor { + Some(existing) => existing.merge(v), + None => merged.advisor = Some(v.clone()), + } + } if let Some(ref v) = config.daemon { match &mut merged.daemon { Some(existing) => existing.merge(v), @@ -1180,6 +1186,7 @@ mod tests { fn test_merge_configs_preserves_single_layer_sections() { let raw = r#"{ "approval_reviewer": { "model": "fixture/reviewer" }, + "advisor": { "model": "fixture/advisor", "deadline_ms": 120000 }, "daemon": { "enabled": true }, "scheduler": { "enabled": true }, "tool_deferral": { "defer_loading": true }, @@ -1207,6 +1214,10 @@ mod tests { .and_then(|c| c.model.as_deref()), Some("fixture/reviewer") ); + assert_eq!( + merged.advisor.as_ref().and_then(|c| c.model.as_deref()), + Some("fixture/advisor") + ); assert_eq!(merged.daemon.as_ref().and_then(|c| c.enabled), Some(true)); assert_eq!( merged.scheduler.as_ref().and_then(|c| c.enabled), diff --git a/crates/codegg-config/src/provenance.rs b/crates/codegg-config/src/provenance.rs index 402e66cf8..d5643009a 100644 --- a/crates/codegg-config/src/provenance.rs +++ b/crates/codegg-config/src/provenance.rs @@ -326,6 +326,14 @@ pub const STRATEGY_TABLE: &[StrategyEntry] = &[ inherited_paths: &[], note: "", }, + StrategyEntry { + section: "advisor", + shape: MergeShape::FieldByField, + rule: AttributionRule::LastContaining, + combine_depth: 1, + inherited_paths: &[], + note: "", + }, StrategyEntry { section: "daemon", shape: MergeShape::FieldByField, diff --git a/crates/codegg-config/src/schema.rs b/crates/codegg-config/src/schema.rs index 321f7e2b4..e783a6672 100644 --- a/crates/codegg-config/src/schema.rs +++ b/crates/codegg-config/src/schema.rs @@ -373,7 +373,6 @@ pub enum SubagentTodoAccess { #[serde(default)] pub struct TaskStatePolicyConfig { pub mode: Option, - pub update_frequency: Option, pub max_total_items: Option, pub expose_completed_items: Option, pub allow_model_todo_read: Option, @@ -383,6 +382,7 @@ pub struct TaskStatePolicyConfig { pub inject_after_tool_calls: Option, pub inject_on_resume: Option, pub inject_after_compaction: Option, + /// Reserved for the delegation decision; checklist access remains parent-only. pub subagent_todo_access: Option, } @@ -436,6 +436,8 @@ pub struct Config { /// When absent or when `model` is absent, `Automatic` escalations safely /// defer to the human (M003 behavior preserved). pub approval_reviewer: Option, + /// Optional bounded second-model consultation. It grants no tool authority. + pub advisor: Option, pub compaction: Option, pub subagent: Option, pub skills: Option, @@ -1762,6 +1764,9 @@ pub struct AgentConfig { pub color: Option, pub steps: Option, pub hidden: Option, + pub selectable: Option, + pub subagent: Option, + pub default: Option, pub disable: Option, pub permission: Option>, pub tools: Option>, @@ -1956,6 +1961,62 @@ impl ApprovalReviewerConfig { } } +/// Configuration for one bounded second-model consultation. +/// +/// This section is intentionally separate from the local `tool_advisor`, which +/// only ranks tool exposure. Missing `model` keeps consultation off. +#[derive(Deserialize, Serialize, Debug, Clone, Default, PartialEq)] +#[serde(default)] +pub struct AdvisorConfig { + /// `provider/model`, or a bare id resolved only against the turn provider. + pub model: Option, + /// Deadline in milliseconds (default 300_000, clamp 30_000..=300_000). + pub deadline_ms: Option, + /// Advice character cap (default 6_000, clamp 1_000..=16_384). + pub max_output_chars: Option, + /// Provider-scoped reasoning effort selection. + pub reasoning_effort: Option, + /// Reasoning token budget selection. + pub thinking_budget: Option, +} + +impl AdvisorConfig { + pub fn resolved_model(&self) -> Option { + self.model.as_ref().and_then(|model| { + let model = model.trim(); + (!model.is_empty() && model.len() <= 256 && !model.contains('\0')) + .then(|| model.to_owned()) + }) + } + + pub fn resolved_deadline_ms(&self) -> u64 { + self.deadline_ms.unwrap_or(300_000).clamp(30_000, 300_000) + } + + pub fn resolved_max_output_chars(&self) -> usize { + self.max_output_chars.unwrap_or(6_000).clamp(1_000, 16_384) + } + + /// Merge non-absent fields from a later config layer. + pub fn merge(&mut self, other: &Self) { + if other.model.is_some() { + self.model.clone_from(&other.model); + } + if other.deadline_ms.is_some() { + self.deadline_ms = other.deadline_ms; + } + if other.max_output_chars.is_some() { + self.max_output_chars = other.max_output_chars; + } + if other.reasoning_effort.is_some() { + self.reasoning_effort.clone_from(&other.reasoning_effort); + } + if other.thinking_budget.is_some() { + self.thinking_budget = other.thinking_budget; + } + } +} + #[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum CompactionModeConfig { @@ -4718,6 +4779,71 @@ fn write_atomic(path: &std::path::Path, content: &str) -> std::io::Result<()> { mod tests { use super::*; + #[test] + fn advisor_config_is_additive_and_distinct_from_tool_advisor() { + let absent: Config = serde_json::from_str("{}").expect("empty config parses"); + assert!(absent.advisor.is_none()); + + let defaults = AdvisorConfig::default(); + assert_eq!(defaults.resolved_deadline_ms(), 300_000); + assert_eq!(defaults.resolved_max_output_chars(), 6_000); + + let low = AdvisorConfig { + deadline_ms: Some(1), + max_output_chars: Some(1), + ..Default::default() + }; + assert_eq!(low.resolved_deadline_ms(), 30_000); + assert_eq!(low.resolved_max_output_chars(), 1_000); + + let high = AdvisorConfig { + deadline_ms: Some(u64::MAX), + max_output_chars: Some(usize::MAX), + ..Default::default() + }; + assert_eq!(high.resolved_deadline_ms(), 300_000); + assert_eq!(high.resolved_max_output_chars(), 16_384); + + let legacy: Config = serde_json::from_str( + r#"{"advisor":{"model":"fixture/reviewer","max_consultations_per_turn":2}}"#, + ) + .expect("the removed legacy count is ignored"); + let legacy_advisor = legacy.advisor.expect("advisor block is retained"); + assert_eq!( + legacy_advisor.resolved_model().as_deref(), + Some("fixture/reviewer") + ); + assert!(serde_json::to_value(legacy_advisor) + .expect("advisor config serializes") + .get("max_consultations_per_turn") + .is_none()); + + let both: Config = serde_json::from_str( + r#"{"advisor":{"model":"fixture/reviewer","reasoning_effort":"high","thinking_budget":512},"tool_advisor":{"enabled":true}}"# + ).expect("both independent config sections parse"); + assert_eq!( + both.advisor + .as_ref() + .and_then(|v| v.resolved_model()) + .as_deref(), + Some("fixture/reviewer") + ); + assert_eq!( + both.advisor + .as_ref() + .and_then(|v| v.reasoning_effort.as_deref()), + Some("high") + ); + assert_eq!( + both.advisor.as_ref().and_then(|v| v.thinking_budget), + Some(512) + ); + assert_eq!( + both.tool_advisor.as_ref().and_then(|v| v.enabled), + Some(true) + ); + } + fn valid_discovery_root(path: &str, id: &str) -> DiscoveryRootConfig { DiscoveryRootConfig { id: Some(id.to_string()), @@ -4726,6 +4852,16 @@ mod tests { } } + #[test] + fn removed_todo_update_frequency_is_ignored_and_reserved_access_still_parses() { + let config: TaskStatePolicyConfig = + serde_json::from_str(r#"{"update_frequency":"never","subagent_todo_access":"none"}"#) + .expect("removed unknown config key remains backward compatible"); + + assert_eq!(config.subagent_todo_access, Some(SubagentTodoAccess::None)); + assert_eq!(config.max_total_items, None); + } + #[test] fn critical_command_deny_gate_preserves_presence() { let omitted: SecurityGateConfig = serde_json::from_str("{}").unwrap(); diff --git a/crates/codegg-core/src/bus/events.rs b/crates/codegg-core/src/bus/events.rs index 8916a3c5f..452fce759 100755 --- a/crates/codegg-core/src/bus/events.rs +++ b/crates/codegg-core/src/bus/events.rs @@ -141,7 +141,8 @@ pub enum AppEvent { /// Application configuration changed. ConfigChanged, /// Todo list was updated. Carries the full snapshot so the TUI can - /// render without re-reading from the agent loop. + /// render without re-reading from the agent loop. `revision` is scoped to + /// the current turn and does not order updates across turns. TodoUpdated { session_id: String, revision: u64, diff --git a/crates/codegg-core/src/command_catalog.rs b/crates/codegg-core/src/command_catalog.rs index 5ef002e8a..3802711d7 100644 --- a/crates/codegg-core/src/command_catalog.rs +++ b/crates/codegg-core/src/command_catalog.rs @@ -267,9 +267,10 @@ impl std::error::Error for CatalogBoundError {} /// The one catalog. Every command the daemon knows about. static THE_CATALOG: CommandCatalog = CommandCatalog { // Versions 3–11 captured earlier catalog compatibility breaks; version 12 - // completed M003's two-level family migration, and version 13 records M004's - // regrouping of the LSP forms into nested paths. - version: 13, + // completed M003's two-level family migration, version 13 records M004's + // regrouping of the LSP forms into nested paths, and version 14 records the + // reconciliation that restored `/advisor` and `/toast` onto that catalog. + version: 14, commands: &[ CommandDescriptor { command_id: "project_init", @@ -366,6 +367,25 @@ static THE_CATALOG: CommandCatalog = CommandCatalog { }, ], }, + CommandDescriptor { + command_id: "advisor", + name: "/advisor", + aliases: &[], + description: "Show bounded advisor configuration and forwarding disclosure", + category: CommandCategory::System, + domain: CommandDomain::Provider, + kind: CommandKind::DaemonEffect, + capability: Some(CommandCapability::CommandExecute), + forms: &[ + CommandForm { + form: "", + kind: CommandKind::DaemonEffect, + argument_hint: "", + argument_required: false, + ..CommandForm::DEFAULT + }, + ], + }, CommandDescriptor { command_id: "policy", name: "/policy", @@ -1694,6 +1714,25 @@ static THE_CATALOG: CommandCatalog = CommandCatalog { }, ], }, + CommandDescriptor { + command_id: "toast", + name: "/toast", + aliases: &[], + description: "Show the notification history without daemon log lines", + category: CommandCategory::System, + domain: CommandDomain::System, + kind: CommandKind::FrontendEffect, + capability: None, + forms: &[ + CommandForm { + form: "", + kind: CommandKind::FrontendEffect, + argument_hint: "", + argument_required: false, + ..CommandForm::DEFAULT + }, + ], + }, CommandDescriptor { command_id: "lsp", name: "/lsp", @@ -2841,9 +2880,11 @@ mod tests { assert!(check_catalog_bounds(bounds_test_catalog(FORMS)).is_ok()); } - /// M004 regroups the LSP paths at catalog version 13. + /// Version 13 regrouped the LSP paths; version 14 is the reconciliation that + /// restored `/advisor` and `/toast` onto the two-level catalog, so a client + /// built against either parent's version is refused. #[test] fn the_catalog_version_includes_the_two_level_family_migration() { - assert_eq!(catalog_version(), 13); + assert_eq!(catalog_version(), 14); } } diff --git a/crates/codegg-core/src/command_tree.rs b/crates/codegg-core/src/command_tree.rs index 685616740..d18b26b06 100644 --- a/crates/codegg-core/src/command_tree.rs +++ b/crates/codegg-core/src/command_tree.rs @@ -435,7 +435,10 @@ mod tests { .map(|command| command.name) .collect::>(); assert_eq!(candidate_names, catalog_names); - assert_eq!(top_level().len(), 88); + // 88 in main's hierarchy plus the two commands this line adds + // (`/advisor`, `/toast`); the count is the catalog's, so it moves with + // the catalog rather than being a second source of truth. + assert_eq!(top_level().len(), 90); for command in the_catalog().commands { assert_eq!( diff --git a/crates/codegg-core/src/frontend_action.rs b/crates/codegg-core/src/frontend_action.rs index 526e60f54..3f432863a 100644 --- a/crates/codegg-core/src/frontend_action.rs +++ b/crates/codegg-core/src/frontend_action.rs @@ -87,6 +87,9 @@ pub enum FrontendAction { OpenFilesPanel, OpenKeybindDialog, InsertCommandTemplate, + /// `/toast`: the retained notification history, without the daemon log + /// tail. Frontend-local for the same reason as `ShowLogs`. + ShowNotifications, } impl FrontendAction { @@ -148,6 +151,7 @@ impl FrontendAction { Self::OpenFilesPanel => "open_files_panel", Self::OpenKeybindDialog => "open_keybind_dialog", Self::InsertCommandTemplate => "insert_command_template", + Self::ShowNotifications => "show_notifications", } } @@ -208,6 +212,7 @@ impl FrontendAction { FrontendAction::OpenFilesPanel, FrontendAction::OpenKeybindDialog, FrontendAction::InsertCommandTemplate, + FrontendAction::ShowNotifications, ]; } @@ -432,6 +437,15 @@ static THE_FRONTEND_ACTION_SET: &[FrontendActionDeclaration] = &[ disposition: FrontendActionDisposition::NonMutating, forms: &[("logs", "")], }, + // M005 (notification surface): /toast reads the retained history, which + // lives in the TUI process. It sends no CoreRequest, so the action is a + // non-mutating frontend effect and the form is declared here rather than + // left to the catalogue alone. + FrontendActionDeclaration { + action: FrontendAction::ShowNotifications, + disposition: FrontendActionDisposition::NonMutating, + forms: &[("toast", "")], + }, FrontendActionDeclaration { action: FrontendAction::SelectAgent, disposition: FrontendActionDisposition::NonMutating, diff --git a/crates/codegg-core/src/lib.rs b/crates/codegg-core/src/lib.rs index a8ed1d9a5..82bfc8b04 100644 --- a/crates/codegg-core/src/lib.rs +++ b/crates/codegg-core/src/lib.rs @@ -25,6 +25,7 @@ pub mod memory; pub mod migration; pub mod model_profile; pub mod model_routing; +pub mod plan_corpus; pub mod presence; pub mod process_admission; pub mod project_catalog; diff --git a/crates/codegg-core/src/model_profile/types.rs b/crates/codegg-core/src/model_profile/types.rs index ff51059fb..0059bdb5c 100644 --- a/crates/codegg-core/src/model_profile/types.rs +++ b/crates/codegg-core/src/model_profile/types.rs @@ -70,7 +70,7 @@ impl TaskStatePolicy { Self { mode: TodoMode::SparsePlan, update_frequency: TodoUpdateFrequency::MilestonesOnly, - max_total_items: 8, + max_total_items: 16, expose_completed_items: CompletedTodoExposure::NoneUnlessAsked, allow_model_todo_read: true, allow_model_todo_write: true, @@ -87,7 +87,7 @@ impl TaskStatePolicy { Self { mode: TodoMode::ExplicitTodo, update_frequency: TodoUpdateFrequency::MilestonesAndTaskSwitches, - max_total_items: 10, + max_total_items: 100, expose_completed_items: CompletedTodoExposure::SummaryOnly, allow_model_todo_read: true, allow_model_todo_write: true, @@ -138,9 +138,6 @@ impl TaskStatePolicy { if let Some(v) = cfg.mode { self.mode = v; } - if let Some(v) = cfg.update_frequency { - self.update_frequency = v; - } if let Some(v) = cfg.max_total_items { self.max_total_items = v; } @@ -185,9 +182,7 @@ impl TaskStatePolicy { self.allow_model_todo_write = false; self.max_total_items = self.max_total_items.min(4); } - if self.max_total_items > 12 { - self.max_total_items = 12; - } + self.max_total_items = self.max_total_items.min(crate::task_state::MAX_TODO_ITEMS); self } } diff --git a/crates/codegg-core/src/plan_corpus/mod.rs b/crates/codegg-core/src/plan_corpus/mod.rs new file mode 100644 index 000000000..e430c82da --- /dev/null +++ b/crates/codegg-core/src/plan_corpus/mod.rs @@ -0,0 +1,396 @@ +//! Pure addressing and section resolution for the per-project planning corpus. +//! +//! Anchors use an explicit trailing `{#id}` suffix when present; otherwise the +//! slug is formed by lowercasing Unicode alphanumeric characters, dropping +//! punctuation, and replacing whitespace runs with one hyphen. Leading section +//! numbers are retained. Digest input is the resolved section, including its +//! heading and nested content, with CRLF converted to LF, trailing whitespace +//! removed from each line, and trailing blank lines dropped. This normalization +//! is a persistent contract: changing it invalidates stored section digests. + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use thiserror::Error; + +pub const MAX_CORPUS_DOC_BYTES: usize = 2 * 1024 * 1024; +pub const MAX_RESOLVED_SECTION_LINES: usize = 400; +pub const MAX_INLINE_SECTION_LINES: usize = 60; +pub const MAX_PLAN_ANCHOR_CHARS: usize = 128; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PlanAddress { + pub doc: String, + pub anchor: String, +} + +impl PlanAddress { + pub fn new(doc: impl Into, anchor: impl Into) -> Result { + let address = Self { + doc: doc.into(), + anchor: anchor.into(), + }; + address.validate()?; + Ok(address) + } + + pub fn validate(&self) -> Result<(), ResolveError> { + let path = self.doc.as_str(); + if path.is_empty() + || !path.ends_with(".md") + || path.starts_with('/') + || path.contains('\\') + || path.contains(':') + || path.chars().any(char::is_control) + || path + .split('/') + .any(|part| part.is_empty() || part == "." || part == "..") + { + return Err(ResolveError::InvalidDocumentPath(self.doc.clone())); + } + if self.anchor.is_empty() + || self.anchor.chars().count() > MAX_PLAN_ANCHOR_CHARS + || self.anchor.chars().any(char::is_control) + { + return Err(ResolveError::InvalidAnchor(self.anchor.clone())); + } + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolvedSection { + pub title: String, + pub start_line: usize, + pub end_line: usize, + pub digest: String, + /// False above 60 lines. The resolver never returns the section body. + pub inline_allowed: bool, +} + +impl ResolvedSection { + pub fn line_count(&self) -> usize { + self.end_line + .saturating_sub(self.start_line) + .saturating_add(1) + } +} + +#[derive(Debug, Error, Clone, PartialEq, Eq)] +pub enum ResolveError { + #[error("invalid corpus document path: {0}")] + InvalidDocumentPath(String), + #[error("invalid section anchor: {0}")] + InvalidAnchor(String), + #[error("corpus document exceeds {max} bytes (got {actual})")] + DocumentTooLarge { max: usize, actual: usize }, + #[error("section anchor not found: {0}")] + MissingAnchor(String), + #[error("section anchor is ambiguous: {0}")] + AmbiguousAnchor(String), + #[error("resolved section exceeds {max} lines (got {actual})")] + SectionTooLarge { max: usize, actual: usize }, +} + +#[derive(Debug)] +struct Heading { + level: usize, + title: String, + anchor: String, + line_index: usize, +} + +/// Resolve a document address into its inclusive line range and normalized digest. +/// +/// This function is deliberately I/O-free. Callers must validate the document +/// path against the corpus root before supplying document bytes. +pub fn resolve_section( + document: &str, + address: &PlanAddress, +) -> Result { + address.validate()?; + let actual = document.len(); + if actual > MAX_CORPUS_DOC_BYTES { + return Err(ResolveError::DocumentTooLarge { + max: MAX_CORPUS_DOC_BYTES, + actual, + }); + } + + let normalized_newlines = document.replace("\r\n", "\n"); + let lines: Vec<&str> = normalized_newlines.lines().collect(); + let headings = headings(&lines); + let matches: Vec = headings + .iter() + .enumerate() + .filter_map(|(index, heading)| (heading.anchor == address.anchor).then_some(index)) + .collect(); + match matches.as_slice() { + [] => Err(ResolveError::MissingAnchor(address.anchor.clone())), + [_, _, ..] => Err(ResolveError::AmbiguousAnchor(address.anchor.clone())), + [index] => { + let heading = &headings[*index]; + let end_exclusive = headings + .iter() + .skip(index + 1) + .find(|next| next.level <= heading.level) + .map_or(lines.len(), |next| next.line_index); + let range = &lines[heading.line_index..end_exclusive]; + if range.len() > MAX_RESOLVED_SECTION_LINES { + return Err(ResolveError::SectionTooLarge { + max: MAX_RESOLVED_SECTION_LINES, + actual: range.len(), + }); + } + let body = normalize_section(range); + let digest = digest8(body.as_bytes()); + let start_line = heading.line_index + 1; + let end_line = end_exclusive.max(heading.line_index + 1); + let line_count = end_line - start_line + 1; + Ok(ResolvedSection { + title: heading.title.clone(), + start_line, + end_line, + digest, + inline_allowed: line_count <= MAX_INLINE_SECTION_LINES, + }) + } + } +} + +fn headings(lines: &[&str]) -> Vec { + lines + .iter() + .enumerate() + .filter_map(|(line_index, line)| parse_heading(line, line_index)) + .collect() +} + +fn parse_heading(line: &str, line_index: usize) -> Option { + let trimmed = line.trim_start_matches(' '); + if line.len() - trimmed.len() > 3 { + return None; + } + let level = trimmed.chars().take_while(|ch| *ch == '#').count(); + if !(1..=6).contains(&level) { + return None; + } + let rest = &trimmed[level..]; + if !rest.chars().next().is_some_and(char::is_whitespace) { + return None; + } + let raw_title = rest.trim(); + let without_closing_hashes = raw_title.trim_end_matches('#'); + let raw_title = if without_closing_hashes + .chars() + .next_back() + .is_some_and(char::is_whitespace) + { + without_closing_hashes.trim_end() + } else { + raw_title + }; + let (title, explicit_anchor) = split_explicit_id(raw_title); + let title = title.trim().to_string(); + let anchor = explicit_anchor.unwrap_or_else(|| slug(&title)); + (!anchor.is_empty()).then_some(Heading { + level, + title, + anchor, + line_index, + }) +} + +fn split_explicit_id(title: &str) -> (&str, Option) { + let Some(open) = title.rfind("{#") else { + return (title, None); + }; + let Some(id) = title[open + 2..].strip_suffix('}') else { + return (title, None); + }; + if id.is_empty() + || id.chars().any(char::is_whitespace) + || (open > 0 + && !title[..open] + .chars() + .next_back() + .is_some_and(char::is_whitespace)) + { + return (title, None); + } + (title[..open].trim_end(), Some(id.to_string())) +} + +fn slug(title: &str) -> String { + let mut out = String::new(); + let mut pending_separator = false; + for ch in title.chars().flat_map(char::to_lowercase) { + if ch.is_alphanumeric() { + if pending_separator && !out.is_empty() { + out.push('-'); + } + pending_separator = false; + out.push(ch); + } else if ch.is_whitespace() { + pending_separator = true; + } + } + out +} + +fn normalize_section(lines: &[&str]) -> String { + let mut normalized: Vec<&str> = lines + .iter() + .map(|line| line.trim_end_matches(char::is_whitespace)) + .collect(); + while normalized.last().is_some_and(|line| line.is_empty()) { + normalized.pop(); + } + normalized.join("\n") +} + +fn digest8(bytes: &[u8]) -> String { + let digest = Sha256::digest(bytes); + digest[..4] + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn address(doc: &str, anchor: &str) -> PlanAddress { + PlanAddress::new(doc, anchor).expect("valid address") + } + + #[test] + fn numbered_heading_slug_retains_number_and_collapses_spaces() { + let resolved = resolve_section( + "# 2. Install, Configure!\nbody\n", + &address("plan.md", "2-install-configure"), + ) + .expect("resolve slug"); + assert_eq!(resolved.title, "2. Install, Configure!"); + assert_eq!((resolved.start_line, resolved.end_line), (1, 2)); + } + + #[test] + fn explicit_id_overrides_heading_slug_and_is_removed_from_title() { + let resolved = resolve_section( + "## Stable Name {#setup-v2}\nbody\n", + &address("plan.md", "setup-v2"), + ) + .expect("explicit id resolves"); + assert_eq!(resolved.title, "Stable Name"); + assert!(matches!( + resolve_section( + "## Stable Name {#setup-v2}\n", + &address("plan.md", "stable-name") + ), + Err(ResolveError::MissingAnchor(_)) + )); + } + + #[test] + fn duplicate_slug_is_ambiguous_instead_of_first_match() { + let error = resolve_section("# Repeat\nA\n# Repeat\nB\n", &address("plan.md", "repeat")) + .expect_err("duplicate headings refuse"); + assert_eq!(error, ResolveError::AmbiguousAnchor("repeat".into())); + } + + #[test] + fn missing_heading_is_typed() { + assert_eq!( + resolve_section("# Existing\n", &address("plan.md", "missing")), + Err(ResolveError::MissingAnchor("missing".into())) + ); + } + + #[test] + fn section_digest_normalizes_crlf_trailing_space_and_trailing_blank_lines() { + let first = resolve_section( + "# First\r\nbody \r\n \r\n\r\n# Next\r\n", + &address("plan.md", "first"), + ) + .expect("resolve CRLF"); + let second = resolve_section("# First\nbody\n# Next\n", &address("plan.md", "first")) + .expect("resolve LF"); + assert_eq!(first.digest, second.digest); + } + + #[test] + fn re_reading_unchanged_section_keeps_digest_stable() { + let source = "# Plan\nintro\n## Step\nbody\n"; + let first = resolve_section(source, &address("plan.md", "step")).unwrap(); + let reread = resolve_section(source, &address("plan.md", "step")).unwrap(); + assert_eq!(first.digest, reread.digest); + } + + #[test] + fn editing_a_different_section_preserves_this_sections_digest() { + let before = "# Plan\n## A\na body\n## B\nb body\n"; + let after = "# Plan\n## A\na body changed\n## B\nb body\n"; + let address = address("plan.md", "b"); + let before_b = resolve_section(before, &address).unwrap(); + let after_b = resolve_section(after, &address).unwrap(); + assert_eq!(before_b.digest, after_b.digest); + let whole_file_before = digest8(before.as_bytes()); + let whole_file_after = digest8(after.as_bytes()); + assert_ne!(whole_file_before, whole_file_after); + } + + #[test] + fn empty_section_resolves_to_its_heading_line() { + let section = resolve_section("# Plan\n## Empty\n## Next\n", &address("plan.md", "empty")) + .expect("empty section"); + assert_eq!((section.start_line, section.end_line), (2, 2)); + assert_eq!(section.line_count(), 1); + } + + #[test] + fn address_rejects_absolute_traversal_and_non_markdown_paths() { + for path in [ + "/plan.md", + "../plan.md", + "docs/../plan.md", + "plan.txt", + "docs\\plan.md", + ] { + assert!( + PlanAddress::new(path, "section").is_err(), + "accepted {path}" + ); + } + } + + #[test] + fn section_over_400_lines_refuses_and_300_line_section_is_not_inlineable() { + let short = format!("# Large\n{}", "line\n".repeat(299)); + let resolved = resolve_section(&short, &address("plan.md", "large")).unwrap(); + assert_eq!(resolved.line_count(), 300); + assert!(!resolved.inline_allowed); + + let long = format!("# Too Large\n{}", "line\n".repeat(400)); + assert!(matches!( + resolve_section(&long, &address("plan.md", "too-large")), + Err(ResolveError::SectionTooLarge { + max: 400, + actual: 401 + }) + )); + } + + #[test] + fn document_byte_limit_is_enforced_before_parsing() { + let source = "x".repeat(MAX_CORPUS_DOC_BYTES + 1); + assert!(matches!( + resolve_section(&source, &address("plan.md", "x")), + Err(ResolveError::DocumentTooLarge { + max: MAX_CORPUS_DOC_BYTES, + .. + }) + )); + } +} diff --git a/crates/codegg-core/src/project_catalog.rs b/crates/codegg-core/src/project_catalog.rs index 364981c7f..a83612ee5 100644 --- a/crates/codegg-core/src/project_catalog.rs +++ b/crates/codegg-core/src/project_catalog.rs @@ -564,7 +564,7 @@ impl ProjectCatalog { // Validate workspace exists let workspace_row = sqlx::query( - "SELECT id, canonical_root, display_name, time_created, time_last_opened, time_archived FROM workspace WHERE id = ?", + "SELECT id, target_kind, host_ref, canonical_root, display_name, time_created, time_last_opened, time_archived FROM workspace WHERE id = ?", ) .bind(workspace_id.as_str()) .fetch_optional(&self.pool) @@ -576,6 +576,13 @@ impl ProjectCatalog { ) })?; + let target_kind: String = workspace_row.get("target_kind"); + let host_ref: String = workspace_row.get("host_ref"); + if target_kind != "local" || !host_ref.is_empty() { + return Err(CatalogError::InvalidValue( + "local registration requires a local workspace target".to_string(), + )); + } let canonical_root: String = workspace_row.get("canonical_root"); // Probe lineage before deciding anything, but DO NOT create the @@ -1994,6 +2001,7 @@ mod tests { let now = Utc::now(); WorkspaceRecord { id: WorkspaceId::new(), + target: crate::workspace::WorkspaceTarget::Local, canonical_root: root.to_path_buf(), display_name: root .file_name() diff --git a/crates/codegg-core/src/project_storage.rs b/crates/codegg-core/src/project_storage.rs index 530229f89..b692bf69b 100644 --- a/crates/codegg-core/src/project_storage.rs +++ b/crates/codegg-core/src/project_storage.rs @@ -15,7 +15,7 @@ use thiserror::Error; use crate::identity::{ProjectId, RepositoryId, WorkspaceId}; use crate::repository_lineage::{inspect_repository_lineage, RepositoryLineageEvidence}; -use crate::workspace::WorkspaceRecord; +use crate::workspace::{RemoteHostRef, TargetRoot, WorkspaceRecord, WorkspaceTarget}; pub const MAX_DISPLAY_NAME_LENGTH: usize = 256; pub const MAX_LINEAGE_VALUE_LENGTH: usize = 512; @@ -556,7 +556,7 @@ impl ProjectStorage { // may bind a workspace the registry has not persisted yet. Keep the // row present so the binding is never an orphan. sqlx::query( - "INSERT INTO workspace (id, canonical_root, display_name, time_created, time_last_opened, time_archived) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO NOTHING", + "INSERT INTO workspace (id, target_kind, host_ref, canonical_root, display_name, time_created, time_last_opened, time_archived) VALUES (?, 'local', '', ?, ?, ?, ?, ?) ON CONFLICT(id) DO NOTHING", ) .bind(workspace.id.as_str()) .bind(workspace.canonical_root.to_string_lossy().as_ref()) @@ -603,6 +603,11 @@ impl ProjectStorage { evidence: &RepositoryLineageEvidence, source: &str, ) -> Result { + if !workspace.target.is_local() { + return Err(ProjectStorageError::InvalidValue( + "remote workspace reconciliation is unavailable".to_string(), + )); + } for attempt in 0..3 { match self .reconcile_workspace_once(workspace, evidence, source) @@ -630,7 +635,7 @@ impl ProjectStorage { let source = bounded_text(source, MAX_LINEAGE_VALUE_LENGTH, "binding source")?; sqlx::query( - "INSERT INTO workspace (id, canonical_root, display_name, time_created, time_last_opened, time_archived) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO NOTHING", + "INSERT INTO workspace (id, target_kind, host_ref, canonical_root, display_name, time_created, time_last_opened, time_archived) VALUES (?, 'local', '', ?, ?, ?, ?, ?) ON CONFLICT(id) DO NOTHING", ) .bind(workspace.id.as_str()) .bind(workspace.canonical_root.to_string_lossy().as_ref()) @@ -718,6 +723,11 @@ impl ProjectStorage { workspace: &WorkspaceRecord, source: &str, ) -> Result { + if !workspace.target.is_local() { + return Err(ProjectStorageError::InvalidValue( + "remote workspace reconciliation is unavailable".to_string(), + )); + } let evidence = inspect_repository_lineage(&workspace.canonical_root) .map_err(|error| ProjectStorageError::InvalidValue(error.to_string()))?; self.reconcile_workspace(workspace, &evidence, source).await @@ -878,7 +888,7 @@ impl ProjectStorage { ) -> Result { let binding = self.workspace_binding(workspace_id).await?; let workspace = sqlx::query( - "SELECT id, canonical_root, display_name, time_created, time_last_opened, time_archived FROM workspace WHERE id = ?", + "SELECT id, target_kind, host_ref, canonical_root, display_name, time_created, time_last_opened, time_archived FROM workspace WHERE id = ?", ) .bind(workspace_id.as_str()) .fetch_optional(&self.pool) @@ -1403,9 +1413,37 @@ fn diagnostic_from_row( fn workspace_from_row( row: sqlx::sqlite::SqliteRow, ) -> Result { + let target_kind: String = row.get("target_kind"); + let host_ref: String = row.get("host_ref"); + let root: String = row.get("canonical_root"); + let target = match target_kind.as_str() { + "local" if host_ref.is_empty() => WorkspaceTarget::Local, + "local" => { + return Err(ProjectStorageError::InvalidValue( + "local workspace has a non-empty host reference".to_string(), + )); + } + "ssh" => WorkspaceTarget::Ssh { + host: RemoteHostRef::parse(&host_ref).map_err(identity_error)?, + root: TargetRoot::new(root.clone()).map_err(|_| { + ProjectStorageError::InvalidValue("invalid remote target root".to_string()) + })?, + }, + _ => { + return Err(ProjectStorageError::InvalidValue( + "invalid workspace target kind".to_string(), + )); + } + }; + let canonical_root = if target.is_local() { + PathBuf::from(root) + } else { + PathBuf::new() + }; Ok(WorkspaceRecord { id: WorkspaceId::parse(row.get::("id").as_str()).map_err(identity_error)?, - canonical_root: PathBuf::from(row.get::("canonical_root")), + target, + canonical_root, display_name: row.get("display_name"), created_at: timestamp(row.get("time_created"), "workspace.time_created")?, last_opened_at: timestamp(row.get("time_last_opened"), "workspace.time_last_opened")?, @@ -1476,6 +1514,7 @@ mod tests { let now = Utc::now(); WorkspaceRecord { id: WorkspaceId::new(), + target: crate::workspace::WorkspaceTarget::Local, canonical_root: root.to_path_buf(), display_name: name.to_string(), created_at: now, diff --git a/crates/codegg-core/src/session/import.rs b/crates/codegg-core/src/session/import.rs index 081fe3180..56106208e 100644 --- a/crates/codegg-core/src/session/import.rs +++ b/crates/codegg-core/src/session/import.rs @@ -54,11 +54,19 @@ pub struct PartImport { #[derive(Deserialize)] pub struct TodoImport { + #[serde(default)] + pub id: Option, pub content: String, #[serde(default)] pub status: String, #[serde(default)] pub priority: String, + #[serde(default)] + pub blocker: Option, + #[serde(default)] + pub plan_ref_json: Option, + #[serde(default)] + pub plan_digest: Option, #[serde(rename = "time_created", default)] pub time_created: Option, #[serde(rename = "time_updated", default)] diff --git a/crates/codegg-core/src/session/models.rs b/crates/codegg-core/src/session/models.rs index c40845053..c0c208b9b 100644 --- a/crates/codegg-core/src/session/models.rs +++ b/crates/codegg-core/src/session/models.rs @@ -167,9 +167,17 @@ pub struct SessionAnalytics { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TodoItem { pub session_id: String, + #[serde(default)] + pub id: Option, pub content: String, pub status: String, pub priority: String, + #[serde(default)] + pub blocker: Option, + #[serde(default)] + pub plan_ref_json: Option, + #[serde(default)] + pub plan_digest: Option, pub position: i64, pub time_created: i64, pub time_updated: i64, @@ -177,9 +185,17 @@ pub struct TodoItem { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TodoItemInput { + #[serde(default)] + pub id: Option, pub content: String, pub status: String, pub priority: String, + #[serde(default)] + pub blocker: Option, + #[serde(default)] + pub plan_ref_json: Option, + #[serde(default)] + pub plan_digest: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/codegg-core/src/session/row.rs b/crates/codegg-core/src/session/row.rs index 7d75e415a..cb02c8663 100644 --- a/crates/codegg-core/src/session/row.rs +++ b/crates/codegg-core/src/session/row.rs @@ -150,9 +150,13 @@ impl From for message::Part { #[derive(sqlx::FromRow)] pub struct TodoRow { pub session_id: String, + pub id: String, pub content: String, pub status: String, pub priority: String, + pub blocker: Option, + pub plan_ref_json: Option, + pub plan_digest: Option, pub position: i64, pub time_created: i64, pub time_updated: i64, @@ -162,9 +166,13 @@ impl From for TodoItem { fn from(r: TodoRow) -> Self { Self { session_id: r.session_id, + id: Some(r.id), content: r.content, status: r.status, priority: r.priority, + blocker: r.blocker, + plan_ref_json: r.plan_ref_json, + plan_digest: r.plan_digest, position: r.position, time_created: r.time_created, time_updated: r.time_updated, diff --git a/crates/codegg-core/src/session/schema.rs b/crates/codegg-core/src/session/schema.rs index eb0efa361..961d02488 100755 --- a/crates/codegg-core/src/session/schema.rs +++ b/crates/codegg-core/src/session/schema.rs @@ -1,4 +1,4 @@ -use sqlx::SqlitePool; +use sqlx::{Connection, SqlitePool}; use crate::error::StorageError; @@ -311,11 +311,26 @@ pub async fn migrate(pool: &SqlitePool) -> Result<(), StorageError> { if current_version < 95 { migrate_and_record(pool, 95).await?; } + if current_version < 96 { + migrate_and_record(pool, 96).await?; + } + if current_version < 97 { + migrate_and_record(pool, 97).await?; + } + if current_version < 98 { + migrate_and_record(pool, 98).await?; + } + if current_version < 99 { + migrate_and_record(pool, 99).await?; + } Ok(()) } async fn migrate_and_record(pool: &SqlitePool, version: i64) -> Result<(), StorageError> { + if version == 96 { + return migrate_v96_and_record(pool).await; + } let mut tx = pool .begin() .await @@ -418,6 +433,10 @@ async fn migrate_and_record(pool: &SqlitePool, version: i64) -> Result<(), Stora 93 => migrate_v93(&mut tx).await?, 94 => migrate_v94(&mut tx).await?, 95 => migrate_v95(&mut tx).await?, + 96 => migrate_v96(&mut tx).await?, + 97 => migrate_v97(&mut tx).await?, + 98 => migrate_v98(&mut tx).await?, + 99 => migrate_v99(&mut tx).await?, _ => { return Err(StorageError::Migration(format!( "unknown migration version {}", @@ -451,6 +470,59 @@ async fn migrate_and_record(pool: &SqlitePool, version: i64) -> Result<(), Stora } } +async fn migrate_v96_and_record(pool: &SqlitePool) -> Result<(), StorageError> { + let mut connection = pool + .acquire() + .await + .map_err(|error| StorageError::Migration(error.to_string()))?; + sqlx::query("PRAGMA foreign_keys = OFF") + .execute(&mut *connection) + .await + .map_err(|error| StorageError::Migration(error.to_string()))?; + + let migration_result = async { + let mut tx = connection + .begin() + .await + .map_err(|error| StorageError::Migration(error.to_string()))?; + let result = async { + migrate_v96(&mut tx).await?; + sqlx::query( + "INSERT INTO migration_version (id, version) VALUES (1, 96) \ + ON CONFLICT(id) DO UPDATE SET version = excluded.version", + ) + .execute(&mut *tx) + .await + .map_err(|error| StorageError::Migration(error.to_string()))?; + Ok::<(), StorageError>(()) + } + .await; + + match result { + Ok(()) => tx + .commit() + .await + .map_err(|error| StorageError::Migration(error.to_string())), + Err(error) => { + drop(tx); + Err(error) + } + } + } + .await; + + let restore_result = sqlx::query("PRAGMA foreign_keys = ON") + .execute(&mut *connection) + .await + .map(|_| ()) + .map_err(|error| StorageError::Migration(error.to_string())); + + match migration_result { + Err(error) => Err(error), + Ok(()) => restore_result, + } +} + /// Session-relative working-directory overrides (ADR-0055 Option A). async fn migrate_v91(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>) -> Result<(), StorageError> { sqlx::query( @@ -536,6 +608,121 @@ async fn migrate_v94(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>) -> Result<(), Ok(()) } +/// Todo identity and blocker data are additive. The columns are nullable because +/// SQLite cannot add a NOT NULL column without a default; the migration backfills +/// every existing row and all writers enforce non-null IDs. +async fn migrate_v97(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>) -> Result<(), StorageError> { + // Both columns are nullable at the schema level: SQLite cannot add a NOT NULL + // column without a default, and the writer enforces non-null. The ALTERs use + // the idempotent helper because this repository's migration tests replay the + // chain from a rewound marker; a bare ALTER would fail on "duplicate column". + add_column_ignore_duplicate(&mut *tx, "ALTER TABLE todo ADD COLUMN id TEXT".to_string()) + .await?; + add_column_ignore_duplicate( + &mut *tx, + "ALTER TABLE todo ADD COLUMN blocker TEXT".to_string(), + ) + .await?; + sqlx::query("UPDATE todo SET id = 'legacy-' || position WHERE id IS NULL") + .execute(&mut **tx) + .await + .map_err(|error| StorageError::Migration(error.to_string()))?; + sqlx::query("CREATE UNIQUE INDEX IF NOT EXISTS idx_todo_session_id ON todo(session_id, id)") + .execute(&mut **tx) + .await + .map_err(|error| StorageError::Migration(error.to_string()))?; + Ok(()) +} + +/// Planning-corpus identity only; the corpus document content remains on disk. +async fn migrate_v98(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>) -> Result<(), StorageError> { + sqlx::query( + r#" + CREATE TABLE IF NOT EXISTS plan_corpus_binding ( + project_identity TEXT PRIMARY KEY, + corpus_root TEXT NOT NULL UNIQUE, + repository_identity TEXT NOT NULL, + head_commit TEXT, + last_observed_digest TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ) + "#, + ) + .execute(&mut **tx) + .await + .map_err(|error| StorageError::Migration(error.to_string()))?; + add_column_ignore_duplicate( + &mut *tx, + "ALTER TABLE todo ADD COLUMN plan_ref_json TEXT".to_string(), + ) + .await?; + add_column_ignore_duplicate( + &mut *tx, + "ALTER TABLE todo ADD COLUMN plan_digest TEXT".to_string(), + ) + .await?; + Ok(()) +} + +async fn migrate_v99(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>) -> Result<(), StorageError> { + add_column_ignore_duplicate( + &mut *tx, + "ALTER TABLE workstream_claim ADD COLUMN note TEXT".to_string(), + ) + .await?; + add_column_ignore_duplicate( + &mut *tx, + "ALTER TABLE workstream_claim ADD COLUMN instruction_ref_json TEXT".to_string(), + ) + .await?; + Ok(()) +} + +/// Remote workspace targets are text-only; the local uniqueness constraint is +/// replaced with a target-qualified key. Foreign keys are disabled only on the +/// dedicated migration connection while the parent table is rebuilt; the +/// surrounding migration transaction preserves rollback atomicity. +async fn migrate_v96(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>) -> Result<(), StorageError> { + for statement in [ + r#" + CREATE TABLE workspace_v96 ( + id TEXT PRIMARY KEY, + target_kind TEXT NOT NULL DEFAULT 'local' CHECK (target_kind IN ('local', 'ssh')), + host_ref TEXT NOT NULL DEFAULT '', + canonical_root TEXT NOT NULL, + display_name TEXT NOT NULL, + time_created INTEGER NOT NULL, + time_last_opened INTEGER NOT NULL, + time_archived INTEGER, + CHECK ( + (target_kind = 'local' AND host_ref = '') OR + (target_kind = 'ssh' AND host_ref <> '') + ) + ) + "#, + r#" + INSERT INTO workspace_v96 ( + id, target_kind, host_ref, canonical_root, display_name, + time_created, time_last_opened, time_archived + ) + SELECT id, 'local', '', canonical_root, display_name, + time_created, time_last_opened, time_archived + FROM workspace + "#, + "DROP TABLE workspace", + "ALTER TABLE workspace_v96 RENAME TO workspace", + "CREATE UNIQUE INDEX idx_workspace_target_root_unique ON workspace(target_kind, host_ref, canonical_root)", + "CREATE INDEX idx_workspace_archived ON workspace(time_archived)", + ] { + sqlx::query(statement) + .execute(&mut **tx) + .await + .map_err(|error| StorageError::Migration(error.to_string()))?; + } + Ok(()) +} + async fn migrate_v95(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>) -> Result<(), StorageError> { sqlx::query( r#" @@ -4198,6 +4385,33 @@ mod migration_upgrade_tests { .expect("open migration fixture database") } + async fn open_pool_with_foreign_keys(path: &Path) -> SqlitePool { + SqlitePoolOptions::new() + .max_connections(1) + .connect_with( + SqliteConnectOptions::new() + .filename(path) + .create_if_missing(true) + .foreign_keys(true), + ) + .await + .expect("open foreign-key-enabled migration fixture database") + } + + async fn apply_through_v95(pool: &SqlitePool) { + sqlx::query( + "CREATE TABLE migration_version (id INTEGER PRIMARY KEY CHECK (id = 1), version INTEGER NOT NULL DEFAULT 0)", + ) + .execute(pool) + .await + .expect("create migration marker"); + for version in 1..=95 { + migrate_and_record(pool, version) + .await + .unwrap_or_else(|error| panic!("apply migration v{}: {}", version, error)); + } + } + async fn apply_through_v77(pool: &SqlitePool, with_origin: bool) { sqlx::query( "CREATE TABLE migration_version (id INTEGER PRIMARY KEY CHECK (id = 1), version INTEGER NOT NULL DEFAULT 0)", @@ -4328,6 +4542,66 @@ mod migration_upgrade_tests { pool.close().await; } + #[tokio::test(flavor = "current_thread")] + async fn v98_populated_workstream_claim_gains_nullable_p002_fields() { + let directory = tempfile::tempdir().expect("claim migration fixture directory"); + let path = directory.path().join("v98-populated.db"); + let pool = open_pool(&path).await; + sqlx::query( + "CREATE TABLE migration_version (id INTEGER PRIMARY KEY CHECK (id = 1), version INTEGER NOT NULL DEFAULT 0)", + ) + .execute(&pool) + .await + .expect("create migration marker"); + for version in 1..=98 { + migrate_and_record(&pool, version) + .await + .unwrap_or_else(|error| panic!("apply migration v{version}: {error}")); + } + sqlx::query( + "INSERT INTO agent_run_group (group_id, root_run_id, owner_run_id, join_policy, cancel_remaining, status, created_at, idempotency_key, owner_kind) VALUES ('group-a', 'run-a', 'run-a', 'all', 0, 'running', 1, 'legacy-group-key', 'run')", + ) + .execute(&pool) + .await + .expect("seed the claim's group row"); + sqlx::query( + "INSERT INTO workstream_claim (claim_id, project_id, workspace_id, group_id, claim_kind, target, state, owner_kind, owner_id, version, lease_generation, lease_expires_at, idempotency_key, created_at, updated_at) VALUES ('legacy-claim', 'project-a', 'workspace-a', 'group-a', 'path', 'src/legacy.rs', 'claimed', 'run', 'run-a', 1, 1, NULL, 'legacy-key', 10, 10)", + ) + .execute(&pool) + .await + .expect("seed a populated v98 claim row"); + + migrate(&pool) + .await + .expect("apply v99 to a populated claim store"); + let (target, version): (String, i64) = sqlx::query_as( + "SELECT target, version FROM workstream_claim WHERE claim_id='legacy-claim'", + ) + .fetch_one(&pool) + .await + .expect("read preserved claim"); + assert_eq!(target, "src/legacy.rs"); + assert_eq!(version, 1); + let (note, instruction): (Option, Option) = sqlx::query_as( + "SELECT note, instruction_ref_json FROM workstream_claim WHERE claim_id='legacy-claim'", + ) + .fetch_one(&pool) + .await + .expect("read additive claim fields"); + assert_eq!(note, None, "existing claim note defaults to null"); + assert_eq!( + instruction, None, + "existing instruction reference defaults to null" + ); + let marker: i64 = sqlx::query_scalar("SELECT version FROM migration_version WHERE id=1") + .fetch_one(&pool) + .await + .expect("read upgraded marker"); + assert_eq!(marker, 99); + + pool.close().await; + } + #[tokio::test(flavor = "current_thread")] async fn v94_database_gains_the_request_ledger_and_reapplies_idempotently() { let directory = tempfile::tempdir().expect("ledger migration fixture directory"); @@ -4368,13 +4642,27 @@ mod migration_upgrade_tests { .await .expect("count post-v95 ledger index"); assert_eq!(index, 1, "v95 creates the per-session read index"); + let corpus_bindings: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'plan_corpus_binding'", + ) + .fetch_one(&pool) + .await + .expect("count v98 corpus binding table"); + assert_eq!(corpus_bindings, 1, "v98 creates the corpus binding table"); + let todo_plan_columns: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM pragma_table_info('todo') WHERE name IN ('plan_ref_json', 'plan_digest')", + ) + .fetch_one(&pool) + .await + .expect("count v98 todo plan fields"); + assert_eq!(todo_plan_columns, 2, "v98 adds both optional plan fields"); let version: i64 = sqlx::query_scalar("SELECT version FROM migration_version WHERE id = 1") .fetch_one(&pool) .await .expect("read the upgraded marker"); assert_eq!(version, STORAGE_LAYOUT_VERSION as i64); assert_eq!( - version, 95, + version, 99, "the layout marker tracks the highest migration" ); @@ -4389,4 +4677,271 @@ mod migration_upgrade_tests { pool.close().await; } + + #[tokio::test(flavor = "current_thread")] + async fn v95_workspace_rebuild_preserves_rows_foreign_keys_indexes_and_target_uniqueness() { + use sqlx::Row; + + let directory = tempfile::tempdir().expect("workspace migration fixture directory"); + let path = directory.path().join("v95-populated.db"); + let pool = open_pool_with_foreign_keys(&path).await; + apply_through_v95(&pool).await; + for (id, root, name, archived) in [ + ("local-a", "/work/a", "A", None), + ("local-b", "/work/b", "B", Some(123_i64)), + ] { + sqlx::query( + "INSERT INTO workspace (id, canonical_root, display_name, time_created, time_last_opened, time_archived) VALUES (?, ?, ?, 10, 20, ?)", + ) + .bind(id) + .bind(root) + .bind(name) + .bind(archived) + .execute(&pool) + .await + .expect("seed v95 workspace row"); + } + sqlx::query( + "CREATE TABLE workspace_v96_fk_probe (id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL REFERENCES workspace(id) ON DELETE CASCADE)", + ) + .execute(&pool) + .await + .expect("create populated foreign-key probe"); + sqlx::query( + "INSERT INTO workspace_v96_fk_probe (id, workspace_id) VALUES ('probe-1', 'local-a')", + ) + .execute(&pool) + .await + .expect("seed foreign-key probe row"); + + let before: Vec<(String, String, String, i64, i64, Option)> = sqlx::query_as( + "SELECT id, canonical_root, display_name, time_created, time_last_opened, time_archived FROM workspace ORDER BY id", + ) + .fetch_all(&pool) + .await + .expect("capture populated v95 workspace rows"); + assert_eq!(before.len(), 2, "fixture is populated before migration"); + let foreign_keys_before: i64 = sqlx::query_scalar("PRAGMA foreign_keys") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(foreign_keys_before, 1); + + migrate(&pool) + .await + .expect("upgrade populated v95 database"); + + let after: Vec<(String, String, String, i64, i64, Option)> = sqlx::query_as( + "SELECT id, canonical_root, display_name, time_created, time_last_opened, time_archived FROM workspace ORDER BY id", + ) + .fetch_all(&pool) + .await + .expect("read migrated workspace rows"); + assert_eq!( + after, before, + "ids, local roots, names and timestamps are preserved" + ); + let marker: i64 = sqlx::query_scalar("SELECT version FROM migration_version WHERE id = 1") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(marker, 99); + let probe: String = sqlx::query_scalar( + "SELECT workspace_id FROM workspace_v96_fk_probe WHERE id = 'probe-1'", + ) + .fetch_one(&pool) + .await + .expect("preserve referencing row"); + assert_eq!(probe, "local-a"); + let fk_rows = sqlx::query("PRAGMA foreign_key_list(workspace_v96_fk_probe)") + .fetch_all(&pool) + .await + .expect("read preserved foreign key"); + assert_eq!(fk_rows.len(), 1); + assert_eq!(fk_rows[0].get::("table"), "workspace"); + assert!( + sqlx::query("PRAGMA foreign_key_check") + .fetch_all(&pool) + .await + .unwrap() + .is_empty(), + "the rebuilt database has no foreign-key violations" + ); + let foreign_keys_after: i64 = sqlx::query_scalar("PRAGMA foreign_keys") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(foreign_keys_after, 1); + + let indexes: Vec = sqlx::query_scalar( + "SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'workspace' ORDER BY name", + ) + .fetch_all(&pool) + .await + .unwrap(); + assert!(indexes.iter().any(|name| name == "idx_workspace_archived")); + assert!(indexes + .iter() + .any(|name| name == "idx_workspace_target_root_unique")); + + let duplicate_local = sqlx::query( + "INSERT INTO workspace (id, target_kind, host_ref, canonical_root, display_name, time_created, time_last_opened) VALUES ('local-duplicate', 'local', '', '/work/a', 'dup', 30, 30)", + ) + .execute(&pool) + .await; + assert!( + duplicate_local.is_err(), + "local root uniqueness remains enforced" + ); + sqlx::query( + "INSERT INTO workspace (id, target_kind, host_ref, canonical_root, display_name, time_created, time_last_opened) VALUES ('remote-a', 'ssh', 'host-a', '/srv/project', 'remote-a', 30, 30)", + ) + .execute(&pool) + .await + .expect("first remote target inserts"); + let duplicate_remote = sqlx::query( + "INSERT INTO workspace (id, target_kind, host_ref, canonical_root, display_name, time_created, time_last_opened) VALUES ('remote-a-duplicate', 'ssh', 'host-a', '/srv/project', 'duplicate', 30, 30)", + ) + .execute(&pool) + .await; + assert!(duplicate_remote.is_err(), "same host/root target is unique"); + sqlx::query( + "INSERT INTO workspace (id, target_kind, host_ref, canonical_root, display_name, time_created, time_last_opened) VALUES ('remote-b', 'ssh', 'host-b', '/srv/project', 'remote-b', 30, 30)", + ) + .execute(&pool) + .await + .expect("different hosts may use the same remote root"); + pool.close().await; + } + + #[tokio::test(flavor = "current_thread")] + async fn failed_v96_workspace_rebuild_rolls_back_and_restores_foreign_keys() { + use sqlx::Row; + + let directory = tempfile::tempdir().expect("workspace rollback fixture directory"); + let path = directory.path().join("v95-rollback.db"); + let pool = open_pool_with_foreign_keys(&path).await; + apply_through_v95(&pool).await; + sqlx::query( + "INSERT INTO workspace (id, canonical_root, display_name, time_created, time_last_opened) VALUES ('local-kept', '/work/kept', 'kept', 10, 20)", + ) + .execute(&pool) + .await + .expect("seed v95 row"); + sqlx::query("CREATE TABLE workspace_v96 (collision INTEGER)") + .execute(&pool) + .await + .expect("force the first v96 DDL statement to fail"); + + assert!(migrate(&pool).await.is_err(), "v96 must fail closed"); + let marker: i64 = sqlx::query_scalar("SELECT version FROM migration_version WHERE id = 1") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(marker, 95, "failed migration leaves the v95 marker"); + let root: String = + sqlx::query_scalar("SELECT canonical_root FROM workspace WHERE id = 'local-kept'") + .fetch_one(&pool) + .await + .expect("original workspace row remains intact"); + assert_eq!(root, "/work/kept"); + let columns = sqlx::query("PRAGMA table_info(workspace)") + .fetch_all(&pool) + .await + .unwrap(); + assert!(columns + .iter() + .all(|row| row.get::("name") != "target_kind")); + let foreign_keys: i64 = sqlx::query_scalar("PRAGMA foreign_keys") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(foreign_keys, 1, "foreign-key enforcement is restored"); + pool.close().await; + } + + #[tokio::test(flavor = "current_thread")] + async fn populated_v96_todos_receive_deterministic_identity_and_blocker_columns() { + use sqlx::Row; + + let directory = tempfile::tempdir().expect("todo migration fixture directory"); + let path = directory.path().join("v96-todos.db"); + let pool = open_pool(&path).await; + apply_through_v95(&pool).await; + migrate_and_record(&pool, 96) + .await + .expect("apply remote-workspace v96 before todo migration"); + sqlx::query( + "INSERT INTO project (id, worktree, time_created, time_updated, sandboxes) VALUES ('legacy-project', '/legacy', 10, 10, '[]')", + ) + .execute(&pool) + .await + .expect("seed legacy todo project"); + sqlx::query( + "INSERT INTO session (id, project_id, slug, directory, title, version, time_created, time_updated) VALUES ('legacy-session', 'legacy-project', 'legacy', '/legacy', 'legacy', '1', 10, 10)", + ) + .execute(&pool) + .await + .expect("seed legacy todo session"); + for (content, position) in [("first legacy item", 0_i64), ("second legacy item", 1_i64)] { + sqlx::query( + "INSERT INTO todo (session_id, content, status, priority, position, time_created, time_updated) VALUES (?, ?, 'pending', 'medium', ?, 10, 20)", + ) + .bind("legacy-session") + .bind(content) + .bind(position) + .execute(&pool) + .await + .expect("seed pre-identity todo row"); + } + + migrate(&pool) + .await + .expect("upgrade populated v96 database"); + let rows = sqlx::query( + "SELECT id, blocker, position FROM todo WHERE session_id = ? ORDER BY position", + ) + .bind("legacy-session") + .fetch_all(&pool) + .await + .expect("read backfilled todo rows"); + assert_eq!(rows.len(), 2); + assert_eq!(rows[0].get::("id"), "legacy-0"); + assert_eq!(rows[0].get::, _>("blocker"), None); + assert_eq!(rows[1].get::("id"), "legacy-1"); + assert_eq!(rows[1].get::, _>("blocker"), None); + + let unique_index: Option = sqlx::query_scalar( + "SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'idx_todo_session_id'", + ) + .fetch_optional(&pool) + .await + .expect("query todo identity index"); + assert_eq!(unique_index.as_deref(), Some("idx_todo_session_id")); + let duplicate_identity = sqlx::query( + "INSERT INTO todo (session_id, id, content, status, priority, position, time_created, time_updated) VALUES ('legacy-session', 'legacy-0', 'duplicate', 'pending', 'medium', 2, 30, 30)", + ) + .execute(&pool) + .await; + assert!( + duplicate_identity.is_err(), + "the migrated identity index is unique" + ); + + migrate(&pool) + .await + .expect("a second migration pass is a no-op"); + let marker: i64 = sqlx::query_scalar("SELECT version FROM migration_version WHERE id = 1") + .fetch_one(&pool) + .await + .expect("read final schema marker"); + assert_eq!(marker, STORAGE_LAYOUT_VERSION as i64); + let count: i64 = + sqlx::query_scalar("SELECT COUNT(*) FROM todo WHERE session_id = 'legacy-session'") + .fetch_one(&pool) + .await + .expect("count migrated rows after second run"); + assert_eq!(count, 2); + pool.close().await; + } } diff --git a/crates/codegg-core/src/session/store.rs b/crates/codegg-core/src/session/store.rs index 900275e95..8be9d50d2 100644 --- a/crates/codegg-core/src/session/store.rs +++ b/crates/codegg-core/src/session/store.rs @@ -24,6 +24,19 @@ use codegg_config::schema::SessionTemplate; /// Row type returned by usage queries (id, session_id, provider, model, /// input_tokens, output_tokens, cached_tokens, cost_usd, timestamp). type UsageRow = (String, String, String, String, i64, i64, i64, f64, i64); +type TodoInsertValues = ( + String, + String, + String, + String, + String, + Option, + Option, + Option, + i64, + i64, + i64, +); /// How many of the most recent messages a forked session inherits. /// @@ -626,7 +639,7 @@ impl SessionStore { let todos = sqlx::query_as::<_, TodoRow>( r#" - SELECT session_id, content, status, priority, position, + SELECT session_id, id, content, status, priority, blocker, plan_ref_json, plan_digest, position, time_created, time_updated FROM todo WHERE session_id = ? ORDER BY position ASC @@ -661,9 +674,11 @@ impl SessionStore { "todos": todos.iter().map(|t| { serde_json::json!({ "session_id": t.session_id, + "id": t.id, "content": t.content, "status": t.status, "priority": t.priority, + "blocker": t.blocker, "position": t.position, "time_created": t.time_created, "time_updated": t.time_updated, @@ -835,16 +850,20 @@ impl SessionStore { .map_err(db_error)?; } - let todo_values: Vec<(String, String, String, String, i64, i64, i64)> = import + let todo_values: Vec = import .todos .iter() .enumerate() .map(|(i, todo)| { ( id.clone(), + todo.id.clone().unwrap_or_else(|| format!("legacy-{i}")), todo.content.clone(), todo.status.clone(), todo.priority.clone(), + todo.blocker.clone(), + todo.plan_ref_json.clone(), + todo.plan_digest.clone(), i as i64, todo.time_created.unwrap_or(now), todo.time_updated.unwrap_or(now), @@ -854,16 +873,20 @@ impl SessionStore { if !todo_values.is_empty() { let mut todo_query: QueryBuilder<_> = QueryBuilder::new( - "INSERT INTO todo (session_id, content, status, priority, position, time_created, time_updated) ", + "INSERT INTO todo (session_id, id, content, status, priority, blocker, plan_ref_json, plan_digest, position, time_created, time_updated) ", ); todo_query.push_values(&todo_values, |mut b, val| { b.push_bind(&val.0) .push_bind(&val.1) .push_bind(&val.2) .push_bind(&val.3) - .push_bind(val.4) - .push_bind(val.5) - .push_bind(val.6); + .push_bind(&val.4) + .push_bind(&val.5) + .push_bind(&val.6) + .push_bind(&val.7) + .push_bind(val.8) + .push_bind(val.9) + .push_bind(val.10); }); todo_query .build() @@ -1345,7 +1368,7 @@ impl SessionStore { let todos = sqlx::query_as::<_, TodoRow>( r#" - SELECT session_id, content, status, priority, position, + SELECT session_id, id, content, status, priority, blocker, plan_ref_json, plan_digest, position, time_created, time_updated FROM todo WHERE session_id = ? ORDER BY position ASC @@ -1356,13 +1379,17 @@ impl SessionStore { .await .map_err(db_error)?; - let mut todo_values: Vec<(String, String, String, String, i64, i64, i64)> = Vec::new(); + let mut todo_values: Vec = Vec::new(); for todo in &todos { todo_values.push(( child_id.clone(), + todo.id.clone(), todo.content.clone(), todo.status.clone(), todo.priority.clone(), + todo.blocker.clone(), + todo.plan_ref_json.clone(), + todo.plan_digest.clone(), todo.position, todo.time_created, todo.time_updated, @@ -1371,16 +1398,20 @@ impl SessionStore { if !todo_values.is_empty() { let mut todo_query: QueryBuilder<_> = QueryBuilder::new( - "INSERT INTO todo (session_id, content, status, priority, position, time_created, time_updated) ", + "INSERT INTO todo (session_id, id, content, status, priority, blocker, plan_ref_json, plan_digest, position, time_created, time_updated) ", ); todo_query.push_values(&todo_values, |mut b, val| { b.push_bind(&val.0) .push_bind(&val.1) .push_bind(&val.2) .push_bind(&val.3) - .push_bind(val.4) - .push_bind(val.5) - .push_bind(val.6); + .push_bind(&val.4) + .push_bind(&val.5) + .push_bind(&val.6) + .push_bind(&val.7) + .push_bind(val.8) + .push_bind(val.9) + .push_bind(val.10); }); todo_query .build() @@ -1990,6 +2021,94 @@ impl SessionStore { } } +async fn insert_todo_items( + connection: &mut sqlx::SqliteConnection, + session_id: &str, + items: &[TodoItemInput], + existing: Option<&[TodoItem]>, +) -> Result, StorageError> { + let now = Utc::now().timestamp_millis(); + let rows: Vec = items + .iter() + .enumerate() + .map(|(position, item)| { + let id = item + .id + .clone() + .unwrap_or_else(|| Uuid::new_v4().to_string()); + let previous = existing.and_then(|rows| { + rows.iter() + .find(|row| row.id.as_deref() == Some(id.as_str())) + }); + let unchanged = previous.is_some_and(|previous| { + previous.content == item.content + && previous.status == item.status + && previous.priority == item.priority + && previous.blocker == item.blocker + && previous.plan_ref_json == item.plan_ref_json + && previous.plan_digest == item.plan_digest + }); + ( + session_id.to_string(), + id, + item.content.clone(), + item.status.clone(), + item.priority.clone(), + item.blocker.clone(), + item.plan_ref_json.clone(), + item.plan_digest.clone(), + position as i64, + previous.map_or(now, |previous| previous.time_created), + if unchanged { + previous.map_or(now, |previous| previous.time_updated) + } else { + now + }, + ) + }) + .collect(); + if !rows.is_empty() { + let mut query: QueryBuilder<_> = QueryBuilder::new( + "INSERT INTO todo (session_id, id, content, status, priority, blocker, plan_ref_json, plan_digest, position, time_created, time_updated) ", + ); + query.push_values(&rows, |mut builder, row| { + builder + .push_bind(&row.0) + .push_bind(&row.1) + .push_bind(&row.2) + .push_bind(&row.3) + .push_bind(&row.4) + .push_bind(&row.5) + .push_bind(&row.6) + .push_bind(&row.7) + .push_bind(row.8) + .push_bind(row.9) + .push_bind(row.10); + }); + query + .build() + .execute(&mut *connection) + .await + .map_err(db_error)?; + } + Ok(rows + .into_iter() + .map(|row| TodoItem { + session_id: row.0, + id: Some(row.1), + content: row.2, + status: row.3, + priority: row.4, + blocker: row.5, + plan_ref_json: row.6, + plan_digest: row.7, + position: row.8, + time_created: row.9, + time_updated: row.10, + }) + .collect()) +} + pub struct TodoStore { pool: SqlitePool, } @@ -2002,7 +2121,7 @@ impl TodoStore { pub async fn list(&self, session_id: &str) -> Result, StorageError> { sqlx::query_as::<_, TodoRow>( r#" - SELECT session_id, content, status, priority, position, + SELECT session_id, id, content, status, priority, blocker, plan_ref_json, plan_digest, position, time_created, time_updated FROM todo WHERE session_id = ? ORDER BY position ASC @@ -2020,67 +2139,57 @@ impl TodoStore { session_id: &str, items: Vec, ) -> Result, StorageError> { - let now = Utc::now().timestamp_millis(); - let mut tx = self.pool.begin().await.map_err(db_error)?; - sqlx::query("DELETE FROM todo WHERE session_id = ?") .bind(session_id) .execute(&mut *tx) .await .map_err(db_error)?; - - if !items.is_empty() { - let todo_values: Vec<(String, String, String, String, i64, i64, i64)> = items - .iter() - .enumerate() - .map(|(i, item)| { - ( - session_id.to_string(), - item.content.clone(), - item.status.clone(), - item.priority.clone(), - i as i64, - now, - now, - ) - }) - .collect(); - - let mut todo_query: QueryBuilder<_> = QueryBuilder::new( - "INSERT INTO todo (session_id, content, status, priority, position, time_created, time_updated) ", - ); - todo_query.push_values(&todo_values, |mut b, val| { - b.push_bind(&val.0) - .push_bind(&val.1) - .push_bind(&val.2) - .push_bind(&val.3) - .push_bind(val.4) - .push_bind(val.5) - .push_bind(val.6); - }); - todo_query - .build() - .execute(&mut *tx) - .await - .map_err(db_error)?; - } - + let stored = insert_todo_items(&mut tx, session_id, &items, None).await?; tx.commit().await.map_err(db_error)?; + Ok(stored) + } - Ok(items - .into_iter() - .enumerate() - .map(|(i, item)| TodoItem { - session_id: session_id.to_string(), - content: item.content, - status: item.status, - priority: item.priority, - position: i as i64, - time_created: now, - time_updated: now, - }) - .collect()) + /// Apply one model operation under an immediate transaction so concurrent + /// read-then-write attempts serialize before observing the current list. + pub async fn apply( + &self, + session_id: &str, + operation: crate::task_state::TodoOperation, + policy: &crate::model_profile::types::TaskStatePolicy, + ) -> Result, StorageError> { + let mut tx = begin_immediate(&self.pool).await.map_err(db_error)?; + let rows = sqlx::query_as::<_, TodoRow>( + "SELECT session_id, id, content, status, priority, blocker, plan_ref_json, plan_digest, position, time_created, time_updated FROM todo WHERE session_id = ? ORDER BY position ASC", + ) + .bind(session_id) + .fetch_all(&mut **tx) + .await + .map_err(db_error)?; + let current_models: Vec = rows.into_iter().map(TodoItem::from).collect(); + let current: Vec = current_models + .iter() + .map(crate::task_state::TodoItem::from_session_model) + .collect(); + let state = crate::task_state::TodoState { + items: current, + ..Default::default() + }; + let candidate = state + .candidate_for_operation(operation, policy) + .map_err(|error| StorageError::Database(error.to_string()))?; + let inputs: Vec = candidate + .iter() + .map(|item| item.to_session_input(0)) + .collect(); + sqlx::query("DELETE FROM todo WHERE session_id = ?") + .bind(session_id) + .execute(&mut **tx) + .await + .map_err(db_error)?; + let stored = insert_todo_items(&mut tx, session_id, &inputs, Some(¤t_models)).await?; + tx.commit().await.map_err(db_error)?; + Ok(stored) } pub async fn add( @@ -2090,30 +2199,38 @@ impl TodoStore { ) -> Result { let now = Utc::now().timestamp_millis(); - let mut tx = self.pool.begin().await.map_err(db_error)?; + let mut tx = begin_immediate(&self.pool).await.map_err(db_error)?; + let id = item + .id + .clone() + .unwrap_or_else(|| Uuid::new_v4().to_string()); let position: i64 = sqlx::query_scalar( "SELECT COALESCE(MAX(position) + 1, 0) FROM todo WHERE session_id = ?", ) .bind(session_id) - .fetch_one(&mut *tx) + .fetch_one(&mut **tx) .await .map_err(db_error)?; sqlx::query( r#" - INSERT INTO todo (session_id, content, status, priority, position, time_created, time_updated) - VALUES (?, ?, ?, ?, ?, ?, ?) + INSERT INTO todo (session_id, id, content, status, priority, blocker, plan_ref_json, plan_digest, position, time_created, time_updated) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "#, ) .bind(session_id) + .bind(&id) .bind(&item.content) .bind(&item.status) .bind(&item.priority) + .bind(&item.blocker) + .bind(&item.plan_ref_json) + .bind(&item.plan_digest) .bind(position) .bind(now) .bind(now) - .execute(&mut *tx) + .execute(&mut **tx) .await .map_err(db_error)?; @@ -2121,9 +2238,13 @@ impl TodoStore { Ok(TodoItem { session_id: session_id.to_string(), + id: Some(id), content: item.content, status: item.status, priority: item.priority, + blocker: item.blocker, + plan_ref_json: item.plan_ref_json, + plan_digest: item.plan_digest, position, time_created: now, time_updated: now, @@ -2140,13 +2261,17 @@ impl TodoStore { sqlx::query( r#" - UPDATE todo SET content = ?, status = ?, priority = ?, time_updated = ? + UPDATE todo SET id = COALESCE(?, id), content = ?, status = ?, priority = ?, blocker = COALESCE(?, blocker), plan_ref_json = ?, plan_digest = ?, time_updated = ? WHERE session_id = ? AND position = ? "#, ) + .bind(item.id.as_deref()) .bind(&item.content) .bind(&item.status) .bind(&item.priority) + .bind(item.blocker.as_deref()) + .bind(&item.plan_ref_json) + .bind(&item.plan_digest) .bind(now) .bind(session_id) .bind(position) @@ -3485,3 +3610,229 @@ mod event_store_idempotency_tests { assert!(!store.has_event("tp-event:other").await.unwrap()); } } + +#[cfg(test)] +mod todo_store_tests { + use super::TodoStore; + use crate::model_profile::types::TaskStatePolicy; + use crate::session::models::TodoItemInput; + use crate::task_state::{TodoItem, TodoOperation, TodoPriority, TodoStatus}; + use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions}; + use sqlx::SqlitePool; + use std::time::Duration; + use tempfile::TempDir; + + async fn fixture(max_connections: u32) -> (TempDir, SqlitePool, TodoStore) { + let directory = tempfile::tempdir().expect("todo-store fixture directory"); + let path = directory.path().join("todo-store.db"); + let pool = SqlitePoolOptions::new() + .max_connections(max_connections) + .connect_with( + SqliteConnectOptions::new() + .filename(&path) + .create_if_missing(true) + .foreign_keys(true) + .busy_timeout(Duration::from_secs(5)), + ) + .await + .expect("open todo-store fixture"); + sqlx::query("CREATE TABLE session (id TEXT PRIMARY KEY)") + .execute(&pool) + .await + .expect("create session parent table"); + sqlx::query( + "CREATE TABLE todo (\ + session_id TEXT NOT NULL, id TEXT, content TEXT NOT NULL, status TEXT NOT NULL,\ + priority TEXT NOT NULL, blocker TEXT, plan_ref_json TEXT, plan_digest TEXT, position INTEGER NOT NULL,\ + time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL,\ + PRIMARY KEY (session_id, position),\ + FOREIGN KEY (session_id) REFERENCES session(id) ON DELETE CASCADE\ + )", + ) + .execute(&pool) + .await + .expect("create todo table"); + for session_id in ["session-1", "session-2"] { + sqlx::query("INSERT INTO session (id) VALUES (?)") + .bind(session_id) + .execute(&pool) + .await + .expect("seed session parent"); + } + let store = TodoStore::new(pool.clone()); + (directory, pool, store) + } + + fn todo(id: &str, content: &str, status: TodoStatus, blocker: Option<&str>) -> TodoItem { + TodoItem { + id: id.into(), + content: content.into(), + status, + priority: TodoPriority::Medium, + blocker: blocker.map(str::to_owned), + plan_ref: None, + plan_digest: None, + } + } + + fn input(item: TodoItem) -> TodoItemInput { + item.to_session_input(0) + } + + #[tokio::test(flavor = "current_thread")] + async fn persisted_ids_and_blockers_survive_reload_and_operations_are_atomic() { + let (_directory, pool, store) = fixture(1).await; + let policy = TaskStatePolicy::explicit_todo(); + let initial = [ + todo("stable-a", "first", TodoStatus::Pending, None), + todo("stable-b", "blocked", TodoStatus::Blocked, Some("waiting")), + ]; + store + .set("session-1", initial.iter().cloned().map(input).collect()) + .await + .unwrap(); + + let reloaded = TodoStore::new(pool.clone()) + .list("session-1") + .await + .unwrap(); + assert_eq!(reloaded.len(), 2); + assert_eq!(reloaded[0].id.as_deref(), Some("stable-a")); + assert_eq!(reloaded[0].position, 0); + assert_eq!(reloaded[1].id.as_deref(), Some("stable-b")); + assert_eq!(reloaded[1].blocker.as_deref(), Some("waiting")); + assert_eq!(reloaded[1].position, 1); + assert!(TodoStore::new(pool.clone()) + .list("session-2") + .await + .unwrap() + .is_empty()); + + let added = store + .apply( + "session-1", + TodoOperation::Add(todo("stable-c", "third", TodoStatus::Pending, None)), + &policy, + ) + .await + .unwrap(); + assert_eq!( + added + .iter() + .map(|item| item.id.as_deref().unwrap()) + .collect::>(), + vec!["stable-a", "stable-b", "stable-c"] + ); + + let updated = store + .apply( + "session-1", + TodoOperation::Update { + id: "stable-b".into(), + content: Some("still blocked".into()), + status: None, + priority: Some(TodoPriority::High), + blocker: None, + plan_ref: None, + }, + &policy, + ) + .await + .unwrap(); + assert_eq!(updated[0].content, "first"); + assert_eq!(updated[1].id.as_deref(), Some("stable-b")); + assert_eq!(updated[1].content, "still blocked"); + assert_eq!(updated[1].blocker.as_deref(), Some("waiting")); + assert_eq!(updated[1].priority, "high"); + + let before_rejection = store.list("session-1").await.unwrap(); + let error = store + .apply( + "session-1", + TodoOperation::Remove { + id: "missing".into(), + }, + &policy, + ) + .await + .unwrap_err(); + assert!(error.to_string().contains("missing")); + assert_eq!( + serde_json::to_value(store.list("session-1").await.unwrap()).unwrap(), + serde_json::to_value(before_rejection).unwrap() + ); + + let removed = store + .apply( + "session-1", + TodoOperation::Remove { + id: "stable-a".into(), + }, + &policy, + ) + .await + .unwrap(); + assert_eq!(removed.len(), 2); + assert_eq!(removed[0].id.as_deref(), Some("stable-b")); + assert_eq!(removed[0].blocker.as_deref(), Some("waiting")); + assert_eq!(removed[1].id.as_deref(), Some("stable-c")); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn concurrent_apply_transactions_return_one_complete_replace_each() { + let (_directory, pool, store) = fixture(4).await; + let policy = TaskStatePolicy::explicit_todo(); + let left_store = TodoStore::new(pool.clone()); + let right_store = TodoStore::new(pool.clone()); + let left = TodoOperation::Replace(vec![todo( + "left", + "left outcome", + TodoStatus::Pending, + None, + )]); + let right = TodoOperation::Replace(vec![todo( + "right", + "right outcome", + TodoStatus::Pending, + None, + )]); + + let (left_result, right_result) = tokio::join!( + left_store.apply("session-1", left, &policy), + right_store.apply("session-1", right, &policy), + ); + let left_result = left_result.expect("first apply returns a defined result"); + let right_result = right_result.expect("second apply returns a defined result"); + let final_rows = serde_json::to_value(store.list("session-1").await.unwrap()).unwrap(); + assert!( + final_rows == serde_json::to_value(left_result).unwrap() + || final_rows == serde_json::to_value(right_result).unwrap(), + "serialized replacement leaves one complete outcome, never a mixed list: {final_rows:?}" + ); + } + + #[tokio::test(flavor = "current_thread")] + async fn plan_address_and_digest_survive_store_reload() { + let (_directory, _pool, store) = fixture(1).await; + let address = crate::plan_corpus::PlanAddress::new("plans/roadmap.md", "phase-one") + .expect("valid plan address"); + let mut item = todo("linked", "Implement phase one", TodoStatus::Pending, None); + item.plan_ref = Some(address.clone()); + item.plan_digest = Some("3f5a9c21".into()); + store + .set("session-1", vec![input(item)]) + .await + .expect("persist linked todo"); + + let reloaded = store.list("session-1").await.expect("reload linked todo"); + assert_eq!(reloaded.len(), 1); + assert_eq!( + reloaded[0].plan_ref_json.as_deref(), + Some(serde_json::to_string(&address).unwrap().as_str()) + ); + assert_eq!(reloaded[0].plan_digest.as_deref(), Some("3f5a9c21")); + let domain = crate::task_state::TodoItem::from_session_model(&reloaded[0]); + assert_eq!(domain.plan_ref, Some(address)); + assert_eq!(domain.plan_digest.as_deref(), Some("3f5a9c21")); + } +} diff --git a/crates/codegg-core/src/storage/mod.rs b/crates/codegg-core/src/storage/mod.rs index 764dc5787..ad8e8dc1f 100755 --- a/crates/codegg-core/src/storage/mod.rs +++ b/crates/codegg-core/src/storage/mod.rs @@ -58,7 +58,8 @@ use crate::error::StorageError; /// /// M007-I adds **v94**, the daemon's durable skill-promotion record, keyed on /// the canonical `WorkspaceId`. -pub const STORAGE_LAYOUT_VERSION: u32 = 95; +/// Migration markers: R001 v96, M001 v97, P001 v98, P002 v99. +pub const STORAGE_LAYOUT_VERSION: u32 = 99; pub struct Database { pool: SqlitePool, diff --git a/crates/codegg-core/src/task_state/mod.rs b/crates/codegg-core/src/task_state/mod.rs index 65197e191..a51ce0a77 100644 --- a/crates/codegg-core/src/task_state/mod.rs +++ b/crates/codegg-core/src/task_state/mod.rs @@ -2,6 +2,18 @@ use crate::model_profile::types::{CompletedTodoExposure, TaskStatePolicy, TodoMo use serde::{Deserialize, Serialize}; use thiserror::Error; +pub const MAX_TODO_ITEMS: usize = 512; +pub const MAX_TODO_ITEM_CONTENT_CHARS: usize = 512; +pub const MAX_TODO_LIST_BYTES: usize = 262_144; +pub const MAX_TODO_PROJECTION_CHARS: usize = 2_048; +pub const MAX_PLAN_SPINE_BYTES: usize = 2_048; +pub const MAX_TODO_WINDOW_ITEMS: usize = 16; +pub const MAX_TODO_ECHO_ITEMS: usize = 8; + +pub fn effective_todo_limit(policy: &TaskStatePolicy) -> usize { + policy.max_total_items.min(MAX_TODO_ITEMS) +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TodoItem { pub id: String, @@ -9,6 +21,10 @@ pub struct TodoItem { pub status: TodoStatus, pub priority: TodoPriority, pub blocker: Option, + #[serde(default)] + pub plan_ref: Option, + #[serde(default)] + pub plan_digest: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -29,6 +45,23 @@ pub enum TodoPriority { High, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TodoOperation { + Replace(Vec), + Add(TodoItem), + Update { + id: String, + content: Option, + status: Option, + priority: Option, + blocker: Option>, + plan_ref: Option>, + }, + Remove { + id: String, + }, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] pub struct TodoState { pub items: Vec, @@ -55,6 +88,18 @@ pub enum TodoStateError { MissingBlockerReason, #[error("Invalid status: {0}")] InvalidStatus(String), + #[error("Todo item {index} content exceeds {max} characters")] + ContentTooLong { index: usize, max: usize }, + #[error("Todo item {index} contains a control character")] + ControlCharacter { index: usize }, + #[error("Todo list exceeds {max} bytes")] + ListTooLarge { max: usize }, + #[error("Todo item id is empty or duplicated: {0}")] + DuplicateId(String), + #[error("Invalid plan_ref: {0}")] + InvalidPlanAddress(String), + #[error("No todo item exists with id {0}")] + UnknownId(String), } impl TodoItem { @@ -103,9 +148,16 @@ impl TodoItem { TodoPriority::High => "high".to_string(), }; crate::session::models::TodoItemInput { + id: Some(self.id.clone()), content: self.content.clone(), status, priority, + blocker: self.blocker.clone(), + plan_ref_json: self + .plan_ref + .as_ref() + .and_then(|address| serde_json::to_string(address).ok()), + plan_digest: self.plan_digest.clone(), } } @@ -124,13 +176,20 @@ impl TodoItem { "high" => TodoPriority::High, _ => TodoPriority::Medium, }; - let id = format!("pos-{}", model.position); TodoItem { - id, + id: model + .id + .clone() + .unwrap_or_else(|| format!("legacy-{}", model.position)), content: model.content.clone(), status, priority, - blocker: None, + blocker: model.blocker.clone(), + plan_ref: model + .plan_ref_json + .as_deref() + .and_then(|value| serde_json::from_str(value).ok()), + plan_digest: model.plan_digest.clone(), } } } @@ -149,9 +208,8 @@ impl TodoState { /// the user saw the todo list vanish on resume/pause. Callers that /// genuinely mean "clear the list" set it explicitly instead. /// - /// `revision` is deliberately left monotonic rather than reset to 0: - /// consumers compare revisions across turn boundaries, and a restarted - /// counter makes a fresh write look stale. + /// Rehydration leaves this in-memory turn's revision untouched. The + /// revision is per-turn and does not establish ordering across turns. pub fn load_from_session(&mut self, session_items: Vec) { if session_items.is_empty() { return; @@ -179,51 +237,153 @@ impl TodoState { items: Vec, policy: &TaskStatePolicy, ) -> Result<(), TodoStateError> { + self.apply_operation(TodoOperation::Replace(items), policy) + } + + /// Build and validate a candidate without mutating this state. + pub fn candidate_for_operation( + &self, + operation: TodoOperation, + policy: &TaskStatePolicy, + ) -> Result, TodoStateError> { if policy.mode == TodoMode::Disabled { return Err(TodoStateError::ModeDisabled); } if !policy.allow_model_todo_write { return Err(TodoStateError::WriteNotAllowed); } - if items.len() > policy.max_total_items { + let mut candidate = self.items.clone(); + match operation { + TodoOperation::Replace(items) => candidate = items, + TodoOperation::Add(item) => candidate.push(item), + TodoOperation::Update { + id, + content, + status, + priority, + blocker, + plan_ref, + } => { + let item = candidate + .iter_mut() + .find(|item| item.id == id) + .ok_or_else(|| TodoStateError::UnknownId(id.clone()))?; + if let Some(content) = content { + item.content = content; + } + if let Some(status) = status { + item.status = status; + } + if let Some(priority) = priority { + item.priority = priority; + } + if let Some(blocker) = blocker { + item.blocker = blocker; + } + if let Some(plan_ref) = plan_ref { + item.plan_ref = plan_ref; + item.plan_digest = None; + } + } + TodoOperation::Remove { id } => { + let Some(index) = candidate.iter().position(|item| item.id == id) else { + return Err(TodoStateError::UnknownId(id)); + }; + candidate.remove(index); + } + } + Self::validate_candidate(&candidate, policy)?; + Ok(candidate) + } + + fn validate_candidate( + items: &[TodoItem], + policy: &TaskStatePolicy, + ) -> Result<(), TodoStateError> { + // Check item-level constraints before the count so an invalid 513th + // item reports its content error rather than hiding it behind the cap. + let mut ids = std::collections::HashSet::with_capacity(items.len()); + let mut bytes = 0usize; + for (index, item) in items.iter().enumerate() { + if item.id.is_empty() || !ids.insert(item.id.as_str()) { + return Err(TodoStateError::DuplicateId(item.id.clone())); + } + if let Some(address) = &item.plan_ref { + address + .validate() + .map_err(|error| TodoStateError::InvalidPlanAddress(error.to_string()))?; + } + let content_chars = item.content.chars().count(); + if content_chars > MAX_TODO_ITEM_CONTENT_CHARS { + return Err(TodoStateError::ContentTooLong { + index, + max: MAX_TODO_ITEM_CONTENT_CHARS, + }); + } + if item.content.chars().any(char::is_control) { + return Err(TodoStateError::ControlCharacter { index }); + } + bytes = bytes + .saturating_add(item.id.len()) + .saturating_add(item.content.len()) + .saturating_add(item.blocker.as_ref().map_or(0, String::len)) + .saturating_add(item.status_str().len()) + .saturating_add(item.priority_str().len()) + .saturating_add(3); + if bytes > MAX_TODO_LIST_BYTES { + return Err(TodoStateError::ListTooLarge { + max: MAX_TODO_LIST_BYTES, + }); + } + } + + let max = effective_todo_limit(policy); + if items.len() > max { let dropped = items - .get(policy.max_total_items) + .get(max) .map(|item| { let preview: String = item.content.chars().take(80).collect(); format!("'{}' (id {})", preview, item.id) }) .unwrap_or_else(|| "unknown".to_string()); return Err(TodoStateError::TooManyItems { - max: policy.max_total_items, + max, got: items.len(), dropped, }); } - if policy.require_single_in_progress { - let in_progress_count = items + if policy.require_single_in_progress + && items .iter() - .filter(|i| i.status == TodoStatus::InProgress) - .count(); - if in_progress_count > 1 { - return Err(TodoStateError::MultipleInProgress); - } + .filter(|item| item.status == TodoStatus::InProgress) + .count() + > 1 + { + return Err(TodoStateError::MultipleInProgress); } - if policy.require_blocker_reason { - for item in &items { - if item.status == TodoStatus::Blocked - && item.blocker.as_ref().is_none_or(|b| b.trim().is_empty()) - { - return Err(TodoStateError::MissingBlockerReason); - } - } + if policy.require_blocker_reason + && items.iter().any(|item| { + item.status == TodoStatus::Blocked + && item + .blocker + .as_ref() + .is_none_or(|reason| reason.trim().is_empty()) + }) + { + return Err(TodoStateError::MissingBlockerReason); } + Ok(()) + } + + pub fn apply_operation( + &mut self, + operation: TodoOperation, + policy: &TaskStatePolicy, + ) -> Result<(), TodoStateError> { + let items = self.candidate_for_operation(operation, policy)?; self.items = items; self.revision += 1; - let all_done = self - .items - .iter() - .all(|i| matches!(i.status, TodoStatus::Completed | TodoStatus::Cancelled)); - self.reminder_pending = !all_done; + self.reminder_pending = !self.is_all_done(); Ok(()) } @@ -266,11 +426,19 @@ impl TodoState { CompletedTodoExposure::NoneUnlessAsked => false, }; - let display_items: Vec<&TodoItem> = if expose_completed { + let mut display_items: Vec<&TodoItem> = if expose_completed { self.items.iter().collect() } else { unfinished }; + display_items.sort_by_key(|item| match item.status { + TodoStatus::InProgress => 0, + TodoStatus::Blocked => 1, + TodoStatus::Pending => 2, + TodoStatus::Completed => 3, + TodoStatus::Cancelled => 4, + }); + display_items.truncate(MAX_TODO_WINDOW_ITEMS); let mut result = String::new(); match policy.mode { @@ -296,12 +464,12 @@ impl TodoState { for item in &in_progress { parts.push(format!("in_progress: {}", item.content)); } - for item in &pending { - parts.push(format!("pending: {}", item.content)); - } for item in &blocked { parts.push(format!("blocked: {}", item.content)); } + for item in &pending { + parts.push(format!("pending: {}", item.content)); + } result.push_str(&parts.join("; ")); result .push_str(". Continue from the active item unless the user changes direction."); @@ -349,7 +517,62 @@ impl TodoState { TodoMode::Disabled => return None, } - Some(result) + Some(bounded_projection(result)) + } + + pub fn plan_spine_projection(&self, policy: &TaskStatePolicy) -> Option { + if !self.items.iter().any(|item| item.plan_ref.is_some()) { + return None; + } + let task_window = self.compact_projection(policy)?; + let mut text = format!( + "Planning corpus spine\nStanding instructions: Use todoread detail to resolve each linked section; read its body only when needed. Addresses and digests are not section content.\n{task_window}\nDocument and section index:\n" + ); + for item in self + .items + .iter() + .filter(|item| item.plan_ref.is_some()) + .take(MAX_TODO_WINDOW_ITEMS) + { + if let Some(address) = &item.plan_ref { + text.push_str(&format!("- {}#{}\n", address.doc, address.anchor)); + } + } + Some(bounded_spine_bytes(text)) + } + + pub fn bounded_echo(&self) -> String { + let counts = [ + ("pending", TodoStatus::Pending), + ("in_progress", TodoStatus::InProgress), + ("blocked", TodoStatus::Blocked), + ("completed", TodoStatus::Completed), + ("cancelled", TodoStatus::Cancelled), + ]; + let mut result = format!("Todos: {} total", self.items.len()); + for (label, status) in counts { + let count = self + .items + .iter() + .filter(|item| item.status == status) + .count(); + result.push_str(&format!(", {label}={count}")); + } + for item in self.items.iter().take(MAX_TODO_ECHO_ITEMS) { + result.push_str(&format!( + "\n- [{}] {} (id: {})", + item.status_str(), + item.content, + item.id + )); + } + if self.items.len() > MAX_TODO_ECHO_ITEMS { + result.push_str(&format!( + "\n… {} more", + self.items.len() - MAX_TODO_ECHO_ITEMS + )); + } + bounded_projection(result) } pub fn full_projection_for_user(&self) -> String { @@ -382,6 +605,61 @@ impl TodoState { } } +fn bounded_projection(value: String) -> String { + if value.chars().count() <= MAX_TODO_PROJECTION_CHARS { + return value; + } + let mut bounded: String = value.chars().take(MAX_TODO_PROJECTION_CHARS - 1).collect(); + bounded.push('…'); + bounded +} + +fn bounded_spine_bytes(mut value: String) -> String { + if value.len() < MAX_PLAN_SPINE_BYTES { + return value; + } + + const INDEX_HEADER: &str = " +Document and section index: +"; + if let Some(index_start) = value + .find(INDEX_HEADER) + .map(|start| start + INDEX_HEADER.len()) + { + while value.len() >= MAX_PLAN_SPINE_BYTES { + let Some(last_item) = value[index_start..].rfind( + " +- ", + ) else { + break; + }; + value.truncate(index_start + last_item); + } + } + if value.len() < MAX_PLAN_SPINE_BYTES { + return value; + } + + let index_start = value.find(INDEX_HEADER).unwrap_or(value.len()); + if let Some(last_item) = value[..index_start].rfind( + " +- ", + ) { + value.truncate(last_item); + } + if value.len() < MAX_PLAN_SPINE_BYTES { + return value; + } + + let mut end = MAX_PLAN_SPINE_BYTES - 1 - '…'.len_utf8(); + while !value.is_char_boundary(end) { + end -= 1; + } + let mut bounded = value[..end].to_owned(); + bounded.push('…'); + bounded +} + /// Build a compact reminder string for injection into the agent loop. pub fn build_todo_reminder(todo: &TodoState, policy: &TaskStatePolicy) -> Option { if policy.mode == TodoMode::Disabled { @@ -395,7 +673,8 @@ pub fn build_todo_reminder(todo: &TodoState, policy: &TaskStatePolicy) -> Option { return None; } - todo.compact_projection(policy) + todo.plan_spine_projection(policy) + .or_else(|| todo.compact_projection(policy)) } #[cfg(test)] @@ -405,9 +684,13 @@ mod tests { fn session_todo(content: &str) -> crate::session::models::TodoItem { crate::session::models::TodoItem { session_id: "s1".into(), + id: Some(format!("test-{}", content)), content: content.into(), status: "pending".into(), priority: "medium".into(), + blocker: None, + plan_ref_json: None, + plan_digest: None, position: 0, time_created: 0, time_updated: 0, @@ -466,9 +749,42 @@ mod tests { status, priority: TodoPriority::Medium, blocker: None, + plan_ref: None, + plan_digest: None, } } + fn assert_rejected_preserves( + state: &mut TodoState, + policy: &TaskStatePolicy, + operation: TodoOperation, + expected: fn(&TodoStateError) -> bool, + ) { + let before = state.clone(); + let error = state.apply_operation(operation, policy).unwrap_err(); + assert!( + expected(&error), + "unexpected todo validation error: {error}" + ); + assert_eq!( + state, &before, + "a rejected operation must leave the full state unchanged" + ); + } + + #[test] + fn no_corpus_todo_reminder_matches_the_existing_projection() { + let mut todo = TodoState::new(); + todo.items = vec![make_item("one", "baseline item", TodoStatus::Pending)]; + todo.reminder_pending = true; + let policy = make_policy(); + assert_eq!( + build_todo_reminder(&todo, &policy), + todo.compact_projection(&policy), + "without corpus links, the baseline reminder remains byte-identical" + ); + } + #[test] fn test_replace_basic() { let mut state = TodoState::new(); @@ -619,6 +935,8 @@ mod tests { status: TodoStatus::Blocked, priority: TodoPriority::Medium, blocker: None, + plan_ref: None, + plan_digest: None, }]; let err = state.replace_from_model(items, &policy).unwrap_err(); assert!(matches!(err, TodoStateError::MissingBlockerReason)); @@ -695,4 +1013,323 @@ mod tests { let policy = make_policy(); assert!(build_todo_reminder(&state, &policy).is_none()); } + + #[test] + fn add_update_remove_operations_preserve_identity_and_untouched_fields() { + let mut state = TodoState::new(); + let policy = make_policy(); + let first = TodoItem { + id: "first".into(), + content: "First".into(), + status: TodoStatus::Pending, + priority: TodoPriority::High, + blocker: Some("existing blocker".into()), + plan_ref: None, + plan_digest: None, + }; + let second = make_item("second", "Second", TodoStatus::Pending); + state + .replace_from_model(vec![first.clone(), second], &policy) + .unwrap(); + + let added = make_item("third", "Third", TodoStatus::Pending); + state + .apply_operation(TodoOperation::Add(added.clone()), &policy) + .unwrap(); + assert_eq!( + state.items, + vec![ + first.clone(), + make_item("second", "Second", TodoStatus::Pending), + added.clone() + ] + ); + + state + .apply_operation( + TodoOperation::Update { + id: "second".into(), + content: Some("Second revised".into()), + status: Some(TodoStatus::Blocked), + priority: Some(TodoPriority::Low), + blocker: Some(Some("waiting on input".into())), + plan_ref: None, + }, + &policy, + ) + .unwrap(); + let updated = TodoItem { + id: "second".into(), + content: "Second revised".into(), + status: TodoStatus::Blocked, + priority: TodoPriority::Low, + blocker: Some("waiting on input".into()), + plan_ref: None, + plan_digest: None, + }; + assert_eq!(state.items, vec![first.clone(), updated.clone(), added]); + + state + .apply_operation(TodoOperation::Remove { id: "first".into() }, &policy) + .unwrap(); + assert_eq!( + state.items, + vec![updated, make_item("third", "Third", TodoStatus::Pending)] + ); + } + + #[test] + fn rejected_operations_preserve_the_full_todo_state() { + let mut policy = make_policy(); + policy.max_total_items = MAX_TODO_ITEMS; + policy.require_single_in_progress = true; + policy.require_blocker_reason = true; + let mut state = TodoState::new(); + state + .replace_from_model( + vec![ + make_item("first", "First", TodoStatus::InProgress), + make_item("second", "Second", TodoStatus::Pending), + ], + &policy, + ) + .unwrap(); + + assert_rejected_preserves( + &mut state, + &policy, + TodoOperation::Update { + id: "missing".into(), + content: Some("changed".into()), + status: None, + priority: None, + blocker: None, + plan_ref: None, + }, + |error| matches!(error, TodoStateError::UnknownId(_)), + ); + assert_rejected_preserves( + &mut state, + &policy, + TodoOperation::Add(make_item("first", "duplicate", TodoStatus::Pending)), + |error| matches!(error, TodoStateError::DuplicateId(_)), + ); + assert_rejected_preserves( + &mut state, + &policy, + TodoOperation::Update { + id: "second".into(), + content: None, + status: Some(TodoStatus::InProgress), + priority: None, + blocker: None, + plan_ref: None, + }, + |error| matches!(error, TodoStateError::MultipleInProgress), + ); + assert_rejected_preserves( + &mut state, + &policy, + TodoOperation::Update { + id: "second".into(), + content: None, + status: Some(TodoStatus::Blocked), + priority: None, + blocker: None, + plan_ref: None, + }, + |error| matches!(error, TodoStateError::MissingBlockerReason), + ); + assert_rejected_preserves( + &mut state, + &policy, + TodoOperation::Update { + id: "second".into(), + content: Some("x".repeat(MAX_TODO_ITEM_CONTENT_CHARS + 1)), + status: None, + priority: None, + blocker: None, + plan_ref: None, + }, + |error| matches!(error, TodoStateError::ContentTooLong { index: 1, .. }), + ); + } + + #[test] + fn configured_item_limit_is_clamped_and_accepts_exactly_the_hard_cap() { + let mut policy = make_policy(); + policy.max_total_items = 10_000; + assert_eq!(effective_todo_limit(&policy), MAX_TODO_ITEMS); + + let items: Vec = (0..MAX_TODO_ITEMS) + .map(|index| make_item(&format!("id-{index}"), "step", TodoStatus::Pending)) + .collect(); + let mut state = TodoState::new(); + state.replace_from_model(items, &policy).unwrap(); + assert_eq!(state.items.len(), MAX_TODO_ITEMS); + + let error = state + .candidate_for_operation( + TodoOperation::Add(make_item("over-cap", "next", TodoStatus::Pending)), + &policy, + ) + .unwrap_err(); + assert!(matches!( + error, + TodoStateError::TooManyItems { max, got, .. } + if max == MAX_TODO_ITEMS && got == MAX_TODO_ITEMS + 1 + )); + let message = error.to_string(); + assert!(message.contains("maximum of 512")); + assert!(message.contains("got 513")); + assert!(message.contains("over-cap")); + assert_eq!(state.items.len(), MAX_TODO_ITEMS); + } + + #[test] + fn overlong_513th_item_is_rejected_by_content_before_count() { + let mut policy = make_policy(); + policy.max_total_items = MAX_TODO_ITEMS; + let mut previous = TodoState::new(); + previous + .replace_from_model( + vec![make_item("existing", "keep", TodoStatus::Pending)], + &policy, + ) + .unwrap(); + let before = previous.clone(); + let mut candidate: Vec = (0..MAX_TODO_ITEMS) + .map(|index| make_item(&format!("id-{index}"), "step", TodoStatus::Pending)) + .collect(); + candidate.push(make_item( + "too-long", + &"x".repeat(MAX_TODO_ITEM_CONTENT_CHARS + 1), + TodoStatus::Pending, + )); + + let error = previous.replace_from_model(candidate, &policy).unwrap_err(); + assert!(matches!( + error, + TodoStateError::ContentTooLong { + index: MAX_TODO_ITEMS, + max: MAX_TODO_ITEM_CONTENT_CHARS + } + )); + assert_eq!(previous, before); + } + + #[test] + fn list_byte_limit_and_render_control_characters_are_enforced_atomically() { + let mut policy = make_policy(); + policy.max_total_items = MAX_TODO_ITEMS; + let mut state = TodoState::new(); + state + .replace_from_model( + vec![make_item("old", "stable", TodoStatus::Pending)], + &policy, + ) + .unwrap(); + let before = state.clone(); + + let oversized: Vec = (0..MAX_TODO_ITEMS) + .map(|index| { + make_item( + &format!("id-{index}"), + &"x".repeat(MAX_TODO_ITEM_CONTENT_CHARS), + TodoStatus::Pending, + ) + }) + .collect(); + let error = state.replace_from_model(oversized, &policy).unwrap_err(); + assert!(matches!( + error, + TodoStateError::ListTooLarge { + max: MAX_TODO_LIST_BYTES + } + )); + assert_eq!(state, before); + + let error = state + .apply_operation( + TodoOperation::Add(make_item("bad-line", "line\nbreak", TodoStatus::Pending)), + &policy, + ) + .unwrap_err(); + assert!(matches!( + error, + TodoStateError::ControlCharacter { index: 1 } + )); + assert_eq!(state, before); + } + + #[test] + fn reminder_prioritizes_active_and_blocked_items_before_pending_window() { + let policy = make_policy(); + let mut state = TodoState::new(); + let mut items: Vec = (0..16) + .map(|index| make_item(&format!("pending-{index}"), "pending", TodoStatus::Pending)) + .collect(); + items.push(make_item( + "blocked-late", + "blocked-late", + TodoStatus::Blocked, + )); + items.push(make_item( + "active-late", + "active-late", + TodoStatus::InProgress, + )); + state.replace_from_model(items, &policy).unwrap(); + + let projection = state.compact_projection(&policy).unwrap(); + assert!(projection.contains("in_progress: active-late")); + assert!(projection.contains("blocked: blocked-late")); + assert!(!projection.contains("pending-15")); + } + + #[test] + fn maximum_sized_todo_injection_is_measured_and_bounded() { + let mut policy = make_policy(); + policy.max_total_items = 10_000; + let items: Vec = (0..MAX_TODO_ITEMS) + .map(|index| { + make_item( + &format!("id-{index}"), + &"x".repeat(400), + TodoStatus::Pending, + ) + }) + .collect(); + let mut state = TodoState::new(); + state.replace_from_model(items, &policy).unwrap(); + assert_eq!(state.items.len(), MAX_TODO_ITEMS); + + let reminder = build_todo_reminder(&state, &policy).unwrap(); + let measured_chars = reminder.chars().count(); + println!("512-item todo injection: {measured_chars} characters"); + assert!(measured_chars <= MAX_TODO_PROJECTION_CHARS); + } + + #[test] + fn echo_is_capped_and_reports_full_status_counts() { + let policy = make_policy(); + let mut state = TodoState::new(); + let items: Vec = (0..10) + .map(|index| { + make_item( + &format!("id-{index}"), + &format!("item-{index}"), + TodoStatus::Pending, + ) + }) + .collect(); + state.replace_from_model(items, &policy).unwrap(); + + let echo = state.bounded_echo(); + assert!(echo.contains("Todos: 10 total, pending=10")); + assert_eq!(echo.matches("\n- [pending]").count(), MAX_TODO_ECHO_ITEMS); + assert!(echo.contains("item-7")); + assert!(!echo.contains("item-8")); + assert!(echo.contains("… 2 more")); + } } diff --git a/crates/codegg-core/src/work_plan/todo_projection.rs b/crates/codegg-core/src/work_plan/todo_projection.rs index 598a774fd..97c255b06 100644 --- a/crates/codegg-core/src/work_plan/todo_projection.rs +++ b/crates/codegg-core/src/work_plan/todo_projection.rs @@ -26,6 +26,8 @@ pub const TODO_WORK_REF_SEPARATOR: &str = "@r"; /// are already bounded (1024); the Todo projection keeps a shorter excerpt /// so the model context stays compact. pub const MAX_PROJECTED_TODO_CONTENT_CHARS: usize = 256; +/// Independent WorkPlan-to-Todo cap; the checklist's 512-item ceiling must not widen it. +pub const MAX_PROJECTED_WORK_ITEMS: usize = 12; #[derive(Debug, Error)] pub enum TodoFeedbackError { @@ -124,7 +126,7 @@ pub fn project_to_todo_items( if policy.max_total_items == 0 { return Vec::new(); } - let cap = policy.max_total_items.clamp(1, 12); + let cap = policy.max_total_items.clamp(1, MAX_PROJECTED_WORK_ITEMS); let actionable = actionable_items(items); let mut ordered: Vec<&WorkItem> = Vec::new(); @@ -180,6 +182,8 @@ pub fn project_to_todo_items( } else { None }, + plan_ref: None, + plan_digest: None, } }) .collect() @@ -308,10 +312,10 @@ mod tests { assert!(disabled.is_empty()); let sparse = project_to_todo_items(&plan, &items, &TaskStatePolicy::sparse_plan()); - assert!(sparse.len() <= 8); + assert!(sparse.len() <= MAX_PROJECTED_WORK_ITEMS); let explicit = project_to_todo_items(&plan, &items, &TaskStatePolicy::explicit_todo()); - assert!(explicit.len() <= 10); + assert!(explicit.len() <= MAX_PROJECTED_WORK_ITEMS); let guided = project_to_todo_items(&plan, &items, &TaskStatePolicy::guided_current_task()); assert!(guided.len() <= 4); @@ -349,6 +353,8 @@ mod tests { status: TodoStatus::InProgress, priority: TodoPriority::Medium, blocker: None, + plan_ref: None, + plan_digest: None, }; let err = validate_todo_feedback(&stale_todo, ¤t, &WorkPlanEvidenceSnapshot::empty()) .unwrap_err(); @@ -364,6 +370,8 @@ mod tests { status: TodoStatus::Completed, priority: TodoPriority::Medium, blocker: None, + plan_ref: None, + plan_digest: None, }; let err = validate_todo_feedback(&todo, ¤t, &WorkPlanEvidenceSnapshot::empty()) .unwrap_err(); @@ -379,6 +387,8 @@ mod tests { status: TodoStatus::InProgress, priority: TodoPriority::Medium, blocker: None, + plan_ref: None, + plan_digest: None, }; let target = validate_todo_feedback(&todo, ¤t, &WorkPlanEvidenceSnapshot::empty()).unwrap(); diff --git a/crates/codegg-core/src/workspace.rs b/crates/codegg-core/src/workspace.rs index be7028c79..8e626f991 100644 --- a/crates/codegg-core/src/workspace.rs +++ b/crates/codegg-core/src/workspace.rs @@ -8,6 +8,7 @@ use std::sync::Arc; use chrono::{DateTime, Utc}; use dashmap::DashMap; use serde::{Deserialize, Serialize}; +use sqlx::Row; use thiserror::Error; use tokio::sync::Mutex; @@ -88,11 +89,151 @@ impl std::fmt::Display for WorkspaceId { } } +/// Stable opaque identity for a remote host. It is an identifier, not a +/// connection string, username, credential, or transport address. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)] +#[serde(transparent)] +pub struct RemoteHostRef(String); + +impl RemoteHostRef { + pub fn parse(value: &str) -> Result { + validate_identity("remote_host_ref", value)?; + Ok(Self(value.to_owned())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl<'de> Deserialize<'de> for RemoteHostRef { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let value = String::deserialize(deserializer)?; + Self::parse(&value).map_err(serde::de::Error::custom) + } +} + +/// Maximum UTF-8 byte length of a host-canonicalized target root. +pub const MAX_TARGET_ROOT_LENGTH: usize = 4096; + +/// An absolute remote root represented only as validated text. It deliberately +/// has no path traits or conversion into a local filesystem path. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)] +#[serde(transparent)] +pub struct TargetRoot(String); + +#[derive(Debug, Error, Clone, PartialEq, Eq)] +pub enum TargetRootError { + #[error("target root must be an absolute POSIX path")] + Relative, + #[error("target root contains a NUL byte")] + ContainsNul, + #[error("target root contains a control character")] + ContainsControlCharacter, + #[error("target root exceeds the {MAX_TARGET_ROOT_LENGTH}-byte limit")] + TooLong, +} + +impl TargetRoot { + pub fn new(value: impl Into) -> Result { + let value = value.into(); + if value.len() > MAX_TARGET_ROOT_LENGTH { + return Err(TargetRootError::TooLong); + } + if value.contains('\0') { + return Err(TargetRootError::ContainsNul); + } + if value.chars().any(char::is_control) { + return Err(TargetRootError::ContainsControlCharacter); + } + if !value.starts_with('/') { + return Err(TargetRootError::Relative); + } + Ok(Self(value)) + } + + /// Text view of the remote path; this is never a local Path view. + pub fn as_str(&self) -> &str { + &self.0 + } + + pub fn is_absolute(&self) -> bool { + self.0.starts_with('/') + } + + pub fn is_root(&self) -> bool { + self.0 == "/" + } +} + +impl<'de> Deserialize<'de> for TargetRoot { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let value = String::deserialize(deserializer)?; + Self::new(value).map_err(serde::de::Error::custom) + } +} + +/// Workspace execution identity. SSH targets carry only an opaque host +/// reference and a validated text root; they carry no transport or credentials. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum WorkspaceTarget { + #[default] + Local, + Ssh { + host: RemoteHostRef, + root: TargetRoot, + }, +} + +impl WorkspaceTarget { + pub fn is_local(&self) -> bool { + matches!(self, Self::Local) + } + + pub fn remote_parts(&self) -> Option<(&RemoteHostRef, &TargetRoot)> { + match self { + Self::Local => None, + Self::Ssh { host, root } => Some((host, root)), + } + } +} + +/// A resolved path remains bound to its execution target. Remote values never +/// expose a local Path or PathBuf conversion. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ResolvedWorkspacePath { + Local(PathBuf), + Remote { + host: RemoteHostRef, + root: TargetRoot, + }, +} + +impl ResolvedWorkspacePath { + pub fn into_local_path(self) -> Result { + match self { + Self::Local(path) => Ok(path), + Self::Remote { .. } => Err(PathPolicyError::RemoteTargetNotLocal), + } + } +} + /// Persisted registry entry for a single workspace. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct WorkspaceRecord { pub id: WorkspaceId, + /// Meaningful only for WorkspaceTarget::Local. Remote roots live only in + /// the validated target arm and this compatibility field remains empty. pub canonical_root: PathBuf, + #[serde(default)] + pub target: WorkspaceTarget, pub display_name: String, pub created_at: DateTime, pub last_opened_at: DateTime, @@ -125,6 +266,23 @@ pub enum PathPolicyError { #[error("path contains NUL byte")] ContainsNul, + + #[error("remote target paths cannot be materialized as local paths")] + RemoteTargetNotLocal, + + #[error("remote target path is not valid UTF-8")] + InvalidTargetPathEncoding, + #[error("remote target path contains a control character")] + TargetPathContainsControlCharacter, + + #[error("remote target path '{path}' escapes workspace root '{root}'")] + OutsideTargetWorkspace { path: String, root: String }, + + #[error("remote target path '{0}' is not under any allowed root")] + OutsideTargetAllowedRoots(String), + + #[error("remote target path exceeds the {MAX_TARGET_ROOT_LENGTH}-byte limit")] + TargetPathTooLong, } /// Errors produced by [`WorkspaceRegistry`] operations. @@ -143,6 +301,12 @@ pub enum WorkspaceError { #[error("storage failure: {0}")] Storage(#[from] StorageError), + + #[error("remote workspace registration is unavailable")] + RemoteWorkspaceUnavailable, + + #[error("remote workspace operations cannot use local filesystem paths")] + RemotePathUnavailable, } /// Storage backend trait for `WorkspaceRegistry`. @@ -179,16 +343,113 @@ impl SqliteWorkspaceStore { } } +fn workspace_record_from_row( + row: sqlx::sqlite::SqliteRow, +) -> Result { + let id: String = row + .try_get("id") + .map_err(|e| WorkspaceError::Storage(StorageError::Database(e.to_string())))?; + let target_kind: String = row + .try_get("target_kind") + .map_err(|e| WorkspaceError::Storage(StorageError::Database(e.to_string())))?; + let host_ref: String = row + .try_get("host_ref") + .map_err(|e| WorkspaceError::Storage(StorageError::Database(e.to_string())))?; + let root: String = row + .try_get("canonical_root") + .map_err(|e| WorkspaceError::Storage(StorageError::Database(e.to_string())))?; + let display_name: String = row + .try_get("display_name") + .map_err(|e| WorkspaceError::Storage(StorageError::Database(e.to_string())))?; + let created_at_ms: i64 = row + .try_get("time_created") + .map_err(|e| WorkspaceError::Storage(StorageError::Database(e.to_string())))?; + let last_opened_at_ms: i64 = row + .try_get("time_last_opened") + .map_err(|e| WorkspaceError::Storage(StorageError::Database(e.to_string())))?; + let archived_at_ms: Option = row + .try_get("time_archived") + .map_err(|e| WorkspaceError::Storage(StorageError::Database(e.to_string())))?; + + let target = match target_kind.as_str() { + "local" if host_ref.is_empty() => WorkspaceTarget::Local, + "local" => { + return Err(WorkspaceError::Storage(StorageError::Database( + "local workspace has a non-empty host reference".to_string(), + ))) + } + "ssh" => WorkspaceTarget::Ssh { + host: RemoteHostRef::parse(&host_ref).map_err(|_| { + WorkspaceError::Storage(StorageError::Database( + "stored remote host reference is invalid".to_string(), + )) + })?, + root: TargetRoot::new(root.clone()).map_err(|_| { + WorkspaceError::Storage(StorageError::Database( + "stored remote target root is invalid".to_string(), + )) + })?, + }, + _ => { + return Err(WorkspaceError::Storage(StorageError::Database( + "stored workspace target kind is invalid".to_string(), + ))) + } + }; + let canonical_root = if target.is_local() { + PathBuf::from(root) + } else { + PathBuf::new() + }; + let created_at = chrono::DateTime::::from_timestamp_millis(created_at_ms) + .ok_or_else(|| { + WorkspaceError::Storage(StorageError::Database( + "stored workspace creation time is invalid".to_string(), + )) + })?; + let last_opened_at = chrono::DateTime::::from_timestamp_millis(last_opened_at_ms) + .ok_or_else(|| { + WorkspaceError::Storage(StorageError::Database( + "stored workspace last-opened time is invalid".to_string(), + )) + })?; + + Ok(WorkspaceRecord { + id: WorkspaceId::new_unchecked(id), + target, + canonical_root, + display_name, + created_at, + last_opened_at, + archived_at: archived_at_ms + .and_then(chrono::DateTime::::from_timestamp_millis), + }) +} + #[async_trait::async_trait] impl WorkspaceStore for SqliteWorkspaceStore { async fn upsert(&self, record: &WorkspaceRecord) -> Result<(), WorkspaceError> { + let (target_kind, host_ref, root) = match &record.target { + WorkspaceTarget::Local => ( + "local", + "", + record + .canonical_root + .as_os_str() + .to_string_lossy() + .into_owned(), + ), + WorkspaceTarget::Ssh { host, root } => ("ssh", host.as_str(), root.as_str().to_owned()), + }; sqlx::query( r#" INSERT INTO workspace ( - id, canonical_root, display_name, + id, target_kind, host_ref, canonical_root, display_name, time_created, time_last_opened, time_archived - ) VALUES (?, ?, ?, ?, ?, ?) + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET + target_kind = excluded.target_kind, + host_ref = excluded.host_ref, canonical_root = excluded.canonical_root, display_name = excluded.display_name, time_last_opened = excluded.time_last_opened, @@ -196,7 +457,9 @@ impl WorkspaceStore for SqliteWorkspaceStore { "#, ) .bind(record.id.as_str()) - .bind(record.canonical_root.as_os_str().to_string_lossy().as_ref()) + .bind(target_kind) + .bind(host_ref) + .bind(root) .bind(&record.display_name) .bind(record.created_at.timestamp_millis()) .bind(record.last_opened_at.timestamp_millis()) @@ -208,85 +471,49 @@ impl WorkspaceStore for SqliteWorkspaceStore { } async fn load_by_id(&self, id: &str) -> Result, WorkspaceError> { - let row: Option<(String, String, String, i64, i64, Option)> = sqlx::query_as( - "SELECT id, canonical_root, display_name, time_created, time_last_opened, time_archived FROM workspace WHERE id = ?", + let row = sqlx::query( + "SELECT id, target_kind, host_ref, canonical_root, display_name, time_created, time_last_opened, time_archived FROM workspace WHERE id = ?", ) .bind(id) .fetch_optional(&self.pool) .await .map_err(|e| WorkspaceError::Storage(StorageError::Database(e.to_string())))?; - Ok(row.and_then(|r| { - Some(WorkspaceRecord { - id: WorkspaceId::new_unchecked(r.0), - canonical_root: PathBuf::from(r.1), - display_name: r.2, - created_at: chrono::DateTime::::from_timestamp_millis(r.3)?, - last_opened_at: chrono::DateTime::::from_timestamp_millis(r.4)?, - archived_at: r - .5 - .and_then(chrono::DateTime::::from_timestamp_millis), - }) - })) + row.map(workspace_record_from_row).transpose() } async fn load_by_canonical_root( &self, canonical_root: &Path, ) -> Result, WorkspaceError> { - let row: Option<(String, String, String, i64, i64, Option)> = sqlx::query_as( - "SELECT id, canonical_root, display_name, time_created, time_last_opened, time_archived FROM workspace WHERE canonical_root = ?", + let row = sqlx::query( + "SELECT id, target_kind, host_ref, canonical_root, display_name, time_created, time_last_opened, time_archived FROM workspace WHERE target_kind = 'local' AND host_ref = '' AND canonical_root = ?", ) .bind(canonical_root.as_os_str().to_string_lossy().as_ref()) .fetch_optional(&self.pool) .await .map_err(|e| WorkspaceError::Storage(StorageError::Database(e.to_string())))?; - Ok(row.and_then(|r| { - Some(WorkspaceRecord { - id: WorkspaceId::new_unchecked(r.0), - canonical_root: PathBuf::from(r.1), - display_name: r.2, - created_at: chrono::DateTime::::from_timestamp_millis(r.3)?, - last_opened_at: chrono::DateTime::::from_timestamp_millis(r.4)?, - archived_at: r - .5 - .and_then(chrono::DateTime::::from_timestamp_millis), - }) - })) + row.map(workspace_record_from_row).transpose() } async fn list(&self, include_archived: bool) -> Result, WorkspaceError> { - let rows: Vec<(String, String, String, i64, i64, Option)> = if include_archived { - sqlx::query_as( - "SELECT id, canonical_root, display_name, time_created, time_last_opened, time_archived FROM workspace ORDER BY time_last_opened DESC", + let rows = if include_archived { + sqlx::query( + "SELECT id, target_kind, host_ref, canonical_root, display_name, time_created, time_last_opened, time_archived FROM workspace ORDER BY time_last_opened DESC", ) .fetch_all(&self.pool) .await } else { - sqlx::query_as( - "SELECT id, canonical_root, display_name, time_created, time_last_opened, time_archived FROM workspace WHERE time_archived IS NULL ORDER BY time_last_opened DESC", + sqlx::query( + "SELECT id, target_kind, host_ref, canonical_root, display_name, time_created, time_last_opened, time_archived FROM workspace WHERE time_archived IS NULL ORDER BY time_last_opened DESC", ) .fetch_all(&self.pool) .await } .map_err(|e| WorkspaceError::Storage(StorageError::Database(e.to_string())))?; - Ok(rows - .into_iter() - .filter_map(|r| { - Some(WorkspaceRecord { - id: WorkspaceId::new_unchecked(r.0), - canonical_root: PathBuf::from(r.1), - display_name: r.2, - created_at: chrono::DateTime::::from_timestamp_millis(r.3)?, - last_opened_at: chrono::DateTime::::from_timestamp_millis(r.4)?, - archived_at: r - .5 - .and_then(chrono::DateTime::::from_timestamp_millis), - }) - }) - .collect()) + rows.into_iter().map(workspace_record_from_row).collect() } async fn archive(&self, id: &str) -> Result<(), WorkspaceError> { @@ -348,7 +575,7 @@ impl WorkspaceStore for InMemoryWorkspaceStore { let guard = self.inner.lock().await; Ok(guard .iter() - .find(|r| r.canonical_root == canonical_root) + .find(|r| r.target.is_local() && r.canonical_root == canonical_root) .cloned()) } @@ -418,9 +645,11 @@ impl WorkspaceRegistry { registry .by_id .insert(record.id.as_str().to_string(), Arc::new(record.clone())); - registry - .by_root - .insert(record.canonical_root.clone(), record.id.clone()); + if record.target.is_local() { + registry + .by_root + .insert(record.canonical_root.clone(), record.id.clone()); + } } Ok(registry) } @@ -448,7 +677,7 @@ impl WorkspaceRegistry { if !self.by_id.contains_key(&id_str) { self.by_id.insert(id_str, Arc::new(record.clone())); } - if !self.by_root.contains_key(&canon) { + if record.target.is_local() && !self.by_root.contains_key(&canon) { self.by_root.insert(canon, record.id.clone()); } } @@ -507,6 +736,7 @@ impl WorkspaceRegistry { let now = Utc::now(); let record = WorkspaceRecord { id: WorkspaceId::new(), + target: WorkspaceTarget::Local, canonical_root: canonical_root.clone(), display_name, created_at: now, @@ -522,6 +752,18 @@ impl WorkspaceRegistry { Ok(arc) } + /// Remote registration remains deliberately unavailable until a later + /// milestone adds an authenticated request and host-side canonicalization. + /// The typed sibling exists so callers cannot route a remote root through + /// the local filesystem canonicalizer. + pub async fn get_or_register_remote( + &self, + _host: RemoteHostRef, + _root: TargetRoot, + ) -> Result, WorkspaceError> { + Err(WorkspaceError::RemoteWorkspaceUnavailable) + } + pub async fn resolve(&self, id: &WorkspaceId) -> Option> { if let Some(cached) = self.by_id.get(id.as_str()) { return Some(cached.clone()); @@ -578,12 +820,15 @@ impl WorkspaceRegistry { pub async fn upsert_test_record(&self, record: Arc) { let id_str = record.id.as_str().to_string(); let canon = record.canonical_root.clone(); + let is_local = record.target.is_local(); let owned: WorkspaceRecord = (*record).clone(); if let Err(e) = self.store.upsert(&owned).await { tracing::warn!(error = %e, "failed to upsert test workspace record"); } self.by_id.insert(id_str, record); - self.by_root.insert(canon, owned.id); + if is_local { + self.by_root.insert(canon, owned.id); + } } } @@ -636,6 +881,9 @@ async fn canonicalize_workspace_root(root: &Path) -> Result<(PathBuf, String), W #[derive(Debug)] pub struct ExecutionContext { pub workspace_id: WorkspaceId, + pub target: WorkspaceTarget, + /// Local-only path state. These fields are empty for remote targets; a + /// remote root is held only by the text-only target fields below. pub workspace_root: PathBuf, /// Immutable per-turn default directory. It never expands allowed roots. pub working_directory: PathBuf, @@ -646,6 +894,10 @@ pub struct ExecutionContext { /// Additional roots that may be written. Always starts with /// `workspace_root`; may be widened by configuration. pub allowed_write_roots: Arc<[PathBuf]>, + /// Remote text roots, scoped by target host. Empty for local targets. + pub remote_working_directory: Option, + pub remote_allowed_read_roots: Arc<[TargetRoot]>, + pub remote_allowed_write_roots: Arc<[TargetRoot]>, /// Cancellation signal for the entire execution attempt. Every /// subsystem that owns long-running work should select on this. pub cancellation: tokio_util::sync::CancellationToken, @@ -658,14 +910,32 @@ impl ExecutionContext { session_id: Option, cancellation: tokio_util::sync::CancellationToken, ) -> Arc { - let root = workspace.canonical_root.clone(); + let target = workspace.target.clone(); + let (root, remote_root) = match &target { + WorkspaceTarget::Local => (workspace.canonical_root.clone(), None), + WorkspaceTarget::Ssh { root, .. } => (PathBuf::new(), Some(root.clone())), + }; + let (allowed_read_roots, allowed_write_roots) = if target.is_local() { + (Arc::from([root.clone()]), Arc::from([root.clone()])) + } else { + (Arc::from([]), Arc::from([])) + }; + let remote_allowed_read_roots = remote_root + .as_ref() + .map(|root| Arc::<[TargetRoot]>::from([root.clone()])) + .unwrap_or_else(|| Arc::from([])); + let remote_allowed_write_roots = remote_allowed_read_roots.clone(); Arc::new(Self { workspace_id: workspace.id.clone(), + target, workspace_root: root.clone(), - working_directory: root.clone(), + working_directory: root, session_id, - allowed_read_roots: Arc::from([root.clone()]), - allowed_write_roots: Arc::from([root]), + allowed_read_roots, + allowed_write_roots, + remote_working_directory: remote_root, + remote_allowed_read_roots, + remote_allowed_write_roots, cancellation, }) } @@ -680,6 +950,10 @@ impl ExecutionContext { write_roots: Vec, cancellation: tokio_util::sync::CancellationToken, ) -> Arc { + if !workspace.target.is_local() { + // PathBuf grants are local-only and cannot widen a remote target. + return Self::new(workspace, session_id, cancellation); + } let root = workspace.canonical_root.clone(); let mut read = vec![root.clone()]; for r in read_roots { @@ -695,21 +969,68 @@ impl ExecutionContext { } Arc::new(Self { workspace_id: workspace.id.clone(), + target: WorkspaceTarget::Local, workspace_root: root.clone(), working_directory: root, session_id, allowed_read_roots: Arc::from(read.into_boxed_slice()), allowed_write_roots: Arc::from(write.into_boxed_slice()), + remote_working_directory: None, + remote_allowed_read_roots: Arc::from([]), + remote_allowed_write_roots: Arc::from([]), cancellation, }) } + /// Construct a remote context using only roots already interpreted by its target host. + /// This is an internal domain seam; no authenticated request exposes it in this milestone. + pub fn with_remote_allowed_roots( + workspace: Arc, + session_id: Option, + read_roots: Vec, + write_roots: Vec, + cancellation: tokio_util::sync::CancellationToken, + ) -> Result, WorkspaceError> { + let Some((_, root)) = workspace.target.remote_parts() else { + return Err(WorkspaceError::RemotePathUnavailable); + }; + let target = workspace.target.clone(); + let mut read = vec![root.clone()]; + for allowed in read_roots { + if !read.contains(&allowed) { + read.push(allowed); + } + } + let mut write = vec![root.clone()]; + for allowed in write_roots { + if !write.contains(&allowed) { + write.push(allowed); + } + } + Ok(Arc::new(Self { + workspace_id: workspace.id.clone(), + target, + workspace_root: PathBuf::new(), + working_directory: PathBuf::new(), + session_id, + allowed_read_roots: Arc::from([]), + allowed_write_roots: Arc::from([]), + remote_working_directory: Some(root.clone()), + remote_allowed_read_roots: Arc::from(read.into_boxed_slice()), + remote_allowed_write_roots: Arc::from(write.into_boxed_slice()), + cancellation, + })) + } + /// Return a turn-scoped copy with a canonical default directory beneath /// the immutable workspace root. The authorization ceiling is unchanged. pub fn with_working_directory( self: &Arc, directory: PathBuf, ) -> Result, WorkspaceError> { + if !self.target.is_local() { + return Err(WorkspaceError::RemotePathUnavailable); + } let canonical = directory.canonicalize().map_err(|error| { WorkspaceError::CanonicalizationFailed(directory.clone(), error.to_string()) })?; @@ -718,11 +1039,15 @@ impl ExecutionContext { } Ok(Arc::new(Self { workspace_id: self.workspace_id.clone(), + target: self.target.clone(), workspace_root: self.workspace_root.clone(), working_directory: canonical, session_id: self.session_id.clone(), allowed_read_roots: self.allowed_read_roots.clone(), allowed_write_roots: self.allowed_write_roots.clone(), + remote_working_directory: self.remote_working_directory.clone(), + remote_allowed_read_roots: self.remote_allowed_read_roots.clone(), + remote_allowed_write_roots: self.remote_allowed_write_roots.clone(), cancellation: self.cancellation.clone(), })) } @@ -734,19 +1059,48 @@ impl ExecutionContext { pub async fn resolve_relative_cwd( &self, requested: Option<&Path>, - ) -> Result { - match requested { - None => Ok(self.working_directory.clone()), - Some(p) if p.as_os_str().is_empty() => Ok(self.working_directory.clone()), + ) -> Result { + if let Some((host, target_root)) = self.target.remote_parts() { + let working = self + .remote_working_directory + .as_ref() + .unwrap_or(target_root); + let Some(requested) = requested.filter(|path| !path.as_os_str().is_empty()) else { + return Ok(ResolvedWorkspacePath::Remote { + host: host.clone(), + root: working.clone(), + }); + }; + let resolved = resolve_remote_path( + requested, + working, + &self.remote_allowed_read_roots, + target_root, + )?; + if !remote_path_within_any(resolved.as_str(), &self.remote_allowed_write_roots) { + return Err(PathPolicyError::OutsideTargetAllowedRoots( + requested.to_string_lossy().into_owned(), + )); + } + return Ok(ResolvedWorkspacePath::Remote { + host: host.clone(), + root: resolved, + }); + } + + let path = match requested { + None => self.working_directory.clone(), + Some(p) if p.as_os_str().is_empty() => self.working_directory.clone(), Some(p) if p.is_absolute() => { let canonical = self.pick_allowed_root(p, &self.allowed_read_roots).await?; if !path_within_any(&canonical, &self.allowed_write_roots) { return Err(PathPolicyError::OutsideAllowedRoots(p.to_path_buf())); } - Ok(canonical) + canonical } - Some(p) => resolve_under_root(&self.working_directory, p).await, - } + Some(p) => resolve_under_root(&self.working_directory, p).await?, + }; + Ok(ResolvedWorkspacePath::Local(path)) } /// Verify and canonicalize a *read* access target. Relative paths @@ -754,17 +1108,57 @@ impl ExecutionContext { /// an explicitly allowed read root. Existing files are canonicalized /// directly; paths that don't yet exist canonicalize the nearest /// existing ancestor and append the missing suffix. - pub async fn resolve_read_path(&self, requested: &Path) -> Result { + pub async fn resolve_read_path( + &self, + requested: &Path, + ) -> Result { + if let Some((host, target_root)) = self.target.remote_parts() { + let working = self + .remote_working_directory + .as_ref() + .unwrap_or(target_root); + let root = resolve_remote_path( + requested, + working, + &self.remote_allowed_read_roots, + target_root, + )?; + return Ok(ResolvedWorkspacePath::Remote { + host: host.clone(), + root, + }); + } self.resolve_path_with_allowed(requested, &self.allowed_read_roots) .await + .map(ResolvedWorkspacePath::Local) } /// Verify and canonicalize a *write* access target. Same rules as /// read, plus the destination must also lie under /// `allowed_write_roots`. - pub async fn resolve_write_path(&self, requested: &Path) -> Result { + pub async fn resolve_write_path( + &self, + requested: &Path, + ) -> Result { + if let Some((host, target_root)) = self.target.remote_parts() { + let working = self + .remote_working_directory + .as_ref() + .unwrap_or(target_root); + let root = resolve_remote_path( + requested, + working, + &self.remote_allowed_write_roots, + target_root, + )?; + return Ok(ResolvedWorkspacePath::Remote { + host: host.clone(), + root, + }); + } self.resolve_path_with_allowed(requested, &self.allowed_write_roots) .await + .map(ResolvedWorkspacePath::Local) } async fn resolve_path_with_allowed( @@ -816,6 +1210,85 @@ impl ExecutionContext { } } +fn resolve_remote_path( + requested: &Path, + working_directory: &TargetRoot, + allowed_roots: &[TargetRoot], + workspace_root: &TargetRoot, +) -> Result { + if requested.as_os_str().is_empty() { + return Err(PathPolicyError::EmptyPath); + } + let requested_text = requested + .to_str() + .ok_or(PathPolicyError::InvalidTargetPathEncoding)?; + if requested_text.contains('\0') { + return Err(PathPolicyError::ContainsNul); + } + if requested_text.chars().any(char::is_control) { + return Err(PathPolicyError::TargetPathContainsControlCharacter); + } + let is_absolute = requested_text.starts_with('/'); + let joined = if is_absolute { + requested_text.to_owned() + } else { + format!( + "{}/{requested_text}", + working_directory.as_str().trim_end_matches('/') + ) + }; + if joined.len() > MAX_TARGET_ROOT_LENGTH { + return Err(PathPolicyError::TargetPathTooLong); + } + let resolved = normalize_remote_absolute(&joined); + if remote_path_within_any(&resolved, allowed_roots) { + return TargetRoot::new(resolved).map_err(|error| match error { + TargetRootError::TooLong => PathPolicyError::TargetPathTooLong, + TargetRootError::ContainsNul => PathPolicyError::ContainsNul, + TargetRootError::ContainsControlCharacter => { + PathPolicyError::TargetPathContainsControlCharacter + } + TargetRootError::Relative => PathPolicyError::InvalidTargetPathEncoding, + }); + } + if is_absolute { + Err(PathPolicyError::OutsideTargetAllowedRoots(resolved)) + } else { + Err(PathPolicyError::OutsideTargetWorkspace { + path: resolved, + root: workspace_root.as_str().to_owned(), + }) + } +} + +fn normalize_remote_absolute(path: &str) -> String { + let mut components = Vec::new(); + for component in path.split('/') { + match component { + "" | "." => {} + ".." => { + components.pop(); + } + value => components.push(value), + } + } + if components.is_empty() { + return "/".to_owned(); + } + format!("/{}", components.join("/")) +} + +fn remote_path_within_any(candidate: &str, roots: &[TargetRoot]) -> bool { + roots.iter().any(|root| { + let normalized_root = normalize_remote_absolute(root.as_str()); + normalized_root == "/" + || candidate == normalized_root + || candidate + .strip_prefix(&normalized_root) + .is_some_and(|suffix| suffix.starts_with('/')) + }) +} + /// Canonicalize a path that may not yet exist. Walks up until a /// directory exists, canonicalizes that ancestor, then reattaches the /// trailing segments. Returns an `OutsideWorkspace` error when the @@ -886,6 +1359,160 @@ mod tests { dir } + fn remote_workspace() -> WorkspaceRecord { + let now = Utc::now(); + WorkspaceRecord { + id: WorkspaceId::new(), + target: WorkspaceTarget::Ssh { + host: RemoteHostRef::parse("host-a").unwrap(), + root: TargetRoot::new("/srv/project").unwrap(), + }, + canonical_root: PathBuf::new(), + display_name: "remote-test".to_string(), + created_at: now, + last_opened_at: now, + archived_at: None, + } + } + + #[test] + fn target_root_accepts_bounded_absolute_text() { + let root = TargetRoot::new("/srv/project").unwrap(); + assert_eq!(root.as_str(), "/srv/project"); + assert!(root.is_absolute()); + assert!(!root.is_root()); + assert!(TargetRoot::new("/").unwrap().is_root()); + } + + #[test] + fn target_root_rejects_relative_text() { + assert_eq!( + TargetRoot::new("relative/path").unwrap_err(), + TargetRootError::Relative + ); + } + + #[test] + fn target_root_rejects_nul() { + assert_eq!( + TargetRoot::new("/srv/project\0hidden").unwrap_err(), + TargetRootError::ContainsNul + ); + } + + #[test] + fn target_root_rejects_control_characters() { + assert_eq!( + TargetRoot::new("/srv/project\nchild").unwrap_err(), + TargetRootError::ContainsControlCharacter + ); + } + + #[test] + fn target_root_rejects_excessive_length() { + let root = format!("/{}", "x".repeat(MAX_TARGET_ROOT_LENGTH)); + assert_eq!(TargetRoot::new(root).unwrap_err(), TargetRootError::TooLong); + } + + #[test] + fn workspace_target_distinguishes_local_and_remote_text_roots() { + let remote = WorkspaceTarget::Ssh { + host: RemoteHostRef::parse("host-a").unwrap(), + root: TargetRoot::new("/srv/project").unwrap(), + }; + assert!(WorkspaceTarget::Local.is_local()); + assert!(!remote.is_local()); + assert_eq!(remote.remote_parts().unwrap().1.as_str(), "/srv/project"); + } + + #[tokio::test(flavor = "current_thread")] + async fn remote_registration_refuses_without_creating_a_workspace() { + let store = Arc::new(InMemoryWorkspaceStore::new()); + let registry = WorkspaceRegistry::load(store).await.unwrap(); + let result = registry + .get_or_register_remote( + RemoteHostRef::parse("host-a").unwrap(), + TargetRoot::new("/srv/project").unwrap(), + ) + .await; + assert!(matches!( + result, + Err(WorkspaceError::RemoteWorkspaceUnavailable) + )); + assert!(registry.list(true).await.unwrap().is_empty()); + } + + #[tokio::test(flavor = "current_thread")] + async fn remote_resolvers_stay_target_scoped_and_refuse_escape() { + let context = ExecutionContext::with_remote_allowed_roots( + Arc::new(remote_workspace()), + Some("remote-session".to_string()), + Vec::new(), + Vec::new(), + Default::default(), + ) + .unwrap(); + let resolved = context + .resolve_read_path(Path::new("src/lib.rs")) + .await + .unwrap(); + assert!(matches!( + &resolved, + ResolvedWorkspacePath::Remote { host, root } + if host.as_str() == "host-a" && root.as_str() == "/srv/project/src/lib.rs" + )); + assert_eq!( + resolved.into_local_path().unwrap_err(), + PathPolicyError::RemoteTargetNotLocal + ); + assert!(matches!( + context + .resolve_read_path(Path::new("../../etc/passwd")) + .await, + Err(PathPolicyError::OutsideTargetWorkspace { .. }) + )); + assert!(matches!( + context.resolve_write_path(Path::new("/etc/passwd")).await, + Err(PathPolicyError::OutsideTargetAllowedRoots(_)) + )); + } + + #[tokio::test(flavor = "current_thread")] + async fn remote_target_round_trips_after_database_reopen() { + let directory = tempfile::tempdir().unwrap(); + let database = directory.path().join("workspace.db"); + let options = sqlx::sqlite::SqliteConnectOptions::new() + .filename(&database) + .create_if_missing(true) + .foreign_keys(true); + let pool = sqlx::sqlite::SqlitePoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .unwrap(); + crate::session::schema::migrate(&pool).await.unwrap(); + let store = SqliteWorkspaceStore::new(pool.clone()); + let record = remote_workspace(); + store.upsert(&record).await.unwrap(); + drop(store); + pool.close().await; + + let options = sqlx::sqlite::SqliteConnectOptions::new() + .filename(&database) + .create_if_missing(false) + .foreign_keys(true); + let pool = sqlx::sqlite::SqlitePoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .unwrap(); + crate::session::schema::migrate(&pool).await.unwrap(); + let store = SqliteWorkspaceStore::new(pool); + let reopened = store.load_by_id(record.id.as_str()).await.unwrap().unwrap(); + assert_eq!(reopened.target, record.target); + assert!(reopened.canonical_root.as_os_str().is_empty()); + } + #[tokio::test(flavor = "current_thread")] async fn session_default_working_directory_is_separate_from_workspace_ceiling() { let dir = temp_root("root"); @@ -901,13 +1528,20 @@ mod tests { assert_eq!(context.workspace_root, record.canonical_root); assert_eq!(context.working_directory, nested.canonicalize().unwrap()); assert_eq!( - context.resolve_relative_cwd(None).await.unwrap(), + context + .resolve_relative_cwd(None) + .await + .unwrap() + .into_local_path() + .unwrap(), context.working_directory ); assert_eq!( context .resolve_read_path(Path::new("Cargo.toml")) .await + .unwrap() + .into_local_path() .unwrap(), nested.canonicalize().unwrap().join("Cargo.toml") ); @@ -993,12 +1627,22 @@ mod tests { let ctx = ExecutionContext::new(rec.clone(), Some("s".into()), Default::default()); // None => workspace root - let cwd = ctx.resolve_relative_cwd(None).await.unwrap(); + let cwd = ctx + .resolve_relative_cwd(None) + .await + .unwrap() + .into_local_path() + .unwrap(); assert_eq!(cwd, rec.canonical_root); // Relative subdir resolves under workspace root let sub_rel = Path::new("sub"); - let cwd_rel = ctx.resolve_relative_cwd(Some(sub_rel)).await.unwrap(); + let cwd_rel = ctx + .resolve_relative_cwd(Some(sub_rel)) + .await + .unwrap() + .into_local_path() + .unwrap(); assert!(cwd_rel.starts_with(&rec.canonical_root)); assert!(cwd_rel.ends_with("sub")); diff --git a/crates/codegg-core/src/workspace_services.rs b/crates/codegg-core/src/workspace_services.rs index 56a6cc352..671837e6b 100644 --- a/crates/codegg-core/src/workspace_services.rs +++ b/crates/codegg-core/src/workspace_services.rs @@ -804,6 +804,7 @@ mod tests { fn record_for_tmp(tmp: &tempfile::TempDir) -> Arc { Arc::new(WorkspaceRecord { id: WorkspaceId::new_unchecked(uuid::Uuid::new_v4().to_string()), + target: crate::workspace::WorkspaceTarget::Local, canonical_root: tmp.path().canonicalize().unwrap(), display_name: "tmp".into(), created_at: Utc::now(), @@ -844,6 +845,7 @@ mod tests { let rec_a = record_for_tmp(&tmp_a); let rec_b = Arc::new(WorkspaceRecord { id: WorkspaceId::new_unchecked(uuid::Uuid::new_v4().to_string()), + target: crate::workspace::WorkspaceTarget::Local, canonical_root: tmp_b.path().canonicalize().unwrap(), display_name: "b".into(), created_at: Utc::now(), diff --git a/crates/codegg-core/src/workstream_claim.rs b/crates/codegg-core/src/workstream_claim.rs index 078d53fb1..9564b87e5 100644 --- a/crates/codegg-core/src/workstream_claim.rs +++ b/crates/codegg-core/src/workstream_claim.rs @@ -1,7 +1,4 @@ -//! Durable intent claims for Agent Workstream Blackboard M003. -//! -//! Claims coordinate declared responsibilities only. They are never consulted -//! by filesystem, Git, sandbox, or scheduler authorization. +//! Intent claims carry no execution authority. use std::sync::Arc; @@ -22,6 +19,9 @@ pub const MAX_CLAIM_DEPENDENCIES: usize = 32; pub const MAX_CLAIMS_PER_GROUP: usize = 128; pub const MAX_CLAIM_EVENTS_PER_GROUP: usize = 4096; pub const MAX_CLAIM_LEASE_MS: i64 = 24 * 60 * 60 * 1000; +pub const MAX_CLAIM_NOTE_CHARS: usize = 512; +pub const MAX_CLAIM_INSTRUCTION_PATH_BYTES: usize = MAX_CLAIM_TARGET_BYTES; +pub const MAX_CLAIM_INSTRUCTION_ANCHOR_CHARS: usize = 128; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "kind", content = "id")] @@ -71,6 +71,33 @@ impl ClaimTarget { } } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ClaimInstructionRef { + pub document_path: String, + pub anchor: String, +} + +impl ClaimInstructionRef { + fn validate(&self) -> Result<(), WorkstreamClaimError> { + let drive_prefix = self.document_path.as_bytes().get(1) == Some(&b':') + && self.document_path.as_bytes()[0].is_ascii_alphabetic(); + if self.document_path.len() > MAX_CLAIM_INSTRUCTION_PATH_BYTES || drive_prefix { + return Err(WorkstreamClaimError::InvalidTarget); + } + normalize_relative_intent(&self.document_path)?; + if self.anchor.is_empty() + || self.anchor.chars().count() > MAX_CLAIM_INSTRUCTION_ANCHOR_CHARS + || self + .anchor + .chars() + .any(|ch| ch.is_control() || is_bidi_control(ch)) + { + return Err(WorkstreamClaimError::InvalidTarget); + } + Ok(()) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ClaimState { @@ -116,6 +143,8 @@ pub struct WorkstreamClaim { pub version: u64, pub lease_generation: u64, pub lease_expires_at: Option, + pub note: Option, + pub instruction: Option, pub created_at: i64, pub updated_at: i64, } @@ -137,6 +166,13 @@ impl WorkstreamClaim { version: self.version, lease_generation: self.lease_generation, lease_expires_at: self.lease_expires_at, + note: self.note.clone(), + instruction: self.instruction.as_ref().map(|reference| { + codegg_protocol::projection::WorkstreamClaimInstructionRefProjection { + document_path: reference.document_path.clone(), + anchor: reference.anchor.clone(), + } + }), updated_at: self.updated_at, }) } @@ -180,6 +216,8 @@ pub struct NewWorkstreamClaim { pub target: ClaimTarget, pub idempotency_key: String, pub lease_expires_at: Option, + pub note: Option, + pub instruction: Option, } #[derive(Debug, Clone, Copy)] @@ -218,8 +256,8 @@ pub enum WorkstreamClaimError { IdempotencyConflict, #[error("claim is owned by another actor")] OwnedByAnother, - #[error("claim revision or lease generation is stale")] - StaleRevision, + #[error("claim revision or lease generation is stale (current version {current_version})")] + StaleRevision { current_version: u64 }, #[error("claim state transition is not allowed")] InvalidTransition, #[error("claim capacity is exhausted")] @@ -256,7 +294,7 @@ impl WorkstreamClaimStore { validate_group_actor(&mut conn, group_id, project_id, workspace_id, actor).await?; let rows = sqlx::query( "SELECT claim_id, project_id, workspace_id, group_id, claim_kind, target, state, \ - owner_kind, owner_id, version, lease_generation, lease_expires_at, created_at, updated_at \ + owner_kind, owner_id, version, lease_generation, lease_expires_at, note, instruction_ref_json, created_at, updated_at \ FROM workstream_claim WHERE group_id=? AND project_id=? AND workspace_id=? \ ORDER BY created_at, claim_id LIMIT ?", ) @@ -310,6 +348,12 @@ impl WorkstreamClaimStore { /// Bounded append-only transition provenance. This carries no claim /// target, description, prompt, or free-form agent text. + /// + /// Events are ordered by `created_at` and then by `rowid`, not by + /// `event_id`: the id is a random UUID, so using it as the tiebreaker let + /// two transitions that landed in the same millisecond list in an arbitrary + /// order — the actions of one claim are a causal sequence, and insertion + /// order is what preserves it. pub async fn list_events( &self, group_id: &AgentRunGroupId, @@ -321,7 +365,8 @@ impl WorkstreamClaimStore { validate_group_actor(&mut conn, group_id, project_id, workspace_id, actor).await?; let rows = sqlx::query( "SELECT event_id, claim_id, actor_kind, actor_id, action, version, lease_generation, created_at \ - FROM workstream_claim_event WHERE group_id=? ORDER BY created_at, event_id LIMIT ?", + FROM workstream_claim_event WHERE group_id=? \ + ORDER BY created_at, rowid LIMIT ?", ) .bind(group_id.as_str()) .bind(MAX_CLAIM_EVENTS_PER_GROUP as i64 + 1) @@ -411,7 +456,7 @@ impl WorkstreamClaimStore { ) -> Result<(), WorkstreamClaimError> { let row = sqlx::query( "SELECT claim_id, project_id, workspace_id, group_id, claim_kind, target, state, \ - owner_kind, owner_id, version, lease_generation, lease_expires_at, created_at, updated_at \ + owner_kind, owner_id, version, lease_generation, lease_expires_at, note, instruction_ref_json, created_at, updated_at \ FROM workstream_claim WHERE claim_id=?", ) .bind(claim_id.as_str()) @@ -501,6 +546,33 @@ impl WorkstreamClaimStore { &self, input: NewWorkstreamClaim, ) -> Result { + self.claim_inner(input, None).await + } + + /// Create claims with same-group dependencies atomically. + pub async fn claim_with_prerequisites( + &self, + input: NewWorkstreamClaim, + prerequisites: Vec, + ) -> Result { + self.claim_inner(input, Some(prerequisites)).await + } + + async fn claim_inner( + &self, + input: NewWorkstreamClaim, + prerequisites: Option>, + ) -> Result { + if let Some(prerequisites) = prerequisites.as_ref() { + if prerequisites.len() > MAX_CLAIM_DEPENDENCIES + || prerequisites + .iter() + .enumerate() + .any(|(index, value)| prerequisites[..index].contains(value)) + { + return Err(WorkstreamClaimError::InvalidDependency); + } + } let target = input.target.normalized()?; let normalized_target = match &input.target { ClaimTarget::Task(id) => ClaimTarget::Task(id.clone()), @@ -511,6 +583,16 @@ impl WorkstreamClaimStore { target: normalized_target, ..input }; + if input + .note + .as_ref() + .is_some_and(|note| note.chars().count() > MAX_CLAIM_NOTE_CHARS) + { + return Err(WorkstreamClaimError::InvalidTarget); + } + if let Some(reference) = input.instruction.as_ref() { + reference.validate()?; + } if input.idempotency_key.is_empty() || input.idempotency_key.len() > MAX_CLAIM_IDEMPOTENCY_BYTES || input.lease_expires_at.is_some_and(|deadline| { @@ -524,7 +606,9 @@ impl WorkstreamClaimStore { .execute(&mut *conn) .await .map_err(storage_error)?; - let result = self.claim_locked(&mut conn, input, target).await; + let result = self + .claim_locked(&mut conn, input, target, prerequisites) + .await; match result { Ok(claim) => { sqlx::query("COMMIT") @@ -545,6 +629,7 @@ impl WorkstreamClaimStore { conn: &mut sqlx::pool::PoolConnection, input: NewWorkstreamClaim, target: String, + prerequisites: Option>, ) -> Result { validate_group_actor( conn, @@ -575,7 +660,7 @@ impl WorkstreamClaimStore { if let Some(existing) = sqlx::query( "SELECT claim_id, project_id, workspace_id, group_id, claim_kind, target, state, \ - owner_kind, owner_id, version, lease_generation, lease_expires_at, created_at, updated_at \ + owner_kind, owner_id, version, lease_generation, lease_expires_at, note, instruction_ref_json, created_at, updated_at \ FROM workstream_claim WHERE group_id = ? AND idempotency_key = ?", ) .bind(input.group_id.as_str()) @@ -585,11 +670,46 @@ impl WorkstreamClaimStore { .map_err(storage_error)? { let claim = row_to_claim(&existing)?; + let prerequisites_match = if let Some(expected_prerequisites) = prerequisites.as_ref() { + let dependency_rows = sqlx::query( + "SELECT prerequisite_claim_id, prerequisite_run_id FROM workstream_claim_dependency WHERE claim_id=?", + ) + .bind(claim.claim_id.as_str()) + .fetch_all(&mut **conn) + .await + .map_err(storage_error)?; + let mut existing_prerequisites = Vec::with_capacity(dependency_rows.len()); + for row in dependency_rows { + let prerequisite_claim: Option = + row.try_get("prerequisite_claim_id").map_err(storage_error)?; + let prerequisite_run: Option = + row.try_get("prerequisite_run_id").map_err(storage_error)?; + existing_prerequisites.push(match (prerequisite_claim, prerequisite_run) { + (Some(id), None) => ClaimPrerequisite::Claim( + WorkstreamClaimId::parse(&id) + .map_err(|_| WorkstreamClaimError::CorruptState)?, + ), + (None, Some(id)) => ClaimPrerequisite::Run( + AgentRunId::parse(&id).map_err(|_| WorkstreamClaimError::CorruptState)?, + ), + _ => return Err(WorkstreamClaimError::CorruptState), + }); + } + let mut expected_prerequisites = expected_prerequisites.clone(); + existing_prerequisites.sort_by_key(prerequisite_key); + expected_prerequisites.sort_by_key(prerequisite_key); + existing_prerequisites == expected_prerequisites + } else { + true + }; if claim.project_id == input.project_id && claim.workspace_id == input.workspace_id && claim.target.kind() == input.target.kind() && claim.target.normalized()? == target && claim.owner == input.actor + && claim.note == input.note + && claim.instruction == input.instruction + && prerequisites_match { return Ok(claim); } @@ -608,7 +728,7 @@ impl WorkstreamClaimStore { let active = sqlx::query( "SELECT claim_id, project_id, workspace_id, group_id, claim_kind, target, state, \ - owner_kind, owner_id, version, lease_generation, lease_expires_at, created_at, updated_at \ + owner_kind, owner_id, version, lease_generation, lease_expires_at, note, instruction_ref_json, created_at, updated_at \ FROM workstream_claim WHERE group_id = ? AND state IN ('offered','claimed','blocked')", ) .bind(input.group_id.as_str()) @@ -617,10 +737,15 @@ impl WorkstreamClaimStore { .map_err(storage_error)?; for row in active { let current = row_to_claim(&row)?; - if current + let expired = current .lease_expires_at - .is_some_and(|deadline| deadline <= now_ms()) - { + .is_some_and(|deadline| deadline <= now_ms()); + let owner_is_live = if expired { + claim_owner_is_live(conn, ¤t.owner).await? + } else { + false + }; + if expired && !owner_is_live { sqlx::query( "UPDATE workstream_claim SET state='released', version=version+1, \ lease_generation=lease_generation+1, updated_at=? WHERE claim_id=? \ @@ -658,11 +783,17 @@ impl WorkstreamClaimStore { let id = WorkstreamClaimId::new(); let now = now_ms(); + let instruction_json = input + .instruction + .as_ref() + .map(serde_json::to_string) + .transpose() + .map_err(storage_error)?; let inserted = sqlx::query( "INSERT INTO workstream_claim \ (claim_id, project_id, workspace_id, group_id, claim_kind, target, state, \ - owner_kind, owner_id, version, lease_generation, lease_expires_at, idempotency_key, created_at, updated_at) \ - VALUES (?, ?, ?, ?, ?, ?, 'claimed', ?, ?, 1, 1, ?, ?, ?, ?)", + owner_kind, owner_id, version, lease_generation, lease_expires_at, note, instruction_ref_json, idempotency_key, created_at, updated_at) \ + VALUES (?, ?, ?, ?, ?, ?, 'claimed', ?, ?, 1, 1, ?, ?, ?, ?, ?, ?)", ) .bind(id.as_str()) .bind(input.project_id.as_str()) @@ -673,6 +804,8 @@ impl WorkstreamClaimStore { .bind(input.actor.kind()) .bind(input.actor.id()) .bind(input.lease_expires_at) + .bind(input.note.as_deref()) + .bind(instruction_json) .bind(&input.idempotency_key) .bind(now) .bind(now) @@ -697,21 +830,43 @@ impl WorkstreamClaimStore { version: 1, lease_generation: 1, lease_expires_at: input.lease_expires_at, + note: input.note, + instruction: input.instruction, created_at: now, updated_at: now, }; insert_claim_event(conn, &claim, &claim.owner, "claimed").await?; + let mut claim = claim; + if let Some(prerequisites) = prerequisites { + for prerequisite in prerequisites { + let claim_id = claim.claim_id.clone(); + let actor = claim.owner.clone(); + let expected_version = claim.version; + claim = self + .add_dependency_locked(conn, &claim_id, prerequisite, &actor, expected_version) + .await?; + } + } Ok(claim) } /// Revision- and generation-fenced lifecycle transition. pub async fn transition(&self, cas: ClaimCas) -> Result { + self.transition_with_note(cas, None).await + } + + /// Transition a claim with optional note. + pub async fn transition_with_note( + &self, + cas: ClaimCas, + note: Option, + ) -> Result { let mut conn = self.pool.acquire().await.map_err(storage_error)?; sqlx::query("BEGIN IMMEDIATE") .execute(&mut *conn) .await .map_err(storage_error)?; - let result = self.transition_locked(&mut conn, cas).await; + let result = self.transition_locked(&mut conn, cas, note).await; match result { Ok(claim) => { sqlx::query("COMMIT") @@ -731,10 +886,11 @@ impl WorkstreamClaimStore { &self, conn: &mut sqlx::pool::PoolConnection, cas: ClaimCas, + note: Option, ) -> Result { let row = sqlx::query( "SELECT claim_id, project_id, workspace_id, group_id, claim_kind, target, state, \ - owner_kind, owner_id, version, lease_generation, lease_expires_at, created_at, updated_at \ + owner_kind, owner_id, version, lease_generation, lease_expires_at, note, instruction_ref_json, created_at, updated_at \ FROM workstream_claim WHERE claim_id = ?", ) .bind(cas.claim_id.as_str()) @@ -751,19 +907,32 @@ impl WorkstreamClaimStore { &cas.actor, ) .await?; - if claim.owner != cas.actor { + let actor_is_group_owner = + claim_actor_is_group_owner(conn, &claim.group_id, &cas.actor).await?; + if claim.owner != cas.actor && !actor_is_group_owner { return Err(WorkstreamClaimError::OwnedByAnother); } + if note + .as_ref() + .is_some_and(|note| note.chars().count() > MAX_CLAIM_NOTE_CHARS) + { + return Err(WorkstreamClaimError::InvalidTarget); + } if claim.version != cas.expected_version || claim.lease_generation != cas.expected_lease_generation { - return Err(WorkstreamClaimError::StaleRevision); + return Err(WorkstreamClaimError::StaleRevision { + current_version: claim.version, + }); } - if claim - .lease_expires_at - .is_some_and(|deadline| deadline <= now_ms()) + if !actor_is_group_owner + && claim + .lease_expires_at + .is_some_and(|deadline| deadline <= now_ms()) { - return Err(WorkstreamClaimError::StaleRevision); + return Err(WorkstreamClaimError::StaleRevision { + current_version: claim.version, + }); } let (state, owner, deadline, bump_generation) = transition_target(&claim, &cas)?; if let Some(new_owner) = owner.as_ref() { @@ -779,7 +948,7 @@ impl WorkstreamClaimStore { let now = now_ms(); let result = sqlx::query( "UPDATE workstream_claim SET state=?, owner_kind=?, owner_id=?, version=version+1, \ - lease_generation=lease_generation+?, lease_expires_at=?, updated_at=? \ + lease_generation=lease_generation+?, lease_expires_at=?, note=COALESCE(?, note), updated_at=? \ WHERE claim_id=? AND version=? AND lease_generation=?", ) .bind(state.as_str()) @@ -787,6 +956,7 @@ impl WorkstreamClaimStore { .bind(owner.as_ref().unwrap_or(&claim.owner).id()) .bind(if bump_generation { 1_i64 } else { 0_i64 }) .bind(deadline) + .bind(note.as_deref()) .bind(now) .bind(claim.claim_id.as_str()) .bind(cas.expected_version as i64) @@ -795,7 +965,9 @@ impl WorkstreamClaimStore { .await .map_err(storage_error)?; if result.rows_affected() != 1 { - return Err(WorkstreamClaimError::StaleRevision); + return Err(WorkstreamClaimError::StaleRevision { + current_version: claim.version, + }); } claim.state = state; if let Some(owner) = owner { @@ -806,6 +978,9 @@ impl WorkstreamClaimStore { claim.lease_generation += 1; } claim.lease_expires_at = deadline; + if let Some(note) = note { + claim.note = Some(note); + } claim.updated_at = now; insert_claim_event(conn, &claim, &cas.actor, transition_action(cas.transition)).await?; Ok(claim) @@ -852,7 +1027,7 @@ impl WorkstreamClaimStore { ) -> Result { let row = sqlx::query( "SELECT claim_id, project_id, workspace_id, group_id, claim_kind, target, state, \ - owner_kind, owner_id, version, lease_generation, lease_expires_at, created_at, updated_at \ + owner_kind, owner_id, version, lease_generation, lease_expires_at, note, instruction_ref_json, created_at, updated_at \ FROM workstream_claim WHERE claim_id=?", ) .bind(claim_id.as_str()) @@ -869,11 +1044,15 @@ impl WorkstreamClaimStore { actor, ) .await?; - if claim.owner != *actor { + if claim.owner != *actor + && !claim_actor_is_group_owner(conn, &claim.group_id, actor).await? + { return Err(WorkstreamClaimError::OwnedByAnother); } if claim.version != expected_version { - return Err(WorkstreamClaimError::StaleRevision); + return Err(WorkstreamClaimError::StaleRevision { + current_version: claim.version, + }); } let fanout: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM workstream_claim_dependency WHERE claim_id=?") @@ -965,7 +1144,9 @@ impl WorkstreamClaimStore { .await .map_err(storage_error)?; if updated.rows_affected() != 1 { - return Err(WorkstreamClaimError::StaleRevision); + return Err(WorkstreamClaimError::StaleRevision { + current_version: claim.version, + }); } claim.version += 1; claim.updated_at = now; @@ -985,6 +1166,46 @@ pub struct WorkstreamClaimEvent { pub created_at: i64, } +async fn claim_actor_is_group_owner( + conn: &mut sqlx::pool::PoolConnection, + group_id: &AgentRunGroupId, + actor: &ClaimActor, +) -> Result { + let row = sqlx::query("SELECT owner_kind, owner_run_id FROM agent_run_group WHERE group_id=?") + .bind(group_id.as_str()) + .fetch_optional(&mut **conn) + .await + .map_err(storage_error)? + .ok_or(WorkstreamClaimError::NotFound)?; + let owner_kind: String = row.try_get("owner_kind").map_err(storage_error)?; + let owner_run_id: Option = row.try_get("owner_run_id").map_err(storage_error)?; + Ok(match actor { + ClaimActor::Run(run_id) => { + owner_kind == "run" && owner_run_id.as_deref() == Some(run_id.as_str()) + } + // Turn-owned principals require a validated group. + ClaimActor::Principal(_) => owner_kind == "turn", + }) +} + +async fn claim_owner_is_live( + conn: &mut sqlx::pool::PoolConnection, + owner: &ClaimActor, +) -> Result { + let ClaimActor::Run(run_id) = owner else { + return Ok(false); + }; + let count: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM agent_run WHERE run_id=? \ + AND status NOT IN ('completed','failed','interrupted','cancelled')", + ) + .bind(run_id.as_str()) + .fetch_one(&mut **conn) + .await + .map_err(storage_error)?; + Ok(count > 0) +} + async fn validate_group_actor( conn: &mut sqlx::pool::PoolConnection, group_id: &AgentRunGroupId, @@ -1146,6 +1367,12 @@ fn row_to_claim(row: &sqlx::sqlite::SqliteRow) -> Result return Err(WorkstreamClaimError::CorruptState), }; + let note: Option = row.try_get("note").map_err(storage_error)?; + let instruction_json: Option = + row.try_get("instruction_ref_json").map_err(storage_error)?; + let instruction = instruction_json + .map(|json| serde_json::from_str(&json).map_err(|_| WorkstreamClaimError::CorruptState)) + .transpose()?; Ok(WorkstreamClaim { claim_id: WorkstreamClaimId::parse( &row.try_get::("claim_id") @@ -1175,6 +1402,8 @@ fn row_to_claim(row: &sqlx::sqlite::SqliteRow) -> Result("lease_generation") .map_err(storage_error)? as u64, lease_expires_at: row.try_get("lease_expires_at").map_err(storage_error)?, + note, + instruction, created_at: row.try_get("created_at").map_err(storage_error)?, updated_at: row.try_get("updated_at").map_err(storage_error)?, }) @@ -1283,6 +1512,13 @@ async fn insert_claim_event( Ok(()) } +fn prerequisite_key(prerequisite: &ClaimPrerequisite) -> String { + match prerequisite { + ClaimPrerequisite::Claim(id) => format!("claim:{}", id.as_str()), + ClaimPrerequisite::Run(id) => format!("run:{}", id.as_str()), + } +} + fn transition_action(transition: ClaimTransition) -> &'static str { match transition { ClaimTransition::Renew => "renewed", @@ -1331,4 +1567,29 @@ mod tests { assert!(!targets_overlap("task", "task_a", "task", "task_b")); assert!(targets_overlap("task", "task_a", "task", "task_a")); } + + #[test] + fn workstream_claim_instruction_reference_rejects_paths_outside_the_corpus_root() { + for path in [ + "../outside.md", + "/absolute.md", + "C:/absolute.md", + "docs\\..\\outside.md", + ] { + let reference = ClaimInstructionRef { + document_path: path.into(), + anchor: "## Section".into(), + }; + assert!(matches!( + reference.validate(), + Err(WorkstreamClaimError::InvalidTarget) + )); + } + ClaimInstructionRef { + document_path: "plans/implementation.md".into(), + anchor: "## Acceptance".into(), + } + .validate() + .expect("a relative path and bounded anchor are opaque references"); + } } diff --git a/crates/codegg-core/tests/cached_models_composite_key.rs b/crates/codegg-core/tests/cached_models_composite_key.rs index 6110e6db0..b32576d2a 100644 --- a/crates/codegg-core/tests/cached_models_composite_key.rs +++ b/crates/codegg-core/tests/cached_models_composite_key.rs @@ -99,6 +99,22 @@ async fn upgrading_from_the_single_key_shape_preserves_rows_and_lifts_the_constr .execute(&pool) .await .expect("seed version 69"); + // v69 already includes the workspace table introduced by migration v22. + sqlx::query( + "CREATE TABLE workspace (id TEXT PRIMARY KEY, canonical_root TEXT NOT NULL UNIQUE, display_name TEXT NOT NULL, time_created INTEGER NOT NULL, time_last_opened INTEGER NOT NULL, time_archived INTEGER)", + ) + .execute(&pool) + .await + .expect("create v69 workspace table"); + // v69 already includes the todo table: its columns and primary key are the + // shape v97 extends, so the fixture must carry it rather than let the + // migration run against a table a real v69 database already has. + sqlx::query( + "CREATE TABLE todo (session_id TEXT NOT NULL, content TEXT NOT NULL, status TEXT NOT NULL, priority TEXT NOT NULL, position INTEGER NOT NULL, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, PRIMARY KEY (session_id, position))", + ) + .execute(&pool) + .await + .expect("create v69 todo table"); sqlx::query("CREATE TABLE agent_run (run_id TEXT PRIMARY KEY)") .execute(&pool) .await diff --git a/crates/codegg-core/tests/context.rs b/crates/codegg-core/tests/context.rs index daf5406e1..18732be50 100644 --- a/crates/codegg-core/tests/context.rs +++ b/crates/codegg-core/tests/context.rs @@ -35,6 +35,7 @@ fn make_workspace(root: impl Into, name: &str) -> WorkspaceRecord { let now = Utc::now(); WorkspaceRecord { id: WorkspaceId::new(), + target: codegg_core::workspace::WorkspaceTarget::Local, canonical_root: root.into(), display_name: name.to_string(), created_at: now, diff --git a/crates/codegg-core/tests/project_catalog.rs b/crates/codegg-core/tests/project_catalog.rs index 69f85c648..026bb5c32 100644 --- a/crates/codegg-core/tests/project_catalog.rs +++ b/crates/codegg-core/tests/project_catalog.rs @@ -53,6 +53,7 @@ fn workspace(root: &std::path::Path, name: &str) -> WorkspaceRecord { let now = Utc::now(); WorkspaceRecord { id: WorkspaceId::new(), + target: codegg_core::workspace::WorkspaceTarget::Local, canonical_root: root.to_path_buf(), display_name: name.to_string(), created_at: now, diff --git a/crates/codegg-core/tests/work_plan_projection_arbiter.rs b/crates/codegg-core/tests/work_plan_projection_arbiter.rs index 63129b0ba..6b01d7eae 100644 --- a/crates/codegg-core/tests/work_plan_projection_arbiter.rs +++ b/crates/codegg-core/tests/work_plan_projection_arbiter.rs @@ -8,6 +8,7 @@ use codegg_core::model_profile::types::TaskStatePolicy; use codegg_core::session::schema; use codegg_core::task_state::TodoStatus; +use codegg_core::work_plan::todo_projection::MAX_PROJECTED_WORK_ITEMS; use codegg_core::work_plan::{ assess_work_plan, item_is_satisfied, lookup_item_summary, parse_todo_work_ref, project_to_todo_items, project_work_plan, todo_id_for_work_item, validate_todo_feedback, @@ -256,10 +257,10 @@ async fn todo_projection_respects_all_modes_and_caps() { assert!(disabled.is_empty()); let sparse = project_to_todo_items(&plan, &items, &TaskStatePolicy::sparse_plan()); - assert!(sparse.len() <= 8); + assert!(sparse.len() <= MAX_PROJECTED_WORK_ITEMS); let explicit = project_to_todo_items(&plan, &items, &TaskStatePolicy::explicit_todo()); - assert!(explicit.len() <= 10); + assert!(explicit.len() <= MAX_PROJECTED_WORK_ITEMS); let guided = project_to_todo_items(&plan, &items, &TaskStatePolicy::guided_current_task()); assert!(guided.len() <= 4); @@ -304,6 +305,8 @@ async fn stale_todo_mapping_cannot_mutate_newer_item() { status: TodoStatus::InProgress, priority: codegg_core::task_state::TodoPriority::Medium, blocker: None, + plan_ref: None, + plan_digest: None, }; let err = validate_todo_feedback(&stale_todo, &newer, &WorkPlanEvidenceSnapshot::empty()) .unwrap_err(); diff --git a/crates/codegg-node-protocol/Cargo.toml b/crates/codegg-node-protocol/Cargo.toml new file mode 100644 index 000000000..510db2942 --- /dev/null +++ b/crates/codegg-node-protocol/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "codegg-node-protocol" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +homepage.workspace = true +description = "Wire contract for the local CodeGG execution node" + +[dependencies] +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true + +[lints] +workspace = true diff --git a/crates/codegg-node-protocol/src/lib.rs b/crates/codegg-node-protocol/src/lib.rs new file mode 100644 index 000000000..01759da08 --- /dev/null +++ b/crates/codegg-node-protocol/src/lib.rs @@ -0,0 +1,345 @@ +//! Types and bounded newline-delimited JSON framing for the local node protocol. +//! +//! This crate contains no execution, workspace, or sandbox authority. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::io::{self, BufRead, Write}; + +pub const API_VERSION: u32 = 1; +pub const MAX_FRAME_BYTES: usize = 1024 * 1024; +pub const CAPABILITIES: &[&str] = &["lifecycle"]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Method { + Initialize, + Attach, + Detach, + Health, + Shutdown, +} + +impl Method { + pub fn as_str(self) -> &'static str { + match self { + Self::Initialize => "initialize", + Self::Attach => "attach", + Self::Detach => "detach", + Self::Health => "health", + Self::Shutdown => "shutdown", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ErrorClass { + ProtocolMismatch, + BuildMismatch, + UnsupportedCapability, + UnknownMethod, + InvalidParams, + WorkspaceUnavailable, + PathEscape, + IsolationNotObtained, + Cancelled, + Busy, + RemoteLost, + PeerRejected, + UnsupportedPlatform, + Internal, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct NodeError { + pub class: ErrorClass, + pub message: String, +} +impl NodeError { + pub fn new(class: ErrorClass, message: impl Into) -> Self { + Self { + class, + message: message.into(), + } + } +} +impl std::fmt::Display for NodeError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}: {}", self.class.as_str(), self.message) + } +} +impl std::error::Error for NodeError {} +impl ErrorClass { + pub fn as_str(self) -> &'static str { + match self { + Self::ProtocolMismatch => "protocol_mismatch", + Self::BuildMismatch => "build_mismatch", + Self::UnsupportedCapability => "unsupported_capability", + Self::UnknownMethod => "unknown_method", + Self::InvalidParams => "invalid_params", + Self::WorkspaceUnavailable => "workspace_unavailable", + Self::PathEscape => "path_escape", + Self::IsolationNotObtained => "isolation_not_obtained", + Self::Cancelled => "cancelled", + Self::Busy => "busy", + Self::RemoteLost => "remote_lost", + Self::PeerRejected => "peer_rejected", + Self::UnsupportedPlatform => "unsupported_platform", + Self::Internal => "internal", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Request { + pub jsonrpc: String, + pub id: Value, + pub method: String, + #[serde(default)] + pub params: Value, +} +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Response { + pub jsonrpc: String, + pub id: Value, + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} +impl Response { + pub fn result(id: Value, result: impl Serialize) -> Result { + Ok(Self { + jsonrpc: "2.0".to_owned(), + id, + result: Some(serde_json::to_value(result)?), + error: None, + }) + } + pub fn error(id: Value, error: NodeError) -> Self { + Self { + jsonrpc: "2.0".to_owned(), + id, + result: None, + error: Some(error), + } + } +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InitializeParams { + pub api_version: u32, + pub build_id: String, + #[serde(default)] + pub capabilities: Vec, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InitializeResult { + pub api_version: u32, + pub codegg_version: String, + pub build_id: String, + pub target: String, + pub uid: u32, + pub socket_path: String, + pub capabilities: Vec, + pub declared_isolation: Vec, +} +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum IsolationProfile { + ReadOnly, + WorkspaceWrite, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AttachParams { + pub root: String, + #[serde(default)] + pub working_directory: Option, + #[serde(default)] + pub requested_isolation: Option, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct IsolationFacts { + pub backend: String, + pub abi: Option, + pub guarantees: Vec, + pub limits: Vec, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AttachResult { + pub canonical_root: String, + pub working_directory: String, + pub tool_count: usize, + pub requested_isolation: IsolationProfile, + pub obtained_isolation: IsolationFacts, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DetachParams { + pub root: String, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DetachResult { + pub detached: bool, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HealthResult { + pub healthy: bool, + pub attached_workspaces: usize, +} +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ShutdownResult { + pub shutting_down: bool, +} + +pub fn validate_capabilities(requested: &[String]) -> Result, NodeError> { + for capability in requested { + if !CAPABILITIES.contains(&capability.as_str()) { + return Err(NodeError::new( + ErrorClass::UnsupportedCapability, + format!("unsupported capability: {capability}"), + )); + } + } + Ok(requested.to_vec()) +} + +#[derive(Debug, thiserror::Error)] +pub enum FrameError { + #[error("frame exceeds {MAX_FRAME_BYTES} bytes")] + TooLarge, + #[error("partial frame at EOF")] + PartialAtEof, + #[error("frame is not UTF-8 JSON")] + InvalidJson, + #[error("I/O error: {0}")] + Io(#[from] io::Error), +} + +/// Read one bounded line. A malformed line is consumed through its newline so the connection can continue. +pub fn read_frame(reader: &mut R) -> Result>, FrameError> { + let mut frame = Vec::new(); + let mut oversized = false; + loop { + let available = reader.fill_buf()?; + if available.is_empty() { + return if frame.is_empty() && !oversized { + Ok(None) + } else if oversized { + Err(FrameError::TooLarge) + } else { + Err(FrameError::PartialAtEof) + }; + } + let until_newline = available + .iter() + .position(|byte| *byte == b'\n') + .map(|i| i + 1) + .unwrap_or(available.len()); + let has_newline = until_newline > 0 && available[until_newline - 1] == b'\n'; + let content_len = if has_newline { + until_newline - 1 + } else { + until_newline + }; + if !oversized { + if frame.len().saturating_add(content_len) > MAX_FRAME_BYTES { + oversized = true; + } else { + frame.extend_from_slice(&available[..content_len]); + } + } + reader.consume(until_newline); + if has_newline { + if oversized { + return Err(FrameError::TooLarge); + } + if frame.last() == Some(&b'\r') { + frame.pop(); + } + std::str::from_utf8(&frame).map_err(|_| FrameError::InvalidJson)?; + serde_json::from_slice::(&frame).map_err(|_| FrameError::InvalidJson)?; + return Ok(Some(frame)); + } + } +} + +pub fn write_frame(writer: &mut W, value: &T) -> Result<(), FrameError> { + let bytes = serde_json::to_vec(value).map_err(|_| FrameError::InvalidJson)?; + if bytes.len() > MAX_FRAME_BYTES { + return Err(FrameError::TooLarge); + } + writer.write_all(&bytes)?; + writer.write_all(b"\n")?; + writer.flush()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn every_method_round_trips() { + for method in [ + Method::Initialize, + Method::Attach, + Method::Detach, + Method::Health, + Method::Shutdown, + ] { + let request = Request { + jsonrpc: "2.0".to_owned(), + id: Value::from(1), + method: method.as_str().to_owned(), + params: Value::Null, + }; + let mut bytes = Vec::new(); + write_frame(&mut bytes, &request).unwrap(); + let parsed: Request = + serde_json::from_slice(&read_frame(&mut Cursor::new(bytes)).unwrap().unwrap()) + .unwrap(); + assert_eq!(parsed.method, method.as_str()); + } + } + #[test] + fn rejects_overlong_line_and_recovers_at_newline() { + let mut bytes = vec![b'x'; MAX_FRAME_BYTES + 1]; + bytes.extend_from_slice(b"\n{}\n"); + let mut input = Cursor::new(bytes); + assert!(matches!(read_frame(&mut input), Err(FrameError::TooLarge))); + assert_eq!(read_frame(&mut input).unwrap().unwrap(), b"{}"); + } + #[test] + fn invalid_json_is_typed_and_connection_continues() { + let mut input = Cursor::new(b"not json\n{}\n"); + assert!(matches!( + read_frame(&mut input), + Err(FrameError::InvalidJson) + )); + assert_eq!(read_frame(&mut input).unwrap().unwrap(), b"{}"); + } + #[test] + fn partial_line_at_eof_is_typed() { + assert!(matches!( + read_frame(&mut Cursor::new(b"{}")), + Err(FrameError::PartialAtEof) + )); + } + #[test] + fn capabilities_refuse_unknown_values() { + let error = validate_capabilities(&["invoke".to_owned()]).unwrap_err(); + assert_eq!(error.class, ErrorClass::UnsupportedCapability); + } +} diff --git a/crates/codegg-protocol/src/projection/mod.rs b/crates/codegg-protocol/src/projection/mod.rs index cab0a16d3..2a5f1959b 100644 --- a/crates/codegg-protocol/src/projection/mod.rs +++ b/crates/codegg-protocol/src/projection/mod.rs @@ -107,7 +107,8 @@ pub use replay::{ pub use snapshot::SessionProjectionSnapshot; pub use workstream::{ project_workstream, project_workstream_with_claims, AgentWorkstreamMember, - AgentWorkstreamSnapshot, WorkstreamClaimProjection, WorkstreamDependencyProjection, - WorkstreamJobFact, WorkstreamProjectionError, WorkstreamWorktreeFact, MAX_WORKSTREAM_CLAIMS, - MAX_WORKSTREAM_DEPENDENCIES, MAX_WORKSTREAM_MEMBERS, + AgentWorkstreamSnapshot, WorkstreamClaimInstructionRefProjection, WorkstreamClaimProjection, + WorkstreamDependencyProjection, WorkstreamJobFact, WorkstreamProjectionError, + WorkstreamWorktreeFact, MAX_WORKSTREAM_CLAIMS, MAX_WORKSTREAM_DEPENDENCIES, + MAX_WORKSTREAM_MEMBERS, }; diff --git a/crates/codegg-protocol/src/projection/snapshot.rs b/crates/codegg-protocol/src/projection/snapshot.rs index f49bb2284..bf6c00687 100644 --- a/crates/codegg-protocol/src/projection/snapshot.rs +++ b/crates/codegg-protocol/src/projection/snapshot.rs @@ -590,6 +590,8 @@ mod tests { version: 1, lease_generation: 1, lease_expires_at: None, + note: None, + instruction: None, updated_at: 10, }; let mut snapshot = SessionProjectionSnapshot::empty("s", "p", "w"); diff --git a/crates/codegg-protocol/src/projection/workstream.rs b/crates/codegg-protocol/src/projection/workstream.rs index f95ceb2ba..675bd87ab 100644 --- a/crates/codegg-protocol/src/projection/workstream.rs +++ b/crates/codegg-protocol/src/projection/workstream.rs @@ -9,6 +9,9 @@ use super::snapshot::SessionProjectionSnapshot; pub const MAX_WORKSTREAM_MEMBERS: usize = 16; pub const MAX_WORKSTREAM_CLAIMS: usize = 128; pub const MAX_WORKSTREAM_DEPENDENCIES: usize = 512; +pub const MAX_WORKSTREAM_CLAIM_NOTE_CHARS: usize = 512; +pub const MAX_WORKSTREAM_CLAIM_INSTRUCTION_PATH_BYTES: usize = 256; +pub const MAX_WORKSTREAM_CLAIM_INSTRUCTION_ANCHOR_CHARS: usize = 128; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct AgentWorkstreamSnapshot { @@ -33,6 +36,12 @@ pub struct AgentWorkstreamSnapshot { pub claims_truncated: bool, } +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct WorkstreamClaimInstructionRefProjection { + pub document_path: String, + pub anchor: String, +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct WorkstreamClaimProjection { pub claim_id: String, @@ -47,6 +56,10 @@ pub struct WorkstreamClaimProjection { pub version: u64, pub lease_generation: u64, pub lease_expires_at: Option, + #[serde(default)] + pub note: Option, + #[serde(default)] + pub instruction: Option, pub updated_at: i64, } @@ -177,6 +190,24 @@ pub fn project_workstream_with_claims( version: claim.version, lease_generation: claim.lease_generation, lease_expires_at: claim.lease_expires_at, + note: claim + .note + .as_ref() + .map(|note| note.chars().take(MAX_WORKSTREAM_CLAIM_NOTE_CHARS).collect()), + instruction: claim.instruction.as_ref().map(|reference| { + WorkstreamClaimInstructionRefProjection { + document_path: truncate_str( + &reference.document_path, + MAX_WORKSTREAM_CLAIM_INSTRUCTION_PATH_BYTES, + ) + .into_owned(), + anchor: reference + .anchor + .chars() + .take(MAX_WORKSTREAM_CLAIM_INSTRUCTION_ANCHOR_CHARS) + .collect(), + } + }), updated_at: claim.updated_at, }); } @@ -384,6 +415,8 @@ mod tests { version: 2, lease_generation: 1, lease_expires_at: None, + note: None, + instruction: None, updated_at: 4, }, WorkstreamClaimProjection { @@ -399,6 +432,8 @@ mod tests { version: 1, lease_generation: 1, lease_expires_at: None, + note: None, + instruction: None, updated_at: 4, }, ]; @@ -457,4 +492,27 @@ mod tests { assert!(view.members.len() <= MAX_WORKSTREAM_MEMBERS); assert!(view.unavailable_member_run_ids.len() <= MAX_WORKSTREAM_MEMBERS); } + + #[test] + fn old_claim_projection_payload_defaults_note_and_instruction() { + let old_payload = serde_json::json!({ + "claim_id": "claim-a", + "project_id": "project-a", + "workspace_id": "workspace-a", + "group_id": "group-a", + "kind": "path", + "target": "src/lib.rs", + "state": "claimed", + "owner_kind": "run", + "owner_id": "run-a", + "version": 1, + "lease_generation": 1, + "lease_expires_at": null, + "updated_at": 4 + }); + let projection: WorkstreamClaimProjection = + serde_json::from_value(old_payload).expect("legacy claim projection decodes"); + assert_eq!(projection.note, None); + assert_eq!(projection.instruction, None); + } } diff --git a/crates/codegg-sandbox/src/policy.rs b/crates/codegg-sandbox/src/policy.rs index 916d16be5..af75ee1a7 100644 --- a/crates/codegg-sandbox/src/policy.rs +++ b/crates/codegg-sandbox/src/policy.rs @@ -683,6 +683,7 @@ pub fn sensitive_deny_paths() -> Vec { // CodeGG's own durable credential store. A sandboxed command // must never be able to read the secrets the agent itself uses. ".config/codegg", + ".codegg/node", ".codegg", ".bash_history", ".zsh_history", @@ -1025,6 +1026,15 @@ mod tests { "Library/Cookies", ]; + #[test] + fn execution_node_socket_has_an_explicit_deny_entry() { + let home = home_dir().expect("HOME is required for the node socket deny"); + assert!( + sensitive_deny_paths().contains(&home.join(".codegg/node")), + "the private execution-node directory must remain an explicit sandbox deny" + ); + } + #[test] fn curated_credential_deny_set_is_complete() { let home = home_dir().expect("HOME is required for the curated deny set"); diff --git a/crates/codegg-tui/src/app/command_argument_tests.rs b/crates/codegg-tui/src/app/command_argument_tests.rs index 9931a81ea..952eead9a 100644 --- a/crates/codegg-tui/src/app/command_argument_tests.rs +++ b/crates/codegg-tui/src/app/command_argument_tests.rs @@ -222,9 +222,21 @@ fn review_change_alias_receives_the_same_id() { fn theme_alias_receives_the_subcommand() { let mut app = App::new_for_testing("/tmp".into()); dispatch_typed(&mut app, "/theme list"); - let messages = toast_messages(&app); + // The list is a report, not an echo of the press: it opens the usage + // dialog, which stays readable, instead of a three-second box. + assert_eq!( + app.ui_state.dialog, + crate::app::Dialog::Usage, + "/theme list output belongs in the persistent usage dialog" + ); + let listed = app + .focus_manager + .with_component::(|dialog| { + dialog.content_lines().join("\n") + }) + .expect("the theme list should be mounted in an InfoDialog"); assert!( - messages.iter().any(|m| m.contains("Themes:")), - "the alias must resolve to the same command and lose its own token: {messages:?}" + listed.contains("Themes:"), + "the alias must resolve to the same command and lose its own token, got: {listed:?}" ); } diff --git a/crates/codegg-tui/src/app/commands.rs b/crates/codegg-tui/src/app/commands.rs index 61b2898d7..1affb6e7a 100644 --- a/crates/codegg-tui/src/app/commands.rs +++ b/crates/codegg-tui/src/app/commands.rs @@ -582,6 +582,11 @@ pub enum TuiCommand { summary: String, is_error: bool, }, + /// Completion of the daemon-owned `/advisor` status read. + AdvisorStatusLoaded { + message: String, + is_error: bool, + }, /// Run diagnostics (search backend, MCP, providers). The result is /// logged at `codegg::doctor` and surfaced as a toast. The /// handler in `tui_cmd.rs` performs the actual async work. @@ -980,7 +985,6 @@ pub enum TuiCommand { session: Option, agent: Option, model: Option, - template_name: String, error: Option, }, /// Completion of a user-initiated new session (Ctrl+N, `/new`). @@ -1136,7 +1140,6 @@ pub enum TuiCommand { ProjectLifecycleFinished { picker_request_id: u64, project_id: String, - restored: bool, error: Option, }, /// Completion of permanent project destruction. diff --git a/crates/codegg-tui/src/app/compact_command_tests.rs b/crates/codegg-tui/src/app/compact_command_tests.rs index 800fe2037..8272af123 100644 --- a/crates/codegg-tui/src/app/compact_command_tests.rs +++ b/crates/codegg-tui/src/app/compact_command_tests.rs @@ -290,16 +290,24 @@ async fn an_answer_about_another_session_is_not_reported_as_this_sessions_compac ); } -/// With no session attached there is nothing to compact, and the command says -/// so instead of asking. +/// With no session attached there is nothing to compact. The refusal used to be +/// a toast repeating the empty session state the TUI already renders; the command +/// now asks for nothing and announces nothing, so this asserts both halves. #[test] -fn the_compact_command_says_so_when_no_session_is_attached() { +fn the_compact_command_asks_nothing_when_no_session_is_attached() { let mut app = App::new_for_testing("/tmp".into()); dispatch(&mut app, "/compact"); - let toast = last_toast(&app); assert!( - toast.contains("No session is attached"), - "the command must say why it did nothing: {toast:?}" + app.session_state.session.is_none(), + "the fixture must have no session, or this case proves nothing" + ); + assert_eq!( + app.session_state.compaction_count, 0, + "no session means no compaction can have happened" + ); + assert!( + app.messages_state.toasts.is_empty(), + "the empty session state is the explanation; a toast would duplicate it" ); } diff --git a/crates/codegg-tui/src/app/input.rs b/crates/codegg-tui/src/app/input.rs index 548b5c7e3..96c7380ea 100644 --- a/crates/codegg-tui/src/app/input.rs +++ b/crates/codegg-tui/src/app/input.rs @@ -106,11 +106,7 @@ impl App { self.handle_connect_send(); } TuiMsg::CloseDialog => { - if self.dialog_state.project_init_draft.take().is_some() { - self.messages_state - .toasts - .info("Initialization preview cancelled; no file was written"); - } + let _ = self.dialog_state.project_init_draft.take(); self.close_dialog(); } // ── Project chat window intents ────────────────────────── @@ -185,10 +181,11 @@ impl App { draft_token: token, }); } else { - self.messages_state - .toasts - .info("AGENTS.md already matches the generated proposal"); self.close_dialog(); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::ProjectInit, + vec!["AGENTS.md already matches the generated proposal".to_string()], + ); } } else { self.messages_state @@ -277,9 +274,7 @@ impl App { self.dialog_state.pending_shell_command = None; self.dialog_state.pending_connection_lifecycle = None; // M007: cancelling a mode-change dialog changes nothing. - if self.dialog_state.pending_policy_confirm.take().is_some() { - self.messages_state.toasts.info("Runtime policy unchanged."); - } + let _ = self.dialog_state.pending_policy_confirm.take(); } } TuiMsg::McpAction { @@ -288,10 +283,14 @@ impl App { } => { match action.as_str() { "Configure OAuth" => { - self.messages_state.toasts.info(&format!( - "OAuth for {} - configure in .codegg/mcp.json", - server_name - )); + self.close_dialog(); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!( + "OAuth for {} - configure in .codegg/mcp.json", + server_name + )], + ); } "Browse Resources" => { if let Some(ref mut mcp) = self.dialog_state.mcp_dialog { @@ -299,42 +298,29 @@ impl App { mcp.action_mode = false; } self.close_dialog(); - return; - } - "Disconnect" => { - self.messages_state - .toasts - .info(&format!("Disconnecting {}...", server_name)); - } - "Reconnect" => { - self.messages_state - .toasts - .info(&format!("Reconnecting {}...", server_name)); - } - "Connect" => { - self.messages_state - .toasts - .info(&format!("Connecting {}...", server_name)); - } - "Remove" => { - self.messages_state - .toasts - .info(&format!("Removing {}...", server_name)); } "Wait" => { - self.messages_state - .toasts - .info("Server is connecting, please wait..."); + self.close_dialog(); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Server is connecting, please wait...".to_string()], + ); } "Configure" => { - self.messages_state.toasts.info(&format!( - "Configure {} - edit .codegg/mcp.json", - server_name - )); + self.close_dialog(); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!("Configure {} - edit .codegg/mcp.json", server_name)], + ); + } + "Disconnect" | "Reconnect" | "Connect" | "Remove" => { + // The action's state is reflected by the server list; do not toast its click. + self.close_dialog(); + } + _ => { + self.close_dialog(); } - _ => {} } - self.close_dialog(); } TuiMsg::KeybindChanged { action: _, @@ -410,13 +396,11 @@ impl App { if let Some(theme) = self.theme_registry.get_tui(&theme_name) { self.ui_state.theme = Arc::new(theme); self.persist_theme_selection(&theme_name); - self.messages_state - .toasts - .info(&format!("Theme: {}", theme_name)); } else { - self.messages_state - .toasts - .error(&format!("Unknown theme: {}", theme_name)); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!("Unknown theme: {}", theme_name)], + ); } self.dialog_state.theme_picker = None; self.close_dialog(); @@ -433,13 +417,11 @@ impl App { if let Some(theme) = self.theme_registry.get_tui(&theme_id) { self.ui_state.theme = Arc::new(theme); self.persist_theme_selection(&theme_id); - self.messages_state - .toasts - .info(&format!("Theme: {}", theme_id)); } else { - self.messages_state - .toasts - .error(&format!("Unknown theme: {}", theme_id)); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!("Unknown theme: {}", theme_id)], + ); } self.dialog_state.theme_picker = None; self.close_dialog(); @@ -485,9 +467,11 @@ impl App { .map(str::to_string) .or_else(|| self.active_project_key()) else { - self.messages_state - .toasts - .warning("No project is active — pick one before launching a session"); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["No project is active — pick one before launching a session" + .to_string()], + ); return; }; let intent = if parent_session_id.is_some() { @@ -520,8 +504,9 @@ impl App { } } TuiMsg::LaunchNeedsCheckout => { - self.messages_state.toasts.info( - "This session runs in the project's own root — it has no managed checkout to reuse", + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["This session runs in the project's own root — it has no managed checkout to reuse".to_string()], ); } TuiMsg::SubmitImportPreview => { @@ -690,35 +675,27 @@ impl App { crate::commands::queue::start_queue_edit(self, entry_id, text, run_at_ms); } // M007: refused in the box, so the user is still sitting in the - // duration step with their input intact. The message names the - // grammar rather than the offending entry, and quotes what they - // typed — which is a duration token, never prompt text. + // duration step with their input intact. Keep the usage result in + // the retained history rather than making it a transient alert. TuiMsg::QueueScheduleRejected { input } => { - self.messages_state.toasts.error(&format!( - "\"{input}\" is not a delay this queue understands. \ - Use a number with a unit: 30s, 5min, 2h, or 1d." - )); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!( + "\"{input}\" is not a delay this queue understands. \ + Use a number with a unit: 30s, 5min, 2h, or 1d." + )], + ); } TuiMsg::QueueReorderSelected { entry_ids } => { crate::commands::queue::start_queue_reorder(self, entry_ids); } - // A refusal the box could not express as a mutation. Surfaced here - // rather than inside the widget because a widget cannot show a - // toast, and a keypress that does nothing is the one outcome this - // milestone must never produce. + // A refusal changes nothing on screen, so the sentence is the + // whole outcome: the box cannot move the row, and the operator + // pressed the key. It stays in the retained history. TuiMsg::QueueReorderUnavailable { reason } => { - let message = match reason { - crate::components::dialogs::queue::QueueReorderRefusal::Delivering => { - "That prompt is being delivered right now — move it once its turn finishes." - } - crate::components::dialogs::queue::QueueReorderRefusal::AlreadyEarliest => { - "That prompt is already first in the queue." - } - crate::components::dialogs::queue::QueueReorderRefusal::AlreadyLatest => { - "That prompt is already last in the queue." - } - }; - self.messages_state.toasts.info(message); + self.messages_state + .toasts + .warning(crate::commands::queue::reorder_refusal_message(reason)); } // M006. The one refusal this layer makes for itself is "nothing is // running": `active_turn_id` is a snapshot of the session's turn @@ -727,18 +704,23 @@ impl App { // direction — it sends a request the daemon can refuse truthfully — // so the check is a fast path, never an authority. TuiMsg::QueueSendNowSelected { entry_id } => { - if self.session_state.active_turn_id.is_none() { - let message = crate::commands::queue::send_now_refusal_message( - crate::components::dialogs::queue::QueueSendRefusal::NoActiveTurn, - ); - self.messages_state.toasts.info(message); - } else { + if self.session_state.active_turn_id.is_some() { crate::commands::queue::start_queue_send_now(self, entry_id); + } else { + // Nothing is running, so the prompt stays where it is. + // That is a fact about the session, not about the row: + // nothing else on screen says it, so say it here. + self.messages_state.toasts.warning( + crate::commands::queue::send_now_refusal_message( + crate::components::dialogs::queue::QueueSendRefusal::NoActiveTurn, + ), + ); } } TuiMsg::QueueSendNowUnavailable { reason } => { - let message = crate::commands::queue::send_now_refusal_message(reason); - self.messages_state.toasts.info(message); + self.messages_state + .toasts + .warning(crate::commands::queue::send_now_refusal_message(reason)); } TuiMsg::SubmitQuestionAnswers { answers_json } => { if let Some(session_id) = self.dialog_state.question_session_id.take() { @@ -774,9 +756,7 @@ impl App { } TuiMsg::CopyShareUrl => { if let Some(ref mut share) = self.dialog_state.share_dialog { - if share.copy_url() { - self.messages_state.toasts.info("URL copied to clipboard!"); - } else { + if !share.copy_url() { self.messages_state.toasts.error("Failed to copy URL"); } } @@ -1271,21 +1251,15 @@ impl App { }); } TuiMsg::SecurityReviewJump { path, line } => { - // Read-only: copy the file path to the clipboard and - // surface a toast. The file is never opened or mutated. + // Read-only: copy the file path to the clipboard. The file is never opened or mutated. let mut text = path.clone(); if let Some(l) = line { text.push_str(&format!(":{l}")); } - match codegg::util::clipboard::copy_to_clipboard(&text) { - Ok(()) => self - .messages_state - .toasts - .info(&format!("Copied {text} to clipboard (file not opened)")), - Err(_) => self - .messages_state + if codegg::util::clipboard::copy_to_clipboard(&text).is_err() { + self.messages_state .toasts - .info(&format!("Jump: {text} (clipboard unavailable)")), + .error(&format!("Jump: {text} (clipboard unavailable)")); } } TuiMsg::ShellInclude { id, mode } => { @@ -1317,32 +1291,129 @@ impl App { crate::commands::run_rerun::start_run_rerun(self, run_id); } TuiMsg::RunPromote { run_id } => { - self.messages_state - .toasts - .info(&format!("Run {} promoted to context", run_id)); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!("Run {} promoted to context", run_id)], + ); } TuiMsg::RunCopyId { run_id } => { #[cfg(feature = "arboard")] { if let Ok(mut clipboard) = arboard::Clipboard::new() { - let _ = clipboard.set_text(run_id.clone()); - self.messages_state - .toasts - .info("Run ID copied to clipboard"); + if clipboard.set_text(run_id.clone()).is_err() { + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!("Run ID: {}", run_id)], + ); + } } else { - self.messages_state - .toasts - .info(&format!("Run ID: {}", run_id)); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!("Run ID: {}", run_id)], + ); } } #[cfg(not(feature = "arboard"))] { - self.messages_state - .toasts - .info(&format!("Run ID: {}", run_id)); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!("Run ID: {}", run_id)], + ); } } _ => {} } } } + +#[cfg(test)] +mod agent_axis_tests { + use super::*; + use std::sync::Arc; + + use codegg::agent::asset_context::{AssetContextBuilder, ProjectId}; + use codegg::agent::registry::AgentRegistry; + use codegg::config::schema::Config; + + #[test] + fn project_selectable_agent_is_available_in_cycle_and_picker() { + let tmp = tempfile::tempdir().unwrap(); + let agents_dir = tmp.path().join(".codegg/agents"); + std::fs::create_dir_all(&agents_dir).unwrap(); + std::fs::write( + agents_dir.join("project-selectable.toml"), + r#"name = "project-selectable" +selectable = true +subagent = false +default = false +"#, + ) + .unwrap(); + std::fs::write( + agents_dir.join("project-spawn-only.toml"), + r#"name = "project-spawn-only" +mode = "subagent" +selectable = false +subagent = true +default = false +"#, + ) + .unwrap(); + let context = AssetContextBuilder::new() + .with_synthetic_project_id(ProjectId::new()) + .with_workspace_root(tmp.path()) + .build() + .unwrap(); + let agents = AgentRegistry::load_for_context(&Config::default(), &context) + .unwrap() + .into_agents(); + + let selectable_index = agents + .iter() + .position(|agent| agent.name == "project-selectable") + .expect("project selectable agent is loaded"); + let spawn_only_index = agents + .iter() + .position(|agent| agent.name == "project-spawn-only") + .expect("project spawn-only agent is loaded"); + assert!(agents[selectable_index].resolved_axes().0); + assert!(agents[spawn_only_index].resolved_axes().1); + + let mut picker = crate::components::dialogs::agent::AgentDialog::new(Arc::new( + crate::theme::Theme::default(), + )); + picker.set_agents(agents.iter().collect()); + assert!(picker + .agents + .iter() + .any(|agent| agent.name == "project-selectable")); + assert!(!picker + .agents + .iter() + .any(|agent| agent.name == "project-spawn-only")); + + let selectable_indices: Vec = agents + .iter() + .enumerate() + .filter(|(_, agent)| agent.resolved_axes().0) + .map(|(index, _)| index) + .collect(); + let position = selectable_indices + .iter() + .position(|index| *index == selectable_index) + .expect("project selectable agent participates in the cycle"); + let previous = selectable_indices + [(position + selectable_indices.len() - 1) % selectable_indices.len()]; + assert!(!selectable_indices.contains(&spawn_only_index)); + + let mut app = App::new_for_testing(tmp.path().to_string_lossy().into_owned()); + app.set_agents(agents); + app.agent_state.current_agent = previous; + app.process_msg(TuiMsg::CycleAgent); + assert_eq!(app.agent_state.current_agent, selectable_index); + assert_eq!( + app.agent_state.agents[app.agent_state.current_agent].name, + "project-selectable" + ); + } +} diff --git a/crates/codegg-tui/src/app/mod.rs b/crates/codegg-tui/src/app/mod.rs index b727dbda7..f712abaf7 100644 --- a/crates/codegg-tui/src/app/mod.rs +++ b/crates/codegg-tui/src/app/mod.rs @@ -16,6 +16,7 @@ mod commands; mod compact_command_tests; mod input; mod modal; +pub(crate) use modal::LogsView; #[path = "plugin_ui.rs"] mod plugin_effects; pub mod present_card; @@ -360,6 +361,10 @@ pub struct App { /// M002: the panel the walk is filling asynchronously. A box that arrives /// for it is docked into the column instead of mounting over it. pub(crate) dock_on_open: Option, + /// A one-shot body view for the next Logs open, set by `/toast` and taken + /// (and cleared) by `open_logs_window`, so a filtered view never leaks + /// into a later panel selection. + pub(crate) pending_logs_view: Option, pub status_bar: StatusBarWidget, /// M007 frontend-local cache of the daemon-resolved runtime policy /// (approval mode / sandbox profile / enforcement / reviewer @@ -859,7 +864,9 @@ impl App { pub fn with_config(project_dir: String, cfg: Option<&codegg::config::schema::Config>) -> Self { let focus_manager = crate::components::component::FocusManager::new(); let agents = builtin_agents(); - let current_agent = agents.iter().position(|a| a.name == "build").unwrap_or(0); + let current_agent = codegg::agent::file_agents::find_default_agent(&agents) + .and_then(|default| agents.iter().position(|agent| agent.name == default.name)) + .unwrap_or(0); // No shipped model defaults. The model list starts empty and is // populated only by real discovery (or by models the operator // declares in config). Seeding it with a compiled-in catalog @@ -1210,6 +1217,7 @@ impl App { &saved_panel_layout, ), dock_on_open: None, + pending_logs_view: None, status_bar: StatusBarWidget::new(Arc::clone(&theme)), policy_ui: crate::commands::policy::PolicyUiState::default(), session_store: None, @@ -1556,7 +1564,9 @@ impl App { pub fn new_for_testing(project_dir: String) -> Self { let focus_manager = crate::components::component::FocusManager::new(); let agents = builtin_agents(); - let current_agent = agents.iter().position(|a| a.name == "build").unwrap_or(0); + let current_agent = codegg::agent::file_agents::find_default_agent(&agents) + .and_then(|default| agents.iter().position(|agent| agent.name == default.name)) + .unwrap_or(0); // Tests start with no models; they opt in explicitly via // `set_models`. See `with_config` for why nothing is seeded. let models: Vec = Vec::new(); @@ -1785,6 +1795,7 @@ impl App { sidebar: SidebarWidget::new(Arc::clone(&theme)), panel_host: crate::panels::SidePanelHost::new(), dock_on_open: None, + pending_logs_view: None, status_bar: StatusBarWidget::new(Arc::clone(&theme)), policy_ui: crate::commands::policy::PolicyUiState::default(), session_store: None, @@ -1943,23 +1954,15 @@ impl App { /// Latch a turn failure so the main buffer can keep saying what went wrong. /// - /// Every turn-failure site used to call `toasts.error` alone. That made the - /// whole record of a dead turn a message that expires in seconds, which is - /// the wrong lifetime for the one thing a user needs while deciding whether - /// to retry: the reason it stopped. - /// - /// The toast stays — it is the notification, and `/logs` retains it — but the - /// latch is what outlives it. Deliberately *not* cleared on a timer: the - /// user reading the reason must not have it vanish, and the user who has - /// resumed has already cleared it via the next `TurnStarted`. + /// Every turn-failure site used to call `toasts.error` alone. The persistent + /// `last_error` row now retains the reason until the next `TurnStarted`, so a + /// transient toast would only repeat the text already on screen. /// /// Only genuine turn failures route here. Shell staging, clipboard, and - /// `/theme` errors are transient command feedback and stay toast-only, or - /// the strip would report a turn failure that never happened. + /// `/theme` errors are transient command feedback; they do not belong in the + /// turn-failure row. pub fn report_turn_error(&mut self, message: impl Into) { - let message = message.into(); - self.session_state.last_error = Some(message.clone()); - self.messages_state.toasts.error(&message); + self.session_state.last_error = Some(message.into()); } /// Release a turn that never started, with a reason the user can act on. @@ -2991,14 +2994,12 @@ impl App { pub fn cancel_security_review(&mut self) -> bool { if let Some(state) = self.security_review_running.take() { self.task_registry.cancel(state.task_id); - self.messages_state - .toasts - .info("Security review cancelled."); true } else { - self.messages_state - .toasts - .warning("No security review is running."); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["No security review is running.".to_string()], + ); false } } @@ -5003,9 +5004,6 @@ impl App { if let Some(picker) = &self.dialog_state.theme_picker { if let Some(theme) = picker.selected_theme() { self.ui_state.theme = Arc::new(theme.clone()); - self.messages_state - .toasts - .info(&format!("Theme: {}", theme.name)); } } self.dialog_state.theme_picker = None; @@ -5022,59 +5020,19 @@ impl App { if mcp.action_mode { if let Some(action) = mcp.selected_action_name() { match action { - "Configure OAuth" => { - if let Some(server) = mcp.selected_server() { - self.messages_state.toasts.info(&format!( - "OAuth for {} - configure in .codegg/mcp.json", - server.name - )); - } - } "Browse Resources" => { mcp.browse_mode = BrowseMode::Resources { selected: 0 }; mcp.action_mode = false; } - "Disconnect" => { - if let Some(server) = mcp.selected_server() { - self.messages_state - .toasts - .info(&format!("Disconnecting {}...", server.name)); - } - } - "Reconnect" => { - if let Some(server) = mcp.selected_server() { - self.messages_state - .toasts - .info(&format!("Reconnecting {}...", server.name)); - } - } - "Connect" => { - if let Some(server) = mcp.selected_server() { - self.messages_state - .toasts - .info(&format!("Connecting {}...", server.name)); - } - } - "Remove" => { - if let Some(server) = mcp.selected_server() { - self.messages_state - .toasts - .info(&format!("Removing {}...", server.name)); - } - } - "Wait" => { - self.messages_state - .toasts - .info("Server is connecting, please wait..."); - } - "Configure" => { - if let Some(server) = mcp.selected_server() { - self.messages_state.toasts.info(&format!( - "Configure {} - edit .codegg/mcp.json", - server.name - )); - } - } + // The rest describe where a server's lifecycle is + // configured (".codegg/mcp.json"); not one of them was + // ever wired to an effect. Each used to acknowledge + // itself with a toast — several claiming work that never + // happened ("Disconnecting foo...") — so the + // acknowledgements are gone. That the dialog still offers + // them is a pre-existing defect in this surface, recorded + // as F3 in + // plans/closure/tui-notification-surface/002-004-status.md. _ => {} } } @@ -5085,11 +5043,7 @@ impl App { } Dialog::Share => { if let Some(ref mut share) = self.dialog_state.share_dialog { - if share.copy_url() { - self.messages_state.toasts.info("URL copied to clipboard!"); - } else { - self.messages_state.toasts.error("Failed to copy URL"); - } + let _ = share.copy_url(); } } Dialog::Import => { @@ -5622,9 +5576,6 @@ impl App { } crate::command::CommandAction::Process => { if self.prompt_state.pending_send { - self.messages_state - .toasts - .warning("Still waiting for previous prompt to finish"); return; } let args = raw_input @@ -5662,9 +5613,6 @@ impl App { } crate::command::CommandAction::Template => { if self.prompt_state.pending_send { - self.messages_state - .toasts - .warning("Still waiting for previous prompt to finish"); return; } let template = cmd @@ -5685,10 +5633,13 @@ impl App { } crate::command::CommandAction::Plugin => { crate::commands::close_command_mode(self); - self.messages_state.toasts.info(&format!( - "{} is a plugin command; use the plugin panel to run it", - cmd.name - )); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!( + "{} is a plugin command; use the plugin panel to run it", + cmd.name + )], + ); } crate::command::CommandAction::Builtin(builtin) => { // The single extraction point: the typed line is resolved to @@ -5773,9 +5724,10 @@ impl App { A::ShowDoctor => crate::commands::diagnostics::dispatch_doctor(self), A::ShowPluginInfo => { if argument.is_empty() { - self.messages_state - .toasts - .warning("Usage: /plugin info "); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /plugin info ".to_string()], + ); } else { crate::commands::plugin_management::show_plugin_info(self, argument); } @@ -5841,9 +5793,7 @@ impl App { ("proposals", true) => promotion::dispatch_skill_proposals(self), _ => { self.ui_state.command_mode = false; - self.messages_state.toasts.warning( - "Usage: /skill [name]|promote |proposal |proposals", - ); + self.show_short_or_info(crate::components::dialogs::info::InfoType::Usage, vec!["Usage: /skill [name]|promote |proposal |proposals".to_string()]); } } } @@ -5866,6 +5816,7 @@ impl App { B::Connect => provider_connections::dispatch_connect(self), B::Connections => provider_connections::dispatch_connections(self), B::Status => session_report::dispatch_status(self), + B::Advisor => diagnostics::dispatch_advisor_status(self, argument), B::Policy => policy::dispatch_policy(self), B::Approval => policy::dispatch_approval(self, argument), B::Sandbox => policy::dispatch_sandbox(self, argument), @@ -5894,8 +5845,12 @@ impl App { "send" => chat::dispatch_chat_send(self, rest), _ => { self.ui_state.command_mode = false; - self.messages_state.toasts.warning( - "Usage: /chat [actions [message-id]|history|read|send |sync]", + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![ + "Usage: /chat [actions [message-id]|history|read|send |sync]" + .to_string(), + ], ); } } @@ -5939,9 +5894,7 @@ impl App { ("search", _) => memory::dispatch_memory_search(self, rest), _ => { self.ui_state.command_mode = false; - self.messages_state - .toasts - .warning("Usage: /memory [list [namespace]|forget |consolidate|remember |search ]"); + self.show_short_or_info(crate::components::dialogs::info::InfoType::Usage, vec!["Usage: /memory [list [namespace]|forget |consolidate|remember |search ]".to_string()]); } } } @@ -5952,9 +5905,10 @@ impl App { ("dismiss", _) => memory::dispatch_habit_dismiss(self, rest), _ => { self.ui_state.command_mode = false; - self.messages_state - .toasts - .warning("Usage: /habit [ready]|dismiss "); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /habit [ready]|dismiss ".to_string()], + ); } } } @@ -5973,6 +5927,10 @@ impl App { argument, ), B::Logs => diagnostics::dispatch_logs(self), + B::Toast => { + self.pending_logs_view = Some(LogsView::Notifications); + crate::commands::panels::select_panel(self, crate::panels::SidePanelId::Logs); + } B::ToolContracts => diagnostics::dispatch_tool_contracts(self), B::Lsp => lsp::dispatch_lsp(self, argument), B::Nodes => diagnostics::dispatch_nodes(self), @@ -6005,9 +5963,7 @@ impl App { ), _ => { self.ui_state.command_mode = false; - self.messages_state.toasts.warning( - "Usage: /research |runs|open |show
", - ); + self.show_short_or_info(crate::components::dialogs::info::InfoType::Usage, vec!["Usage: /research |runs|open |show
".to_string()]); } } } @@ -6022,7 +5978,7 @@ impl App { "rerun" => shell::dispatch_shell_rerun(self, rest), _ => { self.ui_state.command_mode = false; - self.messages_state.toasts.warning("Usage: /shell list|show |expand stdout|stderr [start..end]|kill |rerun "); + self.show_short_or_info(crate::components::dialogs::info::InfoType::Usage, vec!["Usage: /shell list|show |expand stdout|stderr [start..end]|kill |rerun ".to_string()]); } } } @@ -6041,7 +5997,7 @@ impl App { "send" => interactive_terminal::dispatch_terminal_send(self, rest), _ => { self.ui_state.command_mode = false; - self.messages_state.toasts.warning("Usage: /terminal [handle]|attach |resume [handle]|show |focus [handle]|list|send "); + self.show_short_or_info(crate::components::dialogs::info::InfoType::Usage, vec!["Usage: /terminal [handle]|attach |resume [handle]|show |focus [handle]|list|send ".to_string()]); } } } @@ -6063,9 +6019,7 @@ impl App { "install" => plugin_management::dispatch_plugin_install(self, rest), _ => { self.ui_state.command_mode = false; - self.messages_state.toasts.warning( - "Usage: /plugin|info [name]|doctor [name]|enable |disable |remove |install ", - ); + self.show_short_or_info(crate::components::dialogs::info::InfoType::Usage, vec!["Usage: /plugin|info [name]|doctor [name]|enable |disable |remove |install ".to_string()]); } } } @@ -6266,19 +6220,9 @@ impl App { self.clear_selection(); return; } - match codegg::util::clipboard::copy_to_clipboard(&trimmed) { - Ok(()) => { - let lines = trimmed.lines().count(); - let message = format!( - "Copied selection to clipboard ({lines} line{})", - if lines == 1 { "" } else { "s" } - ); - self.messages_state.toasts.info(&message); - } - Err(err) => { - let message = format!("Clipboard unavailable: {err}"); - self.messages_state.toasts.error(&message); - } + if let Err(err) = codegg::util::clipboard::copy_to_clipboard(&trimmed) { + let message = format!("Clipboard unavailable: {err}"); + self.messages_state.toasts.error(&message); } self.clear_selection(); } @@ -6655,7 +6599,7 @@ impl App { .agents .iter() .enumerate() - .filter(|(_, a)| !a.hidden) + .filter(|(_, a)| a.resolved_axes().0) .map(|(i, _)| i) .collect(); if let Some(&real_idx) = visible.get(idx) { @@ -6725,7 +6669,7 @@ impl App { .agents .iter() .enumerate() - .filter(|(_, a)| !a.hidden) + .filter(|(_, a)| a.resolved_axes().0) .map(|(i, _)| i) .collect(); if idx < visible.len() { @@ -7071,17 +7015,17 @@ impl App { .agents .iter() .enumerate() - .filter(|(_, a)| !a.hidden) + .filter(|(_, agent)| agent.resolved_axes().0) .map(|(i, _)| i) .collect(); if visible.is_empty() { return; } - let cur_pos = visible + let next_pos = visible .iter() .position(|&i| i == self.agent_state.current_agent) + .map(|current| (current + 1) % visible.len()) .unwrap_or(0); - let next_pos = (cur_pos + 1) % visible.len(); self.agent_state.current_agent = visible[next_pos]; } @@ -7980,9 +7924,10 @@ impl App { self.ui_state.routes.navigate_to(Route::Home); // A fresh session is a draft now: say what the next key does, since // no row and no system message appear until the first prompt. - self.messages_state - .toasts - .info("New session — the first prompt creates it"); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["New session — the first prompt creates it".to_string()], + ); } /// Enter the pre-session draft state: the tab has a project and a @@ -8053,7 +7998,10 @@ impl App { "list" => { let names = self.theme_registry.names(); if names.is_empty() { - self.messages_state.toasts.warning("No themes available"); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["No themes available".to_string()], + ); } else { let preview = names .iter() @@ -8066,23 +8014,27 @@ impl App { } else { String::new() }; - self.messages_state - .toasts - .info(&format!("Themes: {}{}", preview, extra)); + self.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec![format!("Themes: {}{}", preview, extra)], + ); } } "use" => { if let Some(name) = parts.next() { if self.apply_theme(name) { self.persist_theme_selection(name); - self.messages_state.toasts.info(&format!("Theme: {}", name)); } else { - self.messages_state - .toasts - .error(&format!("Unknown theme: {}", name)); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!("Unknown theme: {}", name)], + ); } } else { - self.messages_state.toasts.error("Usage: /theme use "); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /theme use ".to_string()], + ); } } "reload" => { @@ -8100,12 +8052,15 @@ impl App { // default theme id (Cyber Red). self.apply_theme(codegg::theme::registry::DEFAULT_THEME_ID); } - self.messages_state.toasts.info("Theme registry reloaded"); } "diagnostics" => { let diags = self.theme_registry.diagnostics(); + let mut diagnostics = Vec::new(); if diags.is_empty() { - self.messages_state.toasts.info("No theme diagnostics"); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["No theme diagnostics".to_string()], + ); } else { for d in diags { let level = match d.level { @@ -8113,25 +8068,29 @@ impl App { codegg::theme::validate::ThemeDiagnosticLevel::Error => "error", }; let field = d.field.as_deref().unwrap_or("-"); - self.messages_state.toasts.info(&format!( + diagnostics.push(format!( "[{}] {} / {}: {}", level, d.theme_id, field, d.message )); } + self.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + diagnostics, + ); } } other => { // If the argument looks like a theme name, apply it directly. if self.apply_theme(other) { self.persist_theme_selection(other); - self.messages_state - .toasts - .info(&format!("Theme: {}", other)); } else { - self.messages_state.toasts.error(&format!( - "Unknown theme subcommand or name: {} (try /theme list, use, reload, diagnostics)", - other - )); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!( + "Unknown theme subcommand or name: {} (try /theme list, use, reload, diagnostics)", + other + )], + ); } } } @@ -8158,20 +8117,15 @@ impl App { /// open the whole transcript at once. Model prose is not a disclosure and /// is not touched: it is never collapsed, so there is nothing to expand. /// - /// The outcome is reported in the same toast surface the `/thinking` - /// command uses, because the gesture changes what the buffer shows and - /// the user needs to know which way it went. + /// The buffer is the feedback: every part's disclosure state is visible in + /// the column, so the gesture does not announce itself. It used to report + /// "all details expanded"/"collapsed", which repeated what the operator had + /// just done and could see. pub(crate) fn expand_all_disclosures(&mut self) { let expand = self.messages_state.messages.any_disclosure_collapsed(); self.messages_state .messages .set_all_disclosures_expanded(expand); - let msg = if expand { - "all details expanded" - } else { - "all details collapsed" - }; - self.messages_state.toasts.info(msg); } pub(crate) fn toggle_tts(&mut self) { @@ -8183,19 +8137,12 @@ impl App { let text = msg.text_content(); if !text.is_empty() { self.send_notification_speak_to_daemon(text); - self.messages_state.toasts.info("TTS speak sent to daemon"); return; } } } - self.messages_state - .toasts - .info("TTS enabled (daemon: nothing selected to speak)"); } else { self.send_notification_stop_to_daemon(); - self.messages_state - .toasts - .info("TTS disabled (daemon: stop sent)"); } return; } @@ -8218,7 +8165,6 @@ impl App { } } } - self.messages_state.toasts.info("TTS enabled"); } else { let tts = self.ui_state.tts.clone(); self.task_registry @@ -8227,7 +8173,6 @@ impl App { tracing::debug!("TTS stop error: {}", e); } }); - self.messages_state.toasts.info("TTS disabled"); } } @@ -8243,7 +8188,6 @@ impl App { tracing::debug!("TTS stop error: {}", e); } }); - self.messages_state.toasts.info("TTS stopped"); } /// Send a TTS speak request to the daemon's `NotificationRouter` via @@ -8254,7 +8198,7 @@ impl App { let Some(client) = self.core_client.clone() else { self.messages_state .toasts - .info("TTS: no core client; cannot route to daemon"); + .error("TTS: no core client; cannot route to daemon"); return; }; let session_id = self.session_state.session.as_ref().map(|s| s.id.clone()); @@ -8279,7 +8223,7 @@ impl App { let Some(client) = self.core_client.clone() else { self.messages_state .toasts - .info("TTS: no core client; cannot stop daemon TTS"); + .error("TTS: no core client; cannot stop daemon TTS"); return; }; let request = codegg::core::new_request( @@ -8291,7 +8235,6 @@ impl App { tracing::debug!("core facade notification_stop failed: {}", e); } }); - self.messages_state.toasts.info("TTS stop sent to daemon"); } pub(crate) fn toggle_fullscreen(&mut self) { @@ -8299,10 +8242,8 @@ impl App { use std::io::Write; if self.ui_state.fullscreen { let _ = std::io::stdout().write_all(b"\x1b[?1049h"); - self.messages_state.toasts.info("Fullscreen mode enabled"); } else { let _ = std::io::stdout().write_all(b"\x1b[?1049l"); - self.messages_state.toasts.info("Fullscreen mode disabled"); } } @@ -8312,16 +8253,13 @@ impl App { if let Err(e) = std::process::Command::new(&editor).arg(file).spawn() { self.messages_state .toasts - .info(&format!("Failed to open editor: {}", e)); - } else { - self.messages_state - .toasts - .info(&format!("Opening {} in {}", file, editor)); + .error(&format!("Failed to open editor: {}", e)); } } else { - self.messages_state - .toasts - .info("No recently edited file to open"); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["No recently edited file to open".to_string()], + ); } } @@ -8329,21 +8267,16 @@ impl App { match subcmd { "" | "last" => { let state = &self.session_state_derived; - match &state.test_state { + let mut lines = Vec::new(); + lines.push(match &state.test_state { codegg::session::state::TestState::Unknown => { - self.messages_state - .toasts - .info("Test state: unknown (no tests run yet)"); + "Test state: unknown (no tests run yet)".to_string() } codegg::session::state::TestState::Stale => { - self.messages_state - .toasts - .info("Test state: stale (files changed since last run)"); + "Test state: stale (files changed since last run)".to_string() } codegg::session::state::TestState::Running { command } => { - self.messages_state - .toasts - .info(&format!("Test state: running ({})", command)); + format!("Test state: running ({})", command) } codegg::session::state::TestState::Passed { command, @@ -8352,10 +8285,7 @@ impl App { let duration_str = duration_ms .map(|ms| format!(" ({:.1}s)", ms as f64 / 1000.0)) .unwrap_or_default(); - self.messages_state.toasts.info(&format!( - "Test state: passed{} | command: {}", - duration_str, command - )); + format!("Test state: passed{} | command: {}", duration_str, command) } codegg::session::state::TestState::Failed { command, @@ -8365,36 +8295,36 @@ impl App { let duration_str = duration_ms .map(|ms| format!(" ({:.1}s)", ms as f64 / 1000.0)) .unwrap_or_default(); - self.messages_state.toasts.info(&format!( + format!( "Test state: failed{} | command: {} | {}", duration_str, command, summary - )); + ) } - } + }); let file_count = state.changed_files.len(); if file_count > 0 { - self.messages_state - .toasts - .info(&format!("Changed files since last run: {}", file_count)); + lines.push(format!("Changed files since last run: {}", file_count)); } + self.show_short_or_info(crate::components::dialogs::info::InfoType::Stats, lines); } "failed" => { let state = &self.session_state_derived; - match &state.test_state { + let line = match &state.test_state { codegg::session::state::TestState::Failed { summary, .. } => { - self.messages_state - .toasts - .info(&format!("Failed tests: {}", summary)); + format!("Failed tests: {}", summary) } - _ => { - self.messages_state.toasts.info("No failed tests"); - } - } + _ => "No failed tests".to_string(), + }; + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Stats, + vec![line], + ); } _ => { - self.messages_state - .toasts - .warning("Usage: /tests [last|failed]"); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /tests [last|failed]".to_string()], + ); } } } @@ -8407,9 +8337,6 @@ impl App { pub(crate) fn handle_research_command(&mut self, args: &str) { if self.prompt_state.pending_send { - self.messages_state - .toasts - .warning("Still waiting for previous prompt to finish"); return; } @@ -8437,9 +8364,10 @@ impl App { let question = question_parts.join(" "); if question.is_empty() { - self.messages_state - .toasts - .warning("Usage: /research [--mode ] [--depth ]"); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /research [--mode ] [--depth ]".to_string()], + ); return; } @@ -8464,9 +8392,6 @@ impl App { // `ResearchService` alone would pass even if this handler stopped // passing the runtime along. let service = self.research_service(project_dir); - self.messages_state - .toasts - .info(&format!("Starting research: {}", question)); self.task_registry .spawn(TuiTaskKind::Research, "research-answer", async move { @@ -8562,34 +8487,20 @@ impl App { /// the copy, because the focused component is a clone of the dialog and a /// clone cannot reach the composer. /// - /// The outcome is always reported. A silent no-op would teach the user - /// that the key is dead, which is the failure the claim table exists to - /// prevent. - /// - /// The report names the **size** of the selection rather than its text. - /// Toasts are retained for `/logs`, and a preview of the composer's - /// contents in a retained log is a copy of the user's text in a place - /// they did not ask for it to be. + /// Successful copy and an empty selection are silent: the selection is + /// already visible, and a toast would echo a direct user action. Clipboard + /// failures remain explicit without copying the selected text into logs. /// /// The selection survives the copy: it is a read, and a user who copies /// and then deletes wants the same range both times. fn copy_composer_selection(&mut self) { let Some(text) = self.prompt_state.prompt.selected_text() else { - self.messages_state - .toasts - .info("Nothing to copy — the composer has no selection"); return; }; - let characters = text.chars().count(); - match codegg::util::clipboard::copy_to_clipboard(&text) { - Ok(()) => self - .messages_state - .toasts - .success(&format!("Copied {characters} characters")), - Err(error) => self - .messages_state + if let Err(error) = codegg::util::clipboard::copy_to_clipboard(&text) { + self.messages_state .toasts - .error(&format!("Could not copy: {error}")), + .error(&format!("Could not copy: {error}")); } } @@ -8691,38 +8602,6 @@ impl App { ); } - /// Provider name for a connection being rotated, derived the same way - /// [`Self::open_connection_rotation_dialog`] derives it: the target's - /// `provider_kind` with the `other:` storage prefix stripped, falling back - /// to the connection's `display_name`, then to a generic word when the - /// connection list has not loaded. - /// - /// The rotation toast used to say "Eggpool" unconditionally, so rotating - /// an `other:opencode_go` credential announced the wrong provider in the - /// one message the user sees while the probe runs. - fn rotation_provider_label(&self, connection_id: &str) -> String { - self.dialog_state - .connection_selection_dialog - .as_ref() - .and_then(|dialog| { - dialog - .connections - .iter() - .find(|connection| connection.id == connection_id) - }) - .map(|connection| { - let kind = connection.provider_kind.as_str(); - let stripped = kind.strip_prefix("other:").unwrap_or(kind).trim(); - if stripped.is_empty() { - connection.display_name.clone() - } else { - stripped.to_string() - } - }) - .filter(|label| !label.is_empty()) - .unwrap_or_else(|| "provider".to_string()) - } - fn open_connection_rotation_dialog(&mut self, connection_id: String, expected_revision: u64) { use crate::components::dialogs::connect::ProviderInfo; @@ -8859,7 +8738,6 @@ impl App { self.dialog_state.import_dialog = None; self.close_dialog(); crate::commands::sessions::start_activate_session(self, session.id); - self.messages_state.toasts.info("Session imported"); } } super::components::dialogs::import::ImportState::Error => { @@ -8937,7 +8815,6 @@ impl App { } // Rotation keeps the existing masked-credential editor path. if let Some((connection_id, expected_revision)) = rotation_target.clone() { - let rotation_label = self.rotation_provider_label(&connection_id); let Ok(api_key) = SecretInput::new(api_key_text.clone()) else { let message = "Credential is invalid".to_string(); if let Some(dialog) = self.dialog_state.connect_dialog.as_mut() { @@ -9028,9 +8905,6 @@ impl App { }) }, ); - self.messages_state.toasts.info(&format!( - "Rotating {rotation_label} credential (probe in progress)…" - )); return; } @@ -9211,12 +9085,6 @@ impl App { }) }, ); - // `provider_display` moved into the task above; toast from the entry - // name cloned earlier. - self.messages_state.toasts.info(&format!( - "Connecting to {} (probe in progress)…", - entry.name - )); } fn on_char(&mut self, c: char) { @@ -10317,26 +10185,29 @@ impl App { debug_log!("composer claim: open line below"); } ComposerVerb::Undo => { - // The verb reports in **both** branches. A silent - // no-op would teach the user that the key is dead, - // and "nothing to undo" is a different fact from - // "nothing happened". - if self.prompt_state.prompt.undo() { - self.messages_state.toasts.info("Undid the last edit"); - debug_log!("composer claim: undo"); + // The verb reports in both branches. A silent no-op + // would teach the operator that `u` is dead, and + // "there was nothing to undo" is a different fact from + // "nothing happened" — so the two branches say + // different things and neither can be mistaken for the + // other. The wording names the composer because the + // transcript has its own undo with its own message. + let undone = self.prompt_state.prompt.undo(); + self.messages_state.toasts.info(if undone { + "Undid the composer's last edit" } else { - self.messages_state.toasts.warning("Nothing to undo"); - debug_log!("composer claim: undo with nothing to undo"); - } + "Nothing to undo in the composer" + }); + debug_log!("composer claim: undo"); } ComposerVerb::Redo => { - if self.prompt_state.prompt.redo() { - self.messages_state.toasts.info("Redid the last edit"); - debug_log!("composer claim: redo"); + let redone = self.prompt_state.prompt.redo(); + self.messages_state.toasts.info(if redone { + "Redid the composer's last edit" } else { - self.messages_state.toasts.warning("Nothing to redo"); - debug_log!("composer claim: redo with nothing to redo"); - } + "Nothing to redo in the composer" + }); + debug_log!("composer claim: redo"); } ComposerVerb::WordForward => { self.prompt_state.prompt.cursor_word_forward(); @@ -10382,28 +10253,13 @@ impl App { debug_log!("composer claim: delete selection"); } ComposerVerb::Paste => { - // The clipboard is best-effort, and the verb always - // reports what it did. A silent no-op would teach the - // user that the key is dead, and the report is also - // the only evidence of *what* was pasted — the - // pasted text is not echoed back, because the - // composer can hold a secret. - match codegg::util::clipboard::read_from_clipboard() { - Some(text) if !text.is_empty() => { - let characters = text.chars().count(); + // The composer itself shows pasted text; do not toast a direct-action result. + if let Some(text) = codegg::util::clipboard::read_from_clipboard() { + if !text.is_empty() { self.prompt_state.prompt.paste(text); - self.messages_state - .toasts - .info(&format!("Pasted {characters} characters")); - debug_log!("composer claim: paste"); - } - _ => { - self.messages_state - .toasts - .warning("Nothing to paste — the clipboard is empty"); - debug_log!("composer claim: paste with nothing to paste"); } } + debug_log!("composer claim: paste"); } // There is deliberately **no catch-all arm**. M006 closed // the claim table, so every verb has a behaviour, and an // exhaustive match turns "the table and the runner @@ -11847,7 +11703,10 @@ impl App { let current_agent = current_name .as_deref() .and_then(|name| agents.iter().position(|agent| agent.name == name)) - .or_else(|| agents.iter().position(|agent| agent.name == "build")) + .or_else(|| { + codegg::agent::file_agents::find_default_agent(&agents) + .and_then(|default| agents.iter().position(|agent| agent.name == default.name)) + }) .unwrap_or(0); self.agent_state.agents = agents; @@ -11971,9 +11830,6 @@ impl App { } pub fn refresh_models(&mut self) { - self.messages_state - .toasts - .info("Refreshing model cache in background..."); let core_client = self.core_client.clone(); let cmd_tx = self.tui_cmd_tx.clone(); // M007-D: the daemon owns the effect. The refresh is the @@ -12783,11 +12639,7 @@ impl App { match ¤t { CenterTabRef::Main => return, CenterTabRef::Subagent(id) => { - if let Some(tab) = self.ui_state.subagents.tabs.remove_tab(id) { - self.messages_state - .toasts - .info(&format!("Closed {}", tab.label())); - } + let _ = self.ui_state.subagents.tabs.remove_tab(id); } CenterTabRef::File(id) => { crate::commands::editor::close_file_tab(self, id); @@ -13377,16 +13229,20 @@ impl App { .map(|pending| pending.perm_id.clone()) } + fn refuse_permission_response_while_observing(&mut self) { + self.messages_state.toasts.warning( + "Observer mode is read-only — permission answers are disabled while observing. Use /stop-observing to resume control.", + ); + self.dialog_state.permission_dialog = None; + self.dialog_state.permission_perm_id = None; + self.close_dialog(); + } + pub fn submit_permission_response(&mut self, allowed: bool) { // Presence M003: observers can never answer permission requests // for the observed session. if self.observer.blocks_permission_response() { - self.messages_state.toasts.warning( - "Observer mode is read-only — permission answers are disabled while observing. Use /stop-observing to resume control.", - ); - self.dialog_state.permission_dialog = None; - self.dialog_state.permission_perm_id = None; - self.close_dialog(); + self.refuse_permission_response_while_observing(); return; } if let Some(ref perm_id) = self.dialog_state.permission_perm_id { @@ -13406,12 +13262,7 @@ impl App { pub fn on_permission_confirm(&mut self) -> Option<(bool, usize)> { // Presence M003: same negative as `submit_permission_response`. if self.observer.blocks_permission_response() { - self.messages_state.toasts.warning( - "Observer mode is read-only — permission answers are disabled while observing. Use /stop-observing to resume control.", - ); - self.dialog_state.permission_dialog = None; - self.dialog_state.permission_perm_id = None; - self.close_dialog(); + self.refuse_permission_response_while_observing(); return None; } let pd = self.dialog_state.permission_dialog.as_ref()?; @@ -13544,7 +13395,10 @@ impl App { self.ui_state.timeline_selected = count - 1; self.ui_state.timeline_visible = true; } else { - self.messages_state.toasts.info("No messages in timeline"); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["No messages in timeline".to_string()], + ); } } @@ -13567,10 +13421,6 @@ impl App { .messages .select_index(self.ui_state.timeline_selected); self.ui_state.timeline_visible = false; - self.messages_state.toasts.info(&format!( - "Jumped to message {}", - self.ui_state.timeline_selected - )); } Some(InputAction::Cancel) => { self.ui_state.timeline_visible = false; @@ -13979,9 +13829,6 @@ impl App { md.push_str("- Run targeted tests first.\n"); let _ = codegg::util::clipboard::copy_to_clipboard(&md); - self.messages_state - .toasts - .info("Handoff exported to clipboard"); } } @@ -14881,6 +14728,7 @@ mod remote_core_loader_tests { let now = chrono::Utc::now(); let workspace = codegg_core::workspace::WorkspaceRecord { id: codegg_core::workspace::WorkspaceId::new(), + target: codegg_core::workspace::WorkspaceTarget::Local, canonical_root: tokio::fs::canonicalize("/tmp").await.unwrap(), display_name: "TUI test workspace".to_string(), created_at: now, @@ -15145,6 +14993,34 @@ mod lsp_command_dispatch_tests { Arc::new(LspTool::new(svc)) } + fn assert_lsp_report(app: &App, command: &str, expected: Option<&str>) { + assert_eq!( + app.ui_state.dialog, + Dialog::Context, + "{command} output should open the persistent context dialog" + ); + assert!( + app.messages_state.toasts.is_empty(), + "{command} output belongs in the report dialog, not a toast" + ); + let report = app + .focus_manager + .with_component::(|dialog| { + dialog.content_lines().join("\n") + }) + .expect("the LSP report should be mounted in an InfoDialog"); + assert!( + !report.trim().is_empty(), + "{command} report dialog should contain its output" + ); + if let Some(expected) = expected { + assert!( + report.contains(expected), + "{command} report should contain {expected:?}, got: {report:?}" + ); + } + } + fn dispatch(app: &mut App, query: &str) { let name = query .split_whitespace() @@ -15238,11 +15114,11 @@ mod lsp_command_dispatch_tests { } #[test] - fn lsp_root_with_path_produces_toast() { + fn lsp_root_with_path_opens_report() { let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); dispatch(&mut app, "/lsp root /tmp/test.rs"); - assert!(!app.messages_state.toasts.is_empty()); + assert_lsp_report(&app, "/lsp root /tmp/test.rs", None); } // ── /lsp restart ── @@ -15294,30 +15170,30 @@ mod lsp_command_dispatch_tests { assert!(!app.messages_state.toasts.is_empty()); } - // ── /lsp cache-status ── + // ── /lsp cache status ── #[test] - fn lsp_cache_status_with_tool_produces_toast() { + fn lsp_cache_status_with_tool_opens_report() { let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); - dispatch(&mut app, "/lsp cache-status"); - assert!(!app.messages_state.toasts.is_empty()); + dispatch(&mut app, "/lsp cache status"); + assert_lsp_report(&app, "/lsp cache status", None); } #[test] fn lsp_cache_status_without_tool_shows_unavailable() { let mut app = App::new_for_testing("/tmp".into()); - dispatch(&mut app, "/lsp cache-status"); + dispatch(&mut app, "/lsp cache status"); assert!(!app.messages_state.toasts.is_empty()); } - // ── /lsp cache-clear ── + // ── /lsp cache clear ── #[test] fn lsp_cache_clear_no_args_produces_toast() { let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); - dispatch(&mut app, "/lsp cache-clear"); + dispatch(&mut app, "/lsp cache clear"); assert!(!app.messages_state.toasts.is_empty()); } @@ -15325,14 +15201,14 @@ mod lsp_command_dispatch_tests { fn lsp_cache_clear_with_root_produces_toast() { let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); - dispatch(&mut app, "/lsp cache-clear /tmp/proj"); + dispatch(&mut app, "/lsp cache clear /tmp/proj"); assert!(!app.messages_state.toasts.is_empty()); } #[test] fn lsp_cache_clear_without_tool_shows_unavailable() { let mut app = App::new_for_testing("/tmp".into()); - dispatch(&mut app, "/lsp cache-clear"); + dispatch(&mut app, "/lsp cache clear"); assert!(!app.messages_state.toasts.is_empty()); } @@ -15397,56 +15273,56 @@ mod lsp_command_dispatch_tests { assert!(!app.messages_state.toasts.is_empty()); } - // ── /lsp repair-local ── + // ── /lsp repair local ── #[test] fn lsp_repair_local_missing_arg_shows_usage() { let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); - dispatch(&mut app, "/lsp repair-local"); + dispatch(&mut app, "/lsp repair local"); assert!(!app.messages_state.toasts.is_empty()); } #[test] - fn lsp_repair_local_with_path_produces_toast() { + fn lsp_repair_local_with_path_opens_report() { let rt = tokio::runtime::Runtime::new().unwrap(); let _guard = rt.enter(); let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); - dispatch(&mut app, "/lsp repair-local /tmp/test.rs:10:5"); - assert!(!app.messages_state.toasts.is_empty()); + dispatch(&mut app, "/lsp repair local /tmp/test.rs:10:5"); + assert_lsp_report(&app, "/lsp repair local /tmp/test.rs:10:5", None); } #[test] fn lsp_repair_local_without_tool_shows_unavailable() { let mut app = App::new_for_testing("/tmp".into()); - dispatch(&mut app, "/lsp repair-local /tmp/test.rs"); + dispatch(&mut app, "/lsp repair local /tmp/test.rs"); assert!(!app.messages_state.toasts.is_empty()); } - // ── /lsp review-file ── + // ── /lsp review file ── #[test] fn lsp_review_file_missing_arg_shows_usage() { let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); - dispatch(&mut app, "/lsp review-file"); + dispatch(&mut app, "/lsp review file"); assert!(!app.messages_state.toasts.is_empty()); } #[test] - fn lsp_review_file_with_path_produces_toast() { + fn lsp_review_file_with_path_opens_report() { let rt = tokio::runtime::Runtime::new().unwrap(); let _guard = rt.enter(); let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); - dispatch(&mut app, "/lsp review-file /tmp/test.rs"); - assert!(!app.messages_state.toasts.is_empty()); + dispatch(&mut app, "/lsp review file /tmp/test.rs"); + assert_lsp_report(&app, "/lsp review file /tmp/test.rs", None); } #[test] fn lsp_review_file_without_tool_shows_unavailable() { let mut app = App::new_for_testing("/tmp".into()); - dispatch(&mut app, "/lsp review-file /tmp/test.rs"); + dispatch(&mut app, "/lsp review file /tmp/test.rs"); assert!(!app.messages_state.toasts.is_empty()); } @@ -15460,13 +15336,13 @@ mod lsp_command_dispatch_tests { } #[test] - fn lsp_impact_with_target_produces_toast() { + fn lsp_impact_with_target_opens_report() { let rt = tokio::runtime::Runtime::new().unwrap(); let _guard = rt.enter(); let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); dispatch(&mut app, "/lsp impact /tmp/test.rs:10:5"); - assert!(!app.messages_state.toasts.is_empty()); + assert_lsp_report(&app, "/lsp impact /tmp/test.rs:10:5", None); } #[test] @@ -15476,30 +15352,30 @@ mod lsp_command_dispatch_tests { assert!(!app.messages_state.toasts.is_empty()); } - // ── /lsp test-repair ── + // ── /lsp repair test ── #[test] fn lsp_test_repair_missing_arg_shows_usage() { let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); - dispatch(&mut app, "/lsp test-repair"); + dispatch(&mut app, "/lsp repair test"); assert!(!app.messages_state.toasts.is_empty()); } #[test] - fn lsp_test_repair_with_file_produces_toast() { + fn lsp_test_repair_with_file_opens_report() { let rt = tokio::runtime::Runtime::new().unwrap(); let _guard = rt.enter(); let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); - dispatch(&mut app, "/lsp test-repair /tmp/test_test.rs"); - assert!(!app.messages_state.toasts.is_empty()); + dispatch(&mut app, "/lsp repair test /tmp/test_test.rs"); + assert_lsp_report(&app, "/lsp repair test /tmp/test_test.rs", None); } #[test] fn lsp_test_repair_without_tool_shows_unavailable() { let mut app = App::new_for_testing("/tmp".into()); - dispatch(&mut app, "/lsp test-repair /tmp/test_test.rs"); + dispatch(&mut app, "/lsp repair test /tmp/test_test.rs"); assert!(!app.messages_state.toasts.is_empty()); } @@ -15514,13 +15390,13 @@ mod lsp_command_dispatch_tests { } #[test] - fn lsp_interface_with_path_produces_toast() { + fn lsp_interface_with_path_opens_report() { let rt = tokio::runtime::Runtime::new().unwrap(); let _guard = rt.enter(); let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); dispatch(&mut app, "/lsp interface /tmp/test.rs"); - assert!(!app.messages_state.toasts.is_empty()); + assert_lsp_report(&app, "/lsp interface /tmp/test.rs", None); } #[test] @@ -15530,30 +15406,30 @@ mod lsp_command_dispatch_tests { assert!(!app.messages_state.toasts.is_empty()); } - // ── /lsp cross-repair ── + // ── /lsp repair cross ── #[test] fn lsp_cross_repair_missing_arg_shows_usage() { let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); - dispatch(&mut app, "/lsp cross-repair"); + dispatch(&mut app, "/lsp repair cross"); assert!(!app.messages_state.toasts.is_empty()); } #[test] - fn lsp_cross_repair_with_path_produces_toast() { + fn lsp_cross_repair_with_path_opens_report() { let rt = tokio::runtime::Runtime::new().unwrap(); let _guard = rt.enter(); let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); - dispatch(&mut app, "/lsp cross-repair /tmp/test.rs"); - assert!(!app.messages_state.toasts.is_empty()); + dispatch(&mut app, "/lsp repair cross /tmp/test.rs"); + assert_lsp_report(&app, "/lsp repair cross /tmp/test.rs", None); } #[test] fn lsp_cross_repair_without_tool_shows_unavailable() { let mut app = App::new_for_testing("/tmp".into()); - dispatch(&mut app, "/lsp cross-repair /tmp/test.rs"); + dispatch(&mut app, "/lsp repair cross /tmp/test.rs"); assert!(!app.messages_state.toasts.is_empty()); } @@ -15568,13 +15444,13 @@ mod lsp_command_dispatch_tests { } #[test] - fn lsp_call_neighbors_with_target_produces_toast() { + fn lsp_call_neighbors_with_target_opens_report() { let rt = tokio::runtime::Runtime::new().unwrap(); let _guard = rt.enter(); let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); dispatch(&mut app, "/lsp call-neighbors /tmp/test.rs:10:5"); - assert!(!app.messages_state.toasts.is_empty()); + assert_lsp_report(&app, "/lsp call-neighbors /tmp/test.rs:10:5", None); } #[test] @@ -15584,12 +15460,12 @@ mod lsp_command_dispatch_tests { assert!(!app.messages_state.toasts.is_empty()); } - // ── /lsp context-diagnostics ── + // ── /lsp context diagnostics ── #[test] fn lsp_context_diagnostics_missing_arg_shows_usage() { let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); - dispatch(&mut app, "/lsp context-diagnostics"); + dispatch(&mut app, "/lsp context diagnostics"); assert!(!app.messages_state.toasts.is_empty()); let texts: Vec = app .messages_state @@ -15604,13 +15480,13 @@ mod lsp_command_dispatch_tests { } #[test] - fn lsp_context_diagnostics_with_path_produces_toast() { + fn lsp_context_diagnostics_with_path_opens_report() { let rt = tokio::runtime::Runtime::new().unwrap(); let _guard = rt.enter(); let mut app = App::new_for_testing("/tmp".into()); app.lsp_tool = Some(sample_lsp_tool()); dispatch(&mut app, "/lsp context diagnostics /tmp/test.rs"); - assert!(!app.messages_state.toasts.is_empty()); + assert_lsp_report(&app, "/lsp context diagnostics /tmp/test.rs", None); } #[test] @@ -17221,18 +17097,18 @@ mod reasoning_strip_warning_tests { } #[test] - fn a_passthrough_provider_gets_the_plain_confirmation() { + fn a_passthrough_provider_selection_is_visible_without_a_toast() { let mut app = app_with_model("openai/gpt-5"); app.dispatch_builtin_command(crate::command::BuiltinSlashAction::Reasoning, None); - let toasts = toast_messages(&app); assert!( - toasts.iter().any(|t| t.contains("Extended thinking")), - "expected the normal confirmation, got {toasts:?}" + app.ui_state.reasoning_mode.requests_reasoning(), + "the selected reasoning mode is visible in the buffer" ); + let toasts = toast_messages(&app); assert!( - !toasts.iter().any(|t| t.contains("drops this setting")), - "a pass-through provider must not be warned about, got {toasts:?}" + toasts.is_empty(), + "a pass-through provider needs no warning, and a direct selection must not toast: {toasts:?}" ); } @@ -17246,10 +17122,18 @@ mod reasoning_strip_warning_tests { // fixed ladder, so "all the way to Off" is a walk to the end of the // option set, not a fixed number of steps. let mut app = app_with_model("openrouter/anthropic/claude"); + let mut toast_count_before_off = None; for _ in 0..16 { if app.ui_state.reasoning_mode == codegg::protocol::core::ReasoningMode::Off { break; } + let next = crate::commands::reasoning::next_mode( + &app.ui_state.reasoning_mode, + &crate::commands::reasoning::option_set(&app), + ); + if next == codegg::protocol::core::ReasoningMode::Off { + toast_count_before_off = Some(app.messages_state.toasts.iter().count()); + } app.dispatch_builtin_command(crate::command::BuiltinSlashAction::Reasoning, None); } assert_eq!( @@ -17257,13 +17141,10 @@ mod reasoning_strip_warning_tests { codegg::protocol::core::ReasoningMode::Off, "expected the cycle to land on Off" ); - // Toasts accumulate, so the two earlier effort steps are still - // queued; only the most recent one describes the Off step. - let toasts = toast_messages(&app); - let last = toasts.last().expect("the cycle always toasts"); - assert!( - !last.contains("drops this setting"), - "Off must not warn on a stripping provider, got {last:?}" + assert_eq!( + app.messages_state.toasts.iter().count(), + toast_count_before_off.expect("the model's option cycle must pass through Off"), + "Off is visible in the selected mode and must not add a direct-action toast" ); } } @@ -17561,11 +17442,14 @@ mod connection_rotation_tests { assert_eq!(connect.providers.len(), 1); } - /// The rotation toast named Eggpool for every provider. It is the only - /// feedback between pressing Enter and the probe returning, so it has to - /// name the connection actually being rotated. + /// The rotation dialog named Eggpool for every provider. It used to + /// construct a fixed row, so rotating an `other:opencode_go` credential + /// asked for an Eggpool one — right action, wrong subject, and nothing on + /// screen to contradict it. The toast that carried a second copy of this + /// derivation is gone; the dialog's own row is now the only place it is + /// read, so this asserts that row. #[test] - fn rotation_provider_label_follows_the_rotation_target() { + fn rotation_dialog_names_the_connection_it_rotates() { let mut app = App::new_for_testing("rotation-label".to_string()); let mut dialog = crate::components::dialogs::connection_selection::ConnectionSelectionDialog::new( @@ -17578,11 +17462,23 @@ mod connection_rotation_tests { ]; app.dialog_state.connection_selection_dialog = Some(dialog); - assert_eq!(app.rotation_provider_label("conn-go"), "opencode_go"); - assert_eq!(app.rotation_provider_label("conn-eggpool"), "eggpool"); + app.open_connection_rotation_dialog("conn-go".to_string(), 1); + let connect = app + .dialog_state + .connect_dialog + .as_ref() + .expect("rotation opens the masked credential editor"); + assert_eq!(connect.providers[0].id, "opencode_go"); + assert_eq!(connect.providers[0].name, "eggstackmain"); + + app.open_connection_rotation_dialog("conn-missing".to_string(), 1); + let connect = app + .dialog_state + .connect_dialog + .as_ref() + .expect("rotation opens a dialog even with no matching summary"); assert_eq!( - app.rotation_provider_label("conn-missing"), - "provider", + connect.providers[0].name, "provider", "an unknown target must not be labelled Eggpool" ); } @@ -17835,6 +17731,7 @@ mod row_precise_disclosure_tests { output: "running 3 tests\ntest result: ok".to_string(), status: ToolStatus::Completed, duration_ms: Some(7), + started_at: None, exit_code: Some(0), output_lines: Some(2), expanded: false, @@ -17900,16 +17797,6 @@ mod row_precise_disclosure_tests { ) } - /// The toast the last gesture left behind. - fn last_toast(app: &App) -> String { - app.messages_state - .toasts - .iter() - .last() - .map(|toast| toast.message.clone()) - .unwrap_or_default() - } - /// Clicking a tool call's header expands **that tool call**, in a message /// that also carries a reasoning block. /// @@ -17972,19 +17859,21 @@ mod row_precise_disclosure_tests { } /// The expand-all gesture opens every tool call and every reasoning - /// block, and the next press closes every one of them again. + /// block, and the next press closes every one of them again. Neither press + /// announces itself: the transcript is the feedback. #[test] fn the_expand_all_gesture_opens_everything_and_the_next_press_closes_it() { let mut app = app_with_mixed_message(); + let before = app.messages_state.toasts.iter().count(); app.expand_all_disclosures(); let (tool_expanded, reasoning_collapsed) = disclosure_state(&app); assert!(tool_expanded, "the tool call must be open"); assert!(!reasoning_collapsed, "the reasoning block must be open"); - assert!( - last_toast(&app).contains("expanded"), - "the toast must name the outcome: {:?}", - last_toast(&app) + assert_eq!( + app.messages_state.toasts.iter().count(), + before, + "expanding must emit no toast; the buffer shows the state" ); app.expand_all_disclosures(); @@ -17994,10 +17883,10 @@ mod row_precise_disclosure_tests { reasoning_collapsed, "the reasoning block must be closed again" ); - assert!( - last_toast(&app).contains("collapsed"), - "the toast must name the outcome: {:?}", - last_toast(&app) + assert_eq!( + app.messages_state.toasts.iter().count(), + before, + "collapsing must emit no toast; the buffer shows the state" ); } @@ -18005,6 +17894,7 @@ mod row_precise_disclosure_tests { #[test] fn the_palette_command_expands_everything_too() { let mut app = app_with_mixed_message(); + let toast_count_before = app.messages_state.toasts.iter().count(); app.dispatch_builtin_command( crate::command::BuiltinSlashAction::ExpandAllDisclosures, @@ -18014,10 +17904,10 @@ mod row_precise_disclosure_tests { let (tool_expanded, reasoning_collapsed) = disclosure_state(&app); assert!(tool_expanded, "the tool call must be open"); assert!(!reasoning_collapsed, "the reasoning block must be open"); - assert!( - last_toast(&app).contains("expanded"), - "the toast must name the outcome: {:?}", - last_toast(&app) + assert_eq!( + app.messages_state.toasts.iter().count(), + toast_count_before, + "the transcript shows the disclosure state; the palette gesture must not toast" ); } diff --git a/crates/codegg-tui/src/app/modal.rs b/crates/codegg-tui/src/app/modal.rs index ba9f62c12..f099d5870 100644 --- a/crates/codegg-tui/src/app/modal.rs +++ b/crates/codegg-tui/src/app/modal.rs @@ -27,6 +27,13 @@ const LOG_TAIL_MAX_LINES: usize = 400; /// line cannot dominate the window. const LOG_LINE_MAX_BYTES: usize = 512; +/// Select the content shown by the existing Logs surface. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum LogsView { + All, + Notifications, +} + /// Read at most [`LOG_TAIL_MAX_BYTES`] from the end of `path` and return /// the lines it contains, oldest first. /// @@ -102,17 +109,12 @@ impl App { } } - /// Open the `/logs` window: a bounded tail of the user-scoped daemon - /// log plus every toast notification this session has shown. - /// - /// The TUI process has no in-memory tracing capture and writes no log - /// of its own by default, so the daemon log file is the only durable - /// source. When it is missing or unreadable the window still opens - /// with the notification history and says plainly what is missing — - /// it never substitutes a fabricated source. - pub(crate) fn open_logs_window(&mut self) { + /// Open the Logs surface with the requested body view. A one-shot view + /// queued by `/toast` takes precedence and is cleared as it is consumed. + pub(crate) fn open_logs_window(&mut self, view: LogsView) { use crate::components::dialogs::info::InfoDialog; - let lines = self.logs_window_lines(); + let view = self.pending_logs_view.take().unwrap_or(view); + let lines = self.logs_window_lines(view); self.open_info_dialog(crate::components::dialogs::info::InfoType::Logs, lines); // The window is append-only; land on its newest entry so the // most recent log line is visible without scrolling. @@ -120,33 +122,35 @@ impl App { .with_component_mut::(|dialog| dialog.scroll_to_end()); } - /// Build the `/logs` body: log source header, bounded daemon log - /// tail, then the retained notification history oldest-first. - fn logs_window_lines(&self) -> Vec { + /// Build the Logs body, optionally omitting the bounded daemon log tail. + fn logs_window_lines(&self, view: LogsView) -> Vec { use crate::components::toast::MAX_TOAST_HISTORY; - let log_path = codegg_client::LocalDaemonPaths::resolve().log_path; let mut lines: Vec = Vec::new(); - lines.push(format!("== Daemon log: {} ==", log_path.display())); - match read_log_tail(&log_path) { - Ok(tail) if tail.is_empty() => { - lines.push("(log file is empty)".to_string()); - } - Ok(tail) => { - lines.push(format!( - "(last {} line{} of at most {} KiB)", - tail.len(), - if tail.len() == 1 { "" } else { "s" }, - LOG_TAIL_MAX_BYTES / 1024 - )); - lines.extend(tail); - } - Err(err) => { - lines.push(format!("(daemon log unavailable: {err})")); + if view == LogsView::All { + let log_path = codegg_client::LocalDaemonPaths::resolve().log_path; + lines.push(format!("== Daemon log: {} ==", log_path.display())); + match read_log_tail(&log_path) { + Ok(tail) if tail.is_empty() => { + lines.push("(log file is empty)".to_string()); + } + Ok(tail) => { + lines.push(format!( + "(last {} line{} of at most {} KiB)", + tail.len(), + if tail.len() == 1 { "" } else { "s" }, + LOG_TAIL_MAX_BYTES / 1024 + )); + lines.extend(tail); + } + Err(err) => { + lines.push(format!("(daemon log unavailable: {err})")); + } } + + lines.push(String::new()); } - lines.push(String::new()); lines.push(format!( "== Notifications (newest last, at most {MAX_TOAST_HISTORY} retained) ==" )); @@ -340,7 +344,7 @@ impl App { .agent_state .agents .iter() - .filter(|a| !a.hidden) + .filter(|a| a.resolved_axes().0) .collect(); self.dialog_state.agent_dialog.set_agents(visible); self.dialog_state.agent_dialog.initialize_selection( diff --git a/crates/codegg-tui/src/app/plugin_ui.rs b/crates/codegg-tui/src/app/plugin_ui.rs index 039c25744..5d24c7c2c 100644 --- a/crates/codegg-tui/src/app/plugin_ui.rs +++ b/crates/codegg-tui/src/app/plugin_ui.rs @@ -17,11 +17,14 @@ impl App { use codegg::protocol::ui::UiEffect; // Capability gate: reject effects the client does not support. - // Degrade to a summary toast so the effect is not silently lost. + // Retain a short Usage result so the rejected instruction is not lost. if !self.ui_state.plugin_ui_caps.supports_effect(&effect) { let summary = Self::degrade_effect_to_summary(&effect); if !summary.is_empty() { - self.messages_state.toasts.info(&summary); + self.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![summary], + ); } return PluginUiApplyResult::Unsupported( "effect type not supported by client capabilities".to_string(), diff --git a/crates/codegg-tui/src/app/prompt_turn.rs b/crates/codegg-tui/src/app/prompt_turn.rs index f8bcd7b45..20d228270 100644 --- a/crates/codegg-tui/src/app/prompt_turn.rs +++ b/crates/codegg-tui/src/app/prompt_turn.rs @@ -68,13 +68,6 @@ impl App { return; } if self.prompt_state.pending_send { - self.messages_state.toasts.warning( - if self.prompt_state.pending_session_submit.is_some() { - "Still creating a session for the previous prompt" - } else { - "Still waiting for previous prompt to finish" - }, - ); tracing::debug!(target: "codegg::tui::app", "send_prompt: returning - pending_send already true"); return; } diff --git a/crates/codegg-tui/src/command.rs b/crates/codegg-tui/src/command.rs index c956108c3..3be0ba7c7 100755 --- a/crates/codegg-tui/src/command.rs +++ b/crates/codegg-tui/src/command.rs @@ -134,6 +134,8 @@ pub enum BuiltinSlashAction { Connect, Connections, Status, + /// Read the daemon-owned bounded advisor configuration status. + Advisor, Policy, Approval, Sandbox, @@ -193,6 +195,8 @@ pub enum BuiltinSlashAction { /// Read-only window over recent daemon log lines and the retained /// toast history. Logs, + /// Open the retained notification history without daemon log lines. + Toast, ToolContracts, Lsp, /// Eggwork M002: read-only view of the configured remote nodes' host @@ -506,6 +510,8 @@ impl CommandRegistry { .with_aliases(&["quit", "q"]) .with_description("Exit the app"), Command::new("/status", CommandCategory::System, CommandAction::Builtin(BuiltinSlashAction::Status)).with_description("View status"), + Command::new("/advisor", CommandCategory::System, CommandAction::Builtin(BuiltinSlashAction::Advisor)) + .with_description("Show bounded advisor configuration and forwarding disclosure"), Command::new("/policy", CommandCategory::System, CommandAction::Builtin(BuiltinSlashAction::Policy)) .with_description("Show effective approval mode and sandbox profile (/policy)"), Command::new("/approval", CommandCategory::System, CommandAction::Builtin(BuiltinSlashAction::Approval)) @@ -673,6 +679,8 @@ impl CommandRegistry { .with_description("Run diagnostics (search backend, MCP, providers)"), Command::new("/logs", CommandCategory::System, CommandAction::Builtin(BuiltinSlashAction::Logs)) .with_description("Show recent daemon log lines and past notifications"), + Command::new("/toast", CommandCategory::System, CommandAction::Builtin(BuiltinSlashAction::Toast)) + .with_description("Show the notification history without daemon log lines"), Command::new("/lsp", CommandCategory::System, CommandAction::Builtin(BuiltinSlashAction::Lsp)) .with_description("LSP control, diagnostics and semantic workflows (args:
[args])"), Command::new("/nodes", CommandCategory::System, CommandAction::Builtin(BuiltinSlashAction::Nodes)) @@ -1035,8 +1043,10 @@ mod tests { #[test] fn built_in_command_count_matches_release_docs() { // Keep the builtin cache length in sync with its architecture/command.md - // pin; dialog and template rows are outside this count. - assert_eq!(CommandRegistry::built_in_commands().len(), 88); + // pin; dialog and template rows are outside this count. The + // reconciliation restores the two rows M003's fold could not have known + // about — `/advisor` and `/toast` — on top of its 88. + assert_eq!(CommandRegistry::built_in_commands().len(), 90); } /// WP5: the duplicate identity was two rows, and the fix is one row plus @@ -1223,7 +1233,7 @@ mod tests { // and `[Cc]ount is (\d+)`, and a `BuiltinSlashAction` **variant** count // is neither. That blind spot is not hypothetical — the document // historical prose carried 149 and later 156–158 counts without a - // source-backed variant assertion; the current total is 82. + // source-backed variant assertion; the current total is 84. let manifest = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); let doc = manifest.join("../../architecture/command.md"); let text = std::fs::read_to_string(&doc).expect("architecture/command.md must be readable"); @@ -1274,6 +1284,10 @@ mod tests { B::Connect, B::Connections, B::Status, + // M002: `/advisor`. Same omission the three comments above record: + // the variant reached the enum and the registry, so the "no surplus" + // arm had 160 registry variants against 159 listed ones. + B::Advisor, B::Policy, B::Approval, B::Sandbox, @@ -1323,6 +1337,7 @@ mod tests { B::Search, B::Doctor, B::Logs, + B::Toast, B::ToolContracts, B::Lsp, B::Review, diff --git a/crates/codegg-tui/src/command_route_tests.rs b/crates/codegg-tui/src/command_route_tests.rs index d4b18b37d..eae7f5394 100644 --- a/crates/codegg-tui/src/command_route_tests.rs +++ b/crates/codegg-tui/src/command_route_tests.rs @@ -1186,7 +1186,7 @@ fn a_frontend_effect_is_dispatched_from_the_declared_action() { } } } - assert_eq!(checked, 61, "61 forms are frontend effects"); + assert_eq!(checked, 62, "62 forms are frontend effects"); } // ── The projection consumption (M007-H, D3/D4) ───────────────────────────── diff --git a/crates/codegg-tui/src/commands/agent_editor.rs b/crates/codegg-tui/src/commands/agent_editor.rs index f764e016b..75eb9f68b 100644 --- a/crates/codegg-tui/src/commands/agent_editor.rs +++ b/crates/codegg-tui/src/commands/agent_editor.rs @@ -402,7 +402,10 @@ pub fn create_agent_draft(app: &mut App, name: &str, default_scope: DocumentScop }; match resolve_new_agent(argument, default_scope, &rows) { NewAgentOutcome::Refused(message) => { - app.messages_state.toasts.warning(&message); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec![message], + ); } NewAgentOutcome::Existing(target) => { super::editor::open_editor_in(app, &target.path, target.scope); @@ -510,9 +513,6 @@ pub fn apply_agent_selection( } AgentSelection::Restore => { if !can_restore(row) { - app.messages_state - .toasts - .info(&format!("`{}` has no override to restore", row.name)); return; } let Some((scope, path)) = row.target() else { diff --git a/crates/codegg-tui/src/commands/agents.rs b/crates/codegg-tui/src/commands/agents.rs index 9400e7b6d..870fcf0ac 100644 --- a/crates/codegg-tui/src/commands/agents.rs +++ b/crates/codegg-tui/src/commands/agents.rs @@ -11,7 +11,6 @@ use codegg::agent::asset_context::{AssetContext, AssetContextBuilder, ProjectId} use codegg::agent::registry::{AgentRegistry, AgentSourceKind}; #[cfg(test)] use codegg::agent::resolve_agents; -use codegg::agent::AgentMode; use codegg::config::schema::Config; use codegg::protocol::core::{ AssetRefreshReasonDto, AssetRefreshRequestDto, AssetRefreshScopeDto, CoreRequest, CoreResponse, @@ -201,7 +200,42 @@ pub(crate) fn format_agents_list(agent_state: &AgentState, show_all: bool) -> Ve format_agents_list_for_root(agent_state, show_all, std::path::Path::new(".")) } -pub(crate) fn format_agents_list_for_root( +pub(crate) fn format_axes(agent: &codegg::agent::Agent) -> String { + let (selectable, subagent, default) = agent.resolved_axes(); + format!( + "selectable={}, subagent={}, default={}", + selectable, subagent, default + ) +} + +fn format_agent_source(source: &codegg::agent::registry::AgentSource) -> String { + let kind = match &source.kind { + AgentSourceKind::Builtin => "builtin", + AgentSourceKind::GlobalFile => "global", + AgentSourceKind::ProjectFile => "project", + AgentSourceKind::ConfigAgent => "config", + AgentSourceKind::ConfigMode => "mode", + AgentSourceKind::Session => "session", + AgentSourceKind::PluginFile => "plugin", + }; + source + .path + .as_ref() + .map(|path| format!("{kind}: {}", path.display())) + .unwrap_or_else(|| format!("{kind}: generated")) +} + +fn agent_index_after_reload(agents: &[codegg::agent::Agent], current_name: Option<&str>) -> usize { + current_name + .and_then(|name| agents.iter().position(|agent| agent.name == name)) + .or_else(|| { + codegg::agent::file_agents::find_default_agent(agents) + .and_then(|default| agents.iter().position(|agent| agent.name == default.name)) + }) + .unwrap_or(0) +} + +fn format_agents_list_for_root( agent_state: &AgentState, show_all: bool, workspace_root: &std::path::Path, @@ -223,11 +257,11 @@ pub(crate) fn format_agents_list_for_root( let primary: Vec<_> = agents .iter() - .filter(|ra| matches!(ra.agent.mode, AgentMode::Primary | AgentMode::All)) + .filter(|ra| ra.agent.resolved_axes().0 && !ra.agent.hidden) .collect(); let subagents: Vec<_> = agents .iter() - .filter(|ra| matches!(ra.agent.mode, AgentMode::Subagent)) + .filter(|ra| ra.agent.resolved_axes().1 && !ra.agent.hidden) .collect(); let mut lines = Vec::new(); @@ -246,9 +280,15 @@ pub(crate) fn format_agents_list_for_root( " " }; let hidden = if ra.agent.hidden { " (hidden)" } else { "" }; + let axes = format_axes(&ra.agent); + let source = ra + .sources + .last() + .map(format_agent_source) + .unwrap_or_else(|| "unknown".to_string()); lines.push(format!( - " {} {:<20} {}{}", - marker, ra.agent.name, ra.agent.description, hidden + " {} {:<20} {} [{}] source={}{}", + marker, ra.agent.name, ra.agent.description, axes, source, hidden )); } } @@ -260,9 +300,41 @@ pub(crate) fn format_agents_list_for_root( lines.push("Subagents:".to_string()); for ra in &subagents { let hidden = if ra.agent.hidden { " (hidden)" } else { "" }; + let axes = format_axes(&ra.agent); + let source = ra + .sources + .last() + .map(format_agent_source) + .unwrap_or_else(|| "unknown".to_string()); + lines.push(format!( + " {:<20} {} [{}] source={}{}", + ra.agent.name, ra.agent.description, axes, source, hidden + )); + } + } + + let other: Vec<_> = agents + .iter() + .filter(|ra| { + let (selectable, subagent, _) = ra.agent.resolved_axes(); + !ra.agent.hidden && !selectable && !subagent + }) + .collect(); + if !other.is_empty() { + if !lines.is_empty() { + lines.push(String::new()); + } + lines.push("Other agents:".to_string()); + for ra in &other { + let axes = format_axes(&ra.agent); + let source = ra + .sources + .last() + .map(format_agent_source) + .unwrap_or_else(|| "unknown".to_string()); lines.push(format!( - " {:<20} {}{}", - ra.agent.name, ra.agent.description, hidden + " {:<20} {} [{}] source={}", + ra.agent.name, ra.agent.description, axes, source )); } } @@ -275,9 +347,17 @@ pub(crate) fn format_agents_list_for_root( } lines.push("Hidden/system agents:".to_string()); for ra in &hidden { + let source = ra + .sources + .last() + .map(format_agent_source) + .unwrap_or_else(|| "unknown".to_string()); lines.push(format!( - " {:<20} {} [{:?}]", - ra.agent.name, ra.agent.description, ra.agent.mode + " {:<20} {} [{}] source={}", + ra.agent.name, + ra.agent.description, + format_axes(&ra.agent), + source )); } } @@ -315,6 +395,32 @@ pub(crate) fn format_agent_show_for_root( } lines.push(format!("description: {}", agent.description)); lines.push(format!("mode: {:?}", agent.mode)); + lines.push("axes:".to_string()); + for (axis, value) in [ + ( + codegg::agent::registry::AgentAxis::Selectable, + agent.resolved_axes().0, + ), + ( + codegg::agent::registry::AgentAxis::Subagent, + agent.resolved_axes().1, + ), + ( + codegg::agent::registry::AgentAxis::Default, + agent.resolved_axes().2, + ), + ] { + let source = registry + .axis_source(name, axis) + .map(format_agent_source) + .unwrap_or_else(|| "unrecorded".to_string()); + lines.push(format!( + " {}: {} (source: {})", + axis.as_str(), + value, + source + )); + } if let Some(ref runtime) = agent.runtime_kind { lines.push(format!("runtime: {runtime:?}")); } @@ -685,22 +791,13 @@ pub(crate) fn validate_agent_select(name: &str, agent_state: &AgentState) -> Res let agent = &agent_state.agents[idx]; - // Reject hidden/system agents - if agent.hidden { + if !agent.resolved_axes().0 { return Err(format!( - "Agent '{}' is a hidden/system agent and cannot be selected as the active agent.", + "Agent '{}' is not selectable as the active agent.", name )); } - // Reject subagent-only agents - if matches!(agent.mode, AgentMode::Subagent) { - return Err(format!( - "Agent '{}' is a subagent-only agent and cannot be selected as the active agent. Use @{} to spawn it as a subagent.", - name, name - )); - } - Ok(idx) } @@ -720,12 +817,6 @@ pub(crate) fn dispatch_agent_select(app: &mut App, argument: &str) { match crate::commands::agents::validate_agent_select(&name, &app.agent_state) { Ok(idx) => { app.agent_state.current_agent = idx; - let agent = &app.agent_state.agents[idx]; - let model = app.agent_state.current_model.clone(); - app.messages_state.toasts.info(&format!( - "selected agent: {} (model: {})", - agent.name, model - )); } Err(e) => { app.messages_state.toasts.error(&e); @@ -774,33 +865,35 @@ pub(crate) fn dispatch_agents(app: &mut App, argument: &str) { true, &workspace_root, ); - app.show_short_or_info(crate::components::dialogs::info::InfoType::Agents, lines); + app.open_info_dialog(crate::components::dialogs::info::InfoType::Agents, lines); } "show" => { if subargs.is_empty() { - app.messages_state - .toasts - .warning("Usage: /agents show "); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /agents show ".to_string()], + ); return; } let lines = crate::commands::agents::format_agent_show_for_root(subargs, &workspace_root); - app.show_short_or_info(crate::components::dialogs::info::InfoType::Agents, lines); + app.open_info_dialog(crate::components::dialogs::info::InfoType::Agents, lines); } "diff" => { if subargs.is_empty() { - app.messages_state - .toasts - .warning("Usage: /agents diff "); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /agents diff ".to_string()], + ); return; } let lines = crate::commands::agents::format_agent_diff_for_root(subargs, &workspace_root); - app.show_short_or_info(crate::components::dialogs::info::InfoType::Agents, lines); + app.open_info_dialog(crate::components::dialogs::info::InfoType::Agents, lines); } "validate" => { let (lines, _) = crate::commands::agents::format_agents_validate_inner(&workspace_root); - app.show_short_or_info(crate::components::dialogs::info::InfoType::Agents, lines); + app.open_info_dialog(crate::components::dialogs::info::InfoType::Agents, lines); } "reload" | "rebuild" => { let (new_agents, diags) = @@ -812,49 +905,19 @@ pub(crate) fn dispatch_agents(app: &mut App, argument: &str) { .agents .get(app.agent_state.current_agent) .map(|a| a.name.clone()); + // A session default may be non-selectable; preserve it while present. + let current_index = agent_index_after_reload(&new_agents, current_name.as_deref()); app.agent_state.agents = new_agents; - if let Some(ref name) = current_name { - if let Some(idx) = app.agent_state.agents.iter().position(|a| a.name == *name) { - // Check if agent is still selectable (not hidden, not subagent-only) - let agent = &app.agent_state.agents[idx]; - if !agent.hidden && !matches!(agent.mode, AgentMode::Subagent) { - app.agent_state.current_agent = idx; - } else { - // Current agent became hidden or subagent-only, fall back - if let Some(idx) = app - .agent_state - .agents - .iter() - .position(|a| a.name == "build") - { - app.agent_state.current_agent = idx; - } else { - app.agent_state.current_agent = 0; - } - } - } else { - // Current agent disappeared, fall back to default - if let Some(idx) = app - .agent_state - .agents - .iter() - .position(|a| a.name == "build") - { - app.agent_state.current_agent = idx; - } else { - app.agent_state.current_agent = 0; - } - } - } + app.agent_state.current_agent = current_index; } - app.show_short_or_info(crate::components::dialogs::info::InfoType::Agents, diags); + app.open_info_dialog(crate::components::dialogs::info::InfoType::Agents, diags); } _ => { // Treat unknown subcommand as agent name for convenience // e.g., `/agents build` shows that agent let lines = crate::commands::agents::format_agent_show_for_root(subcmd, &workspace_root); - app.show_short_or_info(crate::components::dialogs::info::InfoType::Agents, lines); + app.open_info_dialog(crate::components::dialogs::info::InfoType::Agents, lines); } } } @@ -863,6 +926,64 @@ pub(crate) fn dispatch_agents(app: &mut App, argument: &str) { mod tests { use super::*; + #[test] + fn project_agent_browse_shows_axes_and_source() { + let tmp = tempfile::tempdir().unwrap(); + let agents_dir = tmp.path().join(".codegg/agents"); + std::fs::create_dir_all(&agents_dir).unwrap(); + std::fs::write( + agents_dir.join("project-selectable.toml"), + r#"name = "project-selectable" +selectable = true +subagent = false +default = false +"#, + ) + .unwrap(); + let state = AgentState { + snapshot: None, + agents: resolve_agents(&Config::default()).unwrap_or_default(), + current_agent: 0, + current_model: String::new(), + models: Vec::new(), + model_idx: 0, + plan_mode: false, + plan_topic: None, + }; + + let output = format_agents_list_for_root(&state, false, tmp.path()).join("\n"); + assert!(output.contains("project-selectable")); + assert!(output.contains("selectable=true, subagent=false, default=false")); + assert!(output.contains("source=project:")); + assert!(output.lines().any(|line| { + line.contains("build") + && line.contains("selectable=false, subagent=false, default=true") + && line.contains("source=builtin: generated") + })); + } + + #[test] + fn removed_selected_agent_falls_back_to_declared_default() { + let agents = vec![ + codegg::agent::Agent { + name: "other".to_string(), + selectable: true, + ..Default::default() + }, + codegg::agent::Agent { + name: "declared-default".to_string(), + selectable: true, + default: true, + ..Default::default() + }, + ]; + + assert_eq!( + agent_index_after_reload(&agents, Some("removed-user-agent")), + 1 + ); + } + #[test] fn format_agents_list_shows_primary_and_subagents() { let state = AgentState { @@ -903,7 +1024,7 @@ mod tests { } #[test] - fn validate_agent_select_rejects_subagent() { + fn validate_agent_select_accepts_selectable_subagent() { let state = AgentState { snapshot: None, agents: resolve_agents(&Config::default()).unwrap_or_default(), @@ -914,14 +1035,12 @@ mod tests { plan_mode: false, plan_topic: None, }; - // "general" is a Subagent-only agent - let result = validate_agent_select("general", &state); - assert!(result.is_err()); - assert!(result.unwrap_err().contains("subagent-only")); + // "general" is both selectable and spawnable. + assert!(validate_agent_select("general", &state).is_ok()); } #[test] - fn validate_agent_select_accepts_primary() { + fn validate_agent_select_rejects_nonselectable_default() { let state = AgentState { snapshot: None, agents: resolve_agents(&Config::default()).unwrap_or_default(), @@ -932,8 +1051,8 @@ mod tests { plan_mode: false, plan_topic: None, }; - let result = validate_agent_select("build", &state); - assert!(result.is_ok()); + let error = validate_agent_select("build", &state).unwrap_err(); + assert!(error.contains("not selectable")); } #[test] @@ -961,13 +1080,12 @@ mod tests { } #[test] - fn validate_agent_select_rejects_hidden() { + fn validate_agent_select_accepts_hidden_selectable_agent() { let hidden_agent = codegg::agent::Agent { - git_read_only: false, name: "compaction".to_string(), hidden: true, - mode: codegg::agent::AgentMode::Primary, - description: "hidden agent".to_string(), + selectable: true, + description: "hidden but selectable".to_string(), ..Default::default() }; let state = AgentState { @@ -980,12 +1098,7 @@ mod tests { plan_mode: false, plan_topic: None, }; - let result = validate_agent_select("compaction", &state); - assert!(result.is_err()); - assert!( - result.unwrap_err().contains("hidden"), - "Error should mention hidden agent" - ); + assert!(validate_agent_select("compaction", &state).is_ok()); } #[test] diff --git a/crates/codegg-tui/src/commands/change_review.rs b/crates/codegg-tui/src/commands/change_review.rs index b0199a816..f7d692add 100644 --- a/crates/codegg-tui/src/commands/change_review.rs +++ b/crates/codegg-tui/src/commands/change_review.rs @@ -145,12 +145,7 @@ pub fn open_carried(app: &mut App, candidate: LspPreviewCandidateDto) { .map(|patch| (patch.path.clone(), patch.patch.clone())) .collect(); let parsed = parse_review(&patches); - let title = candidate.title.clone(); - let file_count = patches.len(); app.change_review_state.open_carried(candidate, parsed); - app.messages_state.toasts.info(&format!( - "Reviewing \"{title}\" — {file_count} file(s). [a]pply or Esc to reject." - )); } /// Read a pending candidate from the daemon and open its review. @@ -162,9 +157,13 @@ pub fn open_carried(app: &mut App, candidate: LspPreviewCandidateDto) { pub fn open_via_daemon(app: &mut App, preview_id: &str) { let id = preview_id.trim().to_string(); if id.is_empty() { - app.messages_state - .toasts - .info("Usage: /review-change "); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + "Usage: /review-change " + .split('\n') + .map(str::to_string) + .collect(), + ); return; } let Some(core_client) = app.core_client.clone() else { @@ -317,9 +316,6 @@ pub fn reject(app: &mut App) { return; } app.change_review_state.reject(); - app.messages_state - .toasts - .info("Change rejected — nothing was applied"); } /// Apply an accept completion, if it belongs to this review. @@ -348,11 +344,7 @@ pub fn apply_completion( app.change_review_state.request.cancel(); return; } - if refused { - app.messages_state - .toasts - .warning("The daemon refused this change — see the review for details"); - } else { + if !refused { reload_editor_after_apply(app); } } @@ -432,10 +424,13 @@ pub(crate) fn dispatch_review(app: &mut App, tail: &str) { codegg_core::frontend_action::FrontendAction::OpenReviewDialog, "", ), - _ if rest.is_empty() => app - .messages_state - .toasts - .info("Usage: /review-change [args]\nforms: patch [path], files, "), + _ if rest.is_empty() => app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + "Usage: /review-change [args]\nforms: patch [path], files, " + .split('\n') + .map(str::to_string) + .collect(), + ), _ => { // M007-H (D4): the daemon owns the preview store, so the // candidate is read from it. The TUI's own `LspTool` copy is diff --git a/crates/codegg-tui/src/commands/chat.rs b/crates/codegg-tui/src/commands/chat.rs index cbb17a74d..903455755 100644 --- a/crates/codegg-tui/src/commands/chat.rs +++ b/crates/codegg-tui/src/commands/chat.rs @@ -32,6 +32,13 @@ use crate::task_lifecycle::TuiTaskKind; use codegg::protocol::core::{ChatChannelDto, ChatMessageDto, CoreRequest, CoreResponse}; use std::sync::Arc; +fn show_chat_usage(app: &mut App, message: &str) { + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec![message.to_string()], + ); +} + /// Maximum body bytes accepted by the composer (matches the daemon /// bound; oversized input fails fast with a typed error and the draft /// retained instead of a wasted round-trip). @@ -137,9 +144,6 @@ pub(crate) fn start_chat_history(app: &mut App, project_id: String) { app.chat.begin_history(&project_id, &bind_channel) }; let Some(request_id) = request_id else { - app.messages_state - .toasts - .warning("Invalid project locator — chat history not loaded"); return; }; let reconnect_epoch = app.chat.reconnect_epoch; @@ -423,9 +427,6 @@ pub(crate) fn apply_chat_history_loaded( false, reconnect_epoch, ); - app.messages_state - .toasts - .warning(&format!("Chat history failed: {err}")); } refresh_chat_panel(app); } @@ -637,9 +638,6 @@ pub(crate) fn apply_chat_sync_loaded( false, reconnect_epoch, ); - app.messages_state - .toasts - .warning(&format!("Chat sync failed: {err}")); refresh_chat_panel(app); } } @@ -658,9 +656,7 @@ pub(crate) fn start_chat_send( ) { let trimmed = body.trim().to_string(); if trimmed.is_empty() { - app.messages_state - .toasts - .warning("Usage: /chat send — message body is empty"); + show_chat_usage(app, "Usage: /chat send — message body is empty"); return; } if trimmed.len() > CHAT_COMPOSER_MAX_BYTES { @@ -669,9 +665,6 @@ pub(crate) fn start_chat_send( trimmed.clone(), "chat_body_too_large: message exceeds 8 KiB".to_string(), ); - app.messages_state - .toasts - .warning("Message exceeds 8 KiB and was not sent — draft retained; shorten and retry"); refresh_chat_panel(app); return; } @@ -680,9 +673,6 @@ pub(crate) fn start_chat_send( || reply.len() > crate::app::state::chat::MAX_CHAT_LOCATOR_LEN || reply.bytes().any(|b| b == 0 || b.is_ascii_control()) { - app.messages_state - .toasts - .warning("Invalid reply target — message not sent"); return; } } @@ -700,9 +690,6 @@ pub(crate) fn start_chat_send( trimmed.clone(), "Core unavailable — check daemon status with /doctor".to_string(), ); - app.messages_state - .toasts - .warning("Chat send failed: core unavailable — draft retained"); refresh_chat_panel(app); return; } @@ -822,7 +809,7 @@ pub(crate) fn apply_chat_message_sent( project_id: String, channel_id: String, message: Option, - duplicate: bool, + _duplicate: bool, draft: String, error: Option, unauthorized: bool, @@ -836,9 +823,6 @@ pub(crate) fn apply_chat_message_sent( draft, "Chat unavailable — daemon does not support project chat".to_string(), ); - app.messages_state - .toasts - .warning("Chat unavailable — daemon does not support project chat; draft retained"); refresh_chat_panel(app); return; } @@ -849,9 +833,6 @@ pub(crate) fn apply_chat_message_sent( "project_not_found: not authorized for project chat".to_string(), ); // Privacy-preserving: identical message for denied vs absent. - app.messages_state - .toasts - .warning("Chat unavailable for this project — draft retained"); refresh_chat_panel(app); return; } @@ -864,23 +845,14 @@ pub(crate) fn apply_chat_message_sent( } else { channel_id.clone() }; - if app + let _ = app .chat - .apply_sent(&project_id, &channel, &message, reconnect_epoch) - && !duplicate - { - app.messages_state - .toasts - .info(&format!("Sent to chat (#{})", message.seq)); - } + .apply_sent(&project_id, &channel, &message, reconnect_epoch); refresh_chat_panel(app); return; } if let Some(err) = error { app.chat.note_failed_send(&project_id, draft, err.clone()); - app.messages_state - .toasts - .warning(&format!("Chat send failed: {err} — draft retained")); refresh_chat_panel(app); } } @@ -898,21 +870,13 @@ pub(crate) fn start_chat_edit( ) { let trimmed = new_body.trim().to_string(); if trimmed.is_empty() { - app.messages_state - .toasts - .warning("Edited message body cannot be empty"); + show_chat_usage(app, "Edited message body cannot be empty"); return; } if trimmed.len() > CHAT_COMPOSER_MAX_BYTES { - app.messages_state - .toasts - .warning("Edited body exceeds 8 KiB — edit not sent"); return; } let Some(channel_id) = active_channel_for(app, &project_id) else { - app.messages_state - .toasts - .warning("No chat channel cached — open /chat first so the message window loads"); return; }; let Some(expected_revision) = app.chat.get(&project_id).and_then(|e| { @@ -921,15 +885,13 @@ pub(crate) fn start_chat_edit( .find(|m| m.message_id == message_id) .map(|m| m.revision) }) else { - app.messages_state - .toasts - .warning("Message not in the local window — run /chat history first, then retry"); + show_chat_usage( + app, + "Message not in the local window — run /chat history first, then retry", + ); return; }; if app.core_client.is_none() { - app.messages_state - .toasts - .warning("Chat edit failed: core unavailable"); return; } let reconnect_epoch = app.chat.reconnect_epoch; @@ -1024,11 +986,7 @@ pub(crate) fn apply_chat_edit_finished( return; } if let Some(message) = message { - if app.chat.apply_event_edited(&message) { - app.messages_state - .toasts - .info(&format!("Edited message (r{})", message.revision)); - } + let _ = app.chat.apply_event_edited(&message); refresh_chat_panel(app); let _ = (project_id, channel_id); return; @@ -1049,9 +1007,6 @@ pub(crate) fn start_chat_redact( reason: Option, ) { let Some(channel_id) = active_channel_for(app, &project_id) else { - app.messages_state - .toasts - .warning("No chat channel cached — open /chat first so the message window loads"); return; }; let expected_revision = app.chat.get(&project_id).and_then(|e| { @@ -1061,9 +1016,6 @@ pub(crate) fn start_chat_redact( .map(|m| m.revision) }); if app.core_client.is_none() { - app.messages_state - .toasts - .warning("Chat redact failed: core unavailable"); return; } let reconnect_epoch = app.chat.reconnect_epoch; @@ -1152,12 +1104,9 @@ pub(crate) fn apply_chat_redact_finished( return; } if error.is_none() { - if app + let _ = app .chat - .apply_event_redacted(&project_id, &channel_id, &message_id, revision) - { - app.messages_state.toasts.info("Message redacted"); - } + .apply_event_redacted(&project_id, &channel_id, &message_id, revision); refresh_chat_panel(app); return; } @@ -1180,18 +1129,10 @@ pub(crate) fn start_chat_read(app: &mut App, project_id: String) { (channel, newest) } None => { - app.messages_state - .toasts - .info("No chat channel cached — open /chat first"); return; } }, - None => { - app.messages_state - .toasts - .info("No chat loaded for this project — open /chat first"); - return; - } + None => return, }; if app.core_client.is_none() { // Local-only fallback still clears the badge optimistically; @@ -1278,15 +1219,9 @@ pub(crate) fn apply_chat_read_marker_set( /// Set or clear the caller's ephemeral composing lease (content-free). pub(crate) fn start_chat_composing(app: &mut App, project_id: String, composing: bool) { let Some(channel_id) = active_channel_for(app, &project_id) else { - app.messages_state - .toasts - .warning("No chat channel cached — open /chat first so the channel resolves"); return; }; if app.core_client.is_none() { - app.messages_state - .toasts - .warning("Chat composing failed: core unavailable"); return; } let core_client = app.core_client.clone(); @@ -1490,15 +1425,9 @@ pub(crate) fn start_chat_switch_channel(app: &mut App, project_id: String, chann /// issuing a round-trip that would fail opaquely. pub(crate) fn start_chat_load_older(app: &mut App, project_id: String) { if !app.chat.backward_paging { - app.messages_state.toasts.warning( - "This daemon does not support loading older chat history — it must be restarted or upgraded", - ); return; } let Some(channel_id) = active_channel_for(app, &project_id) else { - app.messages_state - .toasts - .warning("No chat channel loaded — nothing older to fetch"); return; }; // Anchor strictly before the oldest retained message so the page @@ -1508,9 +1437,6 @@ pub(crate) fn start_chat_load_older(app: &mut App, project_id: String) { .get(&project_id) .and_then(|entry| entry.messages.front().map(|m| m.seq)); let Some(request_id) = app.chat.begin_history_older(&project_id, &channel_id) else { - app.messages_state - .toasts - .warning("Invalid channel locator — older history not loaded"); return; }; let reconnect_epoch = app.chat.reconnect_epoch; @@ -1866,16 +1792,14 @@ pub(crate) fn start_chat_action_list( ) { if let Some(ref target) = message_id { if target.is_empty() || target.len() > 128 { - app.messages_state - .toasts - .warning("Usage: /chat actions [message-id] — invalid message id"); + show_chat_usage( + app, + "Usage: /chat actions [message-id] — invalid message id", + ); return; } } let Some(request_id) = app.chat.begin_action(&project_id) else { - app.messages_state - .toasts - .warning("Invalid project for chat action list"); return; }; let reconnect_epoch = app.chat.reconnect_epoch; @@ -2055,9 +1979,6 @@ pub(crate) fn dispatch_chat_send(app: &mut App, argument: &str) { close_command_mode(app); let body = argument.to_string(); let Some(project_id) = app.chat_target_project_id() else { - app.messages_state.toasts.warning( - "No project selected — select a Workspace project or open a project tab first", - ); return; }; crate::commands::chat::start_chat_send(app, project_id, body, None); @@ -2066,9 +1987,6 @@ pub(crate) fn dispatch_chat_send(app: &mut App, argument: &str) { pub(crate) fn dispatch_chat_history(app: &mut App) { close_command_mode(app); let Some(project_id) = app.chat_target_project_id() else { - app.messages_state.toasts.warning( - "No project selected — select a Workspace project or open a project tab first", - ); return; }; let workspace_active = crate::commands::workspace_dashboard::is_workspace_view_active(app); @@ -2084,9 +2002,6 @@ pub(crate) fn dispatch_chat_history(app: &mut App) { pub(crate) fn dispatch_chat_sync(app: &mut App) { close_command_mode(app); let Some(project_id) = app.chat_target_project_id() else { - app.messages_state.toasts.warning( - "No project selected — select a Workspace project or open a project tab first", - ); return; }; crate::commands::chat::start_chat_sync(app, project_id); @@ -2095,9 +2010,6 @@ pub(crate) fn dispatch_chat_sync(app: &mut App) { pub(crate) fn dispatch_chat_read(app: &mut App) { close_command_mode(app); let Some(project_id) = app.chat_target_project_id() else { - app.messages_state.toasts.warning( - "No project selected — select a Workspace project or open a project tab first", - ); return; }; crate::commands::chat::start_chat_read(app, project_id); @@ -2112,9 +2024,6 @@ pub(crate) fn dispatch_chat_action_list(app: &mut App, argument: &str) { Some(rest.to_string()) }; let Some(project_id) = app.chat_target_project_id() else { - app.messages_state.toasts.warning( - "No project selected — select a Workspace project or open a project tab first", - ); return; }; crate::commands::chat::start_chat_action_list(app, project_id, message_id); diff --git a/crates/codegg-tui/src/commands/compaction.rs b/crates/codegg-tui/src/commands/compaction.rs index 9a3ccadd5..5d8a118b1 100644 --- a/crates/codegg-tui/src/commands/compaction.rs +++ b/crates/codegg-tui/src/commands/compaction.rs @@ -16,9 +16,8 @@ use codegg::protocol::core::CoreResponse; /// Ask the daemon to compact this session's context. pub(crate) fn handle_compact_session(app: &mut App) { if app.session_state.session.is_none() { - app.messages_state - .toasts - .info("No session is attached, so there is nothing to compact."); + // No session means no compaction request can be issued; the empty session state is visible already. + return; } let Some(core_client) = app.core_client.clone() else { diff --git a/crates/codegg-tui/src/commands/control.rs b/crates/codegg-tui/src/commands/control.rs index 588c2002f..13dcc46d4 100644 --- a/crates/codegg-tui/src/commands/control.rs +++ b/crates/codegg-tui/src/commands/control.rs @@ -40,13 +40,20 @@ fn unauthorized_of(code: &str) -> bool { ) } +fn report_control_unavailable(app: &mut App) { + app.messages_state + .toasts + .warning("Session control is unavailable for this session (not found or not authorized)"); +} + /// Entry point for `/control` and its subcommands. `args` is the raw /// text after `/control` (possibly empty for the bare lease view). pub(crate) fn dispatch_control_command(app: &mut App, args: &str) { let Some(session_id) = app.active_session_id().map(str::to_string) else { - app.messages_state - .toasts - .info("No active session — open a session tab first"); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Control, + vec!["No active session — open a session tab first".to_string()], + ); return; }; let mut tokens = args.split_whitespace(); @@ -70,8 +77,9 @@ pub(crate) fn dispatch_control_command(app: &mut App, args: &str) { "transfer" => { let (recipient, revision, reason) = parse_transfer_args(args); let (Some(recipient), Some(revision)) = (recipient, revision) else { - app.messages_state.toasts.warning( - "Usage: /control transfer [--reason ] (see /control for revisions)", + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /control transfer [--reason ] (see /control for revisions)".to_string()], ); return; }; @@ -80,39 +88,43 @@ pub(crate) fn dispatch_control_command(app: &mut App, args: &str) { "release" => { let revision = tokens.next().unwrap_or(""); if revision.is_empty() { - app.messages_state - .toasts - .warning("Usage: /control release (see /control for the revision)"); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec![ + "Usage: /control release (see /control for the revision)" + .to_string(), + ], + ); return; } match revision.parse::() { Ok(revision) => start_control_release(app, session_id, revision), Err(_) => { - app.messages_state - .toasts - .warning("Revision must be a non-negative integer"); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec!["Revision must be a non-negative integer".to_string()], + ); } } } "takeover" => { let (revision, reason) = parse_takeover_args(args); - let Some(revision) = revision else { - app.messages_state.toasts.warning( - "Usage: /control takeover (Maintainer/Owner only)", + let Some(revision) = revision.filter(|_| !reason.trim().is_empty()) else { + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec![ + "Usage: /control takeover (Maintainer/Owner only)" + .to_string(), + ], ); return; }; - if reason.trim().is_empty() { - app.messages_state.toasts.warning( - "Usage: /control takeover (Maintainer/Owner only)", - ); - return; - } start_control_takeover(app, session_id, revision, reason); } _ => { - app.messages_state.toasts.warning( - "Usage: /control, /control request [message], /control transfer [--reason ], /control release , /control takeover ", + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /control, /control request [message], /control transfer [--reason ], /control release , /control takeover ".to_string()], ); } } @@ -586,9 +598,7 @@ pub(crate) fn apply_control_loaded( } if let Some(error) = error { if unauthorized { - app.messages_state.toasts.warning( - "Session control is unavailable for this session (not found or not authorized)", - ); + report_control_unavailable(app); } else if unsupported { app.messages_state.toasts.warning( "Session control requires a newer daemon (session_control.v1 unsupported)", @@ -624,9 +634,7 @@ pub(crate) fn apply_control_mutation( } if let Some(error) = error { if unauthorized { - app.messages_state.toasts.warning( - "Session control is unavailable for this session (not found or not authorized)", - ); + report_control_unavailable(app); } else { app.messages_state.toasts.warning(&error); } diff --git a/crates/codegg-tui/src/commands/diagnostics.rs b/crates/codegg-tui/src/commands/diagnostics.rs index e5bbdcfc9..508dca7a2 100644 --- a/crates/codegg-tui/src/commands/diagnostics.rs +++ b/crates/codegg-tui/src/commands/diagnostics.rs @@ -141,7 +141,7 @@ pub(crate) fn request_lsp_server_status( return; } let Some(lsp_tool) = app.lsp_tool.clone() else { - app.messages_state.toasts.info("LSP not available"); + crate::commands::lsp::show_lsp_unavailable(app); return; }; let tx = app.tui_cmd_tx.clone(); @@ -254,7 +254,7 @@ pub(crate) fn request_lsp_restart(app: &mut App, server_id: String) { return; } let Some(lsp_tool) = app.lsp_tool.clone() else { - app.messages_state.toasts.info("LSP not available"); + crate::commands::lsp::show_lsp_unavailable(app); return; }; let tx = app.tui_cmd_tx.clone(); @@ -499,9 +499,10 @@ pub(crate) async fn handle_run_doctor(app: &mut App) { let config = match codegg::config::schema::Config::load() { Ok(c) => c, Err(e) => { - app.messages_state - .toasts - .error(&format!("doctor: failed to load config: {e}")); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::DoctorReport, + vec![format!("doctor: failed to load config: {e}")], + ); return; } }; @@ -534,7 +535,10 @@ pub(crate) async fn handle_run_doctor(app: &mut App) { } let summary = lines.join("\n"); - app.messages_state.toasts.info(&summary); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::DoctorReport, + summary.split('\n').map(str::to_string).collect(), + ); } pub(crate) fn start_run_doctor(app: &mut App) { @@ -599,21 +603,19 @@ pub(crate) fn start_run_doctor(app: &mut App) { } pub(crate) fn apply_doctor_result(app: &mut App, summary: String, is_error: bool) { + let lines: Vec = summary.split('\n').map(str::to_string).collect(); if is_error { - app.messages_state.toasts.error(&summary); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::DoctorReport, + lines, + ); } else { - let lines: Vec = summary.lines().map(|s| s.to_string()).collect(); - if lines.len() > 2 { - app.open_info_dialog( - crate::components::dialogs::info::InfoType::DoctorReport, - lines, - ); - } else { - app.messages_state.toasts.info(&summary); - } + app.show_short_or_info( + crate::components::dialogs::info::InfoType::DoctorReport, + lines, + ); } } - /// Render the tool contracts the daemon publishes for this session. /// /// The published caller policy is the string this list has always shown @@ -668,7 +670,7 @@ pub(crate) fn dispatch_doctor(app: &mut App) { pub(crate) fn dispatch_logs(app: &mut App) { app.ui_state.command_mode = false; - app.open_logs_window(); + app.open_logs_window(crate::app::LogsView::All); } pub(crate) fn dispatch_tool_contracts(app: &mut App) { @@ -686,6 +688,60 @@ pub(crate) fn dispatch_lsp_status(app: &mut App) { app.enqueue_tui_command(TuiCommand::LspStatusDetailRequested); } +pub(crate) fn dispatch_advisor_status(app: &mut App, argument: &str) { + app.ui_state.command_mode = false; + let Some(client) = app.core_client.clone() else { + app.messages_state + .toasts + .error("advisor: not connected to a core client"); + return; + }; + let scope = crate::command_route::scope_for(app); + let tx = app.tui_cmd_tx.clone(); + let argument = argument.to_owned(); + spawn_registered_tui_task( + tx, + &mut app.task_registry, + TuiTaskKind::Command, + "advisor_status", + async move { + let (message, is_error) = + match crate::command_route::send_command(&client, scope, "advisor", "", &argument) + .await + { + Ok(codegg::protocol::core::CoreResponse::CommandExecute { result }) => { + let is_error = !matches!( + result.status, + codegg::protocol::core::CommandOutcomeStatusDto::Completed + ); + let message = if result.lines.is_empty() { + result.summary + } else { + result.lines.join(" · ") + }; + (message, is_error) + } + Ok(codegg::protocol::core::CoreResponse::Error { code, message }) => { + (format!("{code}: {message}"), true) + } + Ok(response) => (format!("advisor: unexpected response: {response:?}"), true), + Err(error) => (format!("advisor: {error}"), true), + }; + Some(TuiCommand::AdvisorStatusLoaded { message, is_error }) + }, + ); +} + +pub(crate) fn apply_advisor_status(app: &mut App, message: String, is_error: bool) { + if is_error { + app.messages_state.toasts.error(&message); + } else { + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Context, + message.split('\n').map(str::to_string).collect(), + ); + } +} pub(crate) fn dispatch_nodes(app: &mut App) { // Eggwork M002: a read-only operator read of the remote // nodes' host telemetry. It never touches the queue and @@ -710,7 +766,10 @@ pub(crate) fn dispatch_tool_backends(app: &mut App) { )), ); let rendered = report.render(); - app.messages_state.toasts.info(&rendered); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::DoctorReport, + rendered.split('\n').map(str::to_string).collect(), + ); } #[cfg(test)] diff --git a/crates/codegg-tui/src/commands/diff.rs b/crates/codegg-tui/src/commands/diff.rs index 3bb7f5983..10966bb67 100644 --- a/crates/codegg-tui/src/commands/diff.rs +++ b/crates/codegg-tui/src/commands/diff.rs @@ -83,7 +83,9 @@ pub(crate) fn apply_diff_finished( if let Some(error) = error { settle(app, PlaceholderState::Failed(error.clone())); - app.messages_state.toasts.error(&error); + if !panel_waiting { + app.messages_state.toasts.error(&error); + } return; } let Some(response) = response else { @@ -97,7 +99,9 @@ pub(crate) fn apply_diff_finished( CoreResponse::Error { code, message } => { let refusal = format!("{code}: {message}"); settle(app, PlaceholderState::Failed(refusal.clone())); - app.messages_state.toasts.error(&refusal); + if !panel_waiting { + app.messages_state.toasts.error(&refusal); + } } CoreResponse::GitDiff { result } => { if result.old_content == result.new_content { @@ -107,7 +111,12 @@ pub(crate) fn apply_diff_finished( app, PlaceholderState::Empty("No changes: the working tree matches HEAD."), ); - app.messages_state.toasts.info("No changes detected"); + if !panel_waiting { + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Context, + vec!["No changes detected".to_string()], + ); + } return; } if panel_waiting && !result.files.is_empty() { @@ -139,9 +148,11 @@ pub(crate) fn apply_diff_finished( app, PlaceholderState::Failed("the diff returned an unexpected response".to_string()), ); - app.messages_state - .toasts - .warning("The diff returned an unexpected response"); + if !panel_waiting { + app.messages_state + .toasts + .warning("The diff returned an unexpected response"); + } } } } diff --git a/crates/codegg-tui/src/commands/dispatch_tests.rs b/crates/codegg-tui/src/commands/dispatch_tests.rs index 3bd376f1b..9c5b15653 100644 --- a/crates/codegg-tui/src/commands/dispatch_tests.rs +++ b/crates/codegg-tui/src/commands/dispatch_tests.rs @@ -24,6 +24,34 @@ fn fixture() -> App { app } +/// The same fixture, with a session bound. +/// +/// Session-scoped commands refuse on a sessionless frontend (the reachability +/// loop below proves each refusal is silent), so a fixture with no session +/// cannot see what they do when one is bound. This one can, and it is what the +/// reachability loop uses: a command that reaches its handler must leave a +/// trace, and most of them need a session to reach it at all. +fn fixture_with_session() -> App { + let mut app = fixture(); + app.session_state.session = Some(codegg::session::Session { + id: "fixture-session".into(), + project_id: "fixture-project".into(), + workspace_id: Some("fixture-workspace".into()), + directory: "/tmp".into(), + ..Default::default() + }); + // The active tab carries the daemon-typed ids that `active_project_id`, + // `active_workspace_id` and `active_session_id` read. `new_for_testing` + // leaves all three `None`, so a session-scoped command that resolves its + // scope from the tab finds nothing to address. + if let Some(tab) = app.project_tabs.active_mut() { + tab.project_id = Some("fixture-project".into()); + tab.workspace_id = Some("fixture-workspace".into()); + tab.session_id = Some("fixture-session".into()); + } + app +} + /// Every observable a dispatched command can leave behind. /// /// Deliberately wider than the three fields the teardown touches: an action @@ -34,6 +62,8 @@ struct Effect { toasts: Vec, dialog: String, dialog_open: bool, + info_lines: Vec, + pending_logs_view: String, command_mode: bool, prompt: String, completions: bool, @@ -43,6 +73,12 @@ struct Effect { tasks: usize, timestamps: bool, thinking: bool, + /// The selected side panel. `/toast` and `/tasks` open one, and the + /// pending-view field alone does not prove it: selecting the panel + /// consumes that field, so `pending_logs_view` returns to `None` either + /// way. The panel is where the message actually lands. + panel: String, + tts: bool, } fn effect(app: &mut App) -> Effect { @@ -61,6 +97,13 @@ fn effect(app: &mut App) -> Effect { .collect(), dialog: format!("{:?}", app.ui_state.dialog), dialog_open: app.ui_state.dialog.is_open(), + info_lines: app + .focus_manager + .with_component::(|dialog| { + dialog.content_lines().to_vec() + }) + .unwrap_or_default(), + pending_logs_view: format!("{:?}", app.pending_logs_view), command_mode: app.ui_state.command_mode, prompt: app.prompt_state.prompt.get_text(), completions: app.prompt_state.show_completions, @@ -70,6 +113,8 @@ fn effect(app: &mut App) -> Effect { tasks: app.task_registry.active_count(), timestamps: app.ui_state.show_timestamps, thinking: app.ui_state.show_thinking, + panel: format!("{:?}", app.panel_host.active()), + tts: app.ui_state.tts_enabled, } } @@ -83,6 +128,16 @@ fn toast_lines(effect: &Effect) -> String { effect.toasts.join("\n") } +fn displayed_text(effect: &Effect) -> String { + effect + .toasts + .iter() + .chain(&effect.info_lines) + .cloned() + .collect::>() + .join("\n") +} + #[test] fn close_command_mode_clears_all_three_fields() { let mut app = App::new_for_testing("/tmp".into()); @@ -116,16 +171,70 @@ const DAEMON_ONLY_NO_EFFECT: &[(&str, &str)] = &[( connection means there is nothing to refresh", )]; +/// The actions that legitimately change nothing when no turn is in flight. +/// +/// `/stop` and `/start` address a turn; the fixture has none running, so both +/// refuse before they do anything. They used to answer with a toast +/// ("Nothing to stop - the agent is not working"), which the +/// notification-surface workstream removed: the turn state is already on +/// screen, and the request was the user's own. Silence is the design, not an +/// omission — an entry here still fails the loop once the action starts +/// changing state. +const IDLE_TURN_NO_EFFECT: &[(&str, &str)] = &[ + ( + "Stop", + "stopping a turn needs a turn in flight, and the idle state is the visible \ + explanation for the refusal", + ), + ( + "StartTurn", + "carrying on needs a stopped turn, and there is none to carry on from", + ), +]; + +/// The actions that legitimately change nothing in this fixture. +/// +/// Each needs a surface the fixture does not own: an observation in flight, a +/// daemon-supplied chat binding, or a transcript with content in it. They all +/// ended in a toast once, and that toast was the only thing they wrote — which +/// is why the notification-surface workstream removed it and why this fixture +/// stopped seeing them. An entry still fails the loop once the action starts +/// changing state, so a record cannot outlive the limitation that justified +/// it. +const SURFACE_NOT_IN_THIS_FIXTURE: &[(&str, &str)] = &[ + ( + "StopObserving", + "there is no observation to stop, and the stopped state is the visible \ + explanation", + ), + ( + "ChatSync", + "the chat surface is bound to a project chat target, which is a daemon \ + binding this fixture has none of", + ), + ( + "ChatRead", + "reading chat needs the same daemon-supplied chat target as ChatSync", + ), + ( + "ExpandAllDisclosures", + "expanding every disclosure needs a transcript with a disclosure in it, \ + and this fixture's transcript is empty", + ), +]; + #[tokio::test] async fn every_builtin_action_reaches_a_handler() { - let baseline = effect(&mut fixture()); + let baseline = effect(&mut fixture_with_session()); for action in all_builtin_variants() { let name = format!("{action:?}"); - let mut app = fixture(); + let mut app = fixture_with_session(); app.dispatch_builtin_command(action, None); let observed = effect(&mut app); match DAEMON_ONLY_NO_EFFECT .iter() + .chain(IDLE_TURN_NO_EFFECT.iter()) + .chain(SURFACE_NOT_IN_THIS_FIXTURE.iter()) .find(|(recorded, _)| *recorded == name) { Some((_, reason)) => assert_eq!( @@ -179,8 +288,16 @@ async fn an_empty_argument_refuses_before_the_effect_and_a_valid_one_performs_it "an empty id must not reach the scheduler" ); assert!( - toast_lines(&refused).contains("Usage: /task-del "), - "the refusal must be the same usage warning it always was" + refused.dialog_open, + "a missing task id opens its persistent usage dialog" + ); + assert!( + refused + .info_lines + .join("\n") + .contains("Usage: /task-del "), + "the refusal remains readable in the usage dialog, got {:?}", + refused.info_lines ); let accepted = dispatch(B::TaskDel, Some("7")); @@ -216,9 +333,11 @@ async fn an_empty_argument_refuses_before_the_effect_and_a_valid_one_performs_it "{action:?} must refuse before it enqueues anything" ); assert!( - toast_lines(&refused).contains(usage), - "{action:?} must explain the missing argument: {:?}", - refused.toasts + displayed_text(&refused).contains(usage), + "{action:?} must explain the missing argument on its visible surface: \ + toasts={:?}, info={:?}", + refused.toasts, + refused.info_lines ); } } @@ -239,18 +358,27 @@ async fn one_representative_command_per_family_reaches_its_stated_state() { // off — the toggle is the observable, not a fixed literal. let timestamps = dispatch(B::Timestamps, None); assert!(timestamps.timestamps, "/timestamps shows them on first use"); - assert_eq!(timestamps.toasts, vec!["timestamps shown".to_string()]); + assert!( + timestamps.toasts.is_empty(), + "the visible timestamp state is enough; a direct action must not toast its acknowledgement" + ); let thinking = dispatch(B::Thinking, None); assert!( !thinking.thinking, "/thinking flips the fixture's default instead of assigning a constant" ); - assert_eq!(thinking.toasts, vec!["thinking hidden".to_string()]); + assert!( + thinking.toasts.is_empty(), + "the visible thinking state is enough; a direct action must not toast its acknowledgement" + ); // Appearance: `/tui` toggles fullscreen rather than opening anything. let tui = dispatch(B::Tui, None); assert!(tui.fullscreen, "/tui enters fullscreen from the default"); - assert_eq!(tui.toasts, vec!["Fullscreen mode enabled".to_string()]); + assert!( + tui.toasts.is_empty(), + "the fullscreen state is already visible; a direct action must not toast its acknowledgement" + ); // Diagnostics: `/doctor` is a daemon round-trip, not a local render. let doctor = dispatch(B::Doctor, None); @@ -265,9 +393,8 @@ async fn one_representative_command_per_family_reaches_its_stated_state() { let chat = dispatch(B::Chat, Some("send hello")); assert!(chat.queued.is_empty(), "no project means no chat send"); assert!( - toast_lines(&chat).contains("No project selected"), - "the refusal names the missing project: {:?}", - chat.toasts + chat.toasts.is_empty(), + "a direct /chat-send with no project must not create a transient toast" ); // Editor: `/open` with no path keeps the composer's key. diff --git a/crates/codegg-tui/src/commands/edit_history.rs b/crates/codegg-tui/src/commands/edit_history.rs index 57eb36b00..04445f94b 100644 --- a/crates/codegg-tui/src/commands/edit_history.rs +++ b/crates/codegg-tui/src/commands/edit_history.rs @@ -13,9 +13,6 @@ pub(crate) fn dispatch_edit_undo(app: &mut App, argument: &str) { ) { (Some(sid), Some(wid)) => (sid, wid), _ => { - app.messages_state - .toasts - .warning("No active session/workspace for undo"); return; } }; @@ -28,9 +25,6 @@ pub(crate) fn dispatch_edit_undo(app: &mut App, argument: &str) { workspace_id, }, ); - app.messages_state - .toasts - .info("Undoing latest checkpoint..."); } else { let _ = send_tui( tx, @@ -40,9 +34,6 @@ pub(crate) fn dispatch_edit_undo(app: &mut App, argument: &str) { workspace_id, }, ); - app.messages_state - .toasts - .info(&format!("Undoing checkpoint {arg}...")); } } else { app.messages_state @@ -60,9 +51,6 @@ pub(crate) fn dispatch_edit_reapply(app: &mut App, argument: &str) { ) { (Some(sid), Some(wid)) => (sid, wid), _ => { - app.messages_state - .toasts - .warning("No active session/workspace for reapply"); return; } }; @@ -75,9 +63,6 @@ pub(crate) fn dispatch_edit_reapply(app: &mut App, argument: &str) { workspace_id, }, ); - app.messages_state - .toasts - .info("Reapplying latest undone checkpoint..."); } else { let _ = send_tui( tx, @@ -87,9 +72,6 @@ pub(crate) fn dispatch_edit_reapply(app: &mut App, argument: &str) { workspace_id, }, ); - app.messages_state - .toasts - .info(&format!("Reapplying checkpoint {arg}...")); } } else { app.messages_state @@ -107,9 +89,6 @@ pub(crate) fn dispatch_edit_checkpoints(app: &mut App, argument: &str) { ) { (Some(sid), Some(wid)) => (sid, wid), _ => { - app.messages_state - .toasts - .warning("No active session/workspace for checkpoints"); return; } }; @@ -121,7 +100,6 @@ pub(crate) fn dispatch_edit_checkpoints(app: &mut App, argument: &str) { workspace_id, }, ); - app.messages_state.toasts.info("Loading checkpoints..."); } else { app.messages_state .toasts diff --git a/crates/codegg-tui/src/commands/editor.rs b/crates/codegg-tui/src/commands/editor.rs index 0ccfcf68f..8435d5497 100644 --- a/crates/codegg-tui/src/commands/editor.rs +++ b/crates/codegg-tui/src/commands/editor.rs @@ -157,9 +157,6 @@ fn open_document_as_tab(app: &mut App, path: &str, scope: DocumentScope) -> bool && app.editor_state.path.as_deref() == Some(path) && app.editor_state.scope == scope { - app.messages_state - .toasts - .info("Document is already open in the editor"); enter_editor_normal(app); return false; } @@ -1590,9 +1587,9 @@ fn structural_selection_step(app: &mut App, expand: bool) { EditorLspReadArgument::None, ); } else { - app.messages_state - .toasts - .info("No current syntax selection to shrink"); + app.editor_state.notice = Some(EditorNotice::Note( + "No current syntax selection to shrink".to_string(), + )); } return; } @@ -1616,11 +1613,12 @@ fn structural_selection_step(app: &mut App, expand: bool) { index.checked_sub(1) }; let Some(next) = next else { - app.messages_state.toasts.info(if expand { + let message = if expand { "No larger syntax range is available" } else { "No smaller syntax range is available" - }); + }; + app.editor_state.notice = Some(EditorNotice::Note(message.to_string())); return; }; app.editor_state.lsp.selection_range_index = next; @@ -2169,14 +2167,14 @@ fn accept_selected_completion(app: &mut App) { || app.editor_state.generation != scope.read_scope.generation { app.editor_state.completion.clear(); - app.messages_state - .toasts - .info("Completion expired — re-trigger to refresh"); + app.editor_state.notice = Some(EditorNotice::Note( + "Completion expired — re-trigger to refresh".to_string(), + )); return; } let candidate = app.editor_state.completion.selected_candidate().cloned(); let Some(candidate) = candidate else { - app.messages_state.toasts.info("No completion selected"); + app.editor_state.notice = Some(EditorNotice::Note("No completion selected".to_string())); return; }; let edit = match &candidate.applicability { @@ -2202,7 +2200,6 @@ fn accept_selected_completion(app: &mut App) { }; app.editor_state .set_notice(EditorNotice::Rejected(message.to_string())); - app.messages_state.toasts.warning(message); return; } }; @@ -2218,16 +2215,16 @@ fn accept_selected_completion(app: &mut App) { }; if attachment.document_id != scope.document_id || attachment.revision != scope.revision { app.editor_state.completion.clear(); - app.messages_state - .toasts - .info("Completion expired — re-trigger to refresh"); + app.editor_state.notice = Some(EditorNotice::Note( + "Completion expired — re-trigger to refresh".to_string(), + )); return; } let stay_insert = app.editor_state.mode() == EditorMode::Insert; let Some(resolved) = editor::resolve_completion_edit(&snapshot, &edit, stay_insert) else { - app.messages_state - .toasts - .warning("Completion no longer applies to the current text"); + app.editor_state.notice = Some(EditorNotice::Rejected( + "Completion no longer applies to the current text".to_string(), + )); return; }; submit_edit(&mut app.editor_state, resolved); @@ -2393,7 +2390,6 @@ where + 'static, { if !app.editor_state.is_open() { - app.messages_state.toasts.info("No document is open"); return; } if app.editor_state.is_busy() { @@ -2555,14 +2551,6 @@ pub(crate) fn apply_document_deleted( false, super::agents::AssetRefreshTrigger::Internal, ); - app.messages_state.toasts.info( - format!( - "Deleted {} ({})", - path, - crate::commands::agent_editor::scope_label(scope) - ) - .as_str(), - ); } } @@ -3011,13 +2999,13 @@ fn apply_clipboard_text(app: &mut App, verb: ClipboardVerb, read: Option return; } let Some(text) = read else { - app.messages_state - .toasts - .warning("Clipboard unavailable — nothing to paste"); + app.editor_state.notice = Some(EditorNotice::Note( + "Clipboard unavailable — nothing to paste".to_string(), + )); return; }; if text.is_empty() { - app.messages_state.toasts.warning("Clipboard is empty"); + app.editor_state.notice = Some(EditorNotice::Note("Clipboard is empty".to_string())); return; } apply_paste_text(app, verb, &text); @@ -3043,7 +3031,9 @@ fn apply_register_text(app: &mut App, verb: ClipboardVerb, register: RegisterNam return; }; match read { - Err(refusal) => app.messages_state.toasts.warning(&refusal.message()), + Err(refusal) => { + app.editor_state.notice = Some(EditorNotice::Note(refusal.message())); + } Ok(text) => apply_paste_text(app, verb, &text), } } @@ -4029,7 +4019,8 @@ fn dispatch_editor_key(app: &mut App, key: KeyEvent) -> bool { } KeyCode::F(7) => { let Some(query) = editor_word_at_cursor(&app.editor_state) else { - app.messages_state.toasts.info("No symbol at the cursor"); + app.editor_state.notice = + Some(EditorNotice::Note("No symbol at the cursor".to_string())); return true; }; start_editor_lsp_read( @@ -4336,7 +4327,8 @@ fn run_editor_pending_effect(app: &mut App, effect: EditorPendingEffect) { // picker to supply one. The token under the cursor is what F7 // already uses, and it is the only query a keypress can carry. let Some(query) = editor_word_at_cursor(&app.editor_state) else { - app.messages_state.toasts.info("No symbol at the cursor"); + app.editor_state.notice = + Some(EditorNotice::Note("No symbol at the cursor".to_string())); return; }; start_editor_lsp_read( @@ -4628,9 +4620,9 @@ fn open_editor_rename_prompt(app: &mut App) { /// `/` search and the LSP jumps follow, so all three land the same way. fn goto_editor_line(app: &mut App, line: usize) { if line == 0 { - app.messages_state - .toasts - .warning("`:0` is not a line — the first line is `:1`"); + app.editor_state.notice = Some(EditorNotice::Note( + "`:0` is not a line — the first line is `:1`".to_string(), + )); return; } let Some(session) = app.editor_state.session.as_mut() else { @@ -4688,9 +4680,9 @@ fn run_editor_command(app: &mut App, command: EditorCommandName, argument: Optio } EditorCommandName::Open => { let Some(path) = argument else { - app.messages_state - .toasts - .warning("`:open` needs a workspace-relative path"); + app.editor_state.notice = Some(EditorNotice::Note( + "`:open` needs a workspace-relative path".to_string(), + )); return; }; open_editor(app, &path); @@ -4703,16 +4695,16 @@ fn run_editor_command(app: &mut App, command: EditorCommandName, argument: Optio // would be a jump to somewhere the reader did not ask for. EditorCommandName::GotoLine => { let Some(argument) = argument else { - app.messages_state - .toasts - .warning("`:goto` needs a line number"); + app.editor_state.notice = Some(EditorNotice::Note( + "`:goto` needs a line number".to_string(), + )); return; }; let trimmed = argument.trim(); let Ok(line) = trimmed.parse::() else { - app.messages_state - .toasts - .warning(&format!("`:{trimmed}` is not a line number")); + app.editor_state.notice = Some(EditorNotice::Note(format!( + "`:{trimmed}` is not a line number" + ))); return; }; goto_editor_line(app, line); @@ -4734,7 +4726,7 @@ fn run_editor_command(app: &mut App, command: EditorCommandName, argument: Optio | EditorCommandName::SelectRegex => { let Some(pattern) = argument.filter(|value| !value.trim().is_empty()) else { let message = format!("`:{}` needs a regex pattern", command.spec()); - app.messages_state.toasts.warning(&message); + app.editor_state.notice = Some(EditorNotice::Note(message)); return; }; run_selection_regex(&mut app.editor_state, command, pattern); @@ -4755,7 +4747,7 @@ fn run_editor_command(app: &mut App, command: EditorCommandName, argument: Optio let name = match checked_new_name(argument.as_deref()) { Ok(name) => name, Err(reason) => { - app.messages_state.toasts.warning(&reason); + app.editor_state.notice = Some(EditorNotice::Note(reason)); return; } }; @@ -4822,9 +4814,9 @@ fn refuse_quit_with_unsaved_draft(app: &mut App) -> bool { crate::app::state::editor::EditorStatus::DirtyLocal | crate::app::state::editor::EditorStatus::Flushing ) { - app.messages_state - .toasts - .warning("Unsaved changes — use `:w` to write first, or `:q!` to discard them"); + app.editor_state.notice = Some(EditorNotice::Note( + "Unsaved changes — use `:w` to write first, or `:q!` to discard them".to_string(), + )); return true; } false @@ -4984,9 +4976,9 @@ fn open_selected_lsp_target(app: &mut App) { _ => None, }); let Some(target) = target else { - app.messages_state - .toasts - .info("This result has no validated workspace-relative target"); + app.editor_state.notice = Some(EditorNotice::Note( + "This result has no validated workspace-relative target".to_string(), + )); return; }; match normalize_relative_path(&target) { @@ -5005,10 +4997,9 @@ fn open_selected_lsp_target(app: &mut App) { /// review it opens is M016's carried review, so the candidate reviewed is /// the candidate applied. /// -/// An action with no candidate is not a failure. The panel already said why -/// it cannot be applied, and this says the same thing in the place the user -/// pressed the key — the same words, from the same helper, so the two -/// cannot drift apart. +/// An action with no candidate is not a failure. The panel already says why +/// it cannot be applied, so this keypress does not echo that reason in another +/// surface. fn open_selected_code_action(app: &mut App) { use codegg::protocol::lsp::LspReadPayloadDto; let Some(actions) = app @@ -5024,21 +5015,19 @@ fn open_selected_code_action(app: &mut App) { return; }; let Some(action) = actions.get(app.editor_state.lsp.selected_index) else { - app.messages_state.toasts.info("No code action is selected"); + app.editor_state.notice = + Some(EditorNotice::Note("No code action is selected".to_string())); return; }; - if let Some(reason) = crate::editor_lsp::code_action_unavailable_reason(action) { - app.messages_state - .toasts - .info(&format!("\"{}\" cannot be applied: {reason}", action.title)); + if crate::editor_lsp::code_action_unavailable_reason(action).is_some() { return; } let Some(candidate) = action.candidate.clone() else { // A daemon-minted action carries a candidate or a reason, never // neither. Refuse rather than open a review of nothing. - app.messages_state - .toasts - .info("This code action carries no preview"); + app.editor_state.notice = Some(EditorNotice::Note( + "This code action carries no preview".to_string(), + )); return; }; crate::commands::change_review::open_carried(app, candidate); @@ -7444,7 +7433,7 @@ fn yank_editor_ranges_with( }; let text = read_range_text(&snapshot, &ranges); if text.is_empty() { - app.messages_state.toasts.warning("Nothing to yank"); + app.editor_state.notice = Some(EditorNotice::Note("Nothing to yank".to_string())); return; } publish_yank(app, target, &text, copy); @@ -7487,9 +7476,10 @@ fn publish_yank( // stated refusal, not a write to a register that would then lie // about the last search. RegisterName::Search => { - app.messages_state - .toasts - .warning("the search register is read-only — it holds the last search pattern"); + app.editor_state.notice = Some(EditorNotice::Rejected( + "the search register is read-only — it holds the last search pattern" + .to_string(), + )); return; } named => { @@ -7535,12 +7525,11 @@ fn note_truncation( } } -/// Say what the gesture did, in one toast. +/// Record a refusal in the editor's persistent notice surface. /// -/// A truncation and a refused clipboard are both refusals and both belong on -/// screen, so they compose into one sentence rather than two toasts racing -/// each other. A write that reached no register and no clipboard is the -/// `space` family's plain copy, and keeps its original wording. +/// A successful yank needs no echo: its text is already in the selected +/// register (and, when available, the clipboard). Failures stay visible in +/// the editor instead of producing a toast for the direct keypress. fn report_yank( app: &mut App, bytes: usize, @@ -7556,26 +7545,18 @@ fn report_yank( if let Some(error) = clipboard { message.push_str(&format!("; clipboard unavailable: {error}")); } - app.messages_state.toasts.warning(&message); + app.editor_state.notice = Some(EditorNotice::Rejected(message)); return; } - match (written, clipboard) { - (Some(register), Some(error)) => app.messages_state.toasts.warning(&format!( - "Copied {bytes} bytes to {}; clipboard unavailable: {error}", - register.label() - )), - (Some(register), None) => app - .messages_state - .toasts - .info(&format!("Copied {bytes} bytes to {}", register.label())), - (None, Some(error)) => app - .messages_state - .toasts - .warning(&format!("Clipboard unavailable: {error}")), - (None, None) => app - .messages_state - .toasts - .info(&format!("Copied {bytes} bytes")), + if let Some(error) = clipboard { + let message = match written { + Some(register) => format!( + "Copied {bytes} bytes to {}; clipboard unavailable: {error}", + register.label() + ), + None => format!("Clipboard unavailable: {error}"), + }; + app.editor_state.notice = Some(EditorNotice::Rejected(message)); } } @@ -7683,9 +7664,10 @@ pub(crate) fn dispatch_open_document(app: &mut App, argument: &str) { // response. It issues no open request of its own. let path = argument; if path.is_empty() { - app.messages_state - .toasts - .info("Usage: /open (e.g. /open src/lib.rs)"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /open (e.g. /open src/lib.rs)".to_string()], + ); } else { crate::commands::editor::open_editor_via_command(app, path); } @@ -11093,10 +11075,17 @@ mod tests { park_on_app(&mut app, 0); apply_clipboard_text(&mut app, ClipboardVerb::PasteAfter, None); assert_eq!(text_on_app(&app), "abc"); - assert_eq!( - app.messages_state.toasts.len(), - 1, - "a clipboard the system refused must still say so" + assert!( + app.editor_state.notice.as_ref().is_some_and(|notice| { + notice + .message() + .contains("Clipboard unavailable — nothing to paste") + }), + "the failed read is stated in the editor notice" + ); + assert!( + app.messages_state.toasts.is_empty(), + "a direct paste is not toasted" ); let (state, _daemon) = opened_writer("abc").await; @@ -11104,10 +11093,16 @@ mod tests { park_on_app(&mut app, 0); apply_clipboard_text(&mut app, ClipboardVerb::PasteAfter, Some(String::new())); assert_eq!(text_on_app(&app), "abc"); - assert_eq!( - app.messages_state.toasts.len(), - 1, - "a clipboard holding nothing is not the same failure, and says so too" + assert!( + app.editor_state + .notice + .as_ref() + .is_some_and(|notice| { notice.message().contains("Clipboard is empty") }), + "an empty clipboard is stated separately in the editor notice" + ); + assert!( + app.messages_state.toasts.is_empty(), + "a direct paste is not toasted" ); } @@ -11503,14 +11498,15 @@ mod tests { apply_register_text(&mut app, ClipboardVerb::PasteAfter, RegisterName::Blackhole); assert_eq!(text_on_app(&app), "alpha\nbeta\n", "the paste refused"); let reported = app - .messages_state - .toasts - .history() - .map(|toast| toast.message.clone()) - .collect::>(); + .editor_state + .notice + .as_ref() + .map(|notice| notice.message()); assert!( - reported.iter().any(|message| message.contains("blackhole")), - "and said why: {reported:?}" + reported + .as_deref() + .is_some_and(|message| message.contains("blackhole")), + "and said why in the editor notice: {reported:?}" ); } @@ -11530,21 +11526,21 @@ mod tests { ); assert_eq!(text_on_app(&app), "abc", "nothing was inserted"); assert!( - app.messages_state - .toasts - .history() - .any(|toast| toast.message.contains("register `q` is empty")), - "the refusal names the register" + app.editor_state + .notice + .as_ref() + .is_some_and(|notice| { notice.message().contains("register `q` is empty") }), + "the refusal names the register in the editor notice" ); apply_register_text(&mut app, ClipboardVerb::PasteBefore, RegisterName::Search); assert_eq!(text_on_app(&app), "abc"); assert!( - app.messages_state - .toasts - .history() - .any(|toast| toast.message.contains("no search has been accepted")), - "`/` before a search says so" + app.editor_state + .notice + .as_ref() + .is_some_and(|notice| { notice.message().contains("no search has been accepted") }), + "`/` before a search says so in the editor notice" ); let presentation = app @@ -11610,11 +11606,11 @@ mod tests { } assert_eq!(text_on_app(&app), "abc"); assert!( - app.messages_state - .toasts - .history() - .any(|toast| toast.message.contains("register `a` is empty")), - "the route reaches the register paste and reports the refusal" + app.editor_state + .notice + .as_ref() + .is_some_and(|notice| { notice.message().contains("register `a` is empty") }), + "the route reaches the register paste and reports the refusal in the editor" ); } @@ -15711,16 +15707,16 @@ mod tests { press_space(&mut app, 'Y'); - assert_eq!( - app.messages_state.toasts.len(), - 1, - "the refusal is reported, not swallowed" + assert!( + app.editor_state + .notice + .as_ref() + .is_some_and(|notice| { notice.message().contains("Nothing to yank") }), + "the refusal remains visible in the editor notice" ); - let toast = app.messages_state.toasts.iter().last().expect("a toast"); assert!( - toast.message.contains("Nothing to yank"), - "the message is the one `space y` uses: {:?}", - toast.message + app.messages_state.toasts.is_empty(), + "a direct yank is not toasted" ); } @@ -16696,12 +16692,18 @@ mod tests { handle_editor_key(&mut app, key(KeyCode::Enter)); assert_no_read(&mut reads).await; - let reported = reported(&app); assert!( - reported - .iter() - .any(|message| message.contains("needs a new name")), - "the refusal says what is missing, got {reported:?}" + reported(&app).is_empty(), + "the rename refusal belongs in the editor notice, not toast history" + ); + assert!( + matches!( + app.editor_state.notice.as_ref(), + Some(crate::app::state::editor::EditorNotice::Note(message)) + if message.contains("needs a new name") + ), + "the editor notice says what is missing, got {:?}", + app.editor_state.notice ); } @@ -16716,13 +16718,21 @@ mod tests { run_editor_command(&mut app, EditorCommandName::RenamePreview, Some(over_long)); assert_no_read(&mut reads).await; - let reported = reported(&app); assert!( - reported.iter().any(|message| message.contains(&format!( - "{}-byte limit", - codegg_protocol::lsp::MAX_LSP_NEW_NAME_BYTES - ))), - "the refusal names the bound, got {reported:?}" + reported(&app).is_empty(), + "the rename refusal belongs in the editor notice, not toast history" + ); + assert!( + matches!( + app.editor_state.notice.as_ref(), + Some(crate::app::state::editor::EditorNotice::Note(message)) + if message.contains(&format!( + "{}-byte limit", + codegg_protocol::lsp::MAX_LSP_NEW_NAME_BYTES + )) + ), + "the editor notice names the bound, got {:?}", + app.editor_state.notice ); } @@ -17123,17 +17133,27 @@ mod tests { !app.change_review_state.is_open(), "an action that cannot be applied must not open a review" ); - let messages: Vec = app - .messages_state - .toasts - .iter() - .map(|toast| toast.message.clone()) - .collect(); + let panel_action = + app.editor_state + .lsp + .read_result + .as_ref() + .and_then(|result| match result.payload.as_ref() { + Some(codegg::protocol::lsp::LspReadPayloadDto::CodeActions { + actions, .. + }) => actions.first(), + _ => None, + }); assert!( - messages.iter().any( - |message| message.contains("Run the test suite") && message.contains("command") - ), - "the toast must name the action and the reason, got: {messages:?}" + panel_action.is_some_and(|action| { + action.title == "Run the test suite" + && crate::editor_lsp::code_action_unavailable_reason(action).is_some() + }), + "the result panel keeps the action and its unavailable reason" + ); + assert!( + app.messages_state.toasts.is_empty(), + "the action panel already shows this reason, so it is not repeated in a toast" ); } diff --git a/crates/codegg-tui/src/commands/goals.rs b/crates/codegg-tui/src/commands/goals.rs index fd3f3bfd2..b8741c29f 100644 --- a/crates/codegg-tui/src/commands/goals.rs +++ b/crates/codegg-tui/src/commands/goals.rs @@ -9,6 +9,13 @@ use crate::async_cmd::spawn_registered_tui_task; use crate::task_lifecycle::TuiTaskKind; use codegg::protocol::core::{CoreRequest, CoreResponse}; +fn show_goal_usage(app: &mut App, message: &str) { + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec![message.to_string()], + ); +} + pub(crate) fn handle_goal_set( app: &mut App, session_id: String, @@ -16,7 +23,6 @@ pub(crate) fn handle_goal_set( objective: String, ) { let Some(core_client) = app.core_client.clone() else { - app.messages_state.toasts.warning("Core client unavailable"); return; }; tokio::spawn(async move { @@ -52,7 +58,6 @@ pub(crate) fn handle_goal_from_file( path: String, ) { let Some(core_client) = app.core_client.clone() else { - app.messages_state.toasts.warning("Core client unavailable"); return; }; tokio::spawn(async move { @@ -143,17 +148,16 @@ pub(crate) fn apply_goal_operation_finished( "show" => { if let CoreResponse::Json { data } = response { if data.get("active").and_then(|v| v.as_bool()) == Some(false) { - app.messages_state.toasts.info("No active goal"); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::GoalShow, + vec!["No active goal".to_string()], + ); } else if let Some(rendered) = data.get("rendered").and_then(|v| v.as_str()) { let lines: Vec = rendered.lines().map(|l| l.to_string()).collect(); - if lines.len() > 3 { - app.open_info_dialog( - crate::components::dialogs::info::InfoType::GoalShow, - lines, - ); - } else { - app.messages_state.toasts.info(rendered); - } + app.open_info_dialog( + crate::components::dialogs::info::InfoType::GoalShow, + lines, + ); } } } @@ -169,10 +173,13 @@ pub(crate) fn apply_goal_operation_finished( let status = data.get("status").and_then(|v| v.as_str()).unwrap_or("ok"); let label = data.get("label").and_then(|v| v.as_str()).unwrap_or("?"); let value = data.get("value").and_then(|v| v.as_i64()).unwrap_or(0); - app.messages_state.toasts.info(&format!( - "Goal budget: {} = {} (status: {})", - label, value, status - )); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::GoalShow, + vec![format!( + "Goal budget: {} = {} (status: {})", + label, value, status + )], + ); } } _ => {} @@ -436,7 +443,6 @@ pub(crate) fn apply_session_state_refreshed( #[allow(dead_code)] pub(crate) async fn handle_goal_show(app: &mut App, session_id: String) { let Some(core_client) = app.core_client.clone() else { - app.messages_state.toasts.warning("Core client unavailable"); return; }; let response = core_client @@ -448,9 +454,15 @@ pub(crate) async fn handle_goal_show(app: &mut App, session_id: String) { match response { Ok(CoreResponse::Json { data }) => { if data.get("active").and_then(|v| v.as_bool()) == Some(false) { - app.messages_state.toasts.info("No active goal"); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::GoalShow, + vec!["No active goal".to_string()], + ); } else if let Some(rendered) = data.get("rendered").and_then(|v| v.as_str()) { - app.messages_state.toasts.info(rendered); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::GoalShow, + rendered.lines().map(|line| line.to_string()).collect(), + ); } } Ok(CoreResponse::Error { message, .. }) => { @@ -467,7 +479,6 @@ pub(crate) async fn handle_goal_show(app: &mut App, session_id: String) { pub(crate) fn handle_goal_simple(app: &mut App, request: CoreRequest, label: &str) { let Some(core_client) = app.core_client.clone() else { - app.messages_state.toasts.warning("Core client unavailable"); return; }; let label = label.to_string(); @@ -550,7 +561,6 @@ pub(crate) async fn handle_refresh_session_state(app: &mut App, session_id: Stri #[allow(dead_code)] pub(crate) async fn handle_goal_checkpoint(app: &mut App, session_id: String, project_id: String) { let Some(core_client) = app.core_client.clone() else { - app.messages_state.toasts.warning("Core client unavailable"); return; }; let response = core_client @@ -579,8 +589,7 @@ pub(crate) async fn handle_goal_checkpoint(app: &mut App, session_id: String, pr } /// `/goal budget …` handler. Two flavors: -/// * `show` — fetch the active goal and render its budget/usage as -/// a toast (sidebar already shows live status). +/// * `show` — show the active goal budget/usage in a persistent dialog. /// * `raise ` — bump a single axis of the active goal's /// budget. Valid axes: `tokens`, `turns`, `tool-calls`, `wallclock`. pub(crate) fn handle_goal_budget(app: &mut App, session_id: String, subcommand: String) { @@ -594,11 +603,15 @@ pub(crate) fn handle_goal_budget(app: &mut App, session_id: String, subcommand: // GoalSnapshot already on the app, if any. if let Some(ref g) = app.active_goal { let line = crate::app::format_goal_status_line(g); - app.messages_state.toasts.info(&line); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::GoalShow, + vec![line], + ); } else { - app.messages_state - .toasts - .warning("No active goal — set one with /goal set "); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::GoalShow, + vec!["No active goal — set one with /goal set ".to_string()], + ); } return; } @@ -608,24 +621,19 @@ pub(crate) fn handle_goal_budget(app: &mut App, session_id: String, subcommand: let axis = parts.next().unwrap_or("").to_string(); let value_str = parts.next().unwrap_or("").trim(); if axis.is_empty() || value_str.is_empty() { - app.messages_state - .toasts - .warning("Usage: /goal budget raise "); + show_goal_usage( + app, + "Usage: /goal budget raise ", + ); return; } let value: i64 = match value_str.parse() { Ok(v) => v, Err(_) => { - app.messages_state - .toasts - .warning(&format!("Invalid number: {}", value_str)); return; } }; if value < 1 { - app.messages_state - .toasts - .warning("Budget must be a positive integer"); return; } let mut max_turns: Option = None; @@ -642,10 +650,13 @@ pub(crate) fn handle_goal_budget(app: &mut App, session_id: String, subcommand: } "wallclock" | "wall" => max_wallclock_secs = Some(value), _ => { - app.messages_state.toasts.warning(&format!( - "Unknown axis '{}'. Use tokens, turns, tool-calls, or wallclock.", - axis - )); + show_goal_usage( + app, + &format!( + "Unknown axis '{}'. Use tokens, turns, tool-calls, or wallclock.", + axis + ), + ); return; } } @@ -662,9 +673,7 @@ pub(crate) fn handle_goal_budget(app: &mut App, session_id: String, subcommand: return; } - app.messages_state - .toasts - .warning("Usage: /goal budget [show | raise ]"); + show_goal_usage(app, "Usage: /goal budget [show | raise ]"); } pub(crate) fn dispatch_goal(app: &mut App, argument: &str) { @@ -674,7 +683,6 @@ pub(crate) fn dispatch_goal(app: &mut App, argument: &str) { let args = parts.get(1).copied().unwrap_or("").trim(); let Some(session) = app.session_state.session.clone() else { - app.messages_state.toasts.warning("No active session"); return; }; let session_id = session.id.clone(); @@ -683,9 +691,7 @@ pub(crate) fn dispatch_goal(app: &mut App, argument: &str) { match subcmd { "set" => { if args.is_empty() { - app.messages_state - .toasts - .warning("Usage: /goal set "); + show_goal_usage(app, "Usage: /goal set "); return; } if let Some(ref tx) = app.tui_cmd_tx { @@ -701,9 +707,7 @@ pub(crate) fn dispatch_goal(app: &mut App, argument: &str) { } "from-file" => { if args.is_empty() { - app.messages_state - .toasts - .warning("Usage: /goal from-file "); + show_goal_usage(app, "Usage: /goal from-file "); return; } if let Some(ref tx) = app.tui_cmd_tx { @@ -755,9 +759,10 @@ pub(crate) fn dispatch_goal(app: &mut App, argument: &str) { } "budget" => { if args.is_empty() { - app.messages_state - .toasts - .info("Usage: /goal budget [show | raise | raise clear ]"); + show_goal_usage( + app, + "Usage: /goal budget [show | raise | raise clear ]", + ); return; } if let Some(ref tx) = app.tui_cmd_tx { @@ -797,14 +802,10 @@ pub(crate) fn dispatch_goal(app: &mut App, argument: &str) { ); } } else { - app.messages_state - .toasts - .warning("Usage: /goal or /goal set "); + show_goal_usage(app, "Usage: /goal or /goal set "); } } else { - app.messages_state - .toasts - .warning("Usage: /goal or /goal set "); + show_goal_usage(app, "Usage: /goal or /goal set "); } } } diff --git a/crates/codegg-tui/src/commands/interactive_terminal.rs b/crates/codegg-tui/src/commands/interactive_terminal.rs index 4a5a87790..36d11d71b 100644 --- a/crates/codegg-tui/src/commands/interactive_terminal.rs +++ b/crates/codegg-tui/src/commands/interactive_terminal.rs @@ -180,9 +180,6 @@ pub(crate) fn terminal_core_client( /// could never recover. pub(crate) fn start_terminal_create(app: &mut App, argv: Vec) -> bool { if argv.is_empty() { - app.messages_state - .toasts - .warning("Cannot start an interactive terminal without a command"); return false; } let workspace_id = match resolve_terminal_workspace(app) { @@ -488,18 +485,15 @@ pub(crate) fn apply_terminal_list_finished( } app.interactive_terminals.apply_list(&processes); let lines = app.interactive_terminals.list_lines(); - if lines.is_empty() { - app.messages_state - .toasts - .info("No interactive terminals in this workspace"); - } else if lines.len() > 5 { - app.open_info_dialog( - crate::components::dialogs::info::InfoType::TerminalShow, - lines, - ); + let lines = if lines.is_empty() { + vec!["No interactive terminals in this workspace".to_string()] } else { - app.messages_state.toasts.info(&lines.join("\n")); - } + lines + }; + app.open_info_dialog( + crate::components::dialogs::info::InfoType::TerminalShow, + lines, + ); } // ── Attach / resume ───────────────────────────────────────────────── @@ -1478,22 +1472,10 @@ pub(crate) fn apply_terminal_op_finished( match op.as_str() { "detach" => { app.interactive_terminals.apply_detached(&handle); - app.messages_state.toasts.info(&format!( - "Detached from {handle}; the process keeps running" - )); } "terminate" => { app.interactive_terminals .apply_terminated(&handle, exit_code, exit_signal); - app.messages_state.toasts.info(&format!( - "Terminal {handle} terminated (code={} signal={})", - exit_code - .map(|c| c.to_string()) - .unwrap_or_else(|| "-".to_string()), - exit_signal - .map(|s| s.to_string()) - .unwrap_or_else(|| "-".to_string()) - )); } "remove" => { app.interactive_terminals.apply_removed(&handle); @@ -1503,9 +1485,6 @@ pub(crate) fn apply_terminal_op_finished( app.close_dialog(); } } - app.messages_state - .toasts - .info(&format!("Terminal {handle} removed")); return; } "resize" => { @@ -1514,13 +1493,6 @@ pub(crate) fn apply_terminal_op_finished( if let (Some(cols), Some(rows)) = (cols, rows) { app.interactive_terminals .applied_resize(&handle, cols, rows); - app.messages_state - .toasts - .info(&format!("Terminal {handle} resized to {cols}x{rows}")); - } else { - app.messages_state - .toasts - .info(&format!("Terminal {handle} resized")); } } _ => {} @@ -1556,14 +1528,9 @@ pub(crate) fn handle_terminal_show(app: &mut App, handle: String) { // what made the box feel broken: keys typed in that gap went nowhere at // all, neither draft nor process. Focus is best-effort — a terminal that // cannot take keystrokes yet (still attaching) still opens for reading. - let focusing = app.interactive_terminals.focus(&shown); + let _ = app.interactive_terminals.focus(&shown); refresh_terminal_dialog(app, &shown); app.ui_state.dialog = crate::Dialog::Terminal; - if !focusing { - app.messages_state - .toasts - .info("Terminal is not attached yet — keys go to the view. `i` types when it is live."); - } } /// Re-render the open terminal dialog for `handle` when it is the @@ -1694,9 +1661,6 @@ pub(crate) fn focus_terminal(app: &mut App, handle: Option) { return; }; if app.interactive_terminals.focus(&handle) { - app.messages_state.toasts.info(&format!( - "Terminal {handle}: INS — typing goes to the process. Esc reads, Ctrl+] sends a literal esc" - )); refresh_terminal_dialog(app, &handle); } else { app.messages_state.toasts.warning(&format!( @@ -1723,9 +1687,6 @@ pub(crate) fn focus_terminal_panel(app: &mut App, handle: &str) { return; } if app.interactive_terminals.focus(handle) { - app.messages_state.toasts.info(&format!( - "Terminal {handle}: INS — typing goes to the process. Esc reads, Ctrl+] sends a literal esc" - )); return; } // Focus was refused, so this view cannot take keystrokes — and that @@ -1748,9 +1709,11 @@ pub(crate) fn focus_terminal_panel(app: &mut App, handle: &str) { /// Make the terminal panel ready for the next key. /// -/// Selecting the panel is a load, and a terminal that has loaded is for -/// typing. A live attachment takes the PTY keyboard; a live but detached -/// process is re-attached first; an empty panel starts the default shell. +/// Selecting the panel is a load, never a typing session: a PTY left focused by +/// an earlier `i` is parked back at NOR here, so walking away and back cannot +/// leave the keyboard inside the process, and `i` is the one way in. A live but +/// detached process is re-attached first; an empty panel starts the default +/// shell. /// /// An exited or gone handle is left on screen for reading. Its output is the /// post-mortem the user came for, and replacing it on sight would throw that @@ -1787,9 +1750,6 @@ pub(crate) fn ready_terminal_panel(app: &mut App) { /// Return the keyboard to the host, leaving the PTY running. pub(crate) fn blur_terminal_panel(app: &mut App, handle: &str) { app.interactive_terminals.escape(handle); - app.messages_state - .toasts - .info("Terminal NOR: keys move the cursor here. i types; Shift+← leaves the panel"); } /// The bytes a clear sends to the process so it repaints its own prompt. @@ -2221,9 +2181,10 @@ fn terminal_error_hint(code: &str, message: &str) -> String { pub(crate) fn dispatch_terminal_attach(app: &mut App, argument: &str) { let args = argument; if args.is_empty() { - app.messages_state - .toasts - .warning("Usage: /terminal attach "); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /terminal attach ".to_string()], + ); } else { crate::commands::interactive_terminal::start_terminal_attach(app, args.to_string()); } @@ -2232,9 +2193,10 @@ pub(crate) fn dispatch_terminal_attach(app: &mut App, argument: &str) { pub(crate) fn dispatch_terminal_show(app: &mut App, argument: &str) { let args = argument; if args.is_empty() { - app.messages_state - .toasts - .warning("Usage: /terminal show "); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /terminal show ".to_string()], + ); } else if let Some(ref tx) = app.tui_cmd_tx { let _ = send_tui( tx, @@ -2301,9 +2263,10 @@ pub(crate) fn dispatch_terminal_send(app: &mut App, argument: &str) { ); } _ => { - app.messages_state - .toasts - .warning("Usage: /terminal send "); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /terminal send ".to_string()], + ); } } } diff --git a/crates/codegg-tui/src/commands/lsp.rs b/crates/codegg-tui/src/commands/lsp.rs index 418ae2791..bc8945721 100644 --- a/crates/codegg-tui/src/commands/lsp.rs +++ b/crates/codegg-tui/src/commands/lsp.rs @@ -2,10 +2,30 @@ use crate::app::App; use crate::app::TuiCommand; +use crate::components::dialogs::info::InfoType; use egglsp::render_workflow_display; use egglsp::LspWorkflowInvocation; use egglsp::LspWorkflowRecipe; +/// Preserve the shared unavailable message at each existing LSP decision point. +pub(crate) fn show_lsp_unavailable(app: &mut App) { + app.messages_state.toasts.info("LSP not available"); +} + +/// Open an LSP report in the persistent info dialog. +/// +/// A usage line is a Usage dialog; anything else is the report itself. The +/// notification-surface milestone moved this class of output out of the toast +/// queue, and the LSP suite asserts the dialog rather than a toast. +fn show_lsp_result(app: &mut App, text: &str) { + let info_type = if text.starts_with("Usage:") { + InfoType::Usage + } else { + InfoType::Context + }; + app.show_short_or_info(info_type, text.split('\n').map(str::to_string).collect()); +} + /// Serve `/lsp [args]`. /// /// The form is resolved against the catalog's declared paths, so this is a @@ -38,10 +58,13 @@ pub(crate) fn dispatch_lsp(app: &mut App, tail: &str) { fn dispatch_lsp_forms(app: &mut App) { app.ui_state.command_mode = false; - app.messages_state.toasts.info( - "Usage: /lsp [args]\nforms: status, servers, capabilities, errors, root, restart, stop, \ - cache status, cache clear, context diagnostics, repair local, repair test, repair cross, \ - review file, impact, interface, call-neighbors", + show_lsp_result( + app, + concat!( + "Usage: /lsp [args]\nforms: status, servers, capabilities, errors, root, restart, stop, ", + "cache status, cache clear, context diagnostics, repair local, repair test, repair cross, ", + "review file, impact, interface, call-neighbors" + ), ); } @@ -54,9 +77,10 @@ pub(crate) fn dispatch_lsp_capabilities(app: &mut App, argument: &str) { app.ui_state.command_mode = false; let key = argument; if key.is_empty() { - app.messages_state - .toasts - .info("Usage: /lsp capabilities \nUse /lsp servers to see available keys."); + show_lsp_result( + app, + "Usage: /lsp capabilities \nUse /lsp servers to see available keys.", + ); } else { app.enqueue_tui_command(TuiCommand::LspCapabilitiesRequested { server_id: key.to_string(), @@ -68,9 +92,10 @@ pub(crate) fn dispatch_lsp_errors(app: &mut App, argument: &str) { app.ui_state.command_mode = false; let key = argument; if key.is_empty() { - app.messages_state - .toasts - .info("Usage: /lsp errors \nUse /lsp servers to see available keys."); + show_lsp_result( + app, + "Usage: /lsp errors \nUse /lsp servers to see available keys.", + ); } else { app.enqueue_tui_command(TuiCommand::LspErrorsRequested { server_id: key.to_string(), @@ -82,9 +107,7 @@ pub(crate) fn dispatch_lsp_root(app: &mut App, argument: &str) { app.ui_state.command_mode = false; let path_arg = argument; if path_arg.is_empty() { - app.messages_state - .toasts - .info("Usage: /lsp root "); + show_lsp_result(app, "Usage: /lsp root "); } else if app.core_client.is_some() { app.enqueue_tui_command(TuiCommand::LspWorkflowRequested { form: "root", @@ -92,9 +115,9 @@ pub(crate) fn dispatch_lsp_root(app: &mut App, argument: &str) { }); } else if let Some(ref lsp_tool) = app.lsp_tool { let text = lsp_tool.lsp_root_diagnose(path_arg); - app.messages_state.toasts.info(&text); + show_lsp_result(app, &text); } else { - app.messages_state.toasts.info("LSP not available"); + show_lsp_unavailable(app); } } @@ -102,9 +125,7 @@ pub(crate) fn dispatch_lsp_context_diagnostics(app: &mut App, argument: &str) { app.ui_state.command_mode = false; let path_arg = argument; if path_arg.is_empty() { - app.messages_state - .toasts - .info("Usage: /lsp context diagnostics "); + show_lsp_result(app, "Usage: /lsp context diagnostics "); } else if app.core_client.is_some() { app.enqueue_tui_command(TuiCommand::LspWorkflowRequested { form: "context diagnostics", @@ -114,9 +135,9 @@ pub(crate) fn dispatch_lsp_context_diagnostics(app: &mut App, argument: &str) { let text = tokio::task::block_in_place(|| { tokio::runtime::Handle::current().block_on(lsp_tool.lsp_context_diagnostics(path_arg)) }); - app.messages_state.toasts.info(&text); + show_lsp_result(app, &text); } else { - app.messages_state.toasts.info("LSP not available"); + show_lsp_unavailable(app); } } @@ -124,9 +145,7 @@ pub(crate) fn dispatch_lsp_repair_local(app: &mut App, argument: &str) { app.ui_state.command_mode = false; let arg = argument; if arg.is_empty() { - app.messages_state - .toasts - .info("Usage: /lsp repair local "); + show_lsp_result(app, "Usage: /lsp repair local "); } else if app.core_client.is_some() { app.enqueue_tui_command(TuiCommand::LspWorkflowRequested { form: "repair local", @@ -146,12 +165,12 @@ pub(crate) fn dispatch_lsp_repair_local(app: &mut App, argument: &str) { }) { Ok(display) => { let text = render_workflow_display(&display); - app.messages_state.toasts.info(&text); + show_lsp_result(app, &text); } - Err(e) => app.messages_state.toasts.info(&e), + Err(e) => show_lsp_result(app, &e), } } else { - app.messages_state.toasts.info("LSP not available"); + show_lsp_unavailable(app); } } @@ -159,9 +178,7 @@ pub(crate) fn dispatch_lsp_review_file(app: &mut App, argument: &str) { app.ui_state.command_mode = false; let arg = argument; if arg.is_empty() { - app.messages_state - .toasts - .info("Usage: /lsp review file "); + show_lsp_result(app, "Usage: /lsp review file "); } else if app.core_client.is_some() { app.enqueue_tui_command(TuiCommand::LspWorkflowRequested { form: "review file", @@ -178,12 +195,12 @@ pub(crate) fn dispatch_lsp_review_file(app: &mut App, argument: &str) { }) { Ok(display) => { let text = render_workflow_display(&display); - app.messages_state.toasts.info(&text); + show_lsp_result(app, &text); } - Err(e) => app.messages_state.toasts.info(&e), + Err(e) => show_lsp_result(app, &e), } } else { - app.messages_state.toasts.info("LSP not available"); + show_lsp_unavailable(app); } } @@ -191,9 +208,7 @@ pub(crate) fn dispatch_lsp_impact(app: &mut App, argument: &str) { app.ui_state.command_mode = false; let arg = argument; if arg.is_empty() { - app.messages_state - .toasts - .info("Usage: /lsp impact "); + show_lsp_result(app, "Usage: /lsp impact "); } else if app.core_client.is_some() { app.enqueue_tui_command(TuiCommand::LspWorkflowRequested { form: "impact", @@ -213,12 +228,12 @@ pub(crate) fn dispatch_lsp_impact(app: &mut App, argument: &str) { }) { Ok(display) => { let text = render_workflow_display(&display); - app.messages_state.toasts.info(&text); + show_lsp_result(app, &text); } - Err(e) => app.messages_state.toasts.info(&e), + Err(e) => show_lsp_result(app, &e), } } else { - app.messages_state.toasts.info("LSP not available"); + show_lsp_unavailable(app); } } @@ -226,9 +241,7 @@ pub(crate) fn dispatch_lsp_test_repair(app: &mut App, argument: &str) { app.ui_state.command_mode = false; let arg = argument; if arg.is_empty() { - app.messages_state - .toasts - .info("Usage: /lsp repair test [failure-text]"); + show_lsp_result(app, "Usage: /lsp repair test [failure-text]"); } else if app.core_client.is_some() { app.enqueue_tui_command(TuiCommand::LspWorkflowRequested { form: "repair test", @@ -249,12 +262,12 @@ pub(crate) fn dispatch_lsp_test_repair(app: &mut App, argument: &str) { }) { Ok(display) => { let text = render_workflow_display(&display); - app.messages_state.toasts.info(&text); + show_lsp_result(app, &text); } - Err(e) => app.messages_state.toasts.info(&e), + Err(e) => show_lsp_result(app, &e), } } else { - app.messages_state.toasts.info("LSP not available"); + show_lsp_unavailable(app); } } @@ -262,9 +275,7 @@ pub(crate) fn dispatch_lsp_interface(app: &mut App, argument: &str) { app.ui_state.command_mode = false; let arg = argument; if arg.is_empty() { - app.messages_state - .toasts - .info("Usage: /lsp interface "); + show_lsp_result(app, "Usage: /lsp interface "); } else if app.core_client.is_some() { app.enqueue_tui_command(TuiCommand::LspWorkflowRequested { form: "interface", @@ -285,12 +296,12 @@ pub(crate) fn dispatch_lsp_interface(app: &mut App, argument: &str) { }) { Ok(display) => { let text = render_workflow_display(&display); - app.messages_state.toasts.info(&text); + show_lsp_result(app, &text); } - Err(e) => app.messages_state.toasts.info(&e), + Err(e) => show_lsp_result(app, &e), } } else { - app.messages_state.toasts.info("LSP not available"); + show_lsp_unavailable(app); } } @@ -298,9 +309,7 @@ pub(crate) fn dispatch_lsp_cross_repair(app: &mut App, argument: &str) { app.ui_state.command_mode = false; let arg = argument; if arg.is_empty() { - app.messages_state - .toasts - .info("Usage: /lsp repair cross [related...]"); + show_lsp_result(app, "Usage: /lsp repair cross [related...]"); } else if app.core_client.is_some() { app.enqueue_tui_command(TuiCommand::LspWorkflowRequested { form: "repair cross", @@ -321,12 +330,12 @@ pub(crate) fn dispatch_lsp_cross_repair(app: &mut App, argument: &str) { }) { Ok(display) => { let text = render_workflow_display(&display); - app.messages_state.toasts.info(&text); + show_lsp_result(app, &text); } - Err(e) => app.messages_state.toasts.info(&e), + Err(e) => show_lsp_result(app, &e), } } else { - app.messages_state.toasts.info("LSP not available"); + show_lsp_unavailable(app); } } @@ -334,9 +343,10 @@ pub(crate) fn dispatch_lsp_call_neighbors(app: &mut App, argument: &str) { app.ui_state.command_mode = false; let arg = argument; if arg.is_empty() { - app.messages_state - .toasts - .info("Usage: /lsp call-neighbors [incoming|outgoing|both]"); + show_lsp_result( + app, + "Usage: /lsp call-neighbors [incoming|outgoing|both]", + ); } else if app.core_client.is_some() { app.enqueue_tui_command(TuiCommand::LspWorkflowRequested { form: "call-neighbors", @@ -364,12 +374,12 @@ pub(crate) fn dispatch_lsp_call_neighbors(app: &mut App, argument: &str) { }) { Ok(display) => { let text = render_workflow_display(&display); - app.messages_state.toasts.info(&text); + show_lsp_result(app, &text); } - Err(e) => app.messages_state.toasts.info(&e), + Err(e) => show_lsp_result(app, &e), } } else { - app.messages_state.toasts.info("LSP not available"); + show_lsp_unavailable(app); } } @@ -377,9 +387,10 @@ pub(crate) fn dispatch_lsp_restart(app: &mut App, argument: &str) { app.ui_state.command_mode = false; let key = argument; if key.is_empty() { - app.messages_state - .toasts - .info("Usage: /lsp restart \nUse /lsp servers to see available keys."); + show_lsp_result( + app, + "Usage: /lsp restart \nUse /lsp servers to see available keys.", + ); } else { app.enqueue_tui_command(TuiCommand::LspRestartRequested { server_id: key.to_string(), @@ -392,9 +403,10 @@ pub(crate) fn dispatch_lsp_stop(app: &mut App, argument: &str) { let arg = argument; if app.core_client.is_some() { if arg.trim().is_empty() || arg.trim() == "--all" { - app.messages_state - .toasts - .info("Usage: /lsp stop (select one server from /lsp servers)"); + show_lsp_result( + app, + "Usage: /lsp stop (select one server from /lsp servers)", + ); } else { app.enqueue_tui_command(TuiCommand::LspControlRequested { form: "stop", @@ -410,9 +422,9 @@ pub(crate) fn dispatch_lsp_stop(app: &mut App, argument: &str) { let result = tokio::task::block_in_place(|| { tokio::runtime::Handle::current().block_on(lsp_tool.lsp_stop_server(key_opt)) }); - app.messages_state.toasts.info(&result); + show_lsp_result(app, &result); } else { - app.messages_state.toasts.info("LSP not available"); + show_lsp_unavailable(app); } } @@ -425,9 +437,9 @@ pub(crate) fn dispatch_lsp_cache_status(app: &mut App) { }); } else if let Some(ref lsp_tool) = app.lsp_tool { let text = lsp_tool.lsp_cache_status(); - app.messages_state.toasts.info(&text); + show_lsp_result(app, &text); } else { - app.messages_state.toasts.info("LSP not available"); + show_lsp_unavailable(app); } } @@ -436,9 +448,7 @@ pub(crate) fn dispatch_lsp_cache_clear(app: &mut App, argument: &str) { let arg = argument; if app.core_client.is_some() { if !arg.trim().is_empty() && arg.trim() != "--all" { - app.messages_state.toasts.info( - "Cache clear is scoped to the active session workspace; no root argument is accepted", - ); + show_lsp_result(app, "Cache clear is scoped to the active session workspace; no root argument is accepted",); } else { app.enqueue_tui_command(TuiCommand::LspControlRequested { form: "cache clear", @@ -448,19 +458,20 @@ pub(crate) fn dispatch_lsp_cache_clear(app: &mut App, argument: &str) { } else if let Some(ref lsp_tool) = app.lsp_tool { if arg.is_empty() || arg == "--all" { let count = lsp_tool.clear_semantic_cache(); - app.messages_state - .toasts - .info(&format!("Cleared {count} cached entries")); + show_lsp_result(app, &format!("Cleared {count} cached entries")); } else { let root = std::path::PathBuf::from(arg); let count = lsp_tool.clear_semantic_cache_for_root(&root); - app.messages_state.toasts.info(&format!( - "Cleared {count} cached entries for root: {}", - root.display() - )); + show_lsp_result( + app, + &format!( + "Cleared {count} cached entries for root: {}", + root.display() + ), + ); } } else { - app.messages_state.toasts.info("LSP not available"); + show_lsp_unavailable(app); } } diff --git a/crates/codegg-tui/src/commands/manifest_restore.rs b/crates/codegg-tui/src/commands/manifest_restore.rs index b451b5fa0..1d0b44eb1 100644 --- a/crates/codegg-tui/src/commands/manifest_restore.rs +++ b/crates/codegg-tui/src/commands/manifest_restore.rs @@ -326,20 +326,11 @@ fn apply_plan(app: &mut App, plan: RestorePlan) { } } - // Surface the plan in a toast so the user can see what was - // restored. The restore is re-driven as catalog and project - // details arrive, so this fires only on the first apply that - // actually opened a tab; later passes would otherwise repeat - // the same message once per round-trip. + // Gate later restore replay once this plan has opened a tab. The tab list + // is the visible surface, so a success toast would only repeat it. let restored_count = plan.entries.iter().filter(|e| e.opens_tab()).count(); if restored_count > 0 && !app.manifest_restore_announced { app.manifest_restore_announced = true; - let msg = format!( - "Restored {} tab{} from previous session", - restored_count, - if restored_count == 1 { "" } else { "s" } - ); - app.messages_state.toasts.info(&msg); } } diff --git a/crates/codegg-tui/src/commands/memory.rs b/crates/codegg-tui/src/commands/memory.rs index 8f068def3..e0f0e1e64 100644 --- a/crates/codegg-tui/src/commands/memory.rs +++ b/crates/codegg-tui/src/commands/memory.rs @@ -65,9 +65,10 @@ pub(crate) async fn handle_memory_summary(app: &mut App) { } let total = prefs.len() + proj.len(); if total == 0 { - app.messages_state - .toasts - .info("No memories yet. Use /memory-remember to save something."); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::MemoryResults, + vec!["No memories yet. Use /memory-remember to save something.".to_string()], + ); return; } let mut lines = vec![format!("Memory Summary ({} total):", total)]; @@ -143,9 +144,10 @@ pub(crate) async fn handle_memory_search(app: &mut App, query: String) { .cloned() .unwrap_or_default(); if results.is_empty() { - app.messages_state - .toasts - .info(&format!("No memories found matching '{}'", query)); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::MemoryResults, + vec![format!("No memories found matching '{}'", query)], + ); } else { let lines: Vec = results .iter() @@ -211,9 +213,10 @@ pub(crate) async fn handle_memory_remember(app: &mut App, text: String) { }, ); match core_client.request(request).await { - Ok(CoreResponse::Json { .. }) | Ok(CoreResponse::Ack) => { - app.messages_state.toasts.info("Remembered") - } + Ok(CoreResponse::Json { .. }) | Ok(CoreResponse::Ack) => app.show_short_or_info( + crate::components::dialogs::info::InfoType::MemoryResults, + vec!["Remembered".to_string()], + ), Ok(CoreResponse::Error { message, .. }) => app .messages_state .toasts @@ -255,7 +258,10 @@ pub(crate) async fn handle_memory_forget(app: &mut App, id: String) { .and_then(|v| v.as_bool()) .unwrap_or(false); if deleted { - app.messages_state.toasts.info("Memory deleted"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::MemoryResults, + vec!["Memory deleted".to_string()], + ); } else { app.messages_state .toasts @@ -626,14 +632,10 @@ pub(crate) fn apply_memory_result(app: &mut App, toast_message: String, is_error app.messages_state.toasts.error(&toast_message); } else { let lines: Vec = toast_message.lines().map(|s| s.to_string()).collect(); - if lines.len() > 3 { - app.open_info_dialog( - crate::components::dialogs::info::InfoType::MemoryResults, - lines, - ); - } else { - app.messages_state.toasts.info(&toast_message); - } + app.show_short_or_info( + crate::components::dialogs::info::InfoType::MemoryResults, + lines, + ); } } @@ -778,14 +780,10 @@ pub(crate) fn apply_habit_result(app: &mut App, message: String, is_error: bool) app.messages_state.toasts.error(&message); } else { let lines: Vec = message.lines().map(str::to_string).collect(); - if lines.len() > 3 { - app.open_info_dialog( - crate::components::dialogs::info::InfoType::MemoryResults, - lines, - ); - } else { - app.messages_state.toasts.info(&message); - } + app.show_short_or_info( + crate::components::dialogs::info::InfoType::MemoryResults, + lines, + ); } } @@ -910,24 +908,29 @@ pub(crate) fn start_memory_consolidate(app: &mut App) { ); } +fn warn_habit_store_unavailable(app: &mut App) { + app.messages_state.toasts.warning("Habit store unavailable"); +} + pub(crate) fn dispatch_habits(app: &mut App, argument: &str) { let ready_only = argument == "ready"; if let Some(ref tx) = app.tui_cmd_tx { let _ = send_tui(tx, TuiCommand::HabitList { ready_only }); } else { - app.messages_state.toasts.warning("Habit store unavailable"); + warn_habit_store_unavailable(app); } } pub(crate) fn dispatch_habit_dismiss(app: &mut App, argument: &str) { let id = argument.to_string(); if id.is_empty() { - app.messages_state - .toasts - .warning("Usage: /habit dismiss (use /habit)"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /habit dismiss (use /habit)".to_string()], + ); } else if let Some(ref tx) = app.tui_cmd_tx { let _ = send_tui(tx, TuiCommand::HabitDismiss { id }); } else { - app.messages_state.toasts.warning("Habit store unavailable"); + warn_habit_store_unavailable(app); } } diff --git a/crates/codegg-tui/src/commands/observe.rs b/crates/codegg-tui/src/commands/observe.rs index 2a655158c..9a81befe9 100644 --- a/crates/codegg-tui/src/commands/observe.rs +++ b/crates/codegg-tui/src/commands/observe.rs @@ -14,6 +14,12 @@ use crate::commands::close_command_mode; use crate::task_lifecycle::TuiTaskKind; use codegg::protocol::core::{CoreRequest, CoreResponse}; +fn report_observation_denied(app: &mut App) { + app.messages_state + .toasts + .warning("Session not found or not authorized for observation"); +} + /// Kick off an observation of `session_id` in `project_id`. /// /// Replaces any existing observation: the previous observer-owned @@ -21,9 +27,10 @@ use codegg::protocol::core::{CoreRequest, CoreResponse}; /// begins, so at most one observed session is active. pub(crate) fn start_observe(app: &mut App, project_id: String, session_id: String) { if project_id.is_empty() || session_id.is_empty() { - app.messages_state - .toasts - .warning("Usage: /observe — open a project tab first"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /observe — open a project tab first".to_string()], + ); return; } // Tear down any previous observation first (observer-owned only). @@ -31,9 +38,10 @@ pub(crate) fn start_observe(app: &mut App, project_id: String, session_id: Strin stop_subscription_best_effort(app, old_sub); } let Some(request_id) = app.observer.begin_observe(&project_id, &session_id) else { - app.messages_state - .toasts - .warning("Invalid session locator — observation not started"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Invalid session locator — observation not started".to_string()], + ); return; }; if app.core_client.is_none() { @@ -212,9 +220,6 @@ pub(crate) fn apply_observe_subscribed( true, reconnect_epoch, ); - app.messages_state - .toasts - .info("Observation unavailable — daemon does not support session projections"); return; } if unauthorized { @@ -223,9 +228,7 @@ pub(crate) fn apply_observe_subscribed( .apply_denied(request_id, &session_id, reconnect_epoch); // Privacy-preserving: identical message for denied vs absent so // observers learn nothing about existence. - app.messages_state - .toasts - .warning("Session not found or not authorized for observation"); + report_observation_denied(app); return; } if let (Some(sub), Some(cur)) = (subscription_id, cursor) { @@ -240,11 +243,6 @@ pub(crate) fn apply_observe_subscribed( if let Some((descriptor, snapshot)) = projection { install_observed_snapshot(app, &session_id, sub, descriptor, snapshot); } - if let Some(banner) = app.observer.banner_line() { - app.messages_state - .toasts - .info(&format!("{banner} — input is read-only")); - } } return; } @@ -515,23 +513,17 @@ pub(crate) fn apply_observe_resumed( let _ = app .observer .apply_denied(request_id, &session_id, reconnect_epoch); - app.messages_state - .toasts - .warning("Session not found or not authorized for observation"); + report_observation_denied(app); return; } if let Some(cursor) = cursor { - if app.observer.apply_resumed( + app.observer.apply_resumed( request_id, &session_id, cursor, last_delivered_seq, reconnect_epoch, - ) { - app.messages_state - .toasts - .info("Observation resynced — live"); - } + ); return; } if let Some(err) = error { @@ -553,13 +545,9 @@ pub(crate) fn stop_observing(app: &mut App) { // Denied/unsupported shell with no subscription id. app.observer.clear(); } - app.messages_state.toasts.info("Not observing"); return; }; stop_subscription_best_effort(app, owned); - app.messages_state - .toasts - .info("Stopped observing — control restored"); } fn stop_subscription_best_effort( @@ -635,9 +623,10 @@ pub(crate) fn dispatch_observe(app: &mut App, argument: &str) { close_command_mode(app); let session_arg = argument; if session_arg.is_empty() { - app.messages_state - .toasts - .warning("Usage: /observe "); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /observe ".to_string()], + ); return; } // Session locator is the first token; anything after is @@ -648,9 +637,10 @@ pub(crate) fn dispatch_observe(app: &mut App, argument: &str) { .unwrap_or("") .to_string(); let Some(project_id) = app.active_project_id().map(str::to_string) else { - app.messages_state - .toasts - .warning("No active project — open a project tab first"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["No active project — open a project tab first".to_string()], + ); return; }; crate::commands::observe::start_observe(app, project_id, session_id); diff --git a/crates/codegg-tui/src/commands/panels.rs b/crates/codegg-tui/src/commands/panels.rs index 9ef717c4d..dc3d35b40 100644 --- a/crates/codegg-tui/src/commands/panels.rs +++ b/crates/codegg-tui/src/commands/panels.rs @@ -130,25 +130,11 @@ pub(crate) fn sync_manager_placement(app: &mut App) { pub(crate) fn move_manager_panel(app: &mut App, panel: SidePanelId, placement: PanelPlacement) { let from = app.panel_host.placement(); if from == placement && app.panel_host.panel_at(placement) == panel { - // Still confirm. A keypress that appears to do nothing is read as a - // dead key, and the honest "already there" is the useful answer. - app.messages_state.toasts.info(&format!( - "{} is already on the {}", - panel.label(), - placement.label() - )); return; } app.panel_host.dock(panel, placement); app.ui_state.sidebar_visible = app.panel_host.any_visible(); persist_panel_placement(app, placement); - app.messages_state.toasts.info(&format!( - "{} moved to the {}; the {} is now {}", - panel.label(), - placement.label(), - from.label(), - describe_vacated(app, from) - )); sync_manager_placement(app); } @@ -174,9 +160,12 @@ pub(crate) fn toggle_panel_selector(app: &mut App) { /// must not fall through into the composer. pub(crate) fn recall_panel_hotkey(app: &mut App, digit: char) -> bool { let Some(panel) = app.panel_hotkeys.get(digit) else { - app.messages_state.toasts.info(&format!( - "No panel bound to ^-{digit} — bind it in the panel manager (⇧S)" - )); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!( + "No panel bound to ^-{digit} — bind it in the panel manager (⇧S)" + )], + ); return true; }; let placement = app.panel_host.placement(); @@ -198,21 +187,8 @@ pub(crate) fn recall_panel_hotkey(app: &mut App, digit: char) -> bool { /// Persist a new digit binding and confirm it in place. pub(crate) fn save_panel_hotkey(app: &mut App, digit: char, panel: SidePanelId) { - let replaced = app.panel_hotkeys.get(digit); app.panel_hotkeys.set(digit, panel); - let notice = match replaced { - Some(previous) if previous != panel => { - format!( - "^-{digit} rebound: was {}, now {}", - previous.label(), - panel.label() - ) - } - Some(_) => format!("^-{digit} already {} — unchanged", panel.label()), - None => format!("^-{digit} → {} (Ctrl+{digit})", panel.label()), - }; persist_panel_hotkeys(app); - app.messages_state.toasts.info(¬ice); } /// Write the hotkey map back to the **global** config. @@ -226,21 +202,23 @@ pub(crate) fn save_panel_hotkey(app: &mut App, digit: char, panel: SidePanelId) /// Failures are reported but never roll back the in-memory binding: the key /// works for this session either way, and a user who cannot write their /// config should still be able to use the panel they just bound. +fn report_hotkey_save_failure(app: &mut App, error: &str) { + app.messages_state + .toasts + .error(&format!("Hotkey not saved: {error}")); +} + fn persist_panel_hotkeys(app: &mut App) { let mut config = match codegg::config::schema::Config::load() { Ok(config) => config, Err(error) => { - app.messages_state - .toasts - .error(&format!("Hotkey not saved: {error}")); + report_hotkey_save_failure(app, &error.to_string()); return; } }; config.panel_hotkeys = Some(app.panel_hotkeys.to_map().into_iter().collect()); if let Err(error) = config.save_global() { - app.messages_state - .toasts - .error(&format!("Hotkey not saved: {error}")); + report_hotkey_save_failure(app, &error.to_string()); } } @@ -337,11 +315,12 @@ pub(crate) enum SelectOutcome { /// reads snapshots and starts daemon work, all of which panels are barred /// from. A panel with content already (or a bespoke panel) is untouched. /// -/// Returns `true` when the caller should select `id`. That is true for -/// everything except the two outcomes where a live box owns the keyboard — -/// [`PanelFill::StillLoading`] and [`PanelFill::OpenedAs`] — because focusing -/// the panel behind an open modal would claim the badge while every key goes -/// to the modal. +/// Returns `true` for every outcome, so the caller always selects `id`: +/// M002 keeps the column even for an asynchronous filler, because the *panel* +/// is what the user asked to look at. An asynchronous fill paints its +/// placeholder and records `App::dock_on_open`, so the finished box is adopted +/// into this column instead of flashing as a modal — and a box that belongs to +/// a different panel is docked into *that* one, never this one. /// /// Whatever happened is recorded on the panel itself, so the column shows the /// truth instead of a standing "nothing is loaded". @@ -430,7 +409,8 @@ fn materialize_hosted_panel(app: &mut App, id: SidePanelId) -> bool { /// start a load behind it (research runs, the Task view), so the box is live /// but incomplete and must not be adopted. Panels that cannot act at all (a /// plan panel with no pending confirmation, a security panel with no receipt, -/// a memory panel with no query) toast why and say so in the panel. +/// a memory panel with no query) say so in the panel; compact instructions are +/// retained only when the operator needs a next step. /// /// **Every arm returns its own outcome.** That is the contract: a caller must /// never have to re-read `dock_target()` and guess. Two arms deliberately @@ -467,30 +447,20 @@ pub(crate) fn open_panel_box(app: &mut App, id: SidePanelId) -> PanelFill { app.open_dialog(Dialog::Plan); PanelFill::Filled } else { - app.messages_state - .toasts - .info("No pending plan confirmation — /plan shows the current task plan"); PanelFill::Cannot("no pending plan confirmation") } } P::Goal => match app.session_state.session.clone() { Some(session) => { crate::commands::goals::start_goal_show(app, session.id); - app.messages_state.toasts.info("Loading goal…"); PanelFill::Loading } - None => { - app.messages_state.toasts.warning("No active session"); - PanelFill::Cannot("no active session") - } + None => PanelFill::Cannot("no active session"), }, // Mirrors `show_collaborators`: it opens its box synchronously from // already-resolved presence state, but refuses without a project. P::Collaborators => { if app.active_project_id().is_none() { - app.messages_state - .toasts - .info("No active project — open a project tab first"); PanelFill::Cannot("no active project") } else { crate::commands::presence::show_collaborators(app); @@ -498,9 +468,10 @@ pub(crate) fn open_panel_box(app: &mut App, id: SidePanelId) -> PanelFill { } } P::Memory => { - app.messages_state - .toasts - .info("Memory needs a query — run /memory search "); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Context, + vec!["Memory needs a query — run /memory search ".to_string()], + ); PanelFill::Cannot("memory search needs a query") } // The browser mounts with `loading = true` and fills from the reply, @@ -511,7 +482,7 @@ pub(crate) fn open_panel_box(app: &mut App, id: SidePanelId) -> PanelFill { PanelFill::StillLoading } P::Logs => { - app.open_logs_window(); + app.open_logs_window(crate::app::LogsView::All); PanelFill::Filled } P::Context => { @@ -533,25 +504,19 @@ pub(crate) fn open_panel_box(app: &mut App, id: SidePanelId) -> PanelFill { P::Doctor => { if let Some(ref tx) = app.tui_cmd_tx { let _ = crate::app::send_tui(tx, crate::app::TuiCommand::RunDoctor); - app.messages_state.toasts.info("Running doctor…"); PanelFill::Loading } else { - app.messages_state - .toasts - .info("doctor: not connected to a core client"); PanelFill::Cannot("not connected to a core client") } } P::ShellShow => { if app.shell_store.list_recent(10).is_empty() { - app.messages_state - .toasts - .info("No shell commands in history"); PanelFill::Cannot("no shell commands in history") } else { - app.messages_state - .toasts - .info("Run /shell show to open one, then L to dock it"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Run /shell show to open one, then L to dock it".to_string()], + ); PanelFill::Cannot("no shell selected") } } @@ -560,8 +525,12 @@ pub(crate) fn open_panel_box(app: &mut App, id: SidePanelId) -> PanelFill { app.open_dialog(Dialog::SecurityReview); PanelFill::Filled } else { - app.messages_state.toasts.warning( - "No security review result available yet. Run /security-review first.", + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![ + "No security review result available yet. Run /security-review first." + .to_string(), + ], ); PanelFill::Cannot("no security review result yet") } @@ -599,9 +568,10 @@ pub(crate) fn open_panel_box(app: &mut App, id: SidePanelId) -> PanelFill { select_panel(app, SidePanelId::Agents); focus_panel(app); if !app.panel_host.is_focused() { - app.messages_state - .toasts - .warning("Agents panel could not take focus — press L to select it"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Agents panel could not take focus — press L to select it".to_string()], + ); } PanelFill::Bespoke } @@ -617,7 +587,6 @@ pub(crate) fn open_panel_box(app: &mut App, id: SidePanelId) -> PanelFill { let has_manager = app.plugin_manager.is_some(); crate::commands::plugin_management::show_plugins(app); if has_manager { - app.messages_state.toasts.info("Loading plugins…"); PanelFill::Loading } else { PanelFill::Cannot("plugin manager unavailable") @@ -628,9 +597,6 @@ pub(crate) fn open_panel_box(app: &mut App, id: SidePanelId) -> PanelFill { // read whose box arrives from the reply. Mirrors `start_show_team`. P::Team => { if app.active_project_id().is_none() { - app.messages_state - .toasts - .info("No active project — open a project tab first"); PanelFill::Cannot("no active project") } else { // Read the branch before dispatching, because the helper takes @@ -648,9 +614,6 @@ pub(crate) fn open_panel_box(app: &mut App, id: SidePanelId) -> PanelFill { // otherwise starts an async read. P::Control => { if app.active_session_id().is_none() { - app.messages_state - .toasts - .info("No active session — open a session tab first"); PanelFill::Cannot("no active session") } else { crate::commands::control::dispatch_control_command(app, ""); @@ -929,9 +892,10 @@ pub(crate) fn step_panel(app: &mut App, delta: i8) { /// made the refusal worth replacing rather than keeping. pub(crate) fn dock_open_box(app: &mut App, dir: PanelDirection) { let Some(id) = app.dock_target() else { - app.messages_state - .toasts - .warning("No panel for this box — open a panel-capable box first"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["No panel for this box — open a panel-capable box first".to_string()], + ); return; }; // Refuse **before** unmounting. `SidePanelHost::adopt` consumes the widget @@ -944,10 +908,13 @@ pub(crate) fn dock_open_box(app: &mut App, dir: PanelDirection) { // build or share the very content their box was showing. Only `Agents` // pairs a box with a panel that shows something else. if id.discards_a_docked_box() { - app.messages_state.toasts.warning(&format!( - "{} is the management list, not the editor box — there is nothing to dock into", - id.label() - )); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!( + "{} is the management list, not the editor box — there is nothing to dock into", + id.label() + )], + ); return; } // Close first: `select_panel` reads sidebar visibility and focus, and a @@ -963,16 +930,10 @@ pub(crate) fn dock_open_box(app: &mut App, dir: PanelDirection) { let from = app.panel_host.placement(); let placement = edge_named_by(dir, from); app.panel_host.dock(id, placement); - app.ui_state.sidebar_visible = app.panel_host.any_visible(); - if let Some(widget) = unmounted { - app.panel_host.adopt(id, widget); - } - select_panel(app, id); - focus_panel(app); - // Only say something when the panel actually crossed an edge. Docking - // where it already was is the common case and needs no narration, but a - // swap is exactly the moment the user cannot see the other edge change - // on its own — it happened off to the side of the gesture they pressed. + // The panel moving is visible; what the edge it left is showing now is not. + // Nothing is said when the gesture names the edge the panel is already on — + // there is no second edge to describe, and the layout already shows that it + // did not move. if from != placement { app.messages_state.toasts.info(&format!( "{} moved to the {}; the {} is now {}", @@ -982,6 +943,25 @@ pub(crate) fn dock_open_box(app: &mut App, dir: PanelDirection) { describe_vacated(app, from) )); } + app.ui_state.sidebar_visible = app.panel_host.any_visible(); + if let Some(widget) = unmounted { + app.panel_host.adopt(id, widget); + } + select_panel(app, id); + focus_panel(app); +} + +/// What the edge a panel just left is showing `now`. +/// +/// The vacated edge either restores the panel it held before or collapses, and +/// that is a layout change the user did not ask for and cannot watch happen — +/// so it is the part of a move that has to be said out loud. +fn describe_vacated(app: &App, placement: PanelPlacement) -> String { + if app.panel_host.is_visible_at(placement) { + app.panel_host.panel_at(placement).label().to_string() + } else { + "collapsed".to_string() + } } /// The edge a directional gesture names. @@ -1009,28 +989,21 @@ fn edge_named_by(dir: PanelDirection, current: PanelPlacement) -> PanelPlacement /// left placement it is `Shift+H` and under a bottom row `Shift+J` — the /// meaning is the same, only the spelling moved with the panel. /// -/// Shows the panel when it is hidden rather than refusing: the gesture is the -/// direct way to reach it, and a toast telling the user to press `Ctrl+B` and -/// then the same key again is a worse answer than just doing it. +/// Shows the panel when it is hidden rather than refusing: this gesture is +/// the direct way to reach the edge. /// /// An empty hosted panel is materialized first, so this is the same one /// step as picking it from the manager. A live-loading box stays open /// instead and keeps the keyboard. pub(crate) fn focus_side_panel(app: &mut App) { let placement = app.panel_host.placement(); - // Reveal it: the gesture is the direct way to reach this edge, and a toast - // telling the user to press `Ctrl+B` and then the same key again is a - // worse answer than just doing it. + // Reveal it: the gesture is the direct way to reach this edge. app.panel_host.set_visible_at(placement, true); app.ui_state.sidebar_visible = app.panel_host.any_visible(); if select_panel(app, app.panel_host.active()) == SelectOutcome::BoxOpen { return; } - if !focus_panel(app) { - app.messages_state - .toasts - .info("Side panel has nothing to show yet"); - } + focus_panel(app); } /// Move keyboard focus back to the main buffer. @@ -1047,9 +1020,7 @@ pub(crate) fn focus_main_buffer(app: &mut App) { /// Dock the panel on `placement`, show it, and remember the choice. /// -/// Applies immediately and confirms in one line, because "which side is this -/// on" is a question the frame answers badly: the user has to see the panel -/// move to believe it moved. +/// Applies immediately; the rendered frame shows the panel's new placement. /// /// The *panel* is left alone — switching sides is not a request to re-select /// what this edge holds. What does change is the other edge: the panel this @@ -1058,39 +1029,11 @@ pub(crate) fn focus_main_buffer(app: &mut App) { /// whatever was in the way. pub(crate) fn set_panel_placement(app: &mut App, placement: PanelPlacement) { if app.panel_host.placement() == placement { - // Still confirm. A keypress that appears to do nothing is read as a - // dead key, and the honest "already there" is only useful if it is - // visible. - app.messages_state - .toasts - .info(&format!("Panel is already {}", placement.label())); return; } - let from = app.panel_host.placement(); - // Swap first so the toast can describe what the vacated edge became, - // rather than what it used to be. app.panel_host.dock(app.panel_host.active(), placement); app.ui_state.sidebar_visible = app.panel_host.any_visible(); persist_panel_placement(app, placement); - app.messages_state.toasts.info(&format!( - "Panel moved to the {}; the {} is now {}", - placement.label(), - from.label(), - describe_vacated(app, from) - )); -} - -/// Name what an edge shows after a panel left it, for the swap confirmation. -/// -/// Says "collapsed" rather than "empty" when the edge had nothing before, -/// because that is the word `Ctrl+B` uses for the same state — the user -/// recognises one, and would have to guess the other. -fn describe_vacated(app: &App, placement: PanelPlacement) -> String { - if app.panel_host.is_visible_at(placement) { - app.panel_host.panel_at(placement).label().to_string() - } else { - "collapsed".to_string() - } } /// Step to the next placement. The manager's single layout key. @@ -1100,18 +1043,11 @@ fn describe_vacated(app: &App, placement: PanelPlacement) -> String { /// through layouts is trying the panel on another edge, not parking it on /// one and leaving an empty column behind. pub(crate) fn cycle_panel_placement(app: &mut App) { - let from = app.panel_host.placement(); let panel = app.panel_host.active(); let next = app.panel_host.cycle_placement(); app.panel_host.dock(panel, next); app.ui_state.sidebar_visible = app.panel_host.any_visible(); persist_panel_placement(app, next); - app.messages_state.toasts.info(&format!( - "Panel moved to the {}; the {} is now {}", - next.label(), - from.label(), - describe_vacated(app, from) - )); } /// Write the panel placement back to the **global** config. @@ -1120,22 +1056,24 @@ pub(crate) fn cycle_panel_placement(app: &mut App) { /// per-user preference, and `Config::save()` would confine it to one checkout /// and could write it into a tracked file. A failure is reported but never /// rolled back — the frame the user is looking at is already correct. +fn report_layout_save_failure(app: &mut App, error: &str) { + app.messages_state + .toasts + .error(&format!("Layout not saved: {error}")); +} + fn persist_panel_placement(app: &mut App, placement: PanelPlacement) { let mut config = match codegg::config::schema::Config::load() { Ok(config) => config, Err(error) => { - app.messages_state - .toasts - .error(&format!("Layout not saved: {error}")); + report_layout_save_failure(app, &error.to_string()); return; } }; config.panel_placement = Some(placement.as_str().to_string()); config.panel_layout = Some(app.panel_host.layout_map().into_iter().collect()); if let Err(error) = config.save_global() { - app.messages_state - .toasts - .error(&format!("Layout not saved: {error}")); + report_layout_save_failure(app, &error.to_string()); } } @@ -1171,11 +1109,7 @@ pub(crate) fn toggle_selected_pane(app: &mut App) { if select_panel(app, app.panel_host.active()) == SelectOutcome::BoxOpen { return; } - if !focus_panel(app) { - app.messages_state - .toasts - .info("Side panel has nothing to show yet"); - } + focus_panel(app); if app.panel_host.active() == SidePanelId::Session { app.sidebar.focus_sidebar(); } @@ -1264,11 +1198,15 @@ fn announce_resize(app: &mut App, armed: bool) { let message = format!( "Resize {subject}: h/j/k/l drag its own borders outward · Esc or Enter to stop" ); - app.messages_state.toasts.info(&message); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![message], + ); } else { - app.messages_state - .toasts - .info("Resize off: h/j/k/l move the cursor again"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Resize off: h/j/k/l move the cursor again".to_string()], + ); } } diff --git a/crates/codegg-tui/src/commands/plugin_catalogue.rs b/crates/codegg-tui/src/commands/plugin_catalogue.rs index f40bdd458..03da8fd2e 100644 --- a/crates/codegg-tui/src/commands/plugin_catalogue.rs +++ b/crates/codegg-tui/src/commands/plugin_catalogue.rs @@ -8,6 +8,12 @@ use crate::app::TuiCommand; use crate::task_lifecycle::TuiTaskKind; use codegg::protocol::core::CoreResponse; +fn plugin_catalogue_unavailable(app: &mut App) { + app.messages_state + .toasts + .warning("The daemon's plugin catalogue is unavailable"); +} + pub(crate) fn daemon_owns_plugins(app: &App) -> bool { app.core_client.is_some() } @@ -23,9 +29,7 @@ fn published_catalogue( /// Render the published catalogue as the `/plugin` list. pub(crate) fn show_published_plugins(app: &mut App) { let Some(entries) = published_catalogue(app) else { - app.messages_state - .toasts - .warning("The daemon's plugin catalogue is unavailable"); + plugin_catalogue_unavailable(app); return; }; let mut lines = vec![ @@ -44,14 +48,12 @@ pub(crate) fn show_published_plugins(app: &mut App) { )); } } - app.show_short_or_info(crate::components::dialogs::info::InfoType::Stats, lines); + app.open_info_dialog(crate::components::dialogs::info::InfoType::Stats, lines); } pub(crate) fn show_published_plugin_info(app: &mut App, query: &str) { let Some(entries) = published_catalogue(app) else { - app.messages_state - .toasts - .warning("The daemon's plugin catalogue is unavailable"); + plugin_catalogue_unavailable(app); return; }; let query = query.to_ascii_lowercase(); @@ -63,9 +65,10 @@ pub(crate) fn show_published_plugin_info(app: &mut App, query: &str) { }) .collect(); if matches.is_empty() { - app.messages_state - .toasts - .error(&format!("No plugin matches '{query}'")); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Stats, + vec![format!("No plugin matches '{query}'")], + ); return; } let mut lines = Vec::new(); @@ -83,14 +86,12 @@ pub(crate) fn show_published_plugin_info(app: &mut App, query: &str) { lines.push(" the plugin carries an error-level diagnostic".to_string()); } } - app.show_short_or_info(crate::components::dialogs::info::InfoType::Stats, lines); + app.open_info_dialog(crate::components::dialogs::info::InfoType::Stats, lines); } pub(crate) fn show_published_plugin_doctor(app: &mut App, query: Option<&str>) { let Some(entries) = published_catalogue(app) else { - app.messages_state - .toasts - .warning("The daemon's plugin catalogue is unavailable"); + plugin_catalogue_unavailable(app); return; }; let query = query.map(|value| value.to_ascii_lowercase()); @@ -123,7 +124,7 @@ pub(crate) fn show_published_plugin_doctor(app: &mut App, query: Option<&str>) { } )); } - app.show_short_or_info(crate::components::dialogs::info::InfoType::Stats, lines); + app.open_info_dialog(crate::components::dialogs::info::InfoType::Stats, lines); } /// Issue one of the four mutating plugin forms to the daemon. The request @@ -131,9 +132,7 @@ pub(crate) fn show_published_plugin_doctor(app: &mut App, query: Option<&str>) { /// `Run` and authorizes the inner request with `plugin.manage`. pub(crate) fn request_plugin_manage(app: &mut App, form: &'static str, argument: &str) { let Some(core_client) = app.core_client.clone() else { - app.messages_state - .toasts - .error("Plugin manager not available"); + crate::commands::plugin_management::plugin_manager_unavailable(app); return; }; let scope = crate::command_route::scope_for(app); diff --git a/crates/codegg-tui/src/commands/plugin_management.rs b/crates/codegg-tui/src/commands/plugin_management.rs index 8d2b83e94..00add593c 100644 --- a/crates/codegg-tui/src/commands/plugin_management.rs +++ b/crates/codegg-tui/src/commands/plugin_management.rs @@ -12,6 +12,12 @@ use crate::task_lifecycle::TuiTaskKind; // Command handlers (spawn + completion pattern) // --------------------------------------------------------------------------- +pub(crate) fn plugin_manager_unavailable(app: &mut App) { + app.messages_state + .toasts + .error("Plugin manager not available"); +} + /// List all registered plugins (builtins + installed). pub(crate) fn show_plugins(app: &mut App) { if crate::commands::plugin_catalogue::daemon_owns_plugins(app) { @@ -19,9 +25,7 @@ pub(crate) fn show_plugins(app: &mut App) { return; } let Some(mgr) = app.plugin_manager.clone() else { - app.messages_state - .toasts - .error("Plugin manager not available"); + plugin_manager_unavailable(app); return; }; let tx = app.tui_cmd_tx.clone(); @@ -64,9 +68,7 @@ pub(crate) fn show_plugin_info(app: &mut App, query: &str) { } let query = query.to_string(); let Some(mgr) = app.plugin_manager.clone() else { - app.messages_state - .toasts - .error("Plugin manager not available"); + plugin_manager_unavailable(app); return; }; let tx = app.tui_cmd_tx.clone(); @@ -104,9 +106,7 @@ pub(crate) fn enable_plugin(app: &mut App, query: &str) { } let query = query.to_string(); let Some(mgr) = app.plugin_manager.clone() else { - app.messages_state - .toasts - .error("Plugin manager not available"); + plugin_manager_unavailable(app); return; }; let tx = app.tui_cmd_tx.clone(); @@ -138,9 +138,7 @@ pub(crate) fn disable_plugin(app: &mut App, query: &str) { } let query = query.to_string(); let Some(mgr) = app.plugin_manager.clone() else { - app.messages_state - .toasts - .error("Plugin manager not available"); + plugin_manager_unavailable(app); return; }; let tx = app.tui_cmd_tx.clone(); @@ -175,9 +173,7 @@ pub(crate) fn doctor_plugin(app: &mut App, query: Option<&str>) { } let query = query.map(|s| s.to_string()); let Some(mgr) = app.plugin_manager.clone() else { - app.messages_state - .toasts - .error("Plugin manager not available"); + plugin_manager_unavailable(app); return; }; let tx = app.tui_cmd_tx.clone(); @@ -234,9 +230,7 @@ pub(crate) fn remove_plugin(app: &mut App, query: &str) { } let query = query.to_string(); let Some(mgr) = app.plugin_manager.clone() else { - app.messages_state - .toasts - .error("Plugin manager not available"); + plugin_manager_unavailable(app); return; }; let tx = app.tui_cmd_tx.clone(); @@ -279,9 +273,7 @@ pub(crate) fn install_plugin(app: &mut App, source_path: &str) { } let source_path = source_path.to_string(); let Some(mgr) = app.plugin_manager.clone() else { - app.messages_state - .toasts - .error("Plugin manager not available"); + plugin_manager_unavailable(app); return; }; let tx = app.tui_cmd_tx.clone(); @@ -339,7 +331,7 @@ pub(crate) fn apply_plugin_list_finished(app: &mut App, lines: Vec, erro .error(&format!("Plugin list failed: {err}")); return; } - app.show_short_or_info(crate::components::dialogs::info::InfoType::Stats, lines); + app.open_info_dialog(crate::components::dialogs::info::InfoType::Stats, lines); } /// Apply the result of a plugin info operation. @@ -355,7 +347,7 @@ pub(crate) fn apply_plugin_info_finished( .error(&format!("Plugin info: {err}")); return; } - app.show_short_or_info(crate::components::dialogs::info::InfoType::Stats, lines); + app.open_info_dialog(crate::components::dialogs::info::InfoType::Stats, lines); } /// Apply the result of a plugin enable operation. @@ -404,7 +396,7 @@ pub(crate) fn apply_plugin_doctor_finished( .error(&format!("Plugin doctor: {err}")); return; } - app.show_short_or_info( + app.open_info_dialog( crate::components::dialogs::info::InfoType::DoctorReport, lines, ); @@ -467,15 +459,16 @@ pub(crate) fn apply_plugin_install_finished( .error(&format!("Install failed: {err}")); return; } - app.show_short_or_info(crate::components::dialogs::info::InfoType::Stats, lines); + app.open_info_dialog(crate::components::dialogs::info::InfoType::Stats, lines); } pub(crate) fn dispatch_plugin_enable(app: &mut App, argument: &str) { let args = argument; if args.is_empty() { - app.messages_state - .toasts - .warning("Usage: /plugin enable "); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /plugin enable ".to_string()], + ); } else { crate::commands::plugin_management::enable_plugin(app, args); } @@ -484,9 +477,10 @@ pub(crate) fn dispatch_plugin_enable(app: &mut App, argument: &str) { pub(crate) fn dispatch_plugin_disable(app: &mut App, argument: &str) { let args = argument; if args.is_empty() { - app.messages_state - .toasts - .warning("Usage: /plugin disable "); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /plugin disable ".to_string()], + ); } else { crate::commands::plugin_management::disable_plugin(app, args); } @@ -495,9 +489,10 @@ pub(crate) fn dispatch_plugin_disable(app: &mut App, argument: &str) { pub(crate) fn dispatch_plugin_remove(app: &mut App, argument: &str) { let args = argument; if args.is_empty() { - app.messages_state - .toasts - .warning("Usage: /plugin remove "); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /plugin remove ".to_string()], + ); } else { crate::commands::plugin_management::remove_plugin(app, args); } @@ -506,9 +501,10 @@ pub(crate) fn dispatch_plugin_remove(app: &mut App, argument: &str) { pub(crate) fn dispatch_plugin_install(app: &mut App, argument: &str) { let args = argument; if args.is_empty() { - app.messages_state - .toasts - .warning("Usage: /plugin install "); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /plugin install ".to_string()], + ); } else { crate::commands::plugin_management::install_plugin(app, args); } @@ -601,7 +597,8 @@ mod tests { let dialog_open = app .focus_manager .has_component::(); - assert!(!toasts.is_empty() || dialog_open); + assert!(toasts.is_empty()); + assert!(dialog_open); } #[test] @@ -746,7 +743,8 @@ mod tests { let dialog_open = app .focus_manager .has_component::(); - assert!(!toasts.is_empty() || dialog_open); + assert!(toasts.is_empty()); + assert!(dialog_open); } #[test] diff --git a/crates/codegg-tui/src/commands/plugins.rs b/crates/codegg-tui/src/commands/plugins.rs index 44f8607f1..d4416a537 100644 --- a/crates/codegg-tui/src/commands/plugins.rs +++ b/crates/codegg-tui/src/commands/plugins.rs @@ -203,7 +203,7 @@ fn build_invocation( /// diagnostic effects but show an error/warning toast. /// 4. If no structured response exists but `stdout` exists, render stdout /// as chat/plain text or info dialog depending on length. -/// 5. If only `stderr` exists, render as warning/error diagnostics. +/// 5. If only `stderr` exists, render it as diagnostics. /// 6. If nothing exists, show a concise "plugin command produced no output" /// warning. pub(crate) fn apply_plugin_command_finished( @@ -284,9 +284,6 @@ pub(crate) fn apply_plugin_command_finished( if !err_out.is_empty() { let mut lines: Vec = err_out.lines().map(|s| s.to_string()).collect(); lines.insert(0, format!("Plugin '{command}' stderr:")); - app.messages_state - .toasts - .warning(&format!("Plugin '{command}' produced stderr output")); app.show_short_or_info(crate::components::dialogs::info::InfoType::Stats, lines); return; } @@ -610,7 +607,7 @@ mod tests { } #[test] - fn stderr_fallback_shows_warning() { + fn stderr_fallback_surfaces_output() { let mut app = make_test_app(); apply_plugin_command_finished( &mut app, @@ -628,8 +625,11 @@ mod tests { .map(|t| t.message.clone()) .collect(); assert!( - toasts.iter().any(|t| t.contains("err-cmd")), - "stderr should show warning, got: {toasts:?}" + toasts.iter().any(|t| t.contains("some stderr")) + || app + .focus_manager + .has_component::(), + "stderr output should be surfaced, got: {toasts:?}" ); } diff --git a/crates/codegg-tui/src/commands/policy.rs b/crates/codegg-tui/src/commands/policy.rs index 3a607542c..852429964 100644 --- a/crates/codegg-tui/src/commands/policy.rs +++ b/crates/codegg-tui/src/commands/policy.rs @@ -333,9 +333,10 @@ pub(crate) fn apply_snapshot_loaded( } } PolicySnapshotReason::SelectorRefresh => { - for line in format_policy_detail(&view) { - app.messages_state.toasts.info(&line); - } + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Control, + format_policy_detail(&view), + ); } PolicySnapshotReason::AfterUpdate => {} } @@ -402,13 +403,7 @@ pub(crate) fn request_policy_change( sandbox_profile: Option, ) { if approval_mode.is_none() && sandbox_profile.is_none() { - // Bare command: show the cached state, then refresh. Never opens - // a confirmation dialog for the already-active selection. - if let Some(line) = app.policy_ui.status_line() { - app.messages_state - .toasts - .info(&format!("Runtime policy: {}", line)); - } + // The cached state is already visible in the status bar; refresh it. start_snapshot_refresh(app, PolicySnapshotReason::SelectorRefresh); return; } @@ -478,7 +473,6 @@ pub(crate) fn apply_policy_confirm_result(app: &mut App, confirmed: bool) -> boo }; if !confirmed { // Cancelling a mode-change dialog changes nothing. - app.messages_state.toasts.info("Runtime policy unchanged."); return true; } let done = pending.confirmations_done + 1; @@ -749,14 +743,11 @@ pub(crate) fn apply_policy_updated( "Runtime policy updated: {}. Effective state differs from the request — see /policy.", line )); - } else { - app.messages_state - .toasts - .info(&format!("Runtime policy updated: {}", line)); - } - for detail in format_policy_detail(&view) { - app.messages_state.toasts.info(&detail); } + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Control, + format_policy_detail(&view), + ); } fn policy_update_error_hint(code: &str, message: &str) -> String { diff --git a/crates/codegg-tui/src/commands/presence.rs b/crates/codegg-tui/src/commands/presence.rs index ed50b7fd3..d67922de4 100644 --- a/crates/codegg-tui/src/commands/presence.rs +++ b/crates/codegg-tui/src/commands/presence.rs @@ -267,14 +267,18 @@ pub(crate) fn apply_presence_snapshot_loaded( } } +fn report_missing_project(app: &mut App) { + app.messages_state + .toasts + .info("No active project — open a project tab first"); +} + /// Render the collaborator panel for the active project, fetching on demand /// when the entry is missing or stale, then opening the scrollable dialog. /// No session state is mutated. pub(crate) fn show_collaborators(app: &mut App) { let Some(project_id) = app.active_project_id().map(str::to_string) else { - app.messages_state - .toasts - .info("No active project — open a project tab first"); + report_missing_project(app); return; }; if app.presence.needs_refresh(&project_id) { @@ -290,9 +294,7 @@ pub(crate) fn show_collaborators(app: &mut App) { /// Explicit `/collaborators refresh` path. pub(crate) fn refresh_collaborators(app: &mut App) { let Some(project_id) = app.active_project_id().map(str::to_string) else { - app.messages_state - .toasts - .info("No active project — open a project tab first"); + report_missing_project(app); return; }; // `start_refresh_presence` coalesces while loading; for an explicit user diff --git a/crates/codegg-tui/src/commands/project_picker.rs b/crates/codegg-tui/src/commands/project_picker.rs index 09d13b0b6..f5db6b157 100644 --- a/crates/codegg-tui/src/commands/project_picker.rs +++ b/crates/codegg-tui/src/commands/project_picker.rs @@ -398,9 +398,10 @@ pub(crate) fn apply_project_get_loaded( match workspaces.len() { 0 => { // No workspaces — create a compat tab with project_id only - app.messages_state - .toasts - .info("Project has no workspaces — using compat fallback"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Stats, + vec!["Project has no workspaces — using compat fallback".to_string()], + ); open_or_focus_project( app, target_project_id, @@ -1042,9 +1043,7 @@ pub(crate) fn apply_project_update_finished( previous_display_name.unwrap_or_default(), previous_root.unwrap_or_default(), ); - app.messages_state - .toasts - .info("Project renamed and directory rebound"); + app.refresh_project_catalog(); } @@ -1112,7 +1111,6 @@ pub(crate) fn start_project_lifecycle( return Some(TuiCommand::ProjectLifecycleFinished { picker_request_id, project_id, - restored: restore, error: Some("Core unavailable".to_string()), }); }; @@ -1139,7 +1137,6 @@ pub(crate) fn start_project_lifecycle( Some(TuiCommand::ProjectLifecycleFinished { picker_request_id, project_id, - restored: restore, error, }) }, @@ -1150,7 +1147,6 @@ pub(crate) fn apply_project_lifecycle_finished( app: &mut App, picker_request_id: u64, project_id: String, - restored: bool, error: Option, ) { let Some(picker) = app.dialog_state.project_picker.as_mut() else { @@ -1167,11 +1163,6 @@ pub(crate) fn apply_project_lifecycle_finished( picker.phase = crate::app::state::PickerPhase::Error; } else { picker.reset_to_catalog(); - app.messages_state.toasts.info(if restored { - "Project reactivated" - } else { - "Project deactivated" - }); } app.refresh_project_catalog(); } @@ -1329,10 +1320,13 @@ pub(crate) fn apply_project_deleted(app: &mut App, project_id: &str, deleted_ses } } app.presence.clear_project(project_id); - app.messages_state.toasts.info(&format!( - "Project destroyed; {deleted_session_count} session{} permanently deleted", - if deleted_session_count == 1 { "" } else { "s" } - )); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Stats, + vec![format!( + "Project destroyed; {deleted_session_count} session{} permanently deleted", + if deleted_session_count == 1 { "" } else { "s" } + )], + ); app.schedule_manifest_save(); app.refresh_project_catalog(); } @@ -1619,7 +1613,6 @@ pub(crate) fn apply_project_registered( let _ = project_id; if let Some(err) = error { - app.messages_state.toasts.error(&err); picker.last_error = Some(err); picker.phase = crate::app::state::PickerPhase::Error; return; diff --git a/crates/codegg-tui/src/commands/promotion.rs b/crates/codegg-tui/src/commands/promotion.rs index 39880b509..ed821c399 100644 --- a/crates/codegg-tui/src/commands/promotion.rs +++ b/crates/codegg-tui/src/commands/promotion.rs @@ -22,6 +22,13 @@ use codegg::protocol::skill::{ SkillProposalSummaryDto, }; +fn show_promotion_usage(app: &mut App, message: &str) { + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec![message.to_string()], + ); +} + /// Send one promotion request to the daemon. pub(crate) fn start_skill_promotion(app: &mut App, request: SkillPromotionRequestDto) { let action = request.action; @@ -108,9 +115,10 @@ pub(crate) fn apply_skill_promotion_finished( SkillPromotionActionDto::List => { let proposals = result.proposals.unwrap_or_default(); if proposals.is_empty() { - app.messages_state - .toasts - .info("No skill proposals yet. Use /skill promote ."); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::MemoryResults, + vec!["No skill proposals yet. Use /skill promote .".to_string()], + ); return; } let mut lines = vec![format!("Skill proposals ({}):", proposals.len())]; @@ -139,24 +147,19 @@ pub(crate) fn apply_skill_promotion_finished( ); } SkillPromotionActionDto::Reject => { - if result.changed { - app.messages_state.toasts.info("Skill proposal rejected."); - } else { + if !result.changed { app.messages_state .toasts .warning("Proposal not found or is not awaiting review."); } } SkillPromotionActionDto::Publish => { - let Some(relative_path) = result.published_relative_path else { + if result.published_relative_path.is_none() { app.messages_state .toasts .warning("The daemon published no skill"); return; - }; - app.messages_state - .toasts - .success(&format!("Published skill: {relative_path}")); + } // The existing daemon-owned refresh path is the only authority // allowed to publish a new runtime asset generation. crate::commands::agents::start_refresh_assets(app); @@ -217,27 +220,16 @@ fn proposal_detail_lines(detail: &SkillProposalDetailDto) -> Vec { pub(crate) fn dispatch_skill_promote(app: &mut App, argument: &str) { if app.prompt_state.pending_send { - app.messages_state - .toasts - .warning("Still waiting for previous prompt to finish"); return; } let Some(habit_id) = codegg::memory::habit::HabitId::parse(argument) else { - app.messages_state - .toasts - .warning("Usage: /skill promote "); + show_promotion_usage(app, "Usage: /skill promote "); return; }; let Some(session_id) = app.session_state.session.as_ref().map(|s| s.id.clone()) else { - app.messages_state - .toasts - .warning("Start or select a session before promoting a habit"); return; }; let Some(workspace_id) = app.active_workspace_id().map(str::to_owned) else { - app.messages_state - .toasts - .warning("Select a workspace before promoting a habit"); return; }; // M007-I (work package B): the daemon owns the promotion @@ -259,15 +251,9 @@ pub(crate) fn dispatch_skill_promote(app: &mut App, argument: &str) { pub(crate) fn dispatch_skill_proposals(app: &mut App) { let Some(session_id) = app.session_state.session.as_ref().map(|s| s.id.clone()) else { - app.messages_state - .toasts - .warning("Start or select a session before listing proposals"); return; }; let Some(workspace_id) = app.active_workspace_id().map(str::to_owned) else { - app.messages_state - .toasts - .warning("Select a workspace before listing proposals"); return; }; crate::commands::promotion::start_skill_promotion( @@ -285,15 +271,9 @@ pub(crate) fn dispatch_skill_proposals(app: &mut App) { pub(crate) fn dispatch_skill_proposal(app: &mut App, argument: &str) { let Some(session_id) = app.session_state.session.as_ref().map(|s| s.id.clone()) else { - app.messages_state - .toasts - .warning("Start or select a session before acting on a proposal"); return; }; let Some(workspace_id) = app.active_workspace_id().map(str::to_owned) else { - app.messages_state - .toasts - .warning("Select a workspace before acting on a proposal"); return; }; let mut action = codegg::protocol::skill::SkillPromotionActionDto::Preview; @@ -301,18 +281,14 @@ pub(crate) fn dispatch_skill_proposal(app: &mut App, argument: &str) { let id_text = if let Some(publish_args) = argument.strip_prefix("publish") { let parts = publish_args.split_whitespace().collect::>(); if parts.len() != 2 { - app.messages_state - .toasts - .warning("Usage: /skill proposal publish [project|global]"); + show_promotion_usage(app, "Usage: /skill proposal publish [project|global]"); return; } target_scope = Some(match parts[1] { "project" => codegg::protocol::skill::SkillTargetScopeDto::Project, "global" => codegg::protocol::skill::SkillTargetScopeDto::Global, _ => { - app.messages_state - .toasts - .warning("Publication scope must be project or global"); + show_promotion_usage(app, "Publication scope must be project or global"); return; } }); @@ -325,9 +301,10 @@ pub(crate) fn dispatch_skill_proposal(app: &mut App, argument: &str) { argument.trim().to_string() }; if codegg::skills::promotion::SkillProposalId::parse(&id_text).is_none() { - app.messages_state - .toasts - .warning("Usage: /skill proposal or /skill proposal reject "); + show_promotion_usage( + app, + "Usage: /skill proposal or /skill proposal reject ", + ); return; } crate::commands::promotion::start_skill_promotion( diff --git a/crates/codegg-tui/src/commands/queue.rs b/crates/codegg-tui/src/commands/queue.rs index e8ca3f098..29ea6344b 100644 --- a/crates/codegg-tui/src/commands/queue.rs +++ b/crates/codegg-tui/src/commands/queue.rs @@ -96,6 +96,24 @@ pub fn send_now_refusal_message( } } +/// M006: the sentence for a reorder that produced no mutation. +/// +/// Chosen here rather than in the dialog for the same reason as +/// [`send_now_refusal_message`]: the input layer owns the notification, and +/// a value keeps the test able to assert *which* refusal happened. +pub fn reorder_refusal_message( + reason: crate::components::dialogs::queue::QueueReorderRefusal, +) -> &'static str { + use crate::components::dialogs::queue::QueueReorderRefusal; + match reason { + QueueReorderRefusal::Delivering => { + "That prompt is being delivered right now, so it cannot be reordered." + } + QueueReorderRefusal::AlreadyEarliest => "That prompt is already first in the queue.", + QueueReorderRefusal::AlreadyLatest => "That prompt is already last in the queue.", + } +} + /// Who receives a steering payload, and who still holds it if the daemon /// refuses. /// @@ -378,20 +396,12 @@ pub fn open_queue_box(app: &mut App) { .focus_manager .has_dialog(crate::components::component::DialogType::Queue) { - // `FocusManager::push` refuses a duplicate dialog type, so a second - // `/queue` would otherwise silently do nothing while the command - // looked like it had been swallowed. - app.messages_state - .toasts - .info("The prompt queue box is already open."); + // The existing box is already the visible result of `/queue`. return; } let session_id = app.active_session_id().map(str::to_owned); let Some(session_id) = session_id else { - app.messages_state - .toasts - .info("No session is bound yet, so there is no prompt queue to show."); return; }; @@ -430,6 +440,12 @@ pub fn adopt_queue_projection( app.apply_user_prompt_queue_loaded(session_id, entries, None); } +fn report_queue_unavailable(app: &mut App) { + app.messages_state + .toasts + .error("Prompt queue unavailable: no core connection"); +} + /// Start `UserPromptQueueDelete` for one entry. /// /// The `entry_id` is carried from the box rather than re-read from the current @@ -437,15 +453,10 @@ pub fn adopt_queue_projection( /// cannot make the delete name a different prompt. pub fn start_queue_delete(app: &mut App, entry_id: String) { let Some(session_id) = app.active_session_id().map(str::to_owned) else { - app.messages_state - .toasts - .info("No session is bound, so there is nothing to delete from."); return; }; let Some(core_client) = app.core_client.clone() else { - app.messages_state - .toasts - .error("Prompt queue unavailable: no core connection"); + report_queue_unavailable(app); return; }; @@ -556,9 +567,6 @@ pub fn apply_queue_delete_finished( /// queue the same sentence twice. pub fn start_queue_add(app: &mut App, text: String, run_at_ms: Option) { let Some(session_id) = app.active_session_id().map(str::to_owned) else { - app.messages_state - .toasts - .info("No session is bound, so there is nothing to add to."); return; }; let Some(core_client) = app.core_client.clone() else { @@ -567,9 +575,7 @@ pub fn start_queue_add(app: &mut App, text: String, run_at_ms: Option) { crate::components::component::DialogType::Queue, |dialog| dialog.restore_compose(None, text), ); - app.messages_state - .toasts - .error("Prompt queue unavailable: no core connection"); + report_queue_unavailable(app); return; }; @@ -664,9 +670,6 @@ pub fn apply_queue_add_finished( /// Send `UserPromptQueueEdit` for one entry. pub fn start_queue_edit(app: &mut App, entry_id: String, text: String, run_at_ms: Option) { let Some(session_id) = app.active_session_id().map(str::to_owned) else { - app.messages_state - .toasts - .info("No session is bound, so there is nothing to edit."); return; }; let Some(core_client) = app.core_client.clone() else { @@ -675,9 +678,7 @@ pub fn start_queue_edit(app: &mut App, entry_id: String, text: String, run_at_ms crate::components::component::DialogType::Queue, |dialog| dialog.restore_compose(Some(entry_id), text), ); - app.messages_state - .toasts - .error("Prompt queue unavailable: no core connection"); + report_queue_unavailable(app); return; }; @@ -766,15 +767,10 @@ pub fn apply_queue_edit_finished( /// Send `UserPromptQueueReorder` with the permutation the box built. pub fn start_queue_reorder(app: &mut App, entry_ids: Vec) { let Some(session_id) = app.active_session_id().map(str::to_owned) else { - app.messages_state - .toasts - .info("No session is bound, so there is nothing to reorder."); return; }; let Some(core_client) = app.core_client.clone() else { - app.messages_state - .toasts - .error("Prompt queue unavailable: no core connection"); + report_queue_unavailable(app); return; }; @@ -848,15 +844,10 @@ pub fn apply_queue_reorder_finished( /// a turn that ended a moment ago. pub fn start_queue_send_now(app: &mut App, entry_id: String) { let Some(session_id) = app.active_session_id().map(str::to_owned) else { - app.messages_state - .toasts - .info("No session is bound, so there is nothing to send."); return; }; let Some(core_client) = app.core_client.clone() else { - app.messages_state - .toasts - .error("Prompt queue unavailable: no core connection"); + report_queue_unavailable(app); return; }; @@ -1048,6 +1039,45 @@ mod tests { use super::*; use codegg_core::session::user_prompt_queue::UserPromptQueueError; + /// With no session attached there is no queue to show. + /// + /// The refusal used to be a toast repeating the empty session state the TUI + /// already renders. The notification-surface workstream removed it, so the + /// box neither opens nor announces its absence — and the session-bound half + /// is the control that makes the silence a decision rather than a command + /// that never ran. + #[test] + fn opening_the_queue_box_is_silent_when_no_session_is_attached() { + let mut unattached = App::new_for_testing("/tmp".into()); + assert!( + unattached.active_session_id().is_none(), + "the fixture must have no session, or this case proves nothing" + ); + open_queue_box(&mut unattached); + assert!( + !unattached.ui_state.dialog.is_open(), + "no session means no queue to show, got {:?}", + unattached.ui_state.dialog + ); + assert!( + unattached.messages_state.toasts.is_empty(), + "the empty session state is the explanation; a toast would duplicate it" + ); + + let mut attached = App::new_for_testing("/tmp".into()); + let tab = attached + .project_tabs + .active_mut() + .expect("a testing app has one project tab"); + tab.session_id = Some("queue-test-session".into()); + open_queue_box(&mut attached); + assert!( + matches!(attached.ui_state.dialog, Dialog::Queue), + "the control must open the box, got {:?}", + attached.ui_state.dialog + ); + } + /// Every code this module maps is pinned against the daemon's real /// `code()`. These are literals on purpose — the TUI must not import the /// daemon's error enum — so the pin is the only thing standing between a diff --git a/crates/codegg-tui/src/commands/reasoning.rs b/crates/codegg-tui/src/commands/reasoning.rs index 4a6bca816..3b712ffb0 100644 --- a/crates/codegg-tui/src/commands/reasoning.rs +++ b/crates/codegg-tui/src/commands/reasoning.rs @@ -115,6 +115,13 @@ pub fn refusal_message(code: &str, message: &str) -> String { } } +fn report_preference_unavailable(app: &mut App) { + app.messages_state.toasts.error( + "Extended thinking unavailable: this frontend has no daemon connection, so the \ + selection cannot be stored", + ); +} + /// Write one selection through the daemon. /// /// The completion lands as `TuiCommand::ReasoningPreferenceUpdated`; the @@ -126,10 +133,7 @@ pub(crate) fn start_preference_update( previous: ReasoningMode, ) { let Some(core_client) = app.core_client.clone() else { - app.messages_state.toasts.error( - "Extended thinking unavailable: this frontend has no daemon connection, so the \ - selection cannot be stored", - ); + report_preference_unavailable(app); return; }; let request_id = app.ui_state.reasoning_request.begin(); @@ -353,10 +357,7 @@ pub(crate) fn dispatch_reasoning(app: &mut App) { // // The daemon owns the selection, so it needs somewhere to store it. if app.core_client.is_none() { - app.messages_state.toasts.error( - "Extended thinking unavailable: this frontend has no daemon connection, so \ - the selection cannot be stored", - ); + report_preference_unavailable(app); return; } let options = crate::commands::reasoning::option_set(app); @@ -387,8 +388,6 @@ pub(crate) fn dispatch_reasoning(app: &mut App) { .unwrap_or("this provider") )); app.messages_state.toasts.warning(&message); - } else { - app.messages_state.toasts.info(&message); } crate::commands::reasoning::start_preference_update( app, diff --git a/crates/codegg-tui/src/commands/research.rs b/crates/codegg-tui/src/commands/research.rs index f0d0fa124..0833e05e2 100644 --- a/crates/codegg-tui/src/commands/research.rs +++ b/crates/codegg-tui/src/commands/research.rs @@ -21,6 +21,18 @@ fn bullet_list(items: &[String]) -> String { out } +fn report_research_failure(app: &mut App, message: &str) { + app.messages_state.toasts.error(message); +} + +fn report_section_failure(app: &mut App, message: &str) { + app.messages_state.toasts.warning(message); +} + +fn report_missing_research_section(app: &mut App) { + report_section_failure(app, "Could not load section content"); +} + #[allow(dead_code)] #[cfg(test)] pub(crate) async fn handle_research_list_runs(app: &mut App) { @@ -31,16 +43,10 @@ pub(crate) async fn handle_research_list_runs(app: &mut App) { if let Some(ref mut browser) = app.dialog_state.research_browser { browser.loading = false; browser.set_runs(runs); - } else { - app.messages_state - .toasts - .info("No research browser dialog open"); } } Err(e) => { - app.messages_state - .toasts - .error(&format!("Failed to list research runs: {}", e)); + report_research_failure(app, &format!("Failed to list research runs: {}", e)); if let Some(ref mut browser) = app.dialog_state.research_browser { browser.loading = false; } @@ -58,16 +64,10 @@ pub(crate) async fn handle_research_load_run(app: &mut App, run_id: String) { if let Some(ref mut browser) = app.dialog_state.research_browser { browser.loading = false; browser.set_bundle(bundle); - } else { - app.messages_state - .toasts - .info("No research browser dialog open"); } } Err(e) => { - app.messages_state - .toasts - .error(&format!("Failed to load research run: {}", e)); + report_research_failure(app, &format!("Failed to load research run: {}", e)); if let Some(ref mut browser) = app.dialog_state.research_browser { browser.loading = false; } @@ -196,9 +196,7 @@ pub(crate) async fn handle_research_load_section(app: &mut App, run_id: String, if let Some((section, content)) = result { browser.set_report_content(section, content); } else { - app.messages_state - .toasts - .warning("Could not load section content"); + report_missing_research_section(app); } } } @@ -250,7 +248,7 @@ pub(crate) fn apply_research_runs_loaded( { return; } - app.messages_state.toasts.error(&err); + report_research_failure(app, &err); if let Some(ref mut browser) = app.dialog_state.research_browser { browser.loading = false; } @@ -316,7 +314,7 @@ pub(crate) fn apply_research_run_loaded( { return; } - app.messages_state.toasts.error(&err); + report_research_failure(app, &err); if let Some(ref mut browser) = app.dialog_state.research_browser { browser.loading = false; } @@ -487,7 +485,7 @@ pub(crate) fn apply_research_section_loaded( if let Some(ref mut browser) = app.dialog_state.research_browser { browser.loading = false; } - app.messages_state.toasts.warning(&err); + report_section_failure(app, &err); return; } @@ -499,9 +497,7 @@ pub(crate) fn apply_research_section_loaded( if let Some((section_type, content)) = content { browser.set_report_content(section_type, content); } else { - app.messages_state - .toasts - .warning("Could not load section content"); + report_missing_research_section(app); } } } @@ -510,9 +506,10 @@ pub(crate) fn dispatch_research(app: &mut App, argument: &str) { let args = argument; app.ui_state.command_mode = false; if args.is_empty() { - app.messages_state - .toasts - .warning("Usage: /research [--mode ] [--depth ]"); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /research [--mode ] [--depth ]".to_string()], + ); } else { app.handle_research_command(args); } @@ -527,9 +524,10 @@ pub(crate) fn dispatch_research_open(app: &mut App, argument: &str) { let run_id = argument; app.ui_state.command_mode = false; if run_id.is_empty() { - app.messages_state - .toasts - .warning("Usage: /research open "); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /research open ".to_string()], + ); } else { app.handle_research_open_command(run_id); } @@ -545,8 +543,12 @@ pub(crate) fn dispatch_research_show(app: &mut App, argument: &str) { let section = parts[0]; let run_id = parts.get(1).copied().unwrap_or("").trim(); if run_id.is_empty() { - app.messages_state.toasts.warning( - "Usage: /research show
(section: report, brief, claims, handoff)", + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec![ + "Usage: /research show
(section: report, brief, claims, handoff)" + .to_string(), + ], ); } else { app.open_dialog(Dialog::ResearchBrowser); diff --git a/crates/codegg-tui/src/commands/revert.rs b/crates/codegg-tui/src/commands/revert.rs index 65def11b0..f59540cc8 100644 --- a/crates/codegg-tui/src/commands/revert.rs +++ b/crates/codegg-tui/src/commands/revert.rs @@ -74,14 +74,16 @@ pub(crate) fn apply_revert_finished( } CoreResponse::GitRevert { result } => { if result.paths.is_empty() { - app.messages_state - .toasts - .warning("The revert restored nothing"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Stats, + vec!["The revert restored nothing".to_string()], + ); return; } - app.messages_state - .toasts - .success(&format!("Reverted: {}", result.paths.join(", "))); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Stats, + vec![format!("Reverted: {}", result.paths.join(", "))], + ); } _ => { app.messages_state @@ -95,7 +97,10 @@ pub(crate) fn dispatch_revert(app: &mut App, argument: &str) { let path_arg = argument; app.ui_state.command_mode = false; if path_arg.is_empty() { - app.messages_state.toasts.warning("Usage: /revert "); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /revert ".to_string()], + ); } else { // M007-H (work package C): the daemon owns the write. // The TUI no longer spawns `git` for this. diff --git a/crates/codegg-tui/src/commands/security.rs b/crates/codegg-tui/src/commands/security.rs index 5a23c894b..318051081 100644 --- a/crates/codegg-tui/src/commands/security.rs +++ b/crates/codegg-tui/src/commands/security.rs @@ -57,8 +57,8 @@ pub(crate) fn handle_security_review_run( /// Apply a completed security review to the App: store the latest /// receipt, push the rendered report into the message timeline, and -/// surface a success toast. Shared by the inline `SecurityReviewRun` -/// handler and the `SecurityReviewFinished` completion arm. +/// open the requested panel or retain its short Usage instruction. Shared by +/// the inline `SecurityReviewRun` handler and the `SecurityReviewFinished` arm. pub(crate) fn apply_security_review_receipt( app: &mut App, receipt: codegg::security::workflow::SecurityReviewReceipt, @@ -80,12 +80,13 @@ pub(crate) fn apply_security_review_receipt( app.set_latest_security_review(receipt); if open_panel { app.open_dialog(crate::Dialog::SecurityReview); - app.messages_state - .toasts - .success("Security review complete — result panel opened."); } else { - app.messages_state.toasts.success( - "Security review complete — run /security-review show to open the result panel.", + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![ + "Security review complete — run /security-review show to open the result panel." + .to_string(), + ], ); } } @@ -144,10 +145,6 @@ pub(crate) fn dispatch_security_review(app: &mut App, argument: &str) { let id = codegg::security::workflow::SecurityReviewRunId::new(); let lsp_tool = app.lsp_tool.clone(); - app.messages_state - .toasts - .info("Security review started. The result will appear in the message log when complete."); - // Spawn the review in a tokio task so the renderer stays // responsive. The completion path sends // `TuiCommand::SecurityReviewFinished` back through diff --git a/crates/codegg-tui/src/commands/session_report.rs b/crates/codegg-tui/src/commands/session_report.rs index 75aa429a6..f492237cc 100644 --- a/crates/codegg-tui/src/commands/session_report.rs +++ b/crates/codegg-tui/src/commands/session_report.rs @@ -21,7 +21,10 @@ pub(crate) fn dispatch_status(app: &mut App) { if let Some(line) = app.policy_ui.status_line() { status.push_str(&format!(" | {}", line)); } - app.messages_state.toasts.info(&status); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Stats, + vec![status], + ); } pub(crate) fn dispatch_context(app: &mut App) { @@ -45,19 +48,24 @@ pub(crate) fn dispatch_plan(app: &mut App, argument: &str) { // that answer. The local checklist is **gone**: a second // copy of the plan is a second source of truth. if !argument.trim().is_empty() { - app.messages_state - .toasts - .warning("The plan is the daemon's; /plan takes no argument"); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec!["The plan is the daemon's; /plan takes no argument".to_string()], + ); return; } let Some(plan) = app.session_state_derived.plan.clone() else { - app.messages_state - .toasts - .info("No plan published by the daemon"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Stats, + vec!["No plan published by the daemon".to_string()], + ); return; }; if plan.items.is_empty() { - app.messages_state.toasts.info("Plan is empty"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Stats, + vec!["Plan is empty".to_string()], + ); return; } let items: Vec = plan diff --git a/crates/codegg-tui/src/commands/sessions.rs b/crates/codegg-tui/src/commands/sessions.rs index e8bd6dfc9..7050ab71f 100644 --- a/crates/codegg-tui/src/commands/sessions.rs +++ b/crates/codegg-tui/src/commands/sessions.rs @@ -511,26 +511,15 @@ pub(crate) fn start_empty_cleanup(app: &mut App) { let ids = app.dialog_state.session_dialog.empty_session_ids(); app.dialog_state.session_dialog.clear_cleanup_arm(); if ids.is_empty() { - app.messages_state - .toasts - .info("No empty sessions to delete"); return; } - let count = ids.len(); start_bulk_delete(app, ids); - app.messages_state - .toasts - .info(&format!("Deleting {count} empty session(s)")); return; } - match app.dialog_state.session_dialog.arm_empty_cleanup() { - Some(count) => app.messages_state.toasts.warning(&format!( + if let Some(count) = app.dialog_state.session_dialog.arm_empty_cleanup() { + app.messages_state.toasts.warning(&format!( "Press C again to delete {count} empty session(s); the active session is kept" - )), - None => app - .messages_state - .toasts - .info("No empty sessions to delete"), + )); } app.refresh_sessions_dialog_pending_rows(); } @@ -544,7 +533,7 @@ pub(crate) fn apply_session_mutation_finished( request_id: u64, op: SessionMutationOp, _affected_ids: Vec, - message: String, + _message: String, reload_after: bool, error: Option, ) { @@ -563,9 +552,6 @@ pub(crate) fn apply_session_mutation_finished( if !app.dialog_state.session_mutation_request.finish(request_id) { return; } - if !message.is_empty() { - app.messages_state.toasts.info(&message); - } if op == SessionMutationOp::UndoDelete { app.undo_session_id = None; app.undo_until = None; @@ -1482,10 +1468,7 @@ pub(crate) fn apply_unshare_session_finished( return; } if let Some(dto) = session { - if !assign_session_from_dto(app, dto) { - return; - } - app.messages_state.toasts.info("Session unshared"); + assign_session_from_dto(app, dto); } } @@ -1945,6 +1928,7 @@ fn transcript_part(p: &codegg::session::message::PartInfo) -> crate::components: output: output.clone().unwrap_or_default(), status: status.clone(), duration_ms: None, + started_at: None, exit_code: None, output_lines: None, expanded: false, @@ -2071,7 +2055,6 @@ pub(crate) async fn handle_load_session_messages(app: &mut App, session_id: Stri } pub(crate) fn start_load_session_messages(app: &mut App, session_id: String) { - app.messages_state.toasts.info("Loading messages..."); let request_id = app.dialog_state.session_messages_request.begin(); let core_client = app.core_client.clone(); @@ -2205,9 +2188,10 @@ pub(crate) fn apply_session_messages_loaded( /// "Untitled" row on every launch and every keypress. pub(crate) fn start_new_session(app: &mut App) { app.begin_draft_session(); - app.messages_state - .toasts - .info("New session — the first prompt creates it"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["New session — the first prompt creates it".to_string()], + ); } /// Apply a `NewSessionCreated` completion. Stale completions (mismatched @@ -2251,7 +2235,6 @@ pub(crate) fn start_create_from_template( let core_client = app.core_client.clone(); let project_dir = app.active_workspace_root().unwrap_or_default(); let project_id = app.active_project_key().unwrap_or_default(); - let template_name = template.name.clone(); let agent = template.agent.clone(); let model = template.model.clone(); let tx = app.tui_cmd_tx.clone(); @@ -2268,7 +2251,6 @@ pub(crate) fn start_create_from_template( session: None, agent, model, - template_name, error: Some("Core unavailable — check daemon status with /doctor".to_string()), }); }; @@ -2288,7 +2270,6 @@ pub(crate) fn start_create_from_template( session: Some(session), agent, model, - template_name, error: None, }), Ok(CoreResponse::Error { message, .. }) => { @@ -2297,7 +2278,6 @@ pub(crate) fn start_create_from_template( session: None, agent, model, - template_name, error: Some(message), }) } @@ -2306,7 +2286,6 @@ pub(crate) fn start_create_from_template( session: None, agent, model, - template_name, error: Some("Unexpected core response".to_string()), }), Err(e) => Some(TuiCommand::TemplateSessionCreated { @@ -2314,7 +2293,6 @@ pub(crate) fn start_create_from_template( session: None, agent, model, - template_name, error: Some(e.to_string()), }), } @@ -2328,7 +2306,6 @@ pub(crate) fn apply_template_session_created( session: Option, agent: Option, model: Option, - template_name: String, error: Option, ) { if let Some(err) = error { @@ -2377,10 +2354,6 @@ pub(crate) fn apply_template_session_created( tracing::debug!(%session_id, ?error, "failed to queue session message load"); } } - app.messages_state.toasts.info(&format!( - "Session '{}' created from template", - template_name - )); } #[allow(dead_code)] @@ -2392,7 +2365,6 @@ pub(crate) async fn handle_create_from_template( ) { let project_dir = app.active_workspace_root().unwrap_or_default(); let project_id = app.active_project_key().unwrap_or_default(); - let template_name = template.name.clone(); let agent = template.agent.clone(); let model = template.model.clone(); let created = if let Some(core_client) = app.core_client.clone() { @@ -2450,11 +2422,6 @@ pub(crate) async fn handle_create_from_template( tracing::debug!(%session_id, ?error, "failed to queue session message load"); } } - - app.messages_state.toasts.info(&format!( - "Session '{}' created from template", - template_name - )); } Err(e) => { app.messages_state @@ -2583,7 +2550,7 @@ pub(crate) async fn handle_delete_session(app: &mut App, session_id: String) { } else { tracing::warn!("core client unavailable for delete session"); } - app.messages_state.toasts.info("Session deleted"); + reload_sessions(app).await; } @@ -2613,12 +2580,7 @@ pub(crate) async fn handle_archive_session(app: &mut App, session_id: String, un } else { tracing::warn!("core client unavailable for archive session"); } - let msg = if unarchive { - "Session unarchived" - } else { - "Session archived" - }; - app.messages_state.toasts.info(msg); + reload_sessions(app).await; } @@ -2647,14 +2609,13 @@ pub(crate) async fn handle_fork_session(app: &mut App, session_id: String) { } else { tracing::warn!("core client unavailable for fork session"); } - app.messages_state.toasts.info("Session forked"); + reload_sessions(app).await; } #[cfg(test)] #[allow(dead_code)] pub(crate) async fn handle_bulk_delete(app: &mut App, session_ids: Vec) { - let count = session_ids.len(); if let Some(core_client) = app.core_client.clone() { for id in &session_ids { let request = codegg::core::new_request( @@ -2693,16 +2654,13 @@ pub(crate) async fn handle_bulk_delete(app: &mut App, session_ids: Vec) } else { tracing::warn!("core client unavailable for bulk delete"); } - app.messages_state - .toasts - .info(&format!("{} sessions deleted", count)); + reload_sessions(app).await; } #[cfg(test)] #[allow(dead_code)] pub(crate) async fn handle_bulk_archive(app: &mut App, session_ids: Vec, unarchive: bool) { - let count = session_ids.len(); if let Some(core_client) = app.core_client.clone() { for id in &session_ids { let request = codegg::core::new_request( @@ -2737,12 +2695,7 @@ pub(crate) async fn handle_bulk_archive(app: &mut App, session_ids: Vec, } else { tracing::warn!("core client unavailable for bulk archive"); } - let msg = if unarchive { - format!("{} sessions unarchived", count) - } else { - format!("{} sessions archived", count) - }; - app.messages_state.toasts.info(&msg); + reload_sessions(app).await; } @@ -2779,9 +2732,10 @@ pub(crate) async fn handle_bulk_export(app: &mut App, session_ids: Vec) } else { tracing::warn!("core client unavailable for bulk export"); } - app.messages_state - .toasts - .info(&format!("{} sessions exported", count)); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec![format!("{} sessions exported", count)], + ); } #[cfg(test)] @@ -2837,10 +2791,7 @@ pub(crate) async fn handle_unshare_session(app: &mut App, session_id: String) { ); match core_client.request(request).await { Ok(CoreResponse::Session { session }) => { - if !assign_session_from_dto(app, session) { - return; - } - app.messages_state.toasts.info("Session unshared"); + assign_session_from_dto(app, session); } Ok(CoreResponse::Error { message, .. }) => { app.messages_state @@ -2878,14 +2829,10 @@ pub(crate) async fn handle_export_session(app: &mut App, session_id: String) { let json = serde_json::to_string_pretty(&export).unwrap_or_default(); match codegg::util::clipboard::copy_to_clipboard(&json) { Ok(_) => { - app.messages_state - .toasts - .info("Session exported to clipboard"); + // The live completion path owns this notice. } Err(e) => { - app.messages_state - .toasts - .error(&format!("Clipboard error: {}", e)); + tracing::warn!(error = %e, "clipboard error while exporting session"); } } } @@ -2925,10 +2872,9 @@ pub(crate) async fn handle_rename_session(app: &mut App, session_id: String, new ); match core_client.request(request).await { Ok(CoreResponse::Session { session }) => { - if !assign_session_from_dto(app, session) { - return; - } - app.messages_state.toasts.info("Session renamed"); + // The session list already shows the updated name, so the + // assignment is the whole outcome. + assign_session_from_dto(app, session); } Ok(CoreResponse::Error { message, .. }) => { app.messages_state @@ -2963,9 +2909,7 @@ pub(crate) async fn handle_undo_delete(app: &mut App, session_id: String) { ); match core_client.request(request).await { Ok(CoreResponse::Session { .. }) | Ok(CoreResponse::Ack) => { - app.messages_state - .toasts - .success("Session restored successfully"); + // Reloaded session list shows the restored session. reload_sessions(app).await; } Ok(CoreResponse::Error { message, .. }) => { @@ -3710,9 +3654,10 @@ pub(crate) fn dispatch_unshare(app: &mut App) { } pub(crate) fn dispatch_rename(app: &mut App) { - app.messages_state - .toasts - .info("Use /sessions to rename - select and press Enter"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Use /sessions to rename - select and press Enter".to_string()], + ); } pub(crate) fn dispatch_export(app: &mut App, argument: &str) { diff --git a/crates/codegg-tui/src/commands/shell.rs b/crates/codegg-tui/src/commands/shell.rs index 8e5276aed..948d31b76 100644 --- a/crates/codegg-tui/src/commands/shell.rs +++ b/crates/codegg-tui/src/commands/shell.rs @@ -1269,9 +1269,6 @@ pub(crate) fn handle_shell_kill(app: &mut app::App, id: u64) { .map(|e| e.started_at.elapsed().unwrap_or(std::time::Duration::ZERO)) .unwrap_or(std::time::Duration::ZERO); app.shell_store.mark_killed(cmd_id, elapsed); - app.messages_state - .toasts - .info(&format!("Killed shell command {}", id)); } else if let Some(binding) = binding.filter(|_| still_running) { let Some(client) = app.core_client.clone() else { app.messages_state @@ -1329,17 +1326,12 @@ pub(crate) fn handle_shell_list(app: &mut app::App) { .warning("The daemon's shell command list is unavailable"); return; }; - if lines.is_empty() { - app.messages_state - .toasts - .info("No shell commands in history"); - return; - } - if lines.len() > 5 { - app.open_info_dialog(crate::components::dialogs::info::InfoType::ShellShow, lines); + let lines = if lines.is_empty() { + vec!["No shell commands in history".to_string()] } else { - app.messages_state.toasts.info(&lines.join("\n")); - } + lines + }; + app.open_info_dialog(crate::components::dialogs::info::InfoType::ShellShow, lines); } /// The daemon's run ids this frontend promoted: its own annotation, @@ -1815,6 +1807,14 @@ mod shell_list_projection_tests { .join("\n") } + fn info_text(app: &App) -> String { + app.focus_manager + .with_component::(|dialog| { + dialog.content_lines().join("\n") + }) + .expect("the list is shown in an InfoDialog") + } + #[test] fn shell_list_renders_the_published_runs_in_the_daemons_order() { let mut app = app_with_published_runs(vec![ @@ -1824,7 +1824,7 @@ mod shell_list_projection_tests { handle_shell_list(&mut app); - let text = toast_text(&app); + let text = info_text(&app); let newer = text.find("echo newer").expect("the newer run is listed"); let older = text.find("echo older").expect("the older run is listed"); assert!(newer < older, "the daemon's order is kept: {text}"); @@ -1842,7 +1842,7 @@ mod shell_list_projection_tests { handle_shell_list(&mut app); - let text = toast_text(&app); + let text = info_text(&app); assert!( text.contains("No shell commands in history"), "an empty published list reads as empty: {text}" @@ -1902,7 +1902,7 @@ mod shell_list_projection_tests { handle_shell_list(&mut app); - let text = toast_text(&app); + let text = info_text(&app); let promoted = text .lines() .find(|line| line.contains("echo promoted")) @@ -1930,7 +1930,7 @@ mod shell_list_projection_tests { handle_shell_list(&mut app); - let text = toast_text(&app); + let text = info_text(&app); assert!( !text.contains("[promoted]"), "a run with no daemon binding is not claimed: {text}" @@ -1948,9 +1948,10 @@ pub(crate) fn dispatch_shell_rerun(app: &mut App, argument: &str) { } } None => { - app.messages_state - .toasts - .warning("Usage: /shell rerun "); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /shell rerun ".to_string()], + ); } } } @@ -1965,9 +1966,10 @@ pub(crate) fn dispatch_shell_kill(app: &mut App, argument: &str) { } } None => { - app.messages_state - .toasts - .warning("Usage: /shell kill "); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /shell kill ".to_string()], + ); } } } @@ -1978,12 +1980,10 @@ pub(crate) fn dispatch_shell_list(app: &mut App) { let _ = send_tui(tx, TuiCommand::ShellList); } else { let recent = app.shell_store.list_recent(10); - if recent.is_empty() { - app.messages_state - .toasts - .info("No shell commands in history"); + let lines = if recent.is_empty() { + vec!["No shell commands in history".to_string()] } else { - let lines: Vec = recent + recent .iter() .map(|e| { format!( @@ -1999,9 +1999,9 @@ pub(crate) fn dispatch_shell_list(app: &mut App) { } ) }) - .collect(); - app.messages_state.toasts.info(&lines.join("\n")); - } + .collect() + }; + app.open_info_dialog(crate::components::dialogs::info::InfoType::ShellShow, lines); } } @@ -2015,9 +2015,10 @@ pub(crate) fn dispatch_shell_show(app: &mut App, argument: &str) { } } None => { - app.messages_state - .toasts - .warning("Usage: /shell show "); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /shell show ".to_string()], + ); } } } @@ -2043,9 +2044,10 @@ pub(crate) fn dispatch_shell_expand(app: &mut App, argument: &str) { } } None => { - app.messages_state - .toasts - .warning("Usage: /shell expand stdout|stderr [start..end]"); + app.show_short_or_info( + crate::components::dialogs::info::InfoType::Usage, + vec!["Usage: /shell expand stdout|stderr [start..end]".to_string()], + ); } } } diff --git a/crates/codegg-tui/src/commands/skills.rs b/crates/codegg-tui/src/commands/skills.rs index 2eefd7f1f..092f04dee 100644 --- a/crates/codegg-tui/src/commands/skills.rs +++ b/crates/codegg-tui/src/commands/skills.rs @@ -61,7 +61,10 @@ pub(crate) fn dispatch_skills(app: &mut App, argument: &str) { }); if let Some(report) = report { let bounded: String = report.chars().take(2048).collect(); - app.messages_state.toasts.info(&bounded); + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Stats, + vec![bounded], + ); } else { app.messages_state .toasts diff --git a/crates/codegg-tui/src/commands/subagent_steer.rs b/crates/codegg-tui/src/commands/subagent_steer.rs index 66114a3d6..e2045325c 100644 --- a/crates/codegg-tui/src/commands/subagent_steer.rs +++ b/crates/codegg-tui/src/commands/subagent_steer.rs @@ -92,17 +92,13 @@ pub fn arm_addressee_from_focused_tab(app: &mut App) -> bool { true } -/// Arm the composer and say so. +/// Arm the composer for its next prompt. /// /// One place, because the sentence is the contract: it names the **parent** as /// the recipient, and a second copy would be a second thing to keep honest when /// ADR-0041's failure modes are exactly the ones this wording exists to avoid. fn adopt(app: &mut App, addressee: SubagentAddressee) { - let name = addressee.label().to_string(); app.prompt_state.subagent_addressee = Some(addressee); - app.messages_state.toasts.info(&format!( - "Your next prompt goes to the agent running this turn, addressed to {name}." - )); } /// `/subagent-send [off | ]`. @@ -187,11 +183,7 @@ fn find_row(app: &App, value: &str) -> AddresseeMatch { /// badge is visible, but "undo it" must not require knowing which chord clears /// it. pub fn disarm_addressee(app: &mut App) { - if app.prompt_state.subagent_addressee.take().is_some() { - app.messages_state - .toasts - .info("Subagent addressee cleared — your next prompt starts a normal turn."); - } + app.prompt_state.subagent_addressee = None; } /// Hand one addressed reply to the controlling parent turn. diff --git a/crates/codegg-tui/src/commands/tasks.rs b/crates/codegg-tui/src/commands/tasks.rs index d6a4b2e73..efffca32e 100644 --- a/crates/codegg-tui/src/commands/tasks.rs +++ b/crates/codegg-tui/src/commands/tasks.rs @@ -9,6 +9,13 @@ use crate::task_lifecycle::TuiTaskKind; use codegg::core::CoreClient; use codegg::protocol::core::{CoreRequest, CoreResponse}; +fn show_task_usage(app: &mut App, message: &str) { + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec![message.to_string()], + ); +} + pub(crate) const SCHEDULE_DISPLAY_ID_LEN: usize = 8; #[derive(Debug, Clone, PartialEq, Eq)] @@ -218,9 +225,6 @@ pub(crate) fn start_list_tasks(app: &mut App) { .as_ref() .and_then(|session| session.workspace_id.clone()) else { - app.messages_state - .toasts - .warning("Task schedules require an active workspace"); return; }; let request_id = app.dialog_state.task_list_request.begin(); @@ -295,16 +299,12 @@ pub(crate) fn apply_tasks_listed( if !app.dialog_state.task_list_request.finish(request_id) { return; } - if tasks.is_empty() { - app.messages_state.toasts.info("No background tasks"); + let lines = if tasks.is_empty() { + vec!["No background tasks".to_string()] } else { - let list: Vec = tasks.iter().map(durable_schedule_task_line).collect(); - if list.len() > 5 { - app.open_info_dialog(crate::components::dialogs::info::InfoType::TaskList, list); - } else { - app.messages_state.toasts.info(&list.join(" | ")); - } - } + tasks.iter().map(durable_schedule_task_line).collect() + }; + app.open_info_dialog(crate::components::dialogs::info::InfoType::TaskList, lines); } pub(crate) fn start_delete_task(app: &mut App, id: String) { @@ -315,9 +315,6 @@ pub(crate) fn start_delete_task(app: &mut App, id: String) { .and_then(|session| session.workspace_id.clone()) .is_none() { - app.messages_state - .toasts - .warning("Task schedules require an active workspace"); return; }; let request_id = app.dialog_state.task_delete_request.begin(); @@ -409,8 +406,8 @@ pub(crate) fn start_delete_task(app: &mut App, id: String) { pub(crate) fn apply_task_operation_finished( app: &mut App, request_id: u64, - op: String, - task_id: Option, + _op: String, + _task_id: Option, error: Option, ) { if let Some(err) = error { @@ -424,36 +421,16 @@ pub(crate) fn apply_task_operation_finished( app.messages_state.toasts.warning(&err); return; } - if !app.dialog_state.task_delete_request.finish(request_id) { - return; - } - match op.as_str() { - "delete" => { - app.messages_state.toasts.info("Task deleted"); - } - "schedule" => { - let display_id = schedule_display_id(task_id.as_deref().unwrap_or("")); - app.messages_state - .toasts - .info(&format!("Task {} scheduled", display_id)); - } - _ => { - app.messages_state.toasts.info(&format!("{} completed", op)); - } - } + // Nothing follows, so the completion is the whole tail: a request this + // frontend no longer owns is discarded by finish() returning false. + let _ = app.dialog_state.task_delete_request.finish(request_id); } pub(crate) fn start_task_schedule(app: &mut App, interval_secs: u64, message: String) { let Some(session) = app.session_state.session.as_ref() else { - app.messages_state - .toasts - .warning("Task schedules require an active session"); return; }; let Some(workspace_id) = session.workspace_id.clone() else { - app.messages_state - .toasts - .warning("Task schedules require an active workspace"); return; }; let request_id = app.dialog_state.task_delete_request.begin(); @@ -580,31 +557,19 @@ pub(crate) fn handle_spawn_subagent(app: &mut App, agent_name: String, prompt: S use crate::task_lifecycle::TuiTaskKind; if prompt.trim().is_empty() { - app.messages_state - .toasts - .error("Subagent prompt cannot be empty"); return; } let Some(core_client) = app.core_client.clone() else { - app.messages_state - .toasts - .error("Core client unavailable; subagents require the daemon scheduler"); return; }; let Some(session) = app.session_state.session.clone() else { - app.messages_state - .toasts - .error("No active session for subagent"); return; }; let context = match app.project_execution_context() { Ok(context) => context, - Err(error) => { - app.messages_state.toasts.error(&error); - return; - } + Err(_) => return, }; let session_id = context .session_id @@ -735,19 +700,14 @@ pub(crate) fn handle_spawn_subagent(app: &mut App, agent_name: String, prompt: S pub(crate) fn apply_subagent_spawn_finished( app: &mut App, - agent_name: String, - task_id: u64, + _agent_name: String, + _task_id: u64, _prompt: String, error: Option, ) { if let Some(err) = error { app.messages_state.toasts.error(&err); - return; } - app.messages_state.toasts.info(&format!( - "Spawned subagent '{}' with task #{}", - agent_name, task_id - )); } pub(crate) fn handle_file_diff_stats_ready( @@ -794,9 +754,10 @@ pub(crate) fn dispatch_loop(app: &mut App, argument: &str) { // spelling was already removed by the extraction point. let parts: Vec<&str> = argument.splitn(2, ' ').collect(); if parts.len() < 2 { - app.messages_state - .toasts - .warning("Usage: /loop \"\" (e.g. /loop 5m \"check status\")"); + show_task_usage( + app, + "Usage: /loop \"\" (e.g. /loop 5m \"check status\")", + ); } else if let Some(duration) = codegg::background_task_migration::parse_duration(parts[0]) { let message = parts[1].trim_matches('"').to_string(); if let Some(ref tx) = app.tui_cmd_tx { @@ -807,36 +768,27 @@ pub(crate) fn dispatch_loop(app: &mut App, argument: &str) { message, }, ); - } else { - app.messages_state - .toasts - .error("Command channel unavailable"); } } else { - app.messages_state - .toasts - .warning("Invalid interval. Examples: 30s, 5m, 1h, 1d"); + show_task_usage(app, "Invalid interval. Examples: 30s, 5m, 1h, 1d"); } } pub(crate) fn dispatch_schedules(app: &mut App) { if let Some(ref tx) = app.tui_cmd_tx { let _ = send_tui(tx, TuiCommand::ListTasks); - } else { - app.messages_state.toasts.info("No background tasks"); } } pub(crate) fn dispatch_task_del(app: &mut App, argument: &str) { let id = argument; if id.is_empty() { - app.messages_state.toasts.warning( + show_task_usage( + app, "Usage: /task-del (use the ID shown by /tasks; full schedule IDs also work)", ); } else if let Some(ref tx) = app.tui_cmd_tx { let _ = send_tui(tx, TuiCommand::DeleteTask { id: id.to_string() }); - } else { - app.messages_state.toasts.warning("Scheduler not available"); } } diff --git a/crates/codegg-tui/src/commands/team.rs b/crates/codegg-tui/src/commands/team.rs index f1e0c092c..83aacfd22 100644 --- a/crates/codegg-tui/src/commands/team.rs +++ b/crates/codegg-tui/src/commands/team.rs @@ -27,6 +27,33 @@ use codegg::protocol::core::{ TeamMembershipDto, TeamPrincipalDto, TeamTokenDto, }; +fn show_team_usage(app: &mut App, message: &str) { + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec![message.to_string()], + ); +} + +/// Parse a membership revision, or say why it could not be parsed. +/// +/// The revision is the membership's optimistic-concurrency token, so a +/// non-numeric one is an input error rather than a request the daemon can +/// refuse. It used to be swallowed by an empty `Err` arm: `/team role a b c` +/// did nothing whatsoever, which reads as success. The usage dialog is the +/// surface for it — the same one every neighbouring validation arm uses. +fn parse_revision(app: &mut App, text: &str, usage: &str) -> Option { + match text.parse::() { + Ok(revision) => Some(revision), + Err(_) => { + app.open_info_dialog( + crate::components::dialogs::info::InfoType::Usage, + vec![format!("{usage} - the revision must be a number")], + ); + None + } + } +} + fn unauthorized_of(code: &str) -> bool { // Single-project denials use the privacy-safe not-found shape; // LocalOwner-only denials carry the typed scope denial. Both render @@ -45,9 +72,6 @@ fn epoch_of(app: &App) -> u64 { /// after `/team` (possibly empty for the bare administration view). pub(crate) fn dispatch_team_command(app: &mut App, args: &str) { let Some(project_id) = app.active_project_id().map(str::to_string) else { - app.messages_state - .toasts - .info("No active project — open a project tab first"); return; }; let mut tokens = args.split_whitespace(); @@ -60,7 +84,8 @@ pub(crate) fn dispatch_team_command(app: &mut App, args: &str) { let principal = tokens.next().unwrap_or("").to_string(); let role = tokens.next().unwrap_or("").to_string(); if principal.is_empty() || role.is_empty() { - app.messages_state.toasts.warning( + show_team_usage( + app, "Usage: /team add ", ); return; @@ -72,89 +97,92 @@ pub(crate) fn dispatch_team_command(app: &mut App, args: &str) { let role = tokens.next().unwrap_or("").to_string(); let revision = tokens.next().unwrap_or(""); if principal.is_empty() || role.is_empty() || revision.is_empty() { - app.messages_state.toasts.warning( + show_team_usage( + app, "Usage: /team role (see /team for revisions)", ); return; } - match revision.parse::() { - Ok(revision) => { - start_membership_update(app, project_id, principal, Some(role), None, revision); - } - Err(_) => { - app.messages_state - .toasts - .warning("Revision must be a non-negative integer"); - } - } + let Some(revision) = parse_revision( + app, + revision, + "Usage: /team role (see /team for revisions)", + ) else { + return; + }; + start_membership_update(app, project_id, principal, Some(role), None, revision); } "suspend" => { let principal = tokens.next().unwrap_or("").to_string(); let revision = tokens.next().unwrap_or(""); if principal.is_empty() || revision.is_empty() { - app.messages_state.toasts.warning( + show_team_usage( + app, "Usage: /team suspend (see /team for revisions)", ); return; } - match revision.parse::() { - Ok(revision) => start_membership_update( - app, - project_id, - principal, - None, - Some("suspended".to_string()), - revision, - ), - Err(_) => { - app.messages_state - .toasts - .warning("Revision must be a non-negative integer"); - } - } + let Some(revision) = parse_revision( + app, + revision, + "Usage: /team suspend (see /team for revisions)", + ) else { + return; + }; + start_membership_update( + app, + project_id, + principal, + None, + Some("suspended".to_string()), + revision, + ); } "reactivate" => { let principal = tokens.next().unwrap_or("").to_string(); let revision = tokens.next().unwrap_or(""); if principal.is_empty() || revision.is_empty() { - app.messages_state.toasts.warning( + show_team_usage( + app, "Usage: /team reactivate (see /team for revisions)", ); return; } - match revision.parse::() { - Ok(revision) => start_membership_update( - app, - project_id, - principal, - None, - Some("active".to_string()), - revision, - ), - Err(_) => { - app.messages_state - .toasts - .warning("Revision must be a non-negative integer"); - } - } + let Some(revision) = parse_revision( + app, + revision, + "Usage: /team reactivate (see /team for revisions)", + ) else { + return; + }; + start_membership_update( + app, + project_id, + principal, + None, + Some("active".to_string()), + revision, + ); } "revoke" => { let principal = tokens.next().unwrap_or("").to_string(); let revision = tokens.next().unwrap_or(""); if principal.is_empty() || revision.is_empty() { - app.messages_state.toasts.warning( + show_team_usage( + app, "Usage: /team revoke (see /team for revisions; revocation is monotonic)", ); return; } - match revision.parse::() { - Ok(revision) => start_membership_revoke(app, project_id, principal, revision), - Err(_) => { - app.messages_state - .toasts - .warning("Revision must be a non-negative integer"); - } - } + let Some(revision) = parse_revision( + app, + revision, + "Usage: /team revoke (see /team for revisions; \ + revocation is monotonic)", + ) else { + return; + }; + start_membership_revoke(app, project_id, principal, revision); } "principals" => { start_principals_list(app); @@ -162,7 +190,8 @@ pub(crate) fn dispatch_team_command(app: &mut App, args: &str) { "principal-create" => { let rest: Vec<&str> = tokens.collect(); if rest.is_empty() { - app.messages_state.toasts.warning( + show_team_usage( + app, "Usage: /team principal-create [--service] (LocalOwner only)", ); return; @@ -175,7 +204,8 @@ pub(crate) fn dispatch_team_command(app: &mut App, args: &str) { .collect::>() .join(" "); if name.trim().is_empty() { - app.messages_state.toasts.warning( + show_team_usage( + app, "Usage: /team principal-create [--service] (LocalOwner only)", ); return; @@ -186,31 +216,32 @@ pub(crate) fn dispatch_team_command(app: &mut App, args: &str) { let principal = tokens.next().unwrap_or("").to_string(); let revision = tokens.next().unwrap_or(""); if principal.is_empty() || revision.is_empty() { - app.messages_state.toasts.warning( + show_team_usage( + app, "Usage: /team principal-disable|principal-enable (LocalOwner only)", ); return; } - match revision.parse::() { - Ok(revision) => { - let status = if sub == "principal-disable" { - "disabled" - } else { - "active" - }; - start_principal_status(app, principal, status.to_string(), revision); - } - Err(_) => { - app.messages_state - .toasts - .warning("Revision must be a non-negative integer"); - } - } + let Some(revision) = parse_revision( + app, + revision, + "Usage: /team principal-disable|principal-enable \ + (LocalOwner only)", + ) else { + return; + }; + let status = if sub == "principal-disable" { + "disabled" + } else { + "active" + }; + start_principal_status(app, principal, status.to_string(), revision); } "tokens" => { let principal = tokens.next().unwrap_or("").to_string(); if principal.is_empty() { - app.messages_state.toasts.warning( + show_team_usage( + app, "Usage: /team tokens (LocalOwner only; metadata only, never secrets)", ); return; @@ -221,7 +252,8 @@ pub(crate) fn dispatch_team_command(app: &mut App, args: &str) { let principal = tokens.next().unwrap_or("").to_string(); let label = tokens.next().unwrap_or("").to_string(); if principal.is_empty() || label.is_empty() { - app.messages_state.toasts.warning( + show_team_usage( + app, "Usage: /team token-create