diff --git a/.github/workflows/macos_app.yml b/.github/workflows/macos_app.yml index 4f8495ab..3d5d3d27 100644 --- a/.github/workflows/macos_app.yml +++ b/.github/workflows/macos_app.yml @@ -58,6 +58,7 @@ jobs: run: >- python -m unittest tests.setup.test__macos_builder + tests.setup.test__macos_version tests.setup.test__macos_launcher_lock tests.setup.test__macos_launcher_update tests.setup.test__macos_backend_repair -v @@ -68,7 +69,7 @@ jobs: - name: Build ad-hoc signed application with bundled wheel run: bash setup/macos/build_app.sh --wheel - name: Inspect actual application, signing and disk image - run: bash tests/setup/check_macos_app.sh + run: bash tests/setup/check_macos_app.sh --wheel - name: Upload validated ad-hoc signed disk image if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v') }} uses: actions/upload-artifact@v4 diff --git a/.github/workflows/native_release.yml b/.github/workflows/native_release.yml index 5ada1323..59f44bdb 100644 --- a/.github/workflows/native_release.yml +++ b/.github/workflows/native_release.yml @@ -21,6 +21,7 @@ jobs: outputs: version: ${{ steps.version.outputs.version }} prerelease: ${{ steps.version.outputs.prerelease }} + commit: ${{ steps.commit.outputs.sha }} steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 @@ -41,7 +42,8 @@ jobs: with Path("pyproject.toml").open("rb") as stream: version = tomllib.load(stream)["project"]["version"] if not isinstance(version, str) or not re.fullmatch( - r"[0-9]+\.[0-9]+\.[0-9]+(?:b[0-9]+|rc[0-9]+)?", + r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)" + r"(?:(?:b|rc)[1-9][0-9]{0,2})?", version, ): raise SystemExit(f"Unsupported release version: {version!r}") @@ -55,6 +57,13 @@ jobs: file=output, ) PYTHON + - name: Record validated source commit + id: commit + shell: bash + run: | + set -euo pipefail + commit=$(git rev-parse --verify HEAD^{commit}) + echo "sha=$commit" >> "$GITHUB_OUTPUT" - name: Verify tag-pinned PyPI description run: python -m setup.generate_pypi_readme --check @@ -113,6 +122,7 @@ jobs: RELEASE_TAG: ${{ github.ref_name }} RELEASE_VERSION: ${{ needs.validate.outputs.version }} IS_PRERELEASE: ${{ needs.validate.outputs.prerelease }} + RELEASE_COMMIT: ${{ needs.validate.outputs.commit }} run: | set -euo pipefail assets=( @@ -120,7 +130,87 @@ jobs: "release-assets/KiLin-Setup-${RELEASE_VERSION}.exe" "release-assets/SHA256SUMS.txt" ) - if gh release view "$RELEASE_TAG" >/dev/null 2>&1; then + # A failed API request is not evidence that a release is absent. + # Include draft releases and all pages of assets in the preflight. + existing=$(python3 - "${assets[@]}" <<'PYTHON' + import json + import os + from pathlib import Path + import re + import subprocess + import sys + + repo = f"repos/{os.environ['GH_REPO']}" + tag = os.environ["RELEASE_TAG"] + commit = os.environ["RELEASE_COMMIT"] + stage = os.environ["IS_PRERELEASE"] + if stage not in {"true", "false"}: + raise SystemExit("Invalid release classification") + prerelease = stage == "true" + + def api(*args): + return json.loads(subprocess.check_output( + ["gh", "api", *args], encoding="utf-8", + )) + + def items(path): + pages = api("--paginate", "--slurp", path) + if not isinstance(pages, list) or not all( + isinstance(page, list) for page in pages + ): + raise SystemExit("Invalid paginated GitHub response") + return [item for page in pages for item in page] + + releases = [ + release for release in items(f"{repo}/releases?per_page=100") + if release["tag_name"] == tag + ] + if len(releases) > 1: + raise SystemExit("Multiple releases match the version tag") + if releases: + release = releases[0] + if release["prerelease"] is not prerelease: + raise SystemExit("Existing release classification differs") + if release.get("immutable") is True: + raise SystemExit("Existing release is immutable") + release_id = release["id"] + if type(release_id) is not int or release_id <= 0: + raise SystemExit("Invalid existing release identity") + names = { + asset["name"] for asset in items( + f"{repo}/releases/{release_id}/assets?per_page=100" + ) + } + conflicts = names.intersection(Path(p).name for p in sys.argv[1:]) + if conflicts: + raise SystemExit( + "Release assets already exist: " + + ", ".join(sorted(conflicts)) + ) + + # Peel annotated tags to the commit actually used by the builds. + # Resolve the explicit tag ref rather than an ambiguous branch name. + if not re.fullmatch(r"[0-9a-f]{40}", commit): + raise SystemExit("Invalid validated source commit") + target = api(f"{repo}/git/ref/tags/{tag}")["object"] + seen = set() + while True: + sha = target["sha"] + if not re.fullmatch(r"[0-9a-f]{40}", sha) or sha in seen: + raise SystemExit("Invalid release tag target") + if target["type"] == "commit": + break + if target["type"] != "tag": + raise SystemExit("Release tag does not identify a commit") + seen.add(sha) + target = api(f"{repo}/git/tags/{sha}")["object"] + if sha != commit: + raise SystemExit("Release tag no longer identifies built commit") + + print("true" if releases else "false") + PYTHON + ) + if [[ "$existing" == "true" ]]; then # Do not overwrite published assets: a rerun must be reviewed. gh release upload "$RELEASE_TAG" "${assets[@]}" else diff --git a/.github/workflows/windows_app.yml b/.github/workflows/windows_app.yml index 954c605b..9722d92f 100644 --- a/.github/workflows/windows_app.yml +++ b/.github/workflows/windows_app.yml @@ -75,8 +75,9 @@ jobs: $version = (Select-String pyproject.toml -Pattern '^version = "(.*)"$').Matches[0].Groups[1].Value $runtime = Join-Path $env:LOCALAPPDATA "kilin\runtime\$version" if (-not (Test-Path "$runtime\Scripts\kilin-gui.exe")) { throw "kilin-gui.exe is missing." } - & "$runtime\Scripts\python.exe" -c "import kilin, PySide6, torch, transformers; print(torch.__version__)" - if ($LASTEXITCODE -ne 0) { throw "The installed runtime cannot import KiLin." } + & "$runtime\Scripts\python.exe" -I "$env:GITHUB_WORKSPACE\tests\setup\check_windows_runtime.py" ` + "$runtime" "$env:GITHUB_WORKSPACE\pyproject.toml" + if ($LASTEXITCODE -ne 0) { throw "Installed runtime verification failed." } & "$runtime\Scripts\python.exe" -I "$env:GITHUB_WORKSPACE\examples\plugins\check_examples.py" if ($LASTEXITCODE -ne 0) { throw "Installed plugin lifecycle failed." } $shortcut = Join-Path ([Environment]::GetFolderPath("Programs")) "KíLín.lnk" @@ -85,6 +86,67 @@ jobs: $spec = [Environment]::GetEnvironmentVariable("KILIN_APP_SPEC", "User") if (-not (Test-Path -LiteralPath $uv)) { throw "KILIN_APP_UV does not name uv.exe." } if (-not $spec.EndsWith("[app]")) { throw "KILIN_APP_SPEC is $spec." } + - name: Verify failed same-version reinstall restores the runtime + env: + # Force package resolution to fail without a network outage or a + # test-only switch in the production installer. The wheel alone + # cannot supply its dependencies, and uv may not use its cache. + UV_OFFLINE: "1" + UV_NO_CACHE: "1" + UV_NO_CONFIG: "1" + run: | + $version = (Select-String pyproject.toml -Pattern '^version = "(.*)"$').Matches[0].Groups[1].Value + $runtime = Join-Path $env:LOCALAPPDATA "kilin\runtime\$version" + $backup = "$runtime.rollback" + $probe = Join-Path $runtime "reinstall-probe.txt" + $shortcut = Join-Path ([Environment]::GetFolderPath("Programs")) "KíLín.lnk" + $shortcutHash = (Get-FileHash -LiteralPath $shortcut).Hash + $uv = [Environment]::GetEnvironmentVariable("KILIN_APP_UV", "User") + $spec = [Environment]::GetEnvironmentVariable("KILIN_APP_SPEC", "User") + if ((Test-Path -LiteralPath $probe) -or (Test-Path -LiteralPath $backup)) { + throw "Reinstall probe or rollback directory already exists." + } + Set-Content -LiteralPath $probe -Value "Original installed runtime" + $probeHash = (Get-FileHash -LiteralPath $probe).Hash + $setup = Get-ChildItem dist -Filter "KiLin-Setup-*.exe" | Select-Object -First 1 + try { + foreach ($scenario in @("failed", "interrupted")) { + if ($scenario -eq "interrupted") { + # Simulate termination after the backup rename and + # creation of a partial replacement at the final path. + Move-Item -LiteralPath $runtime -Destination $backup + New-Item -ItemType Directory -Path $runtime | Out-Null + Set-Content -LiteralPath (Join-Path $runtime "partial.txt") -Value "Incomplete runtime" + } + $log = "$scenario-reinstall.log" + $process = Start-Process -FilePath $setup.FullName -Wait -PassThru ` + -ArgumentList "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART", "/LOG=$log" + Get-Content -LiteralPath $log -Tail 40 + if ($process.ExitCode -eq 0) { throw "Offline reinstall unexpectedly succeeded." } + $details = Get-Content -LiteralPath $log -Raw + if (-not $details.Contains("Preserved previous runtime at") -or + -not $details.Contains("Restored previous runtime at")) { + throw "Setup did not exercise runtime rollback ($scenario)." + } + if (Test-Path -LiteralPath $backup) { throw "Rollback did not restore the backup." } + if (Test-Path -LiteralPath (Join-Path $runtime "partial.txt")) { + throw "Partial replacement survived rollback." + } + if ((Get-FileHash -LiteralPath $probe).Hash -ne $probeHash) { + throw "Failed reinstall changed the original runtime." + } + if ((Get-FileHash -LiteralPath $shortcut).Hash -ne $shortcutHash -or + [Environment]::GetEnvironmentVariable("KILIN_APP_UV", "User") -ne $uv -or + [Environment]::GetEnvironmentVariable("KILIN_APP_SPEC", "User") -ne $spec) { + throw "Failed reinstall changed the shortcut or repair variables." + } + & "$runtime\Scripts\python.exe" -I "$env:GITHUB_WORKSPACE\tests\setup\check_windows_runtime.py" ` + "$runtime" "$env:GITHUB_WORKSPACE\pyproject.toml" + if ($LASTEXITCODE -ne 0) { throw "Restored runtime verification failed ($scenario)." } + } + } finally { + if (Test-Path -LiteralPath $probe) { Remove-Item -LiteralPath $probe } + } - name: Verify user plugin files survive reinstall run: | # Hosted runner only: seed a reviewed example in the default user store. @@ -102,6 +164,12 @@ jobs: $process = Start-Process -FilePath $setup.FullName -Wait -PassThru ` -ArgumentList "/VERYSILENT", "/SUPPRESSMSGBOXES", "/LOG=reinstall.log" if ($process.ExitCode -ne 0) { throw "Reinstall failed with $($process.ExitCode)." } + $version = (Select-String pyproject.toml -Pattern '^version = "(.*)"$').Matches[0].Groups[1].Value + $runtime = Join-Path $env:LOCALAPPDATA "kilin\runtime\$version" + if (Test-Path -LiteralPath "$runtime.rollback") { throw "Reinstall left a rollback directory." } + & "$runtime\Scripts\python.exe" -I "$env:GITHUB_WORKSPACE\tests\setup\check_windows_runtime.py" ` + "$runtime" "$env:GITHUB_WORKSPACE\pyproject.toml" + if ($LASTEXITCODE -ne 0) { throw "Reinstalled runtime verification failed." } if ((Get-FileHash $toolFile).Hash -ne $toolHash -or (Get-FileHash $type).Hash -ne $typeHash) { throw "Reinstall changed user plugins." } diff --git a/MANIFEST.in b/MANIFEST.in index d917a8b1..f8dada7f 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -10,3 +10,6 @@ include docs/PLUGIN_API.md include docs/PROJECT_TYPE_SCHEMA.md include docs/PLUGIN_AUTHORING.md recursive-include examples/plugins *.py *.json *.md + +# Development tests require the complete repository checkout. +prune tests diff --git a/README.md b/README.md index 0cb53666..108eda0d 100644 --- a/README.md +++ b/README.md @@ -49,44 +49,50 @@ formats is not guaranteed before the stable release. ## Installation -**KíLín `0.1.0b2` requires Python 3.12.** Supported platforms are -Apple Silicon macOS and Linux; Windows support is experimental. Language -model inference runs locally. Package and model downloads require network -access unless previously cached. +**KíLín `0.1.0b2` requires Python 3.12.** The supported setup targets are +native Apple Silicon macOS and Linux (x86-64 or ARM64). Windows x64 support +is experimental; Intel macOS and Rosetta are not supported by the current +setup. Language model inference runs locally. Package and model downloads +require network access unless previously cached. ### Python package -In a Python 3.12 environment, install the GUI and its model backend: +Once this version is available on PyPI, install the GUI and its model +backend in a Python 3.12 environment: ```sh python -m pip install "kilin[app]==0.1.0b2" kilin-gui ``` -The `app` extra installs the graphical interface and the computation backend -appropriate to the platform (MLX on supported Apple Silicon Macs, PyTorch -elsewhere). For the core without the GUI, use `kilin==0.1.0b2`; to select a -backend explicitly, see the -[model-management guide](docs/model_management.md). +The `app` extra installs the graphical interface and the platform-default +computation backend (MLX on supported Apple Silicon Macs, PyTorch elsewhere). +The core package (`kilin==0.1.0b2`) installs neither a model backend nor the +GUI. The `mlx` and `torch` extras select a backend explicitly, and the `gui` +extra adds the graphical interface without either backend. See the +[model-management guide](docs/model_management.md) for backend selection. ### Experimental desktop installers -The [v0.1.0b2 GitHub release](https://github.com/DeepTrackAI/KiLin/releases/tag/v0.1.0b2) -includes two experimental desktop installers built from that version's -source: `KiLin-0.1.0b2-macos-arm64.dmg` for Apple Silicon Macs (macOS 14+) -and `KiLin-Setup-0.1.0b2.exe` for 64-bit Windows 10 or 11. - -The macOS launcher downloads Python 3.12 and dependencies on first launch; -the Windows installer downloads them during setup. Model weights are -obtained separately when requested. **Neither installer is a signed, -notarized production distribution:** the macOS app is ad-hoc signed and -not notarized, while the Windows EXE is unsigned. Gatekeeper or Windows -SmartScreen may display security warnings or block installation. Verify -the downloaded files against the release checksums and read the +Obtain the experimental desktop installers from the +[v0.1.0b2 GitHub release](https://github.com/DeepTrackAI/KiLin/releases/tag/v0.1.0b2) +when its assets are available. Choose `KiLin-0.1.0b2-macos-arm64.dmg` for +Apple Silicon Macs (macOS 14+) or `KiLin-Setup-0.1.0b2.exe` for 64-bit +Windows 10 or 11. Both installers are built from the tagged source. + +The macOS launcher installs Python 3.12 and dependencies on first launch; +the Windows installer installs them during setup. The Windows installer +uses uv's automatic PyTorch backend selection for CUDA or CPU. The pip +command above does not perform this automatic selection. Model weights +are obtained separately when requested. **Neither installer is a +production-signed build:** the macOS app is ad-hoc signed and not +notarized, while the Windows EXE is unsigned. Gatekeeper or Windows SmartScreen may display +security warnings or block installation. Verify the downloaded files +against the release checksums and read the [native installer guidance](docs/release.md) before using them. -Because these installers are not signed, macOS and Windows show a -security warning the first time you open KíLín. To open it anyway: +If the operating system displays a security warning for a verified, +trusted installer: - **macOS:** open KíLín once and close the warning. Then open **System Settings → Privacy & Security**, scroll to **Security**, click **Open @@ -100,19 +106,27 @@ GitHub or from the KíLín team. ## Getting started -After installation, open `kilin-gui`, select models and a project workspace, -create a project of the appropriate type, and add source files. Ask a -question, inspect the retrieved evidence, and save useful conversations. +Launch the installed desktop app, or run `kilin-gui` from the installed +Python environment. The GUI requires a **beta invitation passkey** on +first launch for each user account. Contact the project maintainers to +obtain one. This is a local client-side check, not a security boundary; +the open-source Python API does not require a passkey. + +1. Review and accept the terms of use. +2. Confirm the folder where KíLín will store managed projects. +3. In Settings, select the backend and models for new projects and use + the Download buttons for missing models. GUI project preparation does + not automatically download model weights. +4. Create a project of the appropriate type, with or without sources, or + resume a saved project using its own saved backend and model settings. +5. Ask a question, inspect the retrieved evidence, and save useful + conversations. + Use **Organize sources** in Workspace to assign roles and relate supporting files to their parent documents. Review the proposed changes before applying them. For existing workspaces with missing semantic metadata, initialize it explicitly through the editor; see [Accepted source organization](docs/source_manifest.md). - -The GUI requires a **beta invitation passkey** on first launch for each -user account. Contact the project maintainers to obtain one. This is a -local client-side check, not a security boundary; the open-source -Python API does not require a passkey. See the -[GUI guide](kilin/gui/README.md) for details. +See the [GUI guide](kilin/gui/README.md) for details. Check the application version with `kilin --version` or inspect the full component inventory with `kilin --versions` (`--versions --json` for @@ -133,7 +147,10 @@ On Windows, perform development setup with PowerShell: powershell -NoProfile -ExecutionPolicy Bypass -File setup/setup.ps1 ``` -Then run `uv run kilin --gui`. Select the checkout's `.venv` Python +Then run `uv run kilin --gui`. If setup has installed uv and the current +terminal cannot find it, open a new terminal or use the full-path launch +command printed by the setup script. Run the launch command from the +checkout root. Select the checkout's `.venv` Python kernel when following the tutorials. The [development guide](docs/development.md) covers setup, dependency and test requirements. @@ -165,11 +182,17 @@ and [extension interfaces](docs/extension_interfaces.md). ## Privacy and limitations KíLín is designed for local control, but local model execution does not -make installation and all optional actions offline. Conversations, source -snapshots, and diagnostic traces may contain sensitive material. KíLín -does not provide encrypted workspaces, an execution sandbox, or guaranteed -scientific correctness. Never share a workspace or trace archive assuming -it has been anonymized. +make installation and all optional actions offline. The optional +[reference lookup](kilin/tools/reference_check/README.md) sends selected +bibliographic information to Crossref or OpenAlex only after explicit user +authorization. Choose a projects folder that is not cloud-synchronized when +working with sensitive data; KíLín does not control synchronization by +services such as iCloud or OneDrive. + +Conversations, source snapshots, and diagnostic traces may contain sensitive +material. KíLín does not provide encrypted workspaces, an execution +sandbox, or guaranteed scientific correctness. Never share a workspace or +trace archive assuming it has been anonymized. Read the [security notes](docs/security.md) diff --git a/README.pypi.md b/README.pypi.md index dd2f05f1..dd5b05de 100644 --- a/README.pypi.md +++ b/README.pypi.md @@ -51,44 +51,50 @@ formats is not guaranteed before the stable release. ## Installation -**KíLín `0.1.0b2` requires Python 3.12.** Supported platforms are -Apple Silicon macOS and Linux; Windows support is experimental. Language -model inference runs locally. Package and model downloads require network -access unless previously cached. +**KíLín `0.1.0b2` requires Python 3.12.** The supported setup targets are +native Apple Silicon macOS and Linux (x86-64 or ARM64). Windows x64 support +is experimental; Intel macOS and Rosetta are not supported by the current +setup. Language model inference runs locally. Package and model downloads +require network access unless previously cached. ### Python package -In a Python 3.12 environment, install the GUI and its model backend: +Once this version is available on PyPI, install the GUI and its model +backend in a Python 3.12 environment: ```sh python -m pip install "kilin[app]==0.1.0b2" kilin-gui ``` -The `app` extra installs the graphical interface and the computation backend -appropriate to the platform (MLX on supported Apple Silicon Macs, PyTorch -elsewhere). For the core without the GUI, use `kilin==0.1.0b2`; to select a -backend explicitly, see the -[model-management guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/model_management.md). +The `app` extra installs the graphical interface and the platform-default +computation backend (MLX on supported Apple Silicon Macs, PyTorch elsewhere). +The core package (`kilin==0.1.0b2`) installs neither a model backend nor the +GUI. The `mlx` and `torch` extras select a backend explicitly, and the `gui` +extra adds the graphical interface without either backend. See the +[model-management guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/model_management.md) for backend selection. ### Experimental desktop installers -The [v0.1.0b2 GitHub release](https://github.com/DeepTrackAI/KiLin/releases/tag/v0.1.0b2) -includes two experimental desktop installers built from that version's -source: `KiLin-0.1.0b2-macos-arm64.dmg` for Apple Silicon Macs (macOS 14+) -and `KiLin-Setup-0.1.0b2.exe` for 64-bit Windows 10 or 11. - -The macOS launcher downloads Python 3.12 and dependencies on first launch; -the Windows installer downloads them during setup. Model weights are -obtained separately when requested. **Neither installer is a signed, -notarized production distribution:** the macOS app is ad-hoc signed and -not notarized, while the Windows EXE is unsigned. Gatekeeper or Windows -SmartScreen may display security warnings or block installation. Verify -the downloaded files against the release checksums and read the +Obtain the experimental desktop installers from the +[v0.1.0b2 GitHub release](https://github.com/DeepTrackAI/KiLin/releases/tag/v0.1.0b2) +when its assets are available. Choose `KiLin-0.1.0b2-macos-arm64.dmg` for +Apple Silicon Macs (macOS 14+) or `KiLin-Setup-0.1.0b2.exe` for 64-bit +Windows 10 or 11. Both installers are built from the tagged source. + +The macOS launcher installs Python 3.12 and dependencies on first launch; +the Windows installer installs them during setup. The Windows installer +uses uv's automatic PyTorch backend selection for CUDA or CPU. The pip +command above does not perform this automatic selection. Model weights +are obtained separately when requested. **Neither installer is a +production-signed build:** the macOS app is ad-hoc signed and not +notarized, while the Windows EXE is unsigned. Gatekeeper or Windows SmartScreen may display +security warnings or block installation. Verify the downloaded files +against the release checksums and read the [native installer guidance](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/release.md) before using them. -Because these installers are not signed, macOS and Windows show a -security warning the first time you open KíLín. To open it anyway: +If the operating system displays a security warning for a verified, +trusted installer: - **macOS:** open KíLín once and close the warning. Then open **System Settings → Privacy & Security**, scroll to **Security**, click **Open @@ -102,19 +108,27 @@ GitHub or from the KíLín team. ## Getting started -After installation, open `kilin-gui`, select models and a project workspace, -create a project of the appropriate type, and add source files. Ask a -question, inspect the retrieved evidence, and save useful conversations. +Launch the installed desktop app, or run `kilin-gui` from the installed +Python environment. The GUI requires a **beta invitation passkey** on +first launch for each user account. Contact the project maintainers to +obtain one. This is a local client-side check, not a security boundary; +the open-source Python API does not require a passkey. + +1. Review and accept the terms of use. +2. Confirm the folder where KíLín will store managed projects. +3. In Settings, select the backend and models for new projects and use + the Download buttons for missing models. GUI project preparation does + not automatically download model weights. +4. Create a project of the appropriate type, with or without sources, or + resume a saved project using its own saved backend and model settings. +5. Ask a question, inspect the retrieved evidence, and save useful + conversations. + Use **Organize sources** in Workspace to assign roles and relate supporting files to their parent documents. Review the proposed changes before applying them. For existing workspaces with missing semantic metadata, initialize it explicitly through the editor; see [Accepted source organization](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/source_manifest.md). - -The GUI requires a **beta invitation passkey** on first launch for each -user account. Contact the project maintainers to obtain one. This is a -local client-side check, not a security boundary; the open-source -Python API does not require a passkey. See the -[GUI guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/kilin/gui/README.md) for details. +See the [GUI guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/kilin/gui/README.md) for details. Check the application version with `kilin --version` or inspect the full component inventory with `kilin --versions` (`--versions --json` for @@ -135,7 +149,10 @@ On Windows, perform development setup with PowerShell: powershell -NoProfile -ExecutionPolicy Bypass -File setup/setup.ps1 ``` -Then run `uv run kilin --gui`. Select the checkout's `.venv` Python +Then run `uv run kilin --gui`. If setup has installed uv and the current +terminal cannot find it, open a new terminal or use the full-path launch +command printed by the setup script. Run the launch command from the +checkout root. Select the checkout's `.venv` Python kernel when following the tutorials. The [development guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/development.md) covers setup, dependency and test requirements. @@ -167,11 +184,17 @@ and [extension interfaces](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/do ## Privacy and limitations KíLín is designed for local control, but local model execution does not -make installation and all optional actions offline. Conversations, source -snapshots, and diagnostic traces may contain sensitive material. KíLín -does not provide encrypted workspaces, an execution sandbox, or guaranteed -scientific correctness. Never share a workspace or trace archive assuming -it has been anonymized. +make installation and all optional actions offline. The optional +[reference lookup](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/kilin/tools/reference_check/README.md) sends selected +bibliographic information to Crossref or OpenAlex only after explicit user +authorization. Choose a projects folder that is not cloud-synchronized when +working with sensitive data; KíLín does not control synchronization by +services such as iCloud or OneDrive. + +Conversations, source snapshots, and diagnostic traces may contain sensitive +material. KíLín does not provide encrypted workspaces, an execution +sandbox, or guaranteed scientific correctness. Never share a workspace or +trace archive assuming it has been anonymized. Read the [security notes](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/security.md) diff --git a/assets/brand/README.md b/assets/brand/README.md index 357a9f25..88931925 100644 --- a/assets/brand/README.md +++ b/assets/brand/README.md @@ -8,6 +8,9 @@ copies under `kilin/gui/icons/` instead of loading files from this folder. - `kilin-mascot-master.png` and `kilin-head-master.png`: full mascot and head artwork from which presentation and icon variants are prepared. +- `kilin-qilin-head.png` and `kilin-qilin-head-dark.png`: cropped head + variants for light and dark backgrounds, retained as portable artwork + rather than packaged GUI resources. - `kilin-light.png` and `kilin-dark.png`: light/dark application icon exports. - `01-mark-light.svg` through `04-mark-white.svg`: mascot-and-mark variants, including monochrome black and white versions. diff --git a/kilin/gui/icons/kilin-qilin-head-dark.png b/assets/brand/kilin-qilin-head-dark.png similarity index 100% rename from kilin/gui/icons/kilin-qilin-head-dark.png rename to assets/brand/kilin-qilin-head-dark.png diff --git a/kilin/gui/icons/kilin-qilin-head.png b/assets/brand/kilin-qilin-head.png similarity index 100% rename from kilin/gui/icons/kilin-qilin-head.png rename to assets/brand/kilin-qilin-head.png diff --git a/docs/PLUGIN_API.md b/docs/PLUGIN_API.md index b61eb0ba..b17b15de 100644 --- a/docs/PLUGIN_API.md +++ b/docs/PLUGIN_API.md @@ -181,7 +181,7 @@ Treat indexed data and host-owned records as read-only. | `ToolContext` field | Supported behavior | | --- | --- | -| `project_root`, `source_root` | Workspace root and optional saved source root. | +| `project_root`, `source_root` | Workspace root and optional canonical `sources/` root. | | `chunks`, `graph`, `rank`, `retrieval_count` | Indexed `Chunk` records, `CodeGraph`, complete hybrid ranking and configured retrieval count. | | `source_files()`, `unsearchable(paths)` | Selected source paths and sizes; files without indexed text. | | `source_view(policy, scope)` | Optional host factory returning `ToolSourceServices` bound to one operation generation. | @@ -207,7 +207,7 @@ fields and constructor semantics are part of the tool-facing contract. | Record | Fields and semantics | | --- | --- | -| `Chunk` | `identifier`, source-relative `path`, exact `text`, one-based `start_line`/`end_line`, `kind`, optional `symbol`, `section`, `cell`. | +| `Chunk` | `identifier`, source-relative `path`, exact extracted `text`, one-based inclusive `start_line`/`end_line`, `kind`, optional `symbol`, `section`, `cell`. | | `HybridResult` | `score` (rank-fusion score), `chunk`, `channels`. | | `CodeGraph` | `entities` and `relations`; `CodeEntity(name, kind, path)` and `CodeRelation(source, relation, target)`. | | `EvidenceLimits` | `max_sources`, `passages_per_source`, `max_passages`, `max_tokens`, `coverage` (`bounded` or `exhaustive`). | @@ -225,7 +225,10 @@ fields and constructor semantics are part of the tool-facing contract. See the [retrieval pipeline](retrieval_pipeline.md) and the [retrieval request contracts](../kilin/retrievals/requests.py) for semantics of limits, source -coverage and evidence. A card is not original source evidence. +coverage and evidence. Chunk coordinates refer to the source reader's +extracted content, not necessarily literal file bytes. Notebook lines are +cell-local and PDF lines are page-local with section provenance. A card +is not original source evidence. ### Source-view services @@ -242,10 +245,14 @@ The immutable source-view records and these functions are exported from See [source views](retrieval_pipeline.md#source-views-and-operation-snapshots) for field defaults, purpose, scope, relationship direction, availability and -snapshot semantics. `scope=None`/omitted is project-wide; `scope=()` is -restricted empty. A nonempty explicit scope defaults to restricted except -for a single comparison operand, which defaults to preferred. An explicit -mode takes precedence. `compare` does not enable grouping. +snapshot semantics. With no resolved view or explicit scope mode, +`scope=None`/omitted is project-wide; `scope=()` is restricted empty. A +nonempty explicit scope defaults to restricted except for a single comparison +operand, which defaults to preferred. An explicit mode takes precedence. +When a `RetrievalRequest` receives a resolved `view` and both `scope` and +`scope_mode` are omitted, it inherits the view's scope. Any explicitly +resolved scope that differs from the view is rejected. `compare` does not +enable grouping. The records and pure resolver are available to host code and controlled fixtures. A prepared `RAGSession.source_view(policy, scope)` resolves against @@ -281,9 +288,9 @@ is an eligible relative `Path`. The returned `ToolSourceServices` exposes `rank(text)`, `retrieve(request)`, `card(path)`, `read_bytes(path)` and `validate()`. Construct bounded requests with `view=services.view` to inherit the exact scope; the host rejects scope changes. Query embeddings -are reused across views within one run. Raw views cannot rank. Cards are -available only for eligible independent anchors, and lookup-only members -are not document ranking evidence. `read_bytes` verifies the captured +are reused across views within one run. Raw views cannot rank or retrieve +passages. Cards are available only for eligible independent anchors, and +lookup-only members are not document ranking evidence. `read_bytes` verifies the captured content digest and existing workspace containment. Validate before saving derived output. Changed operation identities cause an explicit conflict. @@ -292,9 +299,15 @@ Tools may declare `source_policies(settings)` on their descriptor; `validate_source_policy` checks the accepted vocabulary. The bound type validates declared policies at load time; project overrides validate merged settings before persistence against accepted organization. Runtime views -are always validated again. Empty role arrays in the reference tools mean -unrestricted roles; empty relation arrays disable expansion. Missing scoped -services are errors, not permission to fall back to `context.rank()`. +are always validated again. In a directly constructed `SourcePolicy`, +`target_roles=None` imposes no additional anchor-role restriction, whereas +`target_roles=()` permits no roles. `candidate_roles=None` inherits the +`target_roles` filter; explicit candidate filters may differ. The bundled +reference tools normalize their empty configured role arrays to `None`, +so their JSON settings do not have the same empty-role semantics as direct +`SourcePolicy` construction. Empty relation tuples disable expansion. +Missing scoped services are errors, not permission to fall back to +`context.rank()`. The original `chunks`, `rank`, `source_files` and related inventory services remain available for tools intentionally working on physical inventory. Do not scan the project or open metadata independently from a tool to @@ -308,8 +321,9 @@ Return `ToolResult(answer, evidence, summary, streamed=False)`. The Markdown answer uses one-based `[n]` citations corresponding to `evidence` records: `citation`, `path`, `start_line`, `end_line`, `symbol`, `text`, and `cell`. Use a source-relative `pathlib.Path` for `path`; the host serializes it. -Evidence text must match original source lines. `summary` contains JSON-safe -facts saved with the turn. Use an empty evidence tuple when no evidence is +Evidence text must match the original extracted source lines, using the +source-unit coordinates described above. `summary` contains JSON-safe facts +saved with the turn. Use an empty evidence tuple when no evidence is cited. Do not manufacture evidence from model responses or diagnostic data. The host raises `IncompleteModelResponse` for rejected model completions; @@ -333,6 +347,13 @@ the raw callbacks. Both helpers preserve the host's interaction records. without asking when no callback exists. The choice helper returns a zero-based option index or `None` for cancellation, invalid choice, or absent callback. The tool owns the meaning and handling of its quick/cancel options. +A `continue` result with `asked=False` is not user consent to external data +disclosure. For a network operation that sends project data outside the +local system, require an available confirmation callback, an explicit +operation-specific plan identifying the data and destination, and an +affirmative response with `asked=True`. Without that approval, do not +perform the external operation. The bundled `reference_check` tool follows +this contract for its optional online lookups. `ToolTrace` describes the supported trace interface: `include_content`, `emit(event_type, *, component, data=None, status="completed", turn_id=None)` @@ -347,9 +368,10 @@ configuration, write its files or invent interaction events. See Use `selected_paths(context)` to obtain the active selected-source inventory. `selected_source_file(project_root, source_root, path, selected)` validates a -selected source-relative regular file and returns a contained path or `None`; -it does not search arbitrary folders or accept symlink traversal. Handle an -absent `source_root` explicitly. These helpers are not a security sandbox. +selected source-relative regular file under the project's real `sources/` +directory and returns a contained path or `None`. It rejects alternate roots, +symlinks, and junctions. Handle an absent `source_root` explicitly. These +helpers are not a security sandbox. `save_output_file(project_root, name, text)` writes a text output under a safe, unique filename in the workspace's outputs folder without overwriting an existing file. Use relative imports for package-local code and locate owned assets relative @@ -379,8 +401,8 @@ files under that namespace. The helpers do not create directories; the core installs only required resources during project creation or explicit repair. Do not scan another tool's namespace or fall back to packaged files when a user-owned template is missing. Tool-specific formats are not restricted to -Markdown. Other workspace resource categories retain their existing contract. -This namespace rule is part of the tool API finalized for beta 2, generation 1. +Markdown. Other workspace resource categories follow their own documented +contracts. ## Catalog access and initialization @@ -391,8 +413,9 @@ in their established order. `kilin.project_type_ids()` returns the project catalog's identifiers. Catalog queries initialize the needed definitions on first use; ordinary contract imports do not. The runtime tool registry is created once per process. Public package directories with `__init__.py` are discovered automatically; private -packages are excluded. Existing iteration and chooser orderings are retained, -with additional bundled names and then user names appended alphabetically. +packages are excluded. The registry and chooser each define their own +canonical bundled-tool order, with additional bundled names and then user +names appended alphabetically. An invalid bundled descriptor prevents publication; invalid user packages are reported individually. Recursive initialization fails explicitly. Project types are discovered after tools and retain individual diagnostics. @@ -619,15 +642,13 @@ A corrupt or ambiguous private journal fails closed rather than overwriting an unknown entry. Replacement identities are captured from staged content and verified against its digest before activation. The tool descriptor is not executed again merely to obtain its queued version. Project-type -metadata is also rechecked during structural validation. Complete or cancel -pending operations in an older prerelease checkout before switching to a -checkout requiring the new journal fields; incomplete old records are not -migrated or assigned guessed versions. Do not edit the journal manually. The mechanism protects -against cooperating-process interruption, not sudden storage loss, malicious -plugins, or manual edits to an active or pending installation. Use a local -filesystem supporting the operating system's file locks and atomic renames. -Older KíLín versions without lifecycle coordination must also be closed -before managed changes. Workspaces and copied workspace assets are not +metadata is also rechecked during structural validation. Incomplete journal +records cannot establish an activation identity; the runtime rejects them +rather than guessing versions. Do not edit the journal manually. The +mechanism protects against cooperating-process interruption, not sudden +storage loss, malicious plugins, or manual edits to an active or pending +installation. Use a local filesystem supporting the operating system's file +locks and atomic renames. Workspaces and copied workspace assets are not modified by installation, updates or removal. ## Desktop plugin management diff --git a/docs/PLUGIN_AUTHORING.md b/docs/PLUGIN_AUTHORING.md index ede7184c..5d56759c 100644 --- a/docs/PLUGIN_AUTHORING.md +++ b/docs/PLUGIN_AUTHORING.md @@ -34,10 +34,12 @@ make a relation or a role grant filesystem access. Bounded `retrieve()` validates and enforces explicit scopes and views; grouped documentary views require source-first retrieval. Count anchors for logical quotas and unique physical passages for hard budgets. Inspect `result.groups` and anchor -coverage rather than counting physical `result.sources` as papers. View-bound -raw ranks, chunks and other tool services are still pending. Fail explicitly -when a required service is unavailable, rather than falling back to -unrestricted ranking or raw reads. +coverage rather than counting physical `result.sources` as papers. Obtain +view-bound ranking, chunks, retrieval and verified physical reads through +`require_source_services`. Raw-file views do not permit passage ranking or +retrieval. Fail explicitly when a required service is unavailable, rather +than falling back to unrestricted ranking or raw reads. See [Scoped source +services](#scoped-source-services). ## A repeatable development loop diff --git a/docs/README.md b/docs/README.md index 8acff755..56fd8c09 100644 --- a/docs/README.md +++ b/docs/README.md @@ -24,7 +24,7 @@ replace one another. The supported environment is defined in | Understand source selection and extraction | [Source pipeline](source_pipeline.md) | [Workspaces](project_workspaces.md), [index identity](retrieval_pipeline.md#index-persistence-and-identity) | | Add a type, reader or tool | [Extension interfaces](extension_interfaces.md) | [Configuration](configuration.md), [tool services](tool_packages.md) | | Change desktop behavior | [GUI architecture](gui_architecture.md) | [Protocol](gui_protocol.md), [conversation ownership](conversation_ownership.md) | -| Debug/test/release | [Development](development.md) | [README publication](readme_publication.md), [macOS builds](release.md), [Performance](performance.md), [Security](security.md) | +| Debug/test/release | [Development](development.md) | [README publication](readme_publication.md), [Native installers and releases](release.md), [Performance](performance.md), [Security](security.md) | ## Contract ownership @@ -64,7 +64,7 @@ responsibility, not authority over the source implementation. | [Trace-format changelog](TRACE_FORMAT_CHANGELOG.md) | Trace-format generation history. | | [Development](development.md) | Coding/documentation process, test runners, packaging and PR verification. | | [README publication](readme_publication.md) | Branch-relative README links, generated PyPI metadata, release tags and checks. | -| [macOS builds](release.md) | Ad-hoc development builds, native artifact checks, limitations and manual testing. | +| [Native installers and releases](release.md) | macOS and Windows installer builds, release automation, native artifact checks, limitations and manual testing. | | [Module map](module_map.md) | Complete production Python inventory and the primary reference for each module. | | [Architecture diagrams](diagrams.md) | Editable SVG inventory, ownership, accessibility and visual-maintenance rules. | diff --git a/docs/answering_pipeline.md b/docs/answering_pipeline.md index 4eeb6d6b..fee91f4b 100644 --- a/docs/answering_pipeline.md +++ b/docs/answering_pipeline.md @@ -27,31 +27,36 @@ loaded answering model and in-memory formatted messages; the router may share that session or be a separate loaded chat model. The optional GUI adapts callbacks and displays core-owned timelines without maintaining a separate record. A `ToolContext` -provides scoped operations for registered built-in tools, not arbitrary -filesystem or Python execution. +provides scoped operations for registered distribution and trusted user +tools. These services do not grant arbitrary filesystem or command access; +trusted Python plugins themselves execute with the user's permissions. +The tool API is not a Python sandbox. ## One turn, in execution order ![Sequence of routing, evidence acquisition, a single model or tool answer producer, citation checks and an atomic completed-turn checkpoint.](figures/answer-sequence.svg) -*Figure: An ordinary successful turn passes through an optional evidence stage, one answer producer, citation-ID checks and persistence before completion.* +*Figure: A high-level view of a successful turn. The detailed sequence below also identifies optional conversation-memory retrieval and the router-generated representation.* ```text ask(question, options) | - +-- validate settings, mark token usage, start trace/turn - +-- route_question(): shortcut or router model -> RouteDecision - +-- resolve intent and related turn IDs / history policy - +-- select retrieval mode and a search query - | +-- search -> ranked chunks and named-file context - | +-- document -> selected full document with budget - | +-- reuse -> previous evidence + +-- validate request, mark usage, start trace + +-- resolve effective settings and eligible history + +-- resolve intent: shortcut, router model or configured default + +-- select related turns, retrieval mode and search query + +-- acquire ordinary evidence when required + | +-- search -> ranked chunks within the resolved source view + | +-- document -> eligible full document with budget + | +-- reuse -> verified current evidence from related turns | `-- none -> no new evidence + +-- retrieve conversation memory when permitted for a direct answer +-- choose exactly one answer producer - | +-- configured built-in tool -> ToolResult - | `-- ChatSession.reply() with history + evidence prompt + | +-- registered tool (owns its retrieval and generation) -> ToolResult + | `-- ChatSession.reply() with history, evidence and permitted memory +-- validate completion or retain an explicitly incomplete result - +-- deterministic citation-ID check; collect token usage + +-- normalize citations and check citation IDs + +-- prepare optional router-generated summary; collect token usage +-- freeze core activity timeline; form ConversationTurn + representation +-- persist checkpoint; append committed turn `-- notify completed phase (observer) @@ -62,9 +67,11 @@ The state machine uses `ANSWER_PHASE_*` identifiers (`routing`, `routed`, `generating`, `saving`, `completed`, and `processing`). Not every intent performs every phase; tools may control additional progress and confirmation. See [GUI protocol](gui_protocol.md) for event wire fields and the distinction between backend and frontend -operation states. A callback's failure **before** commitment can abort the -turn; a failure in the final completed notification is traced but should not -recast a successfully committed answer as a failed generation. +operation states. One answer producer does not imply one model call: +routing, evidence checks, tool-owned generation and answer summarization +can have separate calls. A callback's failure **before** commitment can +abort the turn; a failure in the final completed notification is traced +but should not recast a committed answer as a failed generation. ### Core answer timelines @@ -169,10 +176,10 @@ of previous-turn evidence. The repeated-question dialog has no Cancel button; the normal Stop control remains available. Without a callback, the router selects the route normally. `RouteDecision.repeated_turn` is traced. -Project types currently package several intents for `code` and `literature`: -a mixture of normal answering, named-document reading, source inventory, -mention finding/classification, report generation, related-turn reuse and -small talk. Intent JSON selects retrieval and history behavior, a system +Registered project types declare their supported intents, which can include +ordinary answering, named-document reading, source inventory, mention +finding/classification, report generation, related-turn reuse and small +talk. Intent JSON selects retrieval and history behavior, a system instruction, optional answer guidance, a request-local thinking policy, and possibly a registered tool. `project_type._parse_intent()` defaults to `search` for ordinary intents, @@ -208,10 +215,11 @@ latency; see [Package defaults](package_defaults.md). Saved turns include original question, answer, evidence, timestamp and parameters. `turn_representation()` constructs a compact summary used when routing later questions: the question, cited sources and a one-sentence -answer summary. When the router is used, `summarize_answer()` asks the -router model for that sentence once, before the turn is saved, and the -representation records the model under `summary_model`. Its summary is -bounded to 200 characters for the router; the existing +answer summary. For eligible routed answers, `summarize_answer()` can ask +the router model for that sentence once, before the turn is saved. When a +generated summary is available, the representation records the model +under `summary_model`. The summary is bounded to 200 characters for the +router; the `conversation.turn.representation` diagnostic trace operation also retains the complete generated sentence for the GUI, without changing router inputs. The answer's first sentence is kept for one-sentence answers, small talk, @@ -330,9 +338,10 @@ restriction does not become project-wide. Complete-document selection reads one eligible original target/candidate. The `reuse` path and `include_related_evidence` retain only current eligible passages whose saved source identity, indexed text/coordinates and on-disk content agree. -New ordinary turns save their evidence-source hashes for this purpose; -older unverified citations remain historical records, not current support. -No-retrieval conversation and historical memory operations are unchanged. +Ordinary turns save their evidence-source hashes for this purpose; +unverified citations remain historical records, not current support. +No-retrieval conversation and historical memory operations are distinct +from current source-evidence reuse. For ordinary **hybrid** `search` intents, routed answers make at most one evidence-sufficiency check per search round (one by default) using the @@ -374,8 +383,8 @@ below; truncated text is not accepted as a successful final answer. The core also records `model_summary` in completed-turn parameters, using the active chat model ID and the recorded thinking, temperature and maximum output tokens. For direct answers it reports effective per-intent -thinking when present. The GUI renders the saved description rather than -reconstructing it; older turns use their separately saved fields. +thinking when present. The GUI renders the saved description when present; otherwise it uses +the saved individual settings. When the question is about several documents (a number of them, "review the five articles", or all of them, "all the papers") and the evidence @@ -397,12 +406,13 @@ is owned by [tool generation settings](tool_packages.md#generation-settings-for- The completion checks below apply after those settings have been resolved. For a tool intent, `tools/_registry.run_tool()` invokes the registered -package with a `ToolRequest` and a `ToolContext`. It returns `ToolResult` +distribution or trusted user package with a `ToolRequest` and a `ToolContext`. It returns `ToolResult` containing `answer`, numbered evidence, summary metadata and the `streamed` flag. `streamed=True` means the tool already sent output through the provided writer and it must not be emitted again. The context can supply controlled model calls, ranking, notes, output-file access and confirmation. -It is not a generic arbitrary plugin or unrestricted system command API. +The context is a bounded service interface, not a sandbox for trusted +Python plugin execution. Some tools plan potentially large operations and ask the GUI for a `continue`, `quick` or `cancel` choice via `ToolPlan`. The engine may accept @@ -469,7 +479,7 @@ prompts explicitly warn against interpreting missing notes as absent evidence. A necessary input with no usable notes stops dependent synthesis. Optional `show_source` explanations can fail without hiding the verbatim passages. -History omits wholly incomplete turns and legacy thinking-only answers as +History omits wholly incomplete turns and thinking-only answers as user/assistant pairs. Partial answers retain their completed content and warning. Original turn numbers and diagnostic records remain intact. @@ -482,9 +492,9 @@ When no usable notes or sections survive, no report is published. Ordinary reports with failed validation and no recoverable item failures still fail strictly; unrelated invalid output is not promoted to a complete report. -Existing schema-repair calls remain separate; a completion-failed -classification batch is not sent through another schema-repair retry. Backend -and programming errors are not newly swallowed by a general retry mechanism. +Schema repair is separate from completion recovery; a completion-failed +classification batch is not sent through schema repair. Backend and +programming errors propagate rather than triggering a general retry. Completion validation and partial recovery do not prove factual correctness, citation support, correct routing or exhaustive retrieval. A backend without termination metadata or visible thinking delimiters may not provide enough @@ -492,8 +502,10 @@ information to trigger the conservative recovery condition. ## Citation checks and answer truthfulness -After model/tool output, `_invalid_citations()` checks whether cited numeric -identifiers correspond to supplied evidence. Invalid references are recorded +Prose citations such as `[source 3]` are normalized to `[3]` in streamed +and saved answers without rewriting inline or fenced Markdown code examples. +After output normalization, `_invalid_citations()` checks whether cited +numeric identifiers correspond to supplied evidence. Invalid references are recorded in turn parameters. This is a **diagnostic**, not semantic verification of scientific claims, and it does not trigger a second generation attempt or auto-correction of the text. An answer may contain unsupported or mistaken diff --git a/docs/architecture.md b/docs/architecture.md index d7223882..91dcff21 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -47,9 +47,12 @@ presentation state). Their lifetimes and owners must not be conflated. | Retrieval | `retrievals/` builds semantic, lexical, graph and optional source-card indexes, persists validated records, fuses rankings and identifies named-document context. | | Answering | `rag.py` coordinates an operation; `answering.py` routes intents and selects history; `chat.py` generates text; `embeddings.py` produces query/document vectors. | | Models | `runtime.py`, `model_defaults.py`, `huggingface.py`, `query_formats.py` choose backends, model IDs, cached snapshots and embedding-query formats. | -| Tools | `tools/_registry.py` resolves configured built-in tool packages; `_contract.py` defines requests, context, and results; `_shared/` holds reusable private services. | +| Tools | `tools/_registry.py` resolves configured distribution and trusted user tool packages; `_contract.py` defines requests, context, and results; `_shared/` holds reusable private services. | +| Plugin lifecycle | `plugins/` owns extension discovery, validation, installation and deferred activation. | | Conversation | `conversations.py` owns the project catalog; `conversation_format.py` defines the stored state; `conversation_ownership.py` coordinates writers; `atomic_writes.py` replaces one file safely. | +| Conversation memory | `conversation_memory/` owns feedback, derived memory indexing, retrieval and historical recall, independently of original source evidence. | | Diagnostics | `trace_logging.py` implements optional diagnostic events and shared conversation checkpoints; `docs/performance.md` describes trace-derived benchmarking. | +| System testing | `system_testing/` validates recordings, generates references, replays recorded operations and compares results. | | Desktop | `gui/engine.py` orchestrates core operations; `window.py` owns Qt/QProcess/QWebChannel; `web/app.js` owns frontend state; supporting GUI modules own preferences/model choices/PDF rendering. | The [module map](module_map.md) assigns all implementation modules (including @@ -60,11 +63,13 @@ architecture tables are explanatory, not an alternate API specification. ### Project-type identity `ProjectTypeId` identifies a validated `ProjectType` configuration; -`ProjectProfile.type_id` selects it for a workspace. All packaged type -definitions are available in deterministic filename order, including in -the GUI. No particular type ID is mandatory. See -[configuration](configuration.md#canonical-identifiers-and-schemas) for -field names and [project workspaces](project_workspaces.md) for empty +`ProjectProfile.type_id` selects it for a workspace. The catalog discovers +distribution definitions first, followed by user definitions, in filename +order within each group. Invalid definitions are inspectable but unavailable; +distribution IDs take precedence over conflicting user IDs. No particular +type ID is mandatory. See [extension interfaces](extension_interfaces.md#creating-a-project-type) +for catalog behavior, [configuration](configuration.md#canonical-identifiers-and-schemas) +for field names and [project workspaces](project_workspaces.md) for empty creation and later source import. ## Lifecycle of a project @@ -77,16 +82,22 @@ creation and later source import. last. Opening saved state and later imports/synchronization are separate operations. See [workspace ownership](project_workspaces.md#creation-opening-and-explicit-updates) for collision and rollback rules, including empty projects. -3. **Open session.** `RAGSession` resolves paths, acquires exclusive - conversation ownership, opens a trace or disabled-trace equivalent, - inspects source changes, builds or reuses ordinary and configured - source-card indexes, then constructs model sessions. +3. **Open session.** `RAGSession` opens the project, resolves the + conversation path and establishes conversation ownership through the + trace or an explicit lock when tracing is disabled. It validates saved + conversation state before project diagnostics, indexing or model + construction. After preparing project diagnostics and selecting a + backend, it loads the embedding model, builds or reuses retrieval + indexes and prepares configured source cards. It then loads the main + answering model, restores conversation history and applicable saved + generation settings, and reports readiness. 4. **Answer.** Project-type intents determine routing, history policy, retrieval mode and optional tool. Source-aware operations resolve the accepted semantic graph and physical selection under the effective policy. Logical grouping does not change physical evidence coordinates. Evidence and its provenance accompany the model or tool answer; successful turns - are checkpointed. + are checkpointed. Conversation memory provides separate historical + context, not additional original source evidence. 5. **Resume.** Conversation selection and metadata are managed separately from loading an answer model. A session can change conversations without rebuilding indexes or models (subject to any encountered errors). @@ -104,8 +115,9 @@ fails. A workspace is an organizational directory, **not a process security sandbox**. Core folders include `profile.ini`, `indexes/`, `logs/`, -`outputs/`, and `templates/`. All new projects use `sources/`; saved -profiles retain their recorded source path. Cumulative imports use +`outputs/`, and `templates/`. All projects use the workspace's `sources/` +folder; the profile must declare `source = sources` and cannot redirect +source access to an alternative root. Cumulative imports use `sources.json` and single-origin mirrors use `source_snapshot.json` for provenance. The root `source_manifest.json` separately owns accepted roles, links, suppressions and organization settings; `indexes/index_source_state.json` diff --git a/docs/configuration.md b/docs/configuration.md index d19843d9..a22103cf 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -73,19 +73,19 @@ JSON files itself. This resource does not supersede the separately owned ## Project behavior overrides Each existing project's optional `project_behavior.json` changes only that -project's shared and per-intent behavior. Packaged project types remain -immutable. `profile.ini` still owns backend, model, indexing filters, and -answer settings. `[tool.]` owns shared tool settings. +project's shared and per-intent behavior. The registered project-type +definition is not modified. `profile.ini` still owns backend, model, indexing +filters and answer settings. `[tool.]` owns shared tool settings. The behavior file uses the **`project-behavior`** format, a fixed `project_type_id`, and four required sparse objects: `global`, `intents`, -`capabilities`, and `memory`. Only differences from the packaged defaults -are stored. `capabilities` controls source indexing (`code_graph` and -`document_headers`); `memory` controls conversation-memory indexing, -retrieval and disliked-history exclusion. Intent-local memory settings +`capabilities`, and `memory`. Only differences from the registered +project-type defaults are stored. `capabilities` controls source indexing +(`code_graph` and `document_headers`); `memory` controls conversation-memory +indexing, retrieval and disliked-history exclusion. Intent-local memory settings are stored inside `intents..memory`, independently of the same intent's ordinary routing, tool and retrieval settings. Nested differences merge -into packaged settings before the normal project-type validation. +into the registered definition before the normal project-type validation. An explicit `{ "$delete": true }` removes an optional inherited field when changing retrieval strategy. This is an internal marker, not an editor value. @@ -99,12 +99,10 @@ Prompts and routing edits apply to subsequent requests without model reload or index rebuild. New turns preserve original intent history and retrieval classifications so changes do not reinterpret their behavior. -The additional core editor scopes are `memory` for the complete -project-wide conversation-memory policy and `intent_memory` for one -intent's `indexing`/`read` pair. The same `global` and `intent` editor -scopes remain available. The current core validates and persists these settings; -turn UUIDs, feedback persistence and disliked-history filtering are -implemented independently of the editor. Conversation-memory indexing +The `memory` editor scope covers the project-wide conversation-memory +policy; `intent_memory` covers one intent's `indexing`/`read` pair. The core +validates and persists these settings independently of turn UUIDs, feedback +persistence and disliked-history filtering. Conversation-memory indexing and retrieval are core operations, independent of the GUI. The desktop **Memory** tab edits project-wide policy, inspects eligible saved messages, provides Exclude/Restore, and explicitly synchronizes the derived index @@ -123,10 +121,10 @@ These declarations are not project assignments or a new index configuration. New projects capture these defaults in the [accepted source manifest](source_manifest.md). Project-local organization settings are edited through its preview/apply API. Imports and refreshes use the accepted settings, not newly installed defaults. -Changing `profile.ini` to point to a different source root requires an -explicit semantic rebind. A moved workspace with a project-relative source -root keeps its binding. Missing/corrupt manifests and detector mismatches are -reported rather than implicitly repaired or adopted. +Every project uses its real `sources/` directory. Alternative configured +roots and source-root rebinding are unsupported. Moving the whole current +workspace preserves its relative semantic binding. Missing/corrupt manifests +and detector mismatches are reported rather than implicitly repaired or adopted. Ordinary intents have `retrieval.related_evidence` and `retrieval.related_lookup` arrays of declared relation IDs. The core behavior @@ -146,7 +144,7 @@ the semantic manifest, not `project_behavior.json` or `profile.ini`. ### Source-first retrieval limits -Packaged project types define the source-first search caps per intent: +Project types can define source-first search caps per intent: `max_sources`, `passages_per_source`, `max_passages`, and `evidence_tokens`. The caps are upper bounds, not quotas: a question with only a few relevant sources may return fewer passages. Writing @@ -165,7 +163,7 @@ Code Repository uses hybrid search and the saved project-profile budgets may improve coverage but consume more model context and increase latency; projects can override per-intent limits in Settings → Intents. -The revised Writing Assistant definition now includes Word documents, +The bundled Writing Assistant definition includes Word documents, LaTeX manuscripts and bibliographies, Python/MATLAB code, and notebooks among its default source suffixes, alongside PDF, Markdown, and text. These are creation defaults; existing projects retain their saved @@ -251,15 +249,38 @@ functions, which use the project's `[router]` section. Independently, model and parameters in `[source_card_generation]`. These are core settings, not a way to change active answering or routing sessions. The GUI maintains effort levels and search-depth steps in the same `profile.ini` through -`kilin.gui.model_settings`; it no longer owns router persistence. These -settings are initialized from effective application preferences only when +`kilin.gui.model_settings`. These settings are initialized from effective +application preferences only when missing, including when a valid core-created project is first opened in the GUI. Saved settings take precedence and invalid present values are rejected. Each effort-level record in GUI settings must have exactly `name` and `model`; -search-depth steps are separate. Historical `effort_levels.json` and -`model_choices.json` sidecars are neither read nor deleted. To retain their -old choices, back up the files and transfer the desired values explicitly -through Settings. +search-depth steps are separate. The project's `profile.ini` is the +canonical owner of its saved effort levels and model choices. Update these +values through Settings. + +### Required saved profile fields + +Every persisted `profile.ini` must provide the current core schema. Opening +and configuring a project reject missing fields without rewriting the file +or substituting creation defaults. The core Python API and GUI use the same +reader. + +| Section | Required fields | +| --- | --- | +| `project` | `type_id`, `source`, `extensions`, `max_file_bytes` | +| `models` | `backend`, `allow_download`, `chat_mlx`, `chat_torch`, `embedding_mlx`, `embedding_torch`, `query_format` | +| `chunking` | `target_tokens`, `max_tokens`, `overlap_tokens` | +| `retrieval` | `count` | +| `generation` | `thinking`, `temperature`, `max_new_tokens`, `block_unrequested_cjk` | +| `metadata` | All five [creation-provenance fields](versioning.md#project-creation-provenance) | + +`max_new_tokens = none` is a valid explicit value; a missing option is an +error. Creation provenance records the actual application and project type +used at creation and remains unchanged when the runtime or plugin changes. +Valid historical identity values are descriptive and do not gate execution. +Core-created projects do not need GUI-specific settings sections. Existing +optional GUI settings and router initialization retain their own current +contracts. ### Source-card indexing policy @@ -329,10 +350,11 @@ cards. See [Retrieval pipeline](retrieval_pipeline.md#automatic-source-card-inde ## Core packaged defaults -`kilin.defaults.load_defaults_section()` reads the packaged core JSON via -`importlib.resources` and provides typed validators. Individual modules -validate the sections they own, rather than trusting arbitrary JSON values. -The resource is loaded once per process, not watched for hot reload. +`kilin.defaults` reads `kilin_defaults.json` relative to its module and +caches the parsed resource once per process. `load_defaults_section()` +returns an independent copy of a section. Individual modules validate the +sections they own using the typed validators in `kilin.defaults`. The +resource is not watched for hot reload. Missing keys, invalid types and incompatible values raise errors; the validator does not rewrite or repair the shipped resource. @@ -348,8 +370,10 @@ independent source-card inference defaults, documented in the it does not select which intent should answer an arbitrary question. `CHAT` owns the language/script vocabulary used in positive CJK output requests; a keyword mention alone does not grant permission. The per-project `[generation]` -`block_unrequested_cjk` flag controls whether suppression is enabled, with -`PROJECT_PROFILE.BLOCK_UNREQUESTED_CJK` as the fallback for older profiles. +`block_unrequested_cjk` flag controls whether suppression is enabled. Every +saved profile must include the flag explicitly; omission is an error and +never substitutes a package default. `PROJECT_PROFILE.BLOCK_UNREQUESTED_CJK` +supplies the initial value only when creating a project. Changing scanner exclusions or the answer-routing heuristic vocabulary in this JSON changes future operations and can affect previously created @@ -378,19 +402,30 @@ template. `kilin/question_suggestions.py` fills them in two steps: -1. **Once per source change:** the router model reads the first two files - (usually the user's own) and a random mix of ten others, and picks a - pool of up to three themes (one subject of up to four words each, such - as "Alzheimer's disease"), ten topics and ten exact terms. A word is - kept only when it is printed in the sources. The pool is saved in - `indexes/suggestion_words.json` and picked again only when the sources - or the router model change. -2. **Every time questions are needed** (when a project opens, for each new - empty chat, and for "What can you do for me?"): each template is filled - up to three times with files, themes, topics and terms chosen at - random. No model is called, so this is instant and the examples change - every time. A question with an unfilled placeholder is left out; a code - project's questions name only code files. +1. **Obtain a word pool on demand.** When generation is permitted and no + valid pool exists, the router reads short descriptions of up to twelve + eligible files (the first two ranked files and a random sample of the + rest). It proposes up to three themes (one subject of up to four words + each, such as "Alzheimer's disease"), ten topics and ten exact terms. + Only words and phrases verified in eligible indexed passages are kept. + A successful result is saved in `indexes/suggestion_words.json`. + Reuse requires a supported format and a matching fingerprint of indexed + chunk identifiers (filtered to document candidates for non-code projects), + router model ID and code/document selection policy. Changing these inputs + invalidates the pool but does not itself trigger generation. +2. **Fill templates whenever examples are requested.** Each template is + filled up to three times with files, themes, topics and terms chosen at + random from the available values. Filling itself uses no model. A + question with an unfilled placeholder is left out; code projects + prefer code files when present. + +`RAGSession.question_suggestions()` and `RAGSession.welcome_prompts()` +accept `generate=False` to use a valid saved pool without router inference, +or `generate=True` (the default) to permit generation when needed. The GUI +uses the non-generating form when opening projects or empty conversations. +An explicit assistant-guide request can generate a missing or invalid pool. +Without a valid pool, templates that need only available filenames can still +be filled; configured fallback prompts also remain available. `welcome_templates` is a list of fill-in headings for the top of an empty chat, such as `"What would you like to understand about {theme}?"`, with @@ -416,8 +451,11 @@ per intent and ends with how to add files (drag them onto **sources** in the Workspace panel, or attach them with **+** in the message box) and how to remove one. A question about files, such as "how to drag files", gets only these steps; a project without sources gets them first, followed by -the fixed `suggestions`. No model is called. After the answer, the desktop -app briefly flashes the **+** button and then the **sources** folder. +the fixed `suggestions`. The guide formats its answer without an answering +model call; obtaining examples may invoke the router to generate the word +pool. A file-help request uses deterministic instructions only. After the +answer, the desktop app briefly flashes the **+** button and then the +**sources** folder. An intent can override inherited prompt/history/retrieval settings, specify shortcut regexes and select a registered tool. The parser gives missing @@ -491,7 +529,7 @@ parameters. Missing values have validated core defaults; packaged literature intent values are documented in [Retrieval pipeline](retrieval_pipeline.md#per-intent-source-first-configuration). An existing project can change them through its validated per-intent -`project_behavior.json` overrides, without modifying the packaged type. +`project_behavior.json` overrides, without modifying the registered type. Changes affect subsequent retrieval, not previously saved answers. A tool-backed intent instead uses its tool's validated settings and does not automatically execute source-first retrieval. See the tool precedence @@ -533,10 +571,10 @@ routing still selects the configured default intent and its policy. The control uses the selected model's existing `enable_thinking` chat-template argument. Templates or models that do not support this control cannot be made non-thinking by this setting; no model fallback or output -filter is added. Restart after editing a packaged project-type JSON because -validated types are cached. Existing workspaces use the updated intent policy -on subsequent requests after restart; saved answers are not rewritten and no -profile migration or reindexing is needed. +filter is added. Restart after editing a registered project-type definition +because validated types are cached. Existing workspaces use the updated +intent policy on subsequent requests after restart; saved answers are not +rewritten and no profile update or reindexing is needed. Saved turn parameters keep `thinking` as the configured value used to restore a conversation. Direct model answers additionally record `thinking_effective` @@ -554,9 +592,8 @@ The JSON filename stem is the type ID. The catalog can be empty, but an unavailable type cannot be opened or used to create a project. Saved workspaces remain intact. Catalogs are captured for the process; use the [managed plugin workflow](PLUGIN_AUTHORING.md) rather than editing active -files. Callers of the removed `PROJECT_TYPE_ID_CODE` and -`PROJECT_TYPE_ID_LITERATURE` constants should use the corresponding `"code"` -and `"literature"` identifiers, or query the registry for generic selection. +files. Use the identifiers `"code"` and `"literature"` for those specific +project types, or query `kilin.project_type_ids()` for generic selection. The current representations are: @@ -569,18 +606,20 @@ The current representations are: | Index settings, turn parameters and intent trace metadata | `project_type_id` | | Project-type JSON files | Filename stem; no duplicate ID field | -Former Python project-kind names and old profile/protocol/metadata keys -have no compatibility aliases or migration readers. Workspaces using that -previous profile schema must be recreated; old index or trace metadata -must not be assumed to match this schema. This restriction is distinct from -opening a current-schema profile with an older source-folder name. The -unrelated `kind` fields on source entities and chunks retain their meaning. +Use the canonical identifiers and field names above. Profiles must satisfy +the current schema and select the real `sources/` directory. Unsupported +profiles and layouts are rejected without automatic conversion; preserve the +original workspace and create a new project from its sources if necessary. +Reuse index or trace data only when it satisfies the applicable format and +validation contracts. The `kind` fields on source entities and chunks are +separate from project-type identifiers. -### New-project source convention +### Project source convention Source-folder ownership is fixed by the core, not a project-type setting. See the [source-directory convention](project_workspaces.md#source-directory-convention) -for new projects and the handling of previously saved source paths. +for the required layout in both core and GUI. Unsupported layouts are +preserved without automatic conversion. ## GUI defaults and writable preferences @@ -592,9 +631,9 @@ Missing user preferences are normal on first run. Invalid values are reported, not silently substituted with unknown settings. By default GUI preferences live in a per-user configuration directory; -`KILIN_DEFAULTS_FILE` is an explicit **absolute-path** override for that -user preferences file (despite its historic name). It does **not** point to -the immutable shipped defaults during normal use. +`KILIN_PREFERENCES_FILE` is an explicit **absolute-path** override for that +user preferences file. It does **not** point to the immutable shipped +defaults during normal use. A recognized development checkout defaults GUI workspaces to its repository `sandbox/`; an installed package suggests `KíLín` under the OS Documents @@ -609,8 +648,8 @@ synchronized by iCloud, OneDrive or another external service; users needing strictly local project storage should choose a non-synchronized path. Choose any existing projects folder explicitly using Browse. KíLín does -not search former default locations. Selecting a folder records a preference -without moving or rewriting its projects, which must satisfy the current +not search other locations automatically. Selecting a folder records a +preference without moving or rewriting its projects, which must satisfy the current project format. See [GUI architecture](gui_architecture.md) and [GUI README](../kilin/gui/README.md). @@ -658,8 +697,8 @@ types or bounds fail rather than being silently ignored. `MODEL_CALLS`, `ESTIMATES`, `HEURISTICS` and other non-`SETTINGS` sections are internal packaged configuration, not per-intent or saved project overrides. They are not offered by the tool-settings API. The exact thinking policy, -output-limit resolution, retained short-response exceptions and customized -configuration compatibility notes belong to +output-limit resolution, short-response exceptions and customized +configuration validation belong to [Generation settings for tools](tool_packages.md#generation-settings-for-tools). Packaged files are cached; restart the application or notebook kernel after @@ -706,7 +745,7 @@ new packaged JSON resource. The separation of creation defaults, saved settings and per-call policy is what makes a reopened project reproducible. A configuration edit must identify which lifetime it affects, whether a restart is needed, and whether index -identity changes. Do not treat a new default as an implicit migration. +identity changes. New defaults do not implicitly update saved settings. Inspect the owning validator and every profile/GUI consumer together. Test [project defaults and profiles](../tests/kilin/test_project.py), diff --git a/docs/conversation_memory.md b/docs/conversation_memory.md index 398c35c6..72963bc1 100644 --- a/docs/conversation_memory.md +++ b/docs/conversation_memory.md @@ -46,12 +46,16 @@ project/ ``` The `memory/` folder is created for every new project but feedback JSON is -created **only on an explicit update**. Feedback is not saved inside -conversation checkpoints, trace events, ordinary source files, or derived -indexes. `open_project()` does not create or migrate memory files. -When the configured source directory is the project root, the managed -`memory/` folder is excluded from source scans. A registered tool cannot -install a resource into this reserved folder. +created **only on an explicit update**. `memory/feedback.json` is the +authoritative feedback store; rating changes do not modify conversation +checkpoints or ordinary source files. Enabled GUI diagnostics can retain +copies of requested and committed ratings and revisions in the project +trace. The derived memory index reflects feedback through eligibility and +priority, but is not the feedback store. `open_project()` does not create +or migrate memory files. +Project source scans are rooted in `sources/`, so the managed `memory/` +folder is outside the source inventory. A registered tool cannot install a +resource into this reserved folder. The `FeedbackStore` API lives in `kilin.conversation_memory.feedback`. It accepts a workspace root and @@ -81,7 +85,7 @@ memory indexing; a Dislike makes it ineligible even if it remains saved. A neutral, unsaved, non-excluded record is removed rather than stored. An optional ``"excluded": true`` field independently forbids indexing or retrieval of that specific message, even when Save or Like remains selected. -The field is omitted when false, so existing feedback files remain valid. +The field is omitted when false. Restoring an exclusion re-applies the saved project and intent policies; it does not necessarily force indexing. Resetting Save/Like/Dislike does not silently clear the exclusion, and exclusion does not delete the original @@ -92,8 +96,9 @@ does not certify generated assertions as primary evidence. When a branch retains a turn UUID, it observes the same feedback. When an unrelated answer happens to have the same text, its UUID and feedback are independent. Archiving a conversation does not delete feedback: another -active branch can continue to reference its inherited turn. Memory retrieval restricts origins to active conversations and reconciles -stale records, without deleting authoritative feedback prematurely. +active branch can continue to reference its inherited turn. Memory retrieval +restricts origins to active conversations and reconciles stale records at +synchronization, without deleting authoritative feedback prematurely. ## Atomicity and revision checks @@ -121,7 +126,7 @@ silently reset. Feedback is retained across rebuilds of disposable indexes. ## Excluding disliked answers from conversational context -When `history.exclude_disliked_answers` is true (the default for all five +When `history.exclude_disliked_answers` is true (the default for all bundled project types), `RAGSession` reads the project-owned `feedback.json` before each question and excludes saved turns whose **assistant** feedback is `disliked`. This policy works even when long-term conversation memory is @@ -159,27 +164,38 @@ rebuildable data**. A separate checksum validates the index payload; the same atomic file-write and advisory-lock mechanisms used elsewhere protect index replacement. Corrupt indexes are rebuilt rather than migrated. Invalid conversation or feedback content fails explicitly rather than being trusted. -Archiving or deleting a conversation removes that origin on the next sync; -active branches continue to point to their inherited turn UUID. Metadata +`ConversationStore.archive()` moves a conversation to `logs/traces/.deleted/`, +outside the active scan, so its origin is removed on the next enabled sync. +Active branches continue to point to their inherited turn UUID. A timestamped +file retained in the active directory by `RAGSession.reset()` remains within +the scan; see [Conversation ownership](conversation_ownership.md). Metadata contains the active conversation ID, one-based turn number, timestamp, role, and turn UUID. Cross-project memory is never searched. -Intent policies are applied to the intent originally saved with each turn. -`never` forbids all indexing; `explicit` requires Save or Like; `automatic` -uses the project's question and answer policy. A disliked or explicitly excluded message is never -indexed, even if saved. A disliked **assistant** response does not forbid -independently indexing its paired user question. Answers marked as incomplete -or containing only hidden thinking are not indexed. `answers = none` forbids -assistant entries even when explicitly selected. Source/document and tool -indexes are unaffected by these decisions. +The intent identifier saved with each turn selects its policy from the +**current effective configuration**. A missing intent or one absent from +that configuration makes the turn ineligible. `never` forbids all indexing; +`explicit` requires Save or Like; `automatic` uses the project's question and +answer policy. +A disliked or explicitly excluded message is never indexed, even if saved. +A disliked **assistant** response does not forbid independently indexing its +paired user question. `answers = none` forbids assistant entries even when +explicitly selected. Source/document and tool indexes are unaffected by these +decisions. + +Assistant answers with a saved completion marker, including `incomplete` or +`partial` results, are excluded. Hidden model thinking is removed from +assistant text, and empty messages are skipped. The indexed text is limited +to the first 12,000 characters after this preparation; saved questions and +answers remain unchanged. Each indexed occurrence is keyed by `(conversation_turn_uuid, role)`. Its embedding key is instead the SHA-256 fingerprint of role and normalized searchable text. Identical messages from distinct turns retain separate feedback but reuse one embedding. Inherited branches share a single indexed -occurrence with multiple active origins. Search results avoid repeating the -same fingerprint within one answer. Hidden model thinking is removed from -indexed assistant text; the saved conversation remains unchanged. +occurrence with multiple active origins. Ordinary retrieval avoids repeating +the same fingerprint within one answer. Historical lookup instead preserves +question–answer pairing by turn identity. `RAGSession.sync_conversation_memory()` is the GUI-independent entry point. It checks active file size/mtime signatures, feedback revision, effective @@ -194,7 +210,18 @@ the current process, avoiding repeated turn reads on subsequent syncs when policy, feedback, index and file metadata are unchanged. A process restart may require one new verification. Actual turn, feedback or policy changes invalidate this observation and are re-evaluated. Disabled memory does not -read or embed prior conversation content. +read or embed prior conversation content, and does not delete an existing +index. + +Every newly observed conversation snapshot first passes the shared +[current conversation schema](conversation_ownership.md#current-persisted-schema), +even when an existing derived index has matching file signatures. This +ensures that cached file signatures cannot bypass schema validation. +Subsequent unchanged reads reuse the verified observation; +valid diagnostic-only changes still avoid embedding and index rewrites. +Invalid saved turns, registration groups, evidence, timing, and checkpoint +hashes fail before embedding or modifying the derived index. The read-only +message inspector and summary reader apply the same complete validation. ## Strictly separate answer-prompt channels @@ -225,7 +252,7 @@ current ones, or allowing retrieved text to override project or intent rules. Reviewing's researcher-only judgment boundary remains in force. The memory budget (`max_hits` and estimated `max_tokens`) never reduces the source passage budget or renumbers citations. When no memory is returned, the -source-only prompt remains byte-identical to the existing path. +source-only prompt remains byte-identical to the path without memory. Ordinary memory retrieval combines semantic cosine similarity (75%) and weighted lexical overlap (25%). It requires semantic similarity of at least @@ -244,8 +271,14 @@ An explicit historical request such as *"Did we discuss optical tweezers?"* uses a separate conservative path. ``recall_topic()`` recognizes narrowly phrased first-person history questions; the system checks distinctive topic words against **eligible saved conversation messages in the synchronized -memory index**, without performing a semantic embedding lookup. Recent saved -turns are included even when they also appear in the current chat context. +memory index**. Matching is lexical and does not embed the query. The +preceding synchronization may still embed newly eligible or changed messages +with the loaded embedding model. This path requires enabled project memory +and an intent that answers directly and permits `memory.read`; an unsuitable +routed intent can use the project's default only when that default also +answers directly and permits memory reading. Recent saved turns are included +even when they also appear in the current chat context. + When a matching question is found, its eligible paired answer may also be shown. A previous question establishes only that the researcher *asked*, not that a claim was validated or a conclusion accepted. No match means that the @@ -262,10 +295,10 @@ included immediately after its question when both fit the configured truncated to preserve the pair. If no pair fits an unusually small memory text budget, an eligible question may still be returned on its own to avoid falsely reporting that no matching saved messages exist. An unpaired question -records that a topic was -raised but does not imply an answer or agreement. In particular, an excluded, -disliked, incomplete, or never-indexed reply cannot be reconstructed from -the question. With `max_hits: 1`, only the matching question can be shown +records that a topic was raised but does not imply an answer or agreement. +In particular, an excluded, disliked, incomplete, or never-indexed reply +cannot be reconstructed from the question. With `max_hits: 1`, only the +matching question can be shown for a paired turn; larger paired groups are skipped rather than silently dropping the reply when a partial slot remains. Directly matching assistant messages without an eligible matching question can also appear alone, with @@ -276,7 +309,7 @@ For an executable, no-model illustration of these policies, see For non-historical questions, memory query formatting has its own instruction rather than reusing the source-evidence retrieval instruction. -There is no new summarizing model call. Memory is not used to validate +This formatting adds no summarizing model call. Memory is not used to validate citation claims. ## Desktop feedback and memory navigation @@ -320,12 +353,22 @@ It does not persist copied previews or summaries. The answer's action row shows a small memory icon and the number of retrieved messages, alongside Save, Like, and Dislike. Clicking the icon expands a compact list. The GUI requests current summaries from registered origin conversation traces on -every expansion, without indexing or model calls. Answer notes display the +every expansion, without indexing or model calls. Each origin's saved turn +position must contain the requested UUID. Answer notes prefer the **complete** model-generated summary from the trace's -``conversation.turn.representation`` operation, not the bounded routing -summary in saved parameters. For older traces and inherited branch turns -without that operation, the existing compact saved representation is a -fallback; text already truncated by a prior version cannot be recovered. +``conversation.turn.representation`` operation when an unambiguous +``state.checkpoint.committed`` event associates that diagnostic turn with +the saved UUID. The event must have completed status and +``immutable_state_saved: true``. Diagnostic turn numbers can include failed +attempts and differ from saved turn positions; they do not establish this +association. + +A missing, invalid or ambiguous association uses the compact representation +of the verified saved turn, unless another registered active origin supplies +a matching full diagnostic summary. For example, an inherited branch turn +can use its active parent's diagnostics. An explicitly emptied full summary +stays empty; the reader does not replace it with the saved compact summary. +The read does not modify checkpoints or persist a second summary cache. Question notes display at most 160 characters of the original saved question, including an ellipsis when shortened. This limit applies only to the displayed note, not the trace read or saved question. Both are @@ -365,8 +408,16 @@ eligible messages and origins without copying their text or vectors. See [Trace architecture](trace_architecture.md#conversation-operations). The index contains prior research discussions and embeddings, potentially -including sensitive or speculative content. It is not encrypted or anonymized. -See [Security](security.md) for the local trust boundary. +including sensitive or speculative content. Changes to feedback or active +origins are reconciled in the derived index at the next enabled +synchronization; they do not immediately purge the stored index. Disabling +memory leaves that index in place. These controls do not erase original +conversations, already recorded prompts, or independent backups and copies. +Although retrieval and synchronization metadata omit message text, enabled +model-prompt traces can contain the retrieved memories supplied for answering. +Feedback diagnostics can also retain earlier ratings after they change. +Memory and diagnostic files are not encrypted, anonymized or automatically +redacted. See [Security](security.md) for the local trust boundary. ## Tests and verification @@ -376,8 +427,9 @@ Focused deterministic tests live in `tests/kilin/conversation_memory/test_inspection.py`, `tests/kilin/test__conversation_memory_index.py`, `tests/kilin/test__conversation_memory_retrieval.py`, and -`tests/kilin/test_rag__conversation_memory.py`, alongside the PR2 and PR3 -feedback, checkpoint and disliked-history tests. GUI protocol coverage lives +`tests/kilin/test_rag__conversation_memory.py`, alongside +`tests/kilin/conversation_memory/test_feedback.py`, checkpoint tests, and +`tests/kilin/test_rag__disliked_history.py`. GUI protocol coverage lives in `tests/kilin/gui/test_engine__conversation_memory.py`, `tests/kilin/gui/test_engine__memory_management.py`, `tests/kilin/gui/test__memory_management_frontend.py` and diff --git a/docs/conversation_ownership.md b/docs/conversation_ownership.md index 53e38820..abc5e1a2 100644 --- a/docs/conversation_ownership.md +++ b/docs/conversation_ownership.md @@ -6,6 +6,103 @@ The session's checkpoint and callback lifecycles distinguish committed turns from unsuccessful operations. This document describes how KíLín keeps individual conversation files consistent across components and processes. +## Current persisted schema + +`kilin/conversation_format.py` owns the shared validation contract used by +RAG, tracing, the named conversation store, conversation memory, GUI readers, +and system-test inspection. Resumable state exists only in +`sessions["05_conversations"]["resume_state"]`. The session's separate +`turns` mapping contains diagnostics; `resume_state.turns` is the list of +completed, durable question/answer records. Diagnostics cannot supply +missing resumable fields. + +Registration and resumable history are independent groups. An absent group +is valid; a partially present group is invalid. Fixed records reject unknown +fields. Required nullable fields must be present as JSON `null` when unused. +Readers reject duplicate JSON keys, incorrect scalar types, and unsupported +state fields without coercion, repair, or file rewriting. Resumable-state +parameters contain only finite JSON values. The diagnostic writer's existing +nonfinite-number representation remains readable outside resumable state; +diagnostic numeric values do not prevent restoring valid history. Recording +inspection retains its separate, stricter diagnostic-data requirements. + +| Lifecycle state | Required content | +| --- | --- | +| New trace before any completed answer | Empty `resume_state` is valid. | +| Named conversation before any answer | All seven registration fields; no history required. | +| Core-only conversation | `system_prompt` and `turns`; no named-store registration required. | +| Registered conversation with history | Complete registration and history groups. | +| Full branch | Copies completed turns and any applicable checkpoint. | +| Truncated branch | Keeps `system_prompt` and the selected prefix of `turns`; omits both checkpoint fields. | +| Interrupted attempt | Retains the previous completed state; an unfinished diagnostic turn does not become saved history. | + +A missing conversation file means a new in-memory history. Existing invalid +files never mean an empty history. The named store retains accessible valid +records, reports invalid candidates through logging and `discovery_errors()`, +and refuses to silently create an empty replacement if every registered +candidate is invalid. Valid core-only files remain outside the named catalog +and are retained when a separate named conversation is created. + +### Registration fields + +Every registered conversation contains `conversation_id`, `name`, +`created_at_utc`, `updated_at_utc`, `parent_conversation_id`, +`origin_checkpoint_id`, and `origin_turn_count`. Identifiers remain safe, +opaque strings; they need not follow the generated identifier's spelling. +Names are nonblank strings of at most 80 characters. Metadata timestamps +are valid UTC dates and times, accepting both `Z` and `+00:00`. + +Parent and origin checkpoint identifiers are explicitly nullable. +`origin_turn_count` is an exact nonnegative integer or `null`; a Boolean is +not an integer here. Absence of this field is not interpreted as `null`. + +### Completed turns and evidence + +Every completed turn contains these seven fields: + +| Field | Current value | +| --- | --- | +| `conversation_turn_uuid` | Unique, lowercase, hyphen-free UUID4 string. | +| `timestamp` | Saved timestamp string, retained without rewriting. | +| `question`, `answer` | Strings, including valid empty strings. | +| `evidence` | List of complete evidence records; an empty list is valid. | +| `parameters` | JSON mapping whose keys vary by answering path. | +| `timeline` | Valid timing record or explicit `null` for an untimed answer. | + +Each evidence record requires `citation`, `path`, `start_line`, `end_line`, +`symbol`, `text`, `cell`, and `context_role`. Citation and line numbers are +positive exact integers, with `end_line >= start_line`. `cell` is a positive +exact integer or `null`; `symbol` is a string or `null`; `context_role` is +`"direct"`, `"related"`, `"alternative"`, or `null`. Text is a string and +the saved path is a nonempty, NUL-free string. Historical evidence is read +without resolving or requiring the source file to exist. These references +grant no filesystem access. + +A timeline requires `elapsed_ms` and `steps`; every step requires `phase`, +`label`, and `ms`. Durations are nonnegative exact integers, step durations +sum to elapsed time, and phase and label are nonblank strings. The existing +timeline parser owns those duration rules. Missing timing and explicit +`null` timing have different meanings: only the latter is an untimed turn. + +### Checkpoint consistency + +The outer `checkpoint_id` and `checkpoint` object are optional together. +When present, the checkpoint requires `checkpoint_id`, +`parent_checkpoint_id`, `conversation_sha256`, `index_fingerprint`, and +`turn_count`. The two checkpoint identifiers must agree, the exact integer +count must match the saved turn list, and the SHA256 must match the existing +writer's sorted, UTF-8 JSON serialization of `system_prompt` and `turns`. +The parent identifier is explicitly nullable and the index fingerprint is +a string. Checkpoint identifiers are not recomputed using current models, +project locations, or index settings: the original full snapshot includes +runtime information absent from this persisted checkpoint summary. + +All writers validate the complete candidate after merging an update. A +partial metadata update is allowed only when the resulting full record is +valid. Rejected candidates leave both saved bytes and active in-memory state +unchanged. Conversation initialization validates existing data under its +ownership lease before diagnostic writes or model initialization. + ## The ownership contract ![TraceLogger or a session owns a companion lock before validated state is atomically checkpointed to conversation JSON; conflicting writers fail.](figures/conversation-ownership.svg) @@ -47,7 +144,6 @@ disk after closure; **its existence does not mean that the file is locked**. Do not remove lock files while KíLín may still be using them, because a removed/recreated companion can break coordination between writers. The leading dot hides the sidecar in Finder and typical Linux file browsers. -This fresh-release convention does not migrate legacy lock filenames. ## Lifetimes and ownership @@ -118,19 +214,29 @@ one. If the new logger cannot acquire its target, the previous GUI trace remains active. This also works when the GUI owns the trace used by RAG: RAG borrows it rather than acquiring a second lock. -`RAGSession.reset()` archives the current file while owning its path and -continues with a fresh conversation under that same path. The GUI's -`ConversationStore.archive()` borrows the active owner where applicable, -then moves only the JSON to `logs/traces/.deleted/`. The hidden lock -companion remains at its original path even while a borrowed writer holds -the lease. Before archiving an active trace, the GUI flushes only pending -diagnostics. It then closes the old logger with `emit_event=False` to release -ownership without rewriting the archived JSON. An inactive conversation is -locked independently during archival; a competing owner prevents deletion. - -Archived conversations are excluded from the active catalog. There is no -in-app restore command. Exceptional restoration requires closing all KíLín -instances using the project, moving the archived JSON back to +`RAGSession.reset()` renames the current JSON to a timestamped +`conversation_*.json` file **in the same directory**, while owning the original +path. It clears the in-memory turns and checkpoint identity, resets chat +history to the system instruction, and continues a fresh conversation under +the original path. Loaded models and indexes are reused. An archive retained +in `logs/traces/` still matches conversation discovery and memory scans; it +can remain eligible for memory under the usual validation and indexing policy. +Resetting alone does not exclude that retained history from memory. + +GUI deletion uses `ConversationStore.archive()`, which borrows the active +owner where applicable and moves only the JSON to `logs/traces/.deleted/`. +The hidden lock companion remains at its original path even while a borrowed +writer holds the lease. Before archiving an active trace, the GUI flushes only +pending diagnostics. It then closes the old logger with `emit_event=False` +to release ownership without rewriting the archived JSON. An inactive +conversation is locked independently during archival; a competing owner +prevents deletion. + +The `.deleted` directory is outside active catalog discovery and conversation +memory scans. Derived memory records are reconciled on the next applicable +memory synchronization; see [Conversation memory](conversation_memory.md). +There is no in-app restore command for these archives. Exceptional restoration +requires closing all KíLín instances using the project, moving the JSON back to `logs/traces/`, and reopening the project. Returning it under its original filename reuses the hidden lock. If an archive collision added a suffix, restore to an unused conversation filename; a different filename receives @@ -156,11 +262,14 @@ force data to stable storage after power loss. File access and permissions remain the responsibility of the local environment; this helper introduces no configurable permissions policy. -On `RAGSession.close()`, KíLín attempts to close every owned model, its -owned trace, and its direct-write lock even if one cleanup step raises. The -first failure still propagates, with later failures attached as exception -notes. Errors during partial initialization likewise do not prevent other -models or the owned trace from being cleaned up. +On `RAGSession.close()`, KíLín attempts every owned model's cleanup, closes +both the owned conversation trace and the owned project trace, and releases +its direct-write lock even if one cleanup step raises. Caller-owned trace +sinks remain open for their owner to close. The first failure still +propagates, with later failures attached as exception notes. Failed +initialization likewise attempts cleanup of constructed model sessions, +owned trace sinks, and the session's conversation lease, preserving the +initialization error and attaching cleanup failures as notes. ## Errors and recovery diff --git a/docs/development.md b/docs/development.md index e1091181..abbf19bd 100644 --- a/docs/development.md +++ b/docs/development.md @@ -284,8 +284,9 @@ serialization policy. ## GitHub Actions and Python compatibility KíLín currently supports **Python 3.12** as declared in `pyproject.toml`. -The `uv.lock` file is scoped to the same interpreter range. CI is divided -into five independent workflows under `.github/workflows/`: +The `uv.lock` file is scoped to the same interpreter range. CI includes +five branch/PR workflows and a tag-triggered release workflow under +`.github/workflows/`: | Workflow | Validation | Required checks | | --- | --- | --- | @@ -293,7 +294,8 @@ into five independent workflows under `.github/workflows/`: | `package.yml` | Wheel/sdist, installed package and PyPI description verification | Ubuntu / Python 3.12 | | `docs.yml` | Documentation contracts and generated PyPI README freshness | Ubuntu / Python 3.12 | | `macos_app.yml` | Real Apple Silicon .app/.dmg build, signature, mounted-image inspection and installer regression tests | macOS / Python 3.12, ad-hoc signing | -| `windows_app.yml` | Real Inno Setup build, silent install, runtime and shortcut checks, uninstall | Windows x64, unsigned installer smoke | +| `windows_app.yml` | Real Inno Setup build, silent install, isolated runtime and shortcut checks, failed reinstall recovery, uninstall | Windows x64, unsigned installer smoke | +| `native_release.yml` | Version-tag validation, both reusable native smoke workflows, asset and checksum publication | Matching `v*` tag; both native jobs must succeed | Windows is a target platform, but support is not fully verified yet. Its Python 3.12 and Qt/PDF jobs run on every change and report their @@ -302,9 +304,11 @@ remaining Windows differences (open-file deletion, home-directory lookup, and native Qt/PDF behavior) are checked or corrected. Windows then becomes a required platform. -All workflows run on pull requests and pushes to `main` or `develop`; they -can also be launched manually. Tag pushes do not currently start a separate -publishing or release-verification workflow. The test matrix has +The five branch/PR workflows run on pull requests and pushes to `main` or +`develop` (with path filters where configured) and can also be launched +manually. A `v*` tag push starts `native_release.yml`, which invokes both +native workflows without path filtering. Only its publishing job has write +permission; PyPI publication is separate. The test matrix has `fail-fast: false`, so one platform failure does not cancel the other configurations. A Node.js runtime is installed for the JavaScript checks in the base test suite. @@ -374,6 +378,15 @@ a passing focused subset establishes complete coverage. ## Packaging and source exports +The published source distribution is a build input, not a complete +development checkout. `MANIFEST.in` excludes the repository-level `tests/` +tree from the source distribution; the wheel also excludes it. The tests +require the complete repository, including fixtures and development +resources. Use a Git checkout or a complete repository source ZIP to run +the development suite. The release check `setup.check_pypi_distribution` +verifies this boundary, the release description, and exact licence bytes +in both built archives before publication. + `pyproject.toml` uses setuptools and explicitly ships JSON project types, core defaults, reason codes, GUI HTML/CSS/JS/assets and tool-specific defaults/templates. A new packaged data file must be added to the package @@ -425,17 +438,28 @@ generated PyPI description and all tag-pinned documentation URLs. checks rendering syntax, not whether external image URLs resolve. 3. For `b` and `rc` releases, tag the validated commit on `develop`. For a stable release, merge to `main`, validate the merge commit - and tag it there. Create a GitHub Release marked **prerelease** for - beta and RC versions, not for the stable version. Do not mark - the stable `0.1.0` tag as prerelease. Keep tags pointing at the tested - commit. A `v*` tag push triggers automatic native builds and creates - the GitHub Release after both platform checks pass; do not publish an - immutable release before its installers have been attached. See - [Automatic native release assets](release.md#automatic-native-release-assets). -4. Check that the tag points to the exact source commit used for the - built wheel and sdist, then publish both **reviewed** files to PyPI. - Upload only after the GitHub release tag exists. Use the `kilin` - project and an account authorized to publish it: + and tag it there. Obtain explicit release approval before pushing the + tag, because it starts native publication. Push the matching annotated + `v` tag using a maintainer credential. Keep published tags + immutable. The tag push + starts automatic native builds; the workflow creates the GitHub Release + only after both platform checks pass, marking beta and RC releases as + prereleases and stable releases as ordinary releases. It may attach + assets to a matching existing mutable release, but never replaces them. + Do not publish an immutable release before its installers are attached. + See [Automatic native release assets](release.md#automatic-native-release-assets). +4. Verify both native jobs succeeded for that exact tag and that the GitHub + Release contains the versioned macOS DMG, Windows EXE, and matching + SHA-256 checksums. The builders use wheels from the tagged checkout, + independently of PyPI publication. Both installers remain experimental, + without Developer ID notarization or Windows code signing; complete the + manual installation acceptance checks on real systems before distribution. + For a local comparison, build using `bash setup/macos/build_app.sh --wheel` + or `powershell -NoProfile -ExecutionPolicy Bypass -File setup\windows\build_installer.ps1 -Wheel`. +5. Confirm the tag points to the exact source commit used for the reviewed + wheel and sdist. Only after the native release and checksum checks above, + and with explicit publication approval, publish both reviewed Python + distributions to PyPI. Use the `kilin` project and an authorized account: ```sh uv publish dist/kilin--py3-none-any.whl dist/kilin-.tar.gz @@ -444,17 +468,10 @@ generated PyPI description and all tag-pinned documentation URLs. Provide a project-scoped PyPI API token via the publishing tool's documented secure input method; do not commit tokens. A released PyPI version cannot be re-uploaded with different files, so publish any fix - under a new version. TestPyPI is an optional rehearsal, not a - substitute for checking the production release. Confirm the published - README images, links, citation, license and exact version on PyPI. -5. Check that the tag-triggered native release workflow attached a - versioned macOS DMG, Windows EXE, and SHA-256 checksums. The builders - use wheels from the tagged checkout, independently of PyPI publication. - Both installers remain experimental, without Developer ID notarization - or Windows code signing; public release assets are not substitutes for - manual installation acceptance on real systems. For a local comparison, - build using `bash setup/macos/build_app.sh --wheel` or - `powershell -NoProfile -ExecutionPolicy Bypass -File setup\windows\build_installer.ps1 -Wheel`. + under a new version. TestPyPI is an optional rehearsal, not a substitute + for checking the production release. Confirm the published README images, + links, citation, licence and exact version on PyPI, and verify installation + from the published package. The builder resolves `uv` symlinks (including Homebrew's), checks that its target is an Apple-silicon executable, and bundles the resolved binary. @@ -498,10 +515,21 @@ pointer intact; a crash afterwards selects the completed new release. On retry, an incomplete *inactive* directory for the requested release is rebuilt, while a completed but not yet active release can be reused. -Older versions used `runtime/app` without an active pointer. Such a -complete installation remains usable when its requirement matches the -running application; installing a different version preserves the legacy -environment and activates the versioned release only after validation. +Only the versioned layout is supported. An old `runtime/app` directory is +neither selected nor removed; without an active pointer, the launcher +installs or reuses the requested current release. A pointer containing +`app` or other invalid content is rejected without modification. After +stopping any older app, inspect an invalid pointer manually before retrying. +The pointer contains one relative release name followed by a newline. +Reuse requires the exact requested release identifier, the matching +`.installed` marker, and executable Python and GUI entry points. A real +virtual environment may link its Python interpreter, but the managed +runtime, releases and release directories, `bin`, GUI script and marker +must not be symbolic links. Ordinary aliases of ancestor directories +remain supported. Installation also refuses linked lock, log, Python +installation and cache paths before writing to them. These checks protect +managed entries, not against arbitrary concurrent filesystem changes. + Failed updates preserve the previous working installation and selection, but **do not silently launch the previous version** from a newer app. The launcher reports the failure for correction and retry. Previous releases @@ -549,9 +577,11 @@ The root `LICENSE` holds the Apache License 2.0 text declared by `pyproject.toml`. It must be committed to Git and present in source ZIPs, source distributions, and installed wheels. The source-export notebook requires `"LICENSE": True` and refuses missing or untracked licence files. -The isolated wheel check verifies the actual installed licence text; the -release test verifies the checkout file. Check the generated source -archive and source distribution as part of release verification. +The publication verifier (`python -m setup.check_pypi_distribution`) +compares the actual wheel and source distribution licence bytes with the +nonempty checkout file. The independent isolated wheel check verifies the +installed licence text; repository tests verify the checkout file. Check +the generated source ZIP as part of release verification. A source export is not a user-data backup. It should exclude `.DS_Store`, `__MACOSX`, AppleDouble files, caches, model weights, `sandbox/` contents, diff --git a/docs/extension_interfaces.md b/docs/extension_interfaces.md index e2e2d51f..b3568b63 100644 --- a/docs/extension_interfaces.md +++ b/docs/extension_interfaces.md @@ -26,27 +26,22 @@ stages installation, updates and removal until the next eligible runtime. ## Creating a project type -Packaged JSON files serve as examples. A new type is a -`.json` resource with validated `display_name`, `description`, -`extensions`, `max_file_bytes`, `retrieval_instruction`, `system_prompt`, -optional `answer_guidance`, `capabilities`, history settings, optional -`generation` defaults, a valid `default_intent`, an `intents` object and -optional empty-chat prompts. The loader derives the type ID from the -filename and rejects duplicate JSON keys. Every definition must declare an -independent SemVer `version` and integer `schema_version` (currently `1`). -Neither is inferred from the KíLín release or tool API. Missing declarations -are errors. Required history and conversation-memory fields, -all accepted intent fields, and a complete example are listed in the -[project-type JSON schema](PROJECT_TYPE_SCHEMA.md). For installing a user -type without editing KíLín itself, see [plugin authoring](PLUGIN_AUTHORING.md). - -`capabilities` accepts `code_graph` (`true`, `false` or `"auto"`) and -`document_headers` (`true` or `false`, default `false`). With -`document_headers`, document passages are indexed with title, author, -section and page headers. The separate `capabilities.source_cards` -policy controls whether eligible scientific papers receive card -summaries and stored vectors; it is not implied by `document_headers`. -See [Retrieval pipeline](retrieval_pipeline.md). +Packaged JSON files serve as examples. A project type is a +`.json` resource describing source selection, prompts, history, +conversation memory and intents. The loader derives the type ID from the +filename and rejects duplicate JSON keys. Each definition declares an +independent SemVer `version` and integer `schema_version`, neither inferred +from the KíLín release or tool API. The history exclusion policy and +conversation-memory object are required even when memory is disabled. +`default_intent` is optional and defaults to the first declared intent. +The optional `capabilities` object defaults to automatic code-graph +selection, no document headers and disabled source cards. Source cards +and document headers are independent indexing capabilities. + +The [project-type JSON schema](PROJECT_TYPE_SCHEMA.md) is the authoritative +reference for required fields, accepted values, defaults and examples. +See [Retrieval pipeline](retrieval_pipeline.md) for indexing behavior and +[plugin authoring](PLUGIN_AUTHORING.md) for installing user types. Optional `source_organization` declares a type's source roles, default role, relationship behaviors, and closed-registry deterministic discovery rules. @@ -61,7 +56,7 @@ previews; ordinary retrieval and scoped tool services resolve one-hop relationships against these accepted settings. The runtime catalog captures the raw JSON and validated definition once per -process, in filename order. Structural validation precedes resolution of +process, in discovery order. Structural validation precedes resolution of required tools and validation of their settings. A malformed definition or unavailable required tool makes only that type unavailable. A missing or empty catalog does not prevent saved-workspace inspection. There is no @@ -110,16 +105,16 @@ The `projects` event adds `available` (boolean) and `unavailable_reason` An obsolete new-project selection similarly returns the available list and an error, allowing the GUI to request fresh defaults for a valid selection. Reinstall or correct the definition or its required tools and restart to -restore availability; saved workspaces require no migration. +restore availability without modifying the saved workspace. -A project type does not name the source folder: every new project uses +A project type does not name the source folder: every project uses `sources/`. See [workspace source convention](project_workspaces.md#source-directory-convention) -for the layout and how existing projects keep theirs. A new type cannot bypass -the core's creation-only ownership rules or authorize reuse of an occupied -workspace. Empty projects are -supported for every type. Missing welcome content has generic fallbacks; -project-type prompts, tools and retrieval policies still control answers. +for the required layout and rejection of unsupported source paths. A type +cannot bypass the core's creation-only ownership rules or authorize reuse of +an occupied workspace. Empty projects are supported for every type. Missing +welcome content has generic fallbacks; project-type prompts, tools and +retrieval policies still control answers. Each intent key names an operation. Its fields may supply a description, shortcuts, wording `cues` that set the intent, `requires` patterns a @@ -167,30 +162,42 @@ entire pipeline supports its source formats or domain reasoning. ## Metadata contract for configurable settings Shared setting explanations belong to `kilin/settings_info.json`. Each -existing bundled tool provides `settings_info.json` with one record per +bundled tool provides `settings_info.json` with one record per normalized `SETTINGS` key from its `defaults.json`. Records have only `title`, `summary` and `description` and are served through KíLín's core `get_settings_info()` interface without importing the GUI. Values, validity and precedence remain owned by the existing settings parsers. -The new metadata resource must be included in the tool package-data table +The metadata resource must be included in the tool package-data table and verified in wheel tests. A minimal plugin may omit help metadata. See [configuration metadata](configuration.md#settings-information-explanations-not-configuration). ## Source access by built-in tools Source readers operate on the validated selection produced by the -repository scanner/importer. Built-in tools that subsequently open source -files must apply the same authorization, including when an indexed file -names another file. `tools/_shared/source_access.py` provides a reusable -selected-source resolver: it checks the active inventory, saved source -root, workspace containment and symlinks, returning no path when an item -is unavailable. It does not silently search other project folders. - -The LaTeX reference checker uses that helper for both `.tex` and selected -`.bib`/`.bbl` files. For same-named bibliographies in several directories, -it prefers the referring `.tex` file's directory and rejects ambiguous -fallbacks. Consult the [security policy](security.md#workspace-source-access-policy) -for explicit import exceptions and the limits of these checks. +repository scanner/importer. Tools must preserve that authorization even +when an indexed file names another file. For a scoped operation, request +`ToolSourceServices` through `require_source_services(context, policy, scope)`. +The host resolves a `SourceView` from the accepted source organization and +physical inventory under the requested `SourcePolicy` and `SourceScope`, +binding all views for the tool run to one captured source/index generation. +Use its scoped `rank()` and `retrieve()` services for evidence, its +`read_bytes()` service for authorized raw content, and `validate()` before +publishing derived output. Lookup-only members are not ranking evidence. +Raw reads preserve workspace containment and verify the captured content +digest. Missing scoped services, unauthorized reads and stale views are +errors, not permission to fall back to unrestricted ranking or file access. + +For example, `reference_check` obtains bibliography candidates from +`citing.view.lookup` and reads selected `.bib` and `.bbl` companions through +`optional_source_bytes(citing, path)`, which delegates to the bound +`read_bytes()` service when raw content is available. Missing or ambiguous +companions must not resolve to unrelated files. The full physical inventory +and its services remain available for tools intentionally operating on that +inventory, not as substitutes for scoped access. + +See the [source-view services](PLUGIN_API.md#source-view-services) for +API details and the [security policy](security.md#workspace-source-access-policy) +for workspace containment and the limits of these checks. ## Source reader/extractor contract @@ -256,11 +263,10 @@ versions, verifies generic provenance, then delegates to the kind's own schema checks. Kind registration must be explicit in source code; project JSON must not contain executable import paths. -The kind registry, provenance records, card/vector index, generation -adapter and automatic indexing coordinator are operational. The packaged -literature intents use `source_first`, which searches source-card -vectors as one of its four ranking channels. A new project type can -select trusted registered card kinds without loading arbitrary modules. See [Retrieval pipeline](retrieval_pipeline.md#generic-source-card-contracts). +The packaged literature retrieval intents use `source_first`, which +searches source-card vectors as one of its ranking channels. Project types +can select trusted registered card kinds without loading arbitrary modules. +See [Retrieval pipeline](retrieval_pipeline.md#generic-source-card-contracts). The `scientific_paper` kind keeps a consistent research-oriented schema, including bibliographic metadata and cited aims, methods, data, findings, @@ -268,14 +274,10 @@ and limitations. Its candidate check does not classify a PDF as a paper. The generation response confirms or rejects the kind in the same inference call that writes the card. Only supplied chunk IDs may support statements. -The design permits other registered kinds as requirements emerge: grant -proposals could emphasize objectives and work packages; patents, claims and -applications; technical manuals, procedures; presentations, main topics; -policy decisions, rationale and scope. These are **extension possibilities**, -not implemented kinds or implicit eligibility rules. Each future kind owns -its own validation, fields and instructions while reusing the same generic -card representation, indexing and persistence. See -[Scientific-paper cards](retrieval_pipeline.md#scientific-paper-cards). +Additional kinds require explicit implementation and registration, with +kind-specific fields, instructions and validation under the generic card +contract. See [Scientific-paper cards](retrieval_pipeline.md#scientific-paper-cards) +for the implemented kind. ## Implementing a built-in tool @@ -288,8 +290,11 @@ the package, configuration and resource files. The [public plugin API](PLUGIN_API.md) specifies the `Tool` descriptor exported as `PLUGIN` by each package. It declares its identity, versions, parser, runner, optional `follows_up` or `follows_up_when` behavior, optional -`routing` callback and optional `workspace_resources` callback. The loader -binds resources to the actual imported package. `routing(settings, project_root, others)` +`routing`, `workspace_resources` and `source_policies` callbacks. The +`source_policies(settings)` callback declares the tool's source policies for +validation at configuration boundaries; it does not authorize runtime +source access. The loader binds resources to the actual imported package. +`routing(settings, project_root, others)` returns a `ToolRouting` (cues and router description) built from the project's own files, which `with_project_routing` adds to the intent before each question is routed (`generate_paper_summary` describes the project's @@ -327,8 +332,12 @@ project root; all indexed chunks; the code graph; a ranking callback; retrieval count; source-file and unsearchable-file queries; controlled router and answering-model calls; streaming output; progress/done callbacks; confirmation; trace and turn ID; optional PDF writer; and optional document -choice callback. These are **capabilities supplied by the caller**, not -license to bypass project file ownership. +choice callback. It can also supply bounded `retrieve(request)` and +`source_view(policy, scope)` services; use the latter for generation-bound +scoped access as described above. These are **capabilities supplied by the +caller**, not license to bypass project file ownership. The +[public plugin API](PLUGIN_API.md#execution-context-and-data-records) is the +authoritative field-level reference. `ToolResult` has four fields: @@ -437,7 +446,7 @@ an index file format. - Confirm resource destinations cannot traverse outside the project or overwrite edited user files. - Preserve `kilin` imports without Qt and test the headless path. -- Test both project creation and reopened profiles; no unintended migration. +- Test both project creation and reopening; preserve saved user state. - Update tool README, local module docstrings and the module map. Use [tool dependency checks](../tests/kilin/tools/test__architecture.py), diff --git a/docs/gui_architecture.md b/docs/gui_architecture.md index 82750502..780e077b 100644 --- a/docs/gui_architecture.md +++ b/docs/gui_architecture.md @@ -32,8 +32,10 @@ constraint, which matters for integration test isolation. `resumeProjectConversation`, `previewSources`, `choosePlan`, and `stopOperation`. The bridge translates typed and JSON-encoded arguments into backend commands or handles native OS actions itself. The engine reads -commands sequentially, writes structured JSON events and forwards runtime -output to diagnostic tracing instead of mixing arbitrary text into stdout. +ordinary commands sequentially from a shared queue, writes structured JSON +events and forwards runtime output to diagnostic tracing instead of mixing +arbitrary text into stdout. A dedicated stdin reader applies cancellation +as soon as a `cancel_answer` command arrives. The page's `onEvent` consumes the events and updates transient view state; backend `opened`/`answered`/`conversations` events are not replaced by @@ -59,8 +61,10 @@ proof it will load. Model downloads are explicit GUI operations. Source preview and the core workspace-creation stage do not load inference models; subsequent session activation is a separate stage. -The page receives validated `type_id` entries from the core registry, selects -the first in filename order and keeps prompt-selection state for each type. +The page receives available `type_id` entries from the core registry, retains +the current selection if available and otherwise selects the first returned +type. It keeps prompt-selection state for each type. Distribution entries +precede user entries, with deterministic filename order within each group. Labels and welcome content come from the type definition, with generic source-independent fallbacks. Packaged definitions are examples, not a GUI allowlist. @@ -70,8 +74,9 @@ through the explicit-file path. The page uses `reason_code`, not display wording, for selection decisions; exact eligibility and payload fields are owned by the [source-preview protocol](gui_protocol.md#source-preview-contract). Confirmed sources and settings are passed to core creation and indexing. -An explicit workspace permits an empty source selection; the engine never -substitutes an example repository. +Empty source selections are supported with either an explicit workspace or +an automatically allocated destination. The engine never substitutes an +example repository. ### Creation, conflicts and activation @@ -91,8 +96,10 @@ A conflict leaves the current session and protected destination unchanged, including trace bytes. Failures before switching are displayed without writing an error to the previous project's trace. After creation, ordinary session activation opens the shared project and conversation sinks and loads -models; a model-load failure does not -delete the valid newly created project. +models; a model-load failure does not delete the valid newly created project. +Resume similarly distinguishes preflight failures, which preserve the +current session, from failures after session release has begun. The +`resume_released` error field identifies that boundary. Saved projects are listed and resumed without recopying their original sources. Later additions use `add_project_sources`, not a creation function. @@ -152,9 +159,8 @@ user state. A development checkout and an installed distribution can have different suggested workspace parents. The exact path overrides and preferences rules are owned by [Configuration](configuration.md#gui-defaults-and-writable-preferences). -The GUI uses the saved or explicitly selected projects folder without -scanning former default locations. Selecting a folder does not move or -migrate its projects. +The GUI uses the saved or explicitly selected projects folder. Selecting +a folder changes the catalog location without moving project files. `gui/_activation.py` implements the desktop passkey check. It is called from `gui/app.py`'s `main` after the Qt application exists and before @@ -164,10 +170,9 @@ settings or workspace files. An existing project's profile remains authoritative. `gui/model_settings.py` stores GUI-specific effort/search/router choices there rather than replacing -them from current global defaults. Only missing settings are initialized; -obsolete sidecars are not read or removed. For changes to the saved source -tree or resources, -use the [workspace APIs](project_workspaces.md#creation-opening-and-explicit-updates). +them from current global defaults. Only missing GUI settings are initialized. +Unrelated workspace files are not read as settings or removed. For changes +to the saved source tree or resources, use the [workspace APIs](project_workspaces.md#creation-opening-and-explicit-updates). ## Operation lifecycle and answer display @@ -183,26 +188,32 @@ request to answer: `answered`; the page only renders these and the live progress display. For a large tool plan, the backend can request a user choice **while the -answer is running**. The engine's `read_command` uses the same stdin iterator -for plan choices and ordinary dispatch; while awaiting a choice, unrelated -commands are consumed with an error rather than queued. Arbitrary parallel -command execution is not the current design. The page disables relevant -controls during model/index operations to reduce conflicting requests. +answer is running**. Ordinary dispatch and the engine's `read_command` +consume the same queue populated by the stdin reader. Cancellation is +applied immediately by that reader and also queued to end a choice wait. +Unrelated commands encountered during the wait are consumed with an error +rather than deferred. Ordinary commands execute sequentially. The page +disables relevant controls during model/index operations to reduce +conflicting requests. A numeric citation becomes a source-preview link only when it corresponds to the answer's saved evidence record. Preview requests carry turn index -and citation number; the engine returns exact contextual source excerpts or -a `reference_error` if the reference cannot be resolved. +and citation number. The engine attempts to read current source context, +falling back to the saved evidence when needed. Notebook previews use saved +cell-local excerpts. A `reference_error` reports an invalid or unresolved +citation identity. ## Conversations, Stop and recovery `ConversationStore` manages the local conversation catalog and metadata. The engine can select, create, branch, rename, archive/delete or reset a -conversation. A branch copies the whole conversation, or only its first -turns. Each message's **Branch from here** keeps the turns up to that answer; -on a question it keeps the turns before it and puts the question back in the -message box. Empty chats are not listed, so New chat, or a branch from the -first question, reopens an unused empty chat instead of adding another file. +conversation. A branch copies all or a prefix of the saved turns, including +their UUIDs and timelines, but not the parent's diagnostic sessions. Each +message's **Branch from here** keeps the turns up to that answer; on a +question it keeps the turns before it and puts the question back in the +message box. Unused empty chats are hidden, but the chat generating its +first answer remains visible. New chat, or branching from the first question, +can reopen an unused empty chat instead of adding another file. While an answer runs, another chat can be read: the busy engine is not asked, `ChatBridge.viewConversation()` reads the chat's saved file and sends `conversation_viewed`, and the page shows it read-only, keeping the running @@ -210,8 +221,10 @@ answer in its own chat. An answer that finishes meanwhile marks its chat unread in the sidebar until it is opened. Existing answer-model sessions and indexes are reused when switching conversations within the same project, subject to backend state. -The GUI stores answer timing as optional presentation metadata; it is not the -same thing as the diagnostic trace or the core `ConversationTurn`. +The core owns completed answer timing in `ConversationTurn.timeline`. Its +serialized field is required and may be `null` for an untimed turn. Browser +timers provide transient display estimates; diagnostic traces are separate +from the persisted timeline. Answer Stop requests cooperative cancellation first. An acknowledged cancellation retains the project and loaded models without committing the @@ -290,8 +303,7 @@ user can disable source cards and avoid loading the generation model. Cards are derived and independently regenerable; changing their model does not invalidate valid cached cards. Failed card generation leaves ordinary semantic, lexical, and graph retrieval available. Per-source settings remain -in the core-owned `source_card_sources.json` file, without an editor in the -initial GUI integration. +in the core-owned `source_card_sources.json` file and have no GUI editor. ## Related diff --git a/docs/gui_protocol.md b/docs/gui_protocol.md index 0e3ddc14..107832fb 100644 --- a/docs/gui_protocol.md +++ b/docs/gui_protocol.md @@ -79,10 +79,21 @@ maintains only display estimates while an answer is in flight; the completed summary and activity durations come exclusively from the core. There is no `save_answer_timeline` command or companion timing file. +Every saved completed turn must contain `timeline`; explicit `null` means +the answer was untimed. Missing fields, coercible scalar values, and +inconsistent checkpoints are rejected under the +[shared conversation schema](conversation_ownership.md#current-persisted-schema). +Qt's file reader does not display invalid records as empty chats. Project +usage totals exclude invalid records and accept token counts only as exact +nonnegative integers. Branch copies are counted once by their durable turn +UUID; separate answers with identical question text and timestamps remain +separate uses. Valid state-only and metadata-only records remain +supported without diagnostic events. + ## Project-type identifiers -Project selection uses `type_id` in `startup`, `projects`, `saved_project`, -`opened` and `settings.project_types` entries. The cross-layer identifier +Project selection uses `type_id` in `projects`, `opened` and +`settings.project_types` entries. The cross-layer identifier schema is owned by [Configuration](configuration.md#canonical-identifiers-and-schemas). The `open` command accepts `sources: []` with an empty `workspace`: the core allocates an available `new-project` name. An explicit `workspace` retains @@ -94,29 +105,28 @@ The page may ask whether to resume; confirmation sends `resume` without any creation settings or pending sources. Cancellation keeps the new-project inputs available for choosing another destination. Non-project occupied folders are not offered for resume. The final allocated path is reported by -`opened.project`, not guaranteed by a prior preview. The old project -`kind` protocol key is not accepted. Source-preview rows still use `kind` -for file/folder/link classification; that is a distinct contract. +`opened.project`, not guaranteed by a prior preview. Project identifiers use +`type_id`; source-preview rows use `kind` for file/folder/link classification. ## Engine command inventory -The following are the *existing engine dispatcher* actions. Required fields -are required by the dispatcher unless otherwise noted; the Qt bridge may -preprocess JSON strings or validate a subset before constructing the command. +The following are the engine dispatcher actions. Required fields describe +valid requests unless a dispatcher-specific distinction is noted. The +dispatcher extracts some fields directly and forwards others with defaults +for handler validation. The Qt bridge may preprocess JSON strings or +validate a subset before constructing the command. An empty `workspace` is meaningful for new-project settings. All project paths and source paths remain subject to downstream core validation. | Action | Required fields | Optional fields / current meaning | | --- | --- | --- | -| `startup` | None | Find a recent saved project (engine event currently has no browser handler) | | `readiness` | None | Check selected backend and model availability | | `install_required_models` | None | Download missing required models | | `use_installed_models` | None | Substitute available models where supported | | `settings` | `type_id`, `workspace` | Read project profile or new-project defaults | | `apply_models` | `settings` | Apply model and search-depth choices | | `download_model` | `model_id` | Download selected catalog model | -| `saved_project` | `type_id`, `workspace` | Find a matching saved project (event currently has no browser handler) | -| `saved_projects` | `workspace` | List saved projects for Resume | +| `saved_projects` | `workspace` | List recognized projects, including unavailable types, newest first; an explicit workspace checks that folder only | | `resume` | `project` | Optional `conversation_id` selects that exact saved conversation; without it, the most recently updated conversation is selected | | `close` | None | Release the active project/models; child remains running | | `preview` | `sources`, `extensions`, `max_file_bytes` | `workspace` defaults to `""` | @@ -124,29 +134,29 @@ paths and source paths remain subject to downstream core validation. | `preview_reference` | `turn_index`, `citation` | Look up one citation of a saved turn | | `ask` | `question` | `retrieval_count`, `generation_settings`, `effort` default to `None` | | `cancel_answer` | None | **Special:** applied by the input thread as soon as it arrives, so it stops a running `ask` at the model's next token; ends a wait for a tool plan or option; otherwise ignored | -| `new_conversation` | None | Create an empty conversation | +| `new_conversation` | None | Create an empty conversation or reuse an unused empty one | | `branch_conversation` | None | Create a branch of the active conversation; optional `turn_count` keeps only its first turns (default: all) | | `select_conversation` | `conversation_id` | Switch to a saved conversation | | `rename_conversation` | `conversation_id`, `name` | Rename the registered conversation | | `delete_conversation` | `conversation_id` | Archive/remove it from the visible catalog | | `check_sources` | `sources` | Report what adding these files and folders would copy and leave out, without copying; the page asks the user before `add_project_sources` | -| `add_project_sources` | `sources` | Optional `decisions` maps `sources/` paths to sync actions. Copy eligible new sources, apply supplied choices for existing copies, and reindex once. | +| `add_project_sources` | `sources` | Optional `selected_files` maps input folders to checked file paths; `decisions` maps `sources/` paths to sync actions. Copy eligible new sources, apply supplied choices for existing copies, and reindex once. | | `remove_project_sources` | `paths` | Remove confirmed copied project sources | | `sync_sources` | None | Optional `decisions` maps `sources/` paths to `import`, `replace`, `keep_both`, `delete` or `keep`; an explicit map leaves unlisted files untouched. Omitted or `null` decisions use the core automatic policy: update changed unedited copies, remove deleted unedited copies, and import no new files. Reindex afterward. | -| `edit_folder` | None | `folder` is an editable workspace-relative directory (including a nested directory); `operation` is `add`, `replace`, `remove`, or `mkdir`. For `mkdir`, provide `name` as one directory component; other fields are forwarded as keyword arguments. Returns `folder_changed` on success. | +| `edit_folder` | `folder`, `operation` | `folder` is an editable workspace-relative directory (including a nested directory); `operation` is `add`, `replace`, `remove`, or `mkdir`. For `mkdir`, provide `name` as one directory component; other fields are forwarded as keyword arguments. Returns `folder_changed` on success. | | `rename_project` | `name` | Rename the project | | `delete_project` | `project` | Move that closed project to `.deleted/` beside it (`kilin.project.delete_project`); then send `projects` | | `apply_indexing` | `settings` | Atomically save validated indexing settings, reopen the project and revalidate its index; send `indexing_applied` with the `profile` only after reopening succeeds | | `save_source_cards` | `settings` | Save project-wide source-card policy and both backend generation models, then reconcile derived cards only; send `source_cards_applied` with resolved settings and outcome counts | | `regenerate_source_cards` | None | Confirmed user action regenerating derived cards without rescanning chunks or rebuilding ordinary retrieval indexes; send `source_cards_regenerated` with counts | -| `save_answer_settings` | None at dispatcher | `settings` is forwarded (default `None`); the handler requires an object and an open project. Accepted updates are `temperature`, `thinking`, and `max_new_tokens`; other keys are ignored. The GUI additionally sends `request_id` (positive integer) and canonical `project` path to correlate the result. | +| `save_answer_settings` | `settings` | The dispatcher forwards `None` when omitted; the handler requires an object and an open project. Accepted updates are `temperature`, `thinking`, and `max_new_tokens`; other keys are ignored. The GUI additionally sends `request_id` (positive integer) and canonical `project` path to correlate the result. | | `settings_info` | None | Fetch descriptive core and registered tool metadata without opening a project; returns `settings_info` or `settings_info_failed` | | `source_organization` | `request` | Inspect, preview, apply, initialize or reconcile accepted source organization; correlated `source_organization` reply; see [semantic source commands](#semantic-source-commands) | | `project_behavior` | None | Read project-wide, capability and intent editors, defaults, identity and revision | -| `save_project_behavior` | `project`, `scope`, `intent_id`, `values`, `revision`, `request_id` | Save global, intent, capabilities, memory or intent_memory settings with project and revision checks; rebuild source indexes only for capabilities | +| `save_project_behavior` | `project`, `scope`, `values`, `revision`, `request_id`; `intent_id` for `intent` or `intent_memory` | For `global`, `capabilities` and `memory`, omit `intent_id` or supply `null`. Check project and revision; refresh source indexes only for capabilities. | | `conversation_feedback` | `project` | Read the active project's feedback revision and per-message ratings without changing its conversation files | | `save_message_feedback` | `request` | Write one saved-message selection/reaction with project, conversation ID, turn UUID, role, expected revision and positive request ID | -| `memory_messages` | `project`, `offset` (optional, 0-based) | Inspect a page of active saved messages and current memory eligibility without an embedding call | +| `memory_messages` | `project` | Optional zero-based `offset` defaults to `0`. Inspect a page of active saved messages and current memory eligibility without an embedding call. | | `memory_summaries` | `project`, `request` (`request_id`, `references`) | Read current untruncated summaries from referenced active conversation traces, without embeddings or model calls | | `set_memory_exclusion` | `request` | Exclude/restore one persisted message with project, turn, role, feedback revision and request ID checks | | `memory_status` | `project` | Read current project policy and last saved derived memory-index counts without a model call | @@ -155,9 +165,21 @@ paths and source paths remain subject to downstream core validation. | `versions` | `request_id` | Read application-wide version information and active project creation provenance without loading models | | `tool_settings` | None | List the open project's tools and their settings | | `save_tool_settings` | `tool` | `settings` (object of the tool's changeable settings) saved for the open project | -| `reset` | None | Start a new conversation; do not erase the previous trace | +| `reset` | None | Create a new registered empty conversation, retaining the previous chat; emit `reset` with `archived: null` | | `plan_choice` | None in the outer dispatcher | **Special:** consumed while awaiting a tool plan/option; otherwise ignored | +For `open`, the page submits preparation settings with +`_gui_full_snapshot: true`, including `_gui_effort_levels`, +`_gui_search_depth`, `_gui_router_models` and `_gui_source_cards`. The +engine separates these GUI settings from ordinary creation parameters. +The `gui.project.creation.settings` diagnostic event records requested +settings and, when the matching displayed defaults are available, their +sparse differences as explicit settings (`provenance: "displayed_defaults"`). +Without matching defaults, explicit settings are unknown (`"unavailable"`); +a direct explicit settings mapping without the snapshot flag is recorded +with `"explicit_request"` provenance. This diagnostic information is distinct +from the project's immutable creation provenance in the Versions panel. + ### Plugin management The Plugins panel is application-wide, independent of the selected project. @@ -195,8 +217,9 @@ responses by request ID and delegates rendering to `plugin_panel.js`. `kilin.__version__` for the banner. `ChatBridge.requestVersions(request_id)` forwards a version-report request to the engine. The `versions` event echoes the request ID and carries the active project path (or an empty string), -`creation_provenance` (or null), and `inventory` from `kilin.version_info()`; -failures carry `error`. The Versions section is application-wide and does +`creation_provenance`, and `inventory` from `kilin.version_info()`. Creation +provenance is the complete recorded identity for an open project and is +null only when no project is open; failures carry `error`. The Versions section is application-wide and does not require an open project. The frontend rejects stale replies, renders local data as text, and can copy the complete snapshot as JSON. Runtime catalog discovery follows the normal trusted plugin lifecycle; reporting @@ -217,40 +240,52 @@ and dynamic Settings fields, without embedding the explanatory strings. ### Project behavior editor -The `project_behavior` command emits an event with the canonical project -path, `project_type_id`, SHA-256 `revision`, global, capability and memory -editors (each with `values` and `defaults`), and ordered intents (`id`, -fixed `tool`, `values`, `defaults`, `source_first_defaults`, `memory`). -The editor resolves -packaged definitions with sparse project-local overrides. +The `project_behavior` command emits a `project_behavior` event whose +`behavior` object contains the canonical `project` path, `project_type_id`, +SHA-256 `revision`, `global`, `capabilities` and `memory` editors (each with +`values` and `defaults`), and ordered `intents` (`id`, fixed `tool`, +`values`, `defaults`, `source_first_defaults`, `memory`). The editor resolves +registered project-type definitions with sparse project-local overrides. `save_project_behavior` accepts the project path, scope (`global`, `intent`, -`capabilities`, `memory`, or `intent_memory`), optional `intent_id`, complete -editor values, revision and positive `request_id`. The core rejects different projects, stale -revisions, invalid configurations and tool changes. On success it emits -`project_behavior` with `saved: true` and the new revision; on error it -returns a correlated error. Indexing capability edits trigger a rebuild, -with configuration restoration and index recovery on failure. +`capabilities`, `memory`, or `intent_memory`), complete editor values, +revision and positive `request_id`. `intent_id` must identify a registered +intent for the two intent scopes and must be absent or `null` otherwise. +The engine and core reject different projects, stale revisions, invalid +configurations and tool changes. On success the event contains `behavior` +with the updated identity, editors and revision, plus `saved: true`, +`scope`, `intent_id` and `request_id`. Save errors carry `project`, +`scope`, `intent_id`, `request_id` and `error`. Indexing capability edits +trigger index refresh, with configuration restoration and index recovery +on failure. ### Conversation-memory feedback and index status `conversation_feedback(project)` emits `conversation_feedback` with `project`, SHA-256 `revision`, and `entries` keyed by saved turn UUID and `user`/`assistant` role. Each rating has independent `saved` and `reaction` -(`neutral`, `liked`, `disliked`) fields. Read errors carry `project` and +(`neutral`, `liked`, `disliked`) fields and optional `excluded: true` +(omission means false). Read errors carry `project` and `error`. The read does not load a model or rewrite saved conversations. `save_message_feedback(request)` accepts exactly `project`, `conversation_id`, `turn_uuid`, `role`, `saved`, `reaction`, `revision`, and -positive `request_id`. On success `message_feedback` returns the same -identifiers plus the new feedback `revision` and complete `entries`. -Failure returns the matching identifiers and `error`, without changing -stored feedback. The core verifies the active project and saved turn, -rejects stale revisions, and blocks writes while an answer is running. -The page ignores late acknowledgements from other projects or requests; -failed saves trigger a feedback reload. UUIDs persist across branches. - -`memory_messages(project, offset)` emits `memory_messages` with `project`, +positive `request_id`. A `null` value for `saved` or `reaction` preserves +that field's current value under the feedback lock. Both feedback mutation +commands require `revision` +to be a 64-character lowercase hexadecimal SHA-256 digest; `null` is not +accepted. The core compares that digest under the feedback file lock. The +engine verifies the active project and blocks writes during an answer; the +core verifies the saved turn. On success `message_feedback` echoes `project`, +`request_id`, `turn_uuid` and `role` (not `conversation_id`), plus the new +`revision` and complete `entries`. Failure returns the echoed identifiers +and `error`. Validation and stale-revision rejection do not change stored +feedback; a diagnostic or acknowledgement failure after publication does +not imply rollback. The page ignores late acknowledgements and reloads +authoritative feedback after an error. UUIDs persist across branches. +A successful update also emits `memory_status`. + +`memory_messages(project, offset=0)` emits `memory_messages` with `project`, `offset`, `total`, `revision`, and up to 100 `messages`. Each message has `turn_uuid`, `role`, `conversation_id`, `conversation_name`, `turn_number`, `timestamp`, `preview`, `saved`, `reaction`, `excluded` and status (`eligible`, @@ -264,21 +299,28 @@ to 100 references, each containing an existing turn UUID4, `role` (`user` or `assistant`), and up to 20 origins (`conversation_id`, one-based `turn_number`). Origins are validated against active registered conversation traces and the saved turn UUID. On success `memory_summaries` returns -`project`, `request_id`, and available `{turn_uuid, role, text}` entries; -on failure it returns `error`. Questions use the saved question text; answers -prefer the complete, editable summary in the trace representation event, -falling back to the compact routing representation for older/branched turns. -The page refreshes on every popover expansion, ignores late/wrong-project -replies, and inserts summaries as plain text. No preview is added to the -saved answer, no summary is recomputed, and the operation is read-only. +`project`, `request_id`, and `summaries`, an array of available +`{turn_uuid, role, text}` entries; on failure it returns `error`. Questions +use the saved question text. Answers prefer the complete, editable trace +representation associated with the saved UUID through an unambiguous +`state.checkpoint.committed` event. An accessible inherited origin can +provide its full representation; otherwise the requested turn's compact +saved representation is used. An explicitly empty full summary is not +replaced by the compact summary. Missing text is omitted. The page refreshes +on every popover expansion, ignores late/wrong-project replies, and inserts +summaries as plain text. The API returns untruncated text; the page limits +question previews to 160 characters including the ellipsis. No preview is +added to the saved answer, no summary is recomputed, and the operation is +read-only. `set_memory_exclusion(request)` accepts exactly `project`, `conversation_id`, `turn_uuid`, `role`, boolean `excluded`, SHA-256 `revision`, and positive -`request_id`. `memory_exclusion` returns matching identifiers and the new -feedback revision/entries on success, or `error` on failure. Save and -reaction are preserved; a stale revision is rejected. A successful update -also triggers `memory_status`, but does not rebuild the derived index until -next sync. Commands reject wrong projects, inactive origins, and concurrent +`request_id`. `memory_exclusion` echoes `project`, `request_id`, `turn_uuid` +and `role` (not `conversation_id`), with the new feedback revision/entries +on success, or `error` on failure. Save and reaction are preserved. The same +required-revision and post-publication error rules as for message feedback +apply. A successful update also triggers `memory_status`; the derived +index is reconciled at the next applicable synchronization. Commands reject wrong projects, inactive origins, and concurrent answer generation. Exclusion affects long-term retrieval only, not ordinary chat history or original checkpoints. @@ -294,10 +336,9 @@ commands never call ordinary source indexing or modify source citations. Completed `answered`, `opened` and `conversation_opened` turn objects may contain `parameters.memory_references`: ordered labels `M1`, `M2`, etc., retrieved turn UUID/role, and active conversation/one-based turn origins. -These are navigational identities only, not stored message previews. Older -records containing a `preview` field remain readable, but that field is -ignored. Each retrieved question or answer has its own clickable line; -questions align right and answers left. On expansion the page requests +These are navigational identities only, not stored message previews. The +reader does not use an incidental `preview` field. Each retrieved question +or answer has its own clickable line; questions align right and answers left. On expansion the page requests current text using `memory_summaries`, rather than copying it into the answer. This text is not the numbered, independently validated documentary `evidence` list. Links to archived origins are disabled. The source- @@ -308,7 +349,7 @@ prompts and suggestions. The editable intent and project behavior settings apply only to subsequent requests. `save_answer_settings` updates the saved project profile and the live chat -settings without asking a question. The Qt bridge accepts either the original +settings without asking a question. The Qt bridge accepts either a settings JSON object or an envelope containing `settings`, `request_id`, and `project`, which it forwards as command fields. Correlated GUI requests must match the active project; the engine never applies a late request to a newly @@ -324,7 +365,7 @@ correlated failure emits `answer_settings_failed` with the same identity, `temperature`, `thinking`, and `max_new_tokens`. If false, the page discards pending edits and requires reopening the project before answering. The GUI ignores stale acknowledgements and discards queued edits after any failure. -Uncorrelated callers retain the prior generic `error` event on failure. An +Uncorrelated callers receive the generic `error` event on failure. An omitted `settings` field reaches the handler as `None` and is rejected, not treated as a request to reset defaults. @@ -334,7 +375,10 @@ ID produces an `error` event rather than selecting a different chat; no model is activated. Omitting the field selects the most recently updated conversation. An `opened` event reports the actual selected ID when activation succeeds. This restores the active chat after Stop or engine -restart; it does not recover unsaved partial model output. +restart; it does not recover unsaved partial model output. `new_conversation` +may reuse an unused empty chat. GUI `reset` always creates a new registered +empty chat and emits `reset` with `archived: null`; it does not call the core +`RAGSession.reset()` or archive the previous conversation. `readiness` applies to **new-project creation**, not `resume`. The page can close Settings and issue `resume` from either saved-project list when the @@ -431,7 +475,8 @@ model state silently inconsistent. ### Indexing-settings failure recovery The frontend shows an in-progress status until `indexing_applied` confirms -that the project has reopened with the new indexing settings. An `error` +that the project has reopened and its indexes have been revalidated with +the new indexing settings; compatible artifacts can be reused. An `error` means the change failed, not that the values were saved. Before changing `profile.ini`, the engine snapshots its complete text. If the operation fails, it compares the actual file with the snapshot and restores any @@ -496,7 +541,7 @@ and echoes the operation, project and request ID. | Operation | Additional fields | Effect | | --- | --- | --- | | `inspect` | None | Read saved and current organization; no repair or write | -| `preview` | `revision`, `sha256`; optional `edits`, `organization`, `adopt_type_defaults`, `role_mapping`, `relation_mapping`, `rebind`, `adopt_detector_versions` | Validate a batch against the displayed exact saved identity; no write | +| `preview` | `revision`, `sha256`; optional `edits`, `organization`, `adopt_type_defaults`, `role_mapping`, `relation_mapping`, `adopt_detector_versions` | Validate a batch against the displayed exact saved identity; no write | | `apply` | `preview_id` | Consume the current server-side preview and atomically apply it through the core | | `initialize` | None | Explicitly initialize missing metadata, never overwrite malformed metadata | | `reconcile` | None | Materialize defaults and reconcile selected paths/discovery under accepted settings | @@ -518,10 +563,12 @@ An example element of its `edits` list is: A preview response includes `inspection`, `proposed_source_organization`, `discovery`, `changed`, and an opaque `preview_id`. Only the most recent successful preview is retained in the engine, bound to the current workspace; -starting another valid preview, attempting an apply, another semantic -mutation, closing/activating the project or refreshing sources invalidates -it. Apply accepts only the identifier, never a client-supplied replacement -manifest. The core revalidates exact bytes, inventory, root binding and +once a request passes the command-envelope and active-project checks and +reaches preview execution, it invalidates the previous preview even if the +new proposal fails. Apply and other accepted semantic mutations also +consume the preview. Closing/activating the project or refreshing sources +invalidates it. Apply accepts only the identifier, never a client-supplied +replacement manifest. The core revalidates exact bytes, inventory, root binding and proposal before committing. Conflicts require a new inspection and preview. `inspection` includes `revision`, `sha256`, canonical `source_organization`, @@ -571,15 +618,15 @@ can accompany an event. | Setup | `readiness` (`backend`, `ready`, `environment_ready`, `unavailable_reason` (empty unless the selected backend is unsupported), `required_models`, `cached_models`, `missing_models`, `replacements`, `can_use_installed`, `install_command`, `install_commands` (backend-to-command map), `projects_folder`, `folder_confirmed`, `terms`, `terms_version`, `terms_accepted`, `copyright` (the Settings copyright line, built from the package authors)); `installed_models_used` (`replacements`, updated model settings); `backend_preference_saved`, `backend_preference_failed` (Qt events: saved `backend` or failed `backend` and `message`); `terms_acceptance_saved` (`version`); `terms_acceptance_failed` (`version`, `reason`, `message`, and `current_version` for outdated terms) | | Installation | `installation_started` (`total`, `backend`, `models`: the missing models in download order); `installation_progress` (`index`, `total`, `model_id`, progress details); `installation_model_complete` (`model_id`, elapsed times); `installation_complete` (`elapsed_seconds`) | | Projects folder (Qt) | `projects_folder` (`folder`: effective folder, `standard`: default without a saved choice, `saved`: saved choice or empty string, `missing`: whether a saved folder is unavailable); `projects_folder_cancelled` (native Browse dialog dismissed); `projects_folder_failed` (`message`: unable to save the chosen folder) | -| Settings/models | `settings` (`profile`, project types, model choices, backend, search depth, `selection_reason_codes`, `thinking_switches`: cached model IDs mapped to `True` when toggling `enable_thinking` changes one sample rendered prompt, `False` when unchanged; omitted when unknown (not verified model reasoning)); `models_applied` (updated levels, models and profile, plus `thinking_switches`); `indexing_applied` (`profile` after the index was rebuilt); `source_cards_applied` (validated settings and card counts), `source_cards_regenerated` (card counts); `answer_settings_saved` (confirmed `temperature`, `thinking`, `max_new_tokens`, plus `request_id` and `project` for correlated saves); `answer_settings_failed` (`request_id`, `project`, `message`, `verified`, plus reconciled settings when verified); `model_download_started`, `model_download_progress`, `model_downloaded` (model ID and download status); `project_behavior` (validated project editor, defaults, revision, and correlated saved or error status); `settings_info` (validated core/tool descriptive catalog), `settings_info_failed` (metadata diagnostic only); `tool_settings` (`tools`, each with `name`, `summary`, `intents`, `settings`, `type_settings`, `per_intent`; after a save also `tool` and `saved` or `error`) | +| Settings/models | `settings` (`profile`, project types, model choices, backend, search depth, `selection_reason_codes`, `thinking_switches`: cached model IDs mapped to `True` when toggling `enable_thinking` changes one sample rendered prompt, `False` when unchanged; omitted when unknown (not verified model reasoning)); `models_applied` (updated levels, models and profile, plus `thinking_switches`); `indexing_applied` (`profile` after successful reopening and index revalidation); `source_cards_applied` (validated settings and card counts), `source_cards_regenerated` (card counts); `answer_settings_saved` (confirmed `temperature`, `thinking`, `max_new_tokens`, plus `request_id` and `project` for correlated saves); `answer_settings_failed` (`request_id`, `project`, `message`, `verified`, plus reconciled settings when verified); `model_download_started`, `model_download_progress`, `model_downloaded` (model ID and download status); `project_behavior` (`behavior` containing validated editors, defaults, identity and revision; correlated save status or error); `settings_info` (validated core/tool descriptive catalog), `settings_info_failed` (metadata diagnostic only); `tool_settings` (`tools`, each with `name`, `summary`, `intents`, `settings`, `type_settings`, `per_intent`; after a save also `tool` and `saved` or `error`) | | Plugins | `plugins` (`request_id`, `operation`, optional `error`, `validation`, `change`, `canceled`, `inventory` with installed, runtime and pending records) | | Versions | `versions` (`request_id`, `project`, `creation_provenance`, `inventory` or `error`) | | Semantic source organization | `source_organization` (correlated operation, inspection, preview or mutation outcome); `source_organization_lifecycle` (project, operation, reconciliation outcome and pending roles) | | Source/project | `projects` (`projects`); `preview` (`roots`); `opened` (`project`, `type_id`, `profile`, `turns`, `source_organization`, workspace and conversation metadata); `question_suggestions` (`project`; `questions`, each with `intent` and `question`: ready-to-send example questions about the project's own sources; and `welcome`: headings about the same sources for the top of an empty chat; sent just before every `opened` of that project and before the `conversation_opened` of each new empty chat, chosen anew each time; an empty list keeps the project type's fixed suggestions or welcome prompts); `folder_changed` (`folder`, `operation`, `paths`, `workspace_files`); `source_changes` (`added`, `changed`, `deleted`, `edited`), sent after a saved project reopens if a file can be imported, updated or removed; `sources_checked` (`sources`; `add` with `name`, `kind`, number of `files` and `state`: `new`, `renamed` for a different source with a taken name, or `existing` when imported from the same path; left-out `files` with `path` and `reason_code`; `skipped_folders` without any file to copy; `changes` of existing sources since they were copied, by group), the answer to `check_sources`, which copies nothing | -| Conversation memory | `conversation_feedback` (project, revision, entries or error); `message_feedback` (request ID, turn UUID/role, revision/entries or error); `memory_messages` (paged authoritative inventory); `memory_summaries` (request-correlated trace text or error); `memory_exclusion` (correlated exclusion update or error); `memory_status` (last indexed counts, enabled, stale feedback); `memory_sync_started`, `memory_synced`, `memory_sync_failed` (project, embedded count or error status) | -| Conversation | `conversation_opened` (`turns`, settings, usage, conversation metadata, `workspace_files`); `conversations` (catalog, active ID, `workspace_files`); `conversation_delete_started` (`conversation_id`); `reset` (`archived`); `conversation_viewed` (`conversation_id`, saved `turns`, or `turns` null when unreadable), sent by Qt for a chat read while an answer runs | +| Conversation memory | `conversation_feedback` (project, revision, entries or error); `message_feedback` (project, request ID, turn UUID/role, revision/entries or error); `memory_messages` (paged authoritative inventory); `memory_summaries` (project, request ID, `summaries` or error); `memory_exclusion` (project, request ID, turn UUID/role, revision/entries or error); `memory_status` (last indexed counts, enabled, stale feedback); `memory_sync_started`, `memory_synced`, `memory_sync_failed` (project, embedded count or error status) | +| Conversation | `conversation_opened` (`turns`, settings, usage, conversation metadata, `workspace_files`); `conversations` (catalog, active ID, `workspace_files`); `conversation_delete_started` (`conversation_id`); `reset` (`archived: null`); `conversation_viewed` (`conversation_id`, saved `turns`, or `turns` null when unreadable), sent by Qt for a chat read while an answer runs | | Answer | `status` (`message`); `answer_phase` (`phase` and phase-specific details); `answer_activity` (`index`, `phase`, `label`, `started_ms`); `answer_delta` (`text`); `usage_progress` (token counts); `answered` (`turn`, `usage`, `workspace_files`); `answer_cancelled` (`usage`); `progress` (core progress record) | -| Evidence | `reference_preview` (`turn_index`, `citation`, `path`, contextual excerpt details); `reference_error` (`turn_index`, `citation`, `message`) | +| Evidence | `reference_preview` (`turn_index`, `citation`, `path`, `page`, `start_line`, `end_line`, `note`, `lines`); `reference_error` (`turn_index`, `citation`, `message`) | | Creation conflict | `workspace_conflict` (`workspace`, `existing_project`, `message`); current session remains active and destination is unchanged | | Diagnostics | `trace_ready` (`trace_path`, `scope`, `conversation_id`); `error` (`message`, optionally `trace_path`, `pending_choice`; `resume_released` for saved-project opening failures); `backend_failed` (`message`) | | Process recovery | `stopped` (optional `removed_projects`: empty creation claims removed; `preserved_projects`: known workspaces left intact); `backend_restarted` (`message`, `exit_code`, `diagnostic`) | @@ -594,7 +641,7 @@ The `assistant_guide` tool may generate and save a source-specific pool when explicitly invoked. Subsequent empty chats reuse it and vary their choices without new model calls. Cache keys include the router model, indexed passages, and whether the project prefers code or documents. Existing -suggestion pools from the previous format are regenerated on demand. +suggestion pools are reused only when their format and fingerprint are valid. Saved project overrides of `welcome_prompts` or `suggestions` take precedence over generated landing content. For mixed-source projects, code projects @@ -607,11 +654,20 @@ project. `answered.turn.parameters.model_summary` is a core-produced model description that includes the active chat model, thinking, `T=`, and the maximum answer-token setting. The frontend displays it -unchanged; for older turns without that field it reconstructs the -line from available saved parameters. +unchanged; if that field is absent, it reconstructs the line from available +saved parameters. + +A reference preview identifies a citation by zero-based `turn_index` and +its saved numeric `citation` within the active turn. The response echoes +these identifiers, the source-relative `path`, nullable one-based `page`, +`start_line`, `end_line`, `note`, and `lines` containing `number`, `text` and +`highlighted`. It attempts to match the saved excerpt in current extracted +source text, with up to five surrounding lines on either side. Plain-text +previews may instead use the saved line range in the current file; +unavailable context and notebook cells use the saved passage. A preview is +not necessarily a historical source snapshot. Invalid citation identities +produce `reference_error` with the two identifiers and `message`. -The engine also emits `startup` and `saved_project`, but the current -`web/app.js` `onEvent()` implementation has no branches for these names. Deleting a conversation moves its JSON into `logs/traces/.deleted/`; the hidden `.conversation_*.json.lock` sidecar stays at its original path. `conversation_delete_started` is sent before the archive operation, so an @@ -711,7 +767,13 @@ constants and are covered by the Qt-free protocol tests. A common successful answer can send `status`, several `answer_phase`, `answer_activity`, and `progress` events, zero or more `answer_delta` and `usage_progress` events, -and a final `answered` event with the saved turn. The exact number of phase +and a final `answered` event with the saved turn. Live `usage_progress` +reports `input_tokens` and `output_tokens` accumulated since the answer +began across the answering, routing and tool model sessions. In contrast, +`opened`, `conversation_opened`, `answered` and `answer_cancelled` report +`usage.chat` and `usage.project` totals from valid committed usage records, +each with input/output tokens and `answers`. Project totals include archived +chats and deduplicate shared branch turns by UUID. The exact number of phase updates and intermediate order **depend on intent, tools, model switches, and retrieval paths**. `answer_delta` reports batched model text; the browser's further character-by-character reveal is a presentation effect. @@ -757,7 +819,7 @@ partial visible stream. After stopping the child, Qt can remove only a directory containing its `.kilin-creating` marker and no other entries, with the marker naming the stopped engine's process ID and recording that it created this folder. - Markers from older versions and pre-existing empty folders are retained. + Unrecognized markers and pre-existing empty folders are retained. Qt never recursively deletes a project or a populated partial workspace based on a PID or queued event. `stopped` reports removed empty claims as `removed_projects` and paths diff --git a/docs/model_management.md b/docs/model_management.md index 2c5553de..0dfbe8f0 100644 --- a/docs/model_management.md +++ b/docs/model_management.md @@ -82,14 +82,17 @@ JSON files. It **does not** read model weights or tokenizer vocabularies, compute hashes, contact the Hub, instantiate a tokenizer, or load a model. It is therefore suitable for repeated readiness checks, but can miss an unusual valid file layout or accept files whose contents are incompatible -or corrupt. The actual backend loader remains responsible for loadability. -The GUI's `cached`/`downloaded` labels mean *locally complete by these -supported-file rules*, not *verified loadable*. This is distinct from the -core's less restrictive `cached_model_snapshot()` lookup. - -`ChatSession` passes `trust_remote_code=False` when loading tokenizers and -models via supported backends. This is a useful precaution, **not** a -security isolation guarantee. A model snapshot may still contain untrusted +or corrupt. The check establishes that at least one cached revision meets +these rules, not that the revision subsequently selected by the backend +will load successfully. The GUI's `cached`/`downloaded` labels mean +*locally complete by these supported-file rules*, not *verified loadable*. +The backend loader remains responsible for loadability. This is distinct +from the core's less restrictive `cached_model_snapshot()` lookup. + +`ChatSession` supplies `trust_remote_code=False` through `tokenizer_config` +to `mlx_lm.load()` for MLX, and explicitly to both tokenizer and causal +language model loaders for PyTorch. These are useful precautions, **not** +a security isolation guarantee. A model snapshot may still contain untrusted or malformed files, and a user may explicitly choose paths outside the standard cache. `revision` may be supplied to identify a model revision; separate code in `retrievals/model_identity.py` records the identity of the @@ -102,14 +105,16 @@ exact default IDs and validation. ### GUI chat-template thinking probe -`gui.model_catalog.thinking_switches()` renders the locally cached chat -model's template once with `enable_thinking=True` and once with +`gui.model_catalog.thinking_switches()` examines cached revisions in +sorted order and uses the first template for which both renders succeed. +It renders the template once with `enable_thinking=True` and once with `enable_thinking=False`, using one short sample prompt and a Jinja sandbox. It does not load a tokenizer or model, run inference, or use a model-name heuristic. A `True` result means that the two rendered prompts differ; a -`False` result means they are identical for this test. Missing or failing -templates give no result (unknown). Neither result verifies a model's -reasoning capability, actual behavior, or runtime compatibility. +`False` result means they are identical for this test. If no template can +be rendered successfully, the result is unknown. Neither result verifies +the behavior of every revision, reasoning capability, or runtime +compatibility. The GUI labels these outcomes *thinking switch detected*, *no template switch detected*, and no label, respectively. The composer's Thinking @@ -143,8 +148,13 @@ and the requested/effective CJK token policy. ### Context, history and streaming A tokenizer template, model context length, thinking tags, EOS behavior and -backend streaming granularity can vary across models. A `max_new_tokens` -cap truncates generation; it does not increase the model's context window. +backend streaming granularity can vary across models. The generation +budget is the explicit per-reply `max_new_tokens`, the session's configured +`max_new_tokens`, or the remaining model context if neither is supplied, +in that order. An explicit cap limits generation but does not increase +the model's context window. KíLín does not automatically reduce an +explicit budget to the remaining context; backend context constraints +still apply. `reset()` clears conversational messages while preserving the loaded model; `restore_history()` replaces messages with validated records; `close()` releases model/tokenizer references and requests backend cache cleanup. @@ -206,8 +216,9 @@ The input trace reports `cjk_blocking_requested`, `cjk_tokens_blocked` `cjk_suppressed_token_count`. These describe the mask, not proof that no CJK character can appear. `ChatSession(block_unrequested_cjk=False)`, or `block_unrequested_cjk = false` in a project's `[generation]` section, -disables suppression. Existing profiles retain explicit values; profiles -without the setting use the packaged default. +disables suppression. The packaged default initializes new profiles; +existing profiles must contain an explicit `block_unrequested_cjk` setting. +An incomplete profile is rejected rather than repaired automatically. ## Embeddings and retrieval @@ -236,11 +247,12 @@ session without changing `profile.ini`. Core callers do not need the GUI to read or update router configuration: use `kilin.read_router_model()` / `kilin.write_router_model()`. -When `router_model` equals the -answering model ID, the same model session can be shared; separate IDs can -increase initial model-loading and memory costs. Router side calls are -kept distinct from committed chat history. `router_reply()` exposes a -controlled auxiliary model call (for example a conversation title). +When `router_model` equals the answering model ID, the answering session +also handles router calls. Otherwise, a separate router session is loaded +lazily when first needed and reused. It can increase model-loading latency +and memory use. Router side calls are kept distinct from committed chat +history. `router_reply()` exposes a controlled auxiliary model call (for +example a conversation title). Switching an active conversation keeps the project indexes and compatible loaded sessions. Switching a chat model has backend-specific constraints; @@ -274,10 +286,15 @@ The project-wide `allow_download` setting is passed to this generator; source-card settings do not grant permission to download additional models. The scientific-paper kind uses the configured input-token budget for the whole prompt, while the adapter enforces the output cap. The -indexing coordinator generates missing cards on project opening or source -refresh and releases the card model before the answering model is loaded -or restored. Default literature retrieval uses `source_first` and cites -original source chunks, never generated card text. +indexing coordinator prepares cards on project opening, releasing any +card-generation model before loading the answering model. During an active +session, reconciliation requiring card inference releases the interactive +answering model and any separate router while the card model is in use. +The answering model, eligible history, generation settings and token +totals are restored afterwards; a separate router is reloaded lazily on +its next use. Reconciliation that requires no card-generation inference +retains the interactive models. Default literature retrieval uses +`source_first` and cites original source chunks, never generated card text. ## Failure and cleanup diff --git a/docs/module_map.md b/docs/module_map.md index c2a4d00a..f1a13204 100644 --- a/docs/module_map.md +++ b/docs/module_map.md @@ -30,13 +30,14 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | [`kilin/_tool_sources.py`](../kilin/_tool_sources.py) | Bind tool source services to a captured generation. | [Plugin API](PLUGIN_API.md) | [Live scope tests](../tests/kilin/test_rag__source_scope.py) | | [`kilin/_source_discovery.py`](../kilin/_source_discovery.py) | Reconcile deterministic relationships under accepted project settings. | [Source manifest](source_manifest.md) | [Discovery tests](../tests/kilin/test__source_discovery.py) | | [`kilin/_source_manifest.py`](../kilin/_source_manifest.py) | Define the immutable semantic source-manifest format and its validator. | [Source manifest](source_manifest.md) | [Manifest tests](../tests/kilin/test_source_manifest.py) | +| [`kilin/_source_ownership.py`](../kilin/_source_ownership.py) | Validate exclusive import or mirror ownership and mirror provenance. | [Project workspaces](project_workspaces.md) | [Ownership tests](../tests/kilin/test_workspace__ownership.py), [Mirror tests](../tests/kilin/test_project__mirror_ownership.py) | | [`kilin/answer_timeline.py`](../kilin/answer_timeline.py) | Record lightweight, persistent timing for an answered conversation turn. | [Answering pipeline](answering_pipeline.md) | [Timeline tests](../tests/kilin/test_answer_timeline.py) | | [`kilin/answering.py`](../kilin/answering.py) | Route questions by intent and select conversation history. | [Answering pipeline](answering_pipeline.md) | [Core tests](../tests/kilin/) | | [`kilin/atomic_writes.py`](../kilin/atomic_writes.py) | Replace or exclusively publish text files atomically. | [Conversation ownership](conversation_ownership.md) | [Core tests](../tests/kilin/) | | [`kilin/chat.py`](../kilin/chat.py) | Manage one loaded language model and its in-memory conversation. | [Model management](model_management.md) | [Core tests](../tests/kilin/) | | [`kilin/chunking.py`](../kilin/chunking.py) | Split source units into token-budgeted retrieval chunks. | [Source pipeline](source_pipeline.md) | [Core tests](../tests/kilin/) | | [`kilin/cli.py`](../kilin/cli.py) | Launch KíLín's optional graphical interface from the command line. | [Architecture](architecture.md) | [Core tests](../tests/kilin/) | -| [`kilin/conversation_format.py`](../kilin/conversation_format.py) | Define the canonical persisted conversation-record structure in KíLín. | [Conversation ownership](conversation_ownership.md) | [Core tests](../tests/kilin/) | +| [`kilin/conversation_format.py`](../kilin/conversation_format.py) | Validate the canonical conversation envelope, lifecycle groups, turns, evidence, timing, and checkpoint consistency without models or GUI imports. | [Conversation ownership](conversation_ownership.md) | [Schema tests](../tests/kilin/test_conversation_format__schema.py) | | [`kilin/conversation_memory/__init__.py`](../kilin/conversation_memory/__init__.py) | Keep project conversation memory distinct from research sources. | [Conversation memory](conversation_memory.md) | [Memory tests](../tests/kilin/conversation_memory/) | | [`kilin/conversation_memory/models.py`](../kilin/conversation_memory/models.py) | Define durable turn identities and conversation feedback values. | [Conversation memory](conversation_memory.md) | [Memory tests](../tests/kilin/conversation_memory/) | | [`kilin/conversation_memory/feedback.py`](../kilin/conversation_memory/feedback.py) | Persist project-local conversation feedback with independent ownership. | [Conversation memory](conversation_memory.md) | [Memory tests](../tests/kilin/conversation_memory/) | @@ -280,7 +281,7 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | Model management | 8 | | Per-tool README | 59 | | Plugin API | 9 | -| Project workspaces | 6 | +| Project workspaces | 7 | | Project-type schema | 1 | | Retrieval pipeline | 35 | | Source manifest | 5 | @@ -292,7 +293,7 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | Trace recording | 1 | | Versioning | 1 | -**Total production Python modules: 244.** +**Total production Python modules: 245.** ## Non-Python resources and UI assets @@ -306,7 +307,7 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | [`kilin/gui/web/`](../kilin/gui/web/) | HTML layout, styling and JavaScript state/events | [GUI architecture](gui_architecture.md), [GUI protocol](gui_protocol.md) | | [`kilin/gui/icons/`](../kilin/gui/icons/) | Packaged native GUI icon assets | [GUI architecture](gui_architecture.md) | | [`kilin/tools/`](../kilin/tools/) | Registered tools' READMEs, `defaults.json`, `settings_info.json` and templates | [Tool packages](tool_packages.md), [Extension interfaces](extension_interfaces.md) | -| [`tutorials/`](../tutorials/) | Eighteen executable numbered learning notebooks and reference SVGs | [Development](development.md) | +| [`tutorials/`](../tutorials/) | Numbered learning notebooks, supporting data and reference diagrams | [Development](development.md) | | [`assets/`](../assets/) | Maintenance, benchmark and notebook-validation assets | [Development](development.md), [Performance](performance.md) | | [`pyproject.toml`](../pyproject.toml) | Python requirements, dependency extras, package data, tooling | [Development](development.md) | | [`tests/`](../tests/) | Unit/integration suites and independent runner | [Development](development.md) | diff --git a/docs/package_defaults.md b/docs/package_defaults.md index e89a1b44..153f575a 100644 --- a/docs/package_defaults.md +++ b/docs/package_defaults.md @@ -101,7 +101,7 @@ have per-project overrides. | `REFERS_BACK_PATTERN` | Regex string | Case-insensitive expression matching pronouns, earlier-turn references, follow-up wording, and elliptical openings. Used by `refers_back()`. | | `COMMON_WORDS` | List of words | Lowercase vocabulary ignored when matching distinctive terms between a new question and stored turn summaries. | -All six numerical settings must be **positive integers** (not booleans). +All numerical settings must be **positive integers** (not booleans). In particular, zero is invalid: slicing with a zero limit could select all turns rather than none. The loader validates the regular expression at import time. `COMMON_WORDS` must be a nonempty JSON array of nonempty lowercase @@ -171,7 +171,7 @@ intentionally different from the new-project profile settings. | `THINKING` | `true` | Fallback thinking-mode flag when a project type does not define `generation.thinking`. Must be a JSON boolean. | | `TEMPERATURE` | `0.0` | Fallback model temperature when a project type does not define `generation.temperature`; must be finite and nonnegative. | | `MAX_NEW_TOKENS` | `8192` | Initial cap for generated answer tokens, not for router decisions. | -| `BLOCK_UNREQUESTED_CJK` | `true` | Initial `generation.block_unrequested_cjk` flag: best-effort suppression of unsolicited CJK script tokens. Original user script use or a positive request can authorize output; evidence and generated instructions cannot. Profiles without the setting use this value. Must be a JSON boolean. See the language policy in `model_management.md`. | +| `BLOCK_UNREQUESTED_CJK` | `true` | Initial `generation.block_unrequested_cjk` flag: best-effort suppression of unsolicited CJK script tokens. Original user script use or a positive request can authorize output; evidence and generated instructions cannot. This value initializes new profiles; existing profiles must declare the flag explicitly. Must be a JSON boolean. See the language policy in `model_management.md`. | When a new project type defines `generation.thinking` or `generation.temperature`, that value takes precedence over the matching diff --git a/docs/performance.md b/docs/performance.md index acc6442a..fab2c742 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -12,9 +12,9 @@ The notebook supports two workflows: 1. **Analyze saved traces (default):** point `EXISTING_TRACES` to explicit conversation or project JSON files and run the notebook. No models or - projects are - opened. Readable spans are extracted from the existing numbered session, - turn, stage, and operation hierarchy. + projects are opened. Recognized operations with valid recorded durations + are extracted from the numbered session, turn, stage, and operation + hierarchy. 2. **Repeat standardized questions (opt-in):** create a separate KíLín project under `sandbox/`, configure its models in `profile.ini`, disable model downloads, and set `RUN_BENCHMARK = True`. Each repetition creates a new @@ -51,7 +51,9 @@ subsequent questions are not independent of earlier answers. per-turn operations. The notebook displays a plot if matplotlib is already installed; it does not install packages. -Each repetition creates and closes a fresh RAG session. It does not reset +Each repetition creates and closes a fresh RAG session. Persisted indexes +and source cards can be reused, and the first repetition may perform +preparation that subsequent repetitions avoid. The notebook does not reset operating-system caches, so the result is **not** a controlled hardware cold start. The notebook sets commonly supported Hugging Face offline flags before loading KíLín; other third-party backends may not honor them. The actual @@ -75,13 +77,13 @@ loading KíLín; other third-party backends may not honor them. The actual The notebook also produces an operation-level listing for initialization and other recorded spans, including `session.ready` and model-load spans. These -preparation operations now live in the shared `project.json`. In a live run, -the notebook selects project operations by the project logger ID for each -repetition so previous repetitions are not counted again. For read-only +preparation operations are recorded in the shared `project.json`. In a live +run, the notebook selects project operations by the project logger ID for +each repetition so previous repetitions are not counted again. For read-only analysis, explicitly include the project trace under a separate label; `read_trace_operations` also accepts an optional `trace_id` filter. The filter -is not part of the exported measurements. Older conversation traces remain -readable without a filter. +is not part of the exported measurements. Omit the filter to inspect all +recognized operations in the selected trace. A saved `ConversationTurn.timeline` also contains ordered, non-overlapping phase-based activities, independently of tracing. This is an end-user @@ -100,9 +102,22 @@ Missing stages mean **not measured/not applicable**, not zero milliseconds. Incomplete or failed spans are not considered completed measurements. The output-token count is trace-dependent: it can be unavailable or derived -from decoded text rather than backend token IDs. A turn generated through -other tools may contain several calls or no LLM generation at all. The -analysis labels these cases rather than assuming one generation per question. +from decoded text rather than actual generated tokens. The lightweight parser +reads the recorded count without retaining its provenance marker, so its +recorded output-token throughput can include estimated counts. A turn +produced through a tool may contain several calls or no LLM generation at +all. The analysis reports the number of completed calls rather than +assuming one generation per question. + +For structured comparisons of independently validated full workspaces, use +[System testing](system_testing.md). Its performance observations include +coverage counts, merge overlapping spans within each timing category and +logger clock domain, and calculate generation and reply throughput only +from measured generated-token counts and positive corresponding durations. +These are separate, non-additive timing categories. The lightweight parser +is intended for exploratory analysis: it does not validate recording +completeness, command alignment, or all referenced artifacts. A successfully +parsed trace is not necessarily a valid system-test reference. Time to first generated token, GUI-rendering latency, and actual hardware cold-start latency are not available from the current trace. They must not diff --git a/docs/project_workspaces.md b/docs/project_workspaces.md index d43de582..c5b14ef7 100644 --- a/docs/project_workspaces.md +++ b/docs/project_workspaces.md @@ -37,12 +37,12 @@ not currently use a templated tool. Users can add Markdown templates or other resources manually under `templates//`. The `outputs/` directory is a general area for project-owned results. Neither `outputs/` nor `templates/` is indexed as a -source directory by default. When a project's source is its own root -(`source = .`), KíLín's RAG scans explicitly exclude these managed -folders and the project-owned metadata files `profile.ini`, `sources.json`, -`source_snapshot.json`, `source_manifest.json` and its lock sidecar; -ordinary external source directories and files -with these names are not globally excluded. +source directory. All project scans are rooted in `sources/`, so managed +folders and project-root metadata are outside the source inventory. User +files or directories inside `sources/` may use these same names. The reserved +`.kilin_versions/` directory is excluded from ordinary scans; only explicitly +recorded retained versions are selected separately. Standalone +`scan_repository()` calls can still scan arbitrary directories. The derived `indexes/index_source_state.json` records the physical source inventory used for index reuse; it is distinct from `sources.json` (managed @@ -55,8 +55,10 @@ accepted defaults and relationships once per completed batch. The optional `on_organization` observer reports new assignments, pending roles, retained versions, proposals and reconciliation errors without changing physical API return types. Use `refresh_source_manifest()` for manually arrived files. -A changed source root must be explicitly rebound; an ordinary refresh cannot -transfer old assignments to a different corpus. +The semantic format is `kilin-source-manifest-v2`, with a canonical +`project:sources` binding. Unsupported formats and bindings are rejected +without modifying the manifest. Moving a complete workspace preserves its +relative binding and accepted assignments. See [Accepted source organization](source_manifest.md) for the schema, editing API, reconciliation, and writer ownership. See [Index persistence](retrieval_pipeline.md#index-persistence-and-identity) @@ -64,21 +66,23 @@ for cache reuse and rebuild behavior. ### Source-directory convention -Every new project keeps its sources in `sources/`, whatever its project type +Every project keeps its sources in `sources/`, whatever its project type and however it is created: `initialize_project()`, `prepare_project_workspace()`, and `prepare_sources_workspace()` all create it. The name is the core constant `kilin.workspace_resources.PROJECT_SOURCES_DIRECTORY`; it is not a setting. Project types decide how sources are read, indexed, and answered, not the -folder name, so a project-type JSON file has no `source_directory` field and -one that still names it is rejected as an unknown setting. - -Existing projects keep the `source` recorded in their `profile.ini`, for -example `documents/` or `repository/` from before this convention. -`open_project()` reads that path unchanged and performs no filesystem writes; -no folder is renamed or moved. A single-source mirror made before the -convention keeps its copy under the original's name, and -`synchronize_project_workspace()` updates it there. +folder name. A project-type JSON file must not contain a `source_directory` +field; unknown settings are rejected. + +The saved `[project] source` value is required and must be exactly `sources`. +The field declares the current layout; it cannot redirect source access. +Project-root sources, `documents`, `repository`, original-name mirrors, +absolute paths, and alternate spellings such as `./sources` are rejected in +both the core and GUI. The physical `sources/` entry must exist as a real +directory: files, symbolic links, and junctions are rejected. Opening and +validation never move, rename, delete, or migrate an unsupported layout. +Private profile writers expose no configurable source-root argument. ### Selected sources and authorized reads @@ -87,9 +91,9 @@ workspace**, not arbitrary files visible on the host filesystem. Imports from external folders are explicit user operations; a name or relative path written inside an imported document never authorizes another import. The current index source state records selected relative paths. The -project's configured source root determines where those names resolve, -while a shared core check rejects paths outside the workspace and -symlinks. A selected file missing from its managed location is reported +project's canonical `sources/` directory determines where those names +resolve, while a shared core check rejects alternate roots, traversal, +symbolic links, and junctions. A selected file missing from its managed location is reported unavailable, not substituted from the workspace root or original folder. For example, `.bib` and `.bbl` are ordinary selectable literature sources: @@ -115,7 +119,7 @@ folder.** This rule is enforced in the core, independently of the GUI. | `kilin.open_project(path)` | Read and validate a saved profile and source path without changing files or creating missing folders. | | `kilin.add_project_sources(path, source_paths, ...)` | Explicit cumulative import using the saved profile. Preserve existing snapshots unless `replace_existing=True` is requested. | | `kilin.prepare_project_workspace(source, type_id, parent)` | Create a fresh single-source mirror in `sources/` and record `source_snapshot.json`. | -| `kilin.synchronize_project_workspace(source, path)` | Explicitly synchronize that saved mirror. May replace local snapshot edits or remove copies deleted from the original. | +| `kilin.synchronize_project_workspace(source, path)` | Synchronize only recorded mirror paths. Repair tracked edits or missing copies, remove tracked deletions, and preserve untracked local files. | | `kilin.project.configure_project(path, settings)` | Explicitly validate and update the saved profile. | | `kilin.project.delete_project(path)` | Move a closed project into the `.deleted/` folder beside it, keeping its files. A name already there gets `_2`, `_3`, ... | @@ -129,10 +133,9 @@ subclass of `kilin.WorkspaceOccupiedError`. Other nonempty destinations, partial initialization, linked roots, and in-progress creation are rejected. Even malformed `profile.ini` entries count as an existing project. Creating inside another project's directory is also rejected. There is no creation -option that overrides these safeguards. A single-source mirror also rejects -source basenames that would alias managed state, such as `logs`, `indexes`, -`profile.ini`, or the creation marker. Import such folders with the cumulative -`sources/` API instead; their basenames are safe beneath that managed root. +option that overrides these safeguards. Source basenames do not select a +project source root: single-folder mirrors always copy into `sources/`, +and cumulative imports allocate entries beneath that directory. For automatic workspace naming, omit `workspace_directory` and supply `workspace_root`. With sources, the core derives a base name from the first @@ -178,22 +181,55 @@ Creation installs the normal profile, directories, and selected resources. `sources.json` is written when sources are first imported. For each copied file it records the copy's size and modification time at import (`stamps`), so a later change to the original or to the copy can be told -apart; manifests written before stamps existed remain valid. Later imports +apart. Later imports respect the saved profile and never modify it implicitly. Existing source folders are copied into a new destination rather than adopted in place. -Previously saved root-as-source or external-source profiles remain readable; -opening them does not reinterpret their source layout. Model loading is a -separate session operation. +Root-as-source, external-source, and other noncanonical profiles are rejected +without changing their files or source layout. Model loading is a separate +session operation. + +### Managed import ownership format -### Callers updating existing projects +`sources.json` uses integer generation **2**, declared by +`kilin.workspace.SOURCE_MANIFEST_VERSION`. Its top-level object contains +exactly `version` and `sources`; `sources` is a list of records with these +fields: -Callers that use preparation as an implicit reopen must choose an -operation explicitly. Replace repeated cumulative preparation with -`add_project_sources(existing_path, sources)`, and repeated mirror preparation -with `synchronize_project_workspace(original, existing_path)`. Use -`open_project(existing_path)` for read-only opening. No compatibility switch -reintroduces implicit reuse. Existing project files and schemas need no -migration for this creation-safety change. +| Field | Requirement | Meaning | +| --- | --- | --- | +| `original` | Required nonempty string | Recorded path selected for import. The original need not still exist. | +| `name` | Required safe, unique entry name | Destination inside `sources/`; `.kilin_versions` is reserved. | +| `kind` | Required `"file"` or `"folder"` | Source identity captured at import, never inferred from current disk contents. | +| `files` | Required list | Unique normalized relative filenames currently tracked. An empty inventory is valid. | +| `stamps` | Required mapping | Known import-time `size` and `mtime_ns`, both nonnegative integers, for tracked files only. | +| `versions` | Optional list | Retained versions with their original relative filename, archive path, and SHA-256 digest. | + +Each source has one destination and each destination has one owner. File +records may track only their original basename. Inventories reject traversal, +duplicate paths, and file/directory conflicts. Retained versions must stay +inside their owner's `.kilin_versions//` namespace. Unexpected fields +are rejected at both the manifest and record levels. + +Source names, selected filenames, and version paths use the same canonical +path rules as semantic source manifests. Ambiguous case or Unicode spellings, +including directory prefixes, are rejected across effective managed paths. +Names with control characters, colons, trailing spaces or dots, and other +noncanonical components are rejected. Imports and synchronization validate +selected destinations against recorded ownership and existing local names +before starting batch diagnostics or copying files. Selecting a valid subset +of a folder is allowed; excluded originals do not gain workspace ownership. + +Empty or partial `stamps` mappings are valid after a copy succeeded but its +metadata could not be recorded. Such files have an unknown comparison +baseline: preserving or inspecting a local copy does not invent a stamp. +Only copying the file establishes a new baseline. Missing originals, missing +workspace copies, and retained versions without an active copy remain valid +ownership states. + +Unsupported versions and incomplete records are rejected before +ownership-dependent operations change files. Ownership is not repaired by +filesystem inference or automatic conversion. This format is independent of +the physical repository snapshot and semantic `source_manifest.json` formats. ## Initial project creation @@ -220,21 +256,24 @@ Brainstorming (Creative) (`creative_brainstorming`), Brainstorming brainstorming types share the same source layout but differ in whether ordinary ideation retrieves project evidence by default. -With the current bundled project types: +The bundled project types initially install these resources: | Type | `templates/` contents after new project creation | | --- | --- | | `code` | Empty directory, ready for user templates | | `literature` | `generate_paper_summary/`: `research_briefing.md`, `popular_science_summary.md`, `technical_summary.md`, `experimental_protocol.md`, `README.md`; `project_summary/`: `project_overview.md`, `literature_table.md`, `README.md` | -| `writing` | The same two namespaces and their resources | - -These files are selected because the literature intents configure -`generate_paper_summary` with those template identifiers, and because the -`templated_report` intent (`template: "choose"`, in both types) uses any -template and installs every bundled one with `README.md`, the guide to the -format, and the `templated_project_report` intent installs the bundled -project report templates of `project_summary`; the project initializer -does not hard-code their names. +| `reviewing` | Empty directory, ready for user templates | +| `writing` | The same two namespaces and their resources as `literature` | +| `grounded_brainstorming` | Empty directory, ready for user templates | +| `creative_brainstorming` | Empty directory, ready for user templates | + +The resource plan is determined by the registered tools and settings of +configured intents. In Literature and Writing, `templated_report` selects +any individual-paper template (`template: "choose"`), and +`templated_project_report` selects whole-project formats. Their resource +plans include all bundled templates for the respective tools and each +namespace's `README.md` format guide. The project initializer does not +hard-code these names or select resources by project type. ## Existing projects and user ownership @@ -245,22 +284,23 @@ of implicitly reopening it. As a result: - Edits and new user-created templates remain untouched on reopening. - Templates deliberately deleted by a user stay deleted. -- Missing folders remain missing on read-only opening. Explicitly call - `kilin.project_layout.ensure_project_folders(root)` to restore empty core - folders, and `install_project_resources()` to repair selected resources. +- Missing derived or resource folders remain missing on read-only opening. + Explicitly call `kilin.project_layout.ensure_project_folders(root)` to + restore empty core folders, and `install_project_resources()` to repair + selected resources. A missing `sources/` directory is an invalid project, + not a derived-cache repair case. - Existing, unrelated template files are never removed simply because they are not mentioned by the current project type. - A missing selected template causes the report tool to report an error rather than silently fall back to the globally shipped version. -For workspaces created before tool-specific template namespaces, back up the -project and move the individual-document formats into -`templates/generate_paper_summary/` and the whole-project formats into -`templates/project_summary/`. Use the intended tool and report scope to -classify custom files. Keep customized guides and resolve name conflicts -manually. Opening an old workspace never moves, deletes, or reinstalls its -flat files; report discovery no longer searches the flat directory. The -project's saved creation provenance is not changed by this reorganization. +Report discovery searches the appropriate tool namespace: individual-paper +formats belong in `templates/generate_paper_summary/`, and whole-project +formats in `templates/project_summary/`. Files directly under `templates/` +are not discovered as report templates. Opening a workspace preserves +unrelated files and does not move or reinstall templates. If organizing +custom files manually, back up the project, retain customized guides and +resolve name conflicts before moving files. An explicit, **opt-in** restoration is possible from the Python API: @@ -274,21 +314,25 @@ install_project_resources(project.root, plan_project_layout(project.profile.type ``` This installs only missing packaged resources; it never overwrites existing -files. Tool authors can offer more specific repair or reset commands later. +files. -The core does not move or delete unrelated folders or generated files -implicitly. An existing `target/` directory is left untouched; `outputs/` -is created independently. No legacy migration is performed. +The core creates `outputs/` independently and does not move or delete +unrelated folders or generated files implicitly. ## `profile.ini` and the Settings panel -`profile.ini` is the project's authoritative settings layer (see -[Configuration](configuration.md)). It keeps every project setting from -the day the project was made, so a later KíLín release with new defaults -does not change an existing project. It can also be edited by hand while -the project is closed: reopening the project reads it again, an invalid -value stops the project from opening with a message naming it, and a -changed indexing value rebuilds the index. +`profile.ini` owns the saved model, generation, indexing, retrieval and +shared tool settings. Creation defaults do not overwrite explicitly saved +profile values. The optional `project_behavior.json` owns project-local +behavior overrides; inherited behavior is resolved against the registered +project type. Source organization, per-source card overrides and conversation +feedback have separate owners (`source_manifest.json`, +`source_card_sources.json` and `memory/`, respectively). See +[Configuration](configuration.md) for precedence and ownership. + +The profile can be edited by hand while the project is closed. Reopening +reads and validates it; invalid settings prevent opening, and changes to +indexing settings invalidate the affected derived indexes. | Section and keys | Settings place | Saved from the GUI | | --- | --- | --- | @@ -376,8 +420,8 @@ content, and such errors must be reported to the user. When a source snapshot is deleted through `kilin.remove_workspace_sources(project, paths)`, only files within a managed `sources/` folder can be removed. Original source paths are not -modified, and `sources.json` is updated to reflect removed entries. Projects -with external or root-as-source locations cannot use that deletion API. +modified, and `sources.json` is updated to reflect removed entries. The API +revalidates the current profile and canonical source directory before removal. Index refreshing is a separate core operation. `kilin.preview_project_sources(project, paths)` previews cumulative imports @@ -402,9 +446,10 @@ is a fast heuristic, not proof of identical contents. Previously tracked paths that vanish are `deleted`, including files renamed or moved to another path. Files at the new path may independently be reported as `added`; KíLín does not infer a relocation or transfer tracking identity between paths. -Files without stamps, missing workspace copies, and symlinks are skipped. -Older pre-release manifests without copy stamps remain readable, but -their existing snapshots do not automatically acquire change tracking. +Files without a known stamp, missing workspace copies, and symlinks are +skipped. A valid partial `stamps` mapping differs from an absent required +mapping: only the partial mapping is accepted. Reimporting while preserving +local copies retains unknown stamps until an explicit copy succeeds. An original directory that is unavailable may look deleted, so a caller should confirm bulk deletions. Unreadable source paths raise errors rather than silently triggering deletion. Independently edited workspace copies @@ -475,8 +520,67 @@ after accepted changes, callers should invoke `RAGSession.refresh_sources(project)` once, or reopen a RAG session to trigger incremental indexing. The GUI refreshes once after applying a batch. This API is specific to managed multi-source workspaces; -`kilin.synchronize_project_workspace()` is an older single-source -mirroring API with different semantics. +`kilin.synchronize_project_workspace()` is the single-source mirroring +API described below. + +### Single-source mirror ownership and synchronization + +A workspace uses at most one external-source ownership format: + +| Ownership metadata | Meaning | +| --- | --- | +| Neither file | Empty or manually populated project with no recorded external owner. | +| `sources.json` only | Cumulative managed imports. | +| `source_snapshot.json` only | A mirror of one original folder. | +| Both files | Conflicting ownership; source operations are rejected. | + +A present malformed file, symlink, junction, or non-file entry is an error, +not missing ownership. The semantic `source_manifest.json` is independent of +these files and can describe sources in any of the valid ownership modes. +Neither an import nor a mirror operation converts the other ownership mode. +Cumulative import preview, import, and synchronization reject a valid mirror; +read-only selection and version queries validate its metadata without creating +import records. Explicit local source deletion remains available and retains +mirror provenance, allowing a later mirror synchronization to restore a +tracked copy. Removing manual files without an ownership record does not +create `sources.json`. + +Ownership validation precedes copying, deletion, trace creation, semantic +writer locks, and RAG session preparation. Rejected ownership changes leave +source files and saved state unchanged. Read-only access to the saved project +profile and accepted semantic record remains available for inspection. + +`prepare_project_workspace()` creates a fresh mirror and records the absolute +original directory plus selected file sizes and SHA-256 hashes. An empty +selection still records that owner. `synchronize_project_workspace()` requires +valid saved mirror provenance matching the explicitly supplied original. +Missing, corrupt, incomplete, or conflicting provenance is rejected without +writing, renaming, deleting, or reconstructing the source tree. + +Synchronization scans and validates the whole planned batch before applying +it. It repairs edited or missing **tracked** copies, deletes tracked copies +no longer selected in the original, and imports newly selected originals +only into unoccupied paths. Any new original colliding with an untracked +local file is rejected before the first copy or deletion. Linked parents +are rejected. Original file/directory transitions are supported only when +planned tracked deletions own every blocking entry; untracked descendants, +including empty directories, block replacement. A tracked leaf symlink can +be replaced without reading or modifying its external target. + +Untracked local files, links, unrelated empty directories, and retained-version +contents are preserved. Cleanup attempts only the empty parents of removed +tracked files. There is no recursive removal or reconstruction of `sources/`. +Files are copied through unique temporary siblings and checked against the +scanned hash; newly owned names are published exclusively without overwriting +a concurrent local file. Unchanged tracked copies retain their inode. + +The batch is not one filesystem transaction. If a later copy or deletion +fails, earlier completed changes remain and their actual inventory is saved +atomically so a later synchronization can continue. A provenance write error +is reported, with the original physical error preserved when both fail; +completed physical changes are never falsely described as rolled back. +Original folders are never modified. As with other workspace operations, +these checks do not provide isolation against arbitrary concurrent writers. ## Project-owned outputs and templates @@ -494,7 +598,10 @@ The following GUI-independent core functions manage user-owned files: inside **either** `outputs/` or `templates/`, but cannot remove the managed folders themselves. - `kilin.list_project_files(project)` provides a filesystem inventory, - including empty folders, without importing the GUI. + including empty folders, without importing the GUI. It revalidates the + captured source directory and saved profile, and prunes symbolic links + and junctions before enumerating their contents. An unavailable project + type does not prevent listing, and missing derived folders remain missing. All paths are checked for containment and symlink traversal. These operations do not require a model or reindexing, and the GUI only delegates @@ -535,7 +642,7 @@ creation never guesses that a marker is stale or silently clears the folder. When the GUI stops its engine, it may remove an otherwise empty directory containing only a marker matching that stopped engine's process ID and recording that the attempt created the directory. Pre-existing empty folders -and legacy markers without this ownership information are retained. The GUI +and markers without this ownership information are retained. The GUI never recursively deletes a project or its contents. A published project is preserved even if the GUI has not yet processed its `opened` event. Incomplete files may therefore require explicit inspection and removal by the user. @@ -560,11 +667,10 @@ with a trailing `/` rather than invented by the frontend. Creation, read-only opening, explicit updates and generated output publication are distinct operations because they protect different user-owned state. -A layout change must account for both newly initialized projects and saved -profiles with older source locations; installing a new default is not an -implicit repair or migration. +The same layout validation applies to new and saved projects. Unsupported +source locations are rejected without an implicit repair or migration. -Review `project._preparing_project`, `project_transaction.py`, +Review `project._preparing_project`, `_project_creation.py`, `project_layout.py`, `workspace_resources.py` and the affected `workspace.py` operation together. Changes to sources must also update provenance, source selection and [index refresh](retrieval_pipeline.md#incremental-updates). diff --git a/docs/release.md b/docs/release.md index 4d231447..3017678a 100644 --- a/docs/release.md +++ b/docs/release.md @@ -49,14 +49,22 @@ On an Apple Silicon Mac with Xcode command-line tools, `uv`, and Python python -m pytest -q python -m tests KILIN_SKIP_FINDER_LAYOUT=1 bash setup/macos/build_app.sh --wheel -bash tests/setup/check_macos_app.sh +bash tests/setup/check_macos_app.sh --wheel ``` The checker examines the generated application and disk image: bundled `uv` architecture, expanded launcher, Info.plist, ad-hoc code signature, DMG integrity, and the application and Applications shortcut in the -mounted image. It does **not** install Python packages, exercise the -real GUI, or establish Gatekeeper acceptance. +mounted image. It verifies both exact bundle version strings against +`pyproject.toml`, checks the expanded launcher installation source, and +compares the mounted application's plist, launcher and uv with the build. +It verifies the ad-hoc code signature of both the built and mounted app. +For a bundled wheel it verifies the filename, internal name/version metadata +and the SHA-256 checksum from the launcher in both copies. Use `--wheel` +for a checkout-wheel build to reject a missing wheel; omit it to check a +PyPI-pinned build. The checker requires Python 3.12 or later. It does +**not** install Python packages, exercise the real GUI, or establish +Gatekeeper acceptance. The `.github/workflows/macos_app.yml` workflow performs this native build and inspection on an Apple Silicon runner, plus the deterministic @@ -105,9 +113,11 @@ Before sharing with trusted testers: 5. Verify MLX and PyTorch repair guidance in the app-managed runtime, including when `pip` is unavailable. Test an explicit model download and a basic model answer when hardware and weights are available. -6. Upgrade from an earlier build; check activation of the new runtime, - preservation of the previous one, interrupted installation recovery, - and that failed updates do not silently run an old release. +6. Upgrade from an earlier build using the versioned runtime layout; check + activation of the new runtime, preservation of the previous one, + interrupted installation recovery, and that failed updates do not + silently run an old release. Verify that an obsolete `runtime/app` + installation is left untouched and never selected. 7. Stop and reopen a saved project; verify conversations, checkpoints, traces, and project files survive the upgrade. @@ -138,7 +148,15 @@ The installer holds only uv, an icon and the optional wheel: CPU build otherwise (PyPI alone has only the CPU build on Windows). A failure stops Setup with a message and the log `%LOCALAPPDATA%\kilin\runtime\install.log`; an earlier version is - untouched. After an update, other versions' runtimes are removed. + untouched. During a same-version reinstall, Setup first renames the old + runtime to `.rollback` and installs the replacement at the + original path (Python virtual environments contain absolute paths). + On a failed installation or cancellation before Setup finishes installing + its files, the previous runtime is restored at that path. After a + successful installation, Setup renames the backup to `.retired` + before cleanup. If the rename fails, the intact backup is kept instead. + Other versions' runtimes and retired directories are removed when + possible; intact rollback directories are not recursively deleted. - There is no licence page. As on macOS, the welcome dialog shows the terms of use on first launch and records their acceptance. - The Start-menu shortcut opens `kilin-gui.exe` without a console window. @@ -152,6 +170,19 @@ If KíLín is already installed, Setup first compares versions and offers to upgrade (a newer installer), reinstall (the same version, for example to repair it) or install the older version, or to remove KíLín. +Close KíLín and any other process using its runtime before installing or +repairing it. A named mutex serializes instances of the updated Setup +within the same Windows session. +If Windows prevents moving the existing runtime, Setup stops without +removing it. If Setup is forcibly terminated during a reinstall, or a +locked file prevents rollback, the intact `.rollback` directory +is retained; rerun the same-version installer after closing the application +to recover it. Do not delete that directory manually. The shortcut may be +unusable until recovery finishes. A complete replacement requires room for +both runtimes during the installation. Failure or cancellation can still +leave Python downloads or a partial cache, but does not intentionally +modify projects, preferences or user plugins. + While uv installs, a progress page shows the percentage, the size downloaded and an estimate of the time left, above a list of the large downloads, such as PyTorch, each marked downloading or downloaded, newest @@ -172,12 +203,17 @@ separate decision like Apple notarization. The `.github/workflows/windows_app.yml` workflow builds the installer with a checkout wheel on a Windows runner, installs it silently, checks the -runtime, the shortcut and the repair variables, and uninstalls it. Every -run uploads the unsigned installer as an Actions artifact. Release-tag +runtime using its own Python in isolated mode (`-I`), verifies the import +origin and exact application/distribution/manifest version agreement, +imports the GUI and backend dependencies, checks the shortcut and repair +variables, forces a same-version reinstall to fail without network access +or cached packages, verifies rollback after both ordinary failure and a +simulated interrupted reinstall, then reinstalls successfully and uninstalls. +Every run uploads the unsigned installer as an Actions artifact. Release-tag runs additionally use this validated artifact in the GitHub Release. Before relying on a build, also test on a real Windows PC: first install, -update over an earlier version, an NVIDIA computer, a model download and -a basic answer. +update over an earlier version, a failed same-version reinstall and +recovery, an NVIDIA computer, a model download and a basic answer. ## Automatic native release assets @@ -189,8 +225,16 @@ It packages `KiLin--macos-arm64.dmg`, Beta (`b`) and release-candidate (`rc`) tags create GitHub prereleases; stable tags create ordinary releases. The publisher creates the GitHub Release only after **both** platform jobs succeed, or attaches to a -pre-existing release without replacing any asset. Existing assets must -be dealt with explicitly; reruns do not silently replace binaries. +pre-existing release without replacing any asset. The tag validator and +both native builders enforce the canonical version syntax in the +[versioning policy](versioning.md#application-version). Before uploading, +the publisher checks that the tag still resolves to the validated source +commit, the existing release (if any) has the matching prerelease status, +and none of the three intended asset names is already present. API errors +stop publication rather than being treated as absence. Existing assets must +be dealt with explicitly; reruns do not silently replace binaries. The +preflight is not an atomic transaction with GitHub: do not concurrently +change a tag, release, or its assets. The publishing job alone receives `contents: write` permission. Native build/test jobs run read-only and upload temporary Actions artifacts. @@ -203,6 +247,9 @@ as a draft, attaching assets does not automatically publish that draft. Published immutable releases cannot accept further assets; create the tag before publishing a release manually. See the [public prerelease procedure](development.md#public-prerelease-sequence). +Verify both native jobs, the published native asset names and checksums +before explicitly approving and separately publishing the reviewed wheel +and source distribution to PyPI. ## Native signing and notarization (deferred) diff --git a/docs/retrieval_pipeline.md b/docs/retrieval_pipeline.md index 235750fa..3df0ab76 100644 --- a/docs/retrieval_pipeline.md +++ b/docs/retrieval_pipeline.md @@ -39,25 +39,24 @@ JavaScript, and R code passages are embedded and lexically indexed with file paths in front and, for Python, the first line of the module docstring (`_retrieval_text` in `rag.py`). This helps find functions by module purpose even when their names and bodies use different words. Evidence, citations, -and the answering model retain the original passage text. Prose citations -such as `[source 3]` are normalized to `[3]` in both streamed and saved -answers, without rewriting inline or fenced Markdown code examples. +and the answering model retain the original passage text. The search-text format is recorded in index settings (`retrieval_text`); -changing that format rebuilds saved indexes. The `code_path_languages` -marker additionally -invalidates old JavaScript/R text indexes. - -In project types with the `document_headers` capability (the packaged -`literature` type), each document passage is indexed after a short header: -the document's title, its first author and file name, and the section -heading and page it comes from -(`retrievals/document_headers.py`). Titles and first authors come from -PDF metadata when plausible, from the first `#` -heading of a Markdown file, or else from the file name; section headings -are recognized by name ("Methods", "Data availability") or numbering -("3.1. Software architecture"). A methods paragraph is then found for a -question about its paper even when it never repeats the paper's name. The -header format is recorded in the index settings (`document_headers`). +index reuse requires compatible settings, including the applicable +`code_path_languages` marker for code-path indexing. + +In project types with the `document_headers` capability enabled, eligible +document passages are indexed after a short header: the document title, +first author when known, file name, and available section and page +information (`retrievals/document_headers.py`). PDF and Word metadata +provide titles and first-author surnames when plausible. Markdown and Word +passages can supply a suitable level-one heading when no metadata title is +available; LaTeX uses +its `\title` declaration. The fallback title is the filename stem. +Section headings come from the extracted sections or recognized names +("Methods", "Data availability") and numbering ("3.1. Software architecture"). +This helps find a methods paragraph for a question about its paper even +when the passage never repeats the paper's name. The header format is +recorded in the index settings (`document_headers`). ## Lexical channel @@ -140,15 +139,16 @@ Related functions compete for `RETRIEVAL.RELATED_PASSAGES_MAX` passages, using the **same validated cosine scores** already computed by semantic search. Non-unit embeddings retain the ordinary cosine contract. No extra query embedding, vector conversion, or rescoring is performed for expansion. -The current loop backend already sorts all chunks; RAG retains that ranking -and slices each channel's intended depth before fusion, so reuse does not -silently deepen the fused semantic channel. Scores live only for one query. - -Explicit files and named functions are included in full. Every direct -neighbor requested by a relationship question contributes context outside -the shared passage budget, but each long related function is still limited -to `RELATED_CHUNKS_MAX` chunks (currently two). Those chunks prioritize call -sites and question terms. Zero means unlimited for either passage cap; +RAG retains the complete eligible semantic ranking for expansion and uses +the configured channel depth for ordinary fusion. Reusing the scores does +not by itself deepen the fused semantic channel. Scores are query-local. + +Within the authorized membership, explicit code files and named functions +are included in full by context expansion, subject to the final evidence +limits. Every eligible direct neighbor requested by a relationship +question contributes context outside the shared passage budget, but each +long related function is still limited to `RELATED_CHUNKS_MAX` chunks +(currently two). Those chunks prioritize call sites and question terms. Zero means unlimited for either passage cap; these settings are not a promise that every related function is included in full. Alternatives follow supported related passages in the shared budget. @@ -162,20 +162,25 @@ because they use a question's words more often. ### Requested targets and broader evidence -A named-file scope is a **focus**, not a hard exclusion of other files. -The requested file's best passages seed retrieval; expansion can still find -helpers, tests, documentation, and plausible alternatives elsewhere. The -full semantic ranking is reused when ranking a focused file, preserving -passages outside the original top results without another embedding call. +Retrieval resolves an explicit source scope before ranking. A `project` +scope considers eligible project-wide members; a `preferred` scope +prioritizes explicit operands while permitting other eligible candidates; +a `restricted` scope admits only the authorized members. Semantic, lexical, +card and graph ranking and subsequent context expansion must stay within +that membership. Related helpers, tests, documentation and alternatives +can contribute only when admitted by the resolved view. The complete +eligible semantic ranking can be reused without another embedding call. +See [Source views and operation snapshots](#source-views-and-operation-snapshots) +for the membership and validation contracts. Final RAG evidence prioritizes requested targets, retains the existing ordering within each relevance group, and labels `context_role` as `direct`, `related`, or `alternative`. Direct targets win over other labels. The prompt instructs the model to attribute alternatives to their actual paths and symbols, not to equate differently qualified names without evidence. The -optional label is persisted with evidence and included in traces; older -records without it load as unclassified (`None`). When evidence is reused -from an earlier turn, its old direct-target label becomes related; an +optional label is persisted with evidence and included in traces; an +absent label means unclassified (`None`). When evidence is reused +from an earlier turn, its direct-target label becomes related; an alternative warning is retained. Source text is unchanged. ## Hybrid combination: ranks rather than scores @@ -222,10 +227,9 @@ A kind's deterministic `precheck` may rule out clearly ineligible sources; positive results are only candidates, with full eligibility deferred to the kind's generation/verification logic. Project JSON never imports kind code. -The generic contracts, independent index, dedicated generation adapter, -scientific-paper kind and indexing coordinator are implemented. The -packaged literature intents use four-channel `source_first` retrieval. -No migration layer for the removed paper-card cache is provided. +The registered scientific-paper kind uses the independent source-card +index and dedicated generation adapter. Bundled Literature source-first +intents can use all four ranking channels. ### Independent source-card index @@ -261,8 +265,7 @@ transaction; concurrent writers still need higher-level coordination. prepared vectors. A caller supplies a query embedding; it does not construct one, start a model, or add card text to the evidence presented to an answer. The default `source_first` strategy incorporates the card-vector search -as a fourth source-ranking channel. The persistence format does not -read the older `paper_cards.json` file. +as a fourth source-ranking channel. ### Dedicated generation adapter @@ -283,11 +286,11 @@ runs card generation. ### Scientific-paper cards -`source_cards/kinds/scientific_paper.py` implements the first trusted kind, -`scientific_paper` (schema version 1, validation version 1). It retains the -original paper-card summary fields: `abstract`, `aim`, `methods`, `data`, -`findings`, and `limitations`. Bibliographic metadata additionally records -`title`, `authors`, `year`, `venue`, and `identifiers` when available. Each +`source_cards/kinds/scientific_paper.py` implements the trusted kind +`scientific_paper` (schema version 1, validation version 1). Its substantive +summary fields are `abstract`, `aim`, `methods`, `data`, `findings`, and +`limitations`. Bibliographic metadata records `title`, `authors`, `year`, +`venue`, and `identifiers` when available. Each nonempty substantive statement must cite original chunk IDs; the generated card is never direct evidence for an answer. @@ -296,8 +299,9 @@ methods papers and scientific-software papers. File extensions alone do not establish eligibility. A deterministic precheck rejects bibliography containers (`.bib` and `.bbl`) and sources with no extracted chunks or usable text. Bibliography containers are excluded before card-generation planning; -previously cached paper cards for them are not reused or ranked. For the remaining candidates, **one** -dedicated-model call jointly decides applicability and produces the card. +cards for them are not reused or ranked. For the remaining candidates, +**one** dedicated-model call jointly decides applicability and produces +the card. An explicit non-paper verdict yields `not_applicable`; malformed, ambiguous, truncated or unsupported responses yield `failed`, not a speculative card. No separate eligibility or provenance model call is made. Non-paper sources @@ -317,10 +321,8 @@ statement is semantically entailed by that chunk. The indexing coordinator invokes this generator when scientific-paper cards need to be built; generated text never replaces source passages as answer evidence. -The registry and generic persistence also allow future, independently -validated kinds for grant proposals, patents, CVs, slide decks, technical -manuals, policy documents, and other sources when needed. These kinds -are **not** implemented or inferred from file extensions. +The generic registry and persistence support independently validated +registered kinds; a file extension alone never selects a content kind. ## Automatic source-card indexing @@ -329,10 +331,10 @@ After normal extraction, chunking and semantic/lexical/graph indexing, `RAGSession` calls `reconcile_source_cards()` in `retrievals/source_cards/indexing.py` on both project opening and `refresh_sources()`. The coordinator checks source hashes, card-kind schema -and validation versions, and existing records before calling the separate -Qwen3-8B generation model. It generates only missing or outdated cards, -then embeds only missing or stale card search texts with the current -embedding session. The card-generation session is released before loading +and validation versions, and existing records before calling the configured +source-card generation model (whose packaged default is Qwen3-8B). +It generates only missing or outdated cards, then embeds only missing or +stale card search texts with the current embedding session. The card-generation session is released before loading the interactive answering model on initial project opening. A failed or ineligible card does not prevent normal passage search. @@ -345,9 +347,7 @@ generation model, while vector groups are rebuilt if the embedding model or search-text projection changes. A failed generation attempt can be retried on a source, schema, model or generation-settings change; a cached `not_applicable` result is reused until its source or kind -validation changes. The prerelease implementation does not migrate or read -`paper_cards.json`; the inactive standalone implementation has been -removed and its relevant tests cover the new source-card pipeline. +validation changes. Project-type `capabilities.source_cards` defines default `enabled`, `kind` and `automatic` values. Project-level overrides are saved in @@ -361,8 +361,7 @@ cards can be searched, but missing and outdated cards are not generated. See [Configuration](configuration.md#source-card-indexing-policy). For each valid `scientific_paper` card, the kind projects three search -texts (abstract/aim, methods/data, findings/limitations), retaining -the three-group representation used by document retrieval. The default +texts (abstract/aim, methods/data, findings/limitations). The default `source_first` strategy uses these vectors as one source-ranking channel. Card text is never answer evidence: answers cite original source chunks. @@ -383,8 +382,8 @@ documents ("the hinton paper", "the architecture document"), "notebook" for notebooks, "module" or "script" for other files ("the chat module"). "File" is not enough: "the configuration file" in a question, or in text pasted into it, does not name `configuration.md`, and "the config file" does not -name `config.py`. A named file limits the search to that file, so a weak -match would silently leave the rest of the project out. +name `config.py`. Explicit names affect final scope resolution, so weak +matches could incorrectly narrow or prioritize the search. Which document a follow-up means (`document_scope` in `tools/_shared/choose_document.py`) is decided by its wording when that is @@ -407,11 +406,15 @@ description ambiguous. Named and described targets are combined. For comparisons, all reliably identified sources are retained, including the earlier turn's document -when the question says "it". When a comparison identifies only one of its -targets ("compare these articles with the 2017 paper"), document scoping -is withheld and the wider retrieval remains available. This conservative -fallback prevents an inferred target from excluding an unresolved one; -it does not guarantee that every requested source fits the evidence budget. +when the question says "it". The `document_scope()` helper can withhold a +narrow scope when only one comparison target is recognized. The final +`RAGSession._ordinary_source_view()` resolution preserves explicitly named +operands rather than losing them in that intermediate result. When a +comparison search resolves to one eligible documentary operand, +it uses a preferred scope so other eligible targets can still be discovered. +Otherwise, a nonempty resolved scope is restricted to its authorized +membership. No scope resolution guarantees that every requested source fits +the evidence budget. ## Four-channel source-first retrieval and evidence budgets @@ -443,9 +446,13 @@ evidence count), and the source whose card ranks first. A comparison keeps at least two sources, and a question naming a number of sources ("review the five articles", `requested_source_count`) at least that many (the next ranked ones when fewer qualify). -Exhaustive questions ("all five papers") and several named sources skip -this cut. The trace event `retrieval.sources.ranked` lists the sources -left out as `unrelated`. +Explicit operands are retained by the relevance filter. Exhaustive +coverage bypasses the filter. In grouped mode, relevance depth counts +distinct logical anchors reached through their evidence members rather +than physical passage positions. Minimum representation targets apply +only when sufficient ranked candidates exist and remain subject to the +final evidence limits. The trace event `retrieval.sources.ranked` lists +the sources filtered out as `unrelated`. `retrievals/evidence_budget.py` adds validated per-intent **hard evidence limits** for source-first retrieval. Each selected source receives one @@ -479,31 +486,32 @@ strategies). | `coverage` | `"bounded"` or `"exhaustive"` | Coverage policy; default `"bounded"`. | | `include_related_evidence` | Boolean | Earlier cited passages compete for the **same** limits. | -For example, literature comparisons have the following settings: +For example, the following retrieval object illustrates a source-first +comparison intent using the bundled Literature settings: ```json { + "related_evidence": [ + "supplement_to" + ], + "related_lookup": [ + "bibliography_for" + ], "mode": "search", "strategy": "source_first", - "max_sources": 8, - "passages_per_source": 2, - "max_passages": 16, - "evidence_tokens": 9000, + "max_sources": 12, + "passages_per_source": 3, + "max_passages": 32, + "evidence_tokens": 16000, "coverage": "bounded", "include_related_evidence": true } ``` -The three built-in literature model-answering intents use: - -| Intent | Sources | Target per source | Hard passages | Evidence tokens | -| --- | ---: | ---: | ---: | ---: | -| `question_answering` | 3 | 1 | 8 | 5000 | -| `compare_sources` | 8 | 2 | 16 | 9000 | -| `report_generation` | 8 | 1 | 12 | 8000 | - -These are **packaged project-type defaults**, not universal limits on -project size, the number of indexed sources, or standalone tools. +Consult the registered project-type definition for its per-intent defaults +(for Literature, [`literature.json`](../kilin/project_types/literature.json)). +These settings are not universal limits on project size, the number of +indexed sources, or standalone tools. ### Coverage meaning and failure behavior @@ -512,7 +520,8 @@ It **does not** claim every source was checked. `exhaustive` attempts to represent every requested source with at least one original passage. Questions explicitly asking about *all*, *each*, or *every* source request exhaustive mode for that turn, regardless of the configured bounded default. -When a request names several documents, the explicit scope is strict. +A restriction to several resolved documentary operands admits only their +authorized members. If not every requested source can be represented in exhaustive mode, KíLín appends a deterministic **Coverage incomplete** notice to the @@ -547,10 +556,10 @@ Tools selected by `tool` replace this ordinary retrieval path. A tool continues to own its own validated `part_tokens`, batch and model-call limits, configured in that tool's `defaults.json`, the project-type intent's `tool` object, or saved `[tool.]` overrides (where exposed). -The reusable `EvidenceLimits`/`allocate_evidence` helper permits future -tools to adopt equivalent evidence budgeting, but existing tools do not -silently inherit these new source-first values. Registered tools can -use `ToolContext.retrieve()` without changing `ToolContext.rank()`. +Tools can use `EvidenceLimits` and `allocate_evidence` for equivalent +evidence budgeting, but do not inherit ordinary intent limits implicitly. +Registered tools can use `ToolContext.retrieve()` without changing +`ToolContext.rank()`. The supported answering retrieval strategies are `hybrid` and `source_first`. Literature project defaults use `source_first`. @@ -601,17 +610,15 @@ Two checks address different failure modes: Backend/library versions are not all encoded in the index identity. A source snapshot alone does not guarantee semantic compatibility after changing -models or indexing parameters. Older index formats without recorded model -snapshot identity can require a full rebuild. +models or indexing parameters. Index reuse requires compatible formats and +model-snapshot identity. The RAG coordinator stores the selected physical-file repository manifest -in `indexes/index_source_state.json`. It contains the same hash and size -records as before; its name distinguishes derived index state from managed -imports (`sources.json`) and the [project-root semantic manifest](source_manifest.md). -The obsolete `indexes/source_manifest.json` is neither read nor written. -If only the old cache exists, the next nonempty index preparation rebuilds -through the normal missing-metadata path. User sources and artifacts, as -well as the obsolete cache file itself, are left untouched. +in `indexes/index_source_state.json`. Its hash and size records describe +derived index state, separate from managed imports (`sources.json`) and +the [project-root semantic manifest](source_manifest.md). Missing or +incompatible index metadata prevents cache reuse. Rebuilding derived +indexes does not modify original sources or user artifacts. ### Incremental updates @@ -669,8 +676,9 @@ changing retrieval. Further optimization requires reproducible measurements and evidence-order invariance checks, not only fewer model calls. Progress wording describes actual work, not project IDs. Relationship -search is announced only when the graph has entities, with actual result -counts; otherwise the message explicitly reports that it was skipped. +search runs when the scoped graph contains entities and the question names +code. The progress messages report the actual result count or explain +which condition caused the channel to be skipped. ## Change impact and verification @@ -685,9 +693,10 @@ Run [retrieval algorithms and persistence](../tests/kilin/retrievals/), [retrieval corrections](../tests/kilin/test_rag__retrieval_corrections.py) and [empty workspaces](../tests/kilin/test_rag__empty_workspace.py). Check stable source coordinates, tie ordering, direct/related/alternative -labels, old-cache rejection and explicit failure cases. A deterministic -unit substitute validates structure, not live embedding quality; evaluate -ranking quality separately before claiming a retrieval improvement. +labels, incompatible-cache rejection and explicit failure cases. A +deterministic unit substitute validates structure, not live embedding +quality; evaluate ranking quality separately before claiming a retrieval +improvement. ## Source views and operation snapshots @@ -695,11 +704,11 @@ ranking quality separately before claiming a retrieval improvement. files, consulting installed project-type defaults, constructing models or changing indexes. The records and services are also exported through `kilin.tools`. Ordinary RAG search, complete-document reading, current -reference reuse, bounded tool retrieval and remaining source-aware tools -now enforce these views. The -session captures the accepted manifest and its loaded physical generation -before retrieval. The view is read-only: no role assignment, discovery, -index construction or new embedding model is needed to resolve it. +reference reuse, bounded tool retrieval and source-aware tools enforce +these views. The session captures the accepted manifest and its loaded +physical generation before retrieval. The view is read-only: no role +assignment, discovery, index construction or new embedding model is needed +to resolve it. ### Scope and purpose @@ -760,9 +769,9 @@ Membership and availability differ: a selected file without extracted passages can be a member, reported as `unindexed`. A missing or unresolved related path is reported as `unselected` or `unresolved` and is not included in usable membership. `raw_unavailable` identifies missing captured byte -identity or a source root outside the workspace; it need not imply that -indexed evidence is absent. The view does not assert that a source was read -or that its content supports a claim. +identity; it need not imply that indexed evidence is absent. Noncanonical +source roots are rejected before creating a view. The view does not assert +that a source was read or that its content supports a claim. ### Capturing and validating an operation @@ -894,19 +903,19 @@ reads supply no evidence. Actual model calls and estimated prompt costs include repeated shared excerpts, while final physical source identities are deduplicated. See the [project-summary guide](../kilin/tools/project_summary/README.md). -New ordinary turns record `evidence_source_sha256` in saved parameters. +Ordinary turns record `evidence_source_sha256` in saved parameters. Current reuse or related-turn merging retains only evidence in the active view with matching captured source hashes, exact indexed chunk text and coordinates, and unchanged on-disk source bytes. Only files actually reused -are hashed, not the full corpus. Older or otherwise unverifiable evidence is -not reused as current support; historical citations remain unchanged. +are hashed, not the full corpus. Unverifiable evidence is not reused as +current support; historical citations remain unchanged. ### Logical-group retrieval Set `grouped: true` on an ordinary source-first search intent, or supply a resolved view with `SourcePolicy(grouped=True)` to a bounded retrieval -request. The bundled defaults are unchanged (`false`); comparison alone -never enables grouping. Grouped views have documentary purpose. An ordinary +request. The bundled default is `false`; comparison alone never enables +grouping. Grouped views have documentary purpose. An ordinary explicit bibliography lookup instead uses a physical lookup view. Each eligible evidence member can contribute its best channel position to @@ -978,15 +987,20 @@ by this setting. ## Tool-owned bounded retrieval The core `RetrievalRequest` and `RetrievalResult` records in -`retrievals/requests.py` provide an explicit, model-free retrieval boundary -for registered tools. `ToolContext.retrieve(request)` delegates to the same -`RAGSession._retrieve()` path used by ordinary answering. The request owns +`retrievals/requests.py` provide a bounded retrieval interface independent +of answer generation and intent routing. Request construction and validation +require no model, but semantic retrieval can require query embedding. +`ToolContext.retrieve(request)` delegates to the same `RAGSession._retrieve()` +path used by ordinary answering. The request owns its strategy (`hybrid` or `source_first`), `EvidenceLimits`, explicit source-relative scope, comparison behavior, and optional registered source-card-kind filter. Omitted `scope` is project-wide; `scope=()` is an empty restriction. `scope_mode` explicitly selects the scope, or defaults to preferred for a single comparison operand and restricted for other explicit operands. Use `request.source_scope` for the normalized record. +The private retrieval entry point requires an explicit normalized scope +mode; there is no separate implicit named-document ranking path. Source +selection prioritizes operands within the already authorized rankings. The current coordinator validates explicit operands against the captured physical inventory and handles empty restrictions without querying models. Both strategies support nonempty restricted and preferred operands and @@ -1014,8 +1028,8 @@ and `True` permits bibliography text. No value admits bibliography paper cards. Reference suggestions explicitly use `False`. See [Tool retrieval and settings](tool_packages.md#tool-retrieval-and-settings) -and [suggest_reference](../kilin/tools/suggest_reference/README.md) for the -first opt-in consumer. +and [suggest_reference](../kilin/tools/suggest_reference/README.md) for a +concrete consumer. ### Remaining tool consumers @@ -1039,7 +1053,7 @@ quotation still matches its original coordinate. Otherwise it labels the saved quotation as historical evidence. `filter_results` classifies saved items without fresh retrieval. Neither historical operation turns earlier text into verified current evidence. Physical project inventory and assistant -guide retain their existing physical-inventory contracts. +guide operate on the physical inventory. ### Regeneration and memory-safe refresh diff --git a/docs/security.md b/docs/security.md index e3e9d702..f695fad8 100644 --- a/docs/security.md +++ b/docs/security.md @@ -163,7 +163,8 @@ for safe draft testing and confidentiality when using a frontier LLM. Resolved [source views](retrieval_pipeline.md#source-views-and-operation-snapshots) never grant access outside the selected inventory. The verified raw-byte service additionally retains workspace containment and checks captured -content digests. External source roots remain unavailable for raw reads. +content digests. Project sources must be the real `sources/` directory; +alternate roots, symbolic links, and junctions are rejected for raw reads. These checks are best effort, not race-free or protection from malicious trusted Python. Ordinary retrieval and bounded tool `retrieve()` validate and enforce the resolved view before ranking, including code-graph traversal diff --git a/docs/source_manifest.md b/docs/source_manifest.md index b1ad187a..64fb65b9 100644 --- a/docs/source_manifest.md +++ b/docs/source_manifest.md @@ -48,11 +48,10 @@ or full-document extraction. Opening a project never initializes or reconciles metadata. For an existing workspace missing the semantic manifest, call `kilin.initialize_source_manifest(project)` explicitly. This establishes -revision one under the same current format, not a migration from an old -index filename. A valid existing manifest is not replaced. Malformed or -unsupported metadata raises a diagnostic and remains intact. Back it up and -resolve the problem deliberately; never recover by overwriting it with an -empty graph. +revision one in the supported format. A valid existing manifest is not +replaced. Malformed or unsupported metadata raises a diagnostic and remains +intact. Back it up and resolve the problem deliberately; never recover by +overwriting it with an empty graph. Accepted settings contain the captured project-type identifier, implementation SemVer, schema generation, definition origin and SHA-256 of its exact JSON @@ -60,28 +59,23 @@ bytes. The small saved vocabulary includes the default role, all relation behaviors, automatic rule declarations and detector identities. It does not snapshot the entire project type, tool registry or model configuration. The installed `latex_bibliography` detector has identity `1`. A different -saved identity, including the earlier placeholder `not-implemented`, is not -automatically reinterpreted. Explicit detector adoption previews the new -behavior. - -### Opening a workspace created before source organization - -1. Keep a backup of the workspace, including its profile, sources and logs. - Open it normally; existing source paths and the project type are preserved. -2. In the GUI, use **Organize sources** and explicitly initialize missing - metadata when prompted. In Python, use `initialize_source_manifest()`. - Review the accepted declaration and pending assignments. Initialization - does not infer scientific roles from filenames or import new files. -3. Assign roles and relationships with preview/apply, then refresh semantic - metadata for an active session. If the configured source root differs - from the saved binding, review and explicitly rebind rather than restoring - identities solely by filename. -4. Physical index reuse is independent of this initialization. The old - `indexes/source_manifest.json` cache is not the semantic manifest; it - is ignored by current index preparation. Let normal index preparation - regenerate derived state when needed, and do not copy that cache to the - project root. Preserve historical recordings; older traces lacking the - semantic command history cannot reconstruct unrecorded edits. +saved identity is not automatically reinterpreted. Explicit detector +adoption previews the new behavior. + +### Initializing missing organization metadata + +A canonical workspace without `source_manifest.json` can be inspected without +creating metadata. In the GUI, **Organize sources** offers explicit +initialization; the Python equivalent is `initialize_source_manifest(project)`. +Initialization uses the current project type's defaults and does not infer +scientific roles from filenames, import files, or change the source layout. +Assign roles and relationships through preview/apply, then refresh semantic +metadata for an active session. Physical index reuse is independent of this +initialization. + +An existing malformed or unsupported manifest is rejected and preserved. +The contract requires the project's real `sources/` directory and supports +moving the entire workspace without changing its relative binding. [Tutorial 160](../tutorials/160_project_types.ipynb) demonstrates accepted roles, automatic bibliography links, shared supplements, restricted views @@ -90,14 +84,16 @@ and stale-view rejection using fictional sources and no model inference. ## Format and graph rules The format authority is `kilin.SOURCE_ORGANIZATION_FORMAT`, with value -`kilin-source-manifest-v1`, reported as `source_organization` by +`kilin-source-manifest-v2`, reported as `source_organization` by `kilin.version_info()`. It is independent of the managed-import -`kilin.workspace.SOURCE_MANIFEST_VERSION`. JSON contains precisely these -fields. An illustrative complete manifest (the digest is illustrative): +`kilin.workspace.SOURCE_MANIFEST_VERSION`. The supported semantic format +requires the canonical `project:sources` binding. Unsupported formats and +bindings are rejected without modification. JSON contains precisely the +following fields. A complete example (with an illustrative digest): ```json { - "format": "kilin-source-manifest-v1", + "format": "kilin-source-manifest-v2", "revision": 3, "source_root": {"base": "project", "path": "sources"}, "organization": { @@ -144,18 +140,18 @@ materialized defaults need not equal a later adopted default. A relation has origin `user` with `rule: null`, or `rule` with a syntactically valid rule identifier. A suppression records an exact edge independently of rule version. -File identities are exact POSIX-style paths relative to the configured source -root. Reject absolute file paths, traversal, noncanonical separators, +File identities are exact POSIX-style paths relative to the project's +`sources/` directory. Reject absolute file paths, traversal, noncanonical separators, control characters, trailing dots/spaces and portable case/Unicode aliases, including aliased directory components. Live selection uses the same scanner and recorded explicit imports/versions as RAG. Linked or escaping descendants are not permitted. An incomplete scan cannot serve as a deletion list. -A source root inside the workspace is stored relative to the project, with -`.` for the project root itself. Other roots have `base: "absolute"` and an -absolute POSIX spelling of the resolved path. The saved binding is compared -with the currently configured resolved root; it is never used to authorize -reads. Moving a project with its relative source tree preserves the binding. +The saved root binding must be exactly `{"base": "project", "path": "sources"}`. +Other roots and alternative spellings are rejected. The core validates the +physical source directory independently; the saved binding is identity evidence +and does not authorize file reads. Moving the whole current workspace keeps +this relative binding and the accepted source identities. Dependencies point from dependent to parent and may have multiple parents. Self-links and directed cycles among active declared dependencies are rejected. @@ -168,7 +164,7 @@ which is rejected. A previously missing endpoint cannot become active simply because a file appears with that name. The writer serializes UTF-8 JSON with sorted object keys and canonical ordering -of file records, edges, suppressions and unresolved records. The v1 bounds +of file records, edges, suppressions and unresolved records. The v2 bounds are 16 MiB encoded metadata, 10,000 assignments, 10,000 unresolved records, 40,000 links, 40,000 suppressions, 256 items in each declaration collection, 4,096 UTF-8 bytes per path, 128 bytes per detector identity and revisions up @@ -201,12 +197,14 @@ result = kilin.apply_source_manifest(project, preview) assert result.snapshot == kilin.read_source_manifest(project) ``` -`read_source_manifest()` parses only the saved state and returns an immutable -snapshot with the original-byte SHA-256. `inspect_source_manifest()` refreshes -the profile, scans the selected inventory and reports active assignments, -active relationships, pending selected paths and inactive records. A binding -mismatch yields no active assignments or links, even for identical filenames. -Neither read performs a write or consults today's project-type defaults. +`read_source_manifest()` validates the saved manifest and returns an +immutable snapshot with the original-byte SHA-256. It does not refresh the +profile or scan sources. `inspect_source_manifest()` refreshes the saved +profile, validates the live source layout, scans the selected inventory and +reports active assignments, active relationships, pending selected paths and +inactive records. A matching filename cannot authorize a noncanonical source +root. Neither operation writes metadata or adopts installed project-type +defaults. `preview_source_manifest(project, edits)` validates the entire proposed batch without writing. `apply_source_manifest(project, preview)` revalidates it under @@ -238,14 +236,11 @@ read-only inspection does not persist an observed removal: commit reconciliation when recording removal matters. Deletion and recreation between reconciliations cannot reliably be distinguished from ordinary replacement. -If the configured corpus changes, a normal preview raises a binding conflict. -Use `preview_source_manifest(project, rebind=True)` to inspect the transition. -The preview marks all previously accepted paths `root_rebound`; matching -filenames are not automatically associated with their old meaning. Unmatched -new paths receive the accepted default. Explicit `ResolveSourceEdit` records -can accompany a rebind when the user has deliberately resolved those identities. -The operation changes only the manifest binding; it does not change the saved -profile or import/move any source files. +There is no source-root rebind operation. Preview and apply validate the +current canonical directory before editing metadata; a profile that names a +different source root is rejected without changing sources or semantic state. +Use explicit source import, removal and synchronization for changes to the +contents of `sources/`. ## Accepted settings and adoption @@ -385,7 +380,7 @@ requested batch. A semantic error is returned separately, or warned about when the physical API has no observer. Observer failures cannot roll back completed operations. The original physical exception is still raised. Missing metadata requires explicit initialization, corruption requires -review, and a changed configured source root requires explicit rebinding. +review, and a noncanonical source root is rejected without a rebind fallback. Normal refresh never adopts installed type or detector defaults. After committing only role or relationship changes, call @@ -395,8 +390,8 @@ the existing indexed chunks and saved word pool without a model call. It neither prepares physical indexes nor prepares source cards. The session's conversation, chunks, vectors, cards and models are retained. Subsequent ordinary or bounded retrieval resolves a new view from the accepted metadata -and loaded index. The existing physical suggestion eligibility policy remains -in effect until the suggestion services adopt views. +and loaded index. Suggestion generation uses physical-file eligibility, +independently of role-aware retrieval views. ## Write safety, tracing and replay @@ -448,7 +443,7 @@ Inactive records, retained versions and pending roles are visible but not automatically restored. Unresolved selected files can be restored or reset explicitly. Ordinary settings provide role and discovery-mode controls; advanced settings retain explicit vocabulary mappings, rule declarations, -installed defaults and detector adoption, and deliberate root rebinding. +installed defaults and detector adoption. Every staged batch is previewed through the core before Apply; closing the editor without applying leaves the manifest unchanged. Missing metadata can be initialized after confirmation, while malformed @@ -456,8 +451,8 @@ metadata remains an inspection error. See the [GUI guide](../kilin/gui/README.md Organization is not authorization. A link may refer to a selected SVG or other file with no reader; it does not make the contents searchable or widen -the authority of a raw source-reading tool. Rebinding and reconciliation -use the current scanner, not the stored graph, to establish live selection. +the authority of a raw source-reading tool. Reconciliation uses the current +scanner, not the stored graph, to establish live selection. Locks coordinate cooperating KíLín writers; they do not prevent external programs from bypassing them, nor guarantee race-free protection against hostile filesystem or profile changes. See [Security](security.md). diff --git a/docs/source_pipeline.md b/docs/source_pipeline.md index e4b9c7bb..b99e2568 100644 --- a/docs/source_pipeline.md +++ b/docs/source_pipeline.md @@ -79,8 +79,10 @@ An empty newly created managed workspace is valid. It uses the same as a populated project; no example corpus is invented. Creation eligibility and later import APIs are documented with [workspace creation](project_workspaces.md#creation-opening-and-explicit-updates). -Opening a saved profile retains its source path. Outputs/templates are -separately managed user files, not automatically added to source indexing. +Opening a saved profile requires the canonical real `sources/` directory. +Alternative roots and source-root rebinding are rejected without changing +user files. Outputs/templates are separately managed user files and remain +outside source indexing. After explicit source changes, the GUI asks the core to refresh indexes. Imports and indexing are not a single multi-file transaction: successful @@ -98,18 +100,26 @@ evidence. See [Automatic source-card indexing](retrieval_pipeline.md#automatic-s order. It resolves each selected path again, rejects traversal, links, non-files and paths escaping the selected root, then uses a suffix-specific reader if one exists. Other inputs are decoded as UTF-8. Binary content is -not automatically made readable by giving it a textual suffix. A PDF uses -its dedicated selectable-text reader and may require installed PDF -extraction dependencies. A Word `.docx` file is read with `python-docx` -into Markdown-style text: headings become `#` lines, numbered or bulleted -items become indented `-` lines, and each table row becomes one line of -cells separated by ` | `. Indented paragraphs without numbering are not -turned into list items. An old binary -Word `.doc` file is read with `olefile`: the body text, paragraphs and +not automatically made readable by giving it a textual suffix. The PDF +reader uses two required package dependencies: `pypdf` opens the PDF, +checks encryption, counts pages and supplies fallback text; `pdfminer-six` +provides the primary layout-aware extraction. Invalid, encrypted or entirely +textless PDFs are rejected. Image-only pages are not subjected to OCR. +A Word `.docx` file is read with `python-docx` into Markdown-style text: +headings become `#` lines, numbered or bulleted items become indented `-` +lines, and each table row becomes one line of cells separated by ` | `. +Indented paragraphs without numbering are not turned into list items. A +binary Word `.doc` file is read with `olefile`: the body text, paragraphs and table rows are kept the same way, but headings are not recognized. Word files are recognized by their first bytes, so a `.doc` renamed to `.docx` (or the reverse) is still read by the right reader. +The reader can consume selected files from an incomplete scan report, subject +to the same path and content checks. `build_repository_manifest()` instead +requires a complete, trusted scan report. A partial selection can yield +readable files but cannot establish authoritative repository state for source +removal or index validation. + `SourceFile` contains a relative path and extracted text; `SourceUnit` contains a path, text, inclusive line range, kind, optional symbol/section, optional notebook cell, and optional child units. The `extract_source_units` @@ -156,18 +166,14 @@ is a structural scan, not JSON validation; malformed JSON can still be searched. Projects selecting `.json` record `json_source_units` (`top-level-keys-v2`) in index metadata. Key line coordinates follow Python's `splitlines` boundaries, including Unicode separators inside JSON -strings. Existing JSON indexes with an older version (or no version) are -rebuilt once to correct section provenance. Profiles not selecting `.json` -retain their previous index identity. +strings. Index reuse requires the matching extraction-format marker for +projects selecting `.json`. Other projects do not depend on that marker. -Word title and author properties are read separately for literature +Word title and author properties are read separately for document search headers and the paper-summary tool. The property reader handles OLE (`.doc`) and OOXML (`.docx`) containers based on their signatures, returning missing metadata on unreadable documents. It does not invent bibliographic -information or change the stored-file size policy. The stable -`tests/kilin/sources/extensions/fixtures/sample.docx` fixture was converted -from `sample.doc` with LibreOffice and has explicit title/author properties; -it complements generated tests for specific Word list styles. +information or change the stored-file size policy. **HTML as text or as code.** A project reads its files as code when its type's `code_graph` capability is `true`, as for Code projects; @@ -179,15 +185,15 @@ file as written and `extract_source_units(..., as_code=True)` uses the reader's `extract_code_units`. Citation line numbers refer to the text that was indexed, so the reference preview reads the file the same way. The index records `html_as_code` for projects that select `.html`, and -HTML cached as code has a separate identity from HTML cached as page text; -other file types keep their existing cache identities. In a Code project, -a page imports its local scripts and follows leading direct calls from -inline `on...` handlers. The graph reader ignores HTML comments, inert +HTML cached as code has a separate identity from HTML cached as page text. +In a Code project, a page imports its local scripts and follows leading +direct calls from inline `on...` handlers. The graph reader ignores HTML +comments, inert templates, and JavaScript string contents. HTML read as page text does not contribute code-graph relationships, even when it contains examples of markup. JavaScript functions and methods link their plain calls. -Literature profiles now allow `.bib` and `.bbl` alongside `.tex`. +Literature profiles allow `.bib` and `.bbl` alongside `.tex`. Selected bibliography files are ordinary indexed sources, not hidden auxiliary resources: a BibTeX entry and a compiled `\bibitem` can each be searched with its original source provenance. The lightweight diff --git a/docs/system_testing.md b/docs/system_testing.md index d16d4612..3929f3d9 100644 --- a/docs/system_testing.md +++ b/docs/system_testing.md @@ -108,8 +108,8 @@ need not be accessible on the inspection machine. Incidental regular by validation and replay verification. Links, nonregular entries, missing recorded files and all other unexpected files remain subject to the existing checks. No metadata files are removed from the workspace. Final file -comparisons use the same policy; version-1 publication receipts retain their -existing `.DS_Store` exclusion. +comparisons use the same policy. Reference-publication receipts omit +regular `.DS_Store` files from their artifact fingerprints. Conversation identities, branch prefixes, saved question/checkpoint identities and final saved content hashes are checked against the operation @@ -259,9 +259,11 @@ inputs. New conversation and turn IDs are allocated normally; branch prefixes must consist of the corresponding replayed turns. Explicit names, feedback, exclusions, memory synchronization, archive operations, selection, reset, project reopenings and card regeneration are replayed through the -same engine. A validated project rename is replayed through the normal -close and explicit resume commands, restoring the mapped active conversation -without renaming the replay directory. Normal resume can also emit a +same engine. The reset command creates and selects a new registered empty +conversation, leaving the previous conversation selectable; it does not +invoke `RAGSession.reset()`. A validated project rename is replayed through +the normal close and explicit resume commands, restoring the mapped active +conversation without renaming the replay directory. Normal resume can also emit a source-change diagnostic that the original internal reopening did not emit. The relocation provenance and this normalization are reported separately from effective settings differences. Automatic titles, answers, index files, @@ -396,17 +398,18 @@ Supported-format reports remain readable without this optional field. ### Context, tool coverage and independent inspection Each side's independent event inventory and saved-question observations are -retained even without alignment. Comparison report format 2 requires -independent event counts reconciling with each side's event total. These -counts are not inferred from aligned stages or outside-command observations. -Regenerate unsupported or incomplete reports using the current comparison -implementation; older reports are not migrated in place. Unverified saved -text from an invalid recording is labeled as such; unmatched questions do -not contribute to paired metrics. Aligned history selections resolve branch-local turn numbers through -validated saved prefixes and the reconstructed identity map. Memory inventories -compare mapped turn/role identities and origins without regard to inventory -order; retrieval order, content fingerprints, priorities and scores remain -separate. Missing observations and unknown identities are unavailable, not +retained even without alignment. The supported comparison report format +is 2 and requires independent event counts reconciling with each side's +event total. These counts are not inferred from aligned stages or +outside-command observations. Regenerate unsupported or incomplete reports +using the current comparison implementation; the loader rejects unsupported +formats rather than migrating them in place. Unverified saved text from an +invalid recording is labeled as such; unmatched questions do not contribute +to paired metrics. Aligned history selections resolve branch-local turn +numbers through validated saved prefixes and the reconstructed identity +map. Memory inventories compare mapped turn/role identities and origins +without regard to inventory order; retrieval order, content fingerprints, +priorities and scores remain separate. Missing observations and unknown identities are unavailable, not empty selections. In addition to raw rendered prompts, structured-input comparisons normalize @@ -467,9 +470,13 @@ category and logger clock domain are merged to avoid counting nested spans more than once. Categories overlap and are not additive; measurements are reported with span coverage and no automatic performance thresholds. The recorded output-event generation duration is used when the duplicate detail -is omitted. Generation and reply throughput use only actual recorded generated -token counts with positive corresponding durations, as a ratio of total -covered tokens to total covered time. Neither is necessarily decoding-only +is omitted. Generation and reply throughput use measured generated-token +counts from either MLX (`generated_tokens`) or PyTorch +(`generated_token_ids`) with positive corresponding durations, as a ratio +of total covered tokens to total covered time. Estimated counts (including +`retokenized_decoded_text`), unknown count sources and missing measurements +are excluded from these rates. Recorded output-token totals can still +include estimated counts. Neither rate is necessarily decoding-only throughput. Missing samples remain unavailable. Hardware/cache conditions are not controlled by these observations. @@ -539,7 +546,7 @@ The [module map](module_map.md) lists the package modules and their tests. ## Managed replay and reference publication -The low-level `Experiment.replay()` still requires an absent destination. +The low-level `Experiment.replay()` requires an absent destination. Use the managed API to make the policy for an existing replay explicit: ```python @@ -550,18 +557,22 @@ action = experiment.run_replay(existing_replay="archive") print(action.status, action.archived_workspace, action.error) ``` -`retain` (the default) leaves an existing replay unchanged; `archive` moves -it into a unique directory under `_replay_archive` outside workspace -discovery before creating a fresh replay; `error` refuses an existing replay. -The original must validate before a previous replay is moved. An archive -uses a same-filesystem rename, not copy-and-delete. A failed replay preserves -both the previous archive and the partial new recording. No policy overwrites -an original. A nonstandard archive directory must be separate from the +The original must validate before applying the requested replay policy. +`retain` (the default) leaves an existing replay unchanged and inspects its +recorded execution provenance without executing another replay or checking +live plugin eligibility. `archive` establishes plugin eligibility before +moving an existing replay into a unique directory under `_replay_archive` +outside workspace discovery and executing a fresh replay. `error` refuses +an existing replay. An archive uses a same-filesystem rename, not +copy-and-delete. A failed replay preserves the previous archive and any +partial new recording. No policy overwrites an original. A nonstandard archive directory must be separate from the workspace discovery directory, and only directories with the `_replay` suffix can be archived. Close both projects before invoking this API. A `ManagedReplay` distinguishes a completed execution, retained recording, -and failed action. Only a successful fresh execution writes an exclusive +and failed action. A `retained` action status does not certify recording +validity or equivalence to the original. Inspect validation and comparison +results independently. Only a successful fresh execution writes an exclusive `logs/system_testing_execution.json` receipt, containing the recorded input and output trace fingerprints, package content digest, available Git revision and dirty status, Python/platform information, and UTC execution bounds. @@ -604,11 +615,12 @@ detect changes that have been restored before inspection. ## Scripted references and notebook batch workflows -The optional workflow modules consolidate the former KiLinSystemTests -Python helpers. The experimental repository owns the experiment recipes, -local fixtures and results, not another copy of system-testing logic or -notebook templates. Existing recordings and version-1 comparison reports -retain their format and interpretation. +KíLín owns the recording, validation, replay, comparison and analysis +interfaces and the packaged notebook templates. The experimental repository +owns trusted experiment recipes, local source fixtures, reference and replay +workspaces, and experimental results. Comparison reports use format 2; +reference-publication and replay-execution receipts are independently +versioned and each currently uses format 1. - `kilin.system_testing.generation` provides `Recorder`, `generate_reference`, `check_output` and `reference_overview`. Recipes diff --git a/docs/tool_packages.md b/docs/tool_packages.md index b1f516d8..720c6a75 100644 --- a/docs/tool_packages.md +++ b/docs/tool_packages.md @@ -59,8 +59,7 @@ User packages follow the same descriptor contract; see the storage, validation, trust boundary and restart requirements. Use relative imports for package-local modules. The [public plugin API](PLUGIN_API.md) defines the descriptor and optional files. Use -their documented package exports; obsolete flat-file import paths have no -compatibility aliases. +their documented package exports. ## Generated output safety @@ -158,10 +157,12 @@ For `suggest_reference`, the tool-local `SETTINGS` values in may override these settings, followed by saved project `[tool.name]` settings. When `source_first` is explicitly selected, candidate papers are source-ranked using scientific-paper cards where present. The tool -continues to verify claims against separately ranked original passages; -that second passage ranking can incur another query embedding. Its existing -`FILES`, `PASSAGES`, and `PASSAGE_TOKENS` remain authoritative for how many -papers are judged and how much content is read for each judgment. +continues to verify claims against separately ranked original passages in +its verification view. Each ranking operation is constrained by its own +resolved membership; matching formatted-query embeddings are reused across +bound views within the operation. Candidate selection does not establish +scientific support. `FILES`, `PASSAGES`, and `PASSAGE_TOKENS` determine how +many papers are judged and how much content is selected for each judgment. Other tools, especially exhaustive scanners and full-document readers, retain their existing retrieval behavior. A selected source does not imply @@ -272,24 +273,23 @@ and `internal_generation.calls` with requested thinking, caps, attempts and completion status; model traces record the effective allowance. See [trace records](trace_recording.md#recorded-data) for diagnostic ownership. -### Compatibility notes for customized tool configuration - -Customized intent tool objects must not retain `answer_tokens`, -`note_tokens` or `section_tokens`. The corresponding packaged `SETTINGS` -keys `ANSWER_TOKENS`, `NOTE_TOKENS` and `SECTION_TOKENS` are not accepted. -Unknown settings fail validation rather than overriding the user allowance -or becoming ineffective settings. In `reference_check` only, rename a -customized `max_model_calls` override to `max_checked_claims`; other tools -retain their own `max_model_calls` settings. - -`MODEL_CALLS` accepts only `THINKING`; remove `SHORT_REPLY_THINKING` and -`SHORT_REPLY_MAX_TOKENS` from older customized files. The old selection caps -`find_passages.JUDGE_REPLY_TOKENS`, `filter_results.REPLY_TOKENS` and -`batch_classify.REPLY_TOKEN_LIMIT_PER_ITEM` must also be removed from -customized estimate groups; their validators no longer accept those keys. -Use the current validated defaults and restart the process/kernel after -edits. These settings changes require neither source reindexing nor -rewriting historical answers. +### Validation of customized tool configuration + +Use the documented tool-specific `SETTINGS` keys for customized intent +settings. Output allowances inherit the active session as described above; +`answer_tokens`, `note_tokens` and `section_tokens` are not accepted as +intent settings, nor are their uppercase equivalents in packaged +`SETTINGS`. Unknown or invalid settings fail validation. + +`reference_check` accepts `max_checked_claims` as its claim limit, not +`max_model_calls`. Other tools may define their own `max_model_calls` +settings; consult each tool's configuration documentation. + +`MODEL_CALLS` accepts only `THINKING`. Internal estimate groups must match +the owning tool's validated defaults. They do not set generation limits; +use the active session settings and the documented output-limit policy. +Restart the process/kernel after editing packaged defaults. These settings +changes require neither source reindexing nor rewriting saved answers. ## Partial tool completion diff --git a/docs/trace_architecture.md b/docs/trace_architecture.md index 8cbf6114..357195f5 100644 --- a/docs/trace_architecture.md +++ b/docs/trace_architecture.md @@ -1,15 +1,13 @@ # Project and conversation diagnostic traces The project and conversation traces share a single event-number namespace -within each workspace. The existing grouped JSON format remains the diagnostic -format; there is no second journal of event payloads. +within each workspace. Event payloads are stored in grouped JSON diagnostics. ## Files and ownership - `logs/traces/project.json` holds project-level diagnostic sessions. -- Conversation trace files retain the existing conversation checkpoint and - grouped diagnostic sessions. Their existing exclusive writer ownership - is unchanged. +- Conversation trace files hold the conversation checkpoint and grouped + diagnostic sessions under exclusive writer ownership. - `logs/traces/.sequence.json` contains only the trace format version, allocation high-water mark, and a persistent incomplete-recording flag. It must accompany a copied test workspace. Its lock companion, like other @@ -17,28 +15,28 @@ format; there is no second journal of event payloads. The project trace and allocation counter take short write leases. Each project-trace writer replaces only its own hierarchical session projection; -other writers' sessions are preserved. No workspace-wide session lock is -introduced. A project trace does not own a conversation checkpoint. +other writers' sessions are preserved. Project-trace writes do not acquire a +workspace-wide session lock. A project trace does not own a conversation +checkpoint. ### Readable JSON layout Project and conversation traces share the private `_trace_json` formatter. Arrays containing at least sixteen integers use sixteen values per line; -other values retain the standard two-space JSON layout. This reduces token -array whitespace without removing events, changing values or adding a storage -format. Booleans, floating-point values and mixed arrays retain their original -layout. The standard JSON encoder still owns escaping and validation. - -This layout changes only whitespace outside JSON strings. Event identities, -token identifiers, Unicode text, scalar types, mapping and array order, and -conversation resume state are unchanged. Canonical event fingerprints and -reference receipts therefore remain identical. The writers retain their -existing atomic replacement, ownership and failure policies. Existing files -are not proactively reformatted; ordinary future writes use the shared layout. +other values use the standard two-space JSON layout, including booleans, +floating-point values and mixed arrays. The standard JSON encoder owns +escaping and validation. + +Integer-array grouping affects only whitespace outside JSON strings. It +preserves event identities, token identifiers, Unicode text, scalar types, +mapping and array order, and conversation resume state. Canonical event +fingerprints and reference receipts are independent of this formatting. +Writers use atomic replacement under their ownership and failure policies. +Files are formatted when written; reading a file does not reformat it. ## Event identity -Each newly recorded event in a managed project receives a positive project-wide +Each recorded event in a managed project receives a positive project-wide `sequence` number before publication. This order is allocation order, not a claim that operations in different processes completed sequentially. A process can reserve a number and fail before its event reaches disk. Sequence gaps or @@ -48,23 +46,25 @@ or investigate a recording rather than silently reordering or renumbering it. The hierarchical projection includes explicit event type, component, event ID, trace ID, sequence, timing and correlation metadata. An operation span retains its start metadata in `event` and its terminal metadata in `completion`. -The original status of the start is retained as `started_status`; the existing +The original status of the start is retained as `started_status`; the summary status and completion time remain available for inspection. Sampled progress checkpoints retain event identity as well. Top-level event counts -continue to describe the publishing logger run, not the entire history. +describe the publishing logger run, not the entire history. Conversation archival preserves the event numbers in the archived file. The new active conversation does not re-emit those historical events. Standalone loggers outside a managed project retain local numbering (`sequence_scope` `logger`). -The `trace_format_version` and `sequence_scope` distinguish the new project -recordings from earlier diagnostics. Existing historical recordings are not -renumbered and must not be assumed replayable. A missing or malformed shared -counter for an already project-numbered workspace is not repaired by guessing -new numbers. Optional trace-write failures retain the existing warning/raise -policy; the incomplete flag is persisted on a best-effort basis. The replay -validator must independently check for gaps and missing data. +The `trace_format_version` and `sequence_scope` identify the format and +numbering scope. Replay validation requires the supported format and project +scope; the presence of diagnostic events alone does not establish replay +eligibility. Saved events are never renumbered to repair a recording. A +missing or malformed shared counter for an already project-numbered workspace +is not repaired by guessing new numbers. Optional trace-write failures follow +the configured warning/raise policy; the incomplete flag is persisted on a +best-effort basis. The replay validator independently checks for gaps and +missing data. Missing-counter discovery includes managed JSON traces with custom names and case variants such as `conversation.json` or `custom.JSON`, including archived @@ -76,7 +76,7 @@ trace history. ## Recording coverage The GUI maintains a project trace alongside the active conversation trace. -Conversation switching and archival retain their existing ownership rules. +Conversation switching and archival follow their ownership rules. Before archival, pending diagnostics are published; a trace that already contains all recorded events is left byte-for-byte unchanged. @@ -113,7 +113,7 @@ replacement, deletion, or manual resource edits may destroy historical inputs. Index preparation, including model loading, index reuse/rebuild decisions, source-card reconciliation, and preparation progress, is recorded in the project trace. The physical repository manifest already computed by indexing -is included under the existing `source_manifest` field in +is included under the `source_manifest` field in `index.check.completed` or `index.empty`; it records relative filenames, sizes, and SHA-256 digests without rereading files for tracing. The `manifest_path` field, where present, points to @@ -149,7 +149,7 @@ any independent reconciliation error. The question-request span captures `source_organization_error`) at request start without rescanning source text. These are observations, not a guarantee that no external edit will occur while answering; tool source-operation records describe actual bound views. -The existing physical index `source_manifest` field is unchanged. Replay +The physical index `source_manifest` is recorded independently. Replay reissues the recorded explicit decisions chronologically against live preview identities and compares the resulting semantic observations independently. @@ -222,19 +222,18 @@ persistent index or cache. The lock order is project publication lease, then short sequence lease; ordinary events release the sequence lease before taking the publication lease. A failed publication releases the project lease before applying the -existing recording-health and warning/raise policy. The two files are not a -multi-file atomic transaction. Do not mix older and newer concurrent writers. +recording-health and warning/raise policy. The two files are not a multi-file +atomic transaction. Concurrent writers must use the same trace format and +reference rules. System-testing inspection resolves references in global sequence order, checks their digest and latest-full-snapshot identity, and supplies independent copies of the complete payload to validation, timeline reconstruction, replay and comparison. Publication receipts fingerprint these decoded payloads, so a full configuration and its compact representation have the same trace-prefix -digest. Invalid references are blocking recording issues. Original -files are not rewritten. Full observations remain part of the current -format. The earlier prerelease `configuration_reference` payload is no longer -supported; regenerate recordings that use it. The trace hierarchy and -counter format remain unchanged. +digest. Invalid references are blocking recording issues. Inspection does not +rewrite the original files. The current format supports both full observations +and `configuration_content_reference` payloads. ### Repeated source snapshots @@ -258,18 +257,19 @@ failed or incomplete full observations do not become reference targets. The next complete observation is retained in full after such an observation. These group references are local to one project trace and one event type, and are used only when the canonical compact representation is smaller. -Empty-index and conversation events keep their existing formats. Semantic -commits and completed applications additionally support the independent -manifest representation below. Historical event values are not compacted -retroactively. +Source-snapshot compaction does not apply to empty-index or conversation +events. Semantic commits and completed applications additionally support the +independent manifest representation below. Historical event values are not +compacted retroactively. The inspector expands source snapshots before validation, replay, comparison, and publication-receipt fingerprinting, checking that the target is the latest preceding full observation of the same event type. Missing, ambiguous, forward, chained, superseded, mixed full/reference, and digest-mismatched references are blocking recording issues. A compact observation is never reconstructed from -the current source files or manifest. Older full-snapshot recordings remain -readable; direct JSON readers must understand the new reference field. +the current source files or manifest. The current format supports both full +and compact source snapshots. Direct JSON readers must also handle +`source_snapshot_reference`. Local analysis details also use the recording reader, so references have the same meaning in event inventories and exact-text lookup as in replay and @@ -297,7 +297,7 @@ only when smaller. An incomplete or failed full semantic observation requires fresh full evidence. A reference never becomes a target, including an opening observation using `source_snapshot_reference`. -Opening observations continue to use their existing complete source-group +Opening observations use complete source-group compaction; they supply full manifest targets but do not emit semantic-only references. This preserves savings across repeated GUI openings and avoids making a later source-group reference depend indirectly on a semantic @@ -374,14 +374,16 @@ conversation ID, persistent turn UUID, role, and committed rating/revision. Manual memory updates have project-level spans; automatic memory updates have turn-level spans. Result metadata describes the eligible records, origins, fingerprints, priorities, and index counts without duplicating the -message texts or vectors. Memory remains derived from the authoritative -conversation and feedback state. +message texts or vectors. Model-call diagnostics can separately contain +retrieved memories in recorded prompts. Memory remains derived from the +authoritative conversation and feedback state; see +[conversation memory](conversation_memory.md). ### Recording completeness The creation event carries `operation_recording_version` in addition to the -structural trace-format version. Workspaces created before full operation -recording do not acquire this marker on reopening. A fresh workspace with +structural trace-format version. Opening a workspace does not add a missing +creation marker or reconstruct unrecorded operations. A fresh workspace with tracing enabled throughout is required for a reference experiment. The marker is necessary but not sufficient: independent validation must also check event coverage, sequence continuity, command completion, referenced @@ -390,8 +392,8 @@ traces alone. Interrupted or unsuccessful commands are not silently treated as completed replay inputs. These records are the inputs to timeline reconstruction and independent replay, -implemented in the system-testing package. See [Trace recording](trace_recording.md) for -activation and failure policy. +implemented in the system-testing package. See +[Trace recording](trace_recording.md) for activation and failure policy. For offline inspection of a closed workspace, see [System testing](system_testing.md). The validator expands compact span diff --git a/docs/trace_recording.md b/docs/trace_recording.md index d40451b7..4b94b83c 100644 --- a/docs/trace_recording.md +++ b/docs/trace_recording.md @@ -3,10 +3,9 @@ The authoritative [versioning policy](versioning.md) defines version ownership, compatibility, and contributor obligations. -KíLín uses **one diagnostic tracing behavior**. Enabled traces record all -available structured diagnostic events, including complete prompts, model -responses, retrieved content and token IDs. There is no standard/forensic -mode switch and no automatic redaction or sanitization. +Enabled tracing records all available structured diagnostic events, including +complete prompts, model responses, retrieved content and token IDs. Trace +content is not automatically redacted or sanitized. ## Enabling or disabling tracing @@ -43,11 +42,19 @@ the new conversation sink to agree with the shared project sink's `enabled` value and rejects a mismatch before changing the active session. Close and reopen the RAG session to change tracing activation. -`TraceConfig.include_embedding_vectors=True` is an independent opt-in for -full numerical embedding vectors, which can be large. `failure_policy` stays -independent and controls optional event-write errors (`"warn"` or `"raise"`); -checkpoint write failures always propagate. Output location and tracing -activation also remain configurable. +`TraceConfig` has four fields: + +| Field | Default | Effect | +| --- | --- | --- | +| `enabled` | `False` | Enable or disable optional diagnostic recording. | +| `output_path` | `None` | Exact JSON path or output folder; `None` uses the caller's default folder. | +| `include_embedding_vectors` | `False` | Allow complete numerical embedding vectors, which can be large. | +| `failure_policy` | `"warn"` | Handle optional event-write I/O failures with `"warn"` or `"raise"`. | + +An enabled RAG trace must use the session's authoritative conversation path. +RAG binds an unspecified output path to that file and rejects a different +path. Required conversation writes always propagate failures, independently +of the diagnostic policy. ### Project-creation ordering @@ -78,20 +85,27 @@ owns filesystem recovery. An enabled logger always makes its `include_content` and `include_token_ids` properties true. A disabled `NullTraceLogger` makes them false, allowing -callers to avoid constructing expensive diagnostic artifacts. These are sink capability -properties, not configurable tracing modes. Both built-in and custom events -are recorded without mode-based filtering. +callers to avoid constructing expensive diagnostic artifacts. These sink +capabilities apply to both built-in and custom events; content and token +recording have no separate configuration fields. A grouped `conversation_*.json` file holds diagnostic events and resumable conversation state. The latter stores the question, answer, evidence, history, and checkpoint identity needed to reopen the conversation. Disabling tracing does not remove this state. `trace.started` records the scope, output path, -embedding-vector policy and runtime environment; it has no tracing-mode -field. Exact diagnostic artifacts are stored inline, not loaded from separate -files. Previously stored events are not retroactively filtered or rewritten. -The current prerelease trace format does not support the earlier compact -configuration or file-artifact representations. Regenerate system-test -recordings using the current writer and reader. +embedding-vector policy and runtime environment. Exact diagnostic artifacts +are stored inline, not loaded from separate files. Reopening retains existing +event values. A declared unsupported trace version is rejected without +modifying the original file. System-test recordings must satisfy the current +recording format and its validation requirements. + +The [current conversation schema](conversation_ownership.md#current-persisted-schema) +is validated before a logger appends `trace.started` to an existing record. +Required checkpoint writes validate the complete merged candidate, including +turns, evidence, explicit nullable timing, and checkpoint content hashes. +Optional diagnostic failure policy cannot suppress a schema error or convert +invalid persisted history into a new empty conversation. State-only records +and valid incomplete diagnostic attempts remain supported. Managed workspaces use shared event numbering across conversation and project traces. Initialization, source operations, indexing and configuration are @@ -105,23 +119,25 @@ Tracing only captures information that the execution components expose: external backends and custom tools may not offer every diagnostic detail. Token IDs are included when available; embeddings are included only when explicitly enabled. Diagnostic coverage follows the producing component; -the logger does not synthesize missing backend details. +the logger does not synthesize missing backend details or run model inference +to obtain them. For a direct model answer, `llm.call.input` records the resolved request in both `thinking` and `chat_template.enable_thinking`, matching prompt rendering and tokenization. Turn parameters instead retain `thinking` as the configured session value used on reopening and record `thinking_effective` separately. The latter is absent on tool-written -answers and older turns. These values describe the requested template -policy, not proof that a particular model complied. No extra event or -checkpoint is introduced for an intent override. +answers and may be absent from saved turns. These values describe the +requested template policy, not proof that a particular model complied. +An intent override is recorded within these existing events and the turn's +checkpoint. Completed-turn parameters also include a core-formatted `model_summary` with the active chat model ID, recorded temperature, thinking setting (effective per-intent value for direct answers) and maximum output tokens. This describes the chat session's settings; tool-owned internal model calls may use different generation parameters. The GUI shows the stored -summary, with a field-based fallback for older turns. +summary, with a field-based fallback when the summary is absent. Every tool run is recorded as a `tool.run` span in the turn: its `name`, the `settings` it ran with (including any the project changed in Settings → @@ -135,7 +151,7 @@ values. The [identifier schema](configuration.md#canonical-identifiers-and-schemas) distinguishes profile `type_id` from qualified `project_type_id` in turn and -intent metadata; former project-kind keys are not emitted. An empty source collection reports +intent metadata. An empty source collection reports `index.empty` and index status `empty` without fabricating passages or saving a retrieval bundle. Source-entity `kind` metadata is unchanged. @@ -145,13 +161,23 @@ Trace updates use the [atomic-write and ownership contract](conversation_ownersh not an independent persistence mechanism. The distinction here is between optional diagnostic events and mandatory resumable-state checkpoints. -Optional diagnostic event writes use the configured `failure_policy`. Required -conversation checkpoint writes propagate failures and restore the logger's -previous in-memory resume state. When the GUI updates active conversation -metadata, it delegates the write to the active trace so later diagnostic -events cannot undo a rename or timestamp change from an obsolete snapshot. -These are single-file guarantees, not transactions across metadata, model -state, or multiple files; no power-loss durability is claimed. +An optional event-write I/O failure marks the logger failed. With `"warn"`, +it emits a `RuntimeWarning` and stops recording later optional events on that +logger. With `"raise"`, it raises a `RuntimeError` for the write failure. +Managed traces also try to mark the shared recording incomplete, but that +best-effort write can fail independently. + +Required conversation-state writes still call `update_conversation()` after +an optional diagnostic failure. They validate and atomically write the merged +state, propagate failures, and restore the logger's previous in-memory resume +state if serialization or writing fails. A successful checkpoint can therefore +save an answer even when its diagnostic recording is incomplete. + +When the GUI updates active conversation metadata, it delegates the write to +the active trace so later diagnostic events cannot undo a rename or timestamp +change from an obsolete snapshot. These are single-file guarantees, not +transactions across metadata, model state, or multiple files; no power-loss +durability is claimed. ## Stopped and failed answers @@ -161,9 +187,9 @@ partial text and show "Stopped at your request" without that text becoming resumable history. The [Stop protocol](gui_protocol.md#errors-stop-and-restart) owns the request, token-boundary checks, completion race and forced fallback. -A Stop is easy to find in the trace file. Under -`sessions["05_conversations"]["turns"]`, the turn's operation has `"status": -"failed"`, and its `result` has `"error_type": "GenerationCancelled"` and +When diagnostic recording succeeds, the stopped turn's operation under +`sessions["05_conversations"]["turns"]` has `"status": "failed"`, and its +`result` has `"error_type": "GenerationCancelled"` and `"message": "Stopped by the user."`. `sessions["06_runtime"]` also gets a `gui_answer_cancelled` operation with `"reason": "Stopped by the user."`, timed when the answer ended. Any other failure has a different @@ -189,27 +215,18 @@ as they are emitted, but unwritten events cannot be recovered. Do not infer a successful answer from the mere presence of a traced turn operation. -An answer that **fails before its checkpoint** records the failure in the trace -and adds no turn; the GUI shows the error and puts the question back. A final -GUI notification can fail after the turn is saved: the outer -`gui.question.request` span may then fail while the checkpoint and successful -core turn remain authoritative. An answer -the model could not finish (for example, it reached its token limit) is -different: the trace records `generation.incomplete`, and the turn **is** -saved, with an answer explaining that no reliable result was produced and -the details under its `completion` parameter. The +An answer that **fails before its checkpoint** adds no turn; the GUI shows +the error and puts the question back. Its failure is recorded when diagnostic +writes succeed. A final GUI notification can fail after the turn is saved: +the outer `gui.question.request` span may then fail while the checkpoint and +successful core turn remain authoritative. An answer the model could not +finish (for example, it reached its token limit) is +different: it emits `generation.incomplete` and, if its checkpoint succeeds, +saves a turn with an answer explaining that no reliable result was produced +and the details under its `completion` parameter. The [completion contract](answering_pipeline.md#model-output-completion-and-bounded-recovery) owns incomplete versus partial outcomes and their use in later history. -## Migration from earlier trace configurations - -Remove any `mode=...` argument from `TraceConfig` construction and any imports -of `TraceMode`, `TRACE_MODE_STANDARD`, `TRACE_MODE_FORENSIC`, -`TRACE_MODE_CHOICES`, or `DEFAULT_TRACE_MODE`. These options are no longer -part of KíLín's Python API. The `TRACE.DEFAULT_MODE` entry is also removed -from `kilin_defaults.json`; no replacement setting is needed. The change -does not migrate, rewrite, or delete older conversation files. - ## Privacy, storage, and deletion Traces are private *only to the extent that their files and environment are @@ -229,8 +246,8 @@ physical erasure. For the GUI's archival and lock rules, see For read-only timing analysis of existing conversation traces, and an optional standardized-question notebook, see [Performance analysis](performance.md). -The analysis does not require a new trace mode or change the persistence -behavior described above. Raw traces remain sensitive project data. +The analysis uses the recorded timing data. Raw traces remain sensitive +project data. ## Operation recording @@ -243,9 +260,10 @@ than independent user commands. A proposal and its outcome share an interaction ID; option labels are retained alongside numeric indices. See [Trace architecture](trace_architecture.md#conversation-operations) for -the command boundaries and the creation-time recording version. Existing -workspaces remain usable but are not automatically upgraded into complete -reference experiments. +the command boundaries and the creation-time recording version. Reopening a +workspace does not reconstruct missing operations or add a creation-time +recording marker. Complete reference experiments require a recorded lifecycle +that satisfies independent validation. ## Tests diff --git a/docs/versioning.md b/docs/versioning.md index 3f178890..739b65eb 100644 --- a/docs/versioning.md +++ b/docs/versioning.md @@ -194,7 +194,7 @@ for the trace format or the application version. | Operation recording | `kilin._trace_project.OPERATION_RECORDING_VERSION` | | Repository manifest | `kilin.repository._MANIFEST_VERSION` | | Managed source manifest | `kilin.workspace.SOURCE_MANIFEST_VERSION` | -| [Semantic source organization](source_manifest.md) | `kilin.SOURCE_ORGANIZATION_FORMAT` (`kilin-source-manifest-v1`) | +| [Semantic source organization](source_manifest.md) | `kilin.SOURCE_ORGANIZATION_FORMAT` (`kilin-source-manifest-v2`) | | Pending plugin operation | `kilin.plugins._management.PENDING_OPERATION_FORMAT_VERSION` | | Comparison report | `kilin.system_testing.comparison.COMPARISON_FORMAT_VERSION` | | Reference receipt | `kilin.system_testing.reference.REFERENCE_RECEIPT_FORMAT_VERSION` | @@ -208,6 +208,15 @@ reports unsupported traces without decoding their events. Existing numbered and descriptive retrieval, source-card, and settings format identifiers retain their own declarations and meanings. +The persisted project profile and standalone conversation resume state are +unnumbered current schemas. Required fields are enforced directly; a missing +field is not a request for an older-version default. This prerelease cleanup +does not add migration paths or invent historical format generations. +Conversation state embedded in a trace follows the same strict validation +while the pre-stable trace contract remains generation 1 under the policy +above. The schema and legitimate lifecycle states are documented in +[conversation-file ownership](conversation_ownership.md#current-persisted-schema). + ## Project creation provenance A new project records immutable origin metadata in `profile.ini` at the @@ -225,8 +234,10 @@ created_with_project_type_sha256 = These illustrative values MUST NOT be hard-coded into creation code. Renaming, relocation, settings changes, or application and plugin upgrades MUST NOT -modify creation provenance. Existing projects with unknown provenance MUST -NOT be assigned invented historical values. Creation provenance is descriptive, +modify creation provenance. Every persisted project MUST contain all five +fields, including projects created through the core Python API. Profiles +without creation metadata are invalid and MUST NOT be assigned invented +historical values. Creation provenance is descriptive, not a compatibility gate or an instruction to pin the active project type. The instance evolves through its own user configuration, sources, outputs, and conversation history. No independently incremented project-instance @@ -235,9 +246,10 @@ records the actual identities used at each execution independently of origin. Python exposes the saved record as `QAProject.creation_provenance`, a frozen `kilin.ProjectCreationProvenance` object separate from `ProjectProfile`. -For a workspace without the metadata section, this property is `None`. -Present but incomplete or malformed metadata is reported as an invalid -profile without rewriting it. The application version is validated against +The property is required and is never `None` on a valid project. Absent, +incomplete, or malformed metadata is reported as an invalid profile without +rewriting it. Read-only inspection with `require_registered_type=False` +uses the same schema without activating the current project-type catalog. The application version is validated against the canonical stable, beta, and release-candidate syntax during both creation and reopening. Historical, well-formed versions are read without checking them against the current runtime, catalog, or supported generations. Native @@ -348,8 +360,8 @@ strings independently in frontend assets. The desktop Versions section is application-wide and available before a project is opened. It presents the core inventory in collapsible groups and can copy the complete snapshot as JSON, including separate active-project -creation provenance (None if absent). The bridge obtains the banner value -from `kilin.__version__`; report requests are correlated by request ID and +creation provenance (`None` only when no project is open). The bridge +obtains the banner value from `kilin.__version__`; report requests are correlated by request ID and project, and stale replies are discarded. The Plugins panel consumes the same plugin-record inventory rather than a separately collected catalog. diff --git a/examples/plugins/check_examples.py b/examples/plugins/check_examples.py index c73c803f..cd9c6531 100644 --- a/examples/plugins/check_examples.py +++ b/examples/plugins/check_examples.py @@ -38,7 +38,7 @@ def _child(phase: str, root: Path) -> None: options = ["-I"] if sys.flags.isolated else [] env = dict(os.environ, KILIN_PLUGINS_DIR=str(root / "plugins"), - KILIN_DEFAULTS_FILE=str(root / "preferences.json"), + KILIN_PREFERENCES_FILE=str(root / "preferences.json"), KILIN_WORKSPACES_DIR=str(root / "workspaces"), HF_HUB_OFFLINE="1", HF_HUB_DISABLE_TELEMETRY="1") result = subprocess.run( diff --git a/kilin/_source_access.py b/kilin/_source_access.py index 1d0b4356..0c99689b 100644 --- a/kilin/_source_access.py +++ b/kilin/_source_access.py @@ -26,6 +26,8 @@ from collections.abc import Collection from pathlib import Path +from kilin.workspace_resources import PROJECT_SOURCES_DIRECTORY + __all__ = [] @@ -42,7 +44,7 @@ def selected_source_file( project_root: pathlib.Path Workspace root, containing project state and managed sources. source_root: pathlib.Path - Saved profile's source directory, which must be in the workspace. + Canonical real ``sources`` directory inside the workspace. path: pathlib.Path Source-relative file path, as recorded by the source inventory. selected: Collection[pathlib.Path] @@ -57,9 +59,10 @@ def selected_source_file( Notes ----- No fallback searches the workspace root or an original import folder. - Paths inherited from legacy profiles outside the workspace are not - read by tools through this helper. The checks do not prevent an - uncooperative process from changing files after validation. + Alternate source roots are not read through this helper. Aliases of + ancestor directories do not change the identity of a real source root. + The checks do not prevent an uncooperative process from changing files + or links after validation. """ @@ -71,10 +74,16 @@ def selected_source_file( return None try: root = project_root.resolve(strict=True) + # Reject a linked or differently named source entry, not aliases of + # its ancestors (such as /var on macOS). + if ( + source_root.name != PROJECT_SOURCES_DIRECTORY + or source_root.is_symlink() or source_root.is_junction() + ): + return None source = source_root.resolve(strict=True) if ( - source_root.is_symlink() or source_root.is_junction() - or not source.is_relative_to(root) + source != root / PROJECT_SOURCES_DIRECTORY or not source.is_dir() ): return None diff --git a/kilin/_source_manifest.py b/kilin/_source_manifest.py index 852799a5..84776774 100644 --- a/kilin/_source_manifest.py +++ b/kilin/_source_manifest.py @@ -18,7 +18,7 @@ -------- >>> from kilin.source_manifest import SOURCE_ORGANIZATION_FORMAT >>> SOURCE_ORGANIZATION_FORMAT -'kilin-source-manifest-v1' +'kilin-source-manifest-v2' """ @@ -26,7 +26,7 @@ from collections import deque from dataclasses import asdict, dataclass -from pathlib import PurePosixPath, PureWindowsPath +from pathlib import PureWindowsPath import re from typing import Final import unicodedata @@ -38,7 +38,7 @@ __all__ = [] -SOURCE_ORGANIZATION_FORMAT: Final[str] = "kilin-source-manifest-v1" +SOURCE_ORGANIZATION_FORMAT: Final[str] = "kilin-source-manifest-v2" SOURCE_MANIFEST_FILE: Final[str] = "source_manifest.json" _MAX_BYTES: Final[int] = 16 * 1024 * 1024 _MAX_FILES: Final[int] = 10_000 @@ -49,14 +49,14 @@ @dataclass(frozen=True, slots=True) class SourceRoot: - """Bind accepted file identities to a project-relative or external root. + """Bind accepted file identities to the canonical project sources. Attributes ---------- base: str - ``project`` or ``absolute``. + ``project``; other source-root bases are unsupported. path: str - Canonical POSIX spelling; ``.`` denotes the project root. + ``sources``; identities remain relative when the workspace moves. """ @@ -178,7 +178,7 @@ class UnresolvedSource: path: str Path whose prior assignment is retained. reason: str - ``removed``, ``root_rebound`` or ``missing_assignment``. + ``removed`` or ``missing_assignment``. """ @@ -348,27 +348,13 @@ def root_binding(value: object) -> SourceRoot: Returns ------- SourceRoot - Validated portable binding. + Validated binding to the project's ``sources`` directory. """ raw = _exact(value, "base path", "source_root") - path = _text(raw["path"], "source_root.path") - if raw["base"] == "project": - if path != ".": - canonical_path(path) - elif raw["base"] == "absolute": - posix = PurePosixPath(path) - windows = PureWindowsPath(path) - if "\\" in path or not ( - posix.is_absolute() and posix.as_posix() == path - and ".." not in posix.parts - or windows.is_absolute() and windows.as_posix() == path - and ".." not in windows.parts - ): - raise ValueError("Noncanonical absolute source root.") - else: - raise ValueError("Invalid source_root.base.") - return SourceRoot(raw["base"], path) + if raw["base"] != "project" or raw["path"] != "sources": + raise ValueError("Source root must be the project sources directory.") + return SourceRoot("project", "sources") def _identity(value: object) -> OrganizationIdentity: @@ -622,7 +608,7 @@ def parse_manifest(value: object) -> SourceManifest: row = _exact(value, "path reason", "unresolved source") path = canonical_path(row["path"]) if row["reason"] not in ( - "removed", "root_rebound", "missing_assignment" + "removed", "missing_assignment" ): raise ValueError("Invalid unresolved reason.") unresolved.append(UnresolvedSource(path, row["reason"])) diff --git a/kilin/_source_ownership.py b/kilin/_source_ownership.py new file mode 100644 index 00000000..7f2639ed --- /dev/null +++ b/kilin/_source_ownership.py @@ -0,0 +1,213 @@ +"""Validate the separate import and mirror ownership metadata. + +A canonical workspace may have cumulative import provenance in +``sources.json``, single-folder mirror provenance in +``source_snapshot.json``, or neither. Both files together are a conflict. +Missing metadata is distinct from an invalid or unsafe existing entry. + +Key Features +------------ +- Read-only ownership classification without inferring an owner's identity. +- Strict mirror provenance using the existing repository content format. + +Module Structure +---------------- +- ``source_ownership`` checks metadata entries and mutual exclusion. +- ``read_mirror_manifest`` validates the complete single-folder inventory. + +Examples +-------- +>>> from pathlib import Path +>>> from kilin._source_ownership import source_ownership +>>> kind = source_ownership(Path("/path/to/workspace")) + +""" + +from __future__ import annotations + +import json +from pathlib import Path +import stat +from typing import Literal + +from kilin._source_manifest import canonical_path, check_aliases +from kilin.repository import _manifest_files + +__all__ = [] + + +def _metadata_exists(path: Path) -> bool: + """Distinguish a missing ownership file from an unsafe existing entry. + + Parameters + ---------- + path: pathlib.Path + Expected ordinary ownership JSON file. + + Returns + ------- + bool + Whether a regular file exists at the exact requested path. + + Raises + ------ + ValueError + If the entry is a symbolic link, junction, or nonregular file. + OSError + If the entry cannot be inspected. + + """ + try: + status = path.lstat() + except FileNotFoundError: + return False + if path.is_junction() or not stat.S_ISREG(status.st_mode): + raise ValueError( + f"Source ownership metadata must be a regular file: {path.name}" + ) + return True + + +def source_ownership(root: Path) -> Literal["imports", "mirror"] | None: + """Classify safe, mutually exclusive ownership metadata entries. + + Parameters + ---------- + root: pathlib.Path + Canonical workspace root. + + Returns + ------- + str | None + ``imports``, ``mirror``, or None for a manual/empty project. + + Raises + ------ + ValueError + If both ownership files exist or either entry is unsafe. + + Notes + ----- + This checks entries, not JSON contents. Import callers also validate + ``sources.json`` with the workspace reader; mirror callers use + ``read_mirror_manifest``. Neither reader changes the ownership mode. + + """ + imports = _metadata_exists(root / "sources.json") + mirror = _metadata_exists(root / "source_snapshot.json") + if imports and mirror: + raise ValueError( + "Conflicting source ownership: sources.json and " + "source_snapshot.json cannot both exist." + ) + if imports: + return "imports" + return "mirror" if mirror else None + + +def _unique_pairs(pairs: list[tuple[str, object]]) -> dict[str, object]: + """Reject duplicate JSON keys before ownership records are interpreted. + + Parameters + ---------- + pairs: list[tuple[str, object]] + One JSON object's ordered key/value pairs. + + Returns + ------- + dict[str, object] + Mapping preserving every distinct recorded key. + + """ + result: dict[str, object] = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate mirror provenance key: {key!r}.") + result[key] = value + return result + + +def read_mirror_manifest(root: Path) -> dict[str, object]: + """Read a complete mirror inventory without repairing missing metadata. + + Parameters + ---------- + root: pathlib.Path + Canonical workspace root containing only mirror ownership. + + Returns + ------- + dict[str, object] + Validated original identity and repository content inventory. + + Raises + ------ + ValueError + If mirror ownership is absent, conflicting, or malformed. + OSError + If an existing metadata file cannot be read. + + Notes + ----- + The saved original need not currently exist. Its absolute recorded + identity remains authoritative. Missing local copies do not invalidate + their recorded ownership, and an empty file inventory is valid. + + """ + if source_ownership(root) != "mirror": + raise ValueError( + "Synchronization requires saved mirror provenance in " + "source_snapshot.json." + ) + path = root / "source_snapshot.json" + try: + value = json.loads( + path.read_text(encoding="utf-8"), object_pairs_hook=_unique_pairs, + ) + except (UnicodeError, json.JSONDecodeError) as error: + raise ValueError("Invalid mirror provenance JSON.") from error + return validate_mirror_manifest(value) + + +def validate_mirror_manifest(value: object) -> dict[str, object]: + """Check mirror provenance from either disk or a fresh complete scan. + + Parameters + ---------- + value: object + Complete original identity and repository content inventory. + + Returns + ------- + dict[str, object] + Checked mapping, unchanged and without consulting the filesystem. + + Raises + ------ + ValueError + If fields, identities, paths, or content records are invalid. + + """ + if not isinstance(value, dict) or set(value) != { + "format_version", "files", "source_directory", + }: + raise ValueError("Invalid mirror provenance fields.") + source = value["source_directory"] + if (not isinstance(source, str) or not source + or not Path(source).is_absolute() + or str(Path(source)) != source + or ".." in Path(source).parts + or "\0" in source): + raise ValueError("Invalid original directory in mirror provenance.") + files = _manifest_files(value) + for name, record in value["files"].items(): + canonical_path(name) + if set(record) != {"size_bytes", "sha256"}: + raise ValueError("Invalid mirror file record fields.") + if name.split("/", 1)[0] == ".kilin_versions": + raise ValueError("Mirror provenance cannot own retained versions.") + if any(parent.as_posix() in files + for parent in Path(name).parents if parent != Path(".")): + raise ValueError("Mirror file paths overlap their directories.") + check_aliases(files) + return value diff --git a/kilin/_tool_sources.py b/kilin/_tool_sources.py index cb52c15f..48fd590e 100644 --- a/kilin/_tool_sources.py +++ b/kilin/_tool_sources.py @@ -114,7 +114,9 @@ def bind( self.validate() inspection, inventory = self._state if not inspection.binding_matches: - raise SourceViewConflict("Source root changed; rebind first.") + raise SourceViewConflict( + "Source root does not match the project sources directory." + ) # Resolve before caching: native Path equality must not authorize # differently spelled operands on Windows. view = resolve_source_view(inspection, inventory, policy, scope) diff --git a/kilin/answering.py b/kilin/answering.py index 03964c34..7f217f8e 100644 --- a/kilin/answering.py +++ b/kilin/answering.py @@ -2015,7 +2015,7 @@ def history_messages( text is included. Thinking text is removed, and citation numbers become ``HISTORY_CITATION_MARKER``: the evidence they referred to is not in the prompt, but the answers still show the citing style. - Incomplete turns and legacy thinking-only replies are omitted as + Incomplete turns and thinking-only replies are omitted as complete question/answer pairs; stored turn numbering is unchanged. """ diff --git a/kilin/chat.py b/kilin/chat.py index 5198011f..da0bc9d4 100644 --- a/kilin/chat.py +++ b/kilin/chat.py @@ -844,14 +844,7 @@ def reply( turn_id=trace_turn_id, ): if self.backend == BACKEND_MLX: - if self.trace.enabled: - answer = self._mlx_reply( - tokens, - token_budget, - trace_turn_id=trace_turn_id, - token_callback=token_callback, - ) - elif token_callback is not None: + if token_callback is not None: answer = self._mlx_reply( tokens, token_budget, token_callback=token_callback ) @@ -1010,7 +1003,6 @@ def _mlx_reply( tokens: list[int], token_budget: int, *, - trace_turn_id: str | None = None, token_callback: Callable[[str], None] | None = None, ) -> str: """Generate one decoded reply through MLX. @@ -1021,10 +1013,6 @@ def _mlx_reply( Tokenized and formatted conversation prompt. token_budget: int Maximum number of new tokens to generate. - trace_turn_id: str | None, optional - Reserved trace identifier for parity with backend generation - helpers. The current MLX generation path does not use it directly. - Defaults to ``None``. token_callback: Callable[[str], None] | None, optional Receives each decoded text piece as it is generated. Defaults to ``None``. diff --git a/kilin/conversation_format.py b/kilin/conversation_format.py index 3ea7443c..67bc9aee 100644 --- a/kilin/conversation_format.py +++ b/kilin/conversation_format.py @@ -41,6 +41,15 @@ Construct a complete grouped conversation-session record. +- ``validate_conversation_*`` + + Validate complete persisted candidates without coercion or mutation. + +- ``decode_conversation_json`` and ``read_conversation_json`` + + Reject duplicate keys before interpreting records. Diagnostic numbers + retain their existing representation; resumable values must be finite. + The names are internal to persistence and are not exported by ``kilin``. Examples @@ -54,9 +63,19 @@ from __future__ import annotations +from datetime import datetime +from hashlib import sha256 +import json +import math +import re from typing import Final from kilin._trace_project import TRACE_FORMAT_VERSION +from kilin.answer_timeline import _timeline_from_data +from kilin.conversation_memory.models import ( + require_saved_turn_ids, + require_turn_uuid, +) __all__ = [ "CONVERSATION_SESSION_KEY", @@ -65,6 +84,12 @@ "CONVERSATION_RESUME_STATE_KEY", "new_conversation_session", "conversation_state", + "validate_conversation_state", + "validate_conversation_payload", + "validate_conversation_metadata", + "validate_conversation_turn", + "decode_conversation_json", + "read_conversation_json", ] CONVERSATION_SESSION_KEY: Final[str] = "05_conversations" @@ -73,6 +98,37 @@ CONVERSATION_RESUME_STATE_KEY: Final[str] = "resume_state" +_METADATA_FIELDS: Final[frozenset[str]] = frozenset(( + "conversation_id", "name", "parent_conversation_id", + "origin_checkpoint_id", "origin_turn_count", "created_at_utc", + "updated_at_utc", +)) +_RESUME_FIELDS: Final[frozenset[str]] = frozenset(("system_prompt", "turns")) +_CHECKPOINT_FIELDS: Final[frozenset[str]] = frozenset(( + "checkpoint_id", "parent_checkpoint_id", "conversation_sha256", + "index_fingerprint", "turn_count", +)) +_STATE_FIELDS: Final[frozenset[str]] = ( + _METADATA_FIELDS | _RESUME_FIELDS | {"checkpoint_id", "checkpoint"} +) +_TURN_FIELDS: Final[frozenset[str]] = frozenset(( + "conversation_turn_uuid", "timestamp", "question", "answer", "evidence", + "parameters", "timeline", +)) +_EVIDENCE_FIELDS: Final[frozenset[str]] = frozenset(( + "citation", "path", "start_line", "end_line", "symbol", "text", "cell", + "context_role", +)) +_ID_PATTERN: Final[re.Pattern[str]] = re.compile( + r"[A-Za-z0-9][A-Za-z0-9_-]*" +) +_UTC_TIMESTAMP_PATTERN: Final[re.Pattern[str]] = re.compile( + r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}" + r"(?:\.\d{1,6})?(?:Z|\+00:00)" +) +_SHA256_PATTERN: Final[re.Pattern[str]] = re.compile(r"[0-9a-f]{64}") + + def new_conversation_session( resume_state: dict[str, object] | None = None, ) -> dict[str, object]: @@ -129,8 +185,10 @@ def conversation_state( Notes ----- Creation does not migrate obsolete records. Both modes reject invalid - existing data before making any change. Unrelated valid trace sessions - and top-level metadata are retained. + envelopes before making any change. Unrelated trace sessions and top-level + metadata are retained. This construction helper does not validate complete + resumable state; persisted readers use ``validate_conversation_payload`` + or ``read_conversation_json`` before interpreting it. """ @@ -200,3 +258,454 @@ def conversation_state( if not isinstance(state, dict) or "chat_messages" in state: raise ValueError(invalid) return state + + +def _require_fields( + value: object, fields: frozenset[str], label: str, +) -> dict[str, object]: + """Require exactly the declared keys of one fixed persisted record. + + Parameters + ---------- + value: object + Candidate JSON mapping. + fields: frozenset[str] + Complete required key set. + label: str + Record description used in the error message. + + Returns + ------- + dict[str, object] + Original mapping, without copying or mutation. + + Raises + ------ + ValueError + If the candidate is not a mapping with exactly these fields. + + """ + + if not isinstance(value, dict) or set(value) != fields: + raise ValueError(f"The saved conversation {label} fields are invalid.") + return value + + +def validate_conversation_metadata( + state: dict[str, object], +) -> dict[str, object]: + """Require the complete current registration metadata group. + + Parameters + ---------- + state: dict[str, object] + Resumable state containing all seven registration fields. Additional + resumable fields are validated by ``validate_conversation_state``. + + Returns + ------- + dict[str, object] + A new mapping containing the validated registration fields only. + + Raises + ------ + ValueError + If metadata is missing or a field has an unsupported value. + + Notes + ----- + The whole registration group may be absent from a core-only record. + Calling this helper explicitly requires it, as the named store does. + Opaque safe identifiers and both UTC timestamp spellings remain valid. + + """ + + if not isinstance(state, dict) or not _METADATA_FIELDS <= state.keys(): + raise ValueError("The saved conversation metadata is incomplete.") + metadata = {field: state[field] for field in sorted(_METADATA_FIELDS)} + for field in ("conversation_id", "parent_conversation_id"): + value = metadata[field] + if value is None and field == "parent_conversation_id": + continue + if not isinstance(value, str) or _ID_PATTERN.fullmatch(value) is None: + raise ValueError(f"The saved conversation {field} is invalid.") + name = metadata["name"] + if not isinstance(name, str) or not name.strip() or len(name) > 80: + raise ValueError("The saved conversation name is invalid.") + origin = metadata["origin_checkpoint_id"] + if origin is not None and (not isinstance(origin, str) or not origin): + raise ValueError( + "The saved conversation origin checkpoint is invalid." + ) + count = metadata["origin_turn_count"] + if count is not None and (type(count) is not int or count < 0): + raise ValueError("The saved conversation branch point is invalid.") + for field in ("created_at_utc", "updated_at_utc"): + value = metadata[field] + if ( + not isinstance(value, str) + or _UTC_TIMESTAMP_PATTERN.fullmatch(value) is None + ): + raise ValueError("The saved conversation timestamp is invalid.") + try: + datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError as error: + raise ValueError( + "The saved conversation timestamp is invalid." + ) from error + return metadata + + +def _validate_json_value(value: object, active: set[int]) -> None: + """Reject coercible objects, cycles, and nonfinite parameter values. + + Parameters + ---------- + value: object + A candidate JSON value within the extensible parameter mapping. + active: set[int] + Identities of containers in the current recursion chain. + + Raises + ------ + ValueError + If a value cannot be represented as JSON without coercion. + + """ + + if value is None or type(value) in (str, bool, int): + return + if type(value) is float and math.isfinite(value): + return + if type(value) not in (dict, list) or id(value) in active: + raise ValueError("The saved conversation parameters are invalid.") + active.add(id(value)) + try: + if isinstance(value, dict): + for key, child in value.items(): + if not isinstance(key, str): + raise ValueError( + "The saved conversation parameter key is invalid." + ) + _validate_json_value(child, active) + else: + for child in value: + _validate_json_value(child, active) + finally: + active.remove(id(value)) + + +def _validate_evidence(value: object) -> None: + """Validate one saved evidence record without opening its source. + + Parameters + ---------- + value: object + Candidate evidence mapping with all eight current fields. + + Raises + ------ + ValueError + If a required field is missing, unknown, or has an invalid value. + + Notes + ----- + Historical source paths are descriptive references, not permission to + access the filesystem. Validation does not require sources to still exist. + + """ + + item = _require_fields(value, _EVIDENCE_FIELDS, "evidence") + for field in ("citation", "start_line", "end_line"): + number = item[field] + if type(number) is not int or number <= 0: + raise ValueError(f"The saved evidence {field} is invalid.") + if item["end_line"] < item["start_line"]: + raise ValueError("The saved evidence line range is invalid.") + path = item["path"] + if not isinstance(path, str) or not path or "\x00" in path: + raise ValueError("The saved evidence path is invalid.") + if not isinstance(item["text"], str): + raise ValueError("The saved evidence text is invalid.") + symbol = item["symbol"] + if symbol is not None and not isinstance(symbol, str): + raise ValueError("The saved evidence symbol is invalid.") + cell = item["cell"] + if cell is not None and (type(cell) is not int or cell <= 0): + raise ValueError("The saved evidence cell is invalid.") + role = item["context_role"] + if role is not None and ( + not isinstance(role, str) + or role not in ("direct", "related", "alternative") + ): + raise ValueError("The saved evidence context_role is invalid.") + + +def validate_conversation_turn(value: object) -> dict[str, object]: + """Validate a complete saved turn before reconstructing typed objects. + + Parameters + ---------- + value: object + Candidate turn mapping containing the seven required current fields. + + Returns + ------- + dict[str, object] + The original validated mapping. + + Raises + ------ + ValueError + If identity, text, evidence, parameters, or timing is invalid. + + Notes + ----- + Explicit null timing is valid. Missing timing is not an untimed turn. + Parameter keys vary by execution path, so only JSON structure is fixed. + + """ + + if not isinstance(value, dict): + raise ValueError("The saved conversation turn is invalid.") + require_turn_uuid(value.get("conversation_turn_uuid")) + turn = _require_fields(value, _TURN_FIELDS, "turn") + for field in ("timestamp", "question", "answer"): + if not isinstance(turn[field], str): + raise ValueError(f"The saved conversation {field} is invalid.") + evidence = turn["evidence"] + if not isinstance(evidence, list): + raise ValueError("Saved evidence must be a list.") + for item in evidence: + _validate_evidence(item) + parameters = turn["parameters"] + if not isinstance(parameters, dict): + raise ValueError("Saved parameters must be a mapping.") + _validate_json_value(parameters, set()) + timeline = turn["timeline"] + if timeline is not None: + _require_fields(timeline, frozenset(("elapsed_ms", "steps")), + "timeline") + if isinstance(timeline["steps"], list): + for step in timeline["steps"]: + _require_fields(step, frozenset(("phase", "label", "ms")), + "timeline step") + _timeline_from_data(timeline) + return turn + + +def _validate_checkpoint(state: dict[str, object]) -> None: + """Verify saved checkpoint identity, count, and conversation content. + + Parameters + ---------- + state: dict[str, object] + Validated resumable fields with both checkpoint fields present. + + Raises + ------ + ValueError + If the checkpoint has invalid structure or describes different turns. + + Notes + ----- + The checkpoint identifier also depends on original runtime data that is + not persisted here. Only the saved conversation content hash can be + recomputed, using precisely the existing writer's serialization. + + """ + + checkpoint = _require_fields(state["checkpoint"], _CHECKPOINT_FIELDS, + "checkpoint") + identifier = state["checkpoint_id"] + if not isinstance(identifier, str) or not identifier or ( + checkpoint["checkpoint_id"] != identifier + ): + raise ValueError("The saved conversation checkpoint ID is invalid.") + parent = checkpoint["parent_checkpoint_id"] + if parent is not None and (not isinstance(parent, str) or not parent): + raise ValueError( + "The saved conversation parent checkpoint is invalid." + ) + if not isinstance(checkpoint["index_fingerprint"], str): + raise ValueError("The saved checkpoint index fingerprint is invalid.") + count = checkpoint["turn_count"] + if type(count) is not int or count != len(state["turns"]): + raise ValueError("The saved conversation checkpoint count is invalid.") + digest = checkpoint["conversation_sha256"] + if ( + not isinstance(digest, str) + or _SHA256_PATTERN.fullmatch(digest) is None + ): + raise ValueError("The saved conversation checkpoint hash is invalid.") + saved = {"system_prompt": state["system_prompt"], "turns": state["turns"]} + actual = sha256(json.dumps( + saved, sort_keys=True, ensure_ascii=False, allow_nan=False, + ).encode("utf-8")).hexdigest() + if digest != actual: + raise ValueError("The saved conversation checkpoint hash is invalid.") + + +def validate_conversation_state(value: object) -> dict[str, object]: + """Require one complete current lifecycle state without altering it. + + Parameters + ---------- + value: object + Candidate resumable-state mapping. Registration and resumable history + are independent optional groups; each present group must be complete. + + Returns + ------- + dict[str, object] + The original validated state mapping. + + Raises + ------ + ValueError + If a group is partial, a field is invalid, or a checkpoint disagrees + with its saved conversation content. + + Notes + ----- + Empty, metadata-only, and core-only states are valid. A state with saved + history may omit checkpoint fields, as a truncated branch does. Present + checkpoint fields must form a complete consistent pair. Diagnostics are + independent and cannot supply missing persisted fields. + + """ + + if not isinstance(value, dict) or not value.keys() <= _STATE_FIELDS: + raise ValueError("The saved conversation state fields are invalid.") + if value.keys() & _METADATA_FIELDS: + validate_conversation_metadata(value) + has_resume = bool(value.keys() & _RESUME_FIELDS) + if has_resume: + if not _RESUME_FIELDS <= value.keys(): + raise ValueError( + "The saved conversation resume fields are invalid." + ) + if not isinstance(value["system_prompt"], str): + raise ValueError( + "The saved conversation system prompt is invalid." + ) + require_saved_turn_ids(value["turns"]) + for turn in value["turns"]: + validate_conversation_turn(turn) + checkpoints = {"checkpoint", "checkpoint_id"} & value.keys() + if checkpoints: + if not has_resume or len(checkpoints) != 2: + raise ValueError("The saved conversation checkpoint is invalid.") + _validate_checkpoint(value) + return value + + +def validate_conversation_payload( + payload: dict[str, object], +) -> dict[str, object]: + """Locate and validate persisted state in its canonical envelope. + + Parameters + ---------- + payload: dict[str, object] + Decoded complete conversation document. + + Returns + ------- + dict[str, object] + Validated state by reference, without modifying the document. + + Raises + ------ + ValueError + If either the envelope or resumable state is invalid. + + """ + + return validate_conversation_state(conversation_state(payload)) + + +def _unique_json_object(pairs: list[tuple[str, object]]) -> dict[str, object]: + """Reject repeated JSON object keys before a parser can discard values. + + Parameters + ---------- + pairs: list[tuple[str, object]] + Ordered pairs supplied by the JSON decoder. + + Returns + ------- + dict[str, object] + Mapping with every supplied key represented once. + + Raises + ------ + ValueError + If any key occurs more than once. + + """ + + result: dict[str, object] = {} + for key, value in pairs: + if key in result: + raise ValueError("The saved conversation has duplicate JSON keys.") + result[key] = value + return result + + +def decode_conversation_json(text: str) -> dict[str, object]: + """Decode a JSON object without discarding duplicate key values. + + Parameters + ---------- + text: str + Complete UTF-8-decoded document text. + + Returns + ------- + dict[str, object] + Parsed document. Its lifecycle schema is not interpreted here. + Diagnostic nonfinite numbers retain the current trace representation. + + Raises + ------ + ValueError + If JSON is invalid, has duplicate keys, or is not an object. + + """ + + try: + payload = json.loads( + text, object_pairs_hook=_unique_json_object, + ) + except json.JSONDecodeError as error: + raise ValueError("The saved conversation JSON is invalid.") from error + if not isinstance(payload, dict): + raise ValueError("The saved conversation is invalid.") + return payload + + +def read_conversation_json(text: str) -> dict[str, object]: + """Decode and validate a complete current conversation document. + + Parameters + ---------- + text: str + Complete UTF-8-decoded document text. + + Returns + ------- + dict[str, object] + Newly decoded document with validated resumable state. Numeric + diagnostics are independent; nonfinite resumable values are rejected. + + Raises + ------ + ValueError + If JSON, the grouped envelope, or persisted state is invalid. + + """ + + payload = decode_conversation_json(text) + validate_conversation_payload(payload) + return payload diff --git a/kilin/conversation_memory/index.py b/kilin/conversation_memory/index.py index 47913df8..8aa592c0 100644 --- a/kilin/conversation_memory/index.py +++ b/kilin/conversation_memory/index.py @@ -58,7 +58,10 @@ from typing import Final from kilin.answering import strip_thinking -from kilin.conversation_format import conversation_state +from kilin.conversation_format import ( + conversation_state, + read_conversation_json, +) from kilin.conversation_memory.feedback import FeedbackSnapshot, FeedbackStore from kilin.conversation_memory.models import require_saved_turn_ids from kilin.conversation_memory.persistence import ( @@ -80,9 +83,10 @@ _MAX_MESSAGE_CHARS: Final[int] = 12_000 _BATCH_SIZE: Final[int] = 24 _WORDS: Final[re.Pattern[str]] = re.compile(r"\s+") -# A diagnostics-only checkpoint edit changes file metadata but not memory. -# Cache only that verified observation, never records or source text. A new -# process may recheck once; no persistent sidecar or index rewrite is needed. +# Validate each newly observed conversation snapshot in this process, even +# when it matches a persisted index. Cache only that verified observation, +# never records or source text. Diagnostic edits can then reuse vectors +# without rewriting an otherwise current index. _OBSERVED_MANIFESTS: OrderedDict[ tuple[str, str], tuple[ tuple[tuple[str, int, int], ...], str, str, tuple[int, int] @@ -336,7 +340,7 @@ def _read_records( ] = {} for name, _, _ in manifest: path = root / "logs" / "traces" / name - payload = json.loads(path.read_text(encoding="utf-8")) + payload = read_conversation_json(path.read_text(encoding="utf-8")) record = conversation_state(payload) turns = record.get("turns", []) ids = require_saved_turn_ids(turns) @@ -344,15 +348,9 @@ def _read_records( if not isinstance(conversation_id, str) or not conversation_id: raise ValueError("The conversation identifier is invalid.") for number, (turn, turn_uuid) in enumerate(zip(turns, ids), 1): - if not isinstance(turn, dict): - raise ValueError("The saved conversation turn is invalid.") - params = turn.get("parameters", {}) - if not isinstance(params, dict): - raise ValueError("The saved memory parameters are invalid.") + params = turn["parameters"] intent = params.get("intent") - timestamp = turn.get("timestamp") - if not isinstance(timestamp, str) or not timestamp: - raise ValueError("The saved memory timestamp is invalid.") + timestamp = turn["timestamp"] for role, field in (("user", "question"), ("assistant", "answer")): if role == "assistant" and params.get("completion"): @@ -362,9 +360,7 @@ def _read_records( ) if not eligible: continue - raw_text = turn.get(field) - if not isinstance(raw_text, str): - raise ValueError("The saved memory text is invalid.") + raw_text = turn[field] text = ( strip_thinking(raw_text) if role == "assistant" else raw_text @@ -546,13 +542,6 @@ def synchronize_memory( (index_stat.st_size, index_stat.st_mtime_ns) if index_stat is not None else (-1, -1) ) - if ( - saved is not None and previous is not None - and saved["manifest"] == [list(item) for item in manifest] - and saved["policy_digest"] == digest - and saved["feedback_revision"] == feedback.revision - ): - return previous if ( previous is not None and _OBSERVED_MANIFESTS.get(cache_key) == ( @@ -639,6 +628,14 @@ def synchronize_memory( "vectors": {key: list(value) for key, value in vectors.items()}, } write_memory_index(path, content) + written_stat = path.stat() + _OBSERVED_MANIFESTS[cache_key] = ( + manifest, digest, feedback.revision, + (written_stat.st_size, written_stat.st_mtime_ns), + ) + _OBSERVED_MANIFESTS.move_to_end(cache_key) + if len(_OBSERVED_MANIFESTS) > _MAX_OBSERVED_PROJECTS: + _OBSERVED_MANIFESTS.popitem(last=False) return MemoryIndex( model_identity, records, vectors, changed=True, embedded_count=len(missing), diff --git a/kilin/conversation_memory/inspection.py b/kilin/conversation_memory/inspection.py index b6256584..835c86c7 100644 --- a/kilin/conversation_memory/inspection.py +++ b/kilin/conversation_memory/inspection.py @@ -36,13 +36,13 @@ from __future__ import annotations from dataclasses import dataclass -import json from pathlib import Path from kilin.answering import strip_thinking from kilin.conversation_format import ( CONVERSATION_SESSION_KEY, conversation_state, + read_conversation_json, ) from kilin.conversation_memory.feedback import FeedbackStore from kilin.conversation_memory.index import _eligible, _manifest @@ -125,7 +125,7 @@ def inspect_memory_messages( originals: dict[tuple[str, str], tuple[str, str]] = {} for name, _, _ in _manifest(root): path = root / "logs" / "traces" / name - record = conversation_state(json.loads( + record = conversation_state(read_conversation_json( path.read_text(encoding="utf-8") )) conversation_id = record.get("conversation_id", path.stem) @@ -138,18 +138,13 @@ def inspect_memory_messages( for number, (turn, identifier) in enumerate( zip(turns, identities), start=1 ): - params = turn.get("parameters", {}) - timestamp = turn.get("timestamp") - if (not isinstance(params, dict) - or not isinstance(timestamp, str) or not timestamp): - raise ValueError("The saved memory turn is invalid.") + params = turn["parameters"] + timestamp = turn["timestamp"] for role, field in (("user", "question"), ("assistant", "answer")): if role == "assistant" and params.get("completion"): continue - text = turn.get(field) - if not isinstance(text, str): - raise ValueError("The saved memory text is invalid.") + text = turn[field] text = ( strip_thinking(text) if role == "assistant" else text ).strip() @@ -200,58 +195,109 @@ def inspect_memory_messages( ) -def _trace_answer_summary( - payload: dict[str, object], number: int -) -> str | None: - """Read the current, potentially edited summary from a trace turn. +def _trace_operations( + trace_turn: object, stage: str, +) -> dict[str, object]: + """Read a diagnostic stage's operations without requiring completeness. + + Parameters + ---------- + trace_turn: object + One grouped diagnostic turn, potentially incomplete. + stage: str + Canonical readable stage key. + + Returns + ------- + dict[str, object] + Operations in the stage, or an empty mapping if unavailable. + + """ + + stages = ( + trace_turn.get("stages") if isinstance(trace_turn, dict) else None + ) + group = stages.get(stage) if isinstance(stages, dict) else None + operations = group.get("operations") if isinstance(group, dict) else None + return operations if isinstance(operations, dict) else {} + + +def _trace_answer_summaries( + payload: dict[str, object], +) -> dict[str, str]: + """Associate full diagnostic summaries with committed turn identities. Parameters ---------- payload: dict[str, object] Entire conversation trace, including grouped diagnostic operations. - number: int - One-based position of the requested saved turn. Returns ------- - str | None - The complete trace summary (including a deliberately emptied one), - or None if the operation is absent (for example, on a branch). + dict[str, str] + Summaries keyed by unambiguously committed conversation turn UUID, + including deliberately emptied summaries. Missing or ambiguous + associations are omitted so the caller can use saved representations. + + Notes + ----- + Diagnostic turn numbers also count failed attempts and need not match + saved turn positions, especially in branches or after reopening a file. + Only a completed checkpoint event establishes a diagnostic association. """ sessions = payload.get("sessions", {}) if not isinstance(sessions, dict): - return None + return {} session = sessions.get(CONVERSATION_SESSION_KEY, {}) if not isinstance(session, dict): - return None + return {} turns = session.get("turns", {}) if not isinstance(turns, dict): - return None - trace_turn = turns.get(f"turn_{number:04d}", {}) - if not isinstance(trace_turn, dict): - return None - stages = trace_turn.get("stages", {}) - if not isinstance(stages, dict): - return None - question = stages.get("01_question", {}) - if not isinstance(question, dict): - return None - operations = question.get("operations", {}) - if not isinstance(operations, dict): - return None - for key, operation in reversed(list(operations.items())): - if not key.endswith("_conversation_turn_representation"): - continue - details = operation.get("details", {}) if isinstance( - operation, dict - ) else {} - if isinstance(details, dict) and isinstance( - details.get("summary"), str - ): - return details["summary"] - return None + return {} + + summaries: dict[str, str] = {} + seen: set[str] = set() + for trace_turn in turns.values(): + identifiers: list[str] = [] + generation = _trace_operations(trace_turn, "05_generation") + for operation in generation.values(): + if not isinstance(operation, dict): + continue + event = operation.get("event") + details = operation.get("details") + if (not isinstance(event, dict) + or event.get("event_type") != ( + "state.checkpoint.committed" + ) + or event.get("status") != "completed" + or not isinstance(details, dict) + or details.get("immutable_state_saved") is not True): + continue + identifier = details.get("conversation_turn_uuid") + if isinstance(identifier, str): + identifiers.append(identifier) + # A diagnostic turn must identify exactly one committed answer. + # Conflicting or repeated associations must not choose a summary. + for identifier in identifiers: + if identifier in seen or len(identifiers) != 1: + summaries.pop(identifier, None) + else: + operations = _trace_operations(trace_turn, "01_question") + for key, operation in reversed(list(operations.items())): + if not key.endswith("_conversation_turn_representation"): + continue + details = operation.get("details", {}) if isinstance( + operation, dict + ) else {} + if isinstance(details, dict) and isinstance( + details.get("summary"), str + ): + summaries[identifier] = details["summary"] + break + seen.add(identifier) + return summaries def read_memory_summaries( @@ -272,7 +318,8 @@ def read_memory_summaries( list[dict[str, str]] One entry per accessible message, with ``turn_uuid``, ``role`` and untruncated ``text``. Question text comes from the checkpoint; - answer summaries prefer the trace's representation operation. + answer summaries prefer the representation associated with the + committed turn UUID in the trace. Raises ------ @@ -282,9 +329,10 @@ def read_memory_summaries( Notes ----- A trace is read on every invocation, without embedding or model calls. - Inherited branch checkpoints can lack the original diagnostic operation; - the saved compact representation then provides a legacy fallback. - No summary is written to message provenance or another cache. + Diagnostic associations are resolved once per trace during the request. + Inherited branch checkpoints and incomplete recordings can lack an + unambiguous association; the saved compact representation then supplies + the available summary. No summary is persisted in another cache. """ @@ -292,6 +340,7 @@ def read_memory_summaries( raise ValueError("Invalid memory summary request.") available = {item.conversation_id for item in store.conversations()} snapshots: dict[str, dict[str, object] | None] = {} + trace_summaries: dict[str, dict[str, str]] = {} results: list[dict[str, str]] = [] for reference in references: if not isinstance(reference, dict) or set(reference) != { @@ -323,7 +372,7 @@ def read_memory_summaries( if path.is_symlink() or not path.is_file(): snapshots[name] = None else: - snapshots[name] = json.loads( + snapshots[name] = read_conversation_json( path.read_text(encoding="utf-8") ) payload = snapshots[name] @@ -336,19 +385,16 @@ def read_memory_summaries( continue turn = turns[number - 1] if role == "user": - question = turn.get("question") - if isinstance(question, str): - current = question - break + current = turn["question"] + break else: - current = _trace_answer_summary(payload, number) + if name not in trace_summaries: + trace_summaries[name] = _trace_answer_summaries(payload) + current = trace_summaries[name].get(identifier) if current is not None: break - params = turn.get("parameters", {}) - representation = ( - params.get("representation", {}) - if isinstance(params, dict) else {} - ) + params = turn["parameters"] + representation = params.get("representation", {}) if isinstance(representation, dict): value = representation.get("summary") if isinstance(value, str) and value: diff --git a/kilin/conversation_memory/models.py b/kilin/conversation_memory/models.py index 10cc6951..21319553 100644 --- a/kilin/conversation_memory/models.py +++ b/kilin/conversation_memory/models.py @@ -153,8 +153,8 @@ def require_saved_turn_ids(turns: object) -> tuple[str, ...]: Notes ----- - This is not a migration or a full answer/evidence parser. It ensures - branches cannot duplicate an obsolete identity-less checkpoint. + This checks turn identities without parsing full answers or evidence. + Branches require a present and distinct identity for every saved turn. """ diff --git a/kilin/conversations.py b/kilin/conversations.py index 2e07082f..b8d3efec 100644 --- a/kilin/conversations.py +++ b/kilin/conversations.py @@ -62,6 +62,7 @@ from dataclasses import asdict, dataclass, replace from datetime import datetime, timezone import json +import logging from pathlib import Path import re from uuid import uuid4 @@ -74,16 +75,16 @@ ) from kilin.conversation_format import ( CONVERSATION_SESSION_KEY, - conversation_state, + decode_conversation_json, new_conversation_session, + validate_conversation_metadata, + validate_conversation_payload, + validate_conversation_state, ) __all__ = ["ConversationInfo", "ConversationStore"] -# Accept existing opaque IDs as well as generated ``conversation_`` IDs. -# Do not constrain loaded IDs to the generated UUID format: older records and -# imported conversations may use other alphanumeric identifiers. -_ID_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]*") +_LOGGER = logging.getLogger(__name__) # A branch's name, "Branch: " or "Branch 2: ", starts with this. _BRANCH_PREFIX_PATTERN = re.compile(r"Branch(?: \d+)?: ") @@ -124,7 +125,7 @@ class ConversationInfo: Last metadata-update timestamp as an ISO 8601 UTC string. origin_turn_count: int | None Number of the parent's turns a branch kept, or None for a new - independent conversation and records saved before branch points. + independent conversation. The field is always persisted explicitly. Attributes ---------- @@ -146,7 +147,7 @@ class ConversationInfo: Last metadata-update timestamp as an ISO 8601 UTC string. origin_turn_count: int | None Number of the parent's turns a branch kept, or None for a new - independent conversation and records saved before branch points. + independent conversation. The field is always persisted explicitly. """ @@ -203,6 +204,8 @@ class ConversationStore: Resolve the registered file path of a conversation. contains_turn(conversation_id, turn_uuid) Check whether an active saved conversation contains a turn. + discovery_errors() + Return rejected paths and their validation errors from the last scan. Notes ----- @@ -229,6 +232,7 @@ def __init__(self, project_directory: str | Path) -> None: self._items: dict[str, ConversationInfo] = {} self._paths: dict[str, Path] = {} self._active_id: str | None = None + self._discovery_errors: dict[Path, str] = {} def ensure(self) -> ConversationInfo: """Scan conversation files and select the most recently updated one. @@ -242,23 +246,36 @@ def ensure(self) -> ConversationInfo: Raises ------ ValueError - If the traces directory itself is a symbolic link. + If the traces directory is a symbolic link, or existing invalid + records leave no valid registered conversation to select. OSError If storage cannot be created, scanned, or written. Notes ----- Discovery skips invalid records and duplicate identifiers after their - first discovered path. Existing records are ordered by updated - timestamp and identifier when selecting the active one. + first discovered path, retaining their errors for inspection. Invalid + files never trigger an automatic empty replacement. Valid core-only + files do not register a name and remain independent of this catalog. + Existing records are ordered by updated timestamp and identifier + when selecting the active one. """ self.root.mkdir(parents=True, exist_ok=True) if self.root.is_symlink(): raise ValueError("The traces folder must not be a link.") + previous_items = dict(self._items) + previous_paths = dict(self._paths) self._scan() if not self._items: + if self._discovery_errors: + self._items = previous_items + self._paths = previous_paths + raise ValueError( + "Existing saved conversations are invalid; no empty " + "conversation was created." + ) return self.create() newest = max( self._items.values(), @@ -328,6 +345,7 @@ def select(self, conversation_id: str) -> ConversationInfo: """ item = self._require(conversation_id) + self._registered_state(item) self._active_id = item.conversation_id return item @@ -409,15 +427,9 @@ def create( with conversation_write_ownership( parent_path, ownership=ownership ): - saved = conversation_state(_read_json(parent_path)) + saved = self._registered_state(parent) checkpoint = saved.get("checkpoint_id") - checkpoint = ( - checkpoint - if isinstance(checkpoint, str) and checkpoint - else None - ) turns = saved.get("turns", []) - require_saved_turn_ids(turns) kept = len(turns) if turn_count is None else turn_count if ( isinstance(kept, bool) @@ -442,6 +454,8 @@ def create( item = replace( item, origin_checkpoint_id=checkpoint, origin_turn_count=kept ) + candidate = {**asdict(item), **copied_state} + validate_conversation_state(candidate) with conversation_write_ownership(path): if path.exists(): raise FileExistsError( @@ -452,7 +466,7 @@ def create( { "sessions": { CONVERSATION_SESSION_KEY: new_conversation_session( - {**asdict(item), **copied_state} + candidate ) } }, @@ -582,12 +596,8 @@ def is_empty(self, conversation_id: str) -> bool: """ item = self._require(conversation_id) - record = conversation_state(_read_json(self.state_path(item))) - turns = record.get("turns", []) - if not isinstance(turns, list): - raise ValueError("The saved conversation is invalid.") - - return not turns + record = self._registered_state(item) + return not record.get("turns", []) def archive( self, @@ -640,7 +650,6 @@ def archive( item = self._require(conversation_id) source = self.state_path(item) deleted = self.root / ".deleted" - deleted.mkdir(parents=True, exist_ok=True) if deleted.is_symlink(): raise ValueError( "The deleted-conversations folder must not be a link." @@ -649,6 +658,9 @@ def archive( with conversation_write_ownership( source, ownership=ownership ): + source.stat() + self._registered_state(item) + deleted.mkdir(parents=True, exist_ok=True) destination = deleted / source.name number = 2 while destination.exists(): @@ -702,13 +714,32 @@ def contains_turn(self, conversation_id: str, turn_uuid: str) -> bool: """ + known_path = self._paths.get(conversation_id) + if known_path is not None and known_path.exists(): + saved = self._registered_state(self._items[conversation_id]) + return turn_uuid in require_saved_turn_ids(saved.get("turns", [])) self._scan() if conversation_id not in self._items: + if known_path in self._discovery_errors: + raise ValueError(self._discovery_errors[known_path]) return False - path = self._paths[conversation_id] - saved = conversation_state(_read_json(path)) + saved = self._registered_state(self._items[conversation_id]) return turn_uuid in require_saved_turn_ids(saved.get("turns", [])) + def discovery_errors(self) -> dict[Path, str]: + """Return validation errors for paths excluded by the last scan. + + Returns + ------- + dict[pathlib.Path, str] + Independent mapping of rejected regular files and duplicate IDs + to their error messages. Valid unregistered core records are not + errors. Calling this method performs no filesystem access. + + """ + + return dict(self._discovery_errors) + def state_path(self, conversation: ConversationInfo | str) -> Path: """Resolve the registered file path of a conversation. @@ -741,27 +772,70 @@ def state_path(self, conversation: ConversationInfo | str) -> Path: def _scan(self) -> None: """Rebuild the registry from recognizable conversation files. - Symbolic links, non-files, malformed JSON/state, missing metadata, and - duplicate identifiers after the first are skipped. Persisted metadata - is validated before records enter the registry. + Symbolic links, non-files, and valid core-only records are ignored. + Invalid saved state and duplicate identifiers after the first are + reported and skipped. Whole records are validated before registration. """ + previous_errors = self._discovery_errors self._items.clear() self._paths.clear() + self._discovery_errors = {} for path in sorted(self.root.glob("conversation_*.json")): if path.is_symlink() or not path.is_file(): continue try: - record = conversation_state(_read_json(path)) + record = validate_conversation_payload(_read_json(path)) if not isinstance(record, dict): + raise ValueError("The saved conversation is invalid.") + if "conversation_id" not in record: + # A valid core-only record has no named registration. continue item = _validated_metadata(record) - except (KeyError, TypeError, ValueError): + if item.conversation_id in self._items: + raise ValueError( + "The saved conversation ID duplicates another file." + ) + except (KeyError, TypeError, ValueError) as error: + message = str(error) + self._discovery_errors[path] = message + if previous_errors.get(path) != message: + _LOGGER.warning("Skipping conversation %s: %s", + path.name, message) continue - if item.conversation_id not in self._items: - self._items[item.conversation_id] = item - self._paths[item.conversation_id] = path + self._items[item.conversation_id] = item + self._paths[item.conversation_id] = path + + def _registered_state( + self, item: ConversationInfo, + ) -> dict[str, object]: + """Validate a registered file before selection or mutation. + + Parameters + ---------- + item: ConversationInfo + Cached metadata identifying the intended file. + + Returns + ------- + dict[str, object] + Complete validated saved state for this registration. + + Raises + ------ + ValueError + If the file is invalid or its identity changed after discovery. + + """ + + state = validate_conversation_payload( + _read_json(self._paths[item.conversation_id]) + ) + saved = _validated_metadata(state) + if saved.conversation_id != item.conversation_id: + raise ValueError("The saved conversation registration is invalid.") + return state def _update_metadata( self, @@ -806,8 +880,14 @@ def _update_metadata( ) with conversation_write_ownership(path, ownership=ownership): payload = _read_json(path) - conversation = conversation_state(payload, create=True) + conversation = validate_conversation_payload(payload) + saved = _validated_metadata(conversation) + if saved.conversation_id != item.conversation_id: + raise ValueError( + "The saved conversation registration is invalid." + ) changes = asdict(item) + validate_conversation_state({**conversation, **changes}) if state_writer is None: conversation.update(changes) _write_json(path, payload) @@ -912,8 +992,7 @@ def _checkpoint_id(path: Path) -> str | None: Returns ------- str | None - Nonempty checkpoint string, or None if the field is absent or - invalid. + Nonempty checkpoint string, or None if the pair is absent. Raises ------ @@ -922,9 +1001,8 @@ def _checkpoint_id(path: Path) -> str | None: """ - record = conversation_state(_read_json(path)) - value = record.get("checkpoint_id") - return value if isinstance(value, str) and value else None + record = validate_conversation_payload(_read_json(path)) + return record.get("checkpoint_id") def _utc_datetime(value: object) -> datetime: @@ -982,63 +1060,13 @@ def _validated_metadata(record: dict[str, object]) -> ConversationInfo: Notes ----- Extra fields belong to saved RAG state and are retained in the JSON. - Records saved before branch points have no ``origin_turn_count``. + Every registration field, including nullable branch identity, is required. Validation never rewrites, repairs, or deletes an invalid file. Discovery skips invalid records so other conversations remain accessible. """ - try: - metadata = { - field: record[field] - for field in ConversationInfo.__dataclass_fields__ - if field != "origin_turn_count" - } - except KeyError as error: - raise ValueError( - "The saved conversation metadata is incomplete." - ) from error - - identifier = metadata["conversation_id"] - if ( - not isinstance(identifier, str) - or _ID_PATTERN.fullmatch(identifier) is None - ): - raise ValueError("The saved conversation ID is invalid.") - - name = metadata["name"] - if ( - not isinstance(name, str) - or not name.strip() - or len(name) > 80 - ): - raise ValueError("The saved conversation name is invalid.") - - parent = metadata["parent_conversation_id"] - if ( - parent is not None - and ( - not isinstance(parent, str) - or _ID_PATTERN.fullmatch(parent) is None - ) - ): - raise ValueError("The saved conversation parent ID is invalid.") - - origin = metadata["origin_checkpoint_id"] - if origin is not None and (not isinstance(origin, str) or not origin): - raise ValueError("The saved conversation checkpoint is invalid.") - - turn_count = record.get("origin_turn_count") - if turn_count is not None and ( - isinstance(turn_count, bool) - or not isinstance(turn_count, int) - or turn_count < 0 - ): - raise ValueError("The saved conversation branch point is invalid.") - - _utc_datetime(metadata["created_at_utc"]) - _utc_datetime(metadata["updated_at_utc"]) - return ConversationInfo(**metadata, origin_turn_count=turn_count) + return ConversationInfo(**validate_conversation_metadata(record)) def _read_json(path: Path) -> dict[str, object]: @@ -1063,8 +1091,8 @@ def _read_json(path: Path) -> dict[str, object]: """ try: - payload = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as error: + payload = decode_conversation_json(path.read_text(encoding="utf-8")) + except OSError as error: raise ValueError("The saved conversation is invalid.") from error if not isinstance(payload, dict): raise ValueError("The saved conversation is invalid.") @@ -1100,7 +1128,9 @@ def _write_json(path: Path, payload: object) -> None: path.parent.mkdir(parents=True, exist_ok=True) atomic_write_text( - path, json.dumps(payload, indent=2, ensure_ascii=False) + "\n" + path, json.dumps( + payload, indent=2, ensure_ascii=False, allow_nan=False, + ) + "\n" ) diff --git a/kilin/gui/README.md b/kilin/gui/README.md index 2cfba845..f1bd0b43 100644 --- a/kilin/gui/README.md +++ b/kilin/gui/README.md @@ -72,10 +72,14 @@ and converts bridge calls into JSON-line commands. Engine responses are relayed to JavaScript as JSON events. Unexpected diagnostic output is kept separate from protocol messages where the bridge implements that handling. -`engine.py` handles commands synchronously, invokes KíLín's APIs, and emits -project, progress, answer, reference, and failure events. `model_catalog.py` -contains suggested model records and distribution-presence checks. A cache -entry or an installed distribution is not proof that a model can load or run. +`engine.py` processes ordinary commands sequentially, invokes KíLín's APIs, +and emits project, progress, answer, reference, and failure events. A +separate input thread signals cooperative answer cancellation even while +answer generation is busy. Successful cooperative cancellation retains +loaded models; a process-level stop terminates the engine instead. +`model_catalog.py` contains suggested model records and distribution-presence +checks. A cache entry or an installed distribution is not proof that a +model can load or run. For the existing GUI command/event names, payloads, and recovery rules, see [the desktop protocol reference](../../docs/gui_protocol.md). @@ -186,11 +190,10 @@ creates it. A chosen folder that is missing or not mounted is skipped with a note, and setup asks again. Changing it restarts the engine, so it is offered only on the start screen. Existing projects are never moved. -Browse can explicitly select any existing projects folder, including a folder -used by an earlier installation. KíLín does not search former default -locations or migrate their project files. Projects must satisfy the current -profile and workspace format. A saved choice (or `KILIN_WORKSPACES_DIR`) -remains authoritative. +Browse can explicitly select any existing projects folder. Projects must +satisfy the current profile and workspace format. KíLín does not search +other locations or automatically convert project files. A saved choice +(or `KILIN_WORKSPACES_DIR`) remains authoritative. Cancelling Browse and failures when choosing a folder return to setup so the user can choose again. @@ -272,7 +275,8 @@ dependency is disconnected. disable). Disabling removes that rule from the declaration; restore it in Advanced settings or explicitly adopt the installed type's declarations. Advanced settings retain relationship types, rule definitions, explicit - JSON mappings, detector adoption and deliberate source-root rebinding. + JSON mappings and detector adoption. All project sources use `sources/`; + the editor does not support changing the source root. The core validates all declaration fields against the [source organization schema](../../docs/PROJECT_TYPE_SCHEMA.md#source-organization-declarations). - Review the ordered staged changes and choose **Preview / reconcile**. The @@ -292,14 +296,15 @@ to use their existing physical workflows. ## Project types -Project types live in `kilin/project_types/`, one JSON file per type -(currently `code.json`, `creative_brainstorming.json`, +The six bundled project types live in `kilin/project_types/`, one JSON +file per type (`code.json`, `creative_brainstorming.json`, `grounded_brainstorming.json`, `literature.json`, `reviewing.json`, -and `writing.json`). The filename is the type ID; types -are listed in filename order. After renaming the creative type to -`creative_brainstorming`, `code` is the first (new-project default) type. -Legacy saved creative projects need the explicit migration described in -[Project workspaces](../../docs/project_workspaces.md). Each file sets the display name shown in the +and `writing.json`). The filename stem is the type ID. The desktop app +lists available types in catalog order and initially selects the first +one. Saved projects retain their configured type ID; unknown or +unavailable types are reported without modifying the workspace. See +[Project workspaces](../../docs/project_workspaces.md) for the workspace +contract. Each definition sets the display name shown in the type menu, a one-line description (shown to the router), default file suffixes and size limit for new projects, the retrieval instruction added to Qwen3-format embedding queries, the base system prompt, the answer @@ -322,8 +327,10 @@ the router model, which subsequent empty chats reuse. Source phrases must occur in the indexed files, and document-oriented project types prioritize documents when source files contain both documents and code. Custom welcome prompts and suggested questions saved in the project settings always take -precedence over generated text. Existing saved pools from older formats -are generated again when explicitly needed. +precedence over generated text. Saved pools are reused only when their +format and dependency fingerprint match. Missing, invalid or outdated +pools are regenerated when explicitly requested and a model and indexed +sources are available. Each intent has a description, a system prompt added to the base prompt, an optional answer guidance that replaces the type's (and always applies, also @@ -426,9 +433,9 @@ for light, `icons/kilin-dark.png` for dark, and the operating system's color scheme for System. Missing icon files leave Qt's default icon. The welcome screen displays the locally packaged, full-body Gaudí-inspired mosaic qilin (dragon head, deer body, cow tail). -In an open project, the sidebar now shows the full mascot alone, -without a separate wordmark, while the welcome card continues to -use the refined vector KíLín logotype with evenly spaced letters +In an open project, the sidebar shows the full mascot alone, +without a separate wordmark, while the welcome card uses the +vector KíLín logotype with evenly spaced letters and tapered accents above both i characters. Dark mode keeps the vivid ceramic colors against navy surfaces. The window and Dock use a close-up of the dragon head; `icons/README.md` documents the @@ -572,11 +579,11 @@ settings remain authoritative: later changes to packaged defaults or user preferences affect new projects, not existing ones. To change an existing project's choices, use Settings rather than deleting its saved profile. -Historical `effort_levels.json` and `model_choices.json` files are ignored -and left untouched. Back up these files and transfer any desired old choices -explicitly through Settings. An effort-level record contains only `name` and -`model`; retrieval depth is configured separately. Changing a language -model does not rebuild the index; +Saved project effort levels and model choices are read from `profile.ini`. +Any `effort_levels.json` or `model_choices.json` files are left untouched; +use Settings to enter desired values from other files. An effort-level +record contains only `name` and `model`; retrieval depth is configured +separately. Changing a language model does not rebuild the index; changing the embedding model (also a dropdown of cached embedding models) or query format requires confirmation and rebuilds it. A note above the levels appears only when the selected backend's packages are not installed. @@ -604,7 +611,7 @@ the shipped defaults. The file is not created just to read defaults. - Linux: `${XDG_CONFIG_HOME:-~/.config}/kilin/preferences.json` - Windows: `%APPDATA%/kilin/preferences.json` (with a home fallback) -`KILIN_DEFAULTS_FILE` explicitly overrides the **writable preferences +`KILIN_PREFERENCES_FILE` explicitly overrides the **writable preferences file**, not the packaged defaults. The override must be an absolute path (or a home-expanded `~/...` path). Existing complete settings files at that path are accepted and written as sparse overrides on the next update. Invalid @@ -612,9 +619,9 @@ JSON, unsupported keys, and invalid values produce errors; the file is not silently reset. Updates use atomic replacement, and no package files are modified. When working from a source checkout, edits made directly to the shipped `defaults.json` remain readable as checkout defaults but are not -copied into the user-preferences file. Before reinstalling an earlier KíLín -version with edited installed defaults, manually preserve those edits. -KíLín does not automatically migrate edits to installed package resources. +copied into the user-preferences file. Preserve any manual edits to +installed defaults before replacing the package. KíLín does not transfer +edits to package resources into user preferences. **Generation defaults** for new projects are core-owned. Each bundled project type defines a nonzero `temperature` and `thinking=false` in its @@ -669,8 +676,8 @@ switching chats keeps them, and another project loads its own values. The completed-turn model line is formatted by the core and includes the model ID, effective thinking mode (when recorded), temperature (`T=`), and maximum output tokens. The GUI reuses this saved description and -falls back to saved fields for older conversations. A -question never silently commits unconfirmed settings; it must wait until +falls back to saved fields when the description is absent. A question never +silently commits unconfirmed settings; it must wait until the corresponding profile save has been acknowledged. An ordinary answer intent can override thinking for that reply without @@ -741,7 +748,7 @@ can share feedback and provide another active memory origin. Clicking an answer selects its evidence when the side panels are visible; selecting text does not change the current reference. The References panel identifies the selected answer as ``Turn N`` followed by its full saved -router summary; older turns without a summary show a short question excerpt. +router summary; turns without a summary show a short question excerpt. When fewer passages are cited than were read, the citation count appears on a separate line below the summary. Answers without evidence retain their no-sources notice. No additional model call is made for this display. diff --git a/kilin/gui/_paths.py b/kilin/gui/_paths.py index 4a054436..dee6a23d 100644 --- a/kilin/gui/_paths.py +++ b/kilin/gui/_paths.py @@ -74,7 +74,7 @@ "standard_workspace_directory", ] -PREFERENCES_ENVIRONMENT: Final[str] = "KILIN_DEFAULTS_FILE" +PREFERENCES_ENVIRONMENT: Final[str] = "KILIN_PREFERENCES_FILE" WORKSPACES_ENVIRONMENT: Final[str] = "KILIN_WORKSPACES_DIR" # Set by the macOS .app launcher; the CLI must use that exact bundled wheel @@ -227,7 +227,7 @@ def preferences_path() -> Path: Returns ------- pathlib.Path - Explicit absolute ``KILIN_DEFAULTS_FILE`` path, or a user + Explicit absolute ``KILIN_PREFERENCES_FILE`` path, or a user configuration file. The packaged defaults are never the default. Raises diff --git a/kilin/gui/_source_organization.py b/kilin/gui/_source_organization.py index 13119c0f..5a67fbb8 100644 --- a/kilin/gui/_source_organization.py +++ b/kilin/gui/_source_organization.py @@ -35,6 +35,7 @@ from kilin._source_manifest import manifest_data from kilin.source_manifest import ( + _current_project, RelationEdit, ResolveSourceEdit, RoleEdit, @@ -47,7 +48,6 @@ initialize_source_manifest, inspect_source_manifest, preview_source_manifest, - read_source_manifest, refresh_source_manifest, ) from kilin.source_organization import parse_source_organization @@ -263,7 +263,7 @@ def _preview(project: QAProject, request: dict) -> SourceManifestPreview: raise ValueError("Expected source revision and SHA-256 digest.") edits = _edits(request.get("edits", [])) options = {key: request[key] for key in ( - "adopt_type_defaults", "role_mapping", "relation_mapping", "rebind", + "adopt_type_defaults", "role_mapping", "relation_mapping", "adopt_detector_versions", ) if key in request} if "organization" in request: @@ -340,7 +340,7 @@ def execute(self, engine: ChatEngine, request: object) -> None: "preview": { "revision", "sha256", "edits", "organization", "adopt_type_defaults", "role_mapping", - "relation_mapping", "rebind", + "relation_mapping", "adopt_detector_versions", }} if (not isinstance(operation, str) or operation not in allowed @@ -350,6 +350,7 @@ def execute(self, engine: ChatEngine, request: object) -> None: fields = json.loads(json.dumps(fields, allow_nan=False)) response["project"] = str(project.root) name += f".{operation}" + project = _current_project(project) command = {"command_id": uuid4().hex, "request": fields} if (operation == "apply" and self.pending is not None and fields.get("preview_id") == self.pending[0]): diff --git a/kilin/gui/engine.py b/kilin/gui/engine.py index 1d06ea7b..d4ab04d2 100644 --- a/kilin/gui/engine.py +++ b/kilin/gui/engine.py @@ -13,8 +13,10 @@ complete diagnostic tracing, which can retain conversation and source content. -Commands are processed sequentially. Cancellation in the desktop window -terminates the engine process rather than interrupting a model call in place. +Ordinary commands are processed sequentially. A dedicated input thread +signals answer cancellation immediately while dispatch and interactive tool +choices consume commands from a shared queue. Cooperative cancellation keeps +loaded models available; a process-level stop terminates the engine instead. Key Features ------------ @@ -88,7 +90,6 @@ from kilin._trace_project import OPERATION_RECORDING_VERSION from kilin.model_settings import ( SourceCardGenerationSettings, - default_source_card_generation_settings, read_source_card_generation_settings, write_source_card_generation_settings, ) @@ -151,6 +152,7 @@ ) from kilin import RAGSession, prepare_sources_workspace from kilin.workspace import ( + _source_records, add_project_sources, default_workspace_path, find_source_changes, @@ -175,7 +177,10 @@ remove_project_files, replace_project_file, ) -from kilin.conversation_format import conversation_state +from kilin.conversation_format import ( + conversation_state, + read_conversation_json, +) from kilin.conversation_memory.feedback import FeedbackStore from kilin.conversation_memory.inspection import ( inspect_memory_messages, @@ -201,6 +206,7 @@ delete_project, open_project, ) +from kilin.project_layout import validate_project_sources from kilin.repository import DEFAULT_EXTENSIONS, scan_repository from kilin.repository_reason_codes import ( SELECTION_REASON_CODES, @@ -341,8 +347,6 @@ class ChatEngine: **Startup and model configuration.** - startup() - Suggest the most recently used valid sandbox project. readiness() Report runtime packages and the preferred models' availability. use_installed_models() @@ -361,9 +365,7 @@ class ChatEngine: **Project discovery and sources.** list_saved_projects(workspace) - Report valid projects of all registered types, newest first. - find_saved_project(type_id, workspace) - Refresh Resume for the selected type and workspace folder. + Report recognized projects, including unavailable types, newest first. resume_project(directory, conversation_id=None) Reopen a saved project and optionally restore its exact chat. preview(sources, extensions, max_file_bytes, workspace) @@ -399,7 +401,6 @@ class ChatEngine: Emit progress, saved answer, and evidence events. cancel_answer() Stop the running answer at its next generated token. - Keep how long an answer took, as the page showed it. preview_reference(turn_index, citation) Show nearby source lines for one saved answer citation. @@ -780,16 +781,6 @@ def _report_error( **event_fields, ) - def startup(self) -> None: - """Suggest the most recently used valid sandbox project.""" - - project = self._find_saved_project(None, "") - if project is not None: - folder, type_id = project - self._send("startup", project=str(folder), type_id=type_id) - else: - self._send("startup", project=None) - def readiness(self) -> None: """Report runtime packages and the preferred models' availability. @@ -1101,7 +1092,8 @@ def list_saved_projects(self, workspace: str) -> None: Parameters ---------- workspace: str - Workspace containing saved projects. + Explicit workspace path, or an empty string to discover saved + projects in the engine workspace root. """ @@ -1123,88 +1115,28 @@ def list_saved_projects(self, workspace: str) -> None: }) self._send("projects", projects=projects) - def find_saved_project(self, type_id: str, workspace: str) -> None: - """Refresh Resume for the selected type and workspace folder. - - A chosen workspace is checked directly. Without one, the most recent - valid sandbox project of the selected type is suggested. - - Parameters - ---------- - type_id: str - Requested registered project-type identifier. Discovery helpers - also accept None to search all registered types. - workspace: str - Explicit workspace path string. An empty string requests discovery - or default allocation under the engine workspace root. - - """ - - project = self._find_saved_project(type_id or None, workspace) - self._send( - "saved_project", - project=str(project[0]) if project is not None else None, - type_id=type_id, - workspace=workspace, - ) - - def _find_saved_project( - self, type_id: str | None, workspace: str - ) -> tuple[Path, str] | None: - """Find a current project, ignoring deleted or incomplete folders. - - Parameters - ---------- - type_id: str | None - Requested registered project-type identifier. Discovery helpers - also accept None to search all registered types. - workspace: str - Explicit workspace path string. An empty string requests discovery - or default allocation under the engine workspace root. - - Returns - ------- - tuple[pathlib.Path, str] | None - Pair (workspace_path, project_type_id) for the most recently used - valid candidate, or None. - - Notes - ----- - Discovery inspects profile/source existence and profile/conversation - modification times without loading a model. Invalid candidate profiles - are skipped; the whole project schema is checked later when opening. - - """ - - available = set(project_type_ids()) - projects = [ - item for item in self._saved_projects(workspace, type_id) - if item[2] in available - ] - if not projects: - return None - _, folder, saved_type_id = max( - projects, key=lambda item: (item[0], str(item[1])) - ) - return folder, saved_type_id - def _saved_projects( - self, workspace: str, type_id: str | None = None + self, workspace: str ) -> list[tuple[float, Path, str]]: """Recognize saved projects independently of type availability. Parameters ---------- workspace: str - Workspace containing saved projects. - type_id: str | None, optional - Project-type identifier to filter by. Defaults to ``None``. + Explicit workspace path, or an empty string to discover saved + projects in the engine workspace root. Returns ------- list[tuple[float, Path, str]] Recognized saved projects ordered from newest to oldest. + Notes + ----- + Discovery checks profiles, source layouts and modification times of + profiles and conversations without loading a model. Invalid candidate + profiles are skipped; the full project schema is checked when opening. + """ if workspace.strip(): @@ -1231,16 +1163,9 @@ def _saved_projects( source_text = parser.get("project", "source") if not _ID_PATTERN.fullmatch(saved_type_id): continue - if type_id is not None and saved_type_id != type_id: - continue - if not source_text.strip(): - continue - source = Path(source_text).expanduser() - source_path = ( - source if source.is_absolute() else folder / source - ) - if not source_path.is_dir(): + if source_text != PROJECT_SOURCES_DIRECTORY: continue + validate_project_sources(folder) chat_records = tuple( (folder / "logs" / "traces").glob("conversation_*.json") ) @@ -1262,6 +1187,47 @@ def _saved_projects( reverse=True, ) + def _preflight_source_project( + self, directory: str | Path, message: str, *, + allow_mirror: bool = True, **event_fields: object, + ) -> QAProject | None: + """Validate current source authority before GUI side effects. + + Parameters + ---------- + directory: str | pathlib.Path + Workspace whose profile and ownership are checked by the core. + message: str + Context for a frontend-only error response. + allow_mirror: bool, optional + Permit mirrors for activation, inspection and local removal. + False requires cumulative-import or manual ownership. + **event_fields: object + Additional response fields, such as resume recovery state. + + Returns + ------- + QAProject | None + Current project, or None after reporting a rejected operation. + + Notes + ----- + A rejected preflight never opens a conversation, initializes GUI + settings, changes the live session, or appends a project trace. + Schema and filesystem policy remain entirely in the core readers. + + """ + try: + project = open_project(directory) + _source_records(project.root, allow_mirror=allow_mirror) + except Exception as error: + self._send( + "error", message=f"{message}: {error}", trace_path=None, + **event_fields, + ) + return None + return project + def resume_project( self, directory: str, conversation_id: str | None = None ) -> None: @@ -1279,7 +1245,12 @@ def resume_project( previous_released = False try: - project = open_project(directory) + project = self._preflight_source_project( + directory, "Could not resume the project", + resume_released=False, + ) + if project is None: + return # Once closing starts, the previous UI cannot assume its # session remains usable if a subsequent load fails. previous_released = True @@ -2270,6 +2241,7 @@ def _activate_project( """ + _source_records(project.root, allow_mirror=True) options: dict[str, object] = { "progress_callback": lambda progress: self._send( "progress", **asdict(progress) @@ -2700,6 +2672,30 @@ def _memory_project(self, project: str) -> Path: raise ValueError("The active project has changed.") return root + @staticmethod + def _require_feedback_revision(revision: object) -> None: + """Require the revision returned by the project feedback reader. + + Parameters + ---------- + revision: object + Expected SHA-256 digest of the saved feedback bytes. + + Raises + ------ + ValueError + If the revision is not a lowercase SHA-256 digest. + + Notes + ----- + GUI mutations must not opt out of the core's locked comparison. + + """ + + if (not isinstance(revision, str) + or re.fullmatch(r"[0-9a-f]{64}", revision) is None): + raise ValueError("Feedback revision must be a SHA-256 value.") + @staticmethod def _feedback_entries(snapshot: object) -> dict[str, dict[str, dict]]: """Convert a validated feedback snapshot to a JSON object. @@ -2739,7 +2735,8 @@ def save_message_feedback(self, request: object) -> None: Notes ----- The core FeedbackStore owns authorization, locking and persistence. - An invalid or stale write leaves conversation history unchanged. + GUI requests must supply a revision; the core compares it under + the feedback lock. Invalid or stale writes leave history unchanged. """ @@ -2760,6 +2757,7 @@ def save_message_feedback(self, request: object) -> None: raise ValueError("Invalid message feedback request.") if type(request_id) is not int or request_id < 1: raise ValueError("Invalid message feedback request ID.") + self._require_feedback_revision(identity["revision"]) if self._answering: raise RuntimeError("Finish the current answer first.") root = self._memory_project(project) @@ -2879,6 +2877,7 @@ def set_memory_exclusion(self, request: object) -> None: ----- An exclusion is kept in the authoritative feedback file. Existing Save/Like/Dislike selections are preserved under the same file lock. + GUI requests must supply the expected feedback revision. The next ordinary memory sync removes excluded index records. """ @@ -2900,6 +2899,7 @@ def set_memory_exclusion(self, request: object) -> None: or data["request_id"] < 1 or type(data["excluded"]) is not bool): raise ValueError("Invalid memory exclusion request.") + self._require_feedback_revision(data["revision"]) if self._answering: raise RuntimeError("Finish the current answer first.") root = self._memory_project(data["project"]) @@ -3076,6 +3076,16 @@ def save_behavior_settings( if not isinstance(revision, str): raise ValueError("Invalid project behavior revision.") if scope == "capabilities": + try: + current = open_project(root) + _source_records(current.root, allow_mirror=True) + except Exception as error: + self._send( + "project_behavior", project=project, error=str(error), + scope=scope, intent_id=intent_id, + request_id=request_id, + ) + return recovery_root = root path = root / PROJECT_BEHAVIOR_FILE previous_content = ( @@ -3194,10 +3204,9 @@ def versions(self, request_id: object) -> None: if self.session is not None: project = self.session.project reply["project"] = str(project.root) - if project.creation_provenance is not None: - reply["creation_provenance"] = asdict( - project.creation_provenance - ) + reply["creation_provenance"] = asdict( + project.creation_provenance + ) reply["inventory"] = kilin.version_info() except Exception as error: reply["error"] = str(error) @@ -3381,6 +3390,12 @@ def check_sources(self, sources: list[str]) -> None: try: if self.session is None: raise RuntimeError("Open a project first.") + project = self._preflight_source_project( + self.session.project.root, "Could not check the sources", + allow_mirror=False, + ) + if project is None: + return if ( not sources or not isinstance(sources, list) @@ -3389,7 +3404,6 @@ def check_sources(self, sources: list[str]) -> None: ) ): raise ValueError("Choose source files or folders.") - project = self.session.project plan = preview_project_sources(project, sources) changes = {"added": [], "changed": [], "deleted": [], "edited": []} existing = [ @@ -3456,6 +3470,12 @@ def add_project_sources( try: if self.session is None or self.active_conversation is None: raise RuntimeError("Open a project first.") + project = self._preflight_source_project( + self.session.project.root, "Could not finish adding sources", + allow_mirror=False, + ) + if project is None: + return if ( not sources or not isinstance(sources, list) @@ -3464,7 +3484,7 @@ def add_project_sources( ) ): raise ValueError("Choose source files or folders.") - root = self.session.project.root + root = project.root conversation_id = self.active_conversation.conversation_id self.project_trace.emit( "gui.sources.add.requested", @@ -3488,7 +3508,7 @@ def add_project_sources( # A folder without a single file of the project's types cannot # be copied, and a source already in the project changes only # through the user's choices; the check told the user both. - plan = preview_project_sources(self.session.project, sources) + plan = preview_project_sources(project, sources) new = [ value for value, item in zip(plan["sources"], plan["add"]) @@ -3501,7 +3521,7 @@ def add_project_sources( options = { "trace": self.project_trace, "on_organization": self._organization_observer( - self.session.project, "add"), + project, "add"), } if selected_files is not None: options["selected_files"] = selected_files @@ -3510,7 +3530,7 @@ def add_project_sources( options = { "decisions": decisions, "on_organization": self._organization_observer( - self.session.project, "sync"), + project, "sync"), } if self.project_trace.enabled: options["trace"] = self.project_trace @@ -3568,7 +3588,12 @@ def remove_project_sources(self, paths: list[str]) -> None: try: if self.session is None or self.active_conversation is None: raise RuntimeError("Open a project first.") - root = self.session.project.root + project = self._preflight_source_project( + self.session.project.root, "Could not remove sources", + ) + if project is None: + return + root = project.root conversation_id = self.active_conversation.conversation_id self.project_trace.emit( "gui.sources.remove.requested", @@ -3579,9 +3604,9 @@ def remove_project_sources(self, paths: list[str]) -> None: "status", message="Removing sources and updating the index…" ) removed = remove_workspace_sources( - self.session.project, paths, trace=self.project_trace, + project, paths, trace=self.project_trace, on_organization=self._organization_observer( - self.session.project, "remove"), + project, "remove"), ) self.project_trace.emit( "gui.sources.remove.completed", component="gui_engine", @@ -3638,6 +3663,12 @@ def sync_sources(self, decisions: object = None) -> None: try: if self.session is None: raise RuntimeError("Open a project first.") + project = self._preflight_source_project( + self.session.project.root, "Could not update sources", + allow_mirror=False, + ) + if project is None: + return if decisions is not None and not ( isinstance(decisions, dict) and all( @@ -3646,7 +3677,6 @@ def sync_sources(self, decisions: object = None) -> None: ) ): raise ValueError("Source decisions must map paths to actions.") - project = self.session.project self._send( "status", message="Updating sources and the index…" ) @@ -3751,6 +3781,7 @@ def _refresh_source_indexes( Triggering refresh or recovery operation. """ + _source_records(project.root, allow_mirror=True) self._source_organization_commands.clear() self.session.refresh_sources( project, on_organization=self._organization_observer( @@ -3795,6 +3826,7 @@ def _reopen_project_conversation( """ + _source_records(project.root, allow_mirror=True) self._close_traces() store = ConversationStore(project.root) store.ensure() @@ -4184,7 +4216,7 @@ def _usage_totals(self) -> dict[str, dict[str, int]]: """ - def add(total: dict[str, int], parameters: object) -> None: + def add(total: dict[str, int], parameters: object) -> bool: """Accumulate token counts and answer count from a usage record. Parameters @@ -4194,6 +4226,11 @@ def add(total: dict[str, int], parameters: object) -> None: parameters: object Model usage record, expected to contain a usage dictionary. + Returns + ------- + bool + True when a complete valid usage record was accumulated. + """ usage = ( @@ -4202,9 +4239,17 @@ def add(total: dict[str, int], parameters: object) -> None: else None ) if isinstance(usage, dict): - total["input_tokens"] += int(usage.get("input_tokens", 0)) - total["output_tokens"] += int(usage.get("output_tokens", 0)) + counts = [usage.get(key) for key in ( + "input_tokens", "output_tokens", + )] + if any(type(value) is not int or value < 0 + for value in counts): + return False + total["input_tokens"] += counts[0] + total["output_tokens"] += counts[1] total["answers"] += 1 + return True + return False empty = {"input_tokens": 0, "output_tokens": 0, "answers": 0} chat = dict(empty) @@ -4213,22 +4258,19 @@ def add(total: dict[str, int], parameters: object) -> None: return {"chat": chat, "project": project} for turn in self.session.turns: add(chat, getattr(turn, "parameters", None)) - seen: set[tuple[str, str]] = set() + seen: set[str] = set() traces = self.session.project.root / "logs" / "traces" for path in sorted(traces.rglob("conversation_*.json")): try: state = conversation_state( - json.loads(path.read_text(encoding="utf-8")) + read_conversation_json(path.read_text(encoding="utf-8")) ) except (OSError, ValueError): continue # An unreadable file is left out of the total. - for turn in state.get("turns", []) or []: - if not isinstance(turn, dict): - continue - key = (str(turn.get("timestamp")), str(turn.get("question"))) - if key not in seen: + for turn in state.get("turns", []): + key = turn["conversation_turn_uuid"] + if key not in seen and add(project, turn["parameters"]): seen.add(key) - add(project, turn.get("parameters")) return {"chat": chat, "project": project} def _confirm_plan(self, plan: ToolPlan) -> PlanChoice: @@ -4396,8 +4438,13 @@ def preview_reference(self, turn_index: int, citation: int) -> None: return try: + source_root = validate_project_sources( + self.session.project.root, self.session.project.source, + ) + current = open_project(self.session.project.root) + _source_records(current.root, allow_mirror=True) report = { - "repository": str(self.session.project.source), + "repository": str(source_root), "selected_files": [evidence.path.as_posix()], } # Read as the index read it, so line numbers match. @@ -4857,6 +4904,11 @@ def save_source_card_settings(self, request: object) -> None: try: if self.session is None or getattr(self.session, "_closed", False): raise RuntimeError("Open a project before changing cards.") + current = self._preflight_source_project( + self.session.project.root, "Could not update source cards", + ) + if current is None: + return policy, models = self._validate_source_card_settings(request) session = self.session root = session.project.root @@ -4917,6 +4969,11 @@ def regenerate_source_cards(self) -> None: try: if self.session is None or getattr(self.session, "_closed", False): raise RuntimeError("Open a project before regenerating.") + current = self._preflight_source_project( + self.session.project.root, "Could not regenerate source cards", + ) + if current is None: + return self._send("status", message="Regenerating source cards…") self.session.regenerate_source_cards() self._send( @@ -4958,13 +5015,18 @@ def apply_indexing_settings(self, settings: object) -> None: try: if self.session is None: raise RuntimeError("Open a project before changing indexing.") + current = self._preflight_source_project( + self.session.project.root, "Could not apply indexing settings", + ) + if current is None: + return if ( not isinstance(settings, dict) or not settings or not set(settings) <= _INDEXING_SETTINGS ): raise ValueError("Invalid indexing settings.") - root = self.session.project.root + root = current.root profile_text = (root / PROFILE_FILE).read_text(encoding="utf-8") conversation_id = self.active_conversation.conversation_id self._send("status", message="Rebuilding the index…") @@ -5936,18 +5998,12 @@ def read_input() -> None: engine.apply_model_settings(command["settings"]) elif action == "download_model": engine.download(command["model_id"]) - elif action == "startup": - engine.startup() elif action == "readiness": engine.readiness() elif action == "install_required_models": engine.install_required_models() elif action == "use_installed_models": engine.use_installed_models() - elif action == "saved_project": - engine.find_saved_project( - command["type_id"], command["workspace"] - ) elif action == "saved_projects": engine.list_saved_projects(command["workspace"]) elif action == "resume": diff --git a/kilin/gui/icons/README.md b/kilin/gui/icons/README.md index a3432708..dd267c9d 100644 --- a/kilin/gui/icons/README.md +++ b/kilin/gui/icons/README.md @@ -5,15 +5,14 @@ and project sidebar. The current mosaic-style mascot exports include: - `kilin-qilin.png` and `kilin-qilin-dark.png`: full-body mascot for the light and dark UI themes. -- `kilin-qilin-head.png` and `kilin-qilin-head-dark.png`: cropped head - versions used by the application icon designs. - `kilin-light.png` and `kilin-dark.png`: desktop window/Dock icons. - `kilin-wordmark-light.svg` and `kilin-wordmark-dark.svg`: vector logotypes. - `kilin-mosaic-accent.svg`: decorative mosaic accent. -The portable master artwork and the numbered mark/lockup exports are in -`assets/brand/` at the repository root. GUI resources are bundled with the -installed package; source artwork outside `kilin/` is not required at runtime. +The portable master artwork, cropped mascot head variants, and numbered +mark/lockup exports are in `assets/brand/` at the repository root. GUI +resources are bundled with the installed package; source artwork outside +`kilin/` is not required at runtime. ## Name and artwork permissions diff --git a/kilin/gui/preferences.py b/kilin/gui/preferences.py index 527774df..8cdbc1f4 100644 --- a/kilin/gui/preferences.py +++ b/kilin/gui/preferences.py @@ -379,7 +379,7 @@ def preferences_file() -> Path: Returns ------- pathlib.Path - ``KILIN_DEFAULTS_FILE`` when explicitly supplied, or a + ``KILIN_PREFERENCES_FILE`` when explicitly supplied, or a platform-specific user configuration path. """ diff --git a/kilin/gui/web/index.html b/kilin/gui/web/index.html index e62394bb..9fa7a8eb 100644 --- a/kilin/gui/web/index.html +++ b/kilin/gui/web/index.html @@ -15,7 +15,7 @@