diff --git a/.github/workflows/macos_app.yml b/.github/workflows/macos_app.yml index aefd1ab6..3d5d3d27 100644 --- a/.github/workflows/macos_app.yml +++ b/.github/workflows/macos_app.yml @@ -7,6 +7,11 @@ on: - ".github/workflows/macos_app.yml" - "setup/macos/**" - "tests/setup/**" + - "kilin/plugins/**" + - "kilin/tools/**" + - "kilin/project_types/**" + - "kilin/project_type.py" + - "examples/plugins/**" - "kilin/gui/**" - "pyproject.toml" - "uv.lock" @@ -17,6 +22,11 @@ on: - ".github/workflows/macos_app.yml" - "setup/macos/**" - "tests/setup/**" + - "kilin/plugins/**" + - "kilin/tools/**" + - "kilin/project_types/**" + - "kilin/project_type.py" + - "examples/plugins/**" - "kilin/gui/**" - "pyproject.toml" - "uv.lock" @@ -48,13 +58,18 @@ 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 + - name: Verify plugin lifecycle on macOS + run: >- + uv run --locked --no-dev --python 3.12 + python examples/plugins/check_examples.py - 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/package.yml b/.github/workflows/package.yml index af8edd6f..11d06d12 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -34,6 +34,8 @@ jobs: run: uv build - name: Verify PyPI metadata in wheel and source archive run: python -m setup.check_pypi_distribution + - name: Verify the source distribution authoring pack + run: python examples/plugins/check_examples.py --sdist dist/*.tar.gz - name: Install wheel in a separate environment run: | uv venv --python 3.12 "$RUNNER_TEMP/kilin-wheel-env" @@ -43,6 +45,11 @@ jobs: run: >- "$RUNNER_TEMP/kilin-wheel-env/bin/python" -I "$GITHUB_WORKSPACE/tests/setup/check_installed_wheel.py" + - name: Exercise user plugins with the installed wheel + working-directory: ${{ runner.temp }} + run: >- + "$RUNNER_TEMP/kilin-wheel-env/bin/python" -I + "$GITHUB_WORKSPACE/examples/plugins/check_examples.py" - name: Upload distributions for review uses: actions/upload-artifact@v4 with: diff --git a/.github/workflows/windows_app.yml b/.github/workflows/windows_app.yml index 10556b2b..9722d92f 100644 --- a/.github/workflows/windows_app.yml +++ b/.github/workflows/windows_app.yml @@ -7,6 +7,13 @@ on: - ".github/workflows/windows_app.yml" - "setup/windows/**" - "tests/setup/**" + - "kilin/plugins/**" + - "kilin/tools/**" + - "kilin/project_types/**" + - "kilin/project_type.py" + - "examples/plugins/**" + - "kilin/gui/**" + - "MANIFEST.in" - "pyproject.toml" - "uv.lock" pull_request: @@ -15,6 +22,13 @@ on: - ".github/workflows/windows_app.yml" - "setup/windows/**" - "tests/setup/**" + - "kilin/plugins/**" + - "kilin/tools/**" + - "kilin/project_types/**" + - "kilin/project_type.py" + - "examples/plugins/**" + - "kilin/gui/**" + - "MANIFEST.in" - "pyproject.toml" - "uv.lock" workflow_dispatch: @@ -61,14 +75,106 @@ 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" if (-not (Test-Path -LiteralPath $shortcut)) { throw "The Start-menu shortcut is missing." } $uv = [Environment]::GetEnvironmentVariable("KILIN_APP_UV", "User") $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. + $plugins = Join-Path $env:LOCALAPPDATA "kilin\plugins" + $tool = Join-Path $plugins "tools\repeat_question" + $type = Join-Path $plugins "project_types\repetition.json" + if ((Test-Path $tool) -or (Test-Path $type)) { throw "Plugin probe already exists." } + New-Item -ItemType Directory -Force -Path $tool, (Split-Path $type) | Out-Null + Copy-Item "examples\plugins\tools\repeat_question\__init__.py" -Destination $tool + Copy-Item "examples\plugins\project_types\repetition.json" -Destination $type + $toolFile = Join-Path $tool "__init__.py" + $toolHash = (Get-FileHash $toolFile).Hash + $typeHash = (Get-FileHash $type).Hash + $setup = Get-ChildItem dist -Filter "KiLin-Setup-*.exe" | Select-Object -First 1 + $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." + } + "KILIN_PROBE_TOOL_HASH=$toolHash" >> $env:GITHUB_ENV + "KILIN_PROBE_TYPE_HASH=$typeHash" >> $env:GITHUB_ENV - name: Uninstall silently and check what is removed run: | $uninstaller = Join-Path $env:LOCALAPPDATA "Programs\KiLin\unins000.exe" @@ -78,6 +184,12 @@ jobs: for ($i = 0; $i -lt 60 -and (Test-Path $runtime); $i++) { Start-Sleep -Seconds 1 } if (Test-Path $runtime) { throw "The runtime was not removed." } if ([Environment]::GetEnvironmentVariable("KILIN_APP_UV", "User")) { throw "KILIN_APP_UV was not removed." } + $plugins = Join-Path $env:LOCALAPPDATA "kilin\plugins" + $toolFile = Join-Path $plugins "tools\repeat_question\__init__.py" + $type = Join-Path $plugins "project_types\repetition.json" + if ((Get-FileHash $toolFile).Hash -ne $env:KILIN_PROBE_TOOL_HASH -or (Get-FileHash $type).Hash -ne $env:KILIN_PROBE_TYPE_HASH) { + throw "Uninstall changed user plugins." + } - name: Upload the unsigned development installer uses: actions/upload-artifact@v4 with: diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..bb0fd02a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +# KíLín changelog + +This changelog records application changes and releases. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/CITATION.cff b/CITATION.cff index 2f6fea05..7614d9c6 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -11,4 +11,4 @@ authors: family-names: "Manzo" - given-names: "Giovanni" family-names: "Volpe" -version: "0.1.0b1" +version: "0.1.0b2" diff --git a/MANIFEST.in b/MANIFEST.in index 0ccd99a9..f8dada7f 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,15 @@ +include CHANGELOG.md include CITATION.cff include README.md include README.pypi.md +include docs/versioning.md +include docs/PLUGIN_API_CHANGELOG.md +include docs/PROJECT_TYPE_SCHEMA_CHANGELOG.md +include docs/TRACE_FORMAT_CHANGELOG.md +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 89bfc29b..108eda0d 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,9 @@

Your AI. Your Knowledge. Your Control.

- - 0.1.0b1 beta release + + 0.1.0b2 beta release Python 3.12 @@ -40,52 +40,59 @@ and data without depending on a remote AI service for every answer. KíLín provides six built-in project types for code, literature, writing, grounded brainstorming, creative brainstorming, and researcher-directed reviewing. Source-grounded responses reference project files for independent -inspection. +inspection. Projects can organize selected files by role and relationship, +while citations retain their original physical source locations. -**Version `0.1.0b1` (beta):** This is the first public prerelease. +**Version `0.1.0b2` (beta):** This is the second public beta. Backward compatibility of public interfaces and saved project formats is not guaranteed before the stable release. ## Installation -**KíLín `0.1.0b1` 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.0b1" +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.0b1`; 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.0b1 GitHub release](https://github.com/DeepTrackAI/KiLin/releases/tag/v0.1.0b1) -includes two experimental desktop installers built from that version's -source: `KiLin-0.1.0b1-macos-arm64.dmg` for Apple Silicon Macs (macOS 14+) -and `KiLin-Setup-0.1.0b1.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 @@ -99,15 +106,33 @@ 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. - -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. +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). +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 +structured output). In the desktop app, open **Settings → Versions**. +The report may contain local paths and plugin diagnostics. Review it +before sharing. See the [versioning policy](docs/versioning.md). To run KíLín from a source checkout, on macOS or Linux: @@ -122,17 +147,21 @@ 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. ## Tutorials and documentation -KíLín includes **19 progressive Jupyter notebooks** covering models, +KíLín includes **21 progressive Jupyter notebooks** covering models, source processing, semantic/lexical/code retrieval, indexing, project chat, -diagnostic traces, project types, conversation memory, custom tools, and -an end-to-end research assistant. +diagnostic traces, project types and source organization, conversation +memory, custom tools, an end-to-end research assistant, and LLM-assisted +plugin development. Begin with the [complete tutorial guide](tutorials/README.md), @@ -153,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 f8a761cf..dd5b05de 100644 --- a/README.pypi.md +++ b/README.pypi.md @@ -3,8 +3,8 @@

- + KíLín mosaic qilin mascot and wordmark

@@ -12,12 +12,12 @@

Your AI. Your Knowledge. Your Control.

- - 0.1.0b1 beta release + + 0.1.0b2 beta release Python 3.12 - + Apache License 2.0

@@ -42,52 +42,59 @@ and data without depending on a remote AI service for every answer. KíLín provides six built-in project types for code, literature, writing, grounded brainstorming, creative brainstorming, and researcher-directed reviewing. Source-grounded responses reference project files for independent -inspection. +inspection. Projects can organize selected files by role and relationship, +while citations retain their original physical source locations. -**Version `0.1.0b1` (beta):** This is the first public prerelease. +**Version `0.1.0b2` (beta):** This is the second public beta. Backward compatibility of public interfaces and saved project formats is not guaranteed before the stable release. ## Installation -**KíLín `0.1.0b1` 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.0b1" +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.0b1`; to select a -backend explicitly, see the -[model-management guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/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.0b1 GitHub release](https://github.com/DeepTrackAI/KiLin/releases/tag/v0.1.0b1) -includes two experimental desktop installers built from that version's -source: `KiLin-0.1.0b1-macos-arm64.dmg` for Apple Silicon Macs (macOS 14+) -and `KiLin-Setup-0.1.0b1.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 -[native installer guidance](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/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: +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. + +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 @@ -101,15 +108,33 @@ 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. - -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.0b1/kilin/gui/README.md) for details. +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). +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 +structured output). In the desktop app, open **Settings → Versions**. +The report may contain local paths and plugin diagnostics. Review it +before sharing. See the [versioning policy](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/versioning.md). To run KíLín from a source checkout, on macOS or Linux: @@ -124,46 +149,56 @@ 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.0b1/docs/development.md) +[development guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/development.md) covers setup, dependency and test requirements. ## Tutorials and documentation -KíLín includes **19 progressive Jupyter notebooks** covering models, +KíLín includes **21 progressive Jupyter notebooks** covering models, source processing, semantic/lexical/code retrieval, indexing, project chat, -diagnostic traces, project types, conversation memory, custom tools, and -an end-to-end research assistant. +diagnostic traces, project types and source organization, conversation +memory, custom tools, an end-to-end research assistant, and LLM-assisted +plugin development. Begin with the -[complete tutorial guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/tutorials/README.md), +[complete tutorial guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/tutorials/README.md), or start directly with -[10 — Setup](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/tutorials/10_setup.ipynb), -[20 — Hugging Face models](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/tutorials/20_huggingface_models.ipynb), -and [140 — Project chat](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/tutorials/140_project_chat.ipynb). +[10 — Setup](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/tutorials/10_setup.ipynb), +[20 — Hugging Face models](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/tutorials/20_huggingface_models.ipynb), +and [140 — Project chat](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/tutorials/140_project_chat.ipynb). Some notebooks need previously downloaded models; others work offline with bundled examples. -The [technical documentation](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/docs/README.md) +The [technical documentation](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/README.md) explains the architecture, configuration, sources, retrieval, model management, tools, GUI, testing, and release procedures. In particular, -see [workspace ownership](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/docs/project_workspaces.md), -[conversation memory](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/docs/conversation_memory.md), -and [extension interfaces](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/docs/extension_interfaces.md). +see [workspace ownership](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/project_workspaces.md), +[conversation memory](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/conversation_memory.md), +and [extension interfaces](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/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](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.0b1/docs/security.md) -and [trace-recording guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/docs/trace_recording.md) +[security notes](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/security.md) +and [trace-recording guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/trace_recording.md) for the implemented guarantees and limitations. ## Development @@ -176,9 +211,9 @@ uv run --no-sync black --check kilin setup tests uv run --no-sync ruff check kilin setup tests ``` -Use the [development guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/docs/development.md) +Use the [development guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/development.md) for the complete test matrix, style conventions, and release validation. -The [README publication guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/docs/readme_publication.md) explains how +The [README publication guide](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/docs/readme_publication.md) explains how branch-relative GitHub links become tag-pinned links in PyPI metadata. Contributions and issue reports can be filed at [DeepTrackAI/KiLin](https://github.com/DeepTrackAI/KiLin). @@ -186,19 +221,19 @@ Contributions and issue reports can be filed at ## Citation If KíLín contributes to your research, please cite the **specific version** -used. The [CITATION.cff](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/CITATION.cff) +used. The [CITATION.cff](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/CITATION.cff) file provides version-specific software citation metadata for Io̍k-uí Tiunn, Joana B. Pereira, Carlo Manzo, and Giovanni Volpe. ## License and attribution KíLín's software is available under the -[Apache License 2.0](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/LICENSE). +[Apache License 2.0](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/LICENSE). The KíLín name, wordmark, logos, mascot, and other brand artwork have -[separate branding terms](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/kilin/gui/icons/BRAND_LICENSE.md). +[separate branding terms](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/kilin/gui/icons/BRAND_LICENSE.md). They may accompany authentic, unmodified KíLín releases, while modified software must not imply official endorsement. See the -[brand-asset notes](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/assets/brand/README.md) +[brand-asset notes](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/assets/brand/README.md) for the current artwork and its use. Bundled KaTeX assets retain their -[third-party license](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b1/kilin/gui/web/katex/LICENSE). +[third-party license](https://github.com/DeepTrackAI/KiLin/blob/v0.1.0b2/kilin/gui/web/katex/LICENSE). diff --git a/_si_article_/benchmarks/README.md b/_si_article_/benchmarks/README.md index 59b6f263..1a7cbe15 100644 --- a/_si_article_/benchmarks/README.md +++ b/_si_article_/benchmarks/README.md @@ -55,9 +55,9 @@ DeepTrack checkout are never modified by these operations. ## Gold annotations and comparability - `gold/dogfood_kilin_code.json` contains 22 questions, including five - deliberate abstention cases, verified for source-chunk overlap against the - **23 October 2026** KíLín archive. Citation paths and line numbers describe - that snapshot; review them whenever code or notebooks change. An overlapping + deliberate abstention cases. Citation paths and line numbers were checked + by hand against commit **6cb105d20 (3 December 2026)** and describe that + revision; review them whenever code or notebooks change. An overlapping chunk does not, by itself, establish that the written reference answer is scientifically or technically correct. - `gold/dogfood_deeptrack_code.json` retains the historical DeepTrack2 diff --git a/_si_article_/benchmarks/common.py b/_si_article_/benchmarks/common.py index b5195424..147fc025 100644 --- a/_si_article_/benchmarks/common.py +++ b/_si_article_/benchmarks/common.py @@ -48,6 +48,10 @@ Heuristic answer checks that require human interpretation. +- ``bootstrap_interval`` and ``wilson_interval`` + + 95% intervals for mean scores and for counts. + Examples -------- >>> from benchmarks.common import citation_validity, format_query @@ -65,8 +69,10 @@ from difflib import SequenceMatcher import json from pathlib import Path +import random import re import shutil +from statistics import NormalDist from zoneinfo import ZoneInfo from kilin.query_formats import format_qwen3_query @@ -88,10 +94,17 @@ "citation_coverage", "abstains", "verbatim_overlap_chars", + "bootstrap_interval", + "wilson_interval", ] LOCAL_TIMEZONE = ZoneInfo("Europe/Rome") +# Resamples and seed of the bootstrap intervals; the fixed seed makes the +# intervals of a run reproducible. +BOOTSTRAP_RESAMPLES = 10_000 +BOOTSTRAP_SEED = 0 + CODE_RETRIEVAL_INSTRUCTION = ( "Given a coding problem description, retrieve the source code that " @@ -167,7 +180,9 @@ def evaluate_retrieval( Returns ------- dict[str, dict[str, float]] - Mean NDCG, MAP, recall, precision and MRR at each cutoff. + Mean NDCG, MAP, recall, precision and MRR at each cutoff, and under + ``ndcg_interval`` the 95% bootstrap interval of NDCG@10 over the + queries (when 10 is a cutoff). Notes ----- @@ -222,6 +237,13 @@ def evaluate_retrieval( mrr[f"MRR@{k}"] += 1.0 / (rank + 1) break + ndcg_interval: dict[str, list[float]] = {} + if 10 in k_values and scores: + low, high = bootstrap_interval( + [query_scores["ndcg_cut_10"] for query_scores in scores.values()] + ) + ndcg_interval["NDCG@10"] = [round(low, 5), round(high, 5)] + query_count = len(scores) or 1 qrel_count = len(qrels) or 1 for k in k_values: @@ -237,9 +259,114 @@ def evaluate_retrieval( "recall": recall, "precision": precision, "mrr": mrr, + "ndcg_interval": ndcg_interval, } +def bootstrap_interval( + values, + level: float = 0.95, + resamples: int = BOOTSTRAP_RESAMPLES, + seed: int = BOOTSTRAP_SEED, +) -> tuple[float, float]: + """Return a percentile bootstrap interval for the mean of values. + + Parameters + ---------- + values: Sequence[float] + Per-item scores, for example the NDCG@10 of each query or the + citation coverage of each answer. + level: float, optional + Coverage of the interval. Defaults to 0.95. + resamples: int, optional + Number of resamples. Defaults to ``BOOTSTRAP_RESAMPLES``. + seed: int, optional + Seed of the resampling, so that a run gives the same interval. + Defaults to ``BOOTSTRAP_SEED``. + + Returns + ------- + tuple[float, float] + Lower and upper bound of the mean. + + Raises + ------ + ValueError + If values is empty or level is not between 0 and 1. + + """ + + values = [float(value) for value in values] + if not values: + raise ValueError("values must not be empty.") + if not 0.0 < level < 1.0: + raise ValueError("level must be between 0 and 1.") + generator = random.Random(seed) + count = len(values) + means = sorted( + sum(generator.choices(values, k=count)) / count + for _ in range(resamples) + ) + tail = (1.0 - level) / 2.0 + low = means[int(tail * (resamples - 1))] + high = means[int(round((1.0 - tail) * (resamples - 1)))] + return low, high + + +def wilson_interval( + successes: int, total: int, level: float = 0.95 +) -> tuple[float, float]: + """Return the Wilson score interval of a proportion. + + Parameters + ---------- + successes: int + Number of items with the property, for example answers citing only + supplied evidence. + total: int + Number of items. + level: float, optional + Coverage of the interval. Defaults to 0.95. + + Returns + ------- + tuple[float, float] + Lower and upper bound of the proportion, between 0 and 1. + + Raises + ------ + ValueError + If the counts or level are invalid. + + Notes + ----- + Unlike the normal approximation, the Wilson interval stays inside + [0, 1] and is informative when every item succeeds (for example, 42 of + 42 gives 0.92--1.00). + + """ + + if total < 1 or not 0 <= successes <= total: + raise ValueError("Need 0 <= successes <= total and total >= 1.") + if not 0.0 < level < 1.0: + raise ValueError("level must be between 0 and 1.") + z = NormalDist().inv_cdf(0.5 + level / 2.0) + proportion = successes / total + denominator = 1.0 + z * z / total + centre = (proportion + z * z / (2.0 * total)) / denominator + half_width = ( + z + * ((proportion * (1.0 - proportion) + z * z / (4.0 * total)) / total) + ** 0.5 + / denominator + ) + # The bounds are exactly 0 or 1 when no item or every item succeeds; + # set them directly, as rounding can otherwise give 0.9999999999999999. + low = 0.0 if successes == 0 else max(0.0, centre - half_width) + high = 1.0 if successes == total else min(1.0, centre + half_width) + return low, high + + def corpus_already_written(directory: Path) -> bool: """Return whether a project's corpus folder is already populated. diff --git a/_si_article_/benchmarks/gold/dogfood_kilin_code.json b/_si_article_/benchmarks/gold/dogfood_kilin_code.json index 1a984528..260472ee 100644 --- a/_si_article_/benchmarks/gold/dogfood_kilin_code.json +++ b/_si_article_/benchmarks/gold/dogfood_kilin_code.json @@ -1,12 +1,12 @@ { "corpus": "kilin-code", - "corpus_description": "KíLín kilin/ package and tutorials/ notebooks from KiLin_source(3).zip (2026-10-23). The source includes the packaged JSON defaults and project types. Citation positions must be rechecked when the KíLín source changes.", + "corpus_description": "KíLín kilin/ package and tutorials/ notebooks at commit 6cb105d20 (2026-12-03). The source includes the packaged JSON defaults and project types. Citation positions must be rechecked when the KíLín source changes.", "tasks": [ { "task_id": "A1", "question": "Why does chunk_source_units skip source units and chunks whose text is only whitespace?", "gold_citations": [ - "kilin/chunking.py:356", + "kilin/chunking.py:356-357", "kilin/chunking.py:861" ], "fact_checklist": [ @@ -21,7 +21,7 @@ "task_id": "A2", "question": "How does code_search match named code entities and rank the corresponding chunks?", "gold_citations": [ - "kilin/retrievals/strategies/retrieval_code.py:227-335" + "kilin/retrievals/strategies/retrieval_code.py:305-420" ], "fact_checklist": [ "It resolves entities explicitly named in a nonblank query.", @@ -37,7 +37,8 @@ "task_id": "A3", "question": "What is KíLín's default RAG system prompt, word for word?", "gold_citations": [ - "kilin/rag.py:307-313" + "kilin/rag.py:436-441", + "kilin/project_types/code.json:16" ], "fact_checklist": [ "It instructs grounding in supplied project evidence.", @@ -52,7 +53,8 @@ "task_id": "A4", "question": "How does RAGSession format numbered evidence for a chat answer?", "gold_citations": [ - "kilin/rag.py:4476-4530" + "kilin/retrievals/evidence_budget.py:190-216", + "kilin/rag.py:7350-7485" ], "fact_checklist": [ "Each item starts with [n] and a path plus line range.", @@ -67,7 +69,7 @@ "task_id": "A5", "question": "Does hybrid_search use Reciprocal Rank Fusion, and what are its default rank constant and count?", "gold_citations": [ - "kilin/retrievals/strategies/retrieval_hybrid.py:106-178" + "kilin/retrievals/strategies/retrieval_hybrid.py:106-190" ], "fact_checklist": [ "Hybrid search uses Reciprocal Rank Fusion (RRF).", @@ -81,8 +83,8 @@ "task_id": "A6", "question": "What happens when scan_repository encounters more than its max_entries limit?", "gold_citations": [ - "kilin/repository.py:437-480", - "kilin/repository.py:550-578" + "kilin/repository.py:437-500", + "kilin/repository.py:566-575" ], "fact_checklist": [ "The default max_entries limit is 10,000.", @@ -96,8 +98,8 @@ "task_id": "A7", "question": "Does EmbeddingSession configure embedding batch_size, or is that specified for build_semantic_index?", "gold_citations": [ - "kilin/retrievals/strategies/retrieval_semantic.py:133-193", - "kilin/embeddings.py:144-165" + "kilin/retrievals/strategies/retrieval_semantic.py:133-202", + "kilin/embeddings.py:144-152" ], "fact_checklist": [ "EmbeddingSession does not take a batch_size constructor argument.", @@ -110,8 +112,8 @@ "task_id": "A8", "question": "What retrieval_count and max_new_tokens defaults does KíLín ship for a new project profile?", "gold_citations": [ - "kilin/kilin_defaults.json:184-193", - "kilin/project.py:214-241" + "kilin/kilin_defaults.json:221-231", + "kilin/project.py:212-239" ], "fact_checklist": [ "Project-profile retrieval_count defaults to 5.", @@ -126,8 +128,8 @@ "question": "What distinguishes KíLín's built-in code and literature project types?", "gold_citations": [ "kilin/project_type.py:1-45", - "kilin/project_types/code.json:1-15", - "kilin/project_types/literature.json:1-15" + "kilin/project_types/code.json:1-16", + "kilin/project_types/literature.json:1-17" ], "fact_checklist": [ "Different project type JSON files select extension lists and source folder names.", @@ -141,8 +143,8 @@ "task_id": "A10", "question": "What data does indexes_are_current compare to determine whether a persisted index can be reused?", "gold_citations": [ - "kilin/retrievals/persistence.py:366-405", - "kilin/retrievals/persistence.py:473-498" + "kilin/retrievals/persistence.py:366-409", + "kilin/retrievals/persistence.py:473-506" ], "fact_checklist": [ "It compares a deterministic SHA-256 fingerprint of chunks and the code graph.", @@ -168,7 +170,7 @@ "task_id": "A12", "question": "Does KíLín use a configurable registry of fourth-party retrieval channels inside RAGSession._retrieve, or explicit search calls?", "gold_citations": [ - "kilin/rag.py:2920-3160" + "kilin/rag.py:4584-4682" ], "fact_checklist": [ "The reviewed retrieval path directly calls semantic_search, lexical_search, and code_search before hybrid fusion.", @@ -230,7 +232,8 @@ "task_id": "A17", "question": "Does KíLín's deterministic context expansion replace or reorder the initial RRF ranking?", "gold_citations": [ - "kilin/retrievals/context_expansion.py:139-255" + "kilin/retrievals/context_expansion.py:260-300", + "kilin/retrievals/context_expansion.py:455-586" ], "fact_checklist": [ "plan_context_expansion identifies explicitly requested context.", @@ -244,7 +247,7 @@ "task_id": "A18", "question": "Which model presets does the KíLín GUI offer, and for which roles and backends?", "gold_citations": [ - "kilin/gui/model_catalog.py:90-166" + "kilin/gui/model_catalog.py:154-175" ], "fact_checklist": [ "The catalog lists six presets in MODEL_CHOICES.", @@ -259,7 +262,7 @@ "task_id": "A19", "question": "How does choose_backend resolve auto, and what happens if MLX is explicitly selected off Apple Silicon?", "gold_citations": [ - "kilin/runtime.py:84-112" + "kilin/runtime.py:84-117" ], "fact_checklist": [ "auto chooses MLX on native Apple Silicon and Torch otherwise.", @@ -273,8 +276,8 @@ "task_id": "A20", "question": "Does the GUI restrict model downloads to MODEL_CHOICES, or does it accept validated custom model identifiers?", "gold_citations": [ - "kilin/gui/engine.py:1157-1190", - "kilin/gui/model_catalog.py:136-155" + "kilin/gui/engine.py:1522-1559", + "kilin/gui/model_catalog.py:1-7" ], "fact_checklist": [ "The GUI catalog lists suggested presets, not an allowlist.", diff --git a/_si_article_/benchmarks/notebooks/60_kilin_dogfood_code.ipynb b/_si_article_/benchmarks/notebooks/60_kilin_dogfood_code.ipynb index 3c4aa1cd..af938987 100644 --- a/_si_article_/benchmarks/notebooks/60_kilin_dogfood_code.ipynb +++ b/_si_article_/benchmarks/notebooks/60_kilin_dogfood_code.ipynb @@ -446,9 +446,11 @@ "\n", "from benchmarks.common import (\n", " abstains,\n", + " bootstrap_interval,\n", " citation_coverage,\n", " citation_validity,\n", " verbatim_overlap_chars,\n", + " wilson_interval,\n", ")\n", "\n", "# Long verbatim overlaps need human review, except the prompt quote (A3).\n", @@ -533,6 +535,39 @@ " \"No answerable question had its gold evidence retrieved \"\n", " \"-- coverage undefined.\"\n", " )\n", + "# 95% intervals: Wilson for counts, bootstrap for the mean coverage.\n", + "answerable_rows = [r for r in tier1_rows if not r[\"requires_abstention\"]]\n", + "unanswerable_rows = [r for r in tier1_rows if r[\"requires_abstention\"]]\n", + "interval_counts = {\n", + " \"citation_valid\": (valid_count, len(tier1_rows)),\n", + " \"abstention_correct\": (abstention_correct_count, len(tier1_rows)),\n", + " \"unanswerable_declined\": (\n", + " sum(1 for r in unanswerable_rows if r[\"abstained\"]),\n", + " len(unanswerable_rows),\n", + " ),\n", + " \"answerable_declined\": (\n", + " sum(1 for r in answerable_rows if r[\"abstained\"]),\n", + " len(answerable_rows),\n", + " ),\n", + " \"answerable_gold_retrieved\": (len(coverage_values), len(answerable_rows)),\n", + "}\n", + "intervals: dict[str, object] = {\n", + " name: {\n", + " \"count\": count,\n", + " \"total\": total,\n", + " \"wilson_95\": [\n", + " round(bound, 3) for bound in wilson_interval(count, total)\n", + " ],\n", + " }\n", + " for name, (count, total) in interval_counts.items()\n", + " if total\n", + "}\n", + "if coverage_values:\n", + " intervals[\"mean_citation_coverage_bootstrap_95\"] = [\n", + " round(bound, 3) for bound in bootstrap_interval(coverage_values)\n", + " ]\n", + "for name, value in intervals.items():\n", + " print(f\"95% interval, {name}: {value}\")\n", "print(\n", " f\"Verbatim-copy flags (>= {VERBATIM_CHAR_THRESHOLD} chars, \"\n", " f\"A3 allows quotation): {verbatim_flags or 'none'}\"\n", @@ -660,6 +695,7 @@ " else None\n", " ),\n", " \"verbatim_flagged_task_ids\": verbatim_flags,\n", + " \"intervals\": intervals,\n", " },\n", " \"per_question\": [\n", " {**row, \"tier1\": tier1} for row, tier1 in zip(run_results, tier1_rows)\n", diff --git a/_si_article_/benchmarks/notebooks/70_deeptrack_dogfood_code.ipynb b/_si_article_/benchmarks/notebooks/70_deeptrack_dogfood_code.ipynb index 1e72c400..2fd5a3a2 100644 --- a/_si_article_/benchmarks/notebooks/70_deeptrack_dogfood_code.ipynb +++ b/_si_article_/benchmarks/notebooks/70_deeptrack_dogfood_code.ipynb @@ -492,9 +492,11 @@ "\n", "from benchmarks.common import (\n", " abstains,\n", + " bootstrap_interval,\n", " citation_coverage,\n", " citation_validity,\n", " verbatim_overlap_chars,\n", + " wilson_interval,\n", ")\n", "\n", "# Long verbatim overlaps indicate possible excessive copying.\n", @@ -579,6 +581,39 @@ " \"No answerable question had its gold evidence retrieved \"\n", " \"-- coverage undefined.\"\n", " )\n", + "# 95% intervals: Wilson for counts, bootstrap for the mean coverage.\n", + "answerable_rows = [r for r in tier1_rows if not r[\"requires_abstention\"]]\n", + "unanswerable_rows = [r for r in tier1_rows if r[\"requires_abstention\"]]\n", + "interval_counts = {\n", + " \"citation_valid\": (valid_count, len(tier1_rows)),\n", + " \"abstention_correct\": (abstention_correct_count, len(tier1_rows)),\n", + " \"unanswerable_declined\": (\n", + " sum(1 for r in unanswerable_rows if r[\"abstained\"]),\n", + " len(unanswerable_rows),\n", + " ),\n", + " \"answerable_declined\": (\n", + " sum(1 for r in answerable_rows if r[\"abstained\"]),\n", + " len(answerable_rows),\n", + " ),\n", + " \"answerable_gold_retrieved\": (len(coverage_values), len(answerable_rows)),\n", + "}\n", + "intervals: dict[str, object] = {\n", + " name: {\n", + " \"count\": count,\n", + " \"total\": total,\n", + " \"wilson_95\": [\n", + " round(bound, 3) for bound in wilson_interval(count, total)\n", + " ],\n", + " }\n", + " for name, (count, total) in interval_counts.items()\n", + " if total\n", + "}\n", + "if coverage_values:\n", + " intervals[\"mean_citation_coverage_bootstrap_95\"] = [\n", + " round(bound, 3) for bound in bootstrap_interval(coverage_values)\n", + " ]\n", + "for name, value in intervals.items():\n", + " print(f\"95% interval, {name}: {value}\")\n", "print(\n", " f\"Verbatim-copy flags (>= {VERBATIM_CHAR_THRESHOLD} chars): \"\n", " f\"{verbatim_flags or 'none'}\"\n", @@ -704,6 +739,7 @@ " else None\n", " ),\n", " \"verbatim_flagged_task_ids\": verbatim_flags,\n", + " \"intervals\": intervals,\n", " },\n", " \"per_question\": [\n", " {**row, \"tier1\": tier1} for row, tier1 in zip(run_results, tier1_rows)\n", diff --git a/_si_article_/code_analysis/code_example.py b/_si_article_/code_analysis/code_example.py index 7e4be064..36225ea2 100644 --- a/_si_article_/code_analysis/code_example.py +++ b/_si_article_/code_analysis/code_example.py @@ -26,7 +26,7 @@ uv run --no-sync python _si_article_/code_analysis/code_example.py \\ --ref v0.1.0 uv run --no-sync python _si_article_/code_analysis/code_example.py \\ - --sets evaluation + --questions routing,chunking Models must already be in the local Hugging Face cache unless ``--allow-download`` is given. @@ -36,6 +36,7 @@ from __future__ import annotations from argparse import ArgumentParser +import ast from collections.abc import Iterable, Sequence from datetime import datetime, timezone import json @@ -56,6 +57,7 @@ open_session, prepare_code_project, routed_intent, + set_router_model, ) ANALYSIS_DIRECTORY = Path(__file__).resolve().parent @@ -133,23 +135,94 @@ def _location(chunk: dict) -> tuple[str, int, int]: ) -def _matches(item: dict, gold: dict) -> bool: - """Tell whether a retrieved passage belongs to a gold function.""" +def gold_lines( + source: Path, gold: Sequence[dict] +) -> dict[tuple[str, str], tuple[int, int]]: + """Find the line range of each gold function in the indexed source. + + Parameters + ---------- + source: pathlib.Path + Folder of the indexed source files. + gold: Sequence[dict] + Gold functions, each with ``path`` and ``symbol`` (``Class.method`` + for a method). + + Returns + ------- + dict[tuple[str, str], tuple[int, int]] + First and last line of each gold function found, by + ``(path, symbol)``. Functions that cannot be found are left out. + + """ + + lines: dict[tuple[str, str], tuple[int, int]] = {} + for entry in gold: + path = source / entry["path"] + try: + node = ast.parse(path.read_text(encoding="utf-8")) + except (OSError, SyntaxError, UnicodeDecodeError): + continue + for part in entry["symbol"].split("."): + node = next( + ( + child for child in ast.iter_child_nodes(node) + if isinstance(child, (ast.FunctionDef, + ast.AsyncFunctionDef, + ast.ClassDef)) + and child.name == part + ), + None, + ) + if node is None: + break + if node is not None: + lines[(entry["path"], entry["symbol"])] = ( + node.lineno, node.end_lineno or node.lineno, + ) + return lines + + +def _matches( + item: dict, + gold: dict, + lines: dict[tuple[str, str], tuple[int, int]] | None = None, +) -> bool: + """Tell whether a retrieved passage holds a gold function. + + A passage holds it when it is the function's own passage, or when it is + a passage of the enclosing class whose lines contain the whole method + (a short class is indexed as one passage). + + """ symbol = item.get("symbol") or "" - return item.get("path") == gold["path"] and ( - symbol == gold["symbol"] or symbol.endswith("." + gold["symbol"]) + if item.get("path") != gold["path"]: + return False + if symbol == gold["symbol"] or symbol.endswith("." + gold["symbol"]): + return True + span = (lines or {}).get((gold["path"], gold["symbol"])) + return ( + span is not None + and bool(symbol) + and gold["symbol"].startswith(symbol + ".") + and int(item.get("start_line") or 0) <= span[0] + and int(item.get("end_line") or 0) >= span[1] ) -def _gold_found(items: Iterable[dict], gold: Sequence[dict]) -> list[str]: +def _gold_found( + items: Iterable[dict], + gold: Sequence[dict], + lines: dict[tuple[str, str], tuple[int, int]] | None = None, +) -> list[str]: """List the gold symbols present among retrieved passages.""" items = list(items) return [ entry["symbol"] for entry in gold - if any(_matches(item, entry) for item in items) + if any(_matches(item, entry, lines) for item in items) ] @@ -202,7 +275,10 @@ def read_retrieval(trace_path: Path) -> dict[str, list[dict]]: def analyze( - retrieval: dict[str, list[dict]], answer: str, gold: Sequence[dict] + retrieval: dict[str, list[dict]], + answer: str, + gold: Sequence[dict], + lines: dict[tuple[str, str], tuple[int, int]] | None = None, ) -> dict[str, object]: """Compare retrieved and cited passages with the gold functions. @@ -214,6 +290,10 @@ def analyze( Visible answer text. gold: Sequence[dict] Gold functions, each with ``path`` and ``symbol``. + lines: dict[tuple[str, str], tuple[int, int]] | None, optional + Line ranges of the gold functions (``gold_lines``), so that a class + passage containing a gold method counts for it. Defaults to None, + which matches symbols only. Returns ------- @@ -243,10 +323,10 @@ def analyze( ), }) found = { - name: _gold_found(retrieval[name], gold) + name: _gold_found(retrieval[name], gold, lines) for name in (*_CHANNELS, "hybrid", "evidence") } - found["cited"] = _gold_found(cited, gold) + found["cited"] = _gold_found(cited, gold, lines) found["code_only"] = [ symbol for symbol in found["code"] @@ -338,7 +418,7 @@ def write_worksheet(path: Path, results: dict, questions: Sequence[dict]): record = by_id[item["id"]] found = record.get("gold_found", {}) lines += [ - f"## {item['id']} ({item['kind']}, {item.get('set')})", + f"## {item['id']} ({item['kind']})", "", f"**Question.** {item['question']}", "", @@ -368,7 +448,11 @@ def write_worksheet(path: Path, results: dict, questions: Sequence[dict]): "**Facts (tick those the answer states correctly):**", "", ] - lines += [f"- [ ] {fact}" for fact in item["facts"]] + core = set(item.get("core_facts", ())) + lines += [ + f"- [ ] {'(core) ' if number in core else ''}{fact}" + for number, fact in enumerate(item["facts"], start=1) + ] lines += [ "", "**Errors or unsupported statements:** ", @@ -468,6 +552,11 @@ def main(argv: Sequence[str] | None = None) -> int: action="store_true", help="use the default intent instead of the router", ) + parser.add_argument( + "--router-model", default=None, + help="intent (router) model of the project, a Hugging Face ID such " + "as Qwen/Qwen3-8B-MLX-4bit (default: the packaged default)", + ) parser.add_argument( "--retrieval-count", type=int, @@ -485,10 +574,9 @@ def main(argv: Sequence[str] | None = None) -> int: help="allow model downloads (first run on a new machine)", ) parser.add_argument( - "--sets", + "--questions", default=None, - help="comma-separated question sets to run, such as evaluation " - "(default: all)", + help="comma-separated question identifiers to run (default: all)", ) args = parser.parse_args(argv) if args.retrieval_count is not None and args.retrieval_count < 1: @@ -502,12 +590,12 @@ def main(argv: Sequence[str] | None = None) -> int: questions = json.loads(QUESTIONS_FILE.read_text(encoding="utf-8"))[ "questions" ] - if args.sets: - wanted = {name.strip() for name in args.sets.split(",")} - unknown = wanted - {item.get("set") for item in questions} + if args.questions: + wanted = {name.strip() for name in args.questions.split(",")} + unknown = wanted - {item["id"] for item in questions} if unknown: - parser.error(f"unknown question set: {sorted(unknown)[0]}") - questions = [item for item in questions if item.get("set") in wanted] + parser.error(f"unknown question: {sorted(unknown)[0]}") + questions = [item for item in questions if item["id"] in wanted] project, revision = prepare_code_project( args.ref, DEFAULT_EXCLUDES, allow_download=args.allow_download ) @@ -516,7 +604,9 @@ def main(argv: Sequence[str] | None = None) -> int: "environment": describe_environment(), "indexed_revision": revision, "use_router": not args.no_router, - "question_sets": sorted({item.get("set") for item in questions}), + "router_model": set_router_model(project, args.router_model), + "temperature": project.profile.temperature, + "questions_run": len(questions), "retrieval_count": args.retrieval_count, } @@ -541,7 +631,6 @@ def main(argv: Sequence[str] | None = None) -> int: record = { "id": item["id"], "kind": item["kind"], - "set": item.get("set"), "intent": routed_intent(trace_path), "wall_s": round(elapsed, 2), "answer": answer, @@ -549,7 +638,10 @@ def main(argv: Sequence[str] | None = None) -> int: } retrieval = read_retrieval(trace_path) if retrieval["evidence"]: - record.update(analyze(retrieval, answer, item["gold"])) + record.update(analyze( + retrieval, answer, item["gold"], + gold_lines(project.source, item["gold"]), + )) records.append(record) print(f" {item['id']}: {elapsed:.1f} s, intent {record['intent']}") results["questions"] = records diff --git a/_si_article_/code_analysis/code_questions.json b/_si_article_/code_analysis/code_questions.json index c618fd5c..f68a466e 100644 --- a/_si_article_/code_analysis/code_questions.json +++ b/_si_article_/code_analysis/code_questions.json @@ -1,11 +1,9 @@ { - "description": "Questions about the KíLín code base for the paper's code example. Each question names code entities (except the location questions) and lists the functions a complete answer must draw on (gold), identified by file and symbol rather than line numbers, so the set stays valid while line numbers change. Facts are for grading answers by hand. The 35 questions in set 'development' were written in successive rounds (field 'round': development, held_out_1, held_out_2, held_out_3, evaluation); each round's results led to retrieval, routing, or prompt changes, so all of them are development questions. The ten questions in set 'evaluation' (round 'evaluation_2') were written after the last change (more fused results for source-code intents), in parts of the code base no earlier question covers, mostly as location questions, and were not run before the evaluation.", + "description": "Questions about the KíLín code base for the paper's code example. Each question names code entities (except the location questions) and lists the functions a complete answer must draw on (gold), identified by file and symbol rather than line numbers, so the set stays valid while line numbers change. Facts are for grading answers by hand; core_facts gives the one-based numbers of the facts that state the main mechanism, and the others are details. The 45 questions were written in rounds while KíLín was being developed, and the results of each round led to retrieval, routing, or prompt changes; they are examples of questions about code, not a held-out benchmark. On 2 December 2026, sixteen questions were reworded so that every question starts with 'Explain' and asks about the code rather than about KíLín (some had started 'Where does KíLín' or 'How does KíLín', or used another tool's words such as 'every place' or 'read a whole file'); four of them now name the function they ask about (kind changed to mechanism). Gold sets and facts were brought up to date with the code on 1 December 2026 (commit f88197142); strip_thinking_callers was narrowed to answering.py because strip_thinking had gained sixteen callers elsewhere.", "questions": [ { "id": "routing", "kind": "mechanism", - "set": "development", - "round": "development", "question": "Explain how route_question assigns a question to an intent, and what happens when the router reply cannot be used.", "gold": [ { @@ -26,14 +24,18 @@ "Otherwise the router model is called through side_reply with a router prompt.", "The reply is parsed by _parse_route into a RouteDecision.", "If the router call fails or its reply is unusable, the project type's default intent is used.", - "Related earlier turns proposed by the router are kept only if the question refers back or shares a distinctive term." + "Related earlier turns proposed by the router are kept only if the question refers back or shares a distinctive term.", + "Wording can overrule the router: a question that matches an intent's cue patterns gets that intent, and a router choice that the wording rules out (an intent's required words missing, or a follow-up tool for a question naming a new file) is routed once more without it." + ], + "core_facts": [ + 1, + 2, + 4 ] }, { "id": "index_reuse", "kind": "mechanism", - "set": "development", - "round": "development", "question": "Explain how RAGSession decides whether to reuse the saved retrieval indexes or to rebuild them.", "gold": [ { @@ -50,13 +52,16 @@ "The embedding-model identity of the saved index must match the current model.", "If the sources changed but the configuration did not, unchanged files keep their saved chunks and vectors and only new or changed files are embedded.", "Any problem with the saved index leads to embedding everything again." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "index_storage", "kind": "mechanism", - "set": "development", - "round": "development", "question": "Explain how build_semantic_index embeds the chunks, and how save_indexes and load_indexes protect the saved index.", "gold": [ { @@ -78,14 +83,17 @@ "save_indexes validates the records and the source fingerprint and stores a payload checksum.", "load_indexes verifies the checksum, the embedding-model identity and the fingerprint.", "The checksum detects accidental corruption; it is not an authenticity guarantee." + ], + "core_facts": [ + 1, + 3, + 4 ] }, { "id": "strip_thinking_callers", "kind": "dependency", - "set": "development", - "round": "development", - "question": "Explain which functions call strip_thinking, and why each of them needs to remove the model's reasoning.", + "question": "Explain which functions in answering.py call strip_thinking, and why each of them needs to remove the model's reasoning.", "gold": [ { "path": "kilin/answering.py", @@ -98,19 +106,28 @@ { "path": "kilin/answering.py", "symbol": "history_messages" + }, + { + "path": "kilin/answering.py", + "symbol": "_answer_sentences" } ], "facts": [ - "turn_representation removes reasoning (and citations) from an earlier answer to build the compact representation shown to the router.", - "side_reply returns the reply of an auxiliary model call, such as the router's, without reasoning.", - "history_messages removes reasoning from earlier answers before they are included as conversation history." + "turn_representation removes reasoning from an earlier answer to build the compact representation shown to the router: the cited sources and a summary (a model-written one, or the answer's first sentence).", + "_answer_sentences removes reasoning and citations from an answer and splits off its first sentence, for turn summaries.", + "side_reply returns the reply of an auxiliary model call, such as the router's, without reasoning unless asked to keep it.", + "history_messages removes reasoning from earlier answers before they are included as conversation history, and leaves out incomplete or empty answers." + ], + "core_facts": [ + 1, + 2, + 3, + 4 ] }, { "id": "hybrid_callers", "kind": "dependency", - "set": "development", - "round": "development", "question": "Explain which RAGSession methods call hybrid_search, and how each of them uses the fused ranking.", "gold": [ { @@ -124,20 +141,28 @@ { "path": "kilin/retrievals/strategies/retrieval_hybrid.py", "symbol": "hybrid_search" + }, + { + "path": "kilin/rag.py", + "symbol": "RAGSession._source_passages" } ], "facts": [ - "_retrieve fuses the semantic, lexical and code-graph rankings for the configured retrieval count to select the evidence for an answer.", + "_retrieve fuses the semantic, lexical and code-graph rankings of all candidates, moves tests (and, for source-code intents, documentation) down, and keeps the top results as evidence for an answer.", "_rank_everything ranks every chunk with the same fused channels, for uses that need a complete ranking, such as tools.", + "_source_passages, used by source-first retrieval (literature projects), ranks every passage with the fused channels to choose original passages from the selected sources.", "hybrid_search combines the rankings by reciprocal-rank fusion." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "citation_check", "kind": "location", - "set": "development", - "round": "development", - "question": "Explain where KíLín checks that the citation numbers in an answer refer to the supplied evidence, and what happens when they do not.", + "question": "Explain where the code checks that the citation numbers in an answer refer to the supplied evidence, and what happens when they do not.", "gold": [ { "path": "kilin/rag.py", @@ -151,15 +176,18 @@ "facts": [ "_invalid_citations returns the citation numbers in the answer that do not match any supplied evidence.", "RAGSession.ask records them in the turn parameters as invalid_citations.", - "The answer is neither modified nor regenerated.", + "Only the citation formatting is normalized; the answer is not otherwise changed and is not regenerated.", "The check is syntactic: it does not verify that the cited evidence supports the claim." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "chunking", "kind": "mechanism", - "set": "development", - "round": "development", "question": "Explain how chunk_source_units handles a source unit that is longer than the maximum chunk size, and how the overlap between consecutive chunks is kept.", "gold": [ { @@ -185,13 +213,16 @@ "Otherwise it is split along line boundaries, and within a single line if that line is too long.", "The target size guides where to split; the maximum size is the bound every chunk must respect.", "Overlap with the previous chunk is kept as whole source lines or a character suffix, up to the overlap token limit." + ], + "core_facts": [ + 1, + 3, + 5 ] }, { "id": "rank_everything_callers", "kind": "dependency", - "set": "development", - "round": "development", "question": "Explain which RAGSession methods call _rank_everything, and why each of them needs a ranking of every chunk.", "gold": [ { @@ -211,14 +242,17 @@ "_retrieve ranks every chunk when the question names exactly one document, and keeps that document's best passages, which may not be in the project-wide top results.", "_run_tool gives tools a rank function, so a tool can rank all chunks for any text.", "_read_document ranks all chunks to choose the document to read within the token budget." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "history_selection", "kind": "location", - "set": "development", - "round": "development", - "question": "Explain where KíLín decides which earlier turns of a conversation are given to the model as history, and what determines how many.", + "question": "Explain where the code decides which earlier turns of a conversation are given to the model as history, and what determines how many.", "gold": [ { "path": "kilin/answering.py", @@ -234,13 +268,16 @@ "The intent's history policy decides: none includes nothing, recent includes the last few turns, relevant also adds the turns the router marked as related.", "The number of recent turns comes from the project type (history.recent_turns).", "A question the router judged standalone still receives the previous turn, without its evidence." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "conversation_lock", "kind": "mechanism", - "set": "development", - "round": "development", "question": "Explain how ConversationFileLock prevents two sessions from writing the same conversation file at the same time.", "gold": [ { @@ -258,13 +295,16 @@ "A registry within the process rejects a second owner of the same path before the file is opened.", "The operating system releases the lock when the owning process exits.", "It coordinates KíLín writers only; programs that ignore the lock are not prevented from writing." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "backend_choice", "kind": "mechanism", - "set": "development", - "round": "held_out_1", "question": "Explain how choose_backend selects the computation backend, and which PyTorch device is used when PyTorch is selected.", "gold": [ { @@ -281,13 +321,16 @@ "auto selects MLX on a native Apple silicon Mac (macOS on arm64) and PyTorch otherwise.", "Requesting mlx explicitly on any other platform raises an error.", "With PyTorch, the device is CUDA if available, otherwise Apple MPS if available, otherwise the CPU." + ], + "core_facts": [ + 2, + 3, + 4 ] }, { "id": "tool_confirmation", "kind": "mechanism", - "set": "development", - "round": "held_out_1", "question": "Explain how needs_confirmation and confirm_plan decide whether a tool asks the user before running, and what happens with the user's answer.", "gold": [ { @@ -305,13 +348,16 @@ "confirm_plan asks only when a confirmation callback is available and needs_confirmation says so; otherwise it continues.", "The answer can be continue, quick, or cancel; any other answer is treated as cancel.", "The proposed plan and the decision are both recorded in the trace." + ], + "core_facts": [ + 2, + 3, + 4 ] }, { "id": "ask_choice_callers", "kind": "dependency", - "set": "development", - "round": "held_out_1", "question": "Explain which functions call ask_choice, and what each of them asks the user to choose.", "gold": [ { @@ -321,19 +367,27 @@ { "path": "kilin/tools/_shared/choose_document.py", "symbol": "choose_document" + }, + { + "path": "kilin/tools/reference_check/tool.py", + "symbol": "_choose_list" } ], "facts": [ "offer_export asks whether to save a long list as a Markdown file in outputs/ or to show only the first items in the chat.", "choose_document asks the user which of several candidate files the question refers to.", - "If the user cancels the document choice, the tool stops and says which files matched." + "If the user cancels the document choice, the tool stops and says which files matched.", + "reference_check's _choose_list asks which reference list to check when a paper has several and the question names none; cancelling stops the check." + ], + "core_facts": [ + 1, + 2, + 4 ] }, { "id": "readable_trace", "kind": "mechanism", - "set": "development", - "round": "held_out_1", "question": "Explain when TraceLogger rewrites the human-readable trace file, and how it avoids leaving a partially written file.", "gold": [ { @@ -350,18 +404,20 @@ } ], "facts": [ - "The file is rewritten after each recorded event; progress updates rewrite it at most every half second.", + "The file is rewritten after each recorded event; progress updates and answer-activity events rewrite it at most every half second.", "It is also rewritten when the conversation data is updated.", "A new temporary file replaces the target in one step, while the exclusive lock on the companion file is held.", "Repeated writes replace this run's part of the file without duplicating it or overwriting earlier runs.", "If writing fails, the event stays in memory and the failure is handled rather than raised." + ], + "core_facts": [ + 1, + 3 ] }, { "id": "workspace_sync", "kind": "mechanism", - "set": "development", - "round": "held_out_1", "question": "Explain how synchronize_project_workspace keeps its copy of a source folder up to date with the original folder.", "gold": [ { @@ -383,13 +439,15 @@ "Before using that comparison, the copied files are rehashed and checked against the saved manifest; if the copy was changed, it is rebuilt from the original.", "Otherwise only added and modified files are copied and removed files deleted, then empty folders are removed.", "The new manifest, with the source folder's path, is saved for the next synchronization. The original folder is never modified." + ], + "core_facts": [ + 2, + 4 ] }, { "id": "cached_model_callers", "kind": "dependency", - "set": "development", - "round": "held_out_2", "question": "Explain which functions call cached_model_snapshot, and when each of them uses it instead of downloading the model.", "gold": [ { @@ -407,14 +465,16 @@ "Both call cached_model_snapshot only when downloads are not allowed and the model ID is not a local folder.", "When downloads are allowed, _model_source calls snapshot_download with local_files_only=False, and ChatSession._load passes the model ID to the backend loader, which may fetch missing files.", "cached_model_snapshot never downloads (local_files_only=True) and raises FileNotFoundError if the cached snapshot has no config.json." + ], + "core_facts": [ + 1, + 3 ] }, { "id": "file_selection", - "kind": "location", - "set": "development", - "round": "held_out_2", - "question": "Where does KíLín decide which files of a source folder are indexed, and which files does it always leave out?", + "kind": "mechanism", + "question": "Explain how scan_repository decides which files of a source folder are indexed, and which files it always leaves out.", "gold": [ { "path": "kilin/repository.py", @@ -431,14 +491,17 @@ "Environment, cache, and generated folders (such as .git, .venv, __pycache__, node_modules, build, logs, weights) are skipped.", "Potentially secret files (.env and .env.*, credentials.json, secrets.json, SSH keys) and model weights or key files by suffix (.safetensors, .pt, .gguf, .pem, .key, ...) are always skipped.", "Otherwise files are skipped when excluded by the user's selection, outside the included paths, not regular files, of an unselected file type, empty, or larger than the size limit." + ], + "core_facts": [ + 1, + 3, + 4 ] }, { "id": "query_format", "kind": "location", - "set": "development", - "round": "held_out_2", - "question": "How is a question turned into the text that is embedded for semantic search, and does this depend on the project type?", + "question": "Explain how a question is turned into the text that is embedded for semantic search, and whether this depends on the project type.", "gold": [ { "path": "kilin/rag.py", @@ -452,16 +515,19 @@ "facts": [ "With the plain query format in the project profile, the question is embedded unchanged.", "Otherwise the text has two lines, 'Instruct: ' and 'Query: ', the format used by Qwen3 embedding models.", - "The instruction is the project type's retrieval instruction, so it depends on the project type.", + "The instruction is the project type's retrieval instruction (or the project's own, when its behavior settings override it), so it depends on the project type.", "The instruction must be a single nonempty line; surrounding whitespace is removed from both parts.", "Documents are embedded without this instruction." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "conversation_delete", "kind": "mechanism", - "set": "development", - "round": "held_out_2", "question": "Explain what happens to a saved conversation when ChatEngine.delete_conversation is called. Is the conversation file really deleted?", "gold": [ { @@ -474,18 +540,20 @@ } ], "facts": [ - "The file is not deleted: ConversationStore.archive moves it into a deleted folder under logs/traces, so it can be recovered.", + "The file is not deleted: ConversationStore.archive moves it into a hidden .deleted folder under logs/traces, so it can be recovered; its lock companion file stays in place.", "If a file with the same name is already there, the moved file gets a _2, _3, ... suffix.", "The conversation's write lock is held while the file is moved, and the conversation is removed from the store's list.", "If it was the last conversation, a new empty one is created; if it was the active one, the most recently updated remaining conversation becomes active.", "The engine detaches the trace when the active conversation is deleted, switches to the replacement, and records a conversation.deleted event; on errors the list is refreshed and the error reported." + ], + "core_facts": [ + 1, + 2 ] }, { "id": "torch_embedding", "kind": "mechanism", - "set": "development", - "round": "held_out_2", "question": "Explain how EmbeddingSession computes vectors with the PyTorch backend, which token's hidden state it uses, and how the vectors are checked before they are returned.", "gold": [ { @@ -507,14 +575,17 @@ "Vectors are L2-normalized.", "_check_vectors requires one vector per text, the same nonzero dimension for all, finite numeric values, and no all-zero vector; otherwise it raises RuntimeError.", "embed_documents rejects empty or blank texts and a closed session, and does not truncate inputs." + ], + "core_facts": [ + 2, + 3, + 4 ] }, { "id": "notebook_extraction", "kind": "location", - "set": "development", - "round": "held_out_3", - "question": "Where does KíLín turn a Jupyter notebook into searchable text, and which parts of a notebook are left out?", + "question": "Explain how the notebook source extension turns a Jupyter notebook into searchable text, and which parts of a notebook it leaves out.", "gold": [ { "path": "kilin/sources/extensions/sources_ipynb.py", @@ -531,13 +602,15 @@ "Empty cells are skipped.", "Each kept cell is one unit with its one-based position in the original cell list (skipped cells included) and line numbers local to the cell; a Markdown cell's first heading becomes its section.", "A malformed notebook raises ValueError." + ], + "core_facts": [ + 1, + 2 ] }, { "id": "atomic_files", "kind": "mechanism", - "set": "development", - "round": "held_out_3", "question": "Explain how atomic_write_text and atomic_create_text write a file so that it is never left half-written, and how the two differ.", "gold": [ { @@ -555,13 +628,16 @@ "atomic_create_text publishes with a hard link (os.link), so it fails with FileExistsError if the destination already exists and never overwrites; unsupported hard links fail instead of falling back.", "The temporary file is removed in all cases, including failures.", "Neither takes a lock nor forces the data to disk (no fsync)." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "claim_passages_callers", "kind": "dependency", - "set": "development", - "round": "held_out_3", "question": "Explain which functions call claim_passages, and what each of them uses the selected passages for.", "gold": [ { @@ -571,20 +647,28 @@ { "path": "kilin/tools/suggest_reference/tool.py", "symbol": "run" + }, + { + "path": "kilin/tools/reference_check/tool.py", + "symbol": "_second_look" } ], "facts": [ - "The reference_check tool's _verify calls it for each citing claim, with the citing sentence (citation marks removed) and what the reference is cited for, over the cited file's passages; verify_claim then has the model judge whether they support the claim.", + "The reference_check tool's _verify calls it for each citing claim, with the citing sentence (citation marks removed, and the preceding sentence added when the sentence refers back to it), what the reference is cited for, and the focus proposed for co-cited works, over the cited file's passages; verify_claim then has the model judge whether they support the claim.", + "_second_look calls it again for a claim judged not supported or with no matching passage, skipping the passages already read, and a better verdict from these passages replaces the first.", "The suggest_reference tool's run calls it for each candidate paper with the user's statement; judge_support then has the model judge whether that paper supports the statement.", "claim_passages fuses the rankings of its texts by reciprocal rank, keeps at most count passages within a token budget (the best one is always kept), and returns them in reading order." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "model_identity", "kind": "location", - "set": "development", - "round": "held_out_3", - "question": "How does KíLín identify the embedding model that built a saved index, so that it can tell when the model has changed?", + "question": "Explain how the code identifies the embedding model that built a saved index, so that it can tell when the model has changed.", "gold": [ { "path": "kilin/retrievals/model_identity.py", @@ -605,13 +689,16 @@ "Per-file hashes are cached in a manifest outside the model folder and reused when file size, times, device, and inode are unchanged; force_verify rehashes every file.", "The identity is stored with the index; a different identity means the saved vectors are not reused.", "It is meant for index compatibility, not authentication." + ], + "core_facts": [ + 1, + 2, + 4 ] }, { "id": "conversation_branch", "kind": "mechanism", - "set": "development", - "round": "held_out_3", "question": "Explain how ConversationStore creates a branch of a conversation: what is copied from the parent, how the branch is named, and how it avoids overwriting an existing file.", "gold": [ { @@ -624,19 +711,22 @@ } ], "facts": [ - "With branch_from, the parent's saved resumable state is copied, except its metadata fields, while holding the parent's write lock; old trace operations are not copied.", - "The branch records its parent conversation and the parent's checkpoint identifier.", - "It is named ' branch N' with the first N not already used; a new independent conversation is named 'Conversation N'.", + "With branch_from, the parent's saved resumable state is copied, except its metadata fields, while holding the parent's write lock; old trace operations are not copied, and turn_count can keep only the parent's first turns (then the parent's checkpoint is not copied).", + "The branch records its parent conversation, the parent's checkpoint identifier, and the number of turns kept.", + "A branch is named 'Branch: ', then 'Branch 2: ' and so on, after the original conversation even for a branch of a branch, cut to 80 characters; a new independent conversation is named 'Conversation N'.", "A new file path is chosen, locked, and checked; if it already exists, FileExistsError is raised instead of overwriting.", "The new conversation is registered and becomes the active one." + ], + "core_facts": [ + 1, + 3, + 4 ] }, { "id": "python_units", "kind": "location", - "set": "development", - "round": "evaluation", - "question": "How does KíLín divide a Python file into the parts it indexes, and what happens to a file that is not valid Python?", + "question": "Explain how the Python source extension divides a Python file into units, and what happens to a file that is not valid Python.", "gold": [ { "path": "kilin/sources/extensions/sources_py.py", @@ -652,14 +742,17 @@ "Each top-level function becomes one unit, and the code between definitions (imports, constants) becomes module-context units.", "A class becomes one class unit whose children are its methods and the class-level code between them.", "A file that does not parse (SyntaxError) becomes a single python_file unit." + ], + "core_facts": [ + 1, + 2, + 4 ] }, { "id": "pdf_text", "kind": "location", - "set": "development", - "round": "evaluation", - "question": "How does KíLín get the text out of a PDF file, and what happens when a PDF contains no text?", + "question": "Explain how the PDF source extension extracts the text of a PDF file, and what happens when a PDF contains no text.", "gold": [ { "path": "kilin/sources/extensions/sources_pdf.py", @@ -680,14 +773,17 @@ "The text is cleaned (invalid Unicode surrogates, unmapped glyphs, trailing spaces, repeated blank lines).", "A PDF with no extractable text raises an error saying scanned PDFs need OCR.", "Pages are joined with a page break, and each non-empty page becomes one unit labelled with its page number." + ], + "core_facts": [ + 1, + 4, + 5 ] }, { "id": "call_relations", "kind": "location", - "set": "development", - "round": "evaluation", - "question": "How does KíLín work out which functions call which other functions in Python code, and what happens when a called name could refer to several functions?", + "question": "Explain how the code graph works out which functions call which other functions in Python code, and what happens when a called name could refer to several functions.", "gold": [ { "path": "kilin/retrievals/code_graph/extensions/code_graph_py.py", @@ -707,14 +803,17 @@ "For every call, the called expression is turned into a dotted name (a plain name or attribute chain) and recorded as a calls relation from the enclosing function, method, class, or module.", "The name is resolved by its last component against the known entities: a unique match gives the qualified name.", "An ambiguous name is kept as written (unless only one candidate differs from the name itself), so no call is guessed; calls through non-static expressions are not recorded." + ], + "core_facts": [ + 1, + 3, + 4 ] }, { "id": "keyword_scoring", "kind": "location", - "set": "development", - "round": "evaluation", - "question": "How are passages scored in KíLín's keyword search, and how are code identifiers broken into searchable words?", + "question": "Explain how the lexical search scores passages, and how code identifiers are split into searchable words.", "gold": [ { "path": "kilin/retrievals/strategies/retrieval_lexical.py", @@ -734,13 +833,16 @@ "Adjacent words also form two-word terms; there is no stemming or stop-word removal.", "Each passage and the query become TF-IDF vectors with sublinear term frequency (1 + log f) and smoothed inverse document frequency, normalized to unit length.", "Passages are ranked by cosine similarity, ties by chunk identifier, with no minimum score." + ], + "core_facts": [ + 1, + 3, + 4 ] }, { "id": "follow_up_query", "kind": "mechanism", - "set": "development", - "round": "evaluation", "question": "Explain how refers_back decides that a question depends on the earlier conversation, and how search_text uses that to build the search query.", "gold": [ { @@ -757,13 +859,16 @@ "search_text returns the question unchanged unless the routing decision refers back and lists related turns.", "Otherwise it appends the questions of the related turns, with whitespace normalized, after the new question.", "Model-written text (earlier answers) is never added to the query." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "download_progress", "kind": "mechanism", - "set": "development", - "round": "evaluation", "question": "Explain how download_model reports download progress to its caller, and where the downloaded model files are stored.", "gold": [ { @@ -781,13 +886,15 @@ "That class disables terminal output and reports only the aggregate byte bar as (completed bytes, total bytes).", "Because a disabled tqdm stops counting, the class keeps the count itself.", "It returns the snapshot path and does not load the model." + ], + "core_facts": [ + 1, + 2 ] }, { "id": "reference_matching", "kind": "mechanism", - "set": "development", - "round": "evaluation", "question": "Explain how match_reference decides which project file a reference entry points to, and when a match is only probable.", "gold": [ { @@ -805,13 +912,16 @@ "Otherwise the score is the share of the file's title words found in the entry (or of the entry's words found on the first page when there is no title), compared with found and probable thresholds.", "A high score with a different first author, or a lower score with the same first author, is only probable.", "Found matches come before probable ones, then higher scores; other matches are listed as alternatives; an entry with too few distinctive words is unreadable, and one with no candidate is missing." + ], + "core_facts": [ + 1, + 3, + 4 ] }, { "id": "term_hits_callers", "kind": "dependency", - "set": "development", - "round": "evaluation", "question": "Explain which functions call term_hits, and what each of them does with the passages it returns.", "gold": [ { @@ -833,13 +943,16 @@ "find_fact's run uses them for its quick version: only the parts that contain a hit, per file.", "find_passages' run uses them for its quick version: the sentences of those passages, found without the model.", "Without terms, each falls back to the best-ranked passages." + ], + "core_facts": [ + 2, + 3, + 4 ] }, { "id": "explicit_imports_callers", "kind": "dependency", - "set": "development", - "round": "evaluation", "question": "Explain which functions call include_explicit_imports, and why each of them needs it.", "gold": [ { @@ -856,13 +969,16 @@ "_prepare_retrieval uses the scan to build the source manifest and compare it with the saved index, to decide whether to reuse or rebuild it.", "_prepare_source uses it (when no report is supplied) to choose which files to read and split into chunks.", "include_explicit_imports adds files the user imported one by one (recorded in sources.json) even when their suffix or name would otherwise be skipped; size limits and link safeguards still apply, and imported folders keep the normal rules." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "extension_callers", "kind": "dependency", - "set": "development", - "round": "evaluation", "question": "Explain which functions call normalize_extensions, and what each of them checks with it.", "gold": [ { @@ -883,14 +999,17 @@ "_read_profile checks the extensions setting of a project's profile.ini.", "_parse_project_type checks the extensions declared by a project-type JSON file.", "scan_repository checks the extensions it is asked to select before scanning." + ], + "core_facts": [ + 2, + 3, + 4 ] }, { "id": "markdown_sections", "kind": "location", - "set": "evaluation", - "round": "evaluation_2", - "question": "How does KíLín split a Markdown file into searchable parts, and what happens to the opening lines that come before any heading?", + "question": "Explain how the Markdown source extension splits a Markdown file into searchable parts, and what happens to the opening lines that come before any heading.", "gold": [ { "path": "kilin/sources/extensions/sources_md.py", @@ -906,14 +1025,16 @@ "Headings inside backtick or tilde code fences are ignored.", "The text before the first heading becomes a separate preamble unit.", "Each section keeps its heading title and original line range; nested structure and underlined (setext) headings are not recognized." + ], + "core_facts": [ + 1, + 3 ] }, { "id": "matlab_calls", "kind": "location", - "set": "evaluation", - "round": "evaluation_2", - "question": "How does KíLín work out which functions a MATLAB file calls, and how does this differ from the way it handles Python?", + "question": "Explain how the code graph works out which functions a MATLAB file calls, and how this differs from the way it handles Python.", "gold": [ { "path": "kilin/retrievals/code_graph/extensions/code_graph_m.py", @@ -921,19 +1042,22 @@ } ], "facts": [ - "MATLAB relations come from regular expressions over the text, not from a parser; the code is never run.", + "MATLAB relations come from regular expressions over the text, with comments and strings skipped, not from a parser; the code is never run.", "A classdef makes the class the parent of the file's functions and records inheritance from its base class.", - "Each function's body runs until the next function declaration; every name followed by an opening parenthesis in it is recorded as a call, except control words such as if, for, while, and switch.", + "Each function's body runs until the next function declaration; every name followed by an opening parenthesis in it is recorded as a call (by its last name for a call through an object), except control words such as if, for, while, and switch; py.module.function(...) is recorded as a call into Python.", "Names are resolved against known entities with the shared name resolution, as for Python.", - "Python files are parsed into syntax trees instead; MATLAB matches can miss or misread comments, strings, and nested constructs." + "Python files are parsed into syntax trees instead; MATLAB matches can miss or misread multiline declarations and nested definitions." + ], + "core_facts": [ + 1, + 3, + 5 ] }, { "id": "long_document", - "kind": "location", - "set": "evaluation", - "round": "evaluation_2", - "question": "When a question asks KíLín to read a whole file that does not fit in the evidence budget, how are the parts the model sees chosen?", + "kind": "mechanism", + "question": "Explain how read_document chooses the chunks of a long file to give the model when the whole file does not fit in the evidence budget.", "gold": [ { "path": "kilin/retrievals/document_reading.py", @@ -949,14 +1073,17 @@ "If the whole file fits the budget (estimated tokens), it is supplied whole.", "Otherwise its chunks are taken in the order of the fused search ranking, unranked chunks last; a chunk that does not fit is skipped while smaller later ones may still fit.", "The selected chunks are given to the model in source order, all from one file." + ], + "core_facts": [ + 2, + 3, + 4 ] }, { "id": "exact_mentions", - "kind": "location", - "set": "evaluation", - "round": "evaluation_2", - "question": "How does KíLín find every place where an exact name appears in the project, and how does it avoid matching the name inside a longer word?", + "kind": "mechanism", + "question": "Explain how scan_mentions matches a term only as a whole word, and how it avoids counting overlapping chunks twice.", "gold": [ { "path": "kilin/tools/_shared/mentions.py", @@ -976,14 +1103,16 @@ "Each term becomes a regular expression whose parts may be joined by spaces, underscores, or hyphens.", "With whole words, the term may not continue into adjacent letters or digits (MRI does not match MRIs).", "Case sensitivity is an option (the code project's mention listing matches case); each occurrence keeps its file, line, and a few context lines." + ], + "core_facts": [ + 1, + 3 ] }, { "id": "answer_streaming", - "kind": "location", - "set": "evaluation", - "round": "evaluation_2", - "question": "How does the desktop app show an answer while the model is still writing it?", + "kind": "mechanism", + "question": "Explain how ChatEngine.ask and _AnswerStream send the answer to the window while the model is still generating it.", "gold": [ { "path": "kilin/gui/engine.py", @@ -1003,14 +1132,17 @@ "The stream buffers pieces and sends them to the window as answer_delta events at most every 0.08 seconds.", "After the answer, flush sends whatever is left.", "With MLX the text arrives piece by piece; PyTorch generation is not streamed, so it arrives at once." + ], + "core_facts": [ + 1, + 2, + 3 ] }, { "id": "superscript_citations", "kind": "location", - "set": "evaluation", - "round": "evaluation_2", - "question": "How does KíLín recognize citation numbers printed as small raised numbers in a PDF, and how does it avoid mistaking other raised numbers for citations?", + "question": "Explain how the reference check recognizes citation numbers printed as small raised numbers in a PDF, and how it avoids mistaking other raised numbers for citations.", "gold": [ { "path": "kilin/tools/reference_check/_citations.py", @@ -1027,17 +1159,19 @@ ], "facts": [ "pdfminer.six reads each line's characters with their size and position; digits, commas, and dashes smaller than a set share of the line's median letter size and raised above its baseline form a superscript run.", - "Each run is stored with the text printed just before it, as a signature.", + "Each run is stored with the text printed just before it as a signature, or, for a run printed first on its line, with the text printed after it.", "A number found in a sentence counts as a superscript citation only when the PDF confirms a matching raised run there.", "Superscripts in author lists, affiliations, and equations are skipped; a written-out 'Ref. 50' needs no confirmation.", "If the PDF cannot be read this way, no superscript is confirmed." + ], + "core_facts": [ + 1, + 3 ] }, { "id": "claim_verdict", "kind": "mechanism", - "set": "evaluation", - "round": "evaluation_2", "question": "Explain how verify_claim reaches a verdict on a cited claim, and how the quote the model gives is checked.", "gold": [ { @@ -1058,14 +1192,18 @@ "Otherwise the model sees the claim and the cited passages and replies with a verdict, a quote, and a comment.", "An unrecognized verdict becomes 'unclear', with the reply as comment.", "The quote is kept only if it is found in a passage word for word, or for most of its words in order; otherwise it is dropped and the comment says so.", - "'contradicted' without a confirmed quote becomes 'not supported'." + "'contradicted' without a confirmed quote becomes 'not supported'.", + "Each verdict gets an evidence status: exact or approximate when the quote is found, rejected when it is not, not required for not supported, no matching passage, or unclear, and missing otherwise." + ], + "core_facts": [ + 2, + 4, + 5 ] }, { "id": "output_saving", "kind": "mechanism", - "set": "evaluation", - "round": "evaluation_2", "question": "Explain how save_output_file writes a tool's output into the project without overwriting an existing file.", "gold": [ { @@ -1087,13 +1225,16 @@ "It is then published under the requested name with a hard link, which fails if the name exists; the next candidates are name-2, name-3, and so on.", "If hard links are not supported, the staged file is copied into a newly and exclusively created file, which also cannot overwrite.", "The staging file is removed afterwards; concurrent saves get different names." + ], + "core_facts": [ + 2, + 3, + 4 ] }, { "id": "newest_listed_callers", "kind": "dependency", - "set": "evaluation", - "round": "evaluation_2", "question": "Explain which functions call newest_listed, and what each of them does with the earlier turn it returns.", "gold": [ { @@ -1110,13 +1251,15 @@ "filter_results' run judges that turn's listed items against the question in batches with the model and keeps the matching ones.", "show_source's run picks the cited passages of that turn that the question and the earlier answer point to, and shows their text word for word with nearby sentences.", "Without such a turn, both reply that there is no earlier answer to work from." + ], + "core_facts": [ + 2, + 3 ] }, { "id": "workspace_path_callers", "kind": "dependency", - "set": "evaluation", - "round": "evaluation_2", "question": "Explain which functions call default_workspace_path, and when each of them uses the folder it suggests.", "gold": [ { @@ -1129,10 +1272,14 @@ } ], "facts": [ - "default_workspace_path suggests -<8-character hash of its path> inside a parent folder, without creating or reserving it.", + "default_workspace_path suggests -<8-character hash of its path> inside a parent folder, or new-project when there are no sources, without creating or reserving it.", "The GUI's _workspace_path uses it when the user has not chosen a workspace folder; a chosen folder is used as given.", "prepare_sources_workspace uses it when given a parent folder instead of a workspace folder.", "Creation reserves the folder exclusively and may pick a numbered sibling if the suggested folder is taken." + ], + "core_facts": [ + 2, + 3 ] } ] diff --git a/_si_article_/code_analysis/paper_numbers.py b/_si_article_/code_analysis/paper_numbers.py index 96284c81..0f6bce29 100644 --- a/_si_article_/code_analysis/paper_numbers.py +++ b/_si_article_/code_analysis/paper_numbers.py @@ -58,6 +58,7 @@ sys.path.insert(0, str(REPOSITORY_ROOT)) from assets.trace_benchmark import ( # noqa: E402 + _operation_rows, read_trace_operations, summarize_trace_turns, ) @@ -95,6 +96,9 @@ # Initialization operations reported separately from question turns. _STARTUP_OPERATIONS = ( "session.ready", + "source.read", + "source.extract", + "source.chunk", "model.embedding.load", "model.chat.load", "indexing", @@ -247,19 +251,60 @@ def export_revision( return {"ref": ref, "commit": commit, "excluded": list(excludes)} -def _disable_downloads(profile_path: Path) -> None: - """Set ``allow_download = false`` in a sandbox project profile.""" +def default_temperature(type_id: str) -> float: + """Return the temperature a new project of this type starts with. - text = profile_path.read_text(encoding="utf-8") - updated, count = re.subn( - r"^(\s*allow_download\s*=\s*).*$", - r"\1false", - text, - flags=re.M, + Parameters + ---------- + type_id: str + Project type ID, such as ``code`` or ``literature``. + + Returns + ------- + float + The type's own temperature, or the packaged default when the type + does not set one. + + """ + + from kilin.project import _PROFILE_TEMPERATURE + from kilin.project_type import load_project_types + + temperature = load_project_types()[type_id].generation_temperature + return _PROFILE_TEMPERATURE if temperature is None else temperature + + +def set_router_model(project: object, model_id: str | None) -> str: + """Save the project's intent (router) model and return it. + + Parameters + ---------- + project: kilin.QAProject + Sandbox project to configure. + model_id: str | None + Hugging Face model ID or local folder, or None for the packaged + default. Writing the default too means a model saved by an earlier + run never carries over. + + Returns + ------- + str + The router model the project now uses. + + """ + + import kilin + from kilin.model_settings import ( + default_router_model, + read_router_model, + write_router_model, ) - if count != 1: - raise RuntimeError("Could not find allow_download in profile.ini.") - profile_path.write_text(updated, encoding="utf-8") + + backend = kilin.choose_backend(project.profile.backend) + write_router_model( + project.root, backend, model_id or default_router_model(backend) + ) + return read_router_model(project.root, backend) def prepare_code_project( @@ -280,7 +325,9 @@ def prepare_code_project( Returns ------- tuple[kilin.QAProject, dict[str, object]] - The sandbox project and the description of the indexed revision. + The sandbox project, set to the code type's default temperature + (also in a workspace saved with another value), and the description + of the indexed revision. Notes ----- @@ -324,8 +371,15 @@ def prepare_code_project( f"Expected the sandbox workspace {workspace}, " f"got {project.root}." ) - if not allow_download: - _disable_downloads(project.root / "profile.ini") + from kilin.project import configure_project + + project = configure_project( + project.root, + { + "temperature": default_temperature("code"), + "allow_download": allow_download, + }, + ) return project, revision @@ -421,11 +475,94 @@ def peak_memory_gb() -> dict[str, float]: return result -def _startup_operations(trace_path: Path, label: str) -> dict[str, float]: - """Sum completed initialization operations of one traced opening.""" +# Since the project trace was introduced, startup events (indexing, model +# loading) are recorded in logs/traces/project.json rather than in the +# conversation trace; each session's entries end with its trace ID. +_PROJECT_TRACE = Path("logs") / "traces" / "project.json" +_TRACE_SUFFIX = re.compile(r"_(trace_[0-9a-f]+)$") + + +def _project_sessions(project_root: Path) -> dict[str, dict]: + """Return the project trace's sessions, or none when it is absent.""" + + path = project_root / _PROJECT_TRACE + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + sessions = payload.get("sessions") if isinstance(payload, dict) else None + return sessions if isinstance(sessions, dict) else {} + +def project_trace_ids(project_root: Path) -> frozenset[str]: + """List the session trace IDs already in the project trace. + + Parameters + ---------- + project_root: pathlib.Path + KíLín workspace. + + Returns + ------- + frozenset[str] + Trace IDs (``trace_…``) of the recorded sessions; empty when the + project has no project trace. + + """ + + return frozenset( + match.group(1) + for key in _project_sessions(project_root) + if (match := _TRACE_SUFFIX.search(key)) + ) + + +def _startup_operations( + trace_path: Path, + label: str, + project_root: Path | None = None, + known: frozenset[str] = frozenset(), +) -> dict[str, float]: + """Sum completed initialization operations of one traced opening. + + Parameters + ---------- + trace_path: pathlib.Path + Conversation trace of the session. + label: str + Run label. + project_root: pathlib.Path | None, optional + Workspace whose project trace holds the startup events in current + KíLín versions. Defaults to None (conversation trace only). + known: frozenset[str], optional + Trace IDs present before the session opened (``project_trace_ids``), + so that only the new session's events are counted. Defaults to none. + + Returns + ------- + dict[str, float] + Seconds per startup operation; empty when no events were recorded. + + """ + + rows = list(read_trace_operations(trace_path, label)) + if project_root is not None: + for key, session in _project_sessions(project_root).items(): + match = _TRACE_SUFFIX.search(key) + if ( + match is None + or match.group(1) in known + or not isinstance(session, dict) + or not isinstance(session.get("operations"), dict) + ): + continue + rows.extend(_operation_rows( + session["operations"], label=label, + category=str(session.get("category", "")), stage="", + turn=None, + )) totals: dict[str, float] = defaultdict(float) - for row in read_trace_operations(trace_path, label): + for row in rows: if ( row.get("turn") is None and row.get("status") == "completed" @@ -542,6 +679,11 @@ def main(argv: Sequence[str] | None = None) -> int: action="store_true", help="use the default intent instead of the router", ) + parser.add_argument( + "--router-model", default=None, + help="intent (router) model of the project, a Hugging Face ID such " + "as Qwen/Qwen3-8B-MLX-4bit (default: the packaged default)", + ) parser.add_argument( "--include-examples", action="store_true", @@ -573,6 +715,7 @@ def main(argv: Sequence[str] | None = None) -> int: ["git", "-C", str(REPOSITORY_ROOT), "rev-parse", "HEAD"] ), "use_router": not args.no_router, + "temperature": default_temperature("code"), } # 1. Export the pinned revision outside the repository and mirror it. @@ -581,6 +724,7 @@ def main(argv: Sequence[str] | None = None) -> int: args.ref, excludes, allow_download=args.allow_download ) results["indexed_revision"] = revision + results["router_model"] = set_router_model(project, args.router_model) project_root = project.root backend = kilin.choose_backend(project.profile.backend) results["models"] = { @@ -593,19 +737,25 @@ def main(argv: Sequence[str] | None = None) -> int: if index_file.exists(): index_file.unlink() _reset_backend_peak() + known = project_trace_ids(project_root) session, cold = open_session(project_root, "cold") trace_path = Path(session.conversation_path) session.close() - cold["operations_s"] = _startup_operations(trace_path, "cold") + cold["operations_s"] = _startup_operations( + trace_path, "cold", project_root, known + ) results["cold_open"] = cold results["corpus"] = corpus_size(project_root, project.source) print(f"Cold opening: {cold['wall_s']} s ({cold['index_status']})") # 3. Warm opening with unchanged sources. + known = project_trace_ids(project_root) session, warm = open_session(project_root, "warm") warm_trace = Path(session.conversation_path) session.close() - warm["operations_s"] = _startup_operations(warm_trace, "warm") + warm["operations_s"] = _startup_operations( + warm_trace, "warm", project_root, known + ) results["warm_open"] = warm print(f"Warm opening: {warm['wall_s']} s ({warm['index_status']})") diff --git a/_si_article_/literature_repo/papers/hosseini12gat.pdf b/_si_article_/literature_repo/papers/hosseini12gat.pdf new file mode 100644 index 00000000..609fce98 Binary files /dev/null and b/_si_article_/literature_repo/papers/hosseini12gat.pdf differ diff --git a/_si_article_/literature_repo/papers/mijalkov21dendritic.pdf b/_si_article_/literature_repo/papers/mijalkov21dendritic.pdf new file mode 100644 index 00000000..be538fe4 Binary files /dev/null and b/_si_article_/literature_repo/papers/mijalkov21dendritic.pdf differ diff --git a/_si_article_/literature_repo/papers/tanner24multimodal.pdf b/_si_article_/literature_repo/papers/tanner24multimodal.pdf new file mode 100644 index 00000000..0fe326ab Binary files /dev/null and b/_si_article_/literature_repo/papers/tanner24multimodal.pdf differ diff --git a/_si_article_/literature_repo/papers/wang15gretna.pdf b/_si_article_/literature_repo/papers/wang15gretna.pdf new file mode 100644 index 00000000..933f0fcd Binary files /dev/null and b/_si_article_/literature_repo/papers/wang15gretna.pdf differ diff --git a/_si_article_/literature_repo/papers/xia13brainnet.pdf b/_si_article_/literature_repo/papers/xia13brainnet.pdf new file mode 100644 index 00000000..b1153239 Binary files /dev/null and b/_si_article_/literature_repo/papers/xia13brainnet.pdf differ diff --git a/_si_article_/literature_repo/papers/yan25roadmap.pdf b/_si_article_/literature_repo/papers/yan25roadmap.pdf new file mode 100644 index 00000000..02b2c4b2 Binary files /dev/null and b/_si_article_/literature_repo/papers/yan25roadmap.pdf differ diff --git a/_si_article_/reference_analysis/make_planted.py b/_si_article_/reference_analysis/make_planted.py new file mode 100644 index 00000000..ff262468 --- /dev/null +++ b/_si_article_/reference_analysis/make_planted.py @@ -0,0 +1,241 @@ +"""Make the copy of the reference-example article with planted miscitations. + +Each planted miscitation changes one bracketed citation number in the +article, such as ``[15]`` to ``[25]``, so that the sentence now cites a work +in the project that does not support it. + +The copy is a plain-text file: the article's text read with the PDF reader +KíLín itself uses (pdfminer.six, with the same layout settings), with the +numbers changed. Editing the PDF instead (covering a number and printing +another) splits the edited lines into separate text blocks for that +reader, so the sentences around each change would no longer be read as +they are printed. + +The script writes the copy next to the annotation file under the name in +its ``planted_file`` key, and records the changes in its ``planted`` key, +which ``reference_example.py`` scores. Run it from the repository root, +then check the copy:: + + uv run --no-sync python \\ + _si_article_/reference_analysis/make_planted.py + uv run --no-sync python \\ + _si_article_/reference_analysis/reference_example.py --only planted + +The six "clear" changes cite a work on an unrelated subject; the two +"near" changes cite a related work (another toolbox; another paper that +uses BRAPH 2), which the tool may judge partly supported rather than flag. +Only citations that the unmodified run judged supported, with an exact +quotation, are changed, so a flag can come only from the change. + +""" + +from __future__ import annotations + +from argparse import ArgumentParser +from collections.abc import Sequence +import json +from pathlib import Path +import re +import sys + +REPOSITORY_ROOT = Path(__file__).resolve().parents[2] +ANALYSIS_DIRECTORY = Path(__file__).resolve().parent +ANNOTATIONS_FILE = ANALYSIS_DIRECTORY / "reference_annotations.json" + +# Each change: the words printed just before the marker (to find it), the +# original and planted numbers, how clear the mismatch is, and a few +# distinctive words of the citing sentence (for scoring). +PLANTS: tuple[dict[str, object], ...] = ( + {"before": "[14], GAT", "original": 15, "planted": 25, + "kind": "clear", + "text": "Many free and open-source software platforms"}, + {"before": "BrainNet Viewer", "original": 17, "planted": 20, + "kind": "clear", + "text": "Many free and open-source software platforms"}, + {"before": "elimination pipeline for deep learning", "original": 22, + "planted": 3, "kind": "clear", + "text": "recursive feature elimination pipeline for deep learning"}, + {"before": "loss in postmortem brain tissue", "original": 25, + "planted": 18, "kind": "clear", + "text": "dendritic spine loss in postmortem brain tissue"}, + {"before": "approaches for evaluating cognitive decline", "original": 23, + "planted": 15, "kind": "clear", + "text": "reservoir computing approaches for evaluating cognitive"}, + {"before": "pipeline for recursive feature elimination", "original": 22, + "planted": 17, "kind": "clear", + "text": "Its flexibility is illustrated through three case studies"}, + {"before": "Viewer [17], GRETNA", "original": 18, "planted": 15, + "kind": "near", + "text": "Many free and open-source software platforms"}, + {"before": "study brain network memory capacity", "original": 23, + "planted": 22, "kind": "near", + "text": "standalone distribution for reservoir computing to study"}, +) + + +def article_text(article: Path) -> str: + """Read the article's text as KíLín reads a PDF file. + + Parameters + ---------- + article: pathlib.Path + The article. + + Returns + ------- + str + The text from pdfminer.six with default layout settings. + + """ + + from pdfminer.high_level import extract_text + from pdfminer.layout import LAParams + + return extract_text(str(article), laparams=LAParams()) + + +def marker_pattern(plant: dict[str, object]) -> re.Pattern[str]: + """Return the pattern of one marker after its preceding words. + + Parameters + ---------- + plant: dict[str, object] + One entry of ``PLANTS``. + + Returns + ------- + re.Pattern[str] + Matches the words (separated by any white space) and the marker; + the number is the group ``number``. + + """ + + words = [re.escape(word) for word in str(plant["before"]).split()] + return re.compile( + r"\s+".join(words) + + r"\s*\[(?P" + str(plant["original"]) + r")\]" + ) + + +def make_copy(article: Path, output: Path) -> list[dict[str, object]]: + """Write the text copy of the article with every planned change. + + Parameters + ---------- + article: pathlib.Path + The original article. + output: pathlib.Path + Path of the copy. + + Returns + ------- + list[dict[str, object]] + The changes made, for the annotation file. + + Raises + ------ + SystemExit + If a marker is not found exactly once. + + """ + + text = article_text(article) + spans = [] + for plant in PLANTS: + matches = list(marker_pattern(plant).finditer(text)) + if len(matches) != 1: + raise SystemExit( + f"Expected one [{plant['original']}] after " + f"'{plant['before']}', found {len(matches)}." + ) + spans.append((matches[0].span("number"), plant)) + # Replace from the end, so earlier positions stay valid. + for (start, end), plant in sorted(spans, key=lambda s: -s[0][0]): + text = text[:start] + str(plant["planted"]) + text[end:] + output.write_text(text, encoding="utf-8") + return [dict(plant) for _, plant in spans] + + +def check_copy(output: Path, changes: list[dict[str, object]]) -> None: + """Confirm that every planted number follows its words in the copy. + + Parameters + ---------- + output: pathlib.Path + The copy. + changes: list[dict[str, object]] + The changes made. + + Raises + ------ + SystemExit + If a planted number is missing. + + """ + + text = output.read_text(encoding="utf-8") + for change in changes: + # The preceding words can hold another changed marker. + before = str(change["before"]) + for other in changes: + before = before.replace( + f"[{other['original']}]", f"[{other['planted']}]" + ) + planted = {**change, "before": before, "original": change["planted"]} + if not marker_pattern(planted).search(text): + raise SystemExit( + f"[{change['planted']}] after '{change['before']}' is not " + "in the copy." + ) + + +def main(argv: Sequence[str] | None = None) -> int: + """Make the planted copy and record it in the annotation file. + + Parameters + ---------- + argv: Sequence[str] | None, optional + Command-line arguments. Defaults to ``None``, which reads + ``sys.argv``. + + Returns + ------- + int + Exit status, 0 on success. + + """ + + parser = ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument( + "--annotations", type=Path, default=ANNOTATIONS_FILE, + help="annotation file (default: reference_annotations.json)", + ) + args = parser.parse_args(argv) + + annotations = json.loads(args.annotations.read_text(encoding="utf-8")) + article = REPOSITORY_ROOT / annotations["corpus_folder"] / ( + annotations["article"] + ) + output = args.annotations.parent / annotations["planted_file"] + changes = make_copy(article, output) + check_copy(output, changes) + annotations["planted"] = [ + {key: change[key] for key in + ("text", "original", "planted", "kind", "before")} + for change in changes + ] + args.annotations.write_text( + json.dumps(annotations, indent=2, ensure_ascii=False) + "\n", + encoding="utf-8", + ) + for change in changes: + print(f"[{change['original']}] → " + f"[{change['planted']}] ({change['kind']}) after " + f"'{change['before']}'") + print(f"Wrote {output.relative_to(REPOSITORY_ROOT)} and the 'planted' " + f"list of {args.annotations.name}.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/_si_article_/reference_analysis/reference_annotations.json b/_si_article_/reference_analysis/reference_annotations.json new file mode 100644 index 00000000..5834f898 --- /dev/null +++ b/_si_article_/reference_analysis/reference_annotations.json @@ -0,0 +1,227 @@ +{ + "_instructions": [ + "Hand annotations for reference_example.py. Keys starting with '_' are ignored.", + "article: file name of the citing article inside corpus_folder.", + "corpus_folder: folder of the corpus, relative to the repository root; the script exports it with git archive, so commit it first.", + "planted_file: text copy of the article with planted miscitations, written by make_planted.py next to this file (it may stay outside git). It is added to the papers project under its own file name, which must differ from the article's.", + "Projects (as in the app): sandbox/reference_example/project_reference_papers holds the article, the planted copy and the cited works; project_reference_suggest holds the cited works only.", + "check_question and suggest_question: the requests, as a user would type them.", + "references: for each reference number, the expected project file (file name), or null when the cited work is not in the project. Leave it empty to report the counts only.", + "citations: every in-text citation identified by hand in the original article, before looking at the tool's output. text = a few distinctive words of the citing sentence, copied from the PDF; references = all numbers the marker cites (expand ranges: [1-4] gives 1, 2, 3, 4).", + "planted: written by make_planted.py; one entry per planted miscitation. text = distinctive words of the citing sentence; original = the number printed in the published article; planted = the number in the copy; kind = clear or near.", + "suggestions: test sentences for suggest_reference, written without a citation marker and fixed before running. group = tools, uses, results (one work states it; expected lists that file) or background (several works support it; expected lists every acceptable file). Specific sentences state what the expected work reports, as a careful author would cite it." + ], + "article": "tiunn26braph2.pdf", + "corpus_folder": "_si_article_/literature_repo/papers", + "planted_file": "tiunn26braph2_planted.txt", + "check_question": "Check the references of {article}", + "suggest_question": "Suggest a reference for: \"{sentence}\"", + "references": {}, + "citations": [], + "planted": [ + { + "text": "Many free and open-source software platforms", + "original": 15, + "planted": 25, + "kind": "clear", + "before": "[14], GAT" + }, + { + "text": "Many free and open-source software platforms", + "original": 17, + "planted": 20, + "kind": "clear", + "before": "BrainNet Viewer" + }, + { + "text": "recursive feature elimination pipeline for deep learning", + "original": 22, + "planted": 3, + "kind": "clear", + "before": "elimination pipeline for deep learning" + }, + { + "text": "dendritic spine loss in postmortem brain tissue", + "original": 25, + "planted": 18, + "kind": "clear", + "before": "loss in postmortem brain tissue" + }, + { + "text": "reservoir computing approaches for evaluating cognitive", + "original": 23, + "planted": 15, + "kind": "clear", + "before": "approaches for evaluating cognitive decline" + }, + { + "text": "Its flexibility is illustrated through three case studies", + "original": 22, + "planted": 17, + "kind": "clear", + "before": "pipeline for recursive feature elimination" + }, + { + "text": "Many free and open-source software platforms", + "original": 18, + "planted": 15, + "kind": "near", + "before": "Viewer [17], GRETNA" + }, + { + "text": "standalone distribution for reservoir computing to study", + "original": 23, + "planted": 22, + "kind": "near", + "before": "study brain network memory capacity" + } + ], + "suggestions": [ + { + "group": "tools", + "text": "GAT is an open-source toolbox for graph-theoretical analysis of between-group differences in brain networks.", + "expected": [ + "hosseini12gat.pdf" + ] + }, + { + "group": "tools", + "text": "BrainNet Viewer is a tool for visualizing brain connectomes.", + "expected": [ + "xia13brainnet.pdf" + ] + }, + { + "group": "tools", + "text": "GRETNA is an open-source toolbox with a graphical user interface for imaging connectomics.", + "expected": [ + "wang15gretna.pdf" + ] + }, + { + "group": "tools", + "text": "BRAPH is an object-oriented software for graph-theory analysis of brain connectivity with a graphical user interface.", + "expected": [ + "mijalkov17braph.pdf" + ] + }, + { + "group": "uses", + "text": "Recursive feature elimination with deep learning has been used to classify schizophrenia from brain connectivity.", + "expected": [ + "yao25connecting.pdf" + ] + }, + { + "group": "uses", + "text": "Reservoir computing has been used to measure the memory capacity of brain networks in cognitive decline.", + "expected": [ + "mijalkov25computational.pdf" + ] + }, + { + "group": "uses", + "text": "Dendritic spine organization has been compared between neurons with and without tau pathology in postmortem brain tissue.", + "expected": [ + "mijalkov21dendritic.pdf" + ] + }, + { + "group": "uses", + "text": "Deploying machine learning in healthcare requires monitoring models after deployment.", + "expected": [ + "yan25roadmap.pdf" + ] + }, + { + "group": "results", + "text": "Tau pathology causes dendritic spines to be lost in clusters rather than at random locations.", + "expected": [ + "mijalkov21dendritic.pdf" + ] + }, + { + "group": "results", + "text": "The memory capacity of brain-network reservoirs is a robust marker of aging and is associated with cognitive performance.", + "expected": [ + "mijalkov25computational.pdf" + ] + }, + { + "group": "results", + "text": "Subregions of the hippocampus and amygdala show the strongest enrichment of genetic risk for schizophrenia.", + "expected": [ + "yao25connecting.pdf" + ] + }, + { + "group": "results", + "text": "Survivors of acute lymphoblastic leukemia show altered small-world organization of structural brain networks.", + "expected": [ + "hosseini12gat.pdf" + ] + }, + { + "group": "results", + "text": "Directed and signed edge weights estimated from multimodal data are subject-specific and highly reliable.", + "expected": [ + "tanner24multimodal.pdf" + ] + }, + { + "group": "background", + "text": "Network analyses have rapidly gained traction in neuroscience, linking brain regions, clinical scores, and biomarkers.", + "expected": [ + "tanner24multimodal.pdf", + "hosseini12gat.pdf", + "wang15gretna.pdf", + "xia13brainnet.pdf", + "mijalkov17braph.pdf", + "yao25connecting.pdf", + "mijalkov25computational.pdf" + ] + }, + { + "group": "background", + "text": "Reproducibility of analysis workflows is an increasingly important concern.", + "expected": [ + "mijalkov17braph.pdf", + "yan25roadmap.pdf", + "tanner24multimodal.pdf" + ] + } + ], + "_examples": { + "references": { + "19": "mijalkov17braph.pdf", + "13": null + }, + "citations": [ + { + "text": "linking multiple brain regions, clinical scores, and biomarkers", + "references": [ + 1, + 2, + 3, + 4 + ] + } + ], + "planted": [ + { + "text": "and BRAPH 1", + "original": 19, + "planted": 22 + } + ], + "suggestions": [ + { + "group": "tools", + "text": "BRAPH 1 is a free and open-source software platform for brain connectivity analysis.", + "expected": [ + "mijalkov17braph.pdf" + ] + } + ] + } +} diff --git a/_si_article_/reference_analysis/reference_example.py b/_si_article_/reference_analysis/reference_example.py new file mode 100644 index 00000000..587dd96a --- /dev/null +++ b/_si_article_/reference_analysis/reference_example.py @@ -0,0 +1,1275 @@ +"""Run the paper's reference example: checking and suggesting references. + +The script builds two literature projects from a committed revision of +the article corpus, as a user would in the desktop app, and asks KíLín, +through the ordinary answering pipeline (router, tool, saved conversation +and trace): + +- project ``reference_papers``: the article, the copy of the article with + planted miscitations, and the works the article cites. Two requests: + check the references of the article (run ``check``), and of the copy + (run ``planted``). A check reads only the named paper and the files its + references match, so the other copy does not take part. +- project ``reference_suggest``: the cited works only. One request per + test sentence for a reference to cite (run ``suggest``). The article and + its copy contain every test sentence word for word, and + ``suggest_reference`` cannot be told to leave a file out, so they are not + in this project. + +Each request is asked in a new conversation; the same requests typed in +the app on the same folders give the same answers. + +Every project generates at the default temperature of the literature +type, as in the app, so a rerun can give slightly different verdicts. +Confirmation prompts are answered "continue": every claim is +checked. The workspaces are kept under ``sandbox/reference_example/`` with +fixed names, so they can be opened in the desktop app afterwards and the +saved conversations used for the figures. + +Scoring uses the hand annotations in ``reference_annotations.json``: + +- reference matching: the file matched to each reference entry, against + the expected file when the annotations give one; +- citation detection: detected (sentence, reference) pairs against the + pairs identified by hand (precision and recall); +- claim checking: the verdict of each planted miscitation (flagged when + "not supported" or "contradicted") and of every unmodified citation of + the original article (flagged ones are possible false alarms, listed for + reading); +- suggestion: for sentences that one work states (tools, uses, results), + the rank of that work among the papers the tool suggested, in the order + of its answer; for background sentences, the rank of the best of the + acceptable works and how many of them were suggested. Papers with the + same verdict and score share a rank, reported as a tie. + +Matching and citation detection are rule-based: the script recomputes them +with the tool's own functions on the indexed passages and checks that the +counts agree with those the tool reported. Verdicts and suggestions are +read from the session trace. + +Results are written to ``_si_article_/reference_analysis/results/`` as +JSON, with a Markdown worksheet for reading the verdicts. + +Usage, from the repository root:: + + uv run --no-sync python \\ + _si_article_/reference_analysis/reference_example.py + uv run --no-sync python \\ + _si_article_/reference_analysis/reference_example.py \\ + --ref v0.1.0 --planted path/to/article_planted.pdf + uv run --no-sync python \\ + _si_article_/reference_analysis/reference_example.py --only check + +Models must already be in the local Hugging Face cache unless +``--allow-download`` is given. + +""" + +from __future__ import annotations + +from argparse import ArgumentParser +from collections.abc import Callable, Sequence +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +from tempfile import TemporaryDirectory, gettempdir +from time import perf_counter + +REPOSITORY_ROOT = Path(__file__).resolve().parents[2] +if str(REPOSITORY_ROOT) not in sys.path: + sys.path.insert(0, str(REPOSITORY_ROOT)) + +from _si_article_.code_analysis.paper_numbers import ( # noqa: E402 + default_temperature, + describe_environment, + routed_intent, + set_router_model, + show_progress, +) + +ANALYSIS_DIRECTORY = Path(__file__).resolve().parent +ANNOTATIONS_FILE = ANALYSIS_DIRECTORY / "reference_annotations.json" +OUTPUT_DIRECTORY = ANALYSIS_DIRECTORY / "results" +WORKSPACE_DIRECTORY = REPOSITORY_ROOT / "sandbox" / "reference_example" + +# Every run generates at the literature type's default temperature. +TEMPERATURE = default_temperature("literature") + +# Verdicts that flag a citation as a problem. +FLAGGED = ("not supported", "contradicted") + +RUNS = ("check", "planted", "suggest") + + +# ------------------------------------------------------------------------- +# Small helpers +# ------------------------------------------------------------------------- + + +def normalized(text: str) -> str: + """Return text reduced to lowercase letters and digits. + + Parameters + ---------- + text: str + Text from a PDF or from the annotations. + + Returns + ------- + str + The text without spaces, punctuation or line-break hyphens, so a + sentence extracted from a PDF matches the annotation of it. + + """ + + return re.sub(r"[^a-z0-9]", "", text.lower()) + + +def sha256(path: Path) -> str: + """Return the SHA-256 digest of a file. + + Parameters + ---------- + path: pathlib.Path + File to hash. + + Returns + ------- + str + Hexadecimal digest. + + """ + + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1 << 20), b""): + digest.update(block) + return digest.hexdigest() + + +def git(*arguments: str) -> str: + """Run a git command in the repository and return its output. + + Parameters + ---------- + *arguments: str + Arguments after ``git -C ``. + + Returns + ------- + str + Stripped standard output. + + Raises + ------ + RuntimeError + If git fails. + + """ + + completed = subprocess.run( + ["git", "-C", str(REPOSITORY_ROOT), *arguments], + capture_output=True, text=True, + ) + if completed.returncode != 0: + raise RuntimeError( + f"git {' '.join(arguments)} failed: {completed.stderr.strip()}" + ) + return completed.stdout.strip() + + +def code_version() -> dict[str, object]: + """Describe the KíLín code that runs the example. + + Returns + ------- + dict[str, object] + The checked-out commit, the installed package version, and whether + ``kilin/`` has uncommitted changes (results of a modified checkout + do not correspond to any commit). + + """ + + import kilin + + changes = git("status", "--porcelain", "--", "kilin") + return { + "commit": git("rev-parse", "HEAD"), + "describe": git("describe", "--tags", "--always", "--dirty"), + "package_version": getattr(kilin, "__version__", None), + "uncommitted_kilin_changes": bool(changes), + } + + +def trace_details(trace_path: Path, operation: str) -> list[dict]: + """Return the details of every traced operation with a given name. + + Parameters + ---------- + trace_path: pathlib.Path + Conversation trace of one session. + operation: str + Operation name without its sequence prefix, such as + ``tool_reference_check_claim``. + + Returns + ------- + list[dict] + The ``details`` of each matching operation, in trace order. + + """ + + found: list[tuple[int, dict]] = [] + + def walk(node: object) -> None: + if isinstance(node, dict): + for key, value in node.items(): + if ( + isinstance(value, dict) + and re.fullmatch(rf"\d+_{operation}", key) + ): + sequence = value.get("event", {}).get("sequence", 0) + found.append((sequence, value.get("details", {}))) + walk(value) + elif isinstance(node, list): + for item in node: + walk(item) + + walk(json.loads(trace_path.read_text(encoding="utf-8"))) + return [details for _, details in sorted(found, key=lambda x: x[0])] + + +# ------------------------------------------------------------------------- +# Corpus and projects +# ------------------------------------------------------------------------- + + +def export_corpus(ref: str, folder: str, destination: Path) -> dict: + """Export the corpus folder of one committed revision. + + Parameters + ---------- + ref: str + Git revision, tag or branch. + folder: str + Corpus folder, relative to the repository root. + destination: pathlib.Path + Empty directory that receives the files of the folder. + + Returns + ------- + dict + The requested reference and the resolved commit. + + Raises + ------ + RuntimeError + If the revision or the folder cannot be exported. + + """ + + commit = git("rev-parse", ref) + archive = subprocess.run( + ["git", "-C", str(REPOSITORY_ROOT), "archive", "--format=tar", + commit, "--", folder], + capture_output=True, + ) + if archive.returncode != 0: + raise RuntimeError( + f"Cannot export {folder} at {ref}: " + f"{archive.stderr.decode(errors='replace').strip()}" + ) + with TemporaryDirectory() as unpacked: + subprocess.run( + ["tar", "-x", "-C", unpacked], input=archive.stdout, check=True + ) + source = Path(unpacked) / folder + for path in sorted(source.rglob("*")): + if path.is_file(): + target = destination / path.relative_to(source) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, target) + return {"ref": ref, "commit": commit, "folder": folder} + + +def stage_sources( + corpus: Path, + article: str, + planted: Path | None, + planted_name: str, + staging: Path, +) -> dict[str, Path]: + """Prepare the source folder of each project. + + Parameters + ---------- + corpus: pathlib.Path + The exported corpus: the article and the works it cites. + article: str + File name of the article within the corpus. + planted: pathlib.Path | None + The copy of the article with planted miscitations, or None. + planted_name: str + File name of the copy in the project. + staging: pathlib.Path + Empty directory for the two source folders. + + Returns + ------- + dict[str, pathlib.Path] + ``papers``: the whole corpus and the copy; ``suggest``: the corpus + without the article. The folder names fix the workspace names + (``project_reference_papers`` and ``project_reference_suggest``). + + """ + + files = [path for path in sorted(corpus.rglob("*")) if path.is_file()] + + def fill(name: str, keep: list[Path]) -> Path: + folder = staging / f"reference_{name}" + folder.mkdir(parents=True) + for path in keep: + target = folder / path.relative_to(corpus) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, target) + return folder + + papers = fill("papers", files) + if planted is not None: + shutil.copy2(planted, papers / planted_name) + suggest = fill( + "suggest", + [path for path in files if path.relative_to(corpus).as_posix() + != article], + ) + return {"papers": papers, "suggest": suggest} + + +def open_project(source: Path, allow_download: bool) -> object: + """Create or synchronize a literature workspace for one run. + + Parameters + ---------- + source: pathlib.Path + Source folder of the run. + allow_download: bool + Keep model downloads enabled. + + Returns + ------- + kilin.QAProject + The workspace ``sandbox/reference_example/project_``, + set to the literature type's default temperature (also in a + workspace saved with another value). + + """ + + import kilin + from kilin.project import configure_project + + WORKSPACE_DIRECTORY.mkdir(parents=True, exist_ok=True) + workspace = WORKSPACE_DIRECTORY / f"project_{source.name}" + project = None + if workspace.exists(): + try: + project = kilin.synchronize_project_workspace(source, workspace) + except (OSError, ValueError) as error: + stamp = datetime.now().strftime("%Y%m%d_%H%M%S") + retired = workspace.with_name(f"{workspace.name}_old_{stamp}") + print(f"Cannot reuse {workspace.name} ({error}); " + f"renamed it to {retired.name}.") + workspace.rename(retired) + if project is None: + project = kilin.prepare_project_workspace( + source, "literature", WORKSPACE_DIRECTORY + ) + if project.root != workspace: + raise RuntimeError( + f"Expected the workspace {workspace}, got {project.root}." + ) + return configure_project( + project.root, + {"temperature": TEMPERATURE, "allow_download": allow_download}, + ) + + +def open_session(project_root: Path) -> object: + """Open a traced session on a workspace. + + Parameters + ---------- + project_root: pathlib.Path + Workspace to open. + + Returns + ------- + kilin.RAGSession + The open session. + + """ + + import kilin + + session = kilin.RAGSession( + project_root, + progress_callback=show_progress, + trace=kilin.TraceConfig(enabled=True), + ) + print() + return session + + +def ask(session: object, question: str) -> dict[str, object]: + """Ask one question as a user would, and record what happened. + + Parameters + ---------- + session: kilin.RAGSession + Open session. + question: str + The question. + + Returns + ------- + dict[str, object] + The answer, the routed intent, the tool's summary, the trace file + and the time. Every confirmation is answered "continue"; a request + to choose between options is recorded and cancelled, since the + questions name the paper. + + """ + + choices: list[dict[str, object]] = [] + + def choose(question_text: str, options: Sequence[str]) -> None: + choices.append({"question": question_text, "options": list(options)}) + return None + + started = perf_counter() + answer = session.ask( + question, + confirm_callback=lambda plan: "continue", + choice_callback=choose, + ) + elapsed = perf_counter() - started + trace_path = Path(session.conversation_path) + turn = session.turns[-1] + return { + "question": question, + "answer": answer, + "intent": routed_intent(trace_path), + "tool_summary": dict(turn.parameters.get("tool") or {}), + "choices_requested": choices, + "trace_file": str(trace_path.relative_to(REPOSITORY_ROOT)), + "wall_s": round(elapsed, 1), + } + + +# ------------------------------------------------------------------------- +# Rule-based stage: reference matching and citation detection +# ------------------------------------------------------------------------- + + +def rule_based_report(session: object, article: str) -> object: + """Recompute the tool's rule-based check of the article. + + Parameters + ---------- + session: kilin.RAGSession + Session on a project containing the article. + article: str + The article's file name, as indexed. + + Returns + ------- + kilin.tools.reference_check.ReferenceReport + Reference entries, the file matched to each, and the in-text + citations, without verdicts (no model is called). + + Notes + ----- + This calls the same functions as the tool, in the same way, so its + results equal those behind the tool's answer; ``score_check`` verifies + the counts against the tool's summary. When the article has several + reference lists, the last one is used, as the tool does by default. + + """ + + from collections import defaultdict + + from kilin.tools._shared.references import reference_lists + from kilin.tools.reference_check import _configuration as config + from kilin.tools.reference_check import check_references + from kilin.tools.reference_check._matching import paper_identity + from kilin.tools.reference_check._resolution import linkable_entry + + source_root = Path(session.project.source) + by_file: dict[Path, list] = defaultdict(list) + for chunk in session.chunks: + by_file[Path(chunk.path)].append(chunk) + paper = Path(article) + if paper not in by_file: + raise RuntimeError(f"{article} has no indexed passages.") + + def on_disk(path: Path) -> Path | None: + file = source_root / path + return file if file.is_file() else None + + others = [ + paper_identity(path, passages, on_disk(path), config.MATCH_RULES) + for path, passages in by_file.items() + if path != paper and path.suffix.lower() not in {".bib", ".bbl"} + ] + lists = reference_lists( + by_file[paper], config.REFERENCE_LAYOUT, on_disk(paper), + accept_short=linkable_entry, + ) + if len(lists) > 1: + print(f"Note: {article} has {len(lists)} reference lists; " + "scoring the last one.") + return check_references( + paper, by_file[paper], on_disk(paper), others, -1 + ) + + +def detected_pairs(report: object) -> list[dict[str, object]]: + """List the (sentence, reference) pairs the tool detected. + + Parameters + ---------- + report: ReferenceReport + Rule-based report of the article. + + Returns + ------- + list[dict[str, object]] + One entry per reference number cited in each sentence: the number, + the marker as printed, the sentence's line and text. + + """ + + pairs: dict[tuple[int, int, str], dict[str, object]] = {} + for citation in report.scan.citations: + sentence = citation.sentence + for number in citation.numbers: + key = (number, sentence.line, sentence.text) + pairs.setdefault(key, { + "reference": number, + "marker": citation.marker, + "line": sentence.line, + "sentence": sentence.text, + }) + return list(pairs.values()) + + +def score_check( + report: object, + tool_summary: dict[str, object], + annotations: dict[str, object], +) -> dict[str, object]: + """Score reference matching and citation detection. + + Parameters + ---------- + report: ReferenceReport + Rule-based report of the original article. + tool_summary: dict[str, object] + Summary returned by the tool for the same article. + annotations: dict[str, object] + The hand annotations. + + Returns + ------- + dict[str, object] + Matching counts and, when annotated, matches against the expected + files; citation detection precision and recall against the pairs + identified by hand; and whether the recomputed counts agree with + the tool's. + + """ + + entries = [ + { + "reference": entry.number, + "entry": entry.text, + "status": match.status, + "file": match.path.as_posix() if match.path else None, + "reason": match.reason, + } + for entry, match in zip(report.entries, report.matches) + ] + counts = { + status: sum(e["status"] == status for e in entries) + for status in ("found", "probable", "missing", "unreadable") + } + + expected = { + int(number): file + for number, file in (annotations.get("references") or {}).items() + if not str(number).startswith("_") + } + matching: dict[str, object] = {"counts": counts} + if expected: + correct = wrong = missed = 0 + for entry in entries: + want = expected.get(entry["reference"], "unannotated") + if want == "unannotated": + continue + got = entry["file"] if entry["status"] in ( + "found", "probable") else None + if want is None and got is None: + correct += 1 + elif want is not None and got == want: + correct += 1 + elif got is None: + missed += 1 + else: + wrong += 1 + matching.update( + {"annotated": len(expected), "correct": correct, + "wrong_file": wrong, "missed": missed} + ) + + detected = detected_pairs(report) + manual = [ + {"reference": number, "text": item["text"]} + for item in annotations.get("citations", []) + for number in item["references"] + ] + detection: dict[str, object] = { + "detected": len(detected), + "uncited": list(report.scan.uncited), + "beyond_list": list(report.scan.beyond_list), + "style": report.scan.style, + } + if manual: + def same(pair: dict, item: dict) -> bool: + return ( + pair["reference"] == item["reference"] + and normalized(item["text"]) in normalized(pair["sentence"]) + ) + + true_detected = [ + p for p in detected if any(same(p, m) for m in manual) + ] + found_manual = [m for m in manual if any(same(p, m) for p in detected)] + detection.update({ + "manual": len(manual), + "true_detected": len(true_detected), + "precision": round(len(true_detected) / len(detected), 3) + if detected else None, + "recall": round(len(found_manual) / len(manual), 3), + "missed": [m for m in manual if m not in found_manual], + "extra": [p for p in detected if p not in true_detected], + }) + + agreement = { + key: (counts[key], tool_summary.get(key)) + for key in ("found", "probable", "missing", "unreadable") + } + agreement["references"] = (len(entries), tool_summary.get("references")) + agreement["citations"] = ( + len(report.scan.citations), tool_summary.get("citations") + ) + return { + "entries": entries, + "matching": matching, + "detection": detection, + "agrees_with_tool": all(a == b for a, b in agreement.values()), + "agreement": {k: list(v) for k, v in agreement.items()}, + } + + +# ------------------------------------------------------------------------- +# Model stage: verdicts and suggestions +# ------------------------------------------------------------------------- + + +def claims_of(trace_path: Path) -> list[dict[str, object]]: + """Return every checked claim of a reference check, from its trace. + + Parameters + ---------- + trace_path: pathlib.Path + Trace of the session that ran the check. + + Returns + ------- + list[dict[str, object]] + Reference number, cited file, line, citing sentence, verdict, + quotation status and reading stage of each claim. + + """ + + keep = ( + "reference", "cited", "line", "citation_sentence", "cited_for", + "verdict", "evidence_status", "quote_found", "quote_lines", + "match_status", "verdict_stage", "suitability", + ) + return [ + {key: details.get(key) for key in keep} + for details in trace_details(trace_path, "tool_reference_check_claim") + ] + + +def score_planted( + claims: list[dict[str, object]], planted: list[dict[str, object]] +) -> dict[str, object]: + """Score the verdicts of the planted miscitations. + + Parameters + ---------- + claims: list[dict[str, object]] + Checked claims of the copy with planted miscitations. + planted: list[dict[str, object]] + Annotated miscitations: ``text`` (distinctive words of the citing + sentence), ``original`` and ``planted`` reference numbers. + + Returns + ------- + dict[str, object] + Per planted citation, the claim found for it and its verdict; the + number flagged ("not supported" or "contradicted"). + + """ + + rows = [] + for item in planted: + match = next( + ( + claim for claim in claims + if claim["reference"] == item["planted"] + and normalized(item["text"]) + in normalized(claim["citation_sentence"] or "") + ), + None, + ) + rows.append({ + **item, + "checked": match is not None, + "verdict": match["verdict"] if match else None, + "flagged": bool(match and match["verdict"] in FLAGGED), + "claim": match, + }) + return { + "planted": len(planted), + "checked": sum(row["checked"] for row in rows), + "flagged": sum(row["flagged"] for row in rows), + "rows": rows, + } + + +def score_unmodified(claims: list[dict[str, object]]) -> dict[str, object]: + """Count the verdicts on the original article's citations. + + Parameters + ---------- + claims: list[dict[str, object]] + Checked claims of the original article. + + Returns + ------- + dict[str, object] + Claims checked, the count of each verdict, and the flagged claims + (possible false alarms, to be read: some may be real problems of + the published article). + + """ + + verdicts: dict[str, int] = {} + for claim in claims: + verdicts[claim["verdict"]] = verdicts.get(claim["verdict"], 0) + 1 + flagged = [claim for claim in claims if claim["verdict"] in FLAGGED] + return { + "checked": len(claims), + "verdicts": verdicts, + "flagged": len(flagged), + "flagged_claims": flagged, + } + + +def suggestion_rank( + trace_path: Path, expected: Sequence[str] +) -> dict[str, object]: + """Rank the expected works among the papers the tool suggested. + + Parameters + ---------- + trace_path: pathlib.Path + Trace of the session that ran the suggestion. + expected: Sequence[str] + File names of the works that answer the sentence: the cited work + for a specific sentence, every acceptable work for a background one. + + Returns + ------- + dict[str, object] + The papers in the order of the tool's answer (best verdict first, + then the suitability score); ``rank``, the best position of an + expected work among those suggested (1 = first; papers with the same + verdict and score share a position), or None when none was + suggested; ``tied``, whether another paper shares that position; + and ``expected_suggested``, how many expected works were suggested. + + """ + + from kilin.tools.suggest_reference.tool import _ORDER, _SUGGESTED + + def key(paper: dict) -> tuple[int, int]: + return ( + _ORDER.get(paper.get("verdict"), 99), + -(paper.get("suitability_score") or 0), + ) + + papers = trace_details(trace_path, "tool_suggest_reference_paper") + ordered = sorted(papers, key=key) + suggested = [p for p in ordered if p.get("verdict") in _SUGGESTED] + wanted = set(expected) + hits = [p for p in suggested if Path(p["paper"]).name in wanted] + rank = tied = None + if hits: + best = key(hits[0]) + rank = 1 + sum(key(p) < best for p in suggested) + tied = any( + key(p) == best and Path(p["paper"]).name not in wanted + for p in suggested + ) + return { + "papers": [ + {"paper": p["paper"], "verdict": p.get("verdict"), + "score": p.get("suitability_score"), + "evidence_status": p.get("evidence_status")} + for p in ordered + ], + "expected_checked": sum( + Path(p["paper"]).name in wanted for p in papers + ), + "expected_suggested": len(hits), + "rank": rank, + "tied": tied, + } + + +def suggestion_scores( + suggest: Sequence[dict[str, object]], +) -> dict[str, dict[str, object]]: + """Count the suggestion results of each group of sentences. + + Parameters + ---------- + suggest: Sequence[dict[str, object]] + Per sentence, the recorded result with ``group``, ``rank`` and + ``tied``. + + Returns + ------- + dict[str, dict[str, object]] + Per group: sentences, expected work first (alone or tied), first + with a tie, in the top three, and suggested at all. + + """ + + groups: dict[str, dict[str, object]] = {} + for item in suggest: + counts = groups.setdefault(item.get("group", "ungrouped"), { + "sentences": 0, "first": 0, "first_tied": 0, "top3": 0, + "suggested": 0, + }) + rank = item.get("rank") + counts["sentences"] += 1 + counts["first"] += rank == 1 + counts["first_tied"] += rank == 1 and bool(item.get("tied")) + counts["top3"] += rank is not None and rank <= 3 + counts["suggested"] += rank is not None + return groups + + +# ------------------------------------------------------------------------- +# Runs +# ------------------------------------------------------------------------- + + +def run_check( + run: str, + project: object, + question: str, + article: str, +) -> tuple[dict[str, object], object]: + """Ask for a reference check and collect the results. + + Parameters + ---------- + run: str + ``check`` or ``planted``. + project: kilin.QAProject + Workspace of the run. + question: str + The request, naming the article. + article: str + The article's file name. + + Returns + ------- + tuple[dict[str, object], ReferenceReport] + The recorded answer with its claims, and the rule-based report. + + """ + + session = open_session(project.root) + try: + record = ask(session, question) + report = rule_based_report(session, article) + record["index_status"] = session.index_status + record["chunks"] = len(session.chunks) + finally: + session.close() + record["claims"] = claims_of(REPOSITORY_ROOT / record["trace_file"]) + if record["intent"] != "reference_check": + print(f"WARNING: {run} was routed to {record['intent']}.") + return record, report + + +def run_suggest( + project: object, sentences: list[dict[str, object]], template: str +) -> list[dict[str, object]]: + """Ask for a reference for each test sentence, each in a new session. + + Parameters + ---------- + project: kilin.QAProject + Workspace with the cited works only. + sentences: list[dict[str, object]] + Annotated sentences: ``group``, ``text`` and ``expected`` (file + names of the works that answer it). + template: str + Request with a ``{sentence}`` placeholder. + + Returns + ------- + list[dict[str, object]] + Per sentence, the recorded answer and the rank of the expected + works. + + """ + + results = [] + for index, item in enumerate(sentences, start=1): + print(f"Suggestion {index} of {len(sentences)}") + session = open_session(project.root) + try: + record = ask(session, template.format(sentence=item["text"])) + finally: + session.close() + record["workspace"] = str(project.root) + record.update(item) + record.update(suggestion_rank( + REPOSITORY_ROOT / record["trace_file"], item["expected"] + )) + if record["intent"] != "suggest_reference": + print(f"WARNING: sentence {index} was routed to " + f"{record['intent']}.") + results.append(record) + return results + + +def summarize(results: dict[str, object]) -> dict[str, object]: + """Collect the numbers of the article's table. + + Parameters + ---------- + results: dict[str, object] + Everything recorded by the runs. + + Returns + ------- + dict[str, object] + One value per row of the table, None where a run was skipped. + + """ + + check = results.get("check") or {} + scores = check.get("scores", {}) + matching = scores.get("matching", {}) + detection = scores.get("detection", {}) + planted = (results.get("planted") or {}).get("planted_scores", {}) + unmodified = check.get("unmodified_scores", {}) + suggest = results.get("suggest") or [] + specific = [item for item in suggest if item.get("group") != "background"] + ranks = [item["rank"] for item in specific] + return { + "references": len(scores.get("entries", [])) or None, + "references_matched": ( + matching.get("counts", {}).get("found", 0) + + matching.get("counts", {}).get("probable", 0) + ) if matching else None, + "citations_detected": detection.get("detected"), + "citations_manual": detection.get("manual"), + "detection_precision": detection.get("precision"), + "detection_recall": detection.get("recall"), + "planted_flagged": planted.get("flagged"), + "planted": planted.get("planted"), + "unmodified_flagged": unmodified.get("flagged"), + "unmodified_checked": unmodified.get("checked"), + "suggestion_first": sum(r == 1 for r in ranks) if specific else None, + "suggestion_top3": ( + sum(r is not None and r <= 3 for r in ranks) if specific else None + ), + "suggestion_sentences": len(specific) or None, + "suggestion_groups": suggestion_scores(suggest) if suggest else None, + "time_check_min": round(check["wall_s"] / 60, 1) if check else None, + "time_suggest_min": ( + round(sum(item["wall_s"] for item in suggest) / 60, 1) + if suggest else None + ), + } + + +def worksheet(results: dict[str, object]) -> str: + """Write a Markdown worksheet for reading the verdicts. + + Parameters + ---------- + results: dict[str, object] + Everything recorded by the runs. + + Returns + ------- + str + The worksheet: summary, flagged unmodified citations, planted + miscitations, and suggestions, each with the sentence and verdict. + The quotations and comments are in the reports in each workspace's + ``outputs`` folder. + + """ + + lines = ["# Reference example: worksheet", ""] + lines += [f"- {key}: {value}" for key, value in results["summary"].items()] + check = results.get("check") + if check: + lines += ["", "## Unmodified citations flagged", "", + "Read each: a false alarm, or a real problem of the " + "article?", ""] + for claim in check["unmodified_scores"]["flagged_claims"]: + lines += [ + f"- **[{claim['reference']}] {claim['cited']}**, line " + f"{claim['line']}: {claim['verdict']} " + f"({claim['evidence_status']})", + f" > {claim['citation_sentence']}", + ] + lines += ["", "## All verdicts on the original article", ""] + for claim in check["claims"]: + lines.append( + f"- [{claim['reference']}] line {claim['line']}: " + f"{claim['verdict']} ({claim['evidence_status']})" + ) + planted = results.get("planted") + if planted: + lines += ["", "## Planted miscitations", ""] + for row in planted["planted_scores"]["rows"]: + lines += [ + f"- [{row['original']}→{row['planted']}] " + f"{'flagged' if row['flagged'] else 'not flagged'}: " + f"{row['verdict']}", + f" > {row['text']}", + ] + if results.get("suggest"): + lines += ["", "## Suggestions", ""] + for item in results["suggest"]: + tie = " (tied)" if item.get("tied") else "" + lines.append( + f"- {item.get('group', '')}: expected " + f"{', '.join(item['expected'])}: rank {item['rank']}{tie}" + ) + lines.append(f" > {item['text']}") + for paper in item["papers"]: + lines.append( + f" - {paper['paper']}: {paper['verdict']} " + f"({paper['score']})" + ) + return "\n".join(lines) + "\n" + + +def main(argv: Sequence[str] | None = None) -> int: + """Run the reference example and save its results. + + Parameters + ---------- + argv: Sequence[str] | None, optional + Command-line arguments. Defaults to ``None``, which reads + ``sys.argv``. + + Returns + ------- + int + Exit status, 0 on success. + + """ + + parser = ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument( + "--ref", default="HEAD", + help="git revision of the corpus to export (default: HEAD)", + ) + parser.add_argument( + "--annotations", type=Path, default=ANNOTATIONS_FILE, + help="annotation file (default: reference_annotations.json)", + ) + parser.add_argument( + "--planted", type=Path, + help="copy of the article with planted miscitations " + "(default: the annotation file's 'planted_file')", + ) + parser.add_argument( + "--only", choices=RUNS, action="append", + help="run only this part; repeat for several", + ) + parser.add_argument( + "--router-model", default=None, + help="intent (router) model of the project, a Hugging Face ID such " + "as Qwen/Qwen3-8B-MLX-4bit (default: the packaged default)", + ) + parser.add_argument( + "--allow-download", action="store_true", + help="download models missing from the local cache", + ) + args = parser.parse_args(argv) + + if not args.allow_download: + os.environ["HF_HUB_OFFLINE"] = "1" + os.environ["TRANSFORMERS_OFFLINE"] = "1" + os.environ.setdefault("TRANSFORMERS_VERBOSITY", "error") + + annotations = json.loads(args.annotations.read_text(encoding="utf-8")) + article = annotations["article"] + runs = args.only or list(RUNS) + planted_file = args.planted or ( + (args.annotations.parent / annotations["planted_file"]).resolve() + if annotations.get("planted_file") else None + ) + if planted_file is not None and not Path(planted_file).is_file(): + print(f"No planted copy at {planted_file}.") + planted_file = None + if "planted" in runs and planted_file is None: + print("No planted copy found; skipping the planted run.") + runs = [run for run in runs if run != "planted"] + + results: dict[str, object] = { + "date": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "environment": describe_environment(), + "code": code_version(), + "temperature": TEMPERATURE, + "runs": runs, + } + if results["code"]["uncommitted_kilin_changes"]: + print("WARNING: kilin/ has uncommitted changes; the results do not " + "correspond to a commit.") + + # A fixed staging folder: a workspace is synchronized from the same + # source path on every run, as in paper_numbers.prepare_code_project. + staging = Path(gettempdir()) / "kilin_reference_example" + if staging.exists(): + shutil.rmtree(staging) + corpus = staging / "corpus" + corpus.mkdir(parents=True) + results["corpus"] = export_corpus( + args.ref, annotations["corpus_folder"], corpus + ) + if not (corpus / article).is_file(): + raise SystemExit(f"{article} is not in the exported corpus.") + results["corpus"]["files"] = { + path.relative_to(corpus).as_posix(): sha256(path) + for path in sorted(corpus.rglob("*")) if path.is_file() + } + if planted_file is not None: + # The copy is part of the papers project whenever it exists, so the + # project holds the same files whichever runs are selected. + results["planted_file"] = { + "path": str(planted_file), "sha256": sha256(Path(planted_file)) + } + planted_name = Path(planted_file).name if planted_file else "" + if planted_name == article: + raise SystemExit( + "The planted copy needs a file name different from the " + f"article's ({article})." + ) + sources = stage_sources( + corpus, article, + Path(planted_file) if planted_file is not None else None, + planted_name, staging / "sources", + ) + projects = {} + if "check" in runs or "planted" in runs: + projects["papers"] = open_project( + sources["papers"], args.allow_download + ) + if "suggest" in runs: + projects["suggest"] = open_project( + sources["suggest"], args.allow_download + ) + + routers = { + name: set_router_model(project, args.router_model) + for name, project in projects.items() + } + results["router_model"] = next(iter(routers.values()), None) + + question = annotations["check_question"] + if "check" in runs: + record, report = run_check( + "check", projects["papers"], question.format(article=article), + article, + ) + record["scores"] = score_check( + report, record["tool_summary"], annotations + ) + record["unmodified_scores"] = score_unmodified(record["claims"]) + if not record["scores"]["agrees_with_tool"]: + print("WARNING: recomputed counts differ from the tool's: " + f"{record['scores']['agreement']}") + record["workspace"] = str(projects["papers"].root) + results["check"] = record + if "planted" in runs: + record, _ = run_check( + "planted", projects["papers"], + question.format(article=planted_name), planted_name, + ) + record["planted_scores"] = score_planted( + record["claims"], annotations.get("planted", []) + ) + record["workspace"] = str(projects["papers"].root) + results["planted"] = record + if "suggest" in runs: + results["suggest"] = run_suggest( + projects["suggest"], annotations.get("suggestions", []), + annotations["suggest_question"], + ) + + results["summary"] = summarize(results) + OUTPUT_DIRECTORY.mkdir(parents=True, exist_ok=True) + stamp = datetime.now().strftime("%Y%m%d_%H%M%S") + output = OUTPUT_DIRECTORY / f"reference_example_{stamp}.json" + output.write_text( + json.dumps(results, indent=2, ensure_ascii=False, default=str), + encoding="utf-8", + ) + sheet = OUTPUT_DIRECTORY / f"reference_example_{stamp}_worksheet.md" + sheet.write_text(worksheet(results), encoding="utf-8") + + print("\nSummary") + for key, value in results["summary"].items(): + print(f" {key}: {value}") + print(f"\nResults: {output.relative_to(REPOSITORY_ROOT)}") + print(f"Worksheet: {sheet.relative_to(REPOSITORY_ROOT)}") + print("Workspaces to open in the app: " + f"{WORKSPACE_DIRECTORY.relative_to(REPOSITORY_ROOT)}/") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/_si_article_/reference_analysis/tiunn26braph2_planted.txt b/_si_article_/reference_analysis/tiunn26braph2_planted.txt new file mode 100644 index 00000000..78cf7bc0 --- /dev/null +++ b/_si_article_/reference_analysis/tiunn26braph2_planted.txt @@ -0,0 +1,721 @@ +SoftwareX 35 (2026) 102791 + +Contents lists available at ScienceDirect + +SoftwareX + +journal homepage: www.elsevier.com/locate/softx + +Original Software Publication + +BRAPH 2: A flexible, open-source, reproducible, community-oriented, +easy-to-use framework for network analyses in neurosciences + +Io̍ k-uí Tiunn a,1 , Blanca Zufiria-Gerbol´es b,1, Emiliano G´omez-Ruiz a, Anna Canal-Garcia b, +Hang Zhao a, Mite Mijalkov b, Joana B. Pereira b,*, Giovanni Volpe a,c,* +a Department of Physics, University of Gothenburg, Gothenburg, Sweden +b Department of Clinical Neuroscience, Division of Neuro, Karolinska Institutet, Stockholm, Sweden +c Science for Life Laboratory, Department of Physics, University of Gothenburg, Gothenburg, Sweden + +A R T I C L E I N F O + +A B S T R A C T + +Keywords: +Network analyses +Neuroscience +Deep learning +Specialized distributions +Custom pipelines +Reproducibility + +1. Metadata + +As network analyses in neuroscience continue to grow in both complexity and size, flexible methods are urgently +needed to provide unbiased, reproducible insights into brain function. BRAPH 2 is a versatile, open-source +framework that meets this challenge by offering streamlined workflows for advanced statistical models and +deep learning, while supporting community-oriented extension, reuse, and sharing. Through its Genesis +compiler, users can build specialized distributions with custom pipelines, ensuring flexibility and scalability +across diverse research domains. These capabilities support reproducibility and accelerate discovery in +neuroscience. + +Nr +C1 +C2 + +C3 + +C4 + +C5 +C6 + +C7 + +C8 + +C9 + +Code metadata description +Current code version +Permanent link to code/repository +used for this code version +Permanent link to reproducible +capsule +Legal code license + +Code versioning system used +Software code languages, tools and +services used +Compilation requirements, +operating environments and +dependencies +If available, link to developer +documentation/manual +Support email for questions + +Metadata +v2.0.1 +https://github.com/braph-softwar +e/BRAPH-2 +https://codeocean.com/caps +ule/6589176/tree/v1 +Creative Commons Attribution 4.0 +International (CC-BY-4.0) +Git +MATLAB, C++ + +MATLAB; MinGW C/C++ compiler for +Windows as a MATLAB Add-On for +compiling MEX files +https://github.com/braph-software/B +RAPH-2/tree/develop/tutorials +Giov + +2. Motivation and significance + +In recent years, network analyses have rapidly gained traction in +neurosciences, linking multiple brain regions, clinical scores, and + +biomarkers to reveal system-wide interactions that often remain hidden +when single variables are studied in isolation [1–4]. This approach is +reshaping neurology, psychiatry, and cognitive sciences, driven by the +promise of new tools for disease diagnosis, improved treatment moni- +toring, and deeper insights into how the brain functions. + +The growing availability of large-scale, multimodal datasets has +made network analysis increasingly complex [5–7]. Initiatives such as +the UK Brain Biobank [8], the Human Connectome Project (HCP) [9], +and the ENIGMA Consortium [10] have generated large neuroimaging +datasets together with omics and clinical data [5–7]. Although many +software tools exist for handling these datasets, implementing new +robust, reproducible, and traceable features remains a significant chal- +lenge [11]. These features require rigorous unit testing, the ability to +trace outcomes back to original sources, continuous progress moni- +toring, and the development of user-friendly interfaces—tasks that often +demand far more time and resources than creating core functionalities. +Adopting standardized, containerized environments and automated +testing frameworks can enhance reproducibility and traceability [12], +but integrating these practices into research-oriented software is com- +plex and time-consuming. As a result, research groups often prioritize +the rapid development of new techniques at the expense of software +quality, reproducibility, and long-term maintenance. + +* Corresponding authors. + +E-mail addresses: joana.pereira@ki.se (J.B. Pereira), giovanni.volpe@gu.se (G. Volpe). + +1 These authors contributed equally to this work. + +https://doi.org/10.1016/j.softx.2026.102791 +Received 22 March 2026; Received in revised form 27 May 2026; Accepted 8 June 2026 +Available online 12 June 2026 +2352-7110/© 2026 The Authors. Published by Elsevier B.V. This is an open access article under the CC BY license ( http://creativecommons.org/licenses/by/4.0/ ). + + I.-u. Tiunn et al. + +SoftwareX 35 (2026) 102791 + +Many free and open-source software platforms for brain connectivity +analysis exist, such as the Brain Connectivity Toolbox [13], eConnec- +tome [14], GAT [25], CONN [16], BrainNet Viewer [20], GRETNA [15], +and BRAPH 1 [19]. A reference table comparing BRAPH 2 with these +related software platforms is provided in the Supplementary Material. +While these tools provide essential functions such as data import, +network measures, and visualization, most focus on specific tasks. This +fragmentation can make it difficult to build full workflows without +manual intervention, increasing the risk of mistakes and bias. Moreover, +rapid advances in computational modeling and AI demand continuous +software updates, which can delay the integration of new methods. This +challenge also reflects broader machine learning operations (MLOps) +concerns in healthcare, where ML workflows increasingly require +reproducibility, maintainability, and long-term reliability [20,21]. As a +result, researchers face difficulties in adopting cutting-edge analyses in a +manner that ensures consistency, transparency, and easy verification +across studies, slowing scientific progress and potentially introducing +mistakes. + +BRAPH 2 addresses these challenges by combining a user-friendly +environment for network analysis with a software-generating frame- +work. Compared with BRAPH 1, it adds multiplex graph analysis, deep +learning pipelines, and Genesis-based generation of reusable pipelines +and specialized distributions. Unlike tools focused mainly on individual +analysis steps, BRAPH 2 centers on its Genesis module, which compiles +structured element descriptions into executable MATLAB classes, +graphical user interfaces (GUIs), and unit tests, thereby supporting in- +tegrated statistical testing and reproducible workflows. Users can create +custom elements to extend both pipelines and GUIs without extensive +coding. For example, BRAPH 2 has been used to implement a recursive +feature elimination pipeline for deep learning [3] and a standalone +distribution for reservoir computing to study brain network memory +capacity [22]. Written in MATLAB, BRAPH 2 is portable across oper- +ating systems and supports multiple data types beyond brain imaging. +During development, we also created specialized pipelines for yeast-cell +synchronization [24] and dendritic spine loss in postmortem brain tissue +[18], illustrating its flexibility across domains. + +3. Software description + +BRAPH 2 supports network analysis at three complementary levels: a +standard distribution with ready-to-use pipelines, custom pipelines built +by extending the framework, and standalone specialized distributions +that combine user-defined elements with selected standard components. +This structure supports no-code analyses for domain scientists, workflow +extension for advanced users, and development of new methods for +developers. By using a structured configuration system and modular +design, Genesis simplifies the addition of new graph types, analysis +pipelines, and user interface elements, making it easier to develop and +share specialized analytical tools. + +3.1. Software architecture + +To create a custom BRAPH 2 distribution, users define their desired +components — such as graph types, measures, analyses, and GUI ele- +ments — within a configuration file (braph2newdistribution_config.m) +(Fig. 1a). Alongside this, custom *.gen.m scripts describe the behavior +and properties of each element. The Genesis module then compiles these +inputs through a step-by-step workflow (Fig. 1b): + +• Directory Setup: Establishes the folder structure for the new + +distribution. + +• File Integration: Incorporates custom scripts and resources into the + +framework. + +• Element Compilation: Generates MATLAB classes and methods + +based on the *.gen.m templates. + +• GUI Generation: Builds interactive graphical interfaces for the new + +components. + +• Unit Test Creation: Produces tests to ensure functionality and + +maintain integrity. + +The result is a standalone BRAPH 2 distribution, packaging all +custom features into a cohesive and user-friendly environment (Fig. 1c). +For example, the “Hello, World!” distribution (https://github. +com/braph-software/HelloWorld) demonstrates the minimal setup + +Fig. 1. Genesis in action: compiling a custom BRAPH 2 distribution. a To create a specialized BRAPH 2 distribution with custom analysis pipelines, the user prepares +a compilation configuration file (braph2newdistribution_config.m) and a folder with the necessary custom elements (e.g., _NewAlgorithm.gen.m), pipeline files (e.g., +pipeline_NewAlgorithm.braph2), and optionally tutorial LaTeX files (e.g., tutorial_NewAlgorithm.tex). b The Genesis module of BRAPH 2 compiles these files +together with the core BRAPH 2 files through a series of steps, including creating directory structure, copying static files into the new directories, compiling elements, +creating layouts for the graphical user interface (GUI), and generating unit tests. c The resulting custom BRAPH 2 distribution includes a no-code GUI for end users. +This provides a framework for network analysis in neuroscience that is Flexible, Open-source, Reproducible, Community-oriented, and Easy-to-use (FORCE). + +2 + + I.-u. Tiunn et al. + +SoftwareX 35 (2026) 102791 + +required to build a functional BRAPH 2 extension. On the other hand, +the “Memory Capacity” distribution (https://github.com/braph-softwar +e/MemoryCapacity) highlights how Genesis can support advanced ap- +plications, such as reservoir computing approaches for evaluating +cognitive decline [15]. + +3.2. Software functionalities + +The three usage levels introduced above are implemented in BRAPH +2 through the following complementary software functionalities, which +also correspond to different user profiles and levels of technical +expertise. + +3.2.1. Standard distribution for ready-to-use pipelines + +The standard BRAPH 2 distribution (https://github.com/braph-soft +ware/BRAPH-2) provides over 100 fully functional pipelines for +network neuroscience, including single-layer analyses, multilayer graph +analyses integrating imaging and non-imaging data, and deep learning +pipelines for supervised tasks such as classification, prediction, and +diagnosis. These deep learning pipelines are implemented in MATLAB +within BRAPH 2 and rely on the MATLAB Deep Learning Toolbox. Each +pipeline guides users through data import, graph construction, network +measure computation, statistical comparison, and visualization through +a user-friendly interface. In addition to GUI-based usage, BRAPH 2 can +also be used programmatically, facilitating scripted execution, batch +processing, and integration with high-performance computing envi- +ronments for large-scale datasets. + +3.2.2. Custom pipelines built on the standard distribution + +BRAPH 2 also allows users and developers to create custom pipelines +that are not included in the standard distribution while reusing the +functionalities already available in the framework. By relying on the +Genesis module and the modular design of BRAPH 2, users can adapt +pipeline scripts and introduce new graphs, measures, or analyses with +minimal programming effort. These custom elements integrate with the +existing GUI and workflows, which accelerates development while +maintaining robustness, reproducibility, and traceability. + +3.2.3. Standalone specialized distributions with new methods + +Beyond extending the standard distribution, BRAPH 2 supports the +generation of standalone specialized distributions for specific scientific +applications. In this case, users combine user-defined elements with +selected components from the standard distribution and specify them +through a configuration file. Genesis then assembles these resources into +a complete BRAPH 2 distribution, including executable MATLAB classes, +automatically generated GUI components, and unit tests. This allows +BRAPH 2 to function not only as a software package for network anal- +ysis, but also as a framework for creating specialized software solutions +with minimal coding effort. + +Taken together, these three levels show that BRAPH 2 serves both + +domain scientists and developers. For a quick start, users can: + +1. download the latest stable release; +2. unzip it into a directory; +3. launch MATLAB; +4. navigate to the braph2 folder; and +5. run the script braph2.m. + +This launches the GUI (Fig. 1c) for pipeline selection. The BRAPH 2 +pipeline tutorials (https://github.com/braph-software/BRAPH-2/tree/ +develop/tutorials/pipelines) and developer documentation (https: +//github.com/braph-software/BRAPH-2/tree/develop/tutorials/deve +lopers) provide +instructions for running ready-to-use pipelines, +including minimal datasets and scripts, and for creating, testing, and +distributing new features under the FORCE principles. Their practical +implementation is illustrated in Section 4. + +3 + +4. Illustrative examples + +The capabilities of BRAPH 2 are illustrated by three case studies in +network neuroscience, all realized within the same description- +centered, generative infrastructure. They are deliberately arranged to +show three scales of reuse: (i) a fully standard pipeline assembled purely +from existing elements, (ii) a new pipeline built by reusing the same +neural-network elements, and (iii) a new BRAPH 2 distribution con- +structed by adding elements implementing a state-of-the-art method on +top of the existing graph and subject infrastructure. + +4.1. Standard BRAPH 2 distribution: multiplex graph analysis + +In the first case study, ready-made pipelines from the standard +BRAPH 2 distribution (Fig. 2a) were used to investigate sex differences +in brain organization using combined diffusion magnetic resonance +imaging (dMRI) and resting-state functional magnetic resonance imag- +ing (fMRI) data from the Human Connectome Project (HCP, http://db. +humanconnectome.org). In this work, the term sex refers to the bio- +logical grouping variable provided in the dataset metadata. As shown in +Fig. 2b, the standard pipeline supports multiplex graph theory by +combining anatomical and functional connectomes into a multilayer +representation. Structural and functional connectivity matrices were +constructed from the Brainnetome atlas, and core–periphery structure +was estimated separately for each modality as well as for their multiplex +combination. Fig. 2c–e show the corresponding outputs generated +directly by BRAPH 2 from the ready-made pipeline: Fig. 2c reports the +single-layer anatomical analysis, Fig. 2d reports the single-layer func- +tional analysis, and Fig. 2e reports the multiplex analysis combining +both modalities. The regions highlighted in Fig. 2c–e correspond to sex +differences in nodal coreness, with “Women > Men” and “Men > +Women” indicating regions that show significantly higher coreness in +women and men, respectively. All analyses were performed through +standard pipelines and saved as .b2 files (available at https://github. +com/braph-software/BRAPH-2/issues/1745), +that +multiplex graph analysis and visualization can be combined reproduc- +ibly without bespoke coding. Together, these panels illustrate how a +ready-made BRAPH 2 pipeline supports core–periphery analysis and +visualization in a reproducible workflow without adding new elements. + +demonstrating + +4.2. Custom pipeline: deep learning analysis of recursive feature +elimination + +The second case study implements recursive feature elimination +(RFE) for schizophrenia classification. Most building blocks — including +subject elements, connectivity graphs, graph-derived features, the +multilayer perceptron (MLP) classifier, and brain-surface visualization +— are reused from the standard distribution. The results of this study +were published [22]. As shown in Fig. 3a, the project adds a single new +Genesis generator file (_NNxMLP_FeatureImportance.gen.m) together +with example scripts (example_RFE.m). This produces an RFE pipeline in +which the MLP classifier is trained, feature-importance scores are +computed, the least important regions are removed, and the model is +retrained until a stable subset of predictive regions is obtained (Fig. 3b). +The consistency of the identified regions across two independent cohorts +is shown in Fig. 3c, providing a robust basis for the subsequent genomic +analysis. Fig. 3d shows the corresponding brain-surface visualization. +This example shows how a new and custom analysis pipeline can be +created by reusing existing elements and adding a single Genesis +generator file. + +4.3. Standalone specialized distribution: memory capacity + +The third case study constructs the BRAPH 2 Memory Capacity dis- +tribution to quantify how reservoir-computing-based measures of +memory capacity change across the lifespan. The results of this study + + I.-u. Tiunn et al. + +SoftwareX 35 (2026) 102791 + +Fig. 2. Standard BRAPH 2 distribution. a An analysis pipeline from the Standard BRAPH 2 distribution. b This pipeline implements multiplex graph theory, where +anatomical and functional data are combined to create multiplex networks, providing deeper insights into brain organization. c Results from single-layer analysis of +anatomical data. d Results from single-layer analysis of functional data. e Results from multiplex analysis combining anatomical and functional data, providing new +insights. In panels c–e, “Women > Men” and “Men > Women” denote regions with significantly higher nodal coreness in women and men, respectively. All results +and analysis steps can be reproduced using the provided .b2 files, available at https://github.com/braph-software/BRAPH-2/issues/1745, together with the standard +distribution available at https://github.com/braph-software/BRAPH-2. + +were recently published [23]. Unlike the previous examples, which +extended standard BRAPH 2 pipelines with custom scripts, this case +involved the creation of a standalone distribution. As shown in Fig. 4a, a +dedicated BRAPH 2 distribution was developed to study computational +memory capacity in brain networks. Here, almost all components — +subject and group handling, structural graphs, statistics, and visualiza- +tion — are inherited from the standard distribution, while a small set of +new elements (_GlobalMemoryCapacity.gen.m, _NodalMemoryCapacity. +gen.m) is added to implement the specialized reservoir-computing +functionality. Fig. 4b shows the relationship between memory capac- +ity and aging, Fig. 4c illustrates the reservoir-computing setup, and +Fig. 4d shows the visualization of the identified regions associated with +memory capacity decline. This approach allows researchers to build +customized tools that contain only the necessary functionalities for their +specific applications, thereby reducing complexity and enhancing us- +ability. Crucially, all distributions generated this way preserve BRAPH +2′s GUI functionality, reproducibility mechanisms, and compatibility +across platforms. The Memory Capacity distribution presented in this +case study is publicly available at https://github.com/braph-software/ +MemoryCapacity. + +An introductory video demonstrating how to build a specialized +BRAPH 2 distribution in practice, using the Memory Capacity example +in Section 3.3, is provided as supplementary material. The human +datasets used in the illustrative examples came from previously +approved studies with informed consent, as described in the source +datasets and original publications [9,22,23]. Only de-identified or +publicly available data were used here. + +5. Impact + +Network-based approaches have become central to neuroscience, yet + +many widely used tools remain limited to a single analysis type or data +modality. As the field moves toward multimodal and computationally +intensive models, including deep learning and multilayer analysis, such +limitations have become more evident. BRAPH 2 addresses them by +providing a modular, extensible, and reproducible platform for both +standard graph analysis and custom software development. Its flexibility +is illustrated through three case studies: a standard multiplex pipeline, a +custom deep learning pipeline for recursive feature elimination [17], +and a Genesis-generated standalone distribution for memory capacity +analysis [23]. + +A key strength of BRAPH 2 lies in its commitment to reproducibility +by design. All analyses can be encapsulated in a single .b2 file, as +exemplified by the .b2 files provided for the first case study (https://gith +ub.com/braph-software/BRAPH-2/issues/1745). Each file records +every step of the pipeline, including software versions and configuration +settings. These files can be shared and re-executed across systems, +ensuring exact replication while excluding sensitive personal data. This +infrastructure makes BRAPH 2 particularly useful for collaborative +studies, pre-registered workflows, and reproducible supplements to +published work. The portability of BRAPH 2 is further supported by unit +testing across different operating systems (Linux, Windows, and macOS) +and MATLAB versions (R2022a, R2022b, R2023a, R2023b, R2024a, and +R2024b), as documented in the README on its GitHub page. + +BRAPH 2′s open-source development model strengthens its reli- +ability and transparency. Hosted on GitHub, it supports issue tracking, +feature requests, code submissions, and documentation, while an active +discussion forum fosters knowledge exchange among users and de- +velopers. This model promotes sustainable development and broad +participation. + +One of the most powerful features of BRAPH 2 is the Genesis module, +which allows researchers to package tailored tools, pipelines, and + +4 + + I.-u. Tiunn et al. + +SoftwareX 35 (2026) 102791 + +Fig. 3. Custom deep learning pipeline. a Custom pipeline for deep learning focusing on recursive feature elimination. b The regions were identified using a +multilayer perceptron and iterative feature elimination (used in [22]). c The deep learning pipeline identifies consistent important brain regions across two datasets. +d Results showing the identified regions on a brain surface. + +interfaces into standalone, shareable distributions. This capability is +particularly valuable in translational, clinical, and educational settings, +where simplicity, reproducibility, and scope-specific design are crucial. +The Memory Capacity distribution exemplifies this model: it introduces +two reservoir-computing-based metrics, applies them to lifespan imag- +ing data, and demonstrates their sensitivity to cognitive aging and brain +integrity. Built entirely with Genesis, the distribution is portable, +reproducible, and requires no additional configuration. + +BRAPH 2 is built on Genesis and is primarily designed for region-of- +interest (ROI)-based brain connectivity analyses, which remain standard +in many neuroimaging studies. Because BRAPH 2 is implemented in +MATLAB, large voxel-level networks may be limited by memory de- +mands, although sparse-matrix representations can help mitigate this at +the cost of some computational efficiency. A further limitation of the +present study is that Genesis, as the software-generating core of BRAPH +2, is not naturally suited to direct benchmarking against conventional +analysis tools. Rather, benchmarking is more meaningful for the soft- +ware produced by Genesis, such as the BRAPH 2 standard distribution, +and is therefore left for future work. + +Beyond technical strengths, BRAPH 2 is designed to be accessible and +inclusive. Its GUI supports users with limited coding experience, while +its modular architecture and documentation support full customization. +It accommodates multiple data types, including structural and func- +tional MRI, behavioral data, and electroencephalography (EEG), as well +as analytical approaches ranging from single-layer graphs to multiplex +models and neural networks. + +Future development of BRAPH 2 includes MATLAB–Python inter- +operability, broader multi-omics integration, improved batch processing +for scalable and automated analyses of larger datasets, and built-in +quality-control tools. The Genesis architecture further supports long- +term scalability by enabling specialized distributions to be generated +and maintained while preserving core functionality and reproducibility. +BRAPH 2 is also suited to real-time and streaming data integration, with + +5 + +potential applications in EEG, functional near-infrared spectroscopy, +neurofeedback, closed-loop systems, and brain–computer interfaces. + +6. Conclusions + +BRAPH 2 is an open-source framework that combines ready-to-use +network-neuroscience pipelines with a generative system for creating +custom pipelines and standalone software distributions. Its core inno- +vation, the Genesis module, enables new elements to be defined at a high +level and compiled into executable MATLAB classes, graphical in- +terfaces, and unit tests, thereby providing a reproducible and extensible +foundation for both network analysis and scientific software develop- +ment. Hosted through the BRAPH GitHub organization (https://github. +com/braph-software), this foundation supports the standard and +specialized BRAPH 2 distributions, together with the associated repro- +ducible capsule, while promoting the long-term accessibility and future +growth of the BRAPH software family. Through an active user forum +(https://github.com/braph-software/BRAPH-2/discussions), user tuto- +rials, and developer documentation, BRAPH 2 further lowers technical +barriers and supports shareable workflows in open and collaborative +science. + +Declaration of generative AI and AI-assisted technologies in the +manuscript preparation process + +During the preparation of this work the authors used ChatGPT +(OpenAI) in order to improve the clarity, grammar, and phrasing of the +manuscript text. After using this tool, the authors reviewed and edited +the content as needed and take full responsibility for the content of the +published article. + + I.-u. Tiunn et al. + +SoftwareX 35 (2026) 102791 + +Fig. 4. Memory capacity distribution. a Distribution folder designated to the memory capacity (MC) distribution using reservoir computing. b Boxplots showing the +area under the curve (AUC) of global memory capacity in an aging cohort, highlighting differences between the young and the old groups. c This schematic illustrates +the setup of reservoir computing, where an input signal propagates through the nodes of a brain network and emerges as an output signal. If the network has +sufficient memory capacity, the output will closely resemble the original input. d Visualization showing the correlation between regional MC and age, where negative +correlations are shown in blue and positive in red. This demonstrates how a new algorithm can be provided to the community through a custom pipeline (used in +[23], https://github.com/braph-software/MemoryCapacity). + +CRediT authorship contribution statement + +Foundation (Grant No 2019.0079) (GV). + +Io̍ k-uí Tiunn: Writing – review & editing, Writing – original draft, +Visualization, Validation, Software, Investigation, Formal analysis, Data +curation. Blanca Zufiria-Gerbol´es: Writing – review & editing, Writing +– original draft, Visualization, Validation, Software, Investigation, +Formal analysis. Emiliano G´omez-Ruiz: Visualization, Software, +Investigation. Anna Canal-Garcia: Visualization, Validation, Software, +Investigation, Formal analysis, Data curation. Hang Zhao: Software, +Investigation. Mite Mijalkov: Validation, Software, Resources, Investi- +gation, Data curation. Joana B. Pereira: Writing – review & editing, +Writing – original draft, Supervision, Software, Resources, Project +administration, Methodology, Investigation, Conceptualization. Gio- +vanni Volpe: Writing – review & editing, Writing – original draft, +Visualization, Validation, Supervision, Software, Resources, Project +Investigation, Funding acquisition, +administration, Methodology, +Formal analysis, Data curation, Conceptualization. + +Declaration of competing interest + +The authors declare that they have no known competing financial +interests or personal relationships that could have appeared to influence +the work reported in this paper. + +Acknowledgements + +The authors would like to acknowledge funding from the H2020 +European Research Council (ERC) Starting Grant ComplexSwimmers +(Grant No 677511) (GV), the Horizon Europe ERC Consolidator Grant +MAPEI (Grant No 101001267) (GV), and the Knut and Alice Wallenberg + +Supplementary materials + +Supplementary material associated with this article can be found, in + +the online version, at doi:10.1016/j.softx.2026.102791. + +References + +[1] Seguin C, Sporns O, Zalesky A. Brain network communication: concepts, models + +and applications. Nat Rev Neurosci 2023;24(9):557–74. + +[2] Sebenius I, Dorfschmidt L, Seidlitz J, Alexander-Bloch A, Morgan SE, Bullmore E. + +Structural MRI of brain similarity networks. Nat Rev Neurosci 2025:1–18. + +[3] Tanner J, Faskowitz J, Teixeira AS, Seguin C, Coletta L, Gozzi A, Miˇsi´c B, Betzel RF. +A multi-modal, asymmetric, weighted, and signed description of anatomical +connectivity. Nat Commun 2024;15(1):5865. + +[4] Wang J, He Y. Toward individualized connectomes of brain morphology. Trends + +Neurosci 2024;47(2):106–19. + +[5] Nogare DD, Hartley M, Deschamps J, Ellenberg J, Jug F. Using AI in bioimage + +analysis to elevate the rate of scientific discovery as a community. Nat Methods +2023;20(7):973–5. + +[6] Marek S, Tervo-Clemmens B, Calabro FJ, Montez DF, Kay BP, Hatoum AS, + +Donohue MR, Foran W, Miller RL, Hendrickson TJ, Lynch BJ, Tam A, Chen J, +Newbold DJ, Zheng A, Seider NA, Van AN, Laumann TO, Greene DJ, +Dosenbach NUF. Reproducible brain-wide association studies require thousands of +individuals. Nature 2022;603(7902):654–60. + +[7] Li X, Zhang Y, Wu J, Dai Q. Challenges and opportunities in bioimage analysis. Nat + +Methods 2023;20(7):958–61. + +[8] Matthews PM, Sudlow C. The UK biobank. Brain 2015;138(12):3463–5. +[9] Van Essen DC, Ugurbil K, Auerbach E, Barch D, Behrens TEJ, Bucholz R, Chang A, +Chen L, Corbetta M, Curtiss SW, Della Penna S, Feinberg D, Glasser MF, Harel N, +Heath AC, Larson-Prior L, Marcus D, Michalareas G, Moeller S, Yacoub E. The +Human Connectome Project: a data acquisition perspective. Neuroimage 2012;62 +(4):2222–31. + +[10] Thompson PM, Stein JL, Medland SE, Hibar DP, Vasquez AA, Renteria ME, Toro R, + +Jahanshad N, Schumann G, Franke B, Wright MJ, Martin NG, Agartz I, Alda M, +Alhusaini S, Almasy L, Almeida J, Alpert K, Andreasen NC, Drevets W. The + +6 + + I.-u. Tiunn et al. + +SoftwareX 35 (2026) 102791 + +ENIGMA Consortium: large-scale collaborative analyses of neuroimaging and +genetic data. Brain Imaging Behav 2014;8(2):153–82. + +[11] Botvinik-Nezer R, Wager TD. Reproducibility in neuroimaging analysis: challenges + +and solutions. Biol Psychiatry 2023;8(8):780–8. + +[12] Renton AI, Dao TT, Johnstone T, Civier O, Sullivan RP, White DJ, Lyons P, + +Slade BM, Abbott DF, Amos TJ, Bathelt J, Bellgrove MA, Bissett PG, Brown GG, +Calhoun VD, Cardenas VA, Chen J, Chen X, Choi YY, Gatt JM. Neurodesk: an +accessible, flexible and portable data analysis environment for reproducible +neuroimaging. Nat Methods 2024;21(5):804–8. + +[13] Rubinov M, Sporns O. Complex network measures of brain connectivity: uses and + +interpretations. Neuroimage 2010;52(3):1059–69. + +[14] He B, Dai Y, Astolfi L, Babiloni F, Yuan H, Yang L. eConnectome: a MATLAB +toolbox for mapping and imaging of brain functional connectivity. J Neurosci +Methods 2011;195(2):261–9. + +[15] Hosseini SMH, Hoeft F, Kesler SR. GAT: a graph-theoretical analysis toolbox for + +analyzing between-group differences in large-scale structural and functional brain +networks. PLoS One 2012;7(7):e40709. + +[16] Whitfield-Gabrieli S, Nieto-Castanon A. Conn: a functional connectivity toolbox for + +correlated and anticorrelated brain networks. Brain Connect 2012;2(3):125–41. +[17] Xia M, Wang J, He Y. BrainNet Viewer: a network visualization tool for human + +brain connectomics. PLoS One 2013;8(7):e68910. + +[18] Wang J, Wang X, Xia M, Liao X, Evans A, He Y. GRETNA: a graph theoretical + +network analysis toolbox for imaging connectomics. Front Hum Neurosci 2015;9: +386. + +[19] Mijalkov M, Kakaei E, Pereira JB, Westman E, Volpe G, Alzheimer’s Disease + +Neuroimaging Initiative. BRAPH: a graph theory software for the analysis of brain +connectivity. PLoS One 2017;12(8):e0178798. + +[20] Yan AP, Guo LL, Inoue J, Celi LA, Shickel B, Hong C, Michelson KA, Yoon- + +Flannery K, Brat G, Weiss JC. A roadmap to implementing machine learning in +healthcare: from concept to practice. Front Digit Health 2025;7:1462751. +[21] Steidl M, Felderer M, Ramler R. The pipeline for the continuous development of +artificial intelligence models—current state of research and practice. J Syst Softw +2023;199:111615. + +[22] Yao S, Harder A, Darki F, Chang Y-W, Li A, Nikouei K, Volpe G, Lundstr¨om JN, + +Zeng J, Wray NR, Lu Y, Sullivan PF, Hjerling-Leffler J. Connecting genomic results +for psychiatric disorders to human brain cell types and regions reveals convergence +with functional connectivity. Nat Commun 2025;16(1):395. + +[23] Mijalkov M, Storm L, Zufiria-Gerbol´es B, Ver´eb D, Xu Z, Canal-Garcia A, Sun J, +Chang Y-W, Zhao H, G´omez-Ruiz E, Passaretti M, Garcia-Ptacek S, Kivipelto M, +Svenningsson P, Zetterberg H, Jacobs H, Lüdge K, Brunner D, Mehlig B, Pereira JB. +Computational memory capacity predicts aging and cognitive decline. Nat +Commun 2025;16:2748. + +[24] Mojica-Benavides M, van Niekerk DD, Mijalkov M, Snoep JL, Mehlig B, Volpe G, + +Goks¨or M, Adiels CB. Intercellular communication induces glycolytic +synchronization waves between individually oscillating cells. In: Proceedings of +the National Academy of Sciences. 118; 2021, e2010075118. + +[25] Mijalkov M, Volpe G, Fernaud-Espinosa I, DeFelipe J, Pereira JB, Merino-Serrais P. + +Dendritic spines are lost in clusters in Alzheimer’s disease. Sci Rep 2021;11(1): +12350. + +7 + + \ No newline at end of file diff --git a/assets/benchmark_traces.ipynb b/assets/benchmark_traces.ipynb index 72a97f2e..4d066d1b 100644 --- a/assets/benchmark_traces.ipynb +++ b/assets/benchmark_traces.ipynb @@ -102,6 +102,7 @@ "Start by analyzing saved traces with `EXISTING_TRACES`. Use arbitrary,\n", "**non-sensitive labels** as the dictionary keys. A single conversation trace\n", "may contain multiple turns and multiple logger sessions after reopening.\n", + "For preparation timings, include `project.json` under a separate label.\n", "\n", "Live benchmarking is **disabled by default**. To enable it, create a *separate\n", "benchmark KíLín workspace* inside `sandbox/`, with its own `profile.ini` and\n", @@ -276,8 +277,9 @@ "\n", " Returns\n", " -------\n", - " tuple[list[dict], dict[str, pathlib.Path]]\n", - " Timing-only wall-clock samples and newly written diagnostic traces.\n", + " tuple[list[dict], dict[str, tuple]]\n", + " Timing-only samples and conversation/project trace references. Each\n", + " trace reference includes the project logger ID for that repetition.\n", "\n", " Notes\n", " -----\n", @@ -304,7 +306,11 @@ " )\n", " startup_ms = (perf_counter() - started) * 1000.0\n", " if enabled:\n", - " traces[label] = session.conversation_path\n", + " traces[label] = (\n", + " session.conversation_path,\n", + " session.project_trace.readable_path,\n", + " session.project_trace.trace_id,\n", + " )\n", " for turn, (question_id, question) in enumerate(cases, 1):\n", " started = perf_counter()\n", " answer = session.ask(\n", @@ -364,7 +370,7 @@ "outputs": [], "source": [ "trace_sources = dict(EXISTING_TRACES)\n", - "for label, path in generated_traces.items():\n", + "for label, (path, _, _) in generated_traces.items():\n", " if label in trace_sources:\n", " raise ValueError(f\"Duplicate trace label: {label}\")\n", " trace_sources[label] = path\n", @@ -372,6 +378,11 @@ "operation_rows = []\n", "for label, path in sorted(trace_sources.items()):\n", " records = read_trace_operations(path, label)\n", + " if label in generated_traces:\n", + " _, project_path, trace_id = generated_traces[label]\n", + " records.extend(read_trace_operations(\n", + " project_path, label, trace_id=trace_id\n", + " ))\n", " operation_rows.extend(records)\n", " print(label, \"timed operations:\", len(records))\n", "\n", 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/assets/clean_repository.ipynb b/assets/clean_repository.ipynb index a18e3927..3cc95cb6 100644 --- a/assets/clean_repository.ipynb +++ b/assets/clean_repository.ipynb @@ -14,9 +14,10 @@ " operating-system metadata. In the supplied configuration, deletion is **enabled** (`DELETE = True`).\n", "2. **Select, preview, and optionally export** chosen top-level files and\n", " folders. The default selection includes the required `LICENSE`,\n", - " `CITATION.cff`, `README.pypi.md`, `MANIFEST.in`, Git-tracked\n", - " `.github/` workflows, `.gitignore`, an empty `sandbox/` directory,\n", - " and `_si_article_/`, which includes the Git-tracked benchmark sources,\n", + " `CITATION.cff`, `CHANGELOG.md`, `README.pypi.md`, `MANIFEST.in`,\n", + " Git-tracked `.github/` workflows, `.gitignore`, an empty `sandbox/`\n", + " directory, and `_si_article_/`, which includes the Git-tracked\n", + " benchmark sources,\n", " empty benchmark workspaces, empty repository placeholders, the paper's\n", " `code_analysis/` sources, and the reference-analysis placeholder.\n", "\n", @@ -487,8 +488,8 @@ "Change the Boolean values in `ZIP_TOP_LEVEL_SELECTION` below to choose\n", "which files or folders appear in the ZIP. The default selection includes\n", "repository sources, the mandatory `LICENSE`, `CITATION.cff`,\n", - "`README.pypi.md`, `MANIFEST.in`, Git-tracked `.github/` workflows,\n", - "`.gitignore`, `_si_article_/`, and an empty `sandbox/` directory.\n", + "`CHANGELOG.md`, `README.pypi.md`, `MANIFEST.in`, Git-tracked `.github/`\n", + "workflows, `.gitignore`, `_si_article_/`, and an empty `sandbox/` directory.\n", "\n", "- Names ending in `/` denote top-level folders; other names denote files.\n", "- You may add another top-level name explicitly if needed later. It must be\n", @@ -501,6 +502,8 @@ " Git-tracked; export fails if it is missing, untracked, or disabled.\n", "- `CITATION.cff` must exist and be Git-tracked when selected. A missing\n", " or untracked citation file stops export instead of being silently omitted.\n", + "- The root `CHANGELOG.md` is selected by default for full source exports.\n", + " When selected, it must exist and be Git-tracked like other root files.\n", "- `.gitignore` may be included even if it is not yet tracked by Git.\n", "- `sandbox/` is exported as an empty directory, regardless of local contents.\n", "- `_si_article_/benchmarks/` retains the existing benchmark policy: tracked\n", @@ -829,6 +832,7 @@ "ZIP_TOP_LEVEL_SELECTION = {\n", " \"README.md\": True,\n", " \"README.pypi.md\": True,\n", + " \"CHANGELOG.md\": True,\n", " \"LICENSE\": True,\n", " \"CITATION.cff\": True,\n", " \"MANIFEST.in\": True,\n", @@ -839,6 +843,7 @@ " \"assets/\": True,\n", " \"_si_article_/\": True, # Benchmarks, analyses, empty repositories.\n", " \"docs/\": True,\n", + " \"examples/\": True, # Copyable plugin authoring examples.\n", " \"kilin/\": True,\n", " \"setup/\": True,\n", " \"tests/\": True,\n", diff --git a/assets/trace_benchmark.py b/assets/trace_benchmark.py index 10cbb7fb..b9620c8a 100644 --- a/assets/trace_benchmark.py +++ b/assets/trace_benchmark.py @@ -153,6 +153,7 @@ def _operation_rows( category: str, stage: str, turn: int | None, + trace_id: str | None = None, ) -> list[dict[str, object]]: """Collect only permitted performance fields from readable operations. @@ -168,6 +169,8 @@ def _operation_rows( Turn stage name or empty text for initialization events. turn: int | None Persisted turn ordinal, if applicable. + trace_id: str | None, optional + Restrict measurements to one logger run. Defaults to None. Returns ------- @@ -186,6 +189,8 @@ def _operation_rows( details = operation.get("details") if event_name not in _TRACKED_EVENTS or not isinstance(event, dict): continue + if trace_id is not None and event.get("trace_id") != trace_id: + continue if not isinstance(timing, dict): timing = {} if not isinstance(details, dict): @@ -217,16 +222,19 @@ def _operation_rows( def read_trace_operations( - path: str | Path, label: str + path: str | Path, label: str, *, trace_id: str | None = None ) -> list[dict[str, object]]: - """Read timing-only operations from one KíLín conversation JSON file. + """Read timing-only operations from one KíLín diagnostic JSON file. Parameters ---------- path: str | pathlib.Path - Explicit path of a saved KíLín conversation trace. + Explicit path of a saved KíLín conversation or project trace. label: str Local, non-sensitive run label used to associate its measurements. + trace_id: str | None, optional + Include only events from this logger run; useful for shared project + traces. Defaults to None, reading all recorded runs. Returns ------- @@ -236,7 +244,7 @@ def read_trace_operations( Raises ------ ValueError - If the trace structure or label is invalid. + If the trace structure, declared version, or label is invalid. OSError If the file cannot be read. json.JSONDecodeError @@ -253,9 +261,22 @@ def read_trace_operations( if not isinstance(label, str) or not label.strip(): raise ValueError("A non-empty run label is required.") + if trace_id is not None and ( + not isinstance(trace_id, str) or not trace_id.strip() + ): + raise ValueError("A non-empty trace ID is required.") payload = json.loads(Path(path).read_text(encoding="utf-8")) if not isinstance(payload, dict): raise ValueError("A KíLín trace must contain a JSON object.") + # Older timing-only fixtures have no generation declaration. For a + # declared generation, use the runtime authority before decoding it. + if "trace_format_version" in payload: + from kilin import TRACE_FORMAT_VERSION + + version = payload["trace_format_version"] + if (type(version) is not int + or version != TRACE_FORMAT_VERSION): + raise ValueError("Unsupported trace format version.") sessions = payload.get("sessions") if not isinstance(sessions, dict): raise ValueError("The trace has no valid sessions mapping.") @@ -276,6 +297,7 @@ def read_trace_operations( category=category, stage="", turn=None, + trace_id=trace_id, )) if category != "conversations": continue @@ -304,6 +326,7 @@ def read_trace_operations( category=category, stage=stage, turn=int(match.group(1)), + trace_id=trace_id, )) return rows diff --git a/docs/PLUGIN_API.md b/docs/PLUGIN_API.md new file mode 100644 index 00000000..b17b15de --- /dev/null +++ b/docs/PLUGIN_API.md @@ -0,0 +1,778 @@ +# Python tool plugin API + +The authoritative [versioning policy](versioning.md) governs release numbers, +compatibility generations, and changelog maintenance. + +## Scope and compatibility + +For a complete development and testing workflow, including authoring with a +frontier LLM, see the [plugin authoring guide](PLUGIN_AUTHORING.md). The +[project-type JSON schema](PROJECT_TYPE_SCHEMA.md) specifies the separate +declarative extension contract. The [example pack](../examples/plugins/README.md) +contains copyable packages, matching definitions and offline smoke checks. + +The public authoring interface is `kilin.tools`. `PLUGIN_API_VERSION` is an +integer generation of that interface, independent of KíLín's release version. +Version 1 defines the descriptor and execution contract below. The registry +checks each descriptor's `api_version` before publishing the registry; values +of the wrong type or an unsupported generation are rejected. An incompatible +contract change requires a new API generation. Additions must preserve +existing documented behavior within a generation. + +The runtime discovers distribution and user-level tool packages. Each +bundled descriptor declares its individual version and API explicitly. +Both declarations are required; missing fields are errors. Project types +declare their own implementation `version` and separate JSON +`schema_version`. Their runtime catalog retains missing-tool diagnostics; +see [Project-type JSON schema](PROJECT_TYPE_SCHEMA.md). + +Tool Python code is trusted, in-process code. An API check establishes +compatibility, not safety. The supplied services and filesystem helpers +establish conventions and ownership boundaries; they are not a sandbox. + +## Descriptor and settings + +The supported authoring imports are available from `kilin.tools`, without +constructing the runtime registry, loading project-type definitions or starting +models or Qt. See the [tool contracts](../kilin/tools/_contract.py) for exact +signatures and attribute documentation. + +```python +"""A minimal deterministic tool using only the public authoring API. + +The settings control how many times the original question is repeated. +There are no model calls, filesystem operations, or required assets. + +""" + +from dataclasses import dataclass + +from kilin.tools import ( + Tool, + ToolContext, + ToolRequest, + ToolResult, + check_int, + reject_unknown, +) + + +@dataclass(frozen=True) +class Settings: + """Validated repetition settings. + + Attributes + ---------- + count: int + Number of repetitions, from one to ten. + + """ + + count: int + + +def parse_settings(data: dict, where: str) -> Settings: + """Validate settings from the project type or workspace. + + Parameters + ---------- + data: dict + Raw settings, without the tool name. + where: str + Diagnostic location of the configuration. + + Returns + ------- + Settings + Validated repetition settings. + + """ + + reject_unknown(where, data, ("count",)) + return Settings(check_int(where, data, "count", 1, 1, 10)) + + +def run( + settings: Settings, request: ToolRequest, context: ToolContext, +) -> ToolResult: + """Return the question repeated without invoking host services. + + Parameters + ---------- + settings: Settings + Validated repetition count. + request: ToolRequest + Original user question. + context: ToolContext + Host services, not needed by this deterministic operation. + + Returns + ------- + ToolResult + Repeated question and count, with no claimed source evidence. + + """ + + return ToolResult( + answer="\n".join([request.question] * settings.count), + evidence=(), + summary={"count": settings.count}, + ) + + +PLUGIN = Tool( + name="repeat_question", + summary="Repeat a question a specified number of times.", + version="0.1.0", + api_version=1, + parse_settings=parse_settings, + run=run, +) +``` + +The complete example is also available as a +[copyable source package](../examples/plugins/tools/repeat_question/). Keep +it in a draft folder until you have reviewed it, then use the management +operations described below. Discovery requires no central registry +edit, build metadata, package installer or Python distribution. +The descriptor name must match the package directory and match +`[a-z][a-z0-9_]*`. Declare the API generation the code implements as a literal +integer, not the current host constant: otherwise an incompatible future host +could appear compatible. The descriptor has the following fields: + +| Field | Contract | +| --- | --- | +| `name` | Stable, registered string identifier; use lowercase package-safe names. | +| `summary` | Human-readable explanation of the operation. | +| `version` | Required individual tool version, strict SemVer 2.0.0, independent of KíLín. | +| `api_version` | Required integer generation of the host API implemented by the descriptor. | +| `parse_settings(data, where)` | Validate a configuration mapping; return a settings dataclass or raise `ValueError` with the field/location. | +| `run(settings, request, context)` | Execute with validated settings and return `ToolResult`. | +| `follows_up` | Whether the tool always operates on an earlier answer; defaults to false. Automatic routing excludes its intents when no eligible earlier turn exists in the active conversation. | +| `follows_up_when(question)` | Optional predicate for conditional follow-up behavior. Without `follows_up=True`, the tool remains available for first questions. | +| `routing(settings, project_root, others)` | Optional project-specific `ToolRouting` or `None`; `others` contains settings of other intents using the tool. | +| `source_policies(settings)` | Optional pure tuple of `SourcePolicy` declarations; identifiers are validated at configuration boundaries. | +| `workspace_resources(settings)` | Optional tuple of `WorkspaceResource` declarations for new workspaces. | + +Settings must round-trip through `dataclasses.asdict` and JSON. Use strings, +booleans, finite numbers, `None`, lists/tuples and string-keyed dictionaries; +the parser must accept the JSON representation (tuples become lists). Reject +unknown keys, inappropriate types and out-of-range values. The supported +helpers are `reject_unknown`, `check_bool`, `check_int`, and `check_choice`. +Project-type intent values and workspace overrides are validated by the same +parser. Do not treat a required but missing setting as a successful default. +Bundled tools retain their `defaults.json` and `settings_info.json`. A minimal +plugin may omit either file. If `defaults.json` declares `SETTINGS`, registration +validates those defaults with the parser and checks dataclass/JSON compatibility. +Required settings without declared defaults are validated when configured. +An absent model-call policy inherits the active session; a supplied policy +must be valid. Missing help returns an empty mapping. Malformed supplied help +is rejected by the metadata interface for bundled tools; for user plugins +it produces a nonfatal warning and empty metadata. See +[tool packages](tool_packages.md) and [configuration](configuration.md). + +## Execution context and data records + +`ToolRequest` contains `question`, `text`, optional `guidance`, and `earlier` +(a tuple of `EarlierTurn` records containing number, question, evidence +paths/texts/lines, link status and answer). Use the supplied context rather +than constructing a RAG session, importing the GUI, or invoking another tool. +Treat indexed data and host-owned records as read-only. + +| `ToolContext` field | Supported behavior | +| --- | --- | +| `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. | +| `retrieve(request)` | Optional bounded retrieval returning `RetrievalResult`. | +| `card(path)` | Optional indexed metadata/statements mapping or `None`, without a new model call. | +| `ask_router(system, prompt, max_new_tokens)` | Controlled router call, greedy and without thinking. | +| `ask_model(system, prompt, max_new_tokens)` | Internal answering-model call under the tool's model policy. `None` for the budget inherits the session limit. | +| `ask_check(system, prompt, max_new_tokens)` | Optional short answering-model check, without thinking; otherwise use `ask_router`. | +| `write(system, prompt, max_new_tokens)` | Stream the final answer using session policy; return that reply and set `ToolResult.streamed=True`. | +| `model_id`, `model_attempt_count()` | Model identifier and optional cumulative internal-generation attempt count. | +| `progress(message, **details)`, `done(message, **details)` | Report progress and result status. | +| `confirm`, `choose` | Optional host callbacks; use the recorded interaction helpers below. | +| `trace`, `trace_turn_id` | Host-owned diagnostic sink and turn correlation ID. | +| `write_pdf(markdown, path, label=...)` | Optional PDF renderer; returns actual page count. | +| `suggestions()`, `fixed_suggestions` | Optional current suggested questions and fixed example requests. | + +Optional callbacks may be `None` in notebooks or headless tests. A tool must +handle their absence according to the documented operation rather than assume +that a user or renderer is available. + +The following record types are exported from the same public namespace. Their +fields and constructor semantics are part of the tool-facing contract. + +| Record | Fields and semantics | +| --- | --- | +| `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`). | +| `RetrievalRequest` | `query`, `limits`, `strategy` (`source_first` or `hybrid`), relative `scope`, `scope_mode`, `compare`, `card_kinds`, `include_bibliographies` (`None`, `False`, or `True`; source-first only), optional resolved `view`. | +| `RetrievalResult` | Original `passages` in citation order, selected physical `sources`, JSON-compatible `coverage`, optional logical `groups` and resolved `view`. In grouped mode `sources` contains distinct represented physical paths; `groups` records selected anchors. Source selection does not imply exhaustive reading. | +| `SourceScope`, `ScopeMode` | Immutable mode and ordered explicit path operands; project, preferred or restricted. | +| `SourcePolicy`, `SourcePurpose` | Document/lookup/raw purpose, target/candidate/evidence/lookup role filters, permitted `related_evidence` and `related_lookup`, and opt-in `grouped`. | +| `SourceFileState`, `SourceInventory` | Physical path, recorded digest, indexed availability and captured index generation. | +| `SourceOperation`, `SourceView` | Frozen semantic and physical generation, effective policy/scope, targets, candidates and groups. | +| `SourceGroup`, `UnavailableMember` | Anchor-centered physical evidence/lookup membership and unavailable-path reasons. | +| `SourceGroupCoverage` | Actual represented members and anchor representation; not full-document review. | +| `Suggestion` | `intent`, `question`. | +| `ToolRouting` | Additional regex `cues` and router `description`. | +| `WorkspaceResource` | Package-owned file `source`, workspace-relative POSIX `destination`. | + +See the [retrieval pipeline](retrieval_pipeline.md) and the [retrieval request +contracts](../kilin/retrievals/requests.py) for semantics of limits, source +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 + +The immutable source-view records and these functions are exported from +`kilin.tools`, without initializing the catalog or loading models: + +| Service | Contract | +| --- | --- | +| `capture_source_inventory(inspection, index_state, indexed, index_generation)` | Capture the host's coherent physical selection and index identities. | +| `resolve_source_view(inspection, inventory, policy, scope)` | Validate against accepted project vocabulary and selected membership; resolve one-hop views without I/O. | +| `validate_source_view(view, inspection, inventory, policy, scope)` | Compare with current supplied state; raise `SourceViewConflict` on incompatible or stale views. | +| `read_source_bytes(project_root, source_root, view, path)` | Read a permitted selected file and verify its captured digest, preserving the existing workspace raw-read boundary. | +| `group_coverage(group, passages)` | Derive physical group representation from original returned chunks. | + +See [source views](retrieval_pipeline.md#source-views-and-operation-snapshots) +for field defaults, purpose, scope, relationship direction, availability and +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 +the live accepted manifest and loaded index generation. `retrieve()` enforces +an explicit scope or validated `view` before all ranking channels and +expansion. Grouped documentary views require `source_first`; ungrouped +views support both strategies. Stale views, grouped hybrid and raw ranking +requests fail clearly. Grouped requests count anchors for `max_sources`, +and `passages_per_source` is a target for each selected group. Shared +original passages consume the hard global passage and estimated-token +budgets only once. `groups` reports represented physical members, lookup +membership, unavailable members and actual anchor representation; coverage +counts evidence-bearing groups and anchors separately. +The result carries its resolved view. New scoped tools obtain services +through `require_source_services(context, policy, scope)`. The host captures +one generation lazily and resolves all subsequent views for that tool run +against it. For example: + +```python +from kilin.tools import SourcePolicy, SourceScope, require_source_services + +citing = require_source_services( + context, SourcePolicy(related_lookup=("bibliography_for",)), + SourceScope("restricted", (manuscript,)), +) +for path in citing.view.lookup: + data = citing.read_bytes(path) +``` + +This example assumes the project accepts `bibliography_for` and `manuscript` +is an eligible relative `Path`. The returned `ToolSourceServices` exposes +`view`, immutable `chunks`, `files` (including unindexed members), scoped +`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 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. + +Tools may declare `source_policies(settings)` on their descriptor; +`check_source_ids` validates arrays of distinct identifiers, and +`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. 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 +invent an operation snapshot. +These APIs preserve correctness of selection and provenance, not security +against arbitrary trusted in-process Python. No plugin sandbox is provided. + +## Results, failures and interactions + +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 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; +its `reason`, `finish_reason`, `raw_text`, and `to_dict()` distinguish failure +from a result. The raw text is not a valid answer. Internal thinking retries +and token budgets are owned by the host. For independent items, use +`partial_result(result, failures, completed=True)` to retain verified work +and mark incomplete items; set `completed=False` if nothing was assessed. +`GenerationCancelled` inherits `BaseException`; let it propagate so Stop +cannot become a successful or partial answer. See the +[answering pipeline](answering_pipeline.md). + +For user interactions, use `confirm_plan(plan, policy, large_batches, +context)` and `ask_choice(question, options, context)` rather than invoking +the raw callbacks. Both helpers preserve the host's interaction records. +`ToolPlan` has `tool`, `summary`, `scope`, `items`, `batches`, `batches_to_run`, +`estimated_seconds`, `quick_items`, `quick_seconds`, optional `details`, +`quick_label`, `quick_note`, and `operation`. Confirmation policies are +`always`, `when_large`, and `never`; choices are `continue`, `quick`, and +`cancel`. The confirmation helper returns `(choice, asked)` and continues +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)` +and `span(event_type, *, component, data=None, turn_id=None)`. A span is a +context manager yielding its ID; it propagates operation failures. Use +`component="tool"` and the supplied turn ID. Do not include source or prompt +content unless `include_content` is true. Do not close the trace, alter its +configuration, write its files or invent interaction events. See +[trace recording](trace_recording.md). + +## Source and output ownership + +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 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 +to `Path(__file__).parent`. The loader binds the actual package directory, not +a path claimed by the descriptor. Registered tools expose `resource_root`; +`model_calls` and `internal_defaults` resolve against it. These properties +require a registered descriptor. The core validates and copies declared +`WorkspaceResource` files when creating a workspace. Refer to the +[workspace contract](project_workspaces.md) for ownership and safe publication. + +Template resources must be declared under `templates//`. +Use the public, side-effect-free helpers to construct paths and declarations: + +```python +from pathlib import Path +from kilin.tools import template_resource, templates_folder + +resource = template_resource(Path(__file__).parent / "templates/report.md", + "my_tool") +# resource.destination == "templates/my_tool/report.md" +folder = templates_folder(project_root, "my_tool") +``` + +The core checks ownership against the registered descriptor, not a name +supplied by the caller. A raw `WorkspaceResource` can also declare nested +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 follow their own documented +contracts. + + +## Catalog access and initialization + +`kilin.tools.registered_tools()` returns a read-only mapping of the runtime's +tool definitions. `kilin.tools.tool_choices()` returns available identifiers +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. 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. +Explicit directory validation remains strict. + +`ToolName` is an open `str` alias; it is not authorization to import arbitrary +Python paths. `parse_tool(where, data)` resolves a configured ID and validates +settings; `run_tool(use, request, context)` dispatches a validated `ToolUse`. + +Use the explicit catalog accessors rather than mutable registry dictionaries +or import-time snapshots. Tool-specific settings, constants and helpers belong +to their owning tool packages, not the shared authoring facade. Independent +plugins should use the documented shared interfaces, not private modules. + +## User storage, discovery and validation + +`kilin.plugins.plugin_directory()` returns the captured absolute location: + +| Platform | Default user plugin directory | +| --- | --- | +| macOS | `~/Library/Application Support/kilin/plugins` | +| Linux | `$XDG_DATA_HOME/kilin/plugins`, or `~/.local/share/kilin/plugins` | +| Windows | `%LOCALAPPDATA%/kilin/plugins`, or `~/AppData/Local/kilin/plugins` | + +An absolute `KILIN_PLUGINS_DIR` overrides this location. Set it before the +first catalog query or `plugin_directory()` call. Resolving the location or +importing the API does not create files. Starting a runtime creates its +private coordination files. Management may also create user storage folders. +There is no workspace-level plugin store, registry database or dependency +installer. A missing directory is normal. Managed installation (described +below) creates the following active layout; it may also be created manually +while all KíLín processes and notebook kernels using the directory are closed: + +```text +plugins/ + tools/ + repeat_question/ + __init__.py + project_types/ + repetition.json +``` + +A tool package may also contain its own Python modules, `defaults.json`, +`settings_info.json` and resources. Use relative imports for package-local +code. The loader imports a user package in its own namespace, without +adding its directory to `sys.path`, and uses source rather than cached +bytecode. A package must consist of regular files and directories (no +symlinks, except ignored cache files). Dependencies must already be +available in KíLín's Python environment. Do not import other plugins. + +Project types refer to tool IDs, not Python module paths. For example, +[`repetition.json`](../examples/plugins/project_types/repetition.json) uses +the minimal tool above: + +```json +{ + "version": "0.1.0", + "schema_version": 1, + "source_organization": { + "roles": [ + "document", + "notes" + ], + "default_role": "document", + "relation_types": { + "attached_to": { + "behavior": "dependency" + }, + "related_to": { + "behavior": "association" + } + }, + "automatic_rules": [] + }, + "display_name": "Repetition", + "description": "Repeat a question using a deterministic tool.", + "extensions": [".txt", ".md"], + "max_file_bytes": 4096, + "retrieval_instruction": "Find relevant information.", + "system_prompt": "Use the configured repetition tool.", + "history": {"exclude_disliked_answers": true}, + "conversation_memory": { + "enabled": false, + "questions": "all", + "answers": "selected", + "max_hits": 4, + "max_tokens": 2000 + }, + "intents": { + "repeat": { + "description": "Repeat a question.", + "tool": {"name": "repeat_question", "count": 2} + } + } +} +``` + +Copying code into the tools directory is an explicit trust decision: the +next runtime will import it with the user's permissions. Review generated +code, particularly file access, network operations and dependencies, before +copying or enabling trusted validation. Do not change the directory contents +while a runtime is active: a plugin may read resources or import modules +lazily. Use the managed operations below rather than editing installed files. +Bundled IDs take precedence over user IDs; conflicts +are visible as rejected candidates. An unavailable tool makes only types +that require it unavailable. A missing optional help file is harmless; +invalid user help is reported as a warning and omitted from settings help. + +The headless inspection and validation interface is `kilin.plugins`: + +```python +from pathlib import Path +from kilin import plugins + +for info in plugins.list_tools(): + print(info.name, info.origin, info.available, info.error, info.warnings) +for info in plugins.list_project_types(): + print(info.type_id, info.origin, info.available, info.error) + +candidate = Path("drafts/repeat_question").resolve() +structure = plugins.validate_tool(candidate) +print(structure.error, structure.sha256, structure.runtime_checked) +# Only after inspecting and trusting the code: +checked = plugins.validate_tool(candidate, trusted=True) +print(checked.available, checked.error) + +kind = plugins.validate_project_type(Path("drafts/repetition.json"), + bind_tools=False) +print(kind.error, kind.required_tools, kind.bound) +``` + +The default tool validation checks directory layout, source syntax and +JSON, without executing candidate code. Trusted validation imports the +candidate in a fresh interpreter, with a bounded 30-second worker timeout. +It checks the descriptor, version, defaults and optional help, without +replacing an already loaded plugin. It does not execute the tool runner or +prove its safety, and the worker is **not a security sandbox**. Structural +success is reported as `error is None` with `runtime_checked=False`; only +successfully runtime-checked candidates have `available=True`. Similarly, +project-type validation with `bind_tools=False` checks structure without +resolving tool references; `bound=False` means it is not execution-ready. +The default (`bind_tools=True`) resolves required tools against the current +catalog and validates their settings. It may initialize trusted installed +plugins. Validation is not installation and never activates the candidate. + +The host validates settings dataclasses and JSON-compatible result data at +configuration and execution boundaries, but cannot prove semantic accuracy +or resource use in advance. Use deterministic unit tests for those behaviors. + +## Managed installation and deferred activation + +The headless management API accepts ordinary Python package folders and JSON +files. It copies candidates, rather than installing Python distributions or +linking to a developer's draft. Existing user installations require an +explicit update; bundled entries cannot be modified by this API. Validate +Python only after reviewing and trusting its code. Installation and updates +of tools require `trusted=True` and execute the staged copy in the existing +validation worker. This worker is not a security sandbox. Its plugin store +is disposable, so catalog queries by the candidate cannot activate pending +changes in the real store. Third-party dependencies must already be present. + +```python +from pathlib import Path +from kilin import plugins + +# These queue changes; they do not hot-reload the runtime. +plugins.install_project_type(Path("drafts/repetition.json")) +plugins.install_tool(Path("drafts/repeat_question"), trusted=True) + +for entry in plugins.list_installed_plugins(): + print(entry.kind, entry.name, entry.path) +for change in plugins.pending_changes(): + print(change.kind, change.name, change.action, change.version, + change.api_version, change.schema_version, change.error) + +# Later, after the initial installation has activated: +# plugins.update_tool(Path("drafts/repeat_question"), trusted=True) +# plugins.update_project_type(Path("drafts/repetition.json")) +# plugins.uninstall_tool("repeat_question") +# plugins.uninstall_project_type("repetition") +# plugins.cancel_pending_change("tool", "repeat_question") +``` + +The `InstalledPlugin` and `PendingPluginChange` records are immutable. +`list_installed_plugins()` enumerates user entries without importing them, +including broken packages and user entries conflicting with bundled IDs. +`pending_changes()` lists complete queued operations, including activation +errors and each validated replacement's `version`, `sha256`, and applicable +`api_version` (tool) or `schema_version` (project type). A removal has no +replacement identity. The replacement may differ from the still-active +catalog entry. These queries do not initialize the active catalog or +acquire a runtime lease. By contrast, `list_tools()` and `list_project_types()` inspect +the active catalogs and may start a runtime. Management raises a validation +or filesystem error on an unsuccessful copy or candidate check; it does not +publish an incomplete operation. A project-type JSON may be installed before +its required tools; structural validation does not execute Python or bind +tool settings, and discovery reports it as unavailable until those tools +can be resolved. + +A runtime holds a lease on the captured plugin directory until process exit. +All cooperating KíLín runtimes using that directory, including notebook +kernels and the desktop parent and engine, must close before a pending change +can activate. The first subsequent runtime applies the queue before discovering +plugins. Other runtimes starting while a lease exists continue to use the old +installation. An engine restart while the desktop window is open therefore +cannot activate replacements. A process using only management APIs does not +hold a runtime lease; its first catalog access may activate the queue if no +other runtime remains. Closing a workspace does not release its process lease. + +The private `.management/` directory contains the coordination lock, OS-locked +runtime leases, staged copies and a pending-operation journal. It is not a +second plugin registry or workspace manifest. An exclusive gate serializes +short state transitions, and one live staging reservation per ID prevents +concurrent updates of that entry. Trusted validation runs outside the gate. +Pending operations activate deterministically (tools, then project types, +sorted by ID), with one recoverable transaction per entry, not an all-or-none +transaction across the entire queue. An update first moves the old entry to +its private backup, then publishes the checked replacement by rename. If a +process is interrupted, the next eligible startup recovers the operation +before discovering packages. Recoverable errors preserve the old entry and +retain a diagnostic in the queue; cancel the operation or repair the cause +and restart. Canceling a pending change never undoes a published installation. +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. 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 + +Open **Settings > Plugins**, above the project-specific settings tabs. This +application-level section is available before creating a workspace or loading +models. The existing project Tools tab continues to edit the settings of tools +used by that project, not the installed plugins. The Plugins section displays +bundled and user entries separately, including unavailable definitions, +implementation versions, API or schema generations, captured digests, +required tools and diagnostics. Bundled +entries are read-only; a conflicting user copy is shown separately and can be +removed. Refresh reads the current catalog and durable operation queue, not a +hot-reloaded catalog. + +Choose a tool package folder or project-type JSON file. Selection alone does +not import the candidate or change installed files. **Check structure** checks +layout, syntax or JSON without executing candidate Python; **Validate** checks +the actual descriptor or resolves the required tools, without installing. +Each trusted Python validation, installation or update requires a separate +confirmation describing its source path and execution permissions. A successful +validation is not a security audit. An installation validates a new staged +copy, even if the original candidate was already validated. + +**Install** queues a new entry. **Update** on an existing user entry chooses a +replacement with the same ID. **Remove** queues removal, including for broken +entries; neither operation modifies workspaces. Structurally valid project +types may be queued even when the current runtime lacks required tools. Pending +changes and recovery errors are displayed separately from the active inventory, +with the replacement version, API/schema generation, and digest. +Cancel pending change discards an uncommitted operation. The core retains final +authority over paths, conflicts, validation and activation. No changes are +silently applied on closing Settings, closing a project or restarting the +engine. Quit all KíLín applications and Python/notebook runtimes using this +plugin directory, then launch again. If a validation or mutation is interrupted, +refresh the actual queue before retrying; the interface never automatically +repeats a potentially committed mutation. + +See the [desktop plugin protocol](extension_interfaces.md#desktop-plugin-management-protocol) +and the [frontend regression tests](../tests/kilin/gui/test__plugins_frontend.py). + +## Execution identity + +The immutable discovery records retain an origin, implementation version, +API or schema generation, and SHA-256 digest. Tool +identity hashes sorted relative file names and contents, excluding bytecode +and `__pycache__`; JSON identity hashes the captured definition bytes. +These portable identities do not include absolute user paths. The trace's +`turn.settings.snapshot` includes `project_type_plugin` when available, +and the selected `tool.run` span always includes `plugin` (null if the +identity is unavailable). Persisted turn parameters include the +selected identities as `project_type_plugin` and `tool_plugin` when known. +These describe the package bytes captured during registration, not a proof +of the behavior of arbitrary code or external dependencies. + +## System-testing provenance and replay + +Every `gui.project.configuration.effective` observation also records +`plugins`, with the captured `project_type` identity and a mapping `tools` +from configured tool IDs to their identities. This includes tools that have +not yet executed. The existing compact configuration-reference digest covers +this field; equal snapshots can be referenced, while changed plugin bytes +produce a new full observation. No new trace format or workspace manifest is +required. The tool execution span and saved turn parameters still record the +selected implementation, not just the set of available plugins. + +[System testing](system_testing.md) separates historical inspection from +fresh execution. Validation, comparison, and retained-replay receipt reading +use the recorded identities without importing installed plugin packages or +requiring the original project type to exist. The saved profile still must +satisfy its syntax, value, filesystem and recorded-state contracts. Every +opening configuration requires the complete plugin snapshot, and every tool +execution requires its plugin field. Missing required metadata or malformed +identities block recording validation. Null identities and unavailable +turn identities are `unknown`; no historical identity is inferred. A difference +in identity alone is not a change to persistent workspace settings and does +not invalidate a recording. + +Fresh replay preflight resolves the current project type and all tools +required by its definition, the historical configuration, or historical +execution. Missing or unavailable requirements fail before creating a +workspace, loading models, or archiving a previous managed replay. Replaying +uses the current compatible implementation, not a reconstruction of old +code. The managed execution receipt's `environment.plugins` records the +portable identities checked at preflight, alongside the existing KíLín +package/environment fingerprint. No unrelated installed plugins or absolute +plugin locations are included in this receipt field. + +Comparison JSON contains per-workspace and per-aligned-operation +`plugin_provenance` observations. Markdown and notebook reports distinguish +known changes, unknown identities and one-sided observations (for +example, a different routed tool); only known changes become plugin identity +differences in `ReplayResult.differences`. Batch reports flag these as +environment changes for review, not answer-quality verdicts. A missing +identity never becomes the current installed identity. These observations +identify captured package bytes, not a complete fingerprint of third-party +libraries, model weights, or arbitrary runtime effects. The normal +system-testing restrictions on persistent configuration changes remain in +force. See the [plugin provenance tests](../tests/kilin/system_testing/test__plugin_provenance.py) +for deterministic external-plugin execution, replay and offline inspection. + + +## Verification + +The authoring boundary has fresh-interpreter tests in +[the plugin API regression suite](../tests/test__plugin_api.py). They check +import order, absence of catalog reads, one-time concurrent construction, +failed and recursive initialization, identifier validation, and descriptor +execution using the public interface. The +[registration tests](../tests/kilin/tools/test__registration.py) additionally +check bundled descriptors, optional resources, discovery and relocation. +The [management tests](../tests/kilin/test__plugin_management.py) exercise +trusted staging, pending operations, multiple processes, lazy resources, +crash recovery and declarative type installation. + +For a stacked feature branch, run both complete repository test runners +(`python -m pytest` and `python -m tests`) against the exact head. Run the +existing Python tests and Distribution package workflows on that branch via +their manual dispatch if normal pull-request triggers do not cover the stack +base; verify the reported head SHA. Native and model-dependent checks remain +subject to their documented environments. + +## Related + +[Extension interfaces](extension_interfaces.md), +[Tool packages](tool_packages.md), [Development](development.md), +[Security](security.md). diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md new file mode 100644 index 00000000..b0515896 --- /dev/null +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -0,0 +1,5 @@ +# Tool API changelog + +This changelog records changes to the public tool API contract. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/docs/PLUGIN_AUTHORING.md b/docs/PLUGIN_AUTHORING.md new file mode 100644 index 00000000..5d56759c --- /dev/null +++ b/docs/PLUGIN_AUTHORING.md @@ -0,0 +1,244 @@ +# Authoring your own KíLín plugins + +The authoritative [versioning policy](versioning.md) governs release numbers, +compatibility generations, and changelog maintenance. + +## Choose the smallest extension + +A project type is declarative: use JSON alone to configure source types, +answering instructions, intents, history, retrieval and existing tools. Add +Python only for an operation that needs explicit behavior, such as a +measurement, validated structured output or a deterministic analysis. A +Python tool plugin and its project-type JSON are independent artifacts; the +JSON selects the tool by ID and supplies settings. They use the same contracts +as bundled components. User plugins do not require changes to KíLín itself. + +The [Python API v1](PLUGIN_API.md) and [project-type schema v1](PROJECT_TYPE_SCHEMA.md) +are the authoring contracts. The [example pack](../examples/plugins/README.md) +contains complete source packages and matching JSON. It is included in the +source distribution, not installed as executable tools in the wheel. + +When defining source organization, use the declared vocabulary and closed +set of detector names from the +[project-type schema](PROJECT_TYPE_SCHEMA.md#source-organization-declarations). +Do not name a Python function as a discovery detector. Keep ordinary-intent +relation policies separate from tool-owned settings; ordinary answering +applies them when resolving the active view, and deterministic discovery +operates under the accepted manifest. The [source-view contracts](PLUGIN_API.md#source-view-services) +resolve accepted roles and relationships for host-provided snapshots. +Specify distinct target and candidate roles, supporting evidence and lookup +relations, and explicit scope; bibliographies are not publications. Use +custom role and relation IDs only when declared in the accepted vocabulary. +Test two parents sharing a dependency and a restricted empty scope. Do not +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. 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 + +1. Specify the task, accepted inputs, expected answer/evidence and output + files, settings and bounds, how to handle absence of data, and whether a + user choice or local model call is necessary. Write deterministic examples + of success, failure and cancellation before implementing. +2. Choose a unique stable ID. Keep a draft directory outside the user plugin + store. Write `__init__.py` exposing `PLUGIN = Tool(...)`, with an explicit + SemVer 2.0.0 implementation version (initially `0.1.0`) and literal + `api_version=1`. Both are required. Keep package-local imports + relative. A minimal tool needs no metadata files; more advanced tools can + declare their own settings metadata, defaults and workspace resources. +3. Use only supported `kilin.tools` imports and the supplied request/context + services. Reject unknown or invalid settings; use JSON-compatible dataclass + values. Keep model work bounded, verify evidence and output before + returning, use recorded interaction helpers, and let cancellation + propagate. Do not depend on other plugins or private host modules. +4. Review the complete draft as executable code before running any validation + that imports Python. Check import-time side effects, dependency imports, + file paths, subprocesses, network operations and possible data disclosure. + Use structural validation first; it does not import candidate Python. +5. Run isolated trusted validation, then deterministic execution tests with + synthetic inputs. Exercise invalid settings and missing sources/services, + multiple selections, cancellation, repeat runs, and safe output naming. + Validation alone does not run the tool or demonstrate its correctness. +6. Declare the project type's independent SemVer `version` and integer + `schema_version` explicitly, then validate the matching JSON structurally. + Install or update both artifacts + with the core API or the desktop Plugins panel, then close every process + using that store. Restart and check catalog diagnostics and tool binding. + Use a disposable workspace before testing on valuable data. +7. Assess the individual version against the last published implementation + using the [versioning policy](versioning.md). Increment it when behavior + or the contract warrants a new release; source digests can also change + when the declared version remains unchanged. + Review updates for compatibility with saved workspace settings. Never edit + an installed package while a runtime is active. + +## Developing with a frontier LLM + +A frontier LLM can draft a plugin without having access to the whole KíLín +repository or to the user's data. Provide these three reference documents, +only the relevant example files, and a small fictional input/output example. +Do not upload real workspaces, papers, credentials, trace contents or +confidential research unless you have separately decided that the provider +may receive them. Neither authoring nor installing a plugin requires a +frontier-model service, API key, or network access from KíLín. + +A useful starting prompt (replace the placeholders): + +```text +Implement a KíLín user plugin for [task] using the supplied Python tool API +v1, project-type JSON schema v1, and examples. Do not modify the host package. +Return a folder named [tool_id] with __init__.py exposing PLUGIN, any local +modules/resources, and a separate [type-id].json. Use only public kilin.tools +imports and the standard library unless I approve another dependency. + +Inputs: [selected sources, user request, settings]. +Outputs: [answer, exact evidence, machine-readable summary, optional file]. +Bounds: [maximum work, input size, token or output limits]. +Failure and cancellation behavior: [what must be preserved, what to report]. + +Use a JSON-compatible settings dataclass and explicit validators. Declare +api_version=1 and version="0.1.0" (strict SemVer). The project-type JSON +must also declare version="0.1.0" and schema_version=1. No network access, +package installation, subprocesses or filesystem writes at import time. Do not +introduce private host imports or dependencies on other plugins. Use safe +workspace resource and output helpers. Do not invent evidence. + +Provide a minimal model-free test using controlled services and cases for +invalid settings, missing inputs, cancellation and repeated execution. +Explain all file access and any optional services. If the required capability +is absent from the documented API, explain the limitation instead of +inventing an interface. Wait for my review before execution or installation. +``` + +Check the model's output against the actual API, not just against plausible +names. Return validation diagnostics and the failing synthetic test to the +model for a narrowly scoped correction. Re-review changed bytes. A successful +trusted check is not a security review or proof of correctness. A plugin +executes with the user's permissions; only install code you trust. + +## Safe isolated trial + +Run the following command from a checkout or unpacked source distribution +with KíLín installed in the active interpreter: + +```bash +python examples/plugins/check_examples.py +``` + +The example runner uses its own temporary user store, stages source packages, +starts a fresh child to activate them, runs model-free tests and removes the +temporary directory only after all children exit. It leaves the user's actual +plugin store and workspaces unchanged. The same runner is used for the +installed-wheel acceptance check. Its source is a template for plugin tests; +use explicit synthetic model services and small, nonconfidential sources. + +To validate a draft yourself without executing candidate Python: + +```python +from pathlib import Path +from kilin import plugins + +candidate = Path("drafts/source_note") +info = plugins.validate_tool(candidate) +print(info.error, info.sha256, info.runtime_checked) +``` + +After reviewing the candidate, use `plugins.validate_tool(candidate, +trusted=True)`. Check `info.available`, `info.error` and `info.warnings`. +The validation subprocess has a timeout and disposable plugin store, but it +is not a security sandbox. It does not execute the runner. For a JSON file, +use `plugins.validate_project_type(path, bind_tools=False)` first; the default +full check binds against the *current* installed catalog. A candidate tool +that is only staged is not yet available to the current process. The +catalog, including its selected plugin root, is fixed for that process; do +not try to refresh it by reloading Python modules. + +## Installation and maintenance + +The desktop **Settings > Plugins** section is application-level. Choose the +folder containing `__init__.py` (not its parent) or the individual JSON file. +Use Check structure, then Validate after review. Install queues a new entry; +Update on an existing user entry chooses a replacement with the same ID; +Remove queues removal even when a plugin is broken. Distribution entries +are read-only. Pending changes can be canceled before activation. Close all +applications, Python processes and notebook kernels using that directory, +then start again. Engine recovery or closing one workspace is not enough. + +The headless equivalents are `plugins.install_tool(path, trusted=True)`, +`plugins.install_project_type(path)`, the explicit `update_*` and +`uninstall_*` operations, `plugins.pending_changes()` and +`plugins.cancel_pending_change(kind, name)`. Paths and returned records are +described in the [plugin API](PLUGIN_API.md). The queued replacement identity +is distinct from the active plugin's identity until activation. Dependencies +must already be available in the active interpreter. The manager does not install wheels, +PyPI packages or ZIP archives or resolve dependencies. Keep drafts and tests +under version control separately from the active plugin store. Do not edit +its private management journal. + +New type IDs appear in project selection only when available. Existing +workspaces whose type or required tool is absent remain on disk and visible +with a diagnostic. Restore the required compatible plugin and restart; +never rewrite a saved profile to bypass the missing requirement. Removing a +plugin does not remove its existing workspace outputs or copied resources. +Historical traces and comparisons remain readable; a fresh replay checks +current availability and reports known plugin identity changes. + +## Scoped source services + +A tool that selects documents or supporting evidence should declare its +source policies in validated settings and use `require_source_services` +from `kilin.tools`. The optional `Tool.source_policies` callback returns a +pure tuple of policies, checked against the enclosing type and accepted +project vocabulary. Do not interpret relationship graphs independently. +Use a document view for eligible publication anchors, separate lookup views +for physical queries, and restricted views when the user selects a target. +Use only the bound chunks, rank, card, retrieval and verified-byte services. +Call `validate()` before writing derived outputs. Test empty restrictions, +missing services, stale views and separate evidence/lookup membership. +The runnable `examples/plugins/tools/source_note` example uses an explicit +lookup view and then a restricted view of the chosen original excerpt. +See [source-view services](PLUGIN_API.md#source-view-services). + +## Acceptance checklist + +- Stable ID, explicit version and API/schema generation; no private imports, + unreviewed dependencies, or import-time model/workspace operations. +- JSON round-trip settings, invalid and boundary inputs, defaults and + workspace override precedence tested. +- Bounded work; exact source evidence and honest coverage; no unrelated file + access, source modifications or output overwrites. +- Optional callbacks handled, recorded interactions, incomplete generation + and cancellation handled according to the host contract. +- Structural and trusted checks succeed; real deterministic execution tests + succeed; installation, update and removal verified in an isolated store. +- README documents every setting, expected inputs, output and limitations. + Review the complete package before each trusted execution. + +## Project-owned templates + +Declare packaged templates with `kilin.tools.template_resource(source, name)` +and resolve the project's directory with `kilin.tools.templates_folder(root, +name)`. The namespace is `templates//`; the core +checks declarations and copies only missing resources during creation or +explicit repair. Existing project files are not rewritten on plugin upgrade. +See the [tool API](PLUGIN_API.md). + +## Related + +[Python tool API](PLUGIN_API.md), [Project-type JSON schema](PROJECT_TYPE_SCHEMA.md), +[Security](security.md). + +In a source checkout, [Tutorial 160](../tutorials/160_project_types.ipynb) +introduces project types and [Tutorial 180](../tutorials/180_create_custom_tool.ipynb) +introduces the tool contract. The guided LLM-assisted exercises in +[Tutorial 200](../tutorials/200_develop_project_types_with_llm.ipynb) and +[Tutorial 210](../tutorials/210_develop_tools_with_llm.ipynb) cover requirements, +drafting, review, correction, and model-free checks in a disposable store. +Installation in the regular user store remains an explicit manual step. diff --git a/docs/PROJECT_TYPE_SCHEMA.md b/docs/PROJECT_TYPE_SCHEMA.md new file mode 100644 index 00000000..e0c4f61f --- /dev/null +++ b/docs/PROJECT_TYPE_SCHEMA.md @@ -0,0 +1,338 @@ +# Project-type JSON schema (version 1) + +The authoritative [versioning policy](versioning.md) governs release numbers, +compatibility generations, and changelog maintenance. + +## Identity and compatibility + +A project type is a single UTF-8 JSON object, not executable Python. It +selects source defaults, shared instructions, routing, retrieval, history, +conversation memory and optionally registered tools. Distribution definitions +live under `kilin/project_types/`; user definitions live under +`plugins/project_types/` in the user-level plugin directory returned by +`kilin.plugins.plugin_directory()`. Neither belongs to a workspace. + +Name the file `.json`. Its stem is the stable type identifier saved +in `profile.ini`. Type and intent IDs match `[a-z][a-z0-9_-]{0,31}`. Tool IDs +instead match `[a-z][a-z0-9_]*` and must match a Python package directory and +its `PLUGIN.name`. Distribution IDs take precedence over user conflicts. +Every definition must explicitly declare an independent SemVer 2.0.0 +`version` (initially `"0.1.0"`) and integer `schema_version: 1`. Missing +or malformed declarations, unsupported schema generations, unknown fields +and duplicate JSON object keys are errors. Booleans are not accepted as +integers. Field names are case-sensitive. +The runtime parser, not a second schema implementation, is authoritative: +see [project_type.py](../kilin/project_type.py). Schema generation is +independent of the Python tool API and the application version. + +## Required project-wide fields + +| Field | Accepted value | +| --- | --- | +| `version` | Required independent implementation version, strict SemVer 2.0.0. | +| `schema_version` | Required integer schema generation, currently 1. | +| `display_name` | Nonblank text shown in the selector. | +| `description` | Nonblank text about the project, shown to the router. | +| `extensions` | Nonempty list of literal file suffixes starting with `.`; normalized to lowercase. A suffix does not implement a new source reader. | +| `max_file_bytes` | Positive integer size limit per source file. | +| `retrieval_instruction` | Nonblank task description for embedding queries. | +| `system_prompt` | Nonblank shared answer instructions. | +| `history.exclude_disliked_answers` | Required boolean, excludes disliked answers from context without deleting history. | +| `conversation_memory` | Object with all five fields below, even when disabled. | +| `intents` | Nonempty object mapping intent IDs to their definitions, in routing order. | + +`history.recent_turns` is optional (integer 0–100; defaults to +`PROJECT_TYPES.DEFAULT_RECENT_TURNS` in `kilin_defaults.json`, currently 2). +Conversation memory is distinct from recent or related turns and source +retrieval. The memory object accepts exactly: + +| Field | Accepted values | +| --- | --- | +| `enabled` | Boolean. | +| `questions` | `all` or `none`. | +| `answers` | `none`, `selected`, or `all`. | +| `max_hits` | Integer 1–20. | +| `max_tokens` | Integer 128–20000. | + +## Optional project-wide fields + +| Field | Accepted values and defaults | +| --- | --- | +| `default_intent` | One of the defined intent IDs; defaults to the first intent. | +| `answer_guidance` | Text; empty by default. | +| `source_organization` | Role vocabulary, default role, relation types and deterministic discovery declarations. See below. | +| `generation` | `thinking` (boolean) and/or `temperature` (finite nonnegative number). Omitted fields inherit packaged profile defaults. Applies to new projects only. | +| `capabilities.code_graph` | `true`, `false`, or `"auto"` (default). | +| `capabilities.document_headers` | Boolean; default false. | +| `capabilities.source_cards` | Optional object with `enabled` (boolean, false), `kind` (snake-case identifier or null), `automatic` (boolean, defaults to enabled). | +| `welcome_prompts`, `suggestions` | Lists of nonblank strings, default empty. | +| `welcome_templates` | List of nonblank fill-in headings, default empty. | +| `suggestion_templates` | Object mapping known intent IDs to one nonblank template or a nonempty list of templates. | + +Template placeholders are `{file}`, `{file2}`, `{topic}`, `{term}`, and +`{theme}`. Other placeholders or unmatched braces fail validation. Source-card +kinds must correspond to the available card-generation behavior when used; +this JSON field does not register a new card generator. The parser accepts +an identifier structurally, rather than importing a generator by name. + +## Source organization declarations + +`source_organization` declares a vocabulary, not assignments to individual +files. It is independent of intrinsic file eligibility, physical indexing, +source-card kinds and conversation memory. Both distribution and user types use the same declaration parser. New projects +capture the accepted vocabulary and exact type identity in the +[semantic source manifest](source_manifest.md); later changes to installed +defaults require explicit adoption. Deterministic discovery executes under +accepted settings. [Source views](retrieval_pipeline.md#source-views-and-operation-snapshots) +resolve accepted declarations without I/O; ranking integration remains +subsequent work. + +If the object is omitted, the neutral default is the single role +`unassigned`, the two generic relations, and no automatic rules. If supplied, +`roles` and `default_role` are required. The other fields are optional. + +| Field | Accepted values and defaults | +| --- | --- | +| `roles` | Nonempty array of unique role IDs. | +| `default_role` | One of the declared roles; not inferred from file extension. | +| `relation_types` | Object mapping relation IDs to objects containing exactly `behavior`: `dependency` or `association`. Omitted defaults to the two generic relations. | +| `automatic_rules` | Array of objects containing exactly `id`, `detector`, `relation`, `mode`. Omitted defaults to empty. | + +Role, relation and rule IDs match `[a-z][a-z0-9_-]{0,31}`. Case and whitespace +are not normalized. `attached_to` is always a directed `dependency`, from +the dependent file to its parent. `related_to` is always a symmetric +`association`, preserving both files' independence. Both are supplied even +when omitted and cannot be redefined with a different behavior. A role +alone does not grant access to a file or establish a scientific publication. + +The closed detector registry currently accepts only `latex_bibliography`. +Its declared relation must exist and have `dependency` behavior. The rule +may name a custom dependency relation. Each detector can occur at most once +per vocabulary; duplicate rule IDs also fail validation. Rule mode `apply` +applies confidently identified selected relationships; `propose` returns +them for user acceptance. Omit the rule to disable discovery. +No rule accepts executable expressions, Python paths, or arbitrary imports. +Explicit manifest reconciliation executes the accepted rule and preserves +manual links and suppressions. See [deterministic discovery](source_manifest.md#deterministic-bibliography-discovery). + +Example declaration (inside a complete project type): + +```text +"source_organization": { + "roles": ["document", "bibliography", "supplementary"], + "default_role": "document", + "relation_types": { + "bibliography_for": {"behavior": "dependency"}, + "supplement_to": {"behavior": "dependency"} + }, + "automatic_rules": [ + { + "id": "latex_bibliography", + "detector": "latex_bibliography", + "relation": "bibliography_for", + "mode": "propose" + } + ] +} +``` + +| Bundled type | Default role | Additional roles | Declared discovery | +| --- | --- | --- | --- | +| `code` | `source` | test, documentation, example, configuration, data | None | +| `literature` | `document` | paper, supplementary, reference, bibliography, background | LaTeX bibliography (`apply`) | +| `writing` | `document` | draft, reference, bibliography, figure, supporting | LaTeX bibliography (`apply`) | +| `reviewing` | `unassigned` | primary, supplementary, reference, bibliography, background, guidelines | LaTeX bibliography (`apply`) | +| `grounded_brainstorming` | `material` | paper, background, notes, data, supporting | None | +| `creative_brainstorming` | `material` | notes, background, data, supporting | None | + +Literature, writing and reviewing also declare `bibliography_for` and +`supplement_to` as dependencies. Reviewing never infers a primary role. +The parsed `ProjectType.source_organization` contains immutable tuples of +roles, `RelationType` and `DiscoveryRule` records. Inspect available relation +IDs with `.relation_ids`. `kilin.parse_source_organization()` validates a +standalone declaration using the same parser. + +## Intent objects + +Every intent requires a nonblank `description` for the router. An ordinary +(non-tool) intent also requires a nonblank `system_prompt`. A tool writes its +own answer, so that prompt may be omitted for tool-backed intents. + +| Field | Accepted values and defaults | +| --- | --- | +| `description` | Required nonblank text describing when to select this intent. | +| `system_prompt` | Instruction added to shared prompt; required for ordinary intents, optional text for a tool. | +| `answer_guidance` | Text or null, defaults to null (inherit). | +| `history.policy` | `none`, `recent`, or `relevant` (default). | +| `shortcuts` | List of regular expressions matching entire questions; skips model routing. | +| `cues` | List of patterns searched in a question after history routing. | +| `requires` | List of patterns, at least one of which a question must match for this route to stand. | +| `thinking` | Boolean or null (default null, inherit); tools require null or omission. | +| `memory.indexing` | `automatic` (default), `explicit`, or `never`. | +| `memory.read` | Boolean, defaults to true. | +| `retrieval` | Object described below. | +| `tool` | Object described below; omit for ordinary answering. | + +Patterns are compiled case-insensitively. Missing pattern lists are empty. +Write distinguishing descriptions and narrowly scoped patterns; do not make +all intents match the same broad question. + +### Retrieval object + +| Field | Accepted values and defaults | +| --- | --- | +| `mode` | `search` (default without tool), `document`, `reuse`, or `none` (required/default with tool). | +| `strategy` | `hybrid` (default) or `source_first`. | +| `include_related_evidence` | Boolean, false by default; related earlier conversation evidence. | +| `related_evidence` | Ordinary intent only: array of unique declared relation IDs for linked original evidence; default empty. | +| `related_lookup` | Ordinary intent only: array of unique declared relation IDs for linked lookup material; default empty. | +| `prefer_source_code` | Boolean, false by default. | +| `max_tokens` | Integer 1000–200000; document-reading budget defaults to packaged `PROJECT_TYPES.DOCUMENT_MAX_TOKENS` (currently 30000). | +| `max_sources` | Integer 1–50; omitted defaults to 3 in source-first search. | +| `passages_per_source` | Integer 1–10; omitted defaults to 1. | +| `max_passages` | Integer 1–200; defaults to 8. | +| `evidence_tokens` | Integer 1000–200000; defaults to 5000. | +| `coverage` | `bounded` (default) or `exhaustive`. | +| `grouped` | Boolean, false by default; true selects logical-group source-first retrieval. | + +The five source-first fields (`max_sources` through `coverage`) may be +specified only for non-tool intents with mode `search` and strategy +`source_first`. Coverage describes the retrieval objective, not proof that +all sources were read; budgets still apply. `grouped: true` is allowed only +for an ordinary `source_first` search intent; tool-backed intents must omit +the field. Grouped source quotas count logical anchors and passage quotas +apply to groups, with shared physical passages counted once against global +passage and estimated-token limits. The mode `document` reads one +selected file/function subject to the budget, `reuse` uses related earlier +evidence, and `none` requests no ordinary evidence. See the +[retrieval pipeline](retrieval_pipeline.md) for precise behavior. + +The two relation policies are independent of `include_related_evidence` and +comparison semantics. Both arrays must refer to the enclosing type's +relation vocabulary; unknown IDs, duplicates and non-array values are errors. +Tool-backed intents must omit both fields, even if empty; their policies are +tool-owned. `reference_check` and `suggest_reference` declare role and +relation settings in their `tool` objects. The registered tool validates +identifier syntax and its optional policy callback is validated against +the type vocabulary; project overrides additionally use the accepted +manifest vocabulary. Ordinary intents may retain declarations when retrieval is +`none`, but no retrieval is enabled by these fields. Literature, writing and +reviewing ordinary search intents declare `supplement_to` for evidence and +`bibliography_for` for lookup. Other intents default to empty arrays. These +are validated configuration; ordinary search now expands the allowed +one-hop evidence and lookup members before ranking. For example, a restricted +manuscript search with `related_evidence: ["supplement_to"]` can rank its +selected supplement, but `related_lookup: ["bibliography_for"]` does not +make bibliography text scientific support. A physical lookup view may use +lookup members instead. `project_behavior.json` may override these ordinary +intent arrays +but cannot edit the vocabulary. The core source-view resolver validates a +`SourcePolicy` using these relation IDs against the project's **accepted** +vocabulary; an installed type update does not silently import new relation +semantics. Unknown IDs require explicit adoption or revised policy. See +[source views](retrieval_pipeline.md#source-views-and-operation-snapshots). + +### Tool object + +`tool` must be a JSON object with `name` (the registered ID) and optional +settings fields defined by that tool's `parse_settings`. The tool replaces +ordinary retrieval and answering; set `retrieval.mode` to `none` or omit it. +Do not set a per-intent `thinking` override; tool-owned `MODEL_CALLS` and +session generation policy govern calls. Unknown tool-specific fields fail +when the tool parser runs. A name is never a Python module path. The Python +package must be compatible and registered; a JSON definition alone cannot +install it. + +## Complete example and validation + +This standalone project type uses the bundled inventory tool, so no additional +Python package is required. The source selection and retrieval instructions +are still necessary project-wide fields even for a deterministic tool. + +```json +{ + "version": "0.1.0", + "schema_version": 1, + "source_organization": { + "roles": ["notes"], + "default_role": "notes" + }, + "display_name": "Text inventory", + "description": "Inventory a collection of plain text notes.", + "extensions": [".txt", ".md"], + "max_file_bytes": 2000000, + "retrieval_instruction": "Find relevant notes.", + "system_prompt": "Describe the selected project files.", + "capabilities": {"code_graph": false}, + "history": {"exclude_disliked_answers": true}, + "conversation_memory": { + "enabled": false, + "questions": "all", + "answers": "selected", + "max_hits": 4, + "max_tokens": 2000 + }, + "default_intent": "inventory", + "intents": { + "inventory": { + "description": "List selected files.", + "history": {"policy": "none"}, + "retrieval": {"mode": "none"}, + "tool": {"name": "project_inventory", "max_listed": 20} + } + }, + "suggestions": ["List my project files."] +} +``` + +Save as `text-inventory.json` outside the active plugin store. Validate it +without activating any candidate code: + +```python +from pathlib import Path +from kilin import plugins + +path = Path("text-inventory.json") +structural = plugins.validate_project_type(path, bind_tools=False) +assert structural.error is None, structural.error +print(structural.required_tools, structural.bound) +# Resolve references to already installed, trusted tools. +bound = plugins.validate_project_type(path) +assert bound.available, bound.error +``` + +Structural validation checks the JSON, field values and tool-reference shape +but not availability or tool-specific settings. Full validation resolves +registered tools and runs their settings parsers, and can initialize the +runtime catalog. `kilin.project_type.load_project_types(directory)` is the +strict explicit-folder loader, not a registration or installation API. +Use `plugins.install_project_type(path)` or **Settings > Plugins** to queue +a new definition. The next eligible process startup publishes pending changes +before discovery. An unresolved but structurally valid installed type is +listed as unavailable, with the reason; it does not hide unrelated projects. + +The runtime catalog captures the raw definition and parsed configuration; +`kilin.project_type_catalog()` retains diagnostics, `kilin.project_type_ids()` +returns usable IDs, and `kilin.project_type_raw(type_id)` returns a defensive +copy of an available definition. `plugins.list_project_types()` also reports +conflicting candidates. See the [tool API](PLUGIN_API.md) for trust, storage, +validation, lifecycle and trace identity. + +## Settings precedence and updates + +A new workspace inherits the selected type's source and generation defaults, +then explicit creation settings. Saved profiles take precedence on reopen. +Workspace behavior overrides are checked against the captured installed type; +they do not rename intents or change their tool bindings. Tool defaults are +owned by the tool parser, its intent's `tool` fields override them, and saved +workspace tool settings override the intent. Internal tool-owned model policy +is separate. See [configuration](configuration.md) for the full settings +precedence. Updating a definition does not rewrite profiles, source files, +workspace templates or historic trace identities. Changing IDs or required +settings can make existing workspaces unavailable; keep stable IDs and test +updates on disposable workspaces before staging them. + +## Related + +[Plugin authoring](PLUGIN_AUTHORING.md), [Python tool API](PLUGIN_API.md), +[Configuration](configuration.md), [Extension interfaces](extension_interfaces.md). diff --git a/docs/PROJECT_TYPE_SCHEMA_CHANGELOG.md b/docs/PROJECT_TYPE_SCHEMA_CHANGELOG.md new file mode 100644 index 00000000..22cdc777 --- /dev/null +++ b/docs/PROJECT_TYPE_SCHEMA_CHANGELOG.md @@ -0,0 +1,5 @@ +# Project-type schema changelog + +This changelog records changes to the project-type JSON schema contract. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/docs/README.md b/docs/README.md index ee5ad172..56fd8c09 100644 --- a/docs/README.md +++ b/docs/README.md @@ -20,10 +20,11 @@ replace one another. The supported environment is defined in | --- | --- | --- | | Understand the system | [Architecture](architecture.md) | [Module map](module_map.md), then the owning subsystem and source | | Explain an answer | [Answering](answering_pipeline.md) | [Retrieval](retrieval_pipeline.md), [Traces](trace_recording.md) | -| Import/update local data | [Source pipeline](source_pipeline.md) | [Workspaces](project_workspaces.md), [index identity](retrieval_pipeline.md#index-persistence-and-identity) | +| Import/update local data | [Accepted source organization](source_manifest.md) | Accepted file roles, relations, settings, source-root binding, reconciliation and conflict-safe editing. | +| 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 @@ -36,12 +37,16 @@ responsibility, not authority over the source implementation. | --- | --- | | [Architecture](architecture.md) | Overall component boundaries, core/GUI dependency direction and state lifetimes. | | [Project workspaces](project_workspaces.md) | Creation, source-directory convention, resources, explicit updates and filesystem failure residue. | +| [Accepted source organization](source_manifest.md) | Accepted graph, role and relation declarations, lifecycle, explicit initialization, preview/apply and revision ownership. | | [Source pipeline](source_pipeline.md) | Selection versus reading, source coordinates, extraction and chunk identity. | | [Retrieval pipeline](retrieval_pipeline.md) | Ranking/fusion, context expansion, persisted index identity and empty/incremental indexes. | | [Answering pipeline](answering_pipeline.md) | Routing/history, answer production, completion/recovery, partial results and turn commitment. | | [Model management](model_management.md) | Backends, loading/cache/network behavior, chat/embedding sessions and model-specific limitations. | | [Configuration](configuration.md) | Setting ownership, precedence, canonical identifiers and project overrides. | | [Packaged defaults](package_defaults.md) | Validated core JSON keys, values, bounds and effects; not per-tool defaults. | +| [Plugin API](PLUGIN_API.md) | Versioned tool-authoring contract, supported imports, and registry initialization. | +| [Project-type JSON schema](PROJECT_TYPE_SCHEMA.md) | Required and optional fields, versioning, intent and tool binding, validation. | +| [Plugin authoring](PLUGIN_AUTHORING.md) | User extension workflow, LLM-assisted development, tested examples and lifecycle management. | | [Tool packages](tool_packages.md) | Package boundaries, safe generated outputs and internal/final model-call policy. | | [Extension interfaces](extension_interfaces.md) | Steps and interface obligations for adding types, readers, tools and other components. | | [GUI architecture](gui_architecture.md) | Desktop process/lifecycle integration and presentation ownership. | @@ -49,11 +54,17 @@ responsibility, not authority over the source implementation. | [Conversation ownership](conversation_ownership.md) | Writer leases, atomic files, switching, archival and cleanup guarantees. | | [Conversation memory](conversation_memory.md) | Turn UUIDs, authoritative feedback, active branch origins, independent indexing and separate prompt provenance. | | [Trace recording](trace_recording.md) | Diagnostic activation/content, trace metadata, event versus checkpoint failure policy. | +| [Trace architecture](trace_architecture.md) | Shared project numbering, trace ownership and chronological event identity. | +| [System testing](system_testing.md) | Reference preparation, recording validation, chronological reconstruction, independent replay, and quantitative comparison. | | [Security](security.md) | Trust boundaries, sensitive data, deployment responsibilities and explicit non-guarantees. | | [Performance](performance.md) | Trace-derived measurements, reproducible workloads and limits of timing evidence. | +| [Versioning](versioning.md) | Authoritative versioning policy, compatibility, changelogs and release obligations for humans and AI. | +| [Tool API changelog](PLUGIN_API_CHANGELOG.md) | Tool API generation history. | +| [Project-type schema changelog](PROJECT_TYPE_SCHEMA_CHANGELOG.md) | Project-type schema generation history. | +| [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. | @@ -75,10 +86,11 @@ still applies after a focused subset passes. | --- | --- | --- | --- | | Create/open projects or change their layout | [Workspaces](project_workspaces.md) | Reservation, profile publication, resources, GUI activation and saved-layout compatibility. | [Creation](../tests/kilin/test_project__creation.py), [transactions](../tests/kilin/test__project_transactions.py), [GUI creation](../tests/kilin/gui/test_engine__creation.py) | | Import, synchronize or remove sources | [Source pipeline](source_pipeline.md), [workspace updates](project_workspaces.md#explicit-imports-and-source-selection) | Selection, provenance/version records, original-file protection and explicit index refresh. | [Source management](../tests/kilin/test_workspace__source_management.py), [source changes](../tests/kilin/test_workspace__source_changes.py) | +| Change accepted source roles, links or settings | [Source manifest](source_manifest.md) | Selected inventory, graph validation, creation journal, revision/content ownership and replay boundaries. | [Manifest](../tests/kilin/test_source_manifest.py), [recording validation](../tests/kilin/system_testing/test_experiment.py) | | Add a reader or change chunk boundaries | [Source extensions](extension_interfaces.md#source-readerextractor-contract) | Dispatch, exact text/coordinates, citation previews, chunk IDs and cache reuse. | [Readers](../tests/kilin/sources/), [chunking](../tests/kilin/test_chunking.py), [index provenance](../tests/kilin/test_rag__index_provenance.py) | | Change retrieval, expansion or saved indexes | [Retrieval](retrieval_pipeline.md) | All channel depths/order, model identity, evidence labels, checksum and empty-state behavior. | [Retrieval](../tests/kilin/retrievals/), [RAG corrections](../tests/kilin/test_rag__retrieval_corrections.py), [empty projects](../tests/kilin/test_rag__empty_workspace.py) | | Change answer completion or tool model calls | [Answering](answering_pipeline.md), [tool policy](tool_packages.md#generation-settings-for-tools) | Side-call isolation, thinking/budgets, retries, partial status, usage and committed history. | [Completion](../tests/kilin/test_rag__completion.py), [recovery](../tests/kilin/test_rag__tool_recovery.py), [budgets](../tests/kilin/test_rag__tool_budgets.py) | -| Add a project type, tool or template | [Extensions](extension_interfaces.md) | Parser/registry, intents, settings/resources, package data, local README and module map. | [Type contracts](../tests/kilin/test__project_type_contract.py), [tool boundaries](../tests/kilin/tools/test__architecture.py), [resources](../tests/kilin/tools/test__resources.py) | +| Add a project type, tool or template | [Extensions](extension_interfaces.md), [Plugin API](PLUGIN_API.md) | Parser/registry, intents, settings/resources, package data, local README and module map. | [Type contracts](../tests/kilin/test__project_type_contract.py), [tool boundaries](../tests/kilin/tools/test__architecture.py), [resources](../tests/kilin/tools/test__resources.py) | | Change model loading or generation controls | [Models](model_management.md) | Backend/tokenizer, history, completion metadata, download policy, cleanup and saved configuration. | [Runtime](../tests/kilin/test_runtime.py), [chat units](../tests/kilin/test_chat__unit.py), [embedding units](../tests/kilin/test_embeddings__unit.py) | | Change defaults or saved settings | [Configuration](configuration.md) | Owning JSON/validator, initialization versus reopening, GUI controls and cache invalidation. | [Core defaults](../tests/kilin/test_defaults.py), [tool settings](../tests/kilin/test_tool_settings.py), [documented values](../tests/setup/test__documentation_assets.py) | | Change conversation fields or writer ownership | [Conversation ownership](conversation_ownership.md), [conversation memory](conversation_memory.md), [traces](trace_recording.md) | Store/logger/RAG/GUI writers, old-state fixtures, lock cleanup and trace consumers. | [Format](../tests/kilin/test_conversation_format.py), [ownership](../tests/kilin/test_conversation_ownership.py), [lifecycle](../tests/kilin/test__conversation_lifecycle.py) | diff --git a/docs/TRACE_FORMAT_CHANGELOG.md b/docs/TRACE_FORMAT_CHANGELOG.md new file mode 100644 index 00000000..39e12203 --- /dev/null +++ b/docs/TRACE_FORMAT_CHANGELOG.md @@ -0,0 +1,5 @@ +# Trace-format changelog + +This changelog records changes to the trace-format contract. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/docs/answering_pipeline.md b/docs/answering_pipeline.md index 8a71ee1b..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 @@ -129,14 +136,27 @@ to reconstruct missing activity data. ## Intent routing and fallback `answering.route_question()` takes the question, project type and compact -representations of prior turns. First, a configured shortcut pattern can -match without an additional LLM call. Otherwise a router model produces a +representations of prior turns. If the active conversation has no eligible +turn (including when all earlier turns are small talk or excluded by +feedback), intents with `reuse` retrieval or a tool declaring +`follows_up=True` are unavailable. They are omitted from the router prompt +and cannot be selected through shortcuts, wording cues, repeated-question +choices, or a retry or fallback. This restriction does not depend on +whether other conversations in the project contain saved answers. Tools +with only `follows_up_when` remain available: for example, a line rewrite +can operate directly on a named document without a previous writing check. +An eligible configured shortcut pattern can match without an additional +LLM call. Otherwise a router model produces a structured decision (`RouteDecision`) with intent, standalone/follow-up judgment and related prior-turn identifiers. Parsed IDs are checked against available history and additional reference or distinctive-term heuristics; not every related ID proposed by the model is automatically accepted. Invalid or unusable router output falls back to the project's default -intent rather than interpreting an arbitrary tool name. +intent when eligible, rather than interpreting an arbitrary tool name. +If the default is unavailable, a suitable allowed ordinary intent is used; +if no valid choice or safe fallback exists, routing fails explicitly. +The eligibility check does not require earlier source evidence: individual +follow-up tools still validate whether the earlier result is usable. A question with the same normalized wording as an earlier question is recognized as a repeat; only case, Unicode compatibility, whitespace and @@ -156,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, @@ -174,6 +194,13 @@ turns compete for the same final evidence budget. An explicit request for all sources triggers exhaustive source-coverage reporting; when a source cannot be represented, a deterministic notice is appended **after** the model reply. This reports source representation, not full-document review. +When the selected source-first intent opts into `grouped`, the source quota +counts logical anchors, original anchor passages receive priority, and +shared physical evidence is charged only once. The answer prompt lists +selected logical groups with their original physical citation numbers. +Coverage distinguishes evidence-bearing groups from represented anchors; +a supplement-only match cannot satisfy a request for a read manuscript. +Lookup-only members do not provide scientific supporting evidence. Details and example per-intent JSON are in [Retrieval pipeline](retrieval_pipeline.md#per-intent-source-first-configuration). Tool-backed intents keep their separately validated tool settings. @@ -188,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, @@ -208,7 +236,7 @@ decision. `select_history()` applies the intent's policy: After the router call, two kinds of wording rules from the project type can change its intent; the router's related turns and standalone judgement are kept. An intent's `cues` are patterns searched in the -question: the first intent, in the project type's order, whose cue +question: the first eligible intent, in the project type's order, whose cue matches replaces the router's choice ("give me an overview of the Smith paper" is `paper_overview`, "how does X differ from Y" is `compare_sources`). Without a cue, the wording can rule out the router's @@ -222,9 +250,10 @@ that it found no earlier answer. A question sent to such a tool always relates to an earlier turn (the last one that is not small talk, when the router names none); a tool with `follows_up_when` (`writing_check`, for "rephrase line 75") does so only for the questions it accepts, and is not -ruled out for naming a file. The router is then asked once more with -the ruled-out intents left out of the list; when that call fails or still -names one of them, the default intent is used. +ruled out for naming a file. When a router reply selects an unavailable +or ruled-out intent, the router is asked once more with those intents +left out of the list. If that call fails or still names one of them, an +allowed ordinary fallback is used, preferring the default. Before routing, tools with a `routing` callback add cues and descriptions built from the project's own files (`with_project_routing`): @@ -268,7 +297,9 @@ historical assistant assertions from current documentary evidence. Search hits h budget. Completed turns retain only navigational identities in `parameters.memory_references`, not copies of remembered text or summaries. The GUI requests the current question or answer summary from the origin -conversation trace when the memory note is expanded. The trace operation +conversation trace when the memory note is expanded. Model-facing memory +headers use local message and turn labels, never regenerated UUIDs or +execution timestamps. The trace operation retains the complete router-generated answer summary independently of the bounded, saved routing representation. Neither memory notes nor generated summaries are independent source `Evidence`. @@ -296,8 +327,21 @@ question remains the question to answer even when search text differs. `RAGSession` then chooses among `search`, `document`, `reuse` and `none`. The retrieved evidence supplies exact text and source coordinates, with citation numbers referenced by the answer. A named-document operation may -use extra document-scoped ranking or a full-document token budget; its -semantics cannot be emulated reliably by global top-k alone. +use a restricted [source view](retrieval_pipeline.md#source-views-and-operation-snapshots) +or a full-document token budget; its semantics cannot be emulated reliably +by global top-k alone. The session resolves one immutable operation from the +accepted manifest and loaded index. Ordinary intent relation policies govern +which one-hop evidence and lookup members may participate. Every search +channel, card score and context-expansion step uses that membership. Named +comparison operands may be preferred rather than restricted; an empty +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. +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 @@ -339,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 @@ -362,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 @@ -434,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. @@ -447,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 @@ -457,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 704642fe..91dcff21 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5,11 +5,11 @@ KíLín is a local-first question-answering application and extensible Python framework for working with user-supplied code and literature. Project types are provided through validated JSON definitions. It provides a core API, -retrieval, locally executed model sessions, structured conversations, a set -of **registered built-in tools**, and an optional desktop interface. These -are implemented capabilities. Arbitrary plugin discovery, autonomous -multi-agent operation, secure code execution and distributed inference are -**not** established capabilities of this snapshot. +retrieval, locally executed model sessions, structured conversations, +registered distribution and trusted user tools, and an optional desktop +interface. Both extension categories support user-level installation and +restart-based activation. Autonomous multi-agent operation, sandboxed code +execution and distributed inference are not established capabilities. A major design invariant is that importing `kilin` does not construct a model or start Qt. Project creation, source ownership, indexing, retrieval, @@ -42,13 +42,17 @@ presentation state). Their lifetimes and owners must not be conflated. | API and entry points | `kilin/__init__.py` is the curated public facade; `cli.py` is the optional GUI launcher; `gui/__main__.py` launches the GUI directly. | | Project lifecycle | `project.py` validates `profile.ini`, creates/opens workspaces; `project_layout.py` plans shared folders and tool resources. | | Workspace contents | `workspace.py` imports cumulative sources; `project_files.py` edits outputs/templates; `workspace_resources.py` validates packaged resource declarations. | +| Accepted source organization | `source_manifest.py` owns revisioned semantic roles and links; `source_organization.py` validates vocabulary; `source_views.py` resolves operation-specific membership against the selected physical generation. | | Selection and text | `repository.py` enforces scan policy and manifests; `sources/` supplies readers and provenance-bearing source units; `chunking.py` creates bounded chunks. | | 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 @@ -59,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 @@ -76,13 +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. Evidence and its provenance accompany - the model or tool answer; successful turns are checkpointed. + 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. 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). @@ -100,11 +115,16 @@ 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. [Project workspaces](project_workspaces.md) owns the differences -between their update operations. Imports do not modify source originals. +provenance. The root `source_manifest.json` separately owns accepted roles, +links, suppressions and organization settings; `indexes/index_source_state.json` +records derived physical identities. Semantic edits need no index rebuild. +[Project workspaces](project_workspaces.md) owns the differences between their +update operations, and [Accepted source organization](source_manifest.md) +owns the semantic contract. Imports do not modify source originals. A saved project's `profile.ini` takes precedence over new-project defaults. The desktop's immutable `gui/defaults.json` is combined with per-user @@ -123,10 +143,12 @@ See [Conversation ownership](conversation_ownership.md) and ## Dependency and extension rules - The core must be useful without importing Qt, WebEngine or a GUI module. -- Project types are declarative packaged JSON with validated intents; they - do **not** load arbitrary Python modules. -- Built-in tools register through the existing registry and use `ToolContext`; - tool packages own their defaults, documentation and optional resources. +- Project types are declarative JSON with validated intents; they select + registered tool IDs, not arbitrary Python modules. +- Distribution and user tools expose versioned `PLUGIN` descriptors and use + `ToolContext`. Packages own their defaults, documentation and optional + resources. User Python code is trusted, not sandboxed. See the + [authoring guide](PLUGIN_AUTHORING.md) and [schema](PROJECT_TYPE_SCHEMA.md). - Source extraction is delegated by suffix, retaining source references; adding a format does not mean its contents are automatically safe or indexable. diff --git a/docs/configuration.md b/docs/configuration.md index 9e6f5dd7..a22103cf 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -11,7 +11,7 @@ rewrite an existing project's configuration. | Layer | Source | Scope and owner | Mutability | | --- | --- | --- | --- | | Core packaged defaults | `kilin/kilin_defaults.json` | Initial models, project profile, chunking, retrieval, routing, scanner heuristics | Read-only packaged resource; loaded/validated by core | -| Project types | `kilin/project_types/.json` | Eligible sources, intents, prompts, retrieval and memory policies, optional new-project generation defaults | Packaged declarations; not editable user profiles | +| Project types | `kilin/project_types/.json` or user `plugins/project_types/.json` | Eligible sources, source-organization declarations, intents, prompts, retrieval and memory policies, optional new-project generation defaults | Distribution or user declarations; not workspace profiles | | Tool defaults | `kilin/tools//defaults.json` | Parameter defaults owned by each built-in tool | Packaged and validated by that tool | | GUI packaged defaults | `kilin/gui/defaults.json` | Appearance and initial GUI model/search preferences | Read-only application resource | | User GUI preferences | Per-user `preferences.json` | Sparse overrides of GUI defaults, e.g. appearance | Atomic user-owned write | @@ -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. Existing `global` and `intent` payloads -remain unchanged. 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 @@ -113,23 +111,59 @@ reading permissions for each intent. These controls use the core's validated editors and revision checks; the GUI does not own memory persistence. See [Conversation memory](conversation_memory.md) for their contracts. +### Source-organization declarations and intent policies + +A project type may declare its role vocabulary, default role, relation types +and automatic discovery rules in `source_organization`. The +[project-type schema](PROJECT_TYPE_SCHEMA.md#source-organization-declarations) +defines the six bundled defaults and validates user types by the same rules. +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. +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 +editor accepts these fields in the existing `intent` scope and validates the +merged type before saving. Empty arrays select no linked relations; omitted +configuration defaults to empty. The Intents GUI preserves these arrays from +its editor payload but does not expose dedicated controls for them. Edit them +through the core behavior editor for an existing project, or in the +project-type definition for inherited intent defaults. The source organization +GUI edits the accepted vocabulary and graph, not per-intent retrieval +policies. Tool-backed intents cannot set them. `include_related_evidence` +still means earlier conversation evidence. Ordinary retrieval uses the accepted relation vocabulary and +resolved source view; changing these arrays does not rebuild indexes or +grant new filesystem access. The global editor cannot edit +`source_organization`; actual accepted vocabulary and graph state belong to +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 uses larger evidence budgets for drafting, research, and verification; the two brainstorming types prioritize different behavior. Brainstorming (Creative) defaults to source-free ideation and searches when its -selected intent calls for evidence. Brainstorming (Grounded) searches +selected intent calls for evidence, including experiment design explicitly +based on a named source. Writing requests explicitly drafting or revising +from a named source use grounded writing; editing supplied prose alone +can remain source-free. Report routing distinguishes ordinary source +filenames containing "template" from report-format requests. +Brainstorming (Grounded) searches the indexed project sources for every substantive ideation intent. Code Repository uses hybrid search and the saved project-profile `retrieval_count` instead of these source-first limits. Larger evidence 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 @@ -215,10 +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 not a separate active `effort_levels.json` database. The GUI -still supports controlled migration of recognized older files on first use; -moving or deleting files outside that migration is not authorized. +`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. 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 @@ -288,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. @@ -307,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 @@ -318,9 +383,11 @@ changes. ## Project type JSON and intent precedence -The type loader reads `project_types/*.json` in filename order, uses each -filename stem as its type ID and caches validated records. An invalid -project type is an error, not silently skipped. The top-level object defines +The runtime catalog captures distribution and user JSON definitions, using +each filename stem as its type ID. Unavailable entries retain diagnostics; +the strict explicit-folder loader still raises on invalid definitions. +Distribution IDs take precedence over user conflicts. See the complete +[project-type JSON schema](PROJECT_TYPE_SCHEMA.md). The top-level object defines its display metadata, extensions, size limit, base prompts, retrieval instruction, capabilities, history defaults, optional generation defaults, default intent, intents, welcome prompts and suggestions. @@ -335,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 @@ -373,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 @@ -435,6 +516,12 @@ and related-turn evidence. `coverage` accepts `bounded` (default) or `exhaustive`; explicit requests about all sources demand exhaustive source coverage regardless of that default. Omitted sources cause a saved coverage record and, in exhaustive mode, a deterministic notice. +Set `grouped` to `true` to count logical anchors instead of physical files +for the source quota and apply the per-source target to each group. The +global passage and estimated-token bounds still count original physical +evidence once. Grouping is off by default and can be enabled only for +ordinary source-first search. In the intent editor it appears as +**Logical document groups**. These settings belong to the **selected effective intent**, not the answering model's context-token setting or a tool's internal batch @@ -442,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 @@ -484,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` @@ -499,14 +586,14 @@ and [Trace recording](trace_recording.md). `ProjectTypeId` is an open string alias, not a closed enum. A validated `ProjectType` has an `id`; an individual `ProjectProfile` has a `type_id`. -`kilin.PROJECT_TYPE_IDS` contains all packaged IDs in filename order. -The JSON filename stem is the type ID: applications use the IDs returned -by the registry, rather than one Python constant per packaged type. Any -nonempty collection of valid packaged definitions is supported. An unknown -ID or an empty or invalid registry is an error. Definitions are cached: -restart after edits. 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. +`kilin.project_type_ids()` returns available distribution and user IDs; +`kilin.project_type_catalog()` retains unavailable definitions and reasons. +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. Use the identifiers `"code"` and `"literature"` for those specific +project types, or query `kilin.project_type_ids()` for generic selection. The current representations are: @@ -519,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 @@ -542,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 @@ -558,12 +647,11 @@ location for conversations, workspaces or preferences. Documents may be synchronized by iCloud, OneDrive or another external service; users needing strictly local project storage should choose a non-synchronized path. -If the previous installed-app `workspaces/` data directory contains project -profiles, GUI setup offers to reuse that folder. Choosing it records a -folder preference without moving or rewriting any project files. Otherwise -KíLín keeps the proposed Documents folder. An existing confirmed choice or -environment override is never silently replaced by legacy detection. See -[GUI architecture](gui_architecture.md) and [GUI README](../kilin/gui/README.md). +Choose any existing projects folder explicitly using Browse. KíLín does +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). ### Saved project settings take precedence @@ -609,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 @@ -657,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 074c05b2..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 @@ -212,8 +239,10 @@ The answering prompt uses **independent memory and source sections**: - **Project source evidence:** Numbered source-file excerpts, unchanged citation identifiers and evidence-token budget. - **Conversation memory:** Earlier quoted messages labeled `Memory M1`, etc., - with conversation/turn identity, role and UTC timestamp. These are - navigational references, **not source citations**. + with their role and prompt-local turn label (`Turn T1`, etc.). Messages + from the same saved turn share a turn label. Durable UUIDs, conversation + IDs, timestamps and origins stay in KíLín metadata, not the model prompt. + Memory labels are navigational references, **not source citations**. - **Current chat history:** Recent/relevant saved turns, filtered according to the project's disliked-answer context policy. @@ -223,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 @@ -233,14 +262,23 @@ with no lexical overlap are suppressed unless their semantic score clearly exceeds the anchor's. These fixed thresholds are deterministic heuristics, not a calibrated probability of relevance; they need validation with the researcher's local embedding model and representative conversations. They do -not modify primary-source ranking or citations. +not modify primary-source ranking or citations. Relevance ties use saved +branch-local turn positions and eligible content/priority rather than raw +UUIDs or execution timestamps. Truly indistinguishable occurrences may +resolve to different navigational origins, without changing model context. 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 @@ -257,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 @@ -271,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 @@ -315,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 @@ -352,9 +400,24 @@ message text. No memory activity is emitted when indexing/retrieval is disabled for the current project or intent. These counts are separate from scientific source-reference counts. +Explicit feedback and exclusion commands record requested and committed +revisions and rating state in the project trace. Manual index synchronization +records its result in the project trace; automatic synchronization remains +correlated to the active answer. The synchronization diagnostics identify +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 @@ -364,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 3aca34aa..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,19 +144,22 @@ 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 | Component | Who holds the lock? | When is it released? | | --- | --- | --- | -| `TraceLogger` | Its own `ConversationFileLock` | `close()`, including exceptions during the final write | +| Conversation `TraceLogger` | Its own `ConversationFileLock` | `close()`, including exceptions during the final write | | `RAGSession` with an owned trace | The owned trace logger | Session close or failed initialization | | `RAGSession` with a caller-owned trace | The caller's trace logger | The caller must close the logger | | `RAGSession` with tracing disabled | An independent session lock | Session close, successful switch away, or failed initialization | | `ConversationStore` editing an inactive conversation | A short-lived lock | The operation returns or raises | | `ConversationStore` editing the active conversation | A borrowed owner from RAG or the GUI logger | The originating owner releases it | +Shared project traces and the sequence counter use short write leases, +not conversation-lifetime ownership. See +[Trace architecture](trace_architecture.md). + Passing an ownership token to a store operation does not transfer the lease. The store checks the token and never releases a borrowed lease. GUI metadata updates (`rename`, `touch`) and branch creation borrow the active owner; @@ -114,18 +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. The GUI 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 @@ -151,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 64aa2cf3..abbf19bd 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,5 +1,8 @@ # Development, tests, packaging and repository maintenance +The authoritative [versioning policy](versioning.md) defines version +ownership, compatibility, and contributor obligations. + ## Scope and supported environment This guide applies to developers working with the current KíLín codebase, @@ -17,10 +20,11 @@ matrix, how to inspect changes, and what maintainers should verify. ```text kilin/ # Python core and optional gui/ package - project_types/ # Validated packaged project type definitions + project_types/ # Validated distribution project type definitions sources/ # Format-specific text readers/extractors retrievals/ # Search, graph, index persistence - tools/ # Registered built-in tools and their defaults + tools/ # Distribution tool descriptors and resources + plugins/ # User discovery, validation and managed activation gui/ # Optional engine, Qt bridge and web UI tests/kilin/ # Mirrored core + gui/ + tool tests @@ -37,12 +41,14 @@ _si_article_/ # Paper work, benchmarks and source corpora sandbox/ # Local development workspaces; export empty ``` -The repository includes 19 numbered tutorial notebooks. They introduce +The repository includes 21 numbered tutorial notebooks. They introduce installation, model cache, generation, repository scanning, extraction, embeddings, semantic/lexical/code retrieval, indexes, routing, RAG sessions, -trace logging, project types, custom tools, and an end-to-end research -assistant capstone. Notebook examples are not a -substitute for production API tests and must not rely on changes to hidden +trace logging, project types, source organization, conversation memory, +custom tools, an end-to-end research assistant capstone, and LLM-assisted +plugin development. +Notebook examples are not a substitute for production API tests and must +not rely on changes to hidden per-user files. `assets/clean_repository.ipynb` supports a controlled clean source export. Within `_si_article_/`, benchmark sources are included but benchmark run workspaces and both code/literature corpus directories are @@ -116,6 +122,18 @@ These checks detect structural drift; they do not prove prose semantics or native GUI behavior. Review the implementation and focused runtime tests when changing a contract. +For source-organization changes, verify the complete path from project +creation and explicit imports through pending roles, preview/apply, scoped +retrieval and physical citations, trace validation and replay. Exercise a +shared dependent without merging its independent parents, bibliography +lookup without documentary promotion, no-op and stale previews, and +reopening without implicit adoption. The model-free [Tutorial 160](../tutorials/160_project_types.ipynb) +exercise is executed by the tutorial regression suite. The engine and +system-testing suites cover chronological command replay; native Qt smoke +tests should additionally check the Workspace editor, Settings entry, +pending attachments, cancellation and project switching. A passing +model-free test does not establish model quality or native GUI behavior. + ### Maintaining an integrated reference Choose the [primary contract](README.md#contract-ownership) before editing. @@ -266,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 | | --- | --- | --- | @@ -275,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 @@ -284,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. @@ -356,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 @@ -369,8 +400,8 @@ console. ### Public prerelease sequence -The first public beta is `0.1.0b1`, then `0.1.0rc1`, then stable `0.1.0`. -Use matching Git tags: `v0.1.0b1`, `v0.1.0rc1`, `v0.1.0`. If further +The first published beta is `0.1.0b1`; beta 2 is `0.1.0b2`, followed by +`0.1.0rc1` and stable `0.1.0`. Use matching immutable Git tags. If further beta or RC iterations are needed, increment their sequence numbers. Do not upload `0.1.0` to PyPI until it is the intended stable release. Public prereleases remain subject to the security and platform limits in @@ -380,7 +411,10 @@ generated PyPI description and all tag-pinned documentation URLs. 1. Prepare beta and RC versions on `develop`; prepare stable versions on `main` after merging the accepted release candidate. Update - `pyproject.toml`, `uv.lock` and `CITATION.cff` consistently. Keep + `pyproject.toml`, `uv.lock` and `CITATION.cff` consistently. Set the + citation release date only when the actual publication date is known. + Do not update unrelated locked dependencies for a version-only release. + Follow the [versioning policy](versioning.md#release-checklist). Keep repository-owned links relative in `README.md`; regenerate and commit `README.pypi.md` with: @@ -394,7 +428,9 @@ generated PyPI description and all tag-pinned documentation URLs. current artwork's redistribution rights before publication. 2. Run both complete test suites on Python 3.12, the formatting checks, documentation checks, and the package/installation CI workflows. - Check that the generated README matches before building. Build + Check `kilin --version`, `kilin --versions --json`, and the desktop + Versions section against the release manifest. Check that the generated + README matches before building. Build the distributions with `uv build`; review their contents and metadata. Install the wheel into a fresh Python 3.12 environment using `uv pip install "dist/kilin--py3-none-any.whl[app]"`, and open @@ -402,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 @@ -421,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. @@ -475,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 @@ -518,14 +569,19 @@ Clean source ZIP exports must also include the tracked root files PyPI distribution description. Keep their top-level selection enabled in `assets/clean_repository.ipynb`; see the [README publication contract](readme_publication.md). +The default selection also includes the Git-tracked root `CHANGELOG.md`, +which repository versioning checks expect to be present. When selected, +export rejects a missing or untracked changelog rather than omitting it. 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, @@ -568,6 +624,16 @@ disabled, and any embedding-vector opt-in. There is no selectable trace mode. Do not use arbitrary CI wall-clock thresholds as correctness tests. Further trace/retrieval optimization requires measurements and invariance checks. +## Plugin authoring acceptance + +The [authoring guide](PLUGIN_AUTHORING.md) and [example pack](../examples/plugins/README.md) +are the supported starting point for external plugins. Keep examples out of +runtime package discovery. Run `python examples/plugins/check_examples.py` +with the checkout installed and repeat with a freshly installed wheel. +The checker uses temporary stores, deterministic services and independent +processes. Run the full repository test suites and distribution/native CI +at the exact feature head; stacked branches may require manual dispatch. + ## Related [Architecture](architecture.md), diff --git a/docs/extension_interfaces.md b/docs/extension_interfaces.md index 477b146d..b3568b63 100644 --- a/docs/extension_interfaces.md +++ b/docs/extension_interfaces.md @@ -7,55 +7,114 @@ loading arbitrary Python code mentioned in a project JSON. A new reader, project type or registered tool must preserve provenance, settings and workspace ownership and must not require Qt in the core. This document explains the implemented extension points and where modification is needed; -there is no general-purpose runtime plugin discovery service in this -snapshot. +distribution and trusted user tool packages are discovered automatically +through their descriptors, and project types through JSON definitions. +See the [plugin API](PLUGIN_API.md#user-storage-discovery-and-validation) +for storage, trust, and validation. The headless +[management API](PLUGIN_API.md#managed-installation-and-deferred-activation) +stages installation, updates and removal until the next eligible runtime. | Extension | Registration / owner | Main invariant | | --- | --- | --- | -| Project type | `kilin/project_types/.json` read by `project_type.py` | Validate all intents, tools, sources and prompts before use. | +| Project type | Distribution and user `project_types/.json` | Validate all intents, tools, sources and prompts before use. | | New source format | `sources/extensions/sources_.py`, dispatched by `sources.py` | Return well-formed `SourceFile` / `SourceUnit` records with exact provenance. | | Code graph language | `retrievals/code_graph/extensions/` | Extract structural hints without executing source code. | -| Built-in tool | `tools//` plus `tools/_registry.py` | Validate settings; honor `ToolRequest`, `ToolContext`, `ToolResult`. | +| Tool plugin | Distribution and user `tools//__init__.py` exposing `PLUGIN` | Validate settings; honor `ToolRequest`, `ToolContext`, `ToolResult`. | | Tool workspace asset | Tool's `workspace_resources(settings)` and `project_layout.py` | Declare safe relative destinations, install in core, preserve user edits. | | Model backend | `chat.py`, `embeddings.py`, `runtime.py` | Maintain validated session, tokenizer and vector/generation contracts; not a JSON-only extension. | | Retrieval strategy | `retrievals/strategies/` and `rag.py` integration | Preserve chunk alignment, ranking and evidence coordinates; not dynamically registered today. | ## 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, rejects duplicate JSON keys, -and validates **all** type files on load. - -`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). - -The registry requires at least one valid definition, with no mandatory -type ID. `ProjectTypeId` is an unrestricted string alias and `ProjectType.id` -is the filename-derived identifier. The GUI takes its initial selection -from the first registry entry and derives labels and welcome content from -each definition. Adding a packaged type needs no built-in-specific branch -or public Python constant. -External directories accepted by `load_project_types(directory)` are for -explicit validation; they are not automatically registered or hot-loaded. - -A project type does not name the source folder: every new project uses +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. +It is parsed into immutable records before tool binding. Both generic +`attached_to` and `related_to` are always present. Ordinary intents can +separately declare `retrieval.related_evidence` and `retrieval.related_lookup`; +these are not conversation evidence or tool settings. See the +[source-organization schema](PROJECT_TYPE_SCHEMA.md#source-organization-declarations) +for defaults and validation. [Accepted source organization](source_manifest.md) +owns project-local assignments, links, settings and deterministic discovery +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 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 +mandatory type ID. `ProjectTypeId` is a string alias; IDs must start with a +lowercase letter, contain only lowercase letters, digits, hyphens or +underscores, and be at most 32 characters long. + +Use the core API to inspect the catalog: + +```python +import kilin + +for type_id, info in kilin.project_type_catalog().items(): + print(type_id, info.origin, info.version, info.schema_version, + info.available) + if not info.available: + print(info.error) +``` + +Each immutable information record includes its source path, origin, +required tool IDs (after successful structural validation), implementation +version, schema generation and diagnostic. `kilin.project_type_ids()` and +`load_project_types()` list +only available types. `kilin.project_type(type_id)` and +`kilin.project_type_raw(type_id)` return defensive copies; neither editing +those copies nor changing the original files affects the runtime snapshot. +Project-local behavior overrides use the same captured raw definition. +Restart to activate changes. `load_project_types(directory)` remains a +strict, separately cached validation operation: it rejects empty folders +and any invalid definition and does not register them. Clearing its cache +refreshes explicit validation, not the runtime catalog. Automatic discovery +loads distribution definitions first and then user definitions in filename +order. Distribution IDs take precedence. `kilin.plugins.list_project_types()` +also includes rejected duplicate candidates; `validate_project_type()` can +check a user JSON candidate without adding it to the runtime catalog. + +The GUI selects the first available type for new-project defaults. Saved +workspaces whose type is missing or unavailable remain listed with their +original type ID and diagnostic; neither automatic selection nor opening +substitutes another type. Opening such a workspace fails before models are +loaded, its files are modified, or the previous active session is released. +The `projects` event adds `available` (boolean) and `unavailable_reason` +(string or null) to each saved-project record. When no type is available, +`settings` returns `profile: null`, `project_types: []`, and a +`project_type_error` message rather than constructing a creation profile. +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 without modifying the saved workspace. + +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 @@ -87,7 +146,7 @@ this field omitted or null, because their model calls are tool-owned. The parser rejects explicit overrides on tools. See the complete [thinking policy and precedence](configuration.md#per-intent-thinking-policy). -The packaged project type is an inheritance baseline. Each project's +The captured distribution or user project type is an inheritance baseline. Each project's optional `project_behavior.json` can override shared prompts, router settings, history, retrieval and existing intent behavior without changing intent IDs or tool bindings. It also stores the optional `code_graph` and @@ -103,29 +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 -registered tool must provide `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 -and verified in wheel tests. See [configuration metadata](configuration.md#settings-information-explanations-not-configuration). +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 @@ -191,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, @@ -203,40 +274,45 @@ 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 -![Validated project intents resolve registered built-in tools, which consume ToolRequest and ToolContext and return ToolResult for checkpointing.](figures/tool-contract.svg) +![Validated project intents resolve registered distribution and user tools, which consume ToolRequest and ToolContext and return ToolResult for checkpointing.](figures/tool-contract.svg) *Figure: The tool registry, request/context contract, optional confirmation callbacks and answer persistence are explicitly owned interfaces.* The [standard tool layout](tool_packages.md#standard-tool-layout) specifies -the package, configuration and resource files. `tools/_registry.py` pairs a -canonical `TOOL_*` identifier with its parser, runner, optional `follows_up` -or `follows_up_when` behavior, optional `routing` callback and optional -`workspace_resources` callback. `routing(settings, project_root, others)` +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`, `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 report templates this way). Project-type JSON can select an existing entry, not load another implementation by string. -Implement an extension in this order: +For a user plugin, follow the [authoring guide](PLUGIN_AUTHORING.md) and +[public API](PLUGIN_API.md), rather than changing the distribution package. + +Implement a distribution extension in this order: 1. Create the package, validated settings/parser and `run()` implementation. Document every owned default and supported request in its README. 2. Reuse private shared services where semantics match; do not import an executable sibling tool to reuse its policy. -3. Register the parser/runner and optional resources, then select the tool - in an intended project-type intent. Registration and selection differ. +3. Export the descriptor as `PLUGIN` in the package initializer, then select + the tool in an intended project-type intent. Discovery is automatic; + registration and selection differ. 4. Add deterministic tests under `tests/kilin/tools//test_tool.py` for parsing, invalid inputs, results, registry selection and optional resource declarations. Shared helpers have their own `_shared/` tests. @@ -256,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: @@ -282,18 +362,18 @@ callback, so document the default policy and cost. | `project_inventory` | Summarize selected files and unsearchable source coverage. | [README](../kilin/tools/project_inventory/README.md) | | `scan_and_list` | Count and list literal mentions with source locations. | [README](../kilin/tools/scan_and_list/README.md) | | `batch_classify` | Classify many mentions in model-assisted batches. | [README](../kilin/tools/batch_classify/README.md) | -| `batch_review` | Read one document in parts and answer from notes. | [README](../kilin/tools/batch_review/README.md) | +| `batch_review` | Read one logical target in source-ordered parts and answer from notes. | [README](../kilin/tools/batch_review/README.md) | | `filter_results` | Filter items of an earlier answer against a follow-up. | [README](../kilin/tools/filter_results/README.md) | | `find_fact` | Find one fact or a complete set across a document/corpus. | [README](../kilin/tools/find_fact/README.md) | | `find_passages` | Locate relevant literal passages/sentences. | [README](../kilin/tools/find_passages/README.md) | -| `paper_overview` | Produce a structured overview of a paper. | [README](../kilin/tools/paper_overview/README.md) | -| `project_summary` | Write one report on every document of a project from a project template, with per-document entries assembled in code. | [README](../kilin/tools/project_summary/README.md) | +| `paper_overview` | Produce a bounded overview of an eligible paper and permitted evidence. | [README](../kilin/tools/paper_overview/README.md) | +| `project_summary` | Map eligible logical anchors under a project template; preserve physical evidence citations, aggregate excerpt budgets and member coverage. | [README](../kilin/tools/project_summary/README.md) | | `reference_check` | Check a paper's references against the project's files, find their citations, and judge each claim against the cited paper. | [README](../kilin/tools/reference_check/README.md) | | `suggest_reference` | Suggest papers for a statement from model-assessed passages; include checked quotations when available. | [README](../kilin/tools/suggest_reference/README.md) | | `writing_check` | Check a document's grammar and style paragraph by paragraph, with consistency checks in code; suggest changes and save the report. | [README](../kilin/tools/writing_check/README.md) | | `assistant_guide` | Answer "What can you do for me?" with one ready-to-send example question per kind of request, about the project's own files. | [README](../kilin/tools/assistant_guide/README.md) | | `show_source` | Display requested exact source context. | [README](../kilin/tools/show_source/README.md) | -| `generate_paper_summary` | Create template-driven reports and saved artifacts. | [README](../kilin/tools/generate_paper_summary/README.md) | +| `generate_paper_summary` | Create template-driven reports with original physical citation sources. | [README](../kilin/tools/generate_paper_summary/README.md) | These tools do not have identical output formats, costs or confirmation policies. Consult their own READMEs, `defaults.json` and tests before @@ -301,7 +381,8 @@ assuming reusable behavior. ## Workspace resources are declared, not blindly copied -Register `workspace_resources(settings)` when a tool needs packaged files. +Declare `workspace_resources(settings)` in the descriptor when a tool needs +packaged files. It returns `WorkspaceResource` declarations; the tool does not install them. The [resource contract](project_workspaces.md#tool-resource-contract) owns package containment, safe destinations, conflict detection and preservation @@ -337,6 +418,10 @@ The report-generation package has an additional `_report_template.py` and the template format, parser and report checks themselves are shared in `kilin/tools/_shared/report_templates.py`, which each report tool calls with its own limits (`TemplateRules`). +`kilin/tools/_shared/report_selection.py` discovers templates in their +owning report namespaces using those limits. It resolves qualified paths +and explicit scope, and reports ambiguous requests instead of silently +selecting a different report tool. The GUI offers PDF rendering through its optional `_report_pdf.py`; core tools should still function without Qt (Markdown output remains available). @@ -353,7 +438,7 @@ an index file format. ## Tests and review checklist -- Register explicitly; reject unknown tools/settings/intent references. +- Declare the plugin explicitly; reject unknown tools/settings/intent references. - Validate function return types and source provenance; handle malformed source/LLM output without hidden retries. - Keep model access, source reading and filesystem work in core services. @@ -361,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), @@ -374,6 +459,55 @@ checks, as described in [Source pipeline](source_pipeline.md#change-impact-and-v For optional GUI adapters, run supported-host Qt smoke tests separately. See [Development](development.md) for full verification. +## Desktop plugin management protocol + +The application-level Plugins panel uses the same local QWebChannel and +JSON-line engine transport as the [GUI protocol](gui_protocol.md). The +`ChatBridge.choosePluginPath(kind)` slot returns a native folder (`tool`) or +JSON (`project_type`) selection, or an empty string on cancellation. It does +not validate or execute code. `ChatBridge.managePlugins(request_json)` +forwards a JSON object in the engine command +`{"action": "plugin_management", "request": {...}}`. + +Each request contains a nonempty string `request_id` and `operation`. The +engine emits a `plugins` event with the same `request_id` and `operation`, +plus operation-specific fields below. The adapter does not require an open +project or load models, and errors do not close an active session. + +| Operation | Additional request fields | Successful reply | +| --- | --- | --- | +| `list` | None | `inventory` | +| `structure` | `kind`, absolute `path` | `validation` (structural only) | +| `validate` | `kind`, absolute `path`, `trusted: true` for Python | `validation` (runtime or bound) | +| `install` | `kind`, absolute `path`, `trusted: true` for Python | `change`, `inventory` | +| `update` | `kind`, `name`, absolute `path`, `trusted: true` for Python | `change`, `inventory` | +| `remove` | `kind`, `name` | `change`, `inventory` | +| `cancel` | `kind`, `name` | `canceled: true`, `inventory` | + +`kind` is `tool` or `project_type`. The update candidate's basename/stem must +match the selected ID. `trusted` must be the exact Boolean true for a Python +runtime check, installation or update; structure checks never execute the +candidate. The page asks for trust on each such operation and never reuses a +previous confirmation. JSON project types do not execute candidate Python. + +`inventory` contains `directory`, `tools`, `project_types`, `installed`, +`pending`, and `errors`. The arrays serialize the public core records with +string paths and explicit `available` for runtime records. `errors` maps each +unreadable inventory category to its diagnostic; independent categories remain +visible. A `validation` record includes the original diagnostic, warnings, +identity fields and either `runtime_checked` or `bound`. Structural success +is distinct from runtime availability. A `change` serializes the pending +operation, not an active installation. Operation failures include `error`; +mutations still return the actual inventory when possible. The page matches +responses to the outstanding request and never retries interrupted mutations +automatically. Pending changes require all runtimes using the directory to +close before the next eligible startup; no workspace manifest is introduced. + +The adapter lives in `kilin/gui/_plugin_management.py`; the isolated browser +controller in `kilin/gui/web/plugin_panel.js` renders all paths and diagnostics +as text. All installation and activation policy stays in `kilin.plugins`. +See [Plugin API](PLUGIN_API.md#desktop-plugin-management). + ## Related [Tool packages](tool_packages.md), diff --git a/docs/figures/tool-contract.svg b/docs/figures/tool-contract.svg index 75b1d57e..fc89df92 100644 --- a/docs/figures/tool-contract.svg +++ b/docs/figures/tool-contract.svg @@ -1,7 +1,7 @@ Registered tool execution contract -A validated project type provides an intent with a tool identifier. KíLín resolves it through the built-in registry, passes a ToolRequest and bounded ToolContext, and receives a ToolResult. Output and evidence join the normal turn checkpoint. +A validated project type provides an intent with a tool identifier. KíLín resolves it through the distribution and user tool registry, passes a ToolRequest and host-provided ToolContext, and receives a ToolResult. Output and evidence join the normal turn checkpoint. @@ -17,17 +17,17 @@ Registered tool execution contract -Validated project intent selects one registered, built-in package +Validated project intent selects one registered distribution or user package -ProjectType.IntentDeclarative project JSONValidated tool identifierRetrieval/history policyBuilt-in registrytools/_registry.pyResolve registered toolNo arbitrary plugin discoveryToolRequest + ToolContextRequest: question, intent, evidenceContext: models, files, callbacksValidates settings and capabilitiesTool packagetool.py + defaults.jsonREADME + templatesPrivate shared helpersToolResultAnswer, evidence, summary metadatastreamed flag prevents double outputNo implicit executable shellRAGSession / answer turnDeterministic citation-ID checkConversation checkpointGUI receives saved resultOptional interactionsPlan: continue / quick / cancelGUI supplies PDF callbackHeadless: tool defaultOptional PDF rendering uses a GUI callback; the core tool can save Markdown without Qt +ProjectType.IntentDeclarative project JSONValidated tool identifierRetrieval/history policyRuntime registrytools/_registry.pyResolve registered toolDistribution + user toolsToolRequest + ToolContextRequest: question, text, historyContext: models, files, callbacksValidated settings + host servicesTool packagePLUGIN descriptor + runnerDefaults + resourcesPackage-local codeToolResultAnswer, evidence, summary metadatastreamed flag prevents double outputJSON-compatible metadataRAGSession / answer turnDeterministic citation-ID checkConversation checkpointGUI receives saved resultOptional interactionsPlan: continue / quick / cancelGUI supplies PDF callbackHeadless: tool defaultOptional PDF rendering uses a GUI callback; the core tool can save Markdown without Qt -Tool packages are statically registered and own their defaults/resources · tool results remain part of one answer lifecycle +Trusted packages are discovered at catalog initialization and own their resources · tool results remain part of one answer lifecycle KíLín diff --git a/docs/gui_architecture.md b/docs/gui_architecture.md index 6d6ed326..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 @@ -42,6 +44,14 @@ the same recorder that saves and traces them. Browser phase timers estimate in-flight durations but do not produce activity labels. A character-by- character answer reveal does not necessarily reflect backend token timing. +The application banner reads `kilin.__version__` through the native bridge. +The application-wide Versions section uses the same core `version_info()` +inventory as the CLI and Python API, plus the active project's immutable +creation provenance. Requests are correlated and stale replies discarded. +The panel does not require an active project or a loaded model; its JSON +copy action includes the whole snapshot, including pending plugin identities +and diagnostics. See the [versioning policy](versioning.md#version-reporting). + ## Initial setup and project selection Startup retrieves model choices, backend readiness, project types and @@ -51,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. @@ -62,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 @@ -76,12 +89,17 @@ reported fields and which conflicts can be resumed. Filesystem reservation and rollback belong to [Project workspaces](project_workspaces.md), not Qt. Creation and profile/resource preparation finish before the engine closes -its current session or opens the new project's conversation and trace files. +its current session or opens the new project's conversation files. The +core opens the initial project trace after exclusive destination reservation, +and includes its files in creation rollback. 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 loads models and tracing; a model-load failure does not -delete the valid newly created project. +session activation opens the shared project and conversation sinks and loads +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. @@ -89,6 +107,50 @@ Adding/removing confirmed managed sources refreshes retrieval; editing outputs/templates through `project_files` does not. These are core operations with different ownership, even when adjacent in the interface. +### Accepted source organization + +The headless engine delegates role, relationship and discovery edits to the +core [source manifest](source_manifest.md). Its private adapter retains one +project-bound, single-use preview and serializes inspections and lifecycle +outcomes. It does not reimplement semantic validation or accept a replacement +manifest from a client. Successful semantic edits refresh session metadata +and saved suggestions without model generation or index rebuilding. Physical +source operations continue to refresh indexes; semantic reconciliation is +reported independently, even if a subsequent index build fails. + +The [semantic source command protocol](gui_protocol.md#semantic-source-commands) +is available independently of Qt. `ChatBridge.sourceOrganization()` forwards +requests unchanged; `web/source_organization_panel.js` owns only the transient +editor state. The Workspace action and Settings > General open the same modal. +The editor lists source-relative identities and accepted roles, including +pending and inactive assignments and retained versions. It stages ordered role, +resolution and relationship edits, or explicit declaration changes, then +renders the core's proposed differences before enabling Apply. Automatic +proposals can be staged as manual links, and disconnected automatic edges +remain suppressed unless explicitly restored. No physical tree mutation is +performed by the editor. + +The panel correlates replies by project, request ID and operation. Reopening, +engine recovery, physical lifecycle observations and draft changes invalidate +local preview state. Errors after a possible commit require fresh inspection +rather than an automatic retry. The Workspace tree's role labels and chain buttons are derived +only when the source-root binding exactly matches `sources/`. Active +relationships determine chain tooltips and dependency styling; associations +alone do not subdue files. Context-menu role changes and exact-edge +disconnects open focused previews, while linking supports either dependency +direction. The tree remains a physical inventory with its existing nested +paths, drag targets and file operations. Ordinary settings edit the same +prospective declaration as the advanced JSON fields. + +Lifecycle observations can arrive before physical indexing completes. The +browser accumulates newly pending roles for the reported project and consumes +that notification once on successful activation (`opened`), intersecting it +with the current pending paths. Existing pending files do not repeatedly +prompt on reopening. The compact dialog offers batch assignments and a full +editor; closing without applying retains pending status. A question with +pending attached files is returned to the composer with its imported paths +rather than sent automatically before the user reviews the roles. + ## Workspace ownership and paths `gui/_paths.py` resolves writable config/data locations independently of Qt; @@ -97,6 +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. 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 @@ -106,9 +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. Its controlled legacy import is not a -general project migration. 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 @@ -124,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 @@ -151,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 @@ -162,9 +234,11 @@ interrupted generation. The [Stop and restart protocol](gui_protocol.md#errors-s owns the command, terminal events, grace period and exact resume-ID behavior. The UI may show a remembered partial answer after Stop, but such display -state does not imply a committed `ConversationTurn`. Closing the desktop -window also terminates its owned child; ordinary closing is not a separate -multi-file transaction. The detailed process and error events belong to +state does not imply a committed `ConversationTurn`. Normal desktop window +closure or application exit ends the child's command input and allows the +engine to close its active project and trace loggers. An unresponsive child +is still killed after a bounded wait; closure is not a separate multi-file +transaction. The detailed process and error events belong to [GUI protocol](gui_protocol.md). ## PDF and native capabilities @@ -229,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 11cb2be6..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,37 +134,97 @@ 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`, `operation` default to `""`; other fields forwarded as keyword arguments | +| `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 | | `sync_memory_index` | `project` | Synchronize independent conversation memory and emit progress/result; do not rebuild primary-source indexes | +| `plugin_management` | `request` | Inspect, validate or stage changes to application-wide plugins; emits a correlated `plugins` event | +| `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. +`ChatBridge.choosePluginPath(kind)` selects a tool folder or project-type +JSON file without importing or installing it; cancellation returns an +empty string. `ChatBridge.managePlugins(request_json)` decodes the JSON +request and forwards it under the `request` key of `plugin_management`. +The engine does not open a project or load models for this command. + +The request must contain nonempty string `request_id` and `operation`. +Supported operations are `list`, `structure`, `validate`, `install`, +`update`, `remove` and `cancel`. Except for `list`, `kind` must be `tool` +or `project_type`. Candidate operations (`structure`, `validate`, `install`, +`update`) require an absolute `path`; updates also require the installed +`name` to match the candidate ID. `remove` and `cancel` require `name`. +Tool validation that executes Python, installation and updates require +`trusted: true`; structural checks do not execute candidate code. For a +project type, structural validation does not bind tools; full validation +checks the tool references. Install, update and removal stage changes for +activation on restart, subject to the runtime lease; cancel discards a +pending change. None of these operations hot-loads a plugin. + +The `plugins` response echoes `request_id` and `operation` (empty strings +if those fields were not accepted). It may contain `error`, `validation`, +`change` or `canceled: true`. Listing and mutation requests also return +`inventory`, including `directory`, `installed`, `pending`, runtime +`tools` and `project_types`, and per-inventory `errors`. Mutation requests +refresh that inventory even on failure. Candidate validation returns only +its diagnostic record and does not stage changes. The page correlates +responses by request ID and delegates rendering to `plugin_panel.js`. + +### Version reporting + +`ChatBridge.applicationVersion()` returns the executing application's +`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`, 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 +does not initialize models or execute tools. + ### Setting descriptions `settings_info` requires no project, model, or configuration arguments. @@ -170,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`, @@ -217,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. @@ -247,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- @@ -261,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 @@ -277,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. @@ -287,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 @@ -304,8 +395,8 @@ The page invokes the Qt slots rather than writing these dictionaries itself. The bridge decodes JSON-encoded arguments for source lists, generation settings, folder edits, and model settings. `openProject()` additionally rejects a decoded source selection that is not a list of strings, emitting -`error` directly through the Qt bridge. Other malformed slot arguments can -raise JSON decoding errors in Qt and do not become normal engine commands. +`error` directly through the Qt bridge. `sourceOrganization()` also emits a local `error` for malformed JSON. +Other malformed slot arguments can raise JSON decoding errors in Qt and do not become normal engine commands. Native file selection, `openWorkspaceFile`, appearance and backend preference changes (saved in `preferences.json` by Qt), drag/drop @@ -384,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 @@ -435,6 +527,84 @@ or focusing a prompt never authorizes it. This path is why the child must keep *one shared iterator* over stdin. +## Semantic source commands + +The headless engine accepts an ordinary sequential `source_organization` +action with a `request` object. This protocol is available to Python engine +clients and the browser editor through `ChatBridge.sourceOrganization()`; +the bridge forwards the JSON request without interpreting semantic edits. +All requests require the open project's absolute `project` path, positive integer +`request_id`, and an `operation`. A stale project or closed/busy session +cannot mutate another workspace. The response has event `source_organization` +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`, `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 | + +The preview's ordered edits are JSON objects with `kind`: +`role` requires `path` and `role` (null resets to the accepted default); +`relation` requires `source`, `target`, `relation` and `action` (`link`, +`unlink` or `restore_suppression`); `resolve` requires `path` and boolean +`restore`. All paths are source-relative; declarations and graph constraints +are validated by the core. The `organization` object follows the existing +[declaration schema](PROJECT_TYPE_SCHEMA.md#source-organization-declarations). +After inspection, submit a preview with the returned revision and digest. +An example element of its `edits` list is: + +```json +{"kind": "role", "path": "manuscript.md", "role": "primary"} +``` + +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; +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`, +`source_root`, `binding_matches`, `selected`, `active_files`, `current_files`, +`active_relations`, `inactive_files`, `inactive_relations`, `pending`, +`pending_roles` and `retained_versions`. Successful apply/initialize/reconcile +replies retain the committed revision/digest/state at the top level, and +include `changed`, `discovery` and the refreshed inspection. The metadata +refresh uses no model generation or physical index rebuild. `error` denotes +command or reconciliation failure; `error_type` and `conflict` identify +rejected commands. `refresh_error` or `trace_error` after a successful mutation +is not rollback; inspect again instead of resubmitting the mutation. A source +root or physical inventory change still requires the normal source/index +refresh before using the new physical sources. + +`opened` includes a `source_organization` object with `inspection` or an +inspection error. Physical creation, imports, sync, removal and index refresh +also emit `source_organization_lifecycle` events with `project`, `operation`, +`inspection`, `changed`, `added_files`, `new_pending_roles`, `discovery`, +`error` and `trace_error`. These describe the semantic outcome, not index +completion. Refresh reconciliation is reported before physical indexing; +a subsequent indexing failure does not undo the recorded semantic result. +The browser keeps one request and preview for the current open project. +Only replies matching project, request ID and operation may settle a command. +Project activation, lifecycle observations, draft edits and engine +interruption invalidate local preview authority. A lifecycle observation is +not an indexing or command-completion acknowledgement. On the corresponding +`opened`, the browser can prompt once for the union of newly pending paths +still pending in the fresh inspection. No semantic command or role change +is sent merely by displaying the dialog. Workspace shortcuts and ordinary +settings use the same existing preview/apply protocol. The editor shows +pending assignments, retained versions, inactive records, discovery proposals +and diagnostics. A preview displays canonical changes, and Apply sends only +the opaque token; the browser does not write the manifest. A rejected or +uncertain apply requires fresh inspection and is never retried automatically. + ## Frontend event inventory Events are JSON objects with an `event` string plus event-specific fields. @@ -447,13 +617,16 @@ 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, `legacy`: previous installed-app root with candidate profiles, or empty); `projects_folder_cancelled` (native Browse dialog dismissed); `projects_folder_failed` (`message`: unable to save or old folder no longer exists) | -| 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`) | -| Source/project | `projects` (`projects`); `preview` (`roots`); `opened` (`project`, `type_id`, `profile`, `turns`, 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 | +| 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 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` (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`) | @@ -468,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 @@ -481,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 @@ -585,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. @@ -631,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 @@ -642,8 +830,14 @@ partial visible stream. starts a replacement child. The page requests settings/readiness again and may attempt to reopen the former project. The diagnostic text is bounded; these events do not claim recovery of an interrupted operation. -- Closing the window terminates its child and does not issue an additional - graceful checkpoint transaction. +- Normal window closure or application exit closes the child's standard input + after already written commands, discards unsent commands, and suppresses + restarts. The engine's existing input-loop cleanup releases the active + project and closes its trace loggers. The window waits up to 3,000 ms for + this graceful exit; if the child is still running, it kills the child and + waits up to another 3,000 ms. Closing is not a request to commit an unfinished + answer or a multi-file transaction. A forced fallback can leave an + incomplete recording; Stop retains its separate behavior described above. ## Known limitations and deferred changes diff --git a/docs/model_management.md b/docs/model_management.md index acae562d..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 @@ -229,18 +240,19 @@ may require controlled evaluation. `RAGSession` normally holds an answering chat session, embedding session and possibly a separate router session. The core loads the selected router ID from the project's `[router]` section (separately for MLX and PyTorch). -When absent, it checks the legacy `effort_levels.json` router choice, then -uses the packaged `DEFAULT_ROUTER_MODEL_*` for the selected backend. An +When absent, it uses the packaged `DEFAULT_ROUTER_MODEL_*` for the selected +backend, unless an initial choice is supplied to `read_router_model()`. An explicit `RAGSession(router_model=...)` overrides that choice for the 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 46cfb88d..f1a13204 100644 --- a/docs/module_map.md +++ b/docs/module_map.md @@ -25,13 +25,19 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | [`kilin/__init__.py`](../kilin/__init__.py) | Expose the package-level KíLín API. | [Architecture](architecture.md) | [Core tests](../tests/kilin/) | | [`kilin/_model_completion.py`](../kilin/_model_completion.py) | Validate completed model replies and diagnose incomplete output. | [Answering pipeline](answering_pipeline.md) | [Completion tests](../tests/kilin/test__model_completion.py) | | [`kilin/_project_creation.py`](../kilin/_project_creation.py) | Reserve empty destinations and allocate independent projects exclusively. | [Project workspaces](project_workspaces.md) | [Creation tests](../tests/kilin/test_project__creation.py) | +| [`kilin/_latex_sources.py`](../kilin/_latex_sources.py) | Extract literal LaTeX bibliography names and resolve selected paths. | [Source manifest](source_manifest.md) | [Discovery tests](../tests/kilin/test__source_discovery.py) | +| [`kilin/_source_access.py`](../kilin/_source_access.py) | Resolve authorized source files within a project workspace. | [Source manifest](source_manifest.md) | [Discovery tests](../tests/kilin/test__source_discovery.py) | +| [`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/) | @@ -48,7 +54,9 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | [`kilin/gui/__main__.py`](../kilin/gui/__main__.py) | Start the optional GUI when invoked as ``python -m kilin.gui``. | [GUI architecture](gui_architecture.md) | [GUI tests](../tests/kilin/gui/) | | [`kilin/gui/_activation.py`](../kilin/gui/_activation.py) | Ask for KíLín's passkey before the desktop window first opens. | [GUI architecture](gui_architecture.md) | [GUI tests](../tests/kilin/gui/) | | [`kilin/gui/_paths.py`](../kilin/gui/_paths.py) | Resolve user-owned GUI data paths without importing Qt. | [GUI architecture](gui_architecture.md) | [GUI tests](../tests/kilin/gui/) | +| [`kilin/gui/_plugin_management.py`](../kilin/gui/_plugin_management.py) | Translate application-level plugin management into correlated protocol replies. | [GUI architecture](gui_architecture.md) | [Plugin protocol tests](../tests/kilin/gui/test_engine__plugins.py) | | [`kilin/gui/_report_pdf.py`](../kilin/gui/_report_pdf.py) | Render formatted report Markdown to PDF through optional Qt. | [GUI architecture](gui_architecture.md) | [GUI tests](../tests/kilin/gui/) | +| [`kilin/gui/_source_organization.py`](../kilin/gui/_source_organization.py) | Adapt transactional semantic source operations to the headless engine and recording protocol. | [GUI architecture](gui_architecture.md) | [Source-organization engine tests](../tests/kilin/gui/test_engine__source_organization.py) | | [`kilin/gui/app.py`](../kilin/gui/app.py) | Create and run KíLín's Qt desktop application. | [GUI architecture](gui_architecture.md) | [GUI tests](../tests/kilin/gui/) | | [`kilin/gui/engine.py`](../kilin/gui/engine.py) | Run repository and model operations behind the desktop interface. | [GUI architecture](gui_architecture.md) | [GUI tests](../tests/kilin/gui/) | | [`kilin/gui/model_catalog.py`](../kilin/gui/model_catalog.py) | Describe the model presets displayed by the desktop interface. | [GUI architecture](gui_architecture.md) | [GUI tests](../tests/kilin/gui/) | @@ -58,18 +66,29 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | [`kilin/huggingface.py`](../kilin/huggingface.py) | Inspect and reuse Hugging Face's model cache. | [Model management](model_management.md) | [Core tests](../tests/kilin/) | | [`kilin/model_defaults.py`](../kilin/model_defaults.py) | Define shared model purposes and default model identifiers. | [Model management](model_management.md) | [Core tests](../tests/kilin/) | | [`kilin/model_settings.py`](../kilin/model_settings.py) | Resolve and persist auxiliary model settings in the KíLín core. | [Model management](model_management.md) | [Core tests](../tests/kilin/test_model_settings.py) | +| [`kilin/plugins/__init__.py`](../kilin/plugins/__init__.py) | Expose headless plugin inspection, validation and management. | [Plugin API](PLUGIN_API.md) | [Plugin tests](../tests/kilin/test__user_plugins.py) | +| [`kilin/plugins/_discovery.py`](../kilin/plugins/_discovery.py) | Load trusted source packages and capture portable identity. | [Plugin API](PLUGIN_API.md) | [Plugin tests](../tests/kilin/test__user_plugins.py) | +| [`kilin/plugins/_lifecycle.py`](../kilin/plugins/_lifecycle.py) | Coordinate plugin activation and process-lifetime runtime leases. | [Plugin API](PLUGIN_API.md) | [Plugin management tests](../tests/kilin/test__plugin_management.py) | +| [`kilin/plugins/_management.py`](../kilin/plugins/_management.py) | Stage and recover validated user plugin changes before discovery. | [Plugin API](PLUGIN_API.md) | [Plugin management tests](../tests/kilin/test__plugin_management.py) | +| [`kilin/plugins/_paths.py`](../kilin/plugins/_paths.py) | Resolve and capture user-level plugin storage. | [Plugin API](PLUGIN_API.md) | [Plugin tests](../tests/kilin/test__user_plugins.py) | +| [`kilin/plugins/_validation.py`](../kilin/plugins/_validation.py) | Check candidate packages in a disposable interpreter. | [Plugin API](PLUGIN_API.md) | [Plugin tests](../tests/kilin/test__user_plugins.py) | +| [`kilin/plugins/_versioning.py`](../kilin/plugins/_versioning.py) | Validate independent semantic versions without initializing plugin catalogs. | [Plugin API](PLUGIN_API.md) | [Plugin versioning tests](../tests/kilin/test__plugin_versioning.py) | | [`kilin/project.py`](../kilin/project.py) | Create and open project workspaces independently of the GUI. | [Project workspaces](project_workspaces.md) | [Core tests](../tests/kilin/) | | [`kilin/project_files.py`](../kilin/project_files.py) | Manage project-owned outputs and templates independently of the GUI. | [Project workspaces](project_workspaces.md) | [Core tests](../tests/kilin/) | | [`kilin/settings_info.py`](../kilin/settings_info.py) | Read and validate shared and tool-owned setting descriptions without GUI dependencies. | [Configuration](configuration.md) | [Metadata tests](../tests/kilin/test_settings_info.py) | | [`kilin/project_behavior.py`](../kilin/project_behavior.py) | Resolve and edit validated project-local behavior. | [Configuration](configuration.md) | [Core tests](../tests/kilin/test_project_behavior.py) | | [`kilin/project_layout.py`](../kilin/project_layout.py) | Plan and materialize a project's core folders and tool resources. | [Project workspaces](project_workspaces.md) | [Core tests](../tests/kilin/) | | [`kilin/project_type.py`](../kilin/project_type.py) | Load project types from the JSON files in ``kilin/project_types/``. | [Configuration](configuration.md) | [Core tests](../tests/kilin/) | +| [`kilin/source_manifest.py`](../kilin/source_manifest.py) | Inspect, edit and reconcile accepted source organization. | [Source manifest](source_manifest.md) | [Manifest tests](../tests/kilin/test_source_manifest.py), [Lifecycle tests](../tests/kilin/test_source_manifest__lifecycle.py) | +| [`kilin/source_organization.py`](../kilin/source_organization.py) | Validate immutable role, relation and discovery declarations. | [Project-type schema](PROJECT_TYPE_SCHEMA.md#source-organization-declarations) | [Core tests](../tests/kilin/) | +| [`kilin/source_views.py`](../kilin/source_views.py) | Resolve immutable operation views of accepted source organization. | [Retrieval pipeline](retrieval_pipeline.md#source-views-and-operation-snapshots) | [Source-view tests](../tests/kilin/test_source_views.py) | | [`kilin/query_formats.py`](../kilin/query_formats.py) | Define the supported embedding-query formats and Qwen3 query formatter. | [Model management](model_management.md) | [Core tests](../tests/kilin/) | | [`kilin/question_suggestions.py`](../kilin/question_suggestions.py) | Write suggested questions about a project's own sources. | [Configuration](configuration.md) | [Core tests](../tests/kilin/test_question_suggestions.py) | | [`kilin/rag.py`](../kilin/rag.py) | Coordinate retrieval, chat generation, and resumable project conversations. | [Answering pipeline](answering_pipeline.md) | [Core tests](../tests/kilin/) | | [`kilin/repository.py`](../kilin/repository.py) | Select local source files and compare content manifests. | [Source pipeline](source_pipeline.md) | [Core tests](../tests/kilin/) | | [`kilin/repository_reason_codes.py`](../kilin/repository_reason_codes.py) | Load canonical repository-selection reasons shared with the GUI. | [Source pipeline](source_pipeline.md) | [Core tests](../tests/kilin/) | | [`kilin/retrievals/__init__.py`](../kilin/retrievals/__init__.py) | Expose KíLín's retrieval, code-graph, and index-persistence API. | [Retrieval pipeline](retrieval_pipeline.md) | [Retrieval tests](../tests/kilin/retrievals/) | +| [`kilin/retrievals/_scope.py`](../kilin/retrievals/_scope.py) | Project existing physical indexes and graph onto authorized operation members before ranking. | [Retrieval pipeline](retrieval_pipeline.md#enforcing-a-view-before-ranking) | [Source-scope tests](../tests/kilin/test_rag__source_scope.py) | | [`kilin/retrievals/code_graph/__init__.py`](../kilin/retrievals/code_graph/__init__.py) | Expose the code-graph records and builder. | [Retrieval pipeline](retrieval_pipeline.md) | [Retrieval tests](../tests/kilin/retrievals/) | | [`kilin/retrievals/code_graph/code_graph.py`](../kilin/retrievals/code_graph/code_graph.py) | Build a source-oriented graph of code entities and relationships. | [Retrieval pipeline](retrieval_pipeline.md) | [Retrieval tests](../tests/kilin/retrievals/) | | [`kilin/retrievals/code_graph/extensions/__init__.py`](../kilin/retrievals/code_graph/extensions/__init__.py) | Group language-specific code-relationship extraction hooks. | [Retrieval pipeline](retrieval_pipeline.md) | [Retrieval tests](../tests/kilin/retrievals/) | @@ -105,6 +124,7 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | [`kilin/retrievals/strategies/retrieval_sources.py`](../kilin/retrievals/strategies/retrieval_sources.py) | Rank sources across four channels, then select original passages. | [Retrieval pipeline](retrieval_pipeline.md) | [Retrieval tests](../tests/kilin/retrievals/) | | [`kilin/runtime.py`](../kilin/runtime.py) | Choose backend and device names without loading inference models. | [Model management](model_management.md) | [Core tests](../tests/kilin/) | | [`kilin/source_card_policy.py`](../kilin/source_card_policy.py) | Resolve core-owned source-card indexing policy for one project. | [Configuration](configuration.md) | [Policy tests](../tests/kilin/test_source_card_policy.py) | +| [`kilin/source_eligibility.py`](../kilin/source_eligibility.py) | Distinguish bibliography containers from independent document candidates. | [Source pipeline](source_pipeline.md) | [Eligibility tests](../tests/kilin/test__bibliography_eligibility.py) | | [`kilin/sources/__init__.py`](../kilin/sources/__init__.py) | Expose source-file records and structured source extraction. | [Source pipeline](source_pipeline.md) | [Source tests](../tests/kilin/sources/) | | [`kilin/sources/_word_metadata.py`](../kilin/sources/_word_metadata.py) | Read optional title/author properties from Word files for citations and search. | [Source pipeline](source_pipeline.md) | [Source tests](../tests/kilin/sources/) | | [`kilin/sources/extensions/__init__.py`](../kilin/sources/extensions/__init__.py) | Group optional suffix-specific source readers and extractors. | [Source pipeline](source_pipeline.md) | [Source tests](../tests/kilin/sources/) | @@ -132,12 +152,14 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | [`kilin/tools/_registry.py`](../kilin/tools/_registry.py) | Register KíLín's tools and resolve an intent's tool. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | | [`kilin/tools/_shared/__init__.py`](../kilin/tools/_shared/__init__.py) | Private services shared by registered KíLín tools. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | | [`kilin/tools/_shared/author_year.py`](../kilin/tools/_shared/author_year.py) | Find author-year citations and resolve them to reference-list entries. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/_shared/test_author_year.py) | +| [`kilin/tools/_shared/report_selection.py`](../kilin/tools/_shared/report_selection.py) | Discover tool-owned report templates and resolve qualified or ambiguous report requests. | [Tool extension contracts](extension_interfaces.md) | [Template namespace tests](../tests/kilin/test_project_layout__template_namespaces.py) | | [`kilin/tools/_shared/report_templates.py`](../kilin/tools/_shared/report_templates.py) | Read Markdown report templates and check reports against them. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | | [`kilin/tools/_shared/citations.py`](../kilin/tools/_shared/citations.py) | Validate bounded passage citations for document tools. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/_shared/test_citations.py) | | [`kilin/tools/_shared/claims.py`](../kilin/tools/_shared/claims.py) | Judge whether a cited work supports the sentence that cites it. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | | [`kilin/tools/_shared/_rating.py`](../kilin/tools/_shared/_rating.py) | Rate citation suitability from checked evidence, not search rank. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/_shared/) | | [`kilin/tools/_shared/choose_document.py`](../kilin/tools/_shared/choose_document.py) | Choose the source document a request is about, or ask the user. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | | [`kilin/tools/_shared/document_notes.py`](../kilin/tools/_shared/document_notes.py) | Shared reading, note-taking and citation checks for document tools. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | +| [`kilin/tools/_shared/group_reading.py`](../kilin/tools/_shared/group_reading.py) | Plan source-ordered reading and report actual member coverage from bound views. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | | [`kilin/tools/_shared/enough_evidence.py`](../kilin/tools/_shared/enough_evidence.py) | Ask whether the passages found for a question are enough to answer it. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | | [`kilin/tools/_shared/earlier_turns.py`](../kilin/tools/_shared/earlier_turns.py) | Select an earlier turn with listed supporting evidence. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | | [`kilin/tools/_shared/latex_text.py`](../kilin/tools/_shared/latex_text.py) | Reduce lines of LaTeX to the readable text they print. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | @@ -148,6 +170,7 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | [`kilin/tools/_shared/paths.py`](../kilin/tools/_shared/paths.py) | Name sources by the shortest unique ending of each path. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | | [`kilin/tools/_shared/planning.py`](../kilin/tools/_shared/planning.py) | Plan expensive tool runs and let the user confirm them or choose. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | | [`kilin/tools/_shared/references.py`](../kilin/tools/_shared/references.py) | Find a paper's reference lists and split one into entries, as printed. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | +| [`kilin/tools/_shared/search_sources.py`](../kilin/tools/_shared/search_sources.py) | Bind documentary or physical source views for exhaustive searches and report unindexed selections. | [Retrieval pipeline](retrieval_pipeline.md#remaining-tool-consumers) | [Source consumer tests](../tests/kilin/tools/test__remaining_source_consumers.py) | | [`kilin/tools/_shared/scan_settings.py`](../kilin/tools/_shared/scan_settings.py) | Validate shared mention-scanning fields with caller-owned defaults. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | | [`kilin/tools/_shared/source_access.py`](../kilin/tools/_shared/source_access.py) | Resolve source files only from an authorized project selection. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/_shared/) | | [`kilin/tools/_shared/sentences.py`](../kilin/tools/_shared/sentences.py) | Split indexed text into distinct sentences with source positions. | [Tool extension contracts](extension_interfaces.md) | [Tool tests](../tests/kilin/tools/) | @@ -213,9 +236,37 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | [`kilin/tools/writing_check/_scope.py`](../kilin/tools/writing_check/_scope.py) | Choose the part of a document a question asks to check. | [Per-tool README](../kilin/tools/writing_check/README.md) | [Tool tests](../tests/kilin/tools/) | | [`kilin/tools/writing_check/tool.py`](../kilin/tools/writing_check/tool.py) | Tool ``writing_check``: check the grammar and style of a document. | [Per-tool README](../kilin/tools/writing_check/README.md) | [Tool tests](../tests/kilin/tools/) | | [`kilin/tool_settings.py`](../kilin/tool_settings.py) | List and change the tool settings of one KíLín project. | [Configuration](configuration.md) | [Core tests](../tests/kilin/) | +| [`kilin/system_testing/__init__.py`](../kilin/system_testing/__init__.py) | Expose experiment inspection, validation, replay, and comparison records. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/experiment.py`](../kilin/system_testing/experiment.py) | Represent, inspect, replay, and compare recorded workspaces. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/_plugin_provenance.py`](../kilin/system_testing/_plugin_provenance.py) | Decode historical plugin identities and preflight fresh replay requirements. | [Plugin API](PLUGIN_API.md) | [Plugin provenance tests](../tests/kilin/system_testing/test__plugin_provenance.py) | +| [`kilin/system_testing/replay.py`](../kilin/system_testing/replay.py) | Execute validated chronological commands and map their outcomes. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/_semantic_replay.py`](../kilin/system_testing/_semantic_replay.py) | Validate and compare chronological semantic source organization and bound views. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/_replay_sources.py`](../kilin/system_testing/_replay_sources.py) | Plan historical source selections and verify reproduced inventories. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/_filesystem.py`](../kilin/system_testing/_filesystem.py) | Recognize incidental regular filesystem metadata in test inventories. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/_replay_interactions.py`](../kilin/system_testing/_replay_interactions.py) | Match recorded responses against live prompts without guessing. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/traces.py`](../kilin/system_testing/traces.py) | Decode original diagnostic events and compact span terminals. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/timeline.py`](../kilin/system_testing/timeline.py) | Reconstruct chronological recorded user commands. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/validation.py`](../kilin/system_testing/validation.py) | Validate recording completeness, sources, settings, and durable history. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/comparison.py`](../kilin/system_testing/comparison.py) | Compare independent workspaces and assemble quantitative observations. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/_comparison_alignment.py`](../kilin/system_testing/_comparison_alignment.py) | Align recorded operations and reconstruct persistent identity mappings. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/_comparison_metrics.py`](../kilin/system_testing/_comparison_metrics.py) | Measure text, retrieval, call, timing, and retained file observations. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/_comparison_diagnostics.py`](../kilin/system_testing/_comparison_diagnostics.py) | Compare mapped context and corroborated model-input metadata; inspect tool outcomes. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/_inspection.py`](../kilin/system_testing/_inspection.py) | Identify validated inspection-only extensions without changing strict alignment. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/reference.py`](../kilin/system_testing/reference.py) | Publish and inspect optional reference integrity receipts. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/replay_management.py`](../kilin/system_testing/replay_management.py) | Manage retained and fresh replays and record execution provenance. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/_first_divergence.py`](../kilin/system_testing/_first_divergence.py) | Locate the first observed difference in an aligned system-test replay. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/_comparison_report.py`](../kilin/system_testing/_comparison_report.py) | Render and publish sibling JSON and Markdown comparison reports. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/generation.py`](../kilin/system_testing/generation.py) | Record, validate and publish scripted reference experiments. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/batch.py`](../kilin/system_testing/batch.py) | Run managed experiments and execute independent report notebooks. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/system_testing/analysis.py`](../kilin/system_testing/analysis.py) | Render saved comparison snapshots and diagnostics with verified local trace references. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/_trace_configuration.py`](../kilin/_trace_configuration.py) | Encode complete effective configurations and verify exact or path-preserving content references. | [Trace architecture](trace_architecture.md) | [Configuration trace tests](../tests/kilin/test_trace_logging__configuration.py) | +| [`kilin/_trace_snapshots.py`](../kilin/_trace_snapshots.py) | Encode canonical snapshots and verify direct source-group and shared semantic-manifest references. | [Trace architecture](trace_architecture.md) | [Source trace tests](../tests/kilin/test_trace_logging__sources.py), [semantic trace tests](../tests/kilin/test_trace_logging__semantics.py) | +| [`kilin/_trace_json.py`](../kilin/_trace_json.py) | Format long integer arrays compactly without changing diagnostic JSON values. | [Trace architecture](trace_architecture.md) | [Trace JSON tests](../tests/kilin/test__trace_json.py) | +| [`kilin/_trace_project.py`](../kilin/_trace_project.py) | Coordinate project-wide event numbering and shared trace publication. | [Trace architecture](trace_architecture.md) | [Project trace tests](../tests/kilin/test__trace_project.py) | | [`kilin/trace_logging.py`](../kilin/trace_logging.py) | Record structured execution events and resumable conversation state. | [Trace recording](trace_recording.md) | [Core tests](../tests/kilin/) | | [`kilin/workspace.py`](../kilin/workspace.py) | Copy selected local sources into a managed multi-source workspace. | [Project workspaces](project_workspaces.md) | [Core tests](../tests/kilin/) | | [`kilin/workspace_resources.py`](../kilin/workspace_resources.py) | Represent packaged resources installed into a KíLín project workspace. | [Project workspaces](project_workspaces.md) | [Core tests](../tests/kilin/) | +| [`kilin/versioning.py`](../kilin/versioning.py) | Collect the authoritative application, plugin and persistent-format version inventory. | [Versioning](versioning.md) | [Version inventory tests](../tests/kilin/test_versioning.py) | ## Module owner summary @@ -226,17 +277,23 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | Configuration | 7 | | Conversation ownership | 4 | | Conversation memory | 8 | -| GUI architecture | 11 | +| GUI architecture | 13 | | Model management | 8 | | Per-tool README | 59 | -| Project workspaces | 6 | -| Retrieval pipeline | 32 | -| Source pipeline | 23 | -| Tool extension contracts | 27 | +| Plugin API | 9 | +| Project workspaces | 7 | +| Project-type schema | 1 | +| Retrieval pipeline | 35 | +| Source manifest | 5 | +| Source pipeline | 24 | +| System testing | 22 | +| Tool extension contracts | 29 | | Tool packages | 2 | +| Trace architecture | 4 | | Trace recording | 1 | +| Versioning | 1 | -**Total production Python modules: 194.** +**Total production Python modules: 245.** ## Non-Python resources and UI assets @@ -250,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 6f647c4f..153f575a 100644 --- a/docs/package_defaults.md +++ b/docs/package_defaults.md @@ -32,8 +32,8 @@ identifiers supplied by a project or caller. The identifiers use the form All eight values must be nonempty strings. Core router selection reads the project's saved ``[router]`` setting first; the packaged router default -is used only when the project has no saved or legacy router. Explicit -``RAGSession(router_model=...)`` overrides the saved selection for that +is used when the project has no saved router or supplied initial choice. +Explicit ``RAGSession(router_model=...)`` overrides the saved selection for that session. The GUI may save a user-preference router for a newly created project. These defaults do not automatically download a model. @@ -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 @@ -221,6 +221,13 @@ The recent-turn default is a nonnegative exact integer no greater than 100, and may be zero. The document budget is a positive exact integer between 1,000 and 200,000, matching the project-type parser's validation bounds. +Source-organization defaults are owned by the individual type definitions +and the [source-organization schema](PROJECT_TYPE_SCHEMA.md#source-organization-declarations), +not by `kilin_defaults.json`. An omitted declaration has only the +`unassigned` role, generic `attached_to` and `related_to` relations, and no +automatic rules. Omitted ordinary-intent relation policies default to empty +arrays. These values are declarative, not current index settings. + ## `RETRIEVAL` — ranking and document-selection heuristics Owned by retrieval modules in `kilin/retrievals/`. These settings affect diff --git a/docs/performance.md b/docs/performance.md index b9875863..fab2c742 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -11,9 +11,10 @@ by a small, read-only parser in The notebook supports two workflows: 1. **Analyze saved traces (default):** point `EXISTING_TRACES` to explicit - conversation 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. + conversation or project JSON files and run the notebook. No models or + 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 @@ -50,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 @@ -73,8 +76,14 @@ loading KíLín; other third-party backends may not honor them. The actual | `median_ms`, `min_ms`, `max_ms` | External per-question repeats | Median and observed range, separated by trace state | The notebook also produces an operation-level listing for initialization and -other recorded spans, including `session.ready` and model-load spans. This -allows inspection of startup components without introducing new counters. +other recorded spans, including `session.ready` and model-load spans. These +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. 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 @@ -93,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 36ca6677..c5b14ef7 100644 --- a/docs/project_workspaces.md +++ b/docs/project_workspaces.md @@ -1,5 +1,8 @@ # Project workspaces and tool resources +The authoritative [versioning policy](versioning.md) defines version +ownership, compatibility, and contributor obligations. + KíLín creates and opens project workspaces through **core Python APIs**. The GUI does not decide which folders or packaged tool resources a project needs. This document describes the filesystem contract and how to extend it @@ -16,6 +19,7 @@ Every newly initialized project has the following core entries: ```text project/ profile.ini + source_manifest.json sources/ indexes/ logs/ @@ -30,31 +34,55 @@ ordinary project sources. Feedback JSON is created only on a user update. See [Conversation memory](conversation_memory.md) for the ownership contract. The templates folder also exists in projects that do not currently use a templated tool. Users can add Markdown templates or -other resources manually. The `outputs/` directory is a general area for +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`, -and `source_snapshot.json`; 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 +imports and retained versions) and `source_snapshot.json` (single-source +mirror bookkeeping). The project-root `source_manifest.json` holds accepted +source organization, initialized before profile publication for new projects. +Existing projects missing the manifest require explicit initialization; +opening remains read-only. Creation and explicit source operations reconcile +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. +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) +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 @@ -62,10 +90,10 @@ A project tool's source-data access is limited to files **selected into the 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 source manifest records selected relative paths. The -project's configured source root determines where those names resolve, -while a shared tool-side check rejects paths outside the workspace and -symlinks. A selected file missing from its managed location is reported +The current index source state records selected relative paths. The +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: @@ -73,7 +101,10 @@ they are copied, indexed, and searchable like `.tex`. A reference checker may use their bibliography metadata only if those files were selected. Selection from a folder uses the active project extension/profile policy; users can control that selection before import. No LaTeX declaration -silently adds additional files. See [Security](security.md#workspace-source-access-policy) +silently adds additional files. Explicit semantic reconciliation may link +selected bibliography companions under accepted deterministic rules; it does +not import or index any new file. See [deterministic discovery](source_manifest.md#deterministic-bibliography-discovery) +and [Security](security.md#workspace-source-access-policy) for the limits of this application-level contract. ## Creation, opening, and explicit updates @@ -88,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`, ... | @@ -102,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 @@ -120,11 +150,11 @@ numbered-sibling allocation. The final name is reserved exclusively; import kilin first = kilin.prepare_sources_workspace( - ["/path/to/source"], kilin.PROJECT_TYPE_IDS[0], + ["/path/to/source"], kilin.project_type_ids()[0], workspace_root="/path/to/projects", ) second = kilin.prepare_sources_workspace( - ["/path/to/source"], kilin.PROJECT_TYPE_IDS[0], + ["/path/to/source"], kilin.project_type_ids()[0], workspace_root="/path/to/projects", ) assert first.root != second.root @@ -135,12 +165,12 @@ Both contain no placeholder sources or dummy indexes: ```python project = kilin.prepare_sources_workspace( - [], kilin.PROJECT_TYPE_IDS[0], + [], kilin.project_type_ids()[0], workspace_root="/path/to/projects", ) # For an explicitly chosen name, use the third positional argument instead: # project = kilin.prepare_sources_workspace( -# [], kilin.PROJECT_TYPE_IDS[0], "/path/to/new_workspace" +# [], kilin.project_type_ids()[0], "/path/to/new_workspace" # ) project = kilin.add_project_sources( project.root, ["/path/to/notes.txt"] @@ -151,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 @@ -193,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` | `research_briefing.md`, `popular_science_summary.md`, `technical_summary.md`, `experimental_protocol.md`, `project_overview.md`, `literature_table.md`, `README.md` | -| `writing` | The same templates and `README.md` | - -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. +| `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` | +| `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 @@ -218,14 +284,24 @@ 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. +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: ```python @@ -238,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 | | --- | --- | --- | @@ -299,24 +379,32 @@ callback accepts validated tool settings and returns a tuple of `kilin.workspace_resources.WorkspaceResource` objects. For example, the existing report tool declares a packaged file under -`kilin/tools/generate_paper_summary/templates/` and a destination under the project's -`templates/` folder. A custom template name that has no bundled file is -not declared as a packaged resource; its `templates/` folder is still -created, and the user can add the file manually before running the tool. +`kilin/tools/generate_paper_summary/templates/` and a destination under the +project's `templates/generate_paper_summary/` folder. The public helpers +`kilin.tools.template_resource(source, tool_name)` and +`kilin.tools.templates_folder(project_root, tool_name)` construct the resource +and locate the namespace without creating directories. A custom format with +no bundled file is not declared as a packaged resource. Users can create the +namespace and add the file manually before running the tool. Declaring a resource does not copy it. The core performs all installation. A resource source must be a regular file inside the declaring tool's package, not a symlink or a file owned by another tool. A declaration's -destination must be a safe, relative POSIX file path. +destination must be a safe, relative POSIX file path. A resource under +`templates/` must belong to the declaring registered tool's namespace. +Different tools may use identical template filenames in their own folders. Absolute paths, traversal components, empty components, Windows drive paths, and destinations inside source, index, log, or output areas are rejected. The destination and its parents may not be symbolic links. Existing files are preserved even during explicit resource restoration. -Every registered tool currently has its own validated `defaults.json` -and README. The `generate_paper_summary` package also owns its shipped -Markdown templates; other tools declare no workspace files at present. +Bundled tools own their validated defaults and README. User tools may omit +optional metadata and declare their own workspace resources. The actual +registered package owns the resource source. Updating or removing a plugin +does not overwrite existing workspace files. Unavailable types retain +saved workspaces but prevent execution until their requirements are restored. +See [plugin authoring](PLUGIN_AUTHORING.md). ## Explicit imports and source selection @@ -332,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 @@ -358,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 @@ -431,28 +520,95 @@ 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 The following GUI-independent core functions manage user-owned files: - `kilin.add_project_files(project, folder, paths, replace=False)` copies - selected local files or directories into `outputs/` or `templates/`. - Naming collisions are given numerical suffixes unless replacement is - explicitly requested. + selected local files or directories into `outputs/`, `templates/`, or an + existing subdirectory within either. Naming collisions use numeric suffixes + unless replacement is explicitly requested. +- `kilin.create_project_folder(project, folder, name)` creates one new + subdirectory under an existing editable directory, without overwriting. - `kilin.replace_project_file(project, path, source)` replaces an existing regular file in one of those folders. - `kilin.remove_project_files(project, paths)` removes files or directories 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 -the file operations and reports their results. +the file operations and reports their results. The workspace tree's context +menu adds files to the selected directory (or the selected file's parent) +and creates subdirectories. Native file drops target the deepest visible +editable directory at the drop position. ## Failure behavior and limitations @@ -469,6 +625,13 @@ including one that unexpectedly appears during initialization. Filesystems that cannot provide this operation fail closed, without an overwrite fallback. This is atomic visibility, not a guarantee against power loss. +When source preparation owns an enabled trace, its completion and closing +writes finish before profile publication. Strict diagnostic failures therefore +remain inside the creation rollback boundary; warning policy permits creation +with an incomplete recording. Caller-owned sinks remain open and receive +completion after publication. A failure in that final caller-owned diagnostic +write does not undo the published project. + On failure, the journal rolls back resources created by this attempt; it does not recursively delete arbitrary contents. A pre-existing empty destination is retained. A root created by this attempt is removed only if empty; shared @@ -479,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. @@ -504,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 5f34feba..3017678a 100644 --- a/docs/release.md +++ b/docs/release.md @@ -1,5 +1,8 @@ # Building and validating KíLín for macOS and Windows +The authoritative [versioning policy](versioning.md) defines version +ownership, compatibility, and contributor obligations. + ## Scope and limitations The macOS application is an Apple Silicon launcher containing `uv`, a @@ -17,12 +20,12 @@ macOS uses ad-hoc signing rather than Developer ID signing and is **not notarized**; Windows is unsigned. Gatekeeper or SmartScreen may block ordinary installation. No signing credentials are used by this workflow. -The release sequence is `0.1.0b1` → `0.1.0rc1` → `0.1.0`, with Git tags -`v0.1.0b1`, `v0.1.0rc1`, and `v0.1.0`. Installer specs must match the -exact PyPI version. On macOS, `CFBundleShortVersionString` uses the numeric -base (`0.1.0` for all three), while `CFBundleVersion` distinguishes beta, -RC, and stable builds using numeric release stages: `0.1.1001`, `0.1.2001`, -and `0.1.3000`, respectively. Later patch numbers occupy higher ranges. +The release sequence is `0.1.0b1` → `0.1.0b2` → `0.1.0rc1` → `0.1.0`, +with matching immutable Git tags. Installer specs must match the exact +PyPI version. On macOS, `CFBundleShortVersionString` uses the numeric base +(`0.1.0` for all four), while `CFBundleVersion` distinguishes the release +stages: `0.1.1001`, `0.1.1002`, `0.1.2001`, and `0.1.3000`, respectively. +Later patch numbers occupy higher ranges. On Windows, update comparisons use the semantic order beta < RC < stable. To build from the published PyPI version or from a checkout wheel: @@ -46,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 @@ -102,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. @@ -135,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. @@ -149,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 @@ -169,25 +203,38 @@ 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 Push an annotated tag matching the version in `pyproject.toml`, such as -`v0.1.0b1`, after validating the tagged commit. The tag workflow checks +`v0.1.0b2`, after validating the tagged commit. The tag workflow checks the generated PyPI README and calls both reusable platform workflows. It packages `KiLin--macos-arm64.dmg`, `KiLin-Setup-.exe`, and `SHA256SUMS.txt` for that same tag. 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. @@ -200,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) @@ -219,6 +269,21 @@ tagged source and artwork rights before upload. Follow the [release checklist](development.md#public-prerelease-sequence). +## Plugin acceptance before release + +Run both complete repository test runners and the distribution workflow at +the exact release head. The distribution check verifies the source authoring +pack and executes it through the isolated installed wheel. The native smoke +workflows exercise platform lifecycle behavior; the Windows installer also +checks that user plugin files survive reinstall and uninstall. The macOS +launcher upgrade regression checks user plugin preservation separately from +runtime installation. On each supported native platform, additionally open +Settings > Plugins, validate and install a trusted example, close all runtimes, +restart, verify availability, then update and remove it. Verify saved +workspaces and user plugins survive application upgrades/removal. See +[plugin authoring](PLUGIN_AUTHORING.md). Native dialog and real-model checks +are not established by the model-free checker alone. + ## Related [Development](development.md), [README publication](readme_publication.md), diff --git a/docs/retrieval_pipeline.md b/docs/retrieval_pipeline.md index e13888b9..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,19 +286,22 @@ 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. The kind covers research articles, preprints, reviews, conference papers, methods papers and scientific-software papers. File extensions alone do not -establish eligibility. A deterministic precheck rejects sources with no -extracted chunks or usable text. For the remaining candidates, **one** -dedicated-model call jointly decides applicability and produces the card. +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; +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 @@ -315,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 @@ -327,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. @@ -343,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 @@ -359,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. @@ -381,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 @@ -405,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 @@ -417,10 +422,20 @@ it does not guarantee that every requested source fits the evidence budget. from complete semantic, lexical, applicable code-graph and source-card rankings. Each available channel contributes one reciprocal-rank score per source; repeated chunks or card kinds do not inflate a source's rank. +An opt-in grouped view substitutes logical anchors for physical sources; +see [logical-group retrieval](#logical-group-retrieval). A card-ranked source need not have any globally top-ranked passage to be selected. All answer evidence still comes from the original chunks, not from generated card statements. +Independent source discovery excludes `.bib` and `.bbl` before assigning +channel positions or selecting source and passage quotas. Source-first +lookup can include their original indexed passages when the question or +explicit scope identifies a bibliography. Their scientific-paper cards +remain ineligible. Paper-oriented coverage counts eligible document +candidates, not all selected physical files. This distinction does not +certify that every remaining PDF or other file is a paper. + Fusion gives every source a position in every channel, so in a small project every source is ranked, however unrelated, and a position says nothing about how relevant a source is. Before sources are chosen, @@ -431,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 @@ -459,38 +478,40 @@ strategies). | Setting | Allowed values | Behavior | | --- | --- | --- | | `strategy` | `"source_first"` | Source-level four-channel RRF followed by original evidence. | -| `max_sources` | Integer 1–50 | Upper bound on represented sources; default 3. | -| `passages_per_source` | Integer 1–10 | Target per selected source; default 1. | +| `grouped` | Boolean | Opt into logical-group source-first retrieval; default false. | +| `max_sources` | Integer 1–50 | Upper bound on selected logical anchors in grouped mode, otherwise represented sources; default 3. | +| `passages_per_source` | Integer 1–10 | Target per selected group or physical source; default 1. | | `max_passages` | Integer 1–200 | Final hard number of original evidence passages; default 8. | | `evidence_tokens` | Integer 1000–200000 | Final hard estimate of evidence tokens, including source headers; default 5000. | | `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 @@ -499,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 @@ -534,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`. @@ -588,11 +610,26 @@ 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`. 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 +`RAGSession.refresh_sources(project)` reconciles semantic metadata before +physical preparation and returns its separate `SourceLifecycleResult`. +After only a role/link edit, use `RAGSession.refresh_source_metadata()` to +inspect current assignments, pending roles and retained versions and refresh +headings from saved data. This path never calls embedding or card preparation +and does not rebuild the indexes. Subsequent retrieval resolves a fresh +view from the accepted metadata and the loaded physical generation. + `RAGSession` can reuse cached embeddings for unchanged chunks when a saved index and the current embedding-model snapshot and chunking configuration allow it. Changed/new chunks are embedded; removed entries disappear from @@ -639,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 @@ -655,35 +693,367 @@ 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 + +`kilin.source_views` resolves accepted source organization without reading +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 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 + +| Scope mode | Meaning | +| --- | --- | +| `project` | No explicit operands; consider eligible anchors project-wide. | +| `preferred` | Keep explicit target operands first and permit other eligible candidates. | +| `restricted` | Limit anchors to the explicit operands; an empty tuple means no targets, candidates or members. | + +`SourceScope` uses distinct canonical source-relative `Path` operands. +Both syntax and exact membership in the inspected selected inventory are +validated. Unknown or ineligible explicit operands raise an error; they do +not trigger a project-wide search. Related members may be included in a +restricted view only by the effective relationship policy for its anchors. + +`SourcePolicy` selects the purpose (`document`, `lookup` or `raw`), optional +role filters and permitted relation IDs. It never changes accepted roles or +imports files. For `document`, targets and independent candidates must have +active accepted roles, cannot be active dependency children or retained +historical versions, and cannot be bibliography containers. This is an +eligibility rule, not a scientific-publication classifier. `lookup` and +`raw` can explicitly target any selected physical file, including a +bibliography, a dependent, an unresolved assignment or a retained version. +They do not discover independent publications; their anchors are lookup +members. A source without an active role cannot satisfy a named-role filter. + +| Policy field | Meaning and default | +| --- | --- | +| `target_roles` | Target roles; `None` permits any eligible target. | +| `candidate_roles` | Independent candidate roles; `None` inherits `target_roles`. | +| `evidence_roles` | Related evidence member roles; `None` permits any eligible member. | +| `lookup_roles` | Related lookup member roles; `None` permits any eligible member. | +| `related_evidence` | One-hop relation IDs allowed for supporting evidence; empty by default. | +| `related_lookup` | One-hop relation IDs allowed for lookup; empty by default. | +| `grouped` | Opt into logical-group ranking and quotas for documentary source-first retrieval; false by default. | + +An explicit empty role tuple permits no matching roles; role filters for +related members do not remove a selected anchor. Unknown policy identifiers +are rejected against the **accepted** vocabulary, not today's installed +project type. A mismatch requires explicit settings adoption or a revised +policy. Comparison and grouping are separate from scope. The current +`compare` behavior is not a grouping switch. + +### Physical members and logical anchors + +A `SourceGroup` has one physical anchor, a tuple of physical evidence members, +lookup members and unavailable-member diagnostics. For a dependency, expand +from parent to immediate dependent; for an association, expand symmetrically +only if its relation type is allowed. The latter never changes independence. +Do not follow a dependent's own links recursively. If two anchors share a +supplement or bibliography, both groups retain its path and the view's union +contains it only once. Bibliography containers cannot enter scientific +support membership even if an evidence relation or role names them. Inactive +relationships are diagnostic only and cannot authorize access to missing +files or unresolved roles. + +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; 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 + +Use the authoritative `inspect_source_manifest(project)` result and the +same physical generation's original indexed paths and repository manifest +(`indexes/index_source_state.json`). `capture_source_inventory()` captures +physical paths, recorded SHA-256 identities and whether each has indexed +passages. The host supplies a SHA-256 index-generation identity including +applicable indexing configuration (not just a chunk/graph fingerprint). +Unindexed selected paths without captured hashes are visible but cannot be +verified for a raw read. Stale index entries outside the selection are +rejected. A `SourceOperation` freezes semantic revision, exact manifest-byte +digest, source-root binding, physical inventory/generation, retained-version +identities, scope and effective policy. Do not refresh one service's view +mid-operation while another service uses the old snapshot. + +For a host/notebook that already captured its physical state, for example: + +```python +from pathlib import Path +import kilin +from kilin.tools import ( + SourcePolicy, SourceScope, capture_source_inventory, + resolve_source_view, validate_source_view, +) + +inspection = kilin.inspect_source_manifest(project) +# index_state, indexed_paths and index_generation are captured by the host. +inventory = capture_source_inventory( + inspection, index_state, indexed_paths, index_generation, +) +policy = SourcePolicy( + target_roles=("primary",), + related_evidence=("supplement_to",), + related_lookup=("bibliography_for",), + grouped=True, +) +scope = SourceScope("restricted", (Path("manuscript.pdf"),)) +view = resolve_source_view(inspection, inventory, policy, scope) +print(view.targets, view.evidence, view.lookup, view.unavailable) +validate_source_view(view, inspection, inventory, policy, scope) +``` + +The example assumes a Reviewing vocabulary and an accepted primary +assignment. `validate_source_view()` compares the resolved view with an +explicitly supplied current inspection, inventory and policy; mismatches +raise `SourceViewConflict`. The resolver does not rescan or hash source +bytes. Reuse one validated immutable view for an operation. No lock is held +during model work. The host must supply coherent captured generations and +validate current state before using a view with different index objects. + +`read_source_bytes(project.root, project.source, view, path)` allows only a +member of the captured view, applies the existing selected-file workspace +containment checks, and returns bytes only when their SHA-256 matches the +captured identity. A changed root, unselected member, missing digest, +symlink escape or changed bytes raises `SourceViewConflict`. This is a +best-effort consistency and containment service, not a race-free filesystem +opener or a Python sandbox. Trusted plugins retain the user's permissions. + +### Enforcing a view before ranking + +A loaded `RAGSession` supplies a live view through `source_view(policy, scope)`. +For example, a host with an already prepared session can request independent +scientific evidence, including the permitted supplementary relation: + +```python +from pathlib import Path +from kilin.tools import SourcePolicy, SourceScope, RetrievalRequest +from kilin.retrievals.evidence_budget import EvidenceLimits + +view = session.source_view( + SourcePolicy(related_evidence=("supplement_to",)), + SourceScope("restricted", (Path("manuscript.pdf"),)), +) +request = RetrievalRequest( + "What were the measured effects?", + EvidenceLimits(3, 2, 6, 3000), + view=view, +) +``` + +This example assumes the Reviewing, Writing or Literature vocabulary and a +selected independent manuscript. A bounded retrieval host validates a +supplied view against the current accepted manifest and loaded physical +generation before scoring. A stale or altered view raises +`SourceViewConflict`; an explicitly empty restriction returns empty coverage +without a query embedding. Ordinary search resolves the question's recognized +operands and uses its intent's `related_evidence` and `related_lookup` arrays. +Explicit physical lookup may include dependent or bibliography files. A +recognized removed operand or an ineligible explicit documentary operand +fails rather than widening the scope. Natural-language operand recognition +remains the existing name/description resolver, not a general file parser. + +The private `_scope` projection limits semantic vectors, lexical vectors, +chunks and the code-entity graph before scoring or rank fusion. Original +corpus-wide TF-IDF weights and all eligible vector identities are reused. +Excluded graph entities cannot seed a search or bridge between eligible files; +context planning and expansion also receive the projected graph and chunks. +Card paths must be indexed independent candidates in the view before their +vectors are scored. Related lookup members do not vote as documentary +support. An explicitly preferred scope retains other eligible candidates +but prioritizes its operands; restricted scopes admit only their permitted +physical members. Complete-document mode selects one eligible target or +candidate, not an automatically merged document. Grouped views support +source-first retrieval only; hybrid, complete-document and raw ranking +requests using them fail explicitly. Existing ungrouped retrieval retains +physical-source quotas. + +The single-document tools `paper_overview`, `batch_review` and +`generate_paper_summary` choose one eligible anchor through a bound source +service and then resolve its explicitly permitted related evidence. This is +separate from grouped search and ordinary complete-document retrieval. +Their shared reading helper preserves original passage coordinates and orders +members anchor first, then by relative path. The overview shares one passage +text budget; multi-part tools share their reading-call limit across members. +Coverage reports processed passages per member, including absent and +unindexed members. A related passage never counts as a read anchor. Explicit +physical lookup stays single-file; explicit saved-output inputs remain +outside the indexed-source view and do not enter the manifest. + +The project-wide `project_summary` uses the same accepted source policies. +It enumerates independent anchors before applying `max_documents`. A +logical group receives one bounded map excerpt, including permitted +related evidence; no search or embedding is needed for this enumeration. +Physical citation IDs are distinct from logical report rows. A shared +attachment can contribute to multiple map prompts without becoming a +separate row or duplicating its physical citation. Failed and omitted +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). + +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. 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 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 +its parent anchors, but an anchor receives at most one vote per channel. +Repeated passages and card kinds cannot inflate its score. A shared best +member gives its parents equal channel rank (subsequent positions skip the +tied ranks). Equal fused scores are ordered by source-relative anchor path. +Lookup-only members do not vote or appear as supporting evidence; cards +remain physical discovery hints. One existing query embedding and the +projected physical channels serve all groups. Grouping never rebuilds or +merges indexes. + +`max_sources` limits selected anchors, not their combined physical files. +`passages_per_source` is a desired number of passages per selected group, +not per attachment. First reserve a fitting original anchor passage for +each selected group, then try to represent any still-unrepresented groups, +then approach their desired quotas and fill remaining capacity. A lower +ranked fitting anchor passage may be selected when a larger passage does not +fit. Expand context only within the selected groups' evidence membership. +Deduplicate shared physical passages before charging `max_passages` and +`evidence_tokens`; one shared passage may contribute to each selected parent +but consumes the global budget once. The existing evidence token estimate +includes physical citation headers and text, not the full model context. +Any original lookup passages in a separate explicit lookup request are +subject to that request's physical evidence budget. + +For example, two selected papers sharing one supplement and one bibliography +can be represented by three original evidence passages (one per paper and +one shared supplement) under `max_sources=2`, `passages_per_source=2` and +`max_passages=3`. The bibliography is recorded as lookup membership but is +not a fourth scientific passage. The original supplement citation is shared, +not copied under synthetic paper paths. If neither anchor has an indexed +passage, their shared supplement may still represent both groups under a +one-passage cap, but neither anchor is represented. + +### Group coverage contract + +`RetrievalResult` keeps original chunks and physical `sources`. In grouped +mode `sources` lists distinct represented physical paths in citation order; +`groups` records selected anchors even when no passage fits. With a +resolved view, `SourceGroupCoverage` records actual represented physical +members, omitted available members, unavailable members and whether the +anchor has an original returned passage. `group_coverage(group, passages)` +derives representation from those passages. `RetrievalResult.groups` holds +selected groups' coverage and `coverage["groups"]` is its JSON-compatible +representation. The view-aware result validates membership and duplicate +physical passages; a shared chunk can represent more than one group without +changing its path or identifier. Representation does not mean complete +review, and a supplement alone does not represent its anchor. + +Grouped reports add `requested_groups`, `selected_groups`, +`represented_groups` (at least one evidence member), `represented_anchors` +(at least one passage of the anchor itself), `missing_groups`, +`missing_anchors`, `unselected_groups` and `unselected_group_details`. +The physical `requested_sources`/`represented_sources` counts refer to +unique evidence paths, not the number of papers. Lookup memberships and +unavailable members remain explicit in group rows. `complete` concerns +representation of requested anchors and their authorized evidence paths; +it does not certify that unavailable attachments were read. A shared +member in an unselected group's diagnostic row does not count that group +as selected or represented. Explicit requests for a number of documents +are checked against represented anchors. Ordinary answer prompts identify +the selected groups using original citation numbers, with missing anchors +marked explicitly. Selection and final coverage traces also record the +captured manifest revision/digest, physical generations, policy and scope. +Group-aware complete-document reading is a separate operation, not enabled +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 -its strategy (`hybrid` or `source_first`), `EvidenceLimits`, optional +`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. The result returns original indexed `Chunk` objects -in citation order, the source-ranked candidates, and a deterministic coverage -report. A selected source may not have a passage that fits the token budget; +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 +validated ungrouped views; source-first also accepts grouped documentary +views. The coordinator resolves an operation when the +caller omits a view, preserving independent-document source-first discovery +and explicit physical lookup. The result returns the resolved view, original +indexed `Chunk` objects +in citation order, the source-ranked candidates (represented physical paths +in grouped mode), and a deterministic coverage report. A selected source may not have a passage that fits the token budget; selection is **not** evidence that it supports the user's question. Tools must opt in; `ToolContext.rank(query)` still returns a complete hybrid -ranking without source cards or hard evidence limits. Exhaustive scanners -continue using full rankings or original chunks. `retrieve()` never inherits +ranking without source cards or hard evidence limits. Exhaustive scanners use full rankings or original chunks **within their +bound source views**, without imposing ordinary retrieval limits. `retrieve()` never inherits ordinary answering-intent limits: tools must declare their own budgets in validated tool settings. The hard limits cover selected original passages, source headers and estimated evidence tokens, not model output, full chat history, or the complete source contents. Unknown card kinds are rejected, and card-kind filtering applies only to source-first discovery. +`RetrievalRequest.include_bibliographies` is optional and valid only for +source-first retrieval: `None` recognizes explicit bibliography lookup +from the query or scope, `False` requires independent document candidates, +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 + +`find_fact`, `find_passages`, `scan_and_list`, and `batch_classify` bind a +source view before scanning or ranking. Explicit paper-oriented requests +use independent current document anchors; literal physical lookups retain +selected dependents, retained versions, and bibliography containers. No +relationship expansion is implicit in these tools. Exact restrictions +preserve selected but unindexed members as coverage omissions, not negative +matches. Long-list exports validate their captured view after confirmation. + +`writing_check` resolves one selected physical file and reads its verified +bytes through a restricted `raw` view. It does not assemble a logical group. +A named dependent or retained version may be checked explicitly, but it +cannot become an independent discovery candidate. Binary document readers +receive a temporary copy of the verified bytes. The tool revalidates the +operation and byte identity before report publication or rewrite return. + +`show_source` may add context only from selected indexed files whose saved +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 operate on the physical inventory. ### Regeneration and memory-safe refresh diff --git a/docs/security.md b/docs/security.md index 5a4c7e2d..f695fad8 100644 --- a/docs/security.md +++ b/docs/security.md @@ -31,8 +31,8 @@ data protections remain important. ## Workspace source-access policy -**Project tools may read source content only from the project's explicit -source selection within its workspace.** A path appearing in a document, +**Project tools and semantic discovery may read original source content +only from the project's explicit source selection within its workspace.** A path appearing in a document, a model response, a bibliography command or a tool argument is a reference, not permission to import or read another file. The active selected-source inventory establishes authorization; filesystem existence alone does not. @@ -50,7 +50,7 @@ redirect reads. They must not fall back from an absent selected source to another file with the same name at the workspace root or in the original import directory. Missing or ambiguous dependencies are reported. -The reusable `tools/_shared/source_access.py` helper applies these checks +The reusable core `_source_access.py` helper applies these checks for reference checking. In particular, `.tex` references to `.bib` and `.bbl` files resolve **only** to explicitly selected workspace sources; when the same filename exists in several selected directories, the @@ -59,6 +59,12 @@ contract for future source-reading changes. Existing profiles that point to source directories outside their workspace must import those files before this helper can read them. +A [semantic source role or link](source_manifest.md) does not change the +selected-source authority or broaden a tool's access to external files. Its +metadata is validated independently of live availability; unavailable endpoints +stay inactive. Manifest edits coordinate cooperating writers with a stable +sidecar and exact-content conflict checks, not an operating-system sandbox. + These are **application-level rules**, not an OS-enforced sandbox or a claim of complete repository-wide filesystem isolation. Existing reads outside this tool are not exhaustively audited by this change. The helper @@ -68,7 +74,8 @@ still require a stronger boundary for adversarial multi-user operation. ## Sensitive data paths The original sources, copied `sources/` tree, `sources.json` provenance, -`source_snapshot.json` manifest, `indexes/` vectors and cached exact text, +`source_snapshot.json` mirror inventory, `source_manifest.json` roles, links +and source-root identity, `indexes/` vectors and cached exact text, `logs/traces/conversation_*.json`, archived/deleted conversations, `outputs/`, `templates/`, user preferences and model caches can each expose private information. Embeddings are **derived from** sensitive text and @@ -144,9 +151,30 @@ code. Numeric citation checking establishes only that cited indices exist, not that the answer is supported or correct. Human review is still required for scientific conclusions, software changes and high-impact decisions. -Tools are explicitly registered, and `ToolContext` limits how models -interact with KíLín operations. This is good architectural containment but -not a comprehensive prompt-injection mitigation or command-execution sandbox. +Tools expose explicit descriptors, and `ToolContext` defines the supplied +host services. This is architectural containment, not a comprehensive +prompt-injection mitigation or command-execution sandbox. User Python +plugins execute with the user's permissions. Structural checks do not +execute candidate code; trusted validation imports it in a subprocess, +which is not a security sandbox. Review all source and dependencies before +trusted validation or installation. Managed activation coordinates cooperating +runtimes; it does not contain malicious code. See [plugin authoring](PLUGIN_AUTHORING.md) +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. 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 +and context expansion. Stale views and invalid explicit restrictions cannot +silently broaden selection. Current-evidence reuse additionally checks saved +source digests, exact indexed passages and current file content. Historical +turns are not rewritten. The remaining unbound tool services do not yet +promise view-aware restrictions; trusted tools must not substitute them for +a required bounded retrieval operation. + There is no general agentic OS-shell execution boundary documented as implemented in this repository snapshot. diff --git a/docs/source_manifest.md b/docs/source_manifest.md new file mode 100644 index 00000000..64fb65b9 --- /dev/null +++ b/docs/source_manifest.md @@ -0,0 +1,463 @@ +# Accepted source organization + +The project-root `source_manifest.json` is the authoritative semantic record +of why selected files belong to a project and how they are related. It is not +an import inventory, a retrieval index, a scientific classification model, or +permission to read a file. The core API works without Qt or model sessions. + +Explicit Python editing operations, creation, source updates and explicit +source refresh reconcile accepted deterministic relationships. Immutable +[source views](retrieval_pipeline.md#source-views-and-operation-snapshots) +resolve the accepted graph and a captured physical generation for an explicit +operation policy. Ordinary retrieval and source-aware tools use these views; +logical document groups preserve the physical identity of every cited passage. +The desktop editor delegates to the headless engine, and complete recorded +semantic histories can be validated and replayed chronologically. Semantic +edits change eligibility and grouping, not the underlying physical index. +See [Retrieval](retrieval_pipeline.md#source-views-and-operation-snapshots), +[GUI editing](../kilin/gui/README.md#source-organization), and +[semantic replay](system_testing.md#semantic-source-organization). + +For an ordinary answer explicitly naming a dependent file, KíLín can use a +restricted physical lookup instead of independent-document discovery. Naming +both a manuscript and its supplement permits both named operands without +creating a separate paper candidate or widening the search to unrelated +files. A request naming only the manuscript continues to use its configured +logical evidence group. Document-only tools retain their stricter policies. + +## Ownership and initialization + +| Record | Owner and meaning | +| --- | --- | +| `source_manifest.json` | Accepted roles, links, suppressions, root identity and organization settings. | +| `sources.json` | Managed import provenance and retained versions. | +| `source_snapshot.json` | Single-source mirror bookkeeping. | +| `indexes/index_source_state.json` | Derived physical-file hashes and sizes for incremental indexing. | +| `source_card_sources.json` | Source-card generation overrides. | +| `project_behavior.json` | Ordinary-intent policies and other behavior overrides. | + +All new-project creation paths initialize the manifest at revision zero +inside the existing exclusive creation transaction, after copying sources +and before publishing `profile.ini`. A failure rolls back the journaled +manifest with the other newly created resources. Each selected file receives +the accepted default role with origin `default`, including explicitly imported +unsupported formats and tracked retained versions. Literal bibliography +declarations are discovered under the accepted rules, without model calls +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 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 +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 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 +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-v2`, reported as `source_organization` by +`kilin.version_info()`. It is independent of the managed-import +`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-v2", + "revision": 3, + "source_root": {"base": "project", "path": "sources"}, + "organization": { + "derived_from": { + "project_type": "reviewing", + "project_type_version": "0.1.0", + "schema_version": 1, + "origin": "distribution", + "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + "roles": ["unassigned", "primary", "supplementary", "reference", "bibliography"], + "default_role": "unassigned", + "relation_types": { + "attached_to": {"behavior": "dependency"}, + "related_to": {"behavior": "association"}, + "bibliography_for": {"behavior": "dependency"}, + "supplement_to": {"behavior": "dependency"} + }, + "automatic_rules": [ + {"id": "latex_bibliography", "detector": "latex_bibliography", "relation": "bibliography_for", "mode": "apply"} + ], + "detector_versions": {"latex_bibliography": "1"} + }, + "files": { + "manuscript.tex": {"role": "primary", "origin": "user"}, + "refs.bib": {"role": "bibliography", "origin": "user"}, + "supplement.pdf": {"role": "supplementary", "origin": "user"} + }, + "relations": [ + {"source": "supplement.pdf", "target": "manuscript.tex", "type": "supplement_to", "origin": "user", "rule": null} + ], + "suppressed_automatic": [ + {"source": "refs.bib", "target": "manuscript.tex", "type": "bibliography_for"} + ], + "unresolved": [] +} +``` + +`revision` is a nonnegative integer (not a boolean). A saved organization +must explicitly contain both generic relations and every detector identity. +The [project-type declaration schema](PROJECT_TYPE_SCHEMA.md#source-organization-declarations) +owns vocabulary validation. A file role origin is `default` or `user`; +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 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. + +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. +Associations have lexically ordered endpoints, are symmetric, and preserve +both files' independence. Duplicate links, duplicate suppression keys, +noncanonical persisted associations and duplicate JSON members are rejected. +Unknown syntactically valid role, relation or rule IDs and missing endpoints +remain inspectable but inactive. This is distinct from malformed structure, +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 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 +to 2^63 - 1. The complete source scan also retains its existing entry and +file-size limits. Unreadable or excessive metadata is never silently reset. + +## Python operations + +The following example imports two actual files and explicitly assigns their +roles. It neither moves source bytes nor calls a model. + +```python +import kilin + +project = kilin.prepare_sources_workspace( + ["/data/manuscript.pdf", "/data/supplement.pdf"], + "reviewing", + "/work/review", +) +inspection = kilin.inspect_source_manifest(project) +assert inspection.binding_matches + +preview = kilin.preview_source_manifest(project, ( + kilin.RoleEdit("manuscript.pdf", "primary"), + kilin.RoleEdit("supplement.pdf", "supplementary"), + kilin.RelationEdit("supplement.pdf", "manuscript.pdf", "supplement_to"), +)) +print(preview.before.snapshot.manifest.revision, preview.after.revision) +result = kilin.apply_source_manifest(project, preview) +assert result.snapshot == kilin.read_source_manifest(project) +``` + +`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 +writer ownership and returns the durable snapshot. The operation records are: + +| Operation | Effect | +| --- | --- | +| `RoleEdit(path, role)` | Assign a declared role explicitly, even if its value equals the default. | +| `RoleEdit(path)` | Clear the explicit assignment to the **accepted** default, origin `default`. | +| `RelationEdit(source, target, relation)` | Add or pin one manual link between active selected paths. | +| `RelationEdit(source, target, relation, "unlink")` | Disconnect a stored link and suppress automatic recreation of that exact edge. | +| `RelationEdit(source, target, relation, "restore_suppression")` | Explicitly clear that suppression; an accepted detector may recreate the edge in the same preview. | +| `ResolveSourceEdit(path, restore=True)` | Explicitly restore a retained role and its eligible links. | +| `ResolveSourceEdit(path)` | Reset an unresolved role to the accepted default; remove its old incident links but retain suppressions. | + +Manual linking does not clear a previous suppression: the manual link is +active and automatic recreation remains disabled. A no-op disconnect of an +absent link makes no change. Ordered edits are applied together; the final +proposed graph, rather than every intermediate graph, must be valid. + +An empty batch previews reconciliation. New selected paths receive the saved +default; accepted paths no longer selected are retained in `unresolved` with +reason `removed`. Reappearing paths remain inactive until explicit restoration +or reset. A dangling link with a formerly unassigned endpoint uses reason +`missing_assignment` when that endpoint becomes selected. In-place content +replacement at an active selected path retains its role and manual links; +rule-owned links are reconciled against the current declarations. A +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. + +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 + +Installed type defaults may change between processes without affecting saved +organization. New selected files receive the accepted default until explicit +adoption. To preview the current installed type, use +`preview_source_manifest(project, adopt_type_defaults=True)`. To edit +project-local settings, supply `organization=...` with a validated +`SourceOrganization` declaration instead. The latter retains the original +captured type provenance. The `project_behavior.json` editor does not own +these settings. + +If a used role disappears or a used relation disappears or changes behavior, +the preview fails until the user supplies explicit `role_mapping` or +`relation_mapping` dictionaries, or resolves incompatible records separately. +An identity relation mapping explicitly accepts a changed behavior under the +same identifier. Existing role origins and suppressions are retained through +mappings. Canonicalization must not merge existing links or suppressions; +resolve collisions first. A change to an existing automatic edge's rule declaration is rejected until +the edge is pinned or disconnected. Detector implementation versions alone +can be adopted explicitly without changing the accepted vocabulary. + +## Deterministic bibliography discovery + +An explicit manifest preview runs the accepted `latex_bibliography` rule, +when the saved detector identity matches the installed implementation. It +reads only active, selected `.tex` files within the workspace, using the same +raw-read boundary as the reference tools. It neither opens bibliography +entries nor runs LaTeX. It recognizes literal `\bibliography{...}` and +`\addbibresource{...}` arguments at the top brace level, ignoring comments and verbatim examples. +No macro expansion, input/include traversal or TeX conditional evaluation is +performed. This is lexical discovery, not a TeX interpreter. + +An explicit name resolves relative to the referring document's directory; +a unique bare basename can resolve elsewhere in the selected collection. +An explicit relative path (including `./`) must match its normalized location +inside the source root; absolute paths, traversal outside the source root, +macro paths, remote URLs, unselected names and ambiguous basenames do not +produce links. Selected inactive matches cannot be substituted by another +file with the same basename. An implicit compiled companion must be a selected `.bbl` +with the same stem in the same directory. Both the declared database and +compiled companion can be linked. A shared bibliography can have several +parents. No role is inferred, and no supplement or primary manuscript is +guessed from its name. Missing or unreadable text is reported; an unreadable +referring document does not cause accepted automatic links to be deleted. + +The saved rule's mode determines whether eligible edges are applied or +returned as proposals. `preview.discovery` and `result.discovery` are +immutable `SourceDiscovery` records with `added`, `removed`, `proposed` +and `diagnostics` tuples. A diagnostic identifies the rule, target, reason +and detail. Manual links outrank automatic edges, including when a candidate +would close a dependency cycle. Unlinking an accepted edge suppresses exact +automatic recreation even after reopening or adopting a new detector. +Inactive endpoints remain excluded until explicitly resolved. Repeated +unchanged reconciliation does not write or advance the revision. A +`propose` rule returns candidates without persisting them; accept one via +an explicit `RelationEdit`, which pins a user-owned link. + +For a manifest saved with a different detector identity, +preview adoption without changing the saved project-type declarations: + +```python +preview = kilin.preview_source_manifest( + project, adopt_detector_versions=True, +) +print(preview.discovery.added, preview.discovery.removed) +print(preview.discovery.proposed, preview.discovery.diagnostics) +result = kilin.apply_source_manifest(project, preview) +``` + +A mismatched detector otherwise produces a diagnostic and does not alter +its existing links. If adopting a new version would leave an active +previously automatic link unverifiable because its referring source cannot +be read, adoption fails rather than certifying that link under the new +implementation. Explicit adoption of installed type defaults also adopts +its detector identities. Revalidation repeats discovery before committing; +changed semantic outcomes require a fresh preview. Source bytes are not +stored in the semantic manifest. + +For example, selected `paper.tex` and `other.tex` can both declare +`\bibliography{refs}` while `paper.bbl` is the compiled companion of +`paper.tex`. The preview contains three independent dependency edges: +`refs.bib -> paper.tex`, `refs.bib -> other.tex`, and `paper.bbl -> paper.tex`. +`reference_check` independently chooses inline references, then compiled +references, then the database. The semantic graph does not change that +consumption precedence or authorize an import. Discovery runs in semantic +previews and the source lifecycle, always under the saved detector identities. +Retained historical copies are not candidates for automatic discovery. + +## Source lifecycle and metadata refresh + +Creation (including an empty project), managed batch imports, mirror and +managed synchronization, and managed removal reconcile the actual selected +inventory. Every newly selected path receives its saved default once per +batch, including explicitly selected formats with no reader. Same-path +replacement retains accepted roles and manual links. Known missing paths +become unresolved; a reappearing path needs an explicit `ResolveSourceEdit`. +An unobserved deletion and recreation between refreshes is indistinguishable +from replacement at the same path. + +The physical APIs retain their original return types. Pass an optional +`on_organization` observer to receive one immutable `SourceLifecycleResult` +after publication, including on a partially completed update. The observer +runs outside semantic writer ownership. For example: + +```python +outcomes = [] +project = kilin.prepare_sources_workspace( + [paper, supplement], "reviewing", destination, + on_organization=outcomes.append, +) +outcome = outcomes[-1] +if outcome.error: + print(outcome.error) +else: + print(outcome.inspection.pending_roles) + print(outcome.discovery.proposed) +``` + +`added_files` records newly materialized defaults; intersect these paths with +`inspection.pending_roles` to ask only about new files. The core does not +prompt or assign scientific roles. `pending_roles` includes current +`unassigned` roles and selected unresolved paths. `selected` includes all +selected physical files; `current_files` excludes tracked historical copies +listed in `retained_versions`. Retained versions remain individually editable +and physically indexed under the existing policy. They do not become new +current-primary candidates or automatic bibliography parents merely because +`keep_both` saved them. Untracked contents of the reserved version directory +are excluded from scans of managed sources. + +For manually arrived files or recovery after a partial operation, call +`kilin.refresh_source_manifest(kilin.open_project(project.root))`. This also +runs before explicit `RAGSession.refresh_sources(project)` indexing. A failed +physical batch may leave successful copies or deletions in place; provenance +and semantic reconciliation describe the actual completed portion, not the +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 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 +`session.refresh_source_metadata()`. The returned `SourceMetadataRefresh` +contains a new inspection, suggestions and welcome prompts regenerated from +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. Suggestion generation uses physical-file eligibility, +independently of role-aware retrieval views. + +## Write safety, tracing and replay + +A stable `.source_manifest.json.lock` sidecar uses the existing cross-process +advisory ownership protocol. It is created on explicit editing, initialization +or lifecycle refresh of an existing manifest, not on read, and remains on disk after releasing the lease. Do not remove a +sidecar that could be in use. A competing writer or a stale revision, +exact-content digest, root, source selection, or changed discovery outcome +raises `SourceManifestConflict`. +Create a fresh preview rather than overwriting another editor's work. A no-op +does not advance revision or rewrite the manifest. Atomic replacement preserves +the previous file on a failed write; it is not a cross-file transaction or a +power-loss durability guarantee. + +If supplied with a caller-owned trace logger, a successful mutation emits +`source_organization.committed` with previous/current revision and SHA-256, +and the committed state under `source_organization`. No event is emitted for +a no-op. Trace failures after publication are reported by `result.trace_error`; +the returned snapshot is still committed and must not be retried as if it +had rolled back. Lifecycle refresh emits `source_organization.reconciled` +with the same state and identity fields when it changes the manifest. Initial +creation is part of the existing creation operation, not a separate mutation. +System-test validation requires the current semantic command protocol and +the complete chronological history, including for default-only assignments. +Recorded creation and lifecycle observations, accepted revision/digest, and +question-start identities must form a consistent history ending at the saved +semantic state. Explicit edits, declarations and automatic-discovery outcomes +are supported. Direct core mutations without corresponding replayable engine +commands are not replayable. See +[semantic source organization in system testing](system_testing.md#semantic-source-organization). + +The [headless engine protocol](gui_protocol.md#semantic-source-commands) +exposes these same operations with a correlated request and an opaque +server-side preview. It records explicit command inputs and outcomes in the +project trace, alongside semantic lifecycle observations. The adapter uses +metadata-only session refresh after committed semantic edits; physical source +changes retain their normal indexing lifecycle. The command recording +contract is described in [Trace architecture](trace_architecture.md). + +In the desktop GUI, **Organize sources** in Workspace (or the source +organization entry in Settings > General) opens the same editor. Workspace +rows display accepted roles and active links, with subdued styling only for +active dependency sources. Right-click role, link and disconnect shortcuts +use the same preview/apply transaction; no file is moved or hidden. Newly +pending assignments prompt once when the physical operation completes. +Select one or more source-relative paths to stage role assignments or +explicit default resets, or select one to inspect and edit relationships. +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. +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 +metadata remains an inspection error. See the [GUI guide](../kilin/gui/README.md#source-organization). + +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. 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). + +Semantic recording validation and replay are described in +[system testing](system_testing.md#semantic-source-organization). Replay +re-executes accepted editor commands instead of installing the final manifest +before earlier questions. diff --git a/docs/source_pipeline.md b/docs/source_pipeline.md index af931ac7..b99e2568 100644 --- a/docs/source_pipeline.md +++ b/docs/source_pipeline.md @@ -13,7 +13,7 @@ operations should not be mistaken for one transaction: | Step | Owner / main API | Output | | --- | --- | --- | | Preview policy | `repository.scan_repository()` | Scan report with entries, selected files, skip codes | -| Snapshot / source management | Create through preparation APIs; update through explicit import/synchronization APIs | Managed copies and source manifest | +| Snapshot / source management | Create through preparation APIs; update through explicit import/synchronization APIs | Managed copies and import inventory | | File content | `sources.read_repository_files()` | `SourceFile` records | | Natural units | `sources.extract_source_units()` | `SourceUnit` records | | Chunking | `chunking.chunk_source_units()` | `Chunk` records with stable identifiers | @@ -50,7 +50,7 @@ The directory scanner's exclusions are project/source-selection defaults, not a guarantee that every secret has been identified. Especially important: **direct file selection has a separate rule from automatic directory scans**. An explicitly imported regular file may have an excluded-looking name or -extension. The managed source manifest records the selection, and +extension. The managed import inventory (`sources.json`) records the selection, and `workspace.include_explicit_imports()` keeps eligible snapshots in the RAG index scope; unsupported content can still fail extraction. Do not add a security prohibition to the GUI by reinterpreting a scanner explanation. @@ -79,13 +79,15 @@ 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 copies can remain when a later import or index refresh fails. Do not infer -that a valid source manifest proves a completed retrieval rebuild. +that a valid managed import inventory proves a completed retrieval rebuild. The optional source-card channel runs *after* ordinary chunk, semantic, lexical and graph indexing. It selects eligible documents, reuses cached @@ -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,24 +185,38 @@ 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 extractors do not compile LaTeX or prove that a cited paper supports a scientific claim. Bibliographic declarations in a `.tex` document are -resolved by `reference_check` only against files explicitly included -in the workspace source inventory. See the +resolved by the reference checker and semantic discovery only against files +explicitly included in the workspace source inventory. The accepted manifest +can link both declared databases and same-directory compiled companions during +[deterministic discovery](source_manifest.md#deterministic-bibliography-discovery). +The reference checker independently retains its consumption precedence. See the [workspace source-access policy](security.md#workspace-source-access-policy). +The intrinsic eligibility rules in `source_eligibility.py` distinguish +bibliography containers (`.bib` and `.bbl`, case-insensitively) from +independent document candidates. Both formats remain indexed physical files: +file inventories, literal scans and explicit bibliography lookup retain their +original paths and coordinates. Paper-oriented discovery, scientific-paper +cards, reference suggestions, and project reports exclude these containers +before applying selection limits. Eligibility of another suffix does not +establish that its contents are a publication. These deterministic rules do +not authorize additional reads or infer semantic relationships. Regression +coverage is in [bibliography eligibility tests](../tests/kilin/test__bibliography_eligibility.py). + The implementation uses the actual suffix-to-reader dispatch in `sources/sources.py` and its `extensions/` directory. An unsupported suffix may be decoded as text, but it is not thereby semantically parsed. PDF image @@ -232,15 +252,26 @@ projects; the active RAG pipeline passes its project's saved values. ## 5. Refreshing sources and avoiding unnecessary embeddings -A repository manifest records selected file fingerprints for change -comparison. After a source update, `RAGSession.refresh_sources(project)` -connects the new inventory to extraction, chunking and index reuse. Changes +[Accepted source organization](source_manifest.md) uses the authoritative +selected inventory for role and relationship editing and lifecycle +reconciliation. Managed imports, synchronization and removals reconcile +completed changes under the saved defaults, even after partial failures. +`refresh_source_manifest()` reconciles manually arrived selected files and +reports pending roles, retained versions and discovery proposals. Explicit +semantic edits and `RAGSession.refresh_source_metadata()` do not update +physical fingerprints, rebuild indexes or prepare source cards. + +The derived index source state (`indexes/index_source_state.json`) stores +a repository manifest of selected file fingerprints for change comparison. +After a source update, `RAGSession.refresh_sources(project)` first reconciles +semantic metadata, returning its separate outcome, then connects the new +inventory to extraction, chunking and index reuse. Changes to a reader's text or coordinates can change chunk identity even when the original file is unchanged, so reader changes need cache/evidence tests too. The [incremental-index contract](retrieval_pipeline.md#incremental-updates) owns reuse eligibility, model identity, full-rebuild fallback and which -indexes are rebuilt. Source manifest equality is not index-payload integrity; +indexes are rebuilt. Index source state equality is not index-payload integrity; `retrievals.persistence` validates that separate boundary. A refresh should not silently reuse vectors merely because a path or model ID looks familiar. diff --git a/docs/system_testing.md b/docs/system_testing.md new file mode 100644 index 00000000..3929f3d9 --- /dev/null +++ b/docs/system_testing.md @@ -0,0 +1,738 @@ +# System testing: reference inspection, replay, and comparison + +The authoritative [versioning policy](versioning.md) defines version +ownership, compatibility, and contributor obligations. + +The `kilin.system_testing` package inspects a closed, recorded project as a +reference experiment. It reads the ordinary project and conversation traces, +including archived conversations, and reconstructs the recorded user commands +in project-wide sequence order. Inspection does not start the GUI, initialize +an inference backend, load models, or download resources. Replay is a separate, +explicit operation that runs the validated history in a new workspace. +Comparison reads both existing recordings independently; optional embedding +evaluation is explicitly enabled by the researcher. + +See [trace architecture](trace_architecture.md) for the recording format and +[conversation ownership](conversation_ownership.md) for checkpoint and archive +semantics. + +## Preparing an original reference workspace + +- Create a **new** project with ordinary tracing enabled throughout. Use the + recording version supported by the installed system-testing package. +- Choose the project type, models and persistent project settings at creation. + Keep persistent settings fixed during the experiment, except for generation + settings submitted with a question and recorded as part of that request. +- Add sources through normal project operations, including selected folder + subsets and additive synchronization. Do not remove, replace, rename or + manually edit managed sources. Retain all managed copies. +- Ask questions, respond to choices and plans, and use normal conversation + creation, selection, branching, renaming, deletion, reset, feedback, + exclusion, memory synchronization and source-card regeneration commands. +- Do not manually alter templates, generated outputs, profile files, traces, + indexes, or saved feedback. Avoid cancelled or interrupted operations and + concurrent writers. Close the project before inspection or copying it. +- Renaming the project folder through KíLín is supported. The operation is + recorded as a close followed by reopening the same active conversation. + The replay retains its designated workspace name. +- Keep the original workspace unchanged. Replay requires a separate sibling + workspace path that does not yet exist. + +GUI appearance and view-only actions are not replay inputs. Older recordings +or direct core-only sessions that do not contain the required command and +creation metadata are not complete reference experiments. No migration of +traces or inference of missing commands is attempted. Regenerate references +that lack the current recording protocol. + +## Inspecting a recording + +```python +from pathlib import Path + +from kilin.system_testing import Experiment + +experiment = Experiment(Path("workspaces/010_original")) +report = experiment.validate() +print(report.valid, report.event_count) +for issue in report.issues: + print(issue.code, issue.path, issue.sequence, issue.message) +for warning in report.warnings: + print(warning.code, warning.message) + +if report.valid: + for operation in experiment.timeline(): + print(operation.start_sequence, operation.kind, operation.status) +``` + +`validate()` returns a `ValidationReport`. `issues` contains blocking errors; +`warnings` contains environmental differences and inspection limitations. +`events` preserves every successfully decoded original event in allocation +order, including logger lifecycle and other diagnostics outside command +intervals. `operations` is the candidate command timeline, even for an invalid +reference. Use `timeline()` to obtain a validated timeline: it raises +`InvalidRecordingError` with the full report if errors exist. Both methods +read fresh data; the object does not cache or repair an earlier result. + +`TimelineOperation` exposes the stable `kind`, `start_sequence`, +`end_sequence`, recorded `request`, `status`, and associated `events`. +`operation.matching("tool.choice.decided")`, for example, selects actual +recorded decisions. Each `TraceEvent` retains the relative file and hierarchy +location, original metadata, details, and separately retained exact content. +An operation interval contains intermediate diagnostics, not extra commands. +Generated titles remain diagnostic observations rather than user requests. + +## Validation contract + +Validation checks the current trace format and recording marker, counter +health and contiguous sequences, unique event identities, paired spans, +logger lifetimes, and unambiguous chronological command boundaries. A +missing counter, malformed trace, missing archive or interrupted command is +an error, not permission to reconstruct the missing history. The one +supported detached-writer case is an active conversation archived by a +recorded successful deletion. A project rename is validated using matching +request/completion markers around a successful close and internal reopening, +corroborated by recorded directory paths and the restored conversation. +Missing or incomplete rename markers, same-directory internal reopens, +mismatched active conversations, failed renames, and persistent configuration +mutations are blocking issues. Recorded absolute paths are compared +lexically in their original platform's path syntax, never opened on the +inspection machine. + +The source checks use recorded copy outcomes and historical indexing +manifests. The final managed source inventory and content hashes must agree +with the additive history. Original external paths are provenance, not +locations to reopen. Recorded folder selections and collision-adjusted +managed paths remain available in the timeline. The original source tree +need not be accessible on the inspection machine. Incidental regular +`.DS_Store` files not present in the recorded source inventory are ignored +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. 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 +history, including archived state. Question settings and interactive proposals +and responses are correlated with their core turns. A failed outer request +with a committed checkpoint has the distinct status `committed_with_error`; +it remains a blocking reference issue but its durable effect is not erased +from the candidate history. Feedback mutations are checked against their +recorded revisions and final authoritative state. + +Recorded explicit settings are interpreted using the original displayed +values or submitted request, not the current package defaults. Saved profile +settings and behavior revisions are checked against historical configuration +records. Python, platform and installed-package differences are reported as +warnings; no model availability or inference-quality check is performed. + +## Replaying a reference + +Keep the experiments in a separate repository (for example, +`KiLinSystemTests`), with original and replay workspaces at the same level so +both can be opened in the ordinary GUI. Notebooks and the comparison +reports also belong in that repository. The replay implementation itself +belongs to KíLín; it does not require an experiment repository to be initialized +as a Git repository. + +```text +KiLinSystemTests/ + run_all.ipynb + workspaces/ + 010_literature_original/ + 010_literature_replay/ # created by replay() + 010_literature.ipynb + 010_literature_comparison.json + 010_literature_comparison.md + 020_code_original/ + 020_code_replay/ + 020_code.ipynb +``` + +From a notebook in `workspaces/`: + +```python +from kilin.system_testing import Experiment, ReplayError + +experiment = Experiment("010_literature_original") +report = experiment.validate() +report.raise_for_errors() + +result = experiment.replay( + progress=lambda i, n, op: print(i, n, op.kind) +) +print(result.workspace, result.operation_count, result.validation.valid) +for difference in result.differences: + print(difference.sequence, difference.field) + print("original:", difference.original) + print("replayed:", difference.replayed) +``` + +`replay()` validates again before any execution. An optional `destination` +argument selects another absent sibling directory. By default the suffix +`_original` is replaced with `_replay`, or `_replay` is appended. Existing +paths, including empty directories and symbolic links, are refused. Move or +remove an earlier replay yourself before running another. The package never +automatically replaces or deletes a workspace. + +### Semantic source organization + +Complete recordings require creation and lifecycle observations, accepted +revision/digest and question-start semantic identity. Executed semantic +commands (inspect, preview, apply, initialize and reconcile) require +correlated requests and outcomes, including explicit edits. Validation +verifies their chronological chain, validates +explicit edits with the core's pure transformations, checks recorded automatic +relationship deltas against the proposal and requires the final saved +[semantic source organization](source_manifest.md) to match its recorded state. +Physical indexing manifests remain separate. A direct core mutation without a +correlated replayable command, missing or externally replaced metadata, +incomplete preview linkage, stale question identity, or unrecorded mutation +blocks validation. Recordings without the current semantic command protocol +are rejected, even for empty workspaces or unchanged default roles. A saved +manifest or core reconciliation history alone cannot establish a replayable +semantic history. + +Replay executes semantic commands through the ordinary headless engine. It +rebinds preview requests to the actual replay revision and digest and uses the +new single-use preview token for the corresponding apply. It never copies the +final reference manifest, trusts a historical token, or imports later files +before their recorded availability. Inherited project-type defaults and +accepted detector identities are resolved in the new environment. Explicit +historical edits, declarations, mappings and adoption requests are preserved; +a command that no longer succeeds stops replay and retains the partial +workspace. Initialization of an already initialized manifest is replayable as +a no-op; external deletion of metadata is not a supported replay input. +Physical source history is still additive: replacement, detachment and removal +remain unsupported, and arbitrary source-root relocation is not replayed. + +Comparison reports include semantic snapshots and bound source-view scope, +policy, group membership and coverage observations, including at questions. +Changed inherited policies, discovery results and physical index generation +are reported as differences rather than silently normalized. Preview tokens, +command IDs and relocated project paths are not semantic inputs. Unavailable +observations from older recordings are not treated as equal. The first +observed divergence may be a semantic observation; this is not a causal +claim. + +### Execution and settings + +Replay calls the synchronous `ChatEngine` commands used by the ordinary +frontend. It does not launch the desktop GUI. This is real execution, not a +simulation: models must be available according to the current environment +and the project settings; retrieval, routing, answering, tool calls, and +persistence run normally. Tools producing PDFs may initialize the ordinary +offscreen Qt report renderer. Recorded, compatible approvals for online +reference lookup may also result in ordinary network requests. Replay does +not force offline mode or install missing models outside the normal policies. +Only replay trusted reference workspaces, and review their operations before +execution if they contain network approvals or downloads. + +Run the notebook from the common parent directory, not from a workspace +containing `profile.ini`. The existing GUI defaults command can consult a +profile in the working directory even when requesting new-project defaults; +replay refuses that situation before creating a workspace. + +The original project type is retained. Inherited creation settings and +inherited per-question settings use current defaults. Explicit historical +settings are supplied as overrides. The original submitted form's fields +are retained, including partial backend mappings. Effort and search-depth +choices are reapplied to the current configuration. Effective profile, +behavior, tool, model and question settings are compared with the recorded +values, not forced to match them. If a changed policy makes an original +operation impossible, replay stops rather than silently changing that policy. + +The original managed source copies supply all source bytes. Copy outcomes +identify the collision-adjusted managed names and selected files; later files +are imported only at their recorded operation. Replayed source inventories +and hashes must agree with the recorded historical manifests. Original +external source paths are never opened. The final retained folder snapshot +can expose future file names to source-change previews earlier than in the +original, but not to the managed source index before import. No-effect +requests for unretained external inputs can be omitted with an explicit +reported difference. A source command with no identifiable retained input +cannot be reproduced and is rejected. Do not include irrelevant, unretained +sources in reference commands. + +Every question is executed in the mapped conversation with its recorded +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. 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, +cards, templates and outputs are produced afresh; they are not copied from +the reference. + +### Interactions and failure + +Only responses actually requested from the original user are replayed. +Option responses require the same question and a unique matching label in +the live choices; the original numeric position is not reused. An option +reordering or other option-list difference is recorded. Confirmation plans +must retain their tool, action, scope, and semantic details, including the +meaning of quick mode when selected. Ordinary model-work counts may differ +and are reported. Network approvals additionally require matching work +counts. Timing estimates are not replay inputs. An unexpected, missing, +cancelled, or ambiguous interaction stops the run; there is no fallback +choice, retry, or new approval inferred from a changed model response. + +`ReplayResult` contains the closed replay workspace path, completed operation +count, original-to-replay conversation IDs and turn UUIDs, observed +`ReplayDifference` records, and an independent validation report for the new +workspace. The replay must itself validate and contain the same sequence of +command kinds. Differences in regenerated answers are not replay failures; +answer comparison is a separate concern. The returned mappings allow later +comparison to align branches and messages without relying on generated IDs. + +On divergence, `ReplayError` gives the original operation sequence (if +known), the count of successfully checked operations, the destination path, +observed differences, and final validation when available. The partial replay +is closed if possible and retained for diagnosis; it is never presented as a +successful replay. Invalid original recordings raise `InvalidRecordingError` +before replay. Destination conflicts are rejected before execution. + +## Comparing recorded workspaces + +Once the replay exists, comparison can run independently, including from a +fresh process using the current package. It does not require a `ReplayResult`, +load the original answering model, or issue another question: + +```python +from kilin.system_testing import Experiment + +experiment = Experiment("010_literature_original") +comparison = experiment.compare() +comparison.display() +paths = comparison.save() +print(paths) +``` + +`destination` optionally selects another sibling replay. Both workspaces +must remain closed and stable throughout comparison. Validation errors are +included in the report, and an invalid or missing replay is not treated as +an empty successful run. No command pairs are inferred from invalid records. +When both recordings validate but their operations diverge, only the +unambiguous common prefix is paired. Matching uses recorded requests, +source effects, conversation/turn identities, branch prefixes, and semantic +user interactions, never answer similarity. A historical override may become +identical to a new default: its submitted value must still be preserved, +while the changed provenance remains observable. `comparison.complete` +means the full valid command histories align, not that their outputs match +or that every metric is available. + +`comparison.data` is a JSON-compatible snapshot with `format_version` +(currently 2), `original`, `replayed`, `alignment`, `summary`, `operations`, +`final_state`, `embedding_evaluation`, `files`, and `report_issues`. The +workspace sections include validation issues, recorded model/environment +provenance, command counts, final catalogs, and token coverage. Alignment +includes the mapped conversation IDs and turn UUIDs and any unmatched +command suffixes. Each operation retains intermediate stage observations, +source manifests and settings differences. Each matched committed question +is counted once, including when its turn is inherited in multiple branches. + +### Metrics and coverage + +- Text: exact saved equality, normalized visible equality and multiset + token F1 (Dice overlap of words and punctuation). Normalization removes + model thinking blocks, applies Unicode NFC and collapses whitespace, but + retains case, punctuation and numbered citations. Empty pairs are not + assigned an invented similarity. +- Evidence: Jaccard overlap of exact passages, source-file overlap, common + rank-prefix overlap, and mean absolute rank displacement of shared items. + Exact passage identity uses managed relative paths, line coordinates, + available symbol/section/cell metadata and text SHA-256. Scores and + generated chunk identifiers are not identities. Source-ranking channels + use source paths rather than passages. Ranking occurrences are paired by + recorded channel and ordinal, a descriptive comparison rather than proof + that the changed pipeline issued semantically identical searches. +- Citations: numbered bracket citations are resolved against each saved + evidence list, so renumbering alone does not imply changed evidence. The + parser reports unresolved references and is syntactic; it does not check + whether cited evidence supports a claim or whether a bracketed number in + code is a citation. +- Execution: recorded intents, tools, interaction proposals and decisions, + model-call provenance and available exact-text artifact metrics, event + counts, status, and durations. Only recorded token counts are used. Saved + turn totals and traced chat-call totals are separate observations, not + additive. Generated titles and diagnostics outside command intervals are + also retained. Nested inclusive timings are not a wall-time breakdown. + Cross-logger command timing uses recorded UTC boundaries when no matching + outer span duration is available. +- Files: final regular files in `sources`, `templates` and `outputs` are + compared by relative path, size and SHA-256. Added, removed and changed + files are distinguished. Byte changes in generated files are not semantic + differences; indexes are neither copied nor judged by their bytes. + +Unavailable measurements are `None` in Python and `null` in JSON. Means +include only available measurements and report available and total counts. +Neither an empty evidence union nor a missing trace field is replaced by +zero. Malformed optional diagnostic numbers are reported as unavailable. +No composite quality score, pass threshold, LLM judge, or correctness verdict +is computed. + +### First observed divergence + +The comparison reports the earliest observed difference among aligned model +calls, effective settings, plugin identities, context, retrieval rankings, +saved evidence and answers. The diagnostic uses the original recording's +sequence order, with the corresponding replay sequence where available. +Plugin identity changes are located at their recorded project-opening, +turn-settings or tool-execution boundary. Unknown, invalid and one-sided +plugin observations are unavailable identity comparisons, not evidence of +changed implementation. Equal normalized prompts +are not equal exact model inputs. Output changes with identical zero- or +nonzero-temperature inputs are distinguished from output changes with +unverified or changed inputs. Unlocalized changes and unavailable metrics +remain explicit. Later changed question numbers are possible downstream +observations, not evidence of causality. Unmatched operations, timing and +final file inventories are covered by the existing independent diagnostics. +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. 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 +only corroborated memory headers in the final user message. Headers must +agree with the selected-memory record's label, role and deterministic +prompt-local turn label. The label is mapped to the recorded identity for +diagnostics. Ordinary question text and memory content remain unchanged. +Obsolete, ambiguous or uncorroborated headers are unavailable. Neither model +input nor trace data are changed; raw rendered-prompt comparison still uses +the actual input. + +Functional tool-summary comparisons separate known elapsed-time and plan-time +fields. Explicit incomplete or invalid outcomes remain visible even when +both sides fail identically. Unreported completion is not proof of success. + +Closed GUI inspection after replay can append open, select and close commands. +A validated suffix consisting solely of such sessions without source changes +is annotated as inspection-only if the replay matches the preceding prefix. +Strict alignment remains divergent; substantive changes and failed commands +never qualify. A fresh replay reproduces the entire valid history. + +### Effective model settings, outcome transitions and performance + +Each paired model call retains the recorded backend, device, model source, +recognized Hugging Face snapshot revision, effective generation settings +(including suppression fields), template settings, thinking flag, token +counts, and termination reason. Comparisons are by enclosing stage and +occurrence, not by semantic equivalence. Snapshot revisions are recognized +lexically in the matching repository cache path. Unversioned local model +paths do not establish revision identity; no model files are opened. + +`summary.model_reproducibility` counts input calls and unpaired inputs in +matched commands. Each equality statistic has `equal`, `available` and +`total` counts. Conditional categories require equal recorded model identity, +effective settings, exact rendered prompt and input-token count. Metadata- +normalized structured prompts are reported separately and never used to +qualify exact-input reproducibility. For zero and nonzero temperatures the +report records `identical_inputs`, `available_outputs` and `equal_outputs`. +Missing, ambiguous or incomplete input metadata cannot qualify. Equal output +text is not proof of answer correctness or a universal determinism guarantee. + +Tool outcomes are `complete`, `incomplete`, `unknown` or `not_applicable`. +An absent tool summary with no recorded tool start is not applicable; absence +of a completion flag in a returned tool is unknown. Explicit validation +failure, incomplete items or recorded incomplete completion takes precedence +over a nominal success. Completion of a trace span or existence of a filename +alone does not demonstrate success. The paired `transition` describes a +reproduced completion/limitation, potential regression, possible improvement, +changed outcome or unavailable comparison. Historical generator hints remain +reference observations. Saved output paths are observations; the independent +final file inventories retain their actual hashes and presence. + +The `performance` section covers each independently valid full workspace, +including overhead outside matched commands. Categories select corroborated +recorded spans for project initialization, indexing, model loading, retrieval +and embeddings, model inference, and question duration. Intervals within each +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 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. + +### Optional embedding evaluation + +For semantic answer comparison, explicitly choose a local or already cached +embedding model, and preferably pin its revision for repeated experiments: + +```python +comparison = experiment.compare( + embedding_model="your/local-or-cached-embedding-model", + embedding_backend="auto", + embedding_revision=None, +) +comparison.display() +comparison.save(overwrite=True) +``` + +A single evaluator instance embeds both normalized visible answers and is +closed after use. Cosine similarity is reported in [-1, 1]. The evaluator +uses the same model on both sides regardless of their original embedding +settings. The evaluation model, backend, requested revision and resolved +source are reported when available. Downloads, retries and fallback models +are not requested. Model loading or embedding errors leave the metric +unavailable with an explanation. No additional answer-generation calls are +made. With `embedding_model=None` (the default), no model is loaded. + +### Reports and batch execution + +`display()` renders Markdown in a notebook or prints it in a terminal. +`save()` writes `_comparison.json` and +`_comparison.md` beside the workspaces, removing the original's +`_original` suffix. Existing regular report files are replaced only with +`overwrite=True`. This flag applies to reports, not replay workspaces. +Each report file is published atomically, but the pair is not a filesystem +transaction. The JSON report contains saved answers and potentially +sensitive trace observations; keep it with the private experiment data. + +A root-level batch notebook can enumerate `workspaces/*_original` and +compare each independently. Leave replay disabled unless explicitly +requested, never automatically delete an existing replay, and collect errors +per experiment so a divergent run does not suppress unrelated comparisons. + +## Limits and ownership + +Inspection assumes a stable, closed workspace. It does not acquire a writer +lock, so it creates no lock companions, nor does it make an atomic snapshot +of a concurrently changing directory. Copying or reading files can affect +filesystem access times; no workspace file contents are changed by inspection. +Only retained recording evidence is validated. It is not a cryptographic +attestation of all past actions: unrecorded actions or changes restored before +inspection cannot always be detected. Templates and generated outputs do not +have a complete historical mutation inventory, so the preparation protocol +prohibits manual changes. Validation does not authenticate the producer or +certify answer quality, verify real-model availability, or compare generated +indexes or outputs. A valid report establishes the checked recording +contracts, not deterministic reproducibility of model inference. + +Replay assumes the original remains closed and unchanged throughout the run. +It does not hold a lock on the reference and must not be used with concurrent +writers. Environment and real-model availability remain the researcher's +responsibility. Replay establishes that the recorded operations and their +required durable effects were reproduced, not that regenerated model outputs +are identical or correct. Comparison is a separate read-only operation and never executes replay. + +The [module map](module_map.md) lists the package modules and their tests. + +## Managed replay and reference publication + +The low-level `Experiment.replay()` requires an absent destination. +Use the managed API to make the policy for an existing replay explicit: + +```python +from kilin.system_testing import Experiment + +experiment = Experiment("workspaces/010_original") +action = experiment.run_replay(existing_replay="archive") +print(action.status, action.archived_workspace, action.error) +``` + +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. 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. +Model identities and resolved revisions remain in the recorded trace model +observations. A missing historical receipt is reported as unavailable; the +inspection machine's environment is never attributed to a retained replay. +Failure to publish provenance is reported separately from replay completion. +Receipts are local integrity observations, not cryptographic attestations of +which process executed the code or protection from a malicious editor. + +Generators can publish an optional sibling `_reference.json` receipt: + +```python +from kilin.system_testing import publish_receipt, inspect_receipt + +report = experiment.validate() +report.raise_for_errors() +publish_receipt(experiment.workspace, report, coverage=[]) +print(inspect_receipt(experiment.workspace, report)) +``` + +Publish only after the reference is complete and closed. The receipt records +the original event prefix, command count, managed source/template/output +hashes and generator coverage observations. It is never rewritten by an +ordinary replay or inspection. Later closed GUI inspection may extend the +trace without modifying the published prefix or managed files. Additional +substantive commands are reported as an extension; changed prefix or file +contents are reported separately. These observations do not override the +recording validator or block intentionally extended valid references. +Older or manually recorded references without receipts remain usable. + +Comparison reports include `reference_publication` and `replay_execution` +observations, including whether the recorded input matches the current +reference exactly or only a historical prefix. These receipts do not +replace structural validation or strict +command alignment. No historical environment is inferred when it was not +recorded. The optional receipt does not fingerprint every workspace file or +detect changes that have been restored before inspection. + + +## Scripted references and notebook batch workflows + +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 + supply a trusted function receiving the recorder, explicit project + settings, the expected operation sequence, and a coverage callback. + Staging occurs in `_recordings/` beside `workspaces/`, outside normal GUI + discovery. Successful closed recordings are validated before publication + and receive a reference receipt. Failed staging recordings remain for + diagnosis. Existing originals, replays and receipts are protected. + Scripted interactions allow only explicitly approved local plans and + uniquely matching option labels. Recipe hints are coverage observations, + not scientific judgments. The adapter uses the ordinary engine and does + not change answer generation, retrieval, routing or tool behavior. +- `kilin.system_testing.batch` provides `discover_originals`, `run_batch`, + `load_snapshot`, `collect_issues`, `group_issues` and `save_batch_summary`. + It manages replay through `Experiment.run_replay`, compares each pair + once, and supplies that same snapshot to generated comparison and answer + notebooks. The caller controls the replay policy, report overwrite, + notebook refresh and optional evaluation model. Templates are packaged + resources in `kilin/system_testing/_notebooks/`; only these templates + are executed automatically. Local template copies are not required or + consulted. Historical snapshots are explicitly + distinguished from current comparisons; failures do not silently fall + back to stale data. +- `kilin.system_testing.analysis` presents comparison snapshots as escaped + HTML and Markdown. It includes answer and operation explorers, batch + summaries, event inventories, and optional exact local trace text + verified against its recorded hashes. Optional local event details and + exact-text lookups use the same trace decoder and reference verification + as validation and replay. Each workspace is decoded once per render, + across conversations. Local decoding issues remain visible, including + issues in incomplete standalone recordings. Event details with decoding + failures are labelled unverified; they may contain independently expanded + fields and are not claimed to be either raw or fully verified data. + Original trace files are unchanged. Rendering does not load models, + revalidate a saved report, or change its metrics. + +### Release verification + +A release check is a comparison between a fixed reference collection and +replays generated by the current implementation. Set the existing-replay +policy to `archive` for fresh replays; retaining or comparing saved +workspaces is useful for diagnostic inspection but does not constitute a +fresh replay. No longitudinal benchmark or automatic release verdict is +produced. + +The batch dashboard separates execution status, paired measurement +coverage, behavioral agreement and tool-outcome transitions. A complete +comparison may still contain review findings. Blocking recording, replay, +alignment, comparison and requested artifact failures are critical; +intermediate failed stages in otherwise valid matched commands, incomplete +tool outcomes, unresolved citations and configuration or behavior changes +require review. Ordinary text differences, known relocation differences, +nonzero-temperature variation with identical recorded inputs and historical +generator hints are informational. A reproduced limitation is not evidence +of a new regression, and an incomplete-to-complete transition is not proof +of scientific improvement. + +Aggregate agreement counts sum observed numerators and denominators, not +experiment-level percentages. Each metric includes available observation +counts and snapshot coverage. Current-invocation aggregates exclude saved +comparison snapshots; partial comparisons retain their measured common +prefix without implying complete execution. A report-only dashboard labels +its observations as saved. Missing observations are never assumed equal. + +Event-count differences are attributed to aligned operations when the +stage counts reconcile with the independent workspace inventories. The +remaining differences are reported outside matched commands. When the +attribution is unavailable, only reconciled workspace totals are reported. +Related observations are grouped by aligned operation and diagnostic +category, retaining every underlying observation, including independent +recording-side sequences. Grouping does not establish causation. The answer +explorer's difference filter includes identical answers with incomplete +outcomes, citation problems or execution differences; timing alone is not +a behavioral difference. + +For example, in a separate experiment repository with `workspaces/` and +one batch notebook: + +```python +from pathlib import Path +from kilin.system_testing.batch import discover_originals, run_batch +from kilin.system_testing.analysis import batch_overview + +root = Path.cwd() +reports, runs = run_batch( + discover_originals(root / "workspaces"), root, + run_replay=False, run_comparison=True, save_reports=True, + overwrite_reports=True, save_visual_analysis=True, + run_notebooks=False, refresh_notebooks=False, +) +html = batch_overview(reports, runs=runs) +``` + +The workflow modules do not add required installation dependencies. For +notebook creation and execution, install JupyterLab (or the corresponding +`nbformat`, `nbclient`, `jupyter_client` and `ipykernel` packages) in the +same Python environment as KíLín. These dependencies are imported only at +the notebook stages. `mistune` 3 is optional for formatted Markdown answers; +without it, answer text remains escaped. Normal system-testing imports do +not load Jupyter, a model backend or Qt. Generating and replaying actual +experiments still requires the configured KíLín backend and models. + +## Plugin provenance and availability + +Configuration snapshots record the project-type and configured tool +identities; tool spans record the selected implementation. The environment +receipt records the required plugin identities at fresh replay preflight. +Known changes in version, API/schema or content digest are environment +differences, not answer-quality assessments. Older absent identities remain +unknown. Historical validation, retained replay inspection and comparison do +not require importing the original plugins. Fresh replay resolves the current +compatible requirements before creating a destination, loading models or +archiving a previous managed replay. It does not reconstruct historical code. +See [the plugin API provenance contract](PLUGIN_API.md#system-testing-provenance-and-replay). diff --git a/docs/tool_packages.md b/docs/tool_packages.md index c589cb3d..720c6a75 100644 --- a/docs/tool_packages.md +++ b/docs/tool_packages.md @@ -2,18 +2,22 @@ ## Ownership and boundaries -KíLín's registered tools are Python subpackages under `kilin/tools/`. -The central registry (`kilin/tools/_registry.py`) connects a stable tool -identifier from a project type to `parse_settings` and `run`. It can also -register an optional `workspace_resources` function. Project-type JSON may +KíLín's bundled tools are Python subpackages under `kilin/tools/`. +The registry (`kilin/tools/_registry.py`) discovers distribution and user +packages exposing +a `PLUGIN` descriptor, validates their contracts and binds each descriptor +to its observed package root. The descriptor connects a stable tool identifier +to `parse_settings`, `run` and optional hooks such as `workspace_resources`. Project-type JSON may select and configure registered tools, but cannot load arbitrary code. -Each tool owns its implementation, its validated packaged `defaults.json`, -and its local `README.md`. When a tool needs packaged templates, those +Each bundled tool owns its implementation, its validated packaged +`defaults.json`, and its local `README.md`. When a tool needs packaged templates, those resources also live in its package. The workspace planner rejects files outside their declaring tool package. Only the configured resources are installed into new project workspaces. The core always creates the `templates/` folder, including when the selected tools have no templates. +Declared template files are installed under `templates//`. +Each tool owns its formats and validation rules. The following files and directories form private infrastructure rather than tools callable by project types: @@ -33,10 +37,11 @@ but shared infrastructure should not depend on a tool's configuration. ```text kilin/tools/example_tool/ - __init__.py # Tool's documented exports + __init__.py # PLUGIN descriptor and documented exports tool.py # Settings dataclass, parser, runner _configuration.py # Strictly validate defaults on import defaults.json # Tool-owned settings and internal parameters + settings_info.json # Descriptive metadata for settings README.md # Explanation of every default templates/ # Only when this tool ships resources ``` @@ -47,9 +52,14 @@ remains an optional private GUI adapter (`kilin/gui/_report_pdf.py`), passed to the tool as a callback. The tool does not import the GUI, and it saves validated Markdown even without a PDF backend. Other tools can add private modules as needed. -All registered built-in tools use packages, not flat `.py` modules. Use -their documented package exports; obsolete flat-file import paths have no -compatibility aliases. +All registered built-in tools use packages, not flat `.py` modules. New +packages are discovered without editing a central implementation list. +User packages follow the same descriptor contract; see the +[plugin API](PLUGIN_API.md#user-storage-discovery-and-validation) for their +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. ## Generated output safety @@ -74,7 +84,7 @@ Markdown report remains available. ## Tool-owned settings information -Every registered tool supplies a `settings_info.json` next to its +Every existing bundled tool supplies a `settings_info.json` next to its `defaults.json`. The metadata contains the descriptive `title`, `summary` and `description` of **each public key in `SETTINGS`**, with lowercase keys matching the normalized names returned by the tool-settings API. @@ -84,7 +94,9 @@ markup. The core resolves this metadata through `kilin.get_settings_info()` catalog. Core validation verifies the metadata keys against the tool's `defaults.json` without loading a model. Unknown or invalid descriptions are not used by tool execution and cannot -change a tool's behavior. Future interfaces can consume the same metadata. +change a tool's behavior. Future interfaces can consume the same metadata. A minimal plugin may omit +the help file; the metadata interface then returns an empty mapping. Supplied +metadata remains subject to validation. ## Configuration precedence @@ -145,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 @@ -157,7 +171,7 @@ that every passage was read or that the source supports the claim. ## Creating a tool Follow the [registration and extension checklist](extension_interfaces.md#implementing-a-built-in-tool) -for the parser, runner, registry entry, project intent, packaging and tests. +for the parser, runner, descriptor, project intent, packaging and tests. The layout and shared-service boundary above remain part of that contract. A tool needing workspace files declares resources; it does not copy them from a GUI handler. Tool-specific parameters, outputs and confirmation cost @@ -184,7 +198,10 @@ that an unsupported model obeys it. ### Internal thinking policy -Each tool declares one `MODEL_CALLS` section in its packaged `defaults.json`: +The existing bundled tools declare a `MODEL_CALLS` section in their packaged +`defaults.json`. A minimal plugin may omit this section or the entire file; +its internal calls then inherit the active session. When supplied, the section +must satisfy the same strict validation: ```json { @@ -256,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 new file mode 100644 index 00000000..357195f5 --- /dev/null +++ b/docs/trace_architecture.md @@ -0,0 +1,401 @@ +# Project and conversation diagnostic traces + +The project and conversation traces share a single event-number namespace +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 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 + ownership companions, must not be removed while writers are active. + +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. 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 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 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 +an incomplete-recording flag should therefore be treated as reasons to reject +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 +summary status and completion time remain available for inspection. Sampled +progress checkpoints retain event identity as well. Top-level event counts +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` 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 +files. Initialization stops if a history directory or JSON candidate is +unreadable or linked, because the recorder cannot establish that older +numbered events are absent. Ordinary counter allocation does not rescan the +trace history. + +## Recording coverage + +The GUI maintains a project trace alongside the active conversation trace. +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. + +### Project operations + +Project creation starts its trace only after the destination has been safely +reserved. The creation trace is owned by workspace preparation and is closed +before the profile is published. Its completion and closing writes remain +inside the creation rollback boundary: a strict diagnostic failure removes +the new trace and other files owned by that attempt. Warning policy preserves +successful creation and marks recording incomplete where possible. A creation +conflict does not write to the occupied destination. Caller-owned sinks retain +their caller's lifetime and receive completion after profile publication. + +A successful creation or subsequent import emits `workspace.prepare.started`, +`workspace.source.copied` for each processed source, and +`workspace.prepare.completed`, correlated by a `batch_id`. The start records +requested source paths, selected files, project type, import policy, and +profile settings. Each copy event records the original source, its kind, the +managed workspace-relative destination, and the actual copied and preserved +original-relative filenames. For a direct file, the managed destination is the +file itself, which may have been renamed to avoid a collision. For a folder, +append each copied relative filename to the managed destination. Do not infer +historical imports from the current external directory contents. + +Synchronization records `workspace.sync.started`, the applied decisions in +`workspace.sync.file` or `workspace.sync.detached`, and +`workspace.sync.completed`, with a common batch ID and actual results. Source +removal and explicit resource edits also leave project diagnostics. These +operations are not automatically considered safe to replay: additive source +imports can be reconstructed from the retained workspace copies, whereas +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 `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 +`indexes/index_source_state.json`. Comparing these +manifests can detect changed or removed indexed source content. Source-card +regeneration is recorded separately. Question-related model switches and +inference, evidence, and mandatory checkpoints remain in conversation traces. + +Explicit [semantic source-manifest mutations](source_manifest.md) emit +`source_organization.committed` when tracing is supplied, with the previous +and committed revision/digest and the state under `source_organization`. +Lifecycle reconciliation emits `source_organization.reconciled` with the +same identity and state fields on a changed manifest. Neither is the physical +`source_manifest` field of index events. Replay requires complete semantic +command and lifecycle chains, including creation and opening observations, +regardless of whether any roles or relationships were edited. See +[semantic replay](system_testing.md#semantic-source-organization). + +The headless engine records explicit source-organization commands in the +project trace as `gui.source_organization..requested` and +`.completed` or `.failed`, with a common `command_id`, the original JSON +request and the resulting identity, proposal or error. Apply additionally +retains the original `preview_request` and `preview_command_id`; the opaque +preview ID is a live engine token, not a portable replay input. Rejected +foreign-project or malformed envelopes never write to another project's +trace. A completed mutation may include `refresh_error` or `trace_error`; +these are independent post-publication diagnostics, not rollback markers. + +`gui.source_organization.observed` records opening and lifecycle outcomes, +including the semantic revision, digest, canonical state, pending paths and +any independent reconciliation error. The question-request span captures +`source_organization_revision` and `source_organization_sha256` (or +`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 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. + +Grouped source-first operations retain the physical citation records. Their +`retrieval.sources.ranked` diagnostics describe the selected anchors and +member paths under `source_operation`, including semantic revision, manifest +digest, selection/index generation, effective policy and scope. Final +`retrieval.coverage` and `retrieval.tool.coverage` report requested/selected/ +represented groups, represented anchors, unique physical evidence counts, +unselected groups and unavailable members. A shared physical passage is +recorded once and may represent several selected groups. These diagnostics +are representation records, not full-review or replay certificates. + +### Configuration and lifecycle + +The GUI emits `gui.project.creation.settings` with the original request, +`explicit_settings`, and `provenance`. A direct API request is treated as +explicit. A full GUI settings form is compared recursively to the defaults +last sent for that project type, and the comparison baseline is retained in +`displayed_defaults`. Unchanged fields are inherited; lists are treated as +whole values. Reaffirming a displayed value is indistinguishable from leaving +it unchanged. If the comparison baseline is unavailable, explicit settings +are recorded as null rather than guessed. The original request is preserved +regardless of provenance; this classification does not change the settings +applied during ordinary creation. + +`gui.project.open` spans identify creation, resumption, or an internal reopen +with the selected conversation ID. `gui.project.configuration.effective` +records the effective profile, effort levels, router models, search depths, +source-card settings, behavior and tools after saved defaults are established. +A failed diagnostic snapshot is recorded explicitly. Subsequent saved profile, +model, tool, behavior and card settings changes are traced in the project. + +Each activation retains its own configuration event and global sequence +number. The first complete configuration retains all settings groups and +additional fields. When all settings other than the observed project path +match the most recent complete observation, store one direct reference: + +```json +{ + "configuration_content_reference": { + "sequence": 124, + "sha256": "<64 lowercase hexadecimal characters>" + }, + "project": "/exact/recorded/workspace/path" +} +``` + +This is the only compact configuration representation, whether the workspace +path is unchanged or has moved. The digest is SHA-256 of the referenced +payload with only `behavior.project` removed, encoded as UTF-8 JSON with +sorted object keys, compact separators, unescaped Unicode, and no nonfinite +numbers. Array ordering and scalar representations are significant. +Inspection restores `behavior.project` from `project`, without normalizing +its spelling or consulting the current filesystem. An explicit null value is +preserved; an absent project field is ineligible for compaction. All other +behavior values and unknown fields remain significant. A reference is written +only when it is smaller than the full payload. The reserved reference field +cannot be mixed with full settings groups. + +Changed settings require a new full observation. Restoring settings after a +different full observation also writes a new full observation. References +point directly to the latest full snapshot, never to another reference or a +superseded snapshot. + +Compact configuration and source observations select their payloads and +reserve their sequences under the project publication lease. Each uses the +project trace already read for that publication and requires no separate +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 +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. Inspection does not +rewrite the original files. The current format supports both full observations +and `configuration_content_reference` payloads. + +### Repeated source snapshots + +The same direct-reference mechanism reduces repeated project-level source +payloads without eliding operations. For completed non-turn observations the +following fixed groups can be replaced by `source_snapshot_reference`: + +| Event | Snapshot fields | +| --- | --- | +| `source.scan.completed` | `selected_files`, `entries` | +| `index.check.completed` | `source_manifest`, `expected_metadata`, `saved_metadata` | +| `gui.source_organization.observed` | `source_organization`, `selected`, `pending`, `pending_roles`, `retained_versions` | + +The top-level `source_snapshot_reference` field is reserved for this format. +The reference has the same `sequence` and `sha256` structure as the +configuration reference. Its digest covers exactly the omitted fields as a +canonical JSON object. Other details (including historical paths, completeness, +index reuse decisions, semantic revision/digest, and lifecycle outcomes) stay +inline. A changed group is stored in full. A complete scan is required, and +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. +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. 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 +comparison. Decoder issues are shown alongside partial local diagnostics. +Invalid event payloads remain available as explicitly labelled unverified +details, which may contain independently decoded fields. They are not claimed +to be raw or fully verified, and current workspace state never repairs them. +Raw hierarchy inspection remains available independently; exact model text +must additionally match its saved comparison-report digest. + +### Shared semantic manifests + +`source_organization.committed`, `source_organization.reconciled`, and +`gui.source_organization.apply.completed` can replace an unchanged top-level +`source_organization` field with `semantic_snapshot_reference`. This reference +contains a sequence number and SHA-256 digest of the canonical JSON object +`{"source_organization": }`. The manifest's own +recorded revision and file digest remain separate and unchanged. + +The target is the latest preceding raw full semantic observation among these +three event types and `gui.source_organization.observed`, in the same project +trace. Mapping order is immaterial; scalar types, array order, and all manifest +fields remain significant. References are direct, digest-checked and emitted +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 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 +reference. A first opening after a semantic change may therefore retain one +additional full manifest as its source-group target. + +All event identities, sequencing, span and command correlations, requests, +revision chains, errors, refresh results and nested inspection data stay +intact. In particular, an inspection result is not assumed to equal the +earlier committed state. Shared manifests resolve before source groups, so +validation, replay, comparison, analysis and receipt hashes see the original +full details. Malformed, ambiguous, wrong-scope, mixed, forward, chained, +superseded and digest-invalid references are blocking recording issues. +Resolution never consults the workspace's current semantic manifest. + +### Session closure + +`gui.project.closed` records the selected conversation when the GUI releases +the project. A standalone RAG session similarly records its initialization and +closure in its project sink; switching its conversation does not change that +sink's lifetime. The replacement conversation sink must have the same tracing +activation as the project sink. A mismatch is rejected before any session or +ownership change. Changing activation requires closing the session and +opening another with the desired configuration. + +If RAG initialization fails, constructed model sessions and owned trace sinks +are closed, including when final readiness notification fails. Cleanup errors +are attached to the original exception rather than replacing it. + +### Conversation operations + +The shared project trace records the conversation catalog and active identity +at each opening. Explicit create, select, rename, delete, and reset commands +have `gui.conversation.*` operation spans with request data, results, and +terminal status. Creation records whether the command created or reused an +empty conversation, the selected conversation, and its branch origin and +inherited turn count, if any. Inherited turns retain their persistent UUIDs; +branching does not ask their questions again. Deletion records the archive +and replacement identity, including whether a replacement was created. +Selecting the already active conversation is recorded as a no-op. Generated +titles are separate diagnostics, not explicit rename requests. + +Each `gui.question.request` span in the conversation trace retains the +question passed to the backend, the title question, requested retrieval +count, generation settings, effort selectors, and active conversation ID. +The GUI's full-form generation settings are compared with the saved profile +before applying the request. Reaffirming an unchanged value is not separately +observable. Partial/direct requests are explicit. The resolved selection is +recorded in `gui.question.settings.resolved`. The core turn is correlated to +the request by its parent span. `state.checkpoint.committed` and +`gui.question.saved` identify the persisted turn UUID and checkpoint, so the +original request is not confused with a branch's inherited turn. Settings +changes performed while answering are part of that question operation, not +additional user commands. Direct RAG calls retain their own core turn input +and checkpoint diagnostics, but are not GUI command recordings. + +The GUI request span also covers delivery of the saved answer to the frontend. +A delivery failure can therefore fail that outer span after a successful core +turn and checkpoint. Validation must inspect the persisted checkpoint and +core outcome independently of the GUI request's terminal status. + +Routing and tool choices record a proposal and decision (or failure) with a +common interaction ID and turn correlation. Decisions retain whether a +callback was actually invoked, its response, and the chosen option label as +well as the original index. Plans record the semantic action, confirmation +policy, and whether confirmation was requested. Automatic defaults are not +user choices. Invalid or ended GUI input and callback failures are recorded +separately; recording them does not change ordinary cancellation behavior. +A replay must resolve the original label/action against the newly offered +choices, not blindly reuse the index. + +Feedback and memory exclusions record their requested mutations and revision, +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. 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. 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 +files and identities. An unrecorded change cannot always be detected from +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. + +For offline inspection of a closed workspace, see +[System testing](system_testing.md). The validator expands compact span +terminals, checks global event identity, and uses explicit command boundaries +rather than inferring commands from display titles. diff --git a/docs/trace_recording.md b/docs/trace_recording.md index a89f88c5..4b94b83c 100644 --- a/docs/trace_recording.md +++ b/docs/trace_recording.md @@ -1,13 +1,16 @@ # Diagnostic trace recording -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. +The authoritative [versioning policy](versioning.md) defines version +ownership, compatibility, and contributor obligations. + +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 -A `RAGSession` creates an enabled trace when `trace=None` (the default): +A `RAGSession` creates enabled project and conversation traces when +`trace=None` (the default): ```python session = kilin.RAGSession(project_directory) @@ -34,20 +37,42 @@ events. This **does not disable conversation persistence**. The session still holds exclusive ownership of its conversation path and saves checkpoints there; see [conversation-file ownership](conversation_ownership.md). -`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. +Tracing activation is fixed for a RAG session. `switch_conversation()` requires +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` 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 -The engine creates a project before opening its trace/conversation files; -precreating a trace inside a fresh destination would make that destination -occupied. Core preparation can use a caller-owned external sink and emits -preparation events only after reservation. For a later import, create/open -the project first, start the trace, then call -`add_project_sources(..., trace=trace)`. +The core reserves the creation destination before opening its project trace; +precreating a trace inside a fresh destination would make it occupied. The GUI +requests this ordinary tracing behavior. Core callers can request it with +`prepare_sources_workspace(..., trace=kilin.TraceConfig(enabled=True))`. +The configuration must not specify a path because automatic allocation may +choose a different destination. The preparation owns and closes this sink. +Its final completion and closing writes occur before profile publication, so +strict failures at either point still roll back the new workspace. Warning +policy allows successful creation while marking the recording incomplete. +Caller-owned sinks are also supported; omitting the argument preserves +untraced low-level preparation. A caller-owned sink remains open and receives +completion after publication; an exception from that diagnostic write cannot +undo the published workspace. For a later import or synchronization, pass +the opened project sink to `add_project_sources(..., trace=trace)` or +`sync_project_sources(..., trace=trace)` respectively. GUI creation conflicts and preparation failures before session switching do not append errors to the previous project's trace. The @@ -60,40 +85,59 @@ 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. A legacy `"mode": "forensic"` string is still -emitted in the `trace.started` event for readers of older files; this is a -fixed historical metadata value, not a configuration option. Existing JSON -files with a `"standard"` or `"forensic"` marker remain readable. Previously -stored events are preserved when reopening, without retroactive filtering. +does not remove this state. `trace.started` records the scope, output path, +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 +recorded in `project.json`. An enabled RAG session creates its own project +sink unless the caller supplies a shared `project_trace`; the owner closes +the sink. The GUI shares one project sink through conversation switches. +See [Trace architecture](trace_architecture.md) for event contracts, settings +provenance, sequence scope, ownership, and completeness limitations. 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 → @@ -107,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. @@ -117,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 @@ -133,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 @@ -149,32 +203,30 @@ The activity list remains saved with the turn when optional tracing is off. Activity event writes are throttled like progress updates; normal checkpoint writes flush all pending events. -If the window must terminate the engine, the trace retains events already -written before termination. A mid-turn exit can leave an operation without +Normal GUI closure requests engine cleanup by ending command input. For a +completed, idle project, this writes `gui.project.closed` and the closing +`trace.closed` events for the conversation and project loggers. If cleanup +fails or the window must forcibly terminate an unresponsive engine, these +closing events may be absent. The trace retains events already written +before termination. A mid-turn exit can leave an operation without a completion/failure event; reopening numbers later turns above it. Events other than throttled progress and answer-activity updates rewrite the file 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** with an error records the failure in the trace and -adds no turn; the GUI shows the error and puts the question back. 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 @@ -194,8 +246,24 @@ 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 + +The shared project trace preserves explicit conversation lifecycle, feedback, +and manual memory commands independently of conversation selection. The +conversation trace records each question request and the core turn, including +persistent checkpoint and turn identifiers and correlated interactive choices. +Generated titles and automatic memory synchronization are diagnostics rather +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. 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 @@ -212,6 +280,25 @@ The project targets Python 3.12; run these tests under that interpreter and verify the OS-specific file-lock behavior on supported platforms. +### Project renaming + +A successful GUI project rename records `gui.project.rename.requested` in +its original directory before closing the session and releasing all trace +leases. After the folder move and successful internal reopening, the same +project trace records `gui.project.rename.completed`. Both point events +include the same `rename_id`, `source_directory`, `destination_directory`, +and `conversation_id`. Paths are historical provenance. Neither a span nor +an owned trace file is held across the filesystem move. Failed renames do not +emit a successful completion, even if the old workspace is reopened during +recovery. A no-op rename emits neither marker. System-test validation requires +both matching markers for every successful internal reopening; independent +path observations alone cannot substitute for a recorded rename command. + +Shared trace publication uses atomic UTF-8 replacement. Transient Windows +access-denied or sharing/lock violations during replacement receive a bounded +one-second retry using the same closed temporary file under the existing +lease. Persistent failures retain the ordinary diagnostic failure policy. + ### Change impact and verification Diagnostic writes can fail without the same policy as a required checkpoint. diff --git a/docs/versioning.md b/docs/versioning.md new file mode 100644 index 00000000..739b65eb --- /dev/null +++ b/docs/versioning.md @@ -0,0 +1,426 @@ +# Versioning policy + +This document is the authoritative versioning policy for KíLín. It applies to +human contributors, maintainers, and AI coding agents. MUST and MUST NOT +identify requirements; SHOULD identifies a recommendation that requires a +reason for departing from it. The technical contracts remain defined in their +own reference documents. If implementation and policy disagree, report the +inconsistency rather than inventing a different versioning rule. + +## Scope and release transition + +KíLín `0.1.0b1` is the first published beta. The next intended release is +`0.1.0b2`, followed by release candidates and the first stable release, +`0.1.0`. This policy defines the versioning contracts for beta 2 and later. + +Versions identify different objects and MUST evolve independently: + +| Object | Scheme | Authority | Initial beta 2 value | +| --- | --- | --- | --- | +| KíLín application | Canonical PEP 440 release | `pyproject.toml`; runtime `kilin.__version__` | `0.1.0b2` | +| Individual tool | Semantic Versioning 2.0.0 | `Tool.version` | `0.1.0` for bundled tools | +| Individual project type | Semantic Versioning 2.0.0 | JSON `version` | `0.1.0` for bundled types | +| Tool API | Positive integer | `kilin.tools.PLUGIN_API_VERSION` | `1` | +| Project-type schema | Positive integer | `kilin.project_type.PROJECT_TYPE_SCHEMA_VERSION` | `1` | +| Trace format | Positive integer | `TRACE_FORMAT_VERSION` in `kilin/_trace_project.py` | `1` | +| Other persistent formats | Format-specific | Owning module's declaration | Existing values | +| Individual project instance | Creation provenance, not a release number | Saved creation metadata | Actual creation identity | + +An application release MUST NOT automatically increment any plugin version, +compatibility generation, or persistent-format version. A stable application +release MUST NOT automatically promote tools or project types to `1.0.0`. + +## Application version + +`pyproject.toml` is the only authoritative application release declaration. +Runtime consumers MUST use `kilin.__version__`, which resolves the executing +source checkout's version when available and the installed distribution +version otherwise. Traces, project creation metadata, replay receipts, CLI +output, and GUI responses MUST use that same value. Recording validation MUST +also compare recorded application versions against the inspecting runtime's +`kilin.__version__`, without rewriting historical values. Third-party +dependency versions can be read from their own installed distribution metadata. +Build and release tooling that runs before installation MAY read the +manifest directly; it MUST NOT introduce an independent application version. + +KíLín uses the canonical PEP 440 subset `MAJOR.MINOR.PATCH`, +`MAJOR.MINOR.PATCHbN`, and `MAJOR.MINOR.PATCHrcN`. Components are nonnegative +ASCII decimal integers without leading zeroes; beta and release-candidate +numbers start at 1. The supported native build range is `1` through `999` for +the prerelease number. A development or local version, alpha, epoch, post +release, or noncanonical alias is not a supported public release form under +this policy. Examples: `0.1.0b2`, `0.1.0rc1`, `0.1.0`, and `0.1.1`. +`0.1.0-beta.2`, `v0.1.0`, `0.1`, and `0.1.0.dev1` are not canonical release +values for the manifest. + +The `v` prefix belongs to the Git tag, not the application version. A release +advances the appropriate beta or RC number, or promotes an accepted candidate +to the stable version. Stable releases follow the application's documented +compatibility commitments. Published versions, tags, and artifacts MUST NOT +be reused for different contents. + +## Tool and project-type implementation versions + +Use strict [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html). +Every tool MUST supply `version` and `api_version` explicitly to `Tool`. +Every project-type JSON MUST contain both `version` and `schema_version`. +Missing, null, malformed, or unsupported declarations MUST fail validation; +there are no implicit defaults. The version string is not normalized. +The implementation version describes the plugin, not the host or its schema. + +Examples of valid plugin versions are `0.1.0`, `1.2.3`, `0.1.0-beta.2`, +and `1.2.3+build.5`. The core has exactly three numeric components with no +leading zeroes. Prerelease identifiers follow SemVer rules, including no +leading zeroes in numeric prerelease identifiers. Build identifiers follow +SemVer rules and do not affect precedence. `1.2`, `01.2.3`, `1.2.3-01`, +`0.1.0b2`, `dev`, an empty string, whitespace, and non-string values are +invalid. Tools and project types use the same validator. + +For example, a tool descriptor declares the independent values +`version="0.1.0"` and `api_version=1`. A project-type definition declares +`"version": "0.1.0"` and `"schema_version": 1` in its JSON object. +These examples show only the version fields, not complete definitions. +See the [tool API](PLUGIN_API.md) and [project-type schema](PROJECT_TYPE_SCHEMA.md) +for complete authoring contracts. + +### Version increment rules + +Determine increments relative to the last published implementation of the +component, not every commit or development PR. Before the first publication, +multiple development changes can be consolidated into the initial release. + +| Change | Before plugin 1.0.0 | From plugin 1.0.0 | +| --- | --- | --- | +| Compatible bug correction | `0.1.0` → `0.1.1` | `1.2.3` → `1.2.4` | +| Compatible functionality | `0.1.0` → `0.2.0` | `1.2.3` → `1.3.0` | +| Incompatible behavior or settings contract | `0.1.0` → `0.2.0` | `1.2.3` → `2.0.0` | +| Promotion to independently validated maturity | `0.x.y` → `1.0.0` | Not applicable | + +When increasing a major or minor component, reset the subordinate components +according to SemVer. Each plugin reaches `1.0.0` independently when its +behavior and public contract are considered mature and validated by users. +A release of KíLín `0.1.0` does not itself establish that maturity. + +KíLín does not require dependency resolution, version-range selection, or +simultaneous installation of multiple versions of a plugin. A declared +version does not replace validation of the current host contract. + +### Ownership of changes + +| Change | Version affected | +| --- | --- | +| Shared retrieval, model interface, memory, GUI, or plugin management | Application | +| Tool-specific algorithm, prompt, settings, or behavioral contract | Individual tool | +| Project-type prompt, intents, retrieval, or defaults | Individual project type | +| User modification of a project instance | None of the distributed releases | +| Incompatible host tool API or project-type schema | Corresponding contract generation and affected implementations as appropriate | + +Changes in bundled plugins are included in a subsequent application release. +Changes to shared host services MUST NOT automatically propagate version +increments to all dependent plugins. Formatting, comments, docstrings, +documentation, and tests alone do not require a plugin implementation-version +increment when its behavior and public contract remain unchanged. A change +that does affect behavior must be assessed even if implemented in a resource +rather than a Python file. Contributors MUST explain the versioning impact +of substantive changes, including why any relevant version is unchanged. + +## Compatibility generations + +The tool API, project-type schema, and trace format have independent positive +integer generations. Each has exactly one authoritative declaration in its +owning module. Host writers, validators, and consumers MUST use that +contract's authority, not a copied literal. A plugin's declared API or +schema generation, however, is the generation it actually implements, not a +reference to a moving host constant. Otherwise, old code could claim +compatibility with a new incompatible host without being changed or tested. + +Missing declarations and unsupported generations MUST fail clearly. Integer +validation MUST reject booleans, floats, strings, and other non-integers; +`True` and `1.0` must not be accepted simply because they compare equal to +`1`. The current runtime supports one generation of each contract. There +is no requirement to implement compatibility adapters for older generations. + +The unpublished tool API and project-type schema are finalized at generation +1 for beta 2. After publishing beta 2, incompatible changes to either MUST +increment its generation even during pre-stable development. A published +API or schema generation MUST NOT be reset or reused for a different +incompatible contract to obtain a particular stable-release number. The +trace format has an authoritative generation 1, whose initial stable +contract is finalized at KíLín 0.1.0; incompatible changes after that +release MUST increment its generation. Pre-stable trace representations +need not be compatible with the final generation 1 contract. + +| Change | Contract generation | +| --- | --- | +| Tool-specific correction, feature, or settings change | Tool API unchanged | +| Compatible extension to the public tool interface | Tool API unchanged | +| Incompatible public descriptor, callback, or execution-context contract | Tool API incremented | +| Project-type prompts, defaults, or intents | Schema unchanged | +| Compatible extension to the JSON schema | Schema unchanged | +| Incompatible required JSON structure or interpretation | Schema incremented | +| Change to generated trace content within the same contract | Trace format unchanged | +| Incompatible event structure, field meaning, or provenance representation | Trace format incremented | + +Compatible extensions MUST actually be understood safely by existing +consumers of the generation; a field is not automatically compatible merely +because it is optional. See the [trace recording reference](trace_recording.md) +for the trace contract. Validate changes against readers as well as writers. + +## Persistent formats + +Other persisted structures, including operation recordings, manifests, +indexes, replay receipts, comparison reports, and source-card data, retain +independent format versions or descriptive format identifiers owned by their +respective modules. Retain their existing generations; do not reset them +with the application release. A change in data content or a correction +within the existing format does not require a format increment. An +incompatible structure or field interpretation requires an increment. +Compatible optional additions may retain the existing generation only if +readers can safely handle them. Use strict version validation and reject +unsupported formats with clear diagnostics without silently overwriting +user data. An unnumbered format should be reported as such, not assigned an +invented generation. Do not introduce a general migration framework without +an actual compatibility requirement. + +The trace declaration is exposed as `kilin.TRACE_FORMAT_VERSION` (the +same value is exported by `kilin.trace_logging`). Existing numbered format +owners are listed below; these names are also the sources for version +inventory consumers. The integers are independent contracts, not aliases +for the trace format or the application version. + +| Format | Owning declaration | +| --- | --- | +| Trace and shared sequence counter | `kilin._trace_project.TRACE_FORMAT_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-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` | +| Replay receipt | `kilin.system_testing.replay_management.REPLAY_RECEIPT_FORMAT_VERSION` | + +Readers of a conversation document reject an explicitly declared trace +version that is not a supported integer. A state-only conversation can +exist without a trace header before tracing begins; this is not a claim of +compatibility with an unsupported trace generation. System-test inspection +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 +existing atomic creation boundary, using the actual captured runtime and +project-type identity. The five fields are: + +```ini +[metadata] +created_with_kilin = 0.1.0b2 +created_with_project_type = literature +created_with_project_type_version = 0.1.0 +created_with_project_type_schema_version = 1 +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. 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 +version or last-opened application version is required. Execution provenance +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`. +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 +build limits are not imposed on historical provenance. + +## Content fingerprints and execution provenance + +A version declares the intended implementation release; a SHA-256 digest +identifies captured contents. Preserve both. A tool fingerprint includes the +package files under the existing digest contract, including packaged +changelogs; documentation-only edits can therefore change fingerprints +without changing the declared implementation version. A project-type digest +identifies the JSON definition, not its adjacent changelog. Distribution +packaging MUST preserve the resources covered by tool fingerprints. + +Record actual host, plugin implementation, compatibility-generation, and +content identities in traces and replay provenance where applicable. Never +substitute current catalog information for historical observations. Report +missing, invalid, or unsupported provenance explicitly; do not invent a +version or relax identity comparisons to obtain matching results. Pending +plugin replacement metadata is bound to the validated staged digest. Do not +execute staged Python merely to display a version number. + +## Changelogs + +Create the following independent changelogs: + +- [Application changelog](../CHANGELOG.md). +- Each bundled tool's `kilin/tools//CHANGELOG.md`. +- Each bundled project type's `kilin/project_types/.CHANGELOG.md`, + next to its JSON definition. +- [Tool API changelog](PLUGIN_API_CHANGELOG.md). +- [Project-type schema changelog](PROJECT_TYPE_SCHEMA_CHANGELOG.md). +- [Trace-format changelog](TRACE_FORMAT_CHANGELOG.md). + +Before and through the release of KíLín `0.1.0`, these files contain only a +heading and a statement of their scope and activation policy. There is no +requirement to reconstruct beta or release-candidate history, including for +plugins. **Changelog maintenance becomes mandatory after the first stable +application release.** Individual plugin versions still evolve independently +and need not be `1.0.0` when that maintenance starts. + +After activation, record substantive changes under an `Unreleased` heading +in the affected component's changelog. On publication, group entries under +the actual version or generation and release date, retaining existing +history. Note compatible additions, fixes, changed behavior, removals, +breaking changes, and applicable migration instructions. Contract changelogs +also record compatible extensions that retain the same generation, with the +application release in which they appear. The application changelog summarizes +significant bundled-plugin changes and links to component changelogs without +duplicating all details. Independent external plugin authors maintain their +own version history. Routine formatting or test maintenance without a +contract or behavioral change need not be recorded individually. + +## Compatibility policy + +Before KíLín `0.1.0`, backward compatibility is not required, including with +`0.1.0b1`. Do not add legacy fallbacks, implicit plugin versions, or migration +machinery solely to preserve earlier prerelease behavior. This does not +permit misrepresenting history, destructive handling of incompatible user +data, or reusing a published version for a different contract. After the +stable release, assess compatibility explicitly for each affected interface +and persistent format and provide migration guidance or implementation when +required by its commitments. Independent plugin maturity remains governed +by its own SemVer contract. + +## Version reporting + +The public `kilin.version_info()` interface, `kilin --versions` (including +`--versions --json`), and the desktop Settings > Versions panel must consume +one structured, JSON-compatible, deterministic inventory. Include the actual +application version, supported API/schema/trace generations, individual +bundled and user plugin versions and origins, available/unavailable status, +active and pending changes, other authoritative persistent-format identifiers, +and diagnostics. Unknown values remain unknown. Report active and pending +versions separately. A queued installation or replacement retains its +validated implementation version, applicable API/schema generation, and +content digest in the durable pending-operation record. A removal has no +replacement identity. Pending metadata describes the validated candidate, +not an active registration; reading it does not execute candidate code. +The lightweight `kilin --version` displays only the +application version without discovering plugins. Inventory collection may +use the normal trusted runtime catalog initialization and lifecycle; it MUST +NOT initialize models, run tools, or execute staged replacement code merely +for reporting. The structured inventory has top-level `application`, `contracts`, +`persistent_formats`, `tools`, `project_types`, `installed`, `pending`, +`directory`, and `errors` fields. Each catalog record retains the declared +version, compatibility generation, origin, availability, fingerprint, and +diagnostic fields. Installed entries alone are not proof of a validated +implementation. Collection initializes the runtime catalogs before reading +installed and pending state, so completed startup activation is reflected +in the latter inventories. Each inventory failure is reported independently. +Descriptive format identifiers remain strings, including unnumbered markers. + +Use `kilin --version` for the application alone, `kilin --versions` for a +human-readable report, or `kilin --versions --json` for the complete structured +inventory. JSON output is intended for automation. Non-ASCII characters are +escaped in the JSON text so restrictive output encodings do not lose data; +JSON decoding restores the original values. Trusted plugin discovery messages +printed through Python's standard output are redirected to standard error by +the CLI. In Python, `kilin.version_info()` returns an independent +snapshot suitable for JSON serialization. Reports can contain local paths and +plugin diagnostics, so inspect them before sharing outside the local system. + +The GUI uses the same runtime data for the application banner, +plugin panel, and project creation provenance. It does not maintain version +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` 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. + +## Release checklist + +Use the [development procedure](development.md#public-prerelease-sequence) +and [native release guidance](release.md) for technical build and publication +steps. For every application release, the release maintainer MUST: + +1. Establish the exact intended release baseline and compare it with the + last published versions. Assess tool and project-type implementation + versions, API/schema/trace generations, and persistent-format changes. + Change only the declarations whose contracts or implementations warrant + an increment. Check that all required plugin declarations are explicit. +2. Set the canonical application version in `pyproject.toml` and synchronize + the root package entry in `uv.lock` without unrelated dependency changes. + Update the release version in `CITATION.cff`; set the actual release date + when it is known. Maintain consistency assertions against the authoritative + manifest instead of duplicating the current version in tests. +3. Update current-release information in `README.md`, including badges, + installation commands, GitHub release URLs, and versioned native assets. + Regenerate `README.pypi.md` with `python -m setup.generate_pypi_readme` + and verify with `python -m setup.generate_pypi_readme --check`; do not + edit the generated file manually. Update the release procedure and + applicable active-release examples. Keep historical examples accurate. +4. After changelog activation, finalize the relevant independent changelog + entries. Before activation, retain the introductory files without release + entries. Include packaged changelogs in resource and distribution checks. +5. Validate the exact commit: focused and full Python tests, the independent + test runner, documentation/style/public API checks, installed-wheel + resource and version tests, system-test provenance, and native builds. + Check application, CLI and GUI version reports. Build and inspect the + wheel and sdist; verify their metadata and tag-pinned PyPI description. + Test native upgrade ordering across beta, RC, and stable versions. +6. Use the matching immutable tag `v` on the validated commit and + the corresponding GitHub Release stage. Verify native asset names, + checksums, and both platform checks. Publish only reviewed, matching + artifacts to PyPI following the release procedure; never reuse a released + version or move a published tag. Publication requires explicit approval. + +## Contributor and AI review checklist + +For each substantive PR, contributors and coding agents MUST identify the +actual baseline and affected versioned components, compare against the last +published implementations, assess compatibility and version increments, +update relevant declarations and documentation, and explain why other +versions remain unchanged. Update the relevant changelogs after activation. +Do not add defaults to hide missing declarations or alter user provenance +to match the current release. Preserve existing test coverage, adding cases +for valid versions, missing declarations, malformed types and syntax, +unsupported generations, and safe failure. Check package resources and +runtime provenance where affected. Verify that the PR's scope is atomic and +its changes apply to its actual baseline. Report incomplete verification, +intentional prerelease incompatibilities, and deferred work explicitly. + +## Related + +[Development](development.md), [Tool API](PLUGIN_API.md), +[Project-type schema](PROJECT_TYPE_SCHEMA.md), +[Plugin authoring](PLUGIN_AUTHORING.md), [Trace recording](trace_recording.md), +[Project workspaces](project_workspaces.md), [Release guidance](release.md), +[System testing](system_testing.md). diff --git a/examples/plugins/README.md b/examples/plugins/README.md new file mode 100644 index 00000000..f0579c19 --- /dev/null +++ b/examples/plugins/README.md @@ -0,0 +1,40 @@ +# Copyable KíLín plugin examples + +These are ordinary draft sources, not bundled registrations. Copy the desired +folder and matching JSON to a separate draft area. Read every file before +trusted validation or installation. See the [authoring guide](../../docs/PLUGIN_AUTHORING.md), +[tool API](../../docs/PLUGIN_API.md), and [project-type schema](../../docs/PROJECT_TYPE_SCHEMA.md). + +| Tool package | JSON definition | Demonstrates | +| --- | --- | --- | +| [repeat_question](tools/repeat_question/) | [repetition.json](project_types/repetition.json) | Minimal descriptor, settings parser, deterministic answer. | +| [source_note](tools/source_note/) | [source-notes.json](project_types/source-notes.json) | Public data contracts, optional metadata, declared resource, recorded choice, exact evidence and unique output. | +| [word_count](tools/word_count/) | [output-word-count.json](project_types/output-word-count.json) | Tutorial 180's bounded deterministic analysis of a Markdown output. | + +All example tools use the public tool API v1 and declare their individual +version as `0.1.0`. Each example project type declares version `0.1.0` and +schema generation 1. The examples declare document and notes roles, +with the two generic relations and no discovery rules. Their tool-backed +intents do not declare ordinary-intent relation policies. No model calls or third-party dependencies beyond KíLín are needed +by the operations. Ordinary application startup and indexing can still +require configured models. The package folder name must be preserved, or +changed consistently with its descriptor ID and JSON references. + +## Verify in an isolated store + +From the repository or unpacked sdist, in an interpreter where KíLín is +installed, run `python examples/plugins/check_examples.py`. The checker uses +temporary directories and new child interpreters; it does not alter the real +user plugin store. It checks structure, trusted validation, managed +installation, source choices and exact evidence, workspace resources and +settings, safe output publication, update, deferred activation and removal. +It is not a sandbox or security audit. + +## Install in the application + +Open **Settings > Plugins** and select the tool folder, check structure, +review the source, then Validate and Install. Choose the matching JSON file +and install it. Quit every application or kernel using the same store and +restart; the new type is then available for creating a workspace. Use the +example request described in each package's README. Do not select or modify +files under the active store while a runtime holds a lease. diff --git a/examples/plugins/check_examples.py b/examples/plugins/check_examples.py new file mode 100644 index 00000000..cd9c6531 --- /dev/null +++ b/examples/plugins/check_examples.py @@ -0,0 +1,406 @@ +"""Exercise the authoring examples in disposable, independent runtimes. + +Run with an installed KíLín interpreter, with no models or GUI. A parent +copies the reviewed examples and starts a fresh process for every activation +boundary; it never touches the user's plugin store or workspace. + +""" + +from __future__ import annotations + +from dataclasses import replace +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tarfile +from tempfile import TemporaryDirectory +from unittest.mock import Mock + + +EXAMPLES = Path(__file__).resolve().parent +TOOLS = ("repeat_question", "source_note", "word_count") +TYPES = ("repetition", "source-notes", "output-word-count") + + +def _child(phase: str, root: Path) -> None: + """Run a phase outside the checkout with a private plugin store. + + Parameters + ---------- + phase: str + Lifecycle phase dispatched by this script in the child. + root: pathlib.Path + Temporary root shared by the independent processes. + + """ + + options = ["-I"] if sys.flags.isolated else [] + env = dict(os.environ, KILIN_PLUGINS_DIR=str(root / "plugins"), + 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( + [sys.executable, *options, "-B", str(Path(__file__).resolve()), + phase, str(root)], + cwd=root, env=env, capture_output=True, text=True, encoding="utf-8", + timeout=120, check=False, + ) + if result.returncode: + raise RuntimeError(f"{phase}:\n{result.stdout}\n{result.stderr}") + + +def _stage(root: Path) -> None: + """Validate complete source drafts and queue their installation.""" + + from kilin import plugins + + for name in TOOLS: + path = root / "drafts" / "tools" / name + structural = plugins.validate_tool(path) + assert structural.error is None, structural + assert not structural.runtime_checked + verified = plugins.validate_tool(path, trusted=True) + assert verified.available and verified.runtime_checked, verified + assert verified.api_version == 1 and verified.version == "0.1.0" + change = plugins.install_tool(path, trusted=True) + assert change.sha256 == verified.sha256, change + for name in TYPES: + path = root / "drafts" / "project_types" / (name + ".json") + checked = plugins.validate_project_type(path, bind_tools=False) + assert checked.error is None and not checked.bound, checked + assert plugins.install_project_type(path).action == "install" + assert len(plugins.pending_changes()) == 6 + assert not plugins.list_installed_plugins() + + +def _context(root: Path, chunks=(), inventory=None, choose=None): + """Provide controlled host services and forbid all model calls.""" + + from hashlib import sha256 + from kilin import open_project, inspect_source_manifest + from kilin.tools import ( + CodeGraph, ToolContext, ToolSourceServices, SourceInventory, + SourceFileState, resolve_source_view, read_source_bytes, + ) + + def unused(*args, **kwargs): + """Reject calls not required by these deterministic examples.""" + raise AssertionError("Unexpected retrieval or model call") + + # A controlled host implements the same public resolver contract as RAG. + # Inventory-only examples intentionally leave unrelated services unused. + def bind(policy, scope): + """Resolve selected physical identities without model services.""" + project = open_project(root) + inspection = inspect_source_manifest(project) + states = SourceInventory(tuple( + SourceFileState(path, sha256((project.source / path) + .read_bytes()).hexdigest(), + any(c.path == path for c in chunks)) + for path in inventory or {} + ), "a" * 64) + view = resolve_source_view(inspection, states, policy, scope) + allowed = set(view.lookup if policy.purpose == "lookup" + else view.evidence) + return ToolSourceServices( + view, tuple(c for c in chunks if c.path in allowed), + unused, unused, unused, + lambda path: read_source_bytes(root, project.source, view, path), + lambda: None, + ) + + return ToolContext( + project_root=root, chunks=chunks, graph=CodeGraph((), ()), + rank=unused, retrieval_count=1, unsearchable=lambda paths: [], + source_files=lambda: dict(inventory or {}), ask_router=unused, + ask_model=unused, write=unused, model_id="deterministic-test", + progress=Mock(), done=Mock(), confirm=None, trace=Mock(), + trace_turn_id="example-turn", choose=choose, + source_root=root / "sources", source_view=bind, + ) + + +def _repeat(expected: str) -> None: + """Execute the currently registered repetition plugin.""" + + import kilin + from kilin.tools import ToolRequest, run_tool + + use = kilin.project_type("repetition").intents["repeat"].tool + result = run_tool(use, ToolRequest("hello", "hello"), None) + assert result.answer == expected, result + assert result.evidence == () and result.summary == {"count": 2} + + +def _notes(root: Path) -> None: + """Verify settings, exact evidence, resource copying and choice records.""" + + import kilin + from kilin.tool_settings import save_tool_settings, with_project_settings + from kilin.tools import Chunk, ToolRequest, run_tool + + workspace = root / "notes" + kilin.initialize_project(workspace, "source-notes") + guide = workspace / "templates/source_note/source_note_guide.md" + original = (EXAMPLES / "tools/source_note/templates/source_note_guide.md") + assert guide.read_bytes() == original.read_bytes() + guide.write_text("User-edited guide.\n", encoding="utf-8") + chunks = tuple( + Chunk(name, Path(name), text, 1, 1, "text", None, None) + for name, text in (("b.txt", "Exact second excerpt."), + ("a.txt", "Exact first excerpt."), + ("stale.txt", "Unselected stale excerpt.")) + ) + inventory = {chunk.path: len(chunk.text) for chunk in chunks[:2]} + for chunk in chunks[:2]: + (workspace / "sources" / chunk.path).write_text( + chunk.text, encoding="utf-8" + ) + project = kilin.open_project(workspace) + kilin.apply_source_manifest( + project, kilin.preview_source_manifest(project), + ) + choose = Mock(return_value=1) + context = _context(workspace, chunks, inventory, choose) + use = kilin.project_type("source-notes").intents["note"].tool + assert use.settings.max_options == 3 + assert kilin.get_tool_settings_info("source_note")["max_options"] + request = ToolRequest("Save a note", "Save a note") + result = run_tool(use, request, context) + choose.assert_called_once_with("Which source should I excerpt?", + ("a.txt", "b.txt")) + assert result.evidence[0]["path"] == Path("b.txt") + assert result.evidence[0]["text"] == chunks[0].text + assert result.evidence[0]["start_line"] == 1 + assert result.evidence[0]["end_line"] == 1 + saved = workspace / result.summary["saved"] + first_bytes = saved.read_bytes() + assert chunks[0].text in saved.read_text(encoding="utf-8") + assert b"stale" not in first_bytes + events = {call.args[0]: call.kwargs["data"] + for call in context.trace.emit.call_args_list} + proposed = events["tool.choice.proposed"] + decided = events["tool.choice.decided"] + assert proposed["interaction_id"] == decided["interaction_id"] + assert decided["selected_option"] == "b.txt" + assert decided["asked"] + again = run_tool(use, request, context) + assert again.summary["saved"] != result.summary["saved"] + assert saved.read_bytes() == first_bytes + before = set((workspace / "outputs").iterdir()) + for absent in (replace(context, choose=None), + replace(context, choose=lambda *args: None)): + rejected = run_tool(use, request, absent) + assert rejected.summary["saved"] is None, rejected + assert rejected.evidence == () + assert set((workspace / "outputs").iterdir()) == before + empty = root / "empty-notes" + kilin.initialize_project(empty, "source-notes") + rejected = run_tool(use, request, _context(empty, (), {})) + assert rejected.summary["saved"] is None, rejected + assert rejected.evidence == () + assert not list((empty / "outputs").iterdir()) + + def wrong_view(policy, scope): + """Return a different scope, which the consumer must reject.""" + from kilin.tools import SourceScope + + return context.source_view(policy, SourceScope("restricted")) + + try: + run_tool(use, request, replace(context, source_view=wrong_view)) + except RuntimeError as error: + assert "different policy or scope" in str(error) + else: + raise AssertionError("Mismatched scope was accepted") + try: + run_tool(use, request, replace(context, source_view=None)) + except RuntimeError as error: + assert "requires ToolContext.source_view" in str(error) + else: + raise AssertionError("Missing scoped service widened the view") + save_tool_settings(workspace, "source_note", {"max_options": 1}) + use = with_project_settings(workspace, use) + assert use.settings.max_options == 1 + picked = run_tool(use, request, replace(context, choose=None)) + assert picked.summary["source"] == "a.txt" + assert guide.read_text(encoding="utf-8") == "User-edited guide.\n" + + +def _word_count(root: Path) -> None: + """Run the tutorial tool against ordinary and rejected inputs.""" + + import kilin + from kilin.tools import ToolRequest, run_tool + + workspace = root / "counts" + kilin.initialize_project(workspace, "output-word-count") + folder = workspace / "outputs" + folder.mkdir(exist_ok=True) + report = folder / "report.md" + report.write_text("alpha beta Alpha", encoding="utf-8") + use = kilin.project_type("output-word-count").intents["count"].tool + context = _context(workspace) + result = run_tool(use, ToolRequest("report.md", "report.md"), context) + assert result.summary["count"] == 3 + assert list(map(tuple, result.summary["top"])) == [ + ("alpha", 2), ("beta", 1), + ] + assert result.evidence == () + for question in ("../report.md", str(report), "missing.md"): + rejected = run_tool(use, ToolRequest(question, question), context) + assert not rejected.summary, rejected + large = folder / "large.md" + large.write_bytes(b"a" * (1024 * 1024 + 1)) + rejected = run_tool(use, ToolRequest("large.md", "large.md"), context) + assert not rejected.summary + assert report.read_text(encoding="utf-8") == "alpha beta Alpha" + + +def _exercise(root: Path) -> None: + """Check activated examples and queue a replacement while active.""" + + import kilin + from kilin import plugins + from kilin.tools import registered_tools + + assert set(TYPES) <= set(kilin.project_type_ids()) + assert not plugins.pending_changes() + assert len(plugins.list_installed_plugins()) == 6 + for name in TYPES: + path = root / "drafts/project_types" / (name + ".json") + checked = plugins.validate_project_type(path) + assert checked.available and checked.bound, checked + for name in TOOLS: + tool = registered_tools()[name] + try: + tool.parse_settings({"unknown": True}, name) + except (ValueError, TypeError): + pass + else: + raise AssertionError(f"Accepted unknown setting: {name}") + _repeat("hello\nhello") + _notes(root) + _word_count(root) + draft = root / "drafts/tools/repeat_question" + source = draft / "__init__.py" + text = source.read_text(encoding="utf-8") + text = text.replace('version="0.1.0"', 'version="0.2.0"') + text = text.replace(r'answer="\n".join', 'answer=" | ".join') + source.write_text(text, encoding="utf-8") + previous = next(x for x in plugins.list_tools() + if x.name == "repeat_question") + change = plugins.update_tool(draft, trusted=True) + assert change.sha256 != previous.sha256 + _repeat("hello\nhello") + _child("old", root) + + +def _updated(root: Path) -> None: + """Observe activation of the replacement and queue all removals.""" + + from kilin import plugins + + _repeat("hello | hello") + info = next(x for x in plugins.list_tools() + if x.name == "repeat_question") + assert info.version == "0.2.0" + for name in TOOLS: + assert plugins.uninstall_tool(name).action == "remove" + for name in TYPES: + assert plugins.uninstall_project_type(name).action == "remove" + assert len(plugins.pending_changes()) == 6 + _repeat("hello | hello") + + +def _removed(root: Path) -> None: + """Verify unavailable types and unchanged workspace data after removal.""" + + import kilin + from kilin import plugins + + assert not (set(TYPES) & set(kilin.project_type_ids())) + assert not plugins.list_installed_plugins() + assert not plugins.pending_changes() + workspace = root / "notes" + assert (workspace / "profile.ini").is_file() + assert len(list((workspace / "outputs").glob("source_note*.md"))) == 3 + assert (workspace / "templates/source_note" + / "source_note_guide.md").read_text( + encoding="utf-8" + ) == "User-edited guide.\n" + assert (root / "counts/outputs/report.md").read_text( + encoding="utf-8" + ) == "alpha beta Alpha" + try: + kilin.open_project(workspace) + except ValueError: + pass + else: + raise AssertionError("Opened a project with an unavailable type") + + +def check_source_archive(archive_path: Path) -> None: + """Check that the sdist carries the complete reviewed authoring pack. + + Parameters + ---------- + archive_path: pathlib.Path + Built source distribution to compare with checkout files. + + """ + + repository = EXAMPLES.parents[1] + files = [path for path in EXAMPLES.rglob("*") if path.is_file() + and path.suffix in (".py", ".md", ".json") + and "__pycache__" not in path.parts] + files.extend(repository / "docs" / name for name in ( + "PLUGIN_API.md", "PLUGIN_AUTHORING.md", "PROJECT_TYPE_SCHEMA.md", + )) + with tarfile.open(archive_path, "r:gz") as archive: + members = {member.name.split("/", 1)[1]: member + for member in archive.getmembers() + if member.isfile() and "/" in member.name} + for path in sorted(files): + name = path.relative_to(repository).as_posix() + assert name in members, f"Missing source archive file: {name}" + stream = archive.extractfile(members[name]) + assert stream is not None + with stream: + assert stream.read() == path.read_bytes(), name + print("Verified source distribution authoring files.") + + +def main() -> None: + """Run the complete offline acceptance scenario in a temporary store.""" + + with TemporaryDirectory(prefix="kilin-plugin-examples-") as temporary: + root = Path(temporary).resolve() + for kind in ("tools", "project_types"): + shutil.copytree(EXAMPLES / kind, root / "drafts" / kind, + ignore=shutil.ignore_patterns("__pycache__", + "*.pyc")) + for phase in ("stage", "exercise", "updated", "removed"): + _child(phase, root) + print("Verified example plugin lifecycle and deterministic execution.") + + +if __name__ == "__main__": + if len(sys.argv) == 1: + main() + elif len(sys.argv) == 3 and sys.argv[1] == "--sdist": + check_source_archive(Path(sys.argv[2])) + else: + phase, root = sys.argv[1:] + if sys.flags.isolated: + import kilin + + installed = Path(kilin.__file__).resolve() + assert installed.is_relative_to(Path(sys.prefix).resolve()) + if phase == "old": + _repeat("hello\nhello") + else: + {"stage": _stage, "exercise": _exercise, "updated": _updated, + "removed": _removed}[phase](Path(root)) diff --git a/examples/plugins/project_types/output-word-count.json b/examples/plugins/project_types/output-word-count.json new file mode 100644 index 00000000..eccf79e8 --- /dev/null +++ b/examples/plugins/project_types/output-word-count.json @@ -0,0 +1,62 @@ +{ + "version": "0.1.0", + "schema_version": 1, + "source_organization": { + "roles": [ + "document", + "notes" + ], + "default_role": "document", + "relation_types": { + "attached_to": { + "behavior": "dependency" + }, + "related_to": { + "behavior": "association" + } + }, + "automatic_rules": [] + }, + "display_name": "Output word count", + "description": "Count words in a generated Markdown output.", + "extensions": [ + ".txt", + ".md" + ], + "max_file_bytes": 4096, + "retrieval_instruction": "Find relevant information.", + "system_prompt": "Count words in a generated Markdown output.", + "history": { + "exclude_disliked_answers": true + }, + "conversation_memory": { + "enabled": false, + "questions": "all", + "answers": "selected", + "max_hits": 4, + "max_tokens": 2000 + }, + "intents": { + "count": { + "description": "Count words in a generated Markdown output.", + "history": { + "policy": "none" + }, + "retrieval": { + "mode": "none" + }, + "tool": { + "name": "word_count", + "top_words": 3 + } + } + }, + "default_intent": "count", + "capabilities": { + "code_graph": false + }, + "generation": { + "thinking": false, + "temperature": 0.1 + } +} diff --git a/examples/plugins/project_types/repetition.json b/examples/plugins/project_types/repetition.json new file mode 100644 index 00000000..3f82b2d9 --- /dev/null +++ b/examples/plugins/project_types/repetition.json @@ -0,0 +1,40 @@ +{ + "version": "0.1.0", + "schema_version": 1, + "source_organization": { + "roles": [ + "document", + "notes" + ], + "default_role": "document", + "relation_types": { + "attached_to": { + "behavior": "dependency" + }, + "related_to": { + "behavior": "association" + } + }, + "automatic_rules": [] + }, + "display_name": "Repetition", + "description": "Repeat a question using a deterministic tool.", + "extensions": [".txt", ".md"], + "max_file_bytes": 4096, + "retrieval_instruction": "Find relevant information.", + "system_prompt": "Use the configured repetition tool.", + "history": {"exclude_disliked_answers": true}, + "conversation_memory": { + "enabled": false, + "questions": "all", + "answers": "selected", + "max_hits": 4, + "max_tokens": 2000 + }, + "intents": { + "repeat": { + "description": "Repeat a question.", + "tool": {"name": "repeat_question", "count": 2} + } + } +} diff --git a/examples/plugins/project_types/source-notes.json b/examples/plugins/project_types/source-notes.json new file mode 100644 index 00000000..106bfdf3 --- /dev/null +++ b/examples/plugins/project_types/source-notes.json @@ -0,0 +1,63 @@ +{ + "version": "0.1.0", + "schema_version": 1, + "source_organization": { + "roles": [ + "document", + "notes" + ], + "default_role": "document", + "relation_types": { + "attached_to": { + "behavior": "dependency" + }, + "related_to": { + "behavior": "association" + } + }, + "automatic_rules": [] + }, + "display_name": "Source notes", + "description": "Save an exact indexed excerpt from a selected source.", + "extensions": [ + ".txt", + ".md" + ], + "max_file_bytes": 4096, + "retrieval_instruction": "Find relevant information.", + "system_prompt": "Save an exact indexed excerpt from a selected source.", + "history": { + "exclude_disliked_answers": true + }, + "conversation_memory": { + "enabled": false, + "questions": "all", + "answers": "selected", + "max_hits": 4, + "max_tokens": 2000 + }, + "intents": { + "note": { + "description": "Save an exact indexed excerpt from a selected source.", + "history": { + "policy": "none" + }, + "retrieval": { + "mode": "none" + }, + "tool": { + "name": "source_note", + "max_options": 3, + "max_chars": 2000 + } + } + }, + "default_intent": "note", + "capabilities": { + "code_graph": false + }, + "generation": { + "thinking": false, + "temperature": 0.1 + } +} diff --git a/examples/plugins/tools/repeat_question/README.md b/examples/plugins/tools/repeat_question/README.md new file mode 100644 index 00000000..4d5ff19c --- /dev/null +++ b/examples/plugins/tools/repeat_question/README.md @@ -0,0 +1,13 @@ +# Repeat question + +A minimal tool with no resources, optional services or model calls. It returns +the original question repeated with newline separators, plus a JSON summary +containing the repetition count. There is no source-evidence claim. + +`count` is an integer from 1 to 10, default 1. The accompanying +`repetition.json` selects 2; a workspace tool override can change it. +The parser rejects unknown fields, booleans and out-of-range values. + +Create a Repetition project and ask `hello`; the expected answer contains two +copies of that question. This is a contract example, not a useful research +analysis. diff --git a/examples/plugins/tools/repeat_question/__init__.py b/examples/plugins/tools/repeat_question/__init__.py new file mode 100644 index 00000000..7c28764f --- /dev/null +++ b/examples/plugins/tools/repeat_question/__init__.py @@ -0,0 +1,90 @@ +"""A minimal deterministic tool using only the public authoring API. + +The settings control how many times the original question is repeated. +There are no model calls, filesystem operations, or required assets. + +""" + +from dataclasses import dataclass + +from kilin.tools import ( + Tool, + ToolContext, + ToolRequest, + ToolResult, + check_int, + reject_unknown, +) + + +@dataclass(frozen=True) +class Settings: + """Validated repetition settings. + + Attributes + ---------- + count: int + Number of repetitions, from one to ten. + + """ + + count: int + + +def parse_settings(data: dict, where: str) -> Settings: + """Validate settings from the project type or workspace. + + Parameters + ---------- + data: dict + Raw settings, without the tool name. + where: str + Diagnostic location of the configuration. + + Returns + ------- + Settings + Validated repetition settings. + + """ + + reject_unknown(where, data, ("count",)) + return Settings(check_int(where, data, "count", 1, 1, 10)) + + +def run( + settings: Settings, request: ToolRequest, context: ToolContext, +) -> ToolResult: + """Return the question repeated without invoking host services. + + Parameters + ---------- + settings: Settings + Validated repetition count. + request: ToolRequest + Original user question. + context: ToolContext + Host services, not needed by this deterministic operation. + + Returns + ------- + ToolResult + Repeated question and count, with no claimed source evidence. + + """ + + return ToolResult( + answer="\n".join([request.question] * settings.count), + evidence=(), + summary={"count": settings.count}, + ) + + +PLUGIN = Tool( + name="repeat_question", + summary="Repeat a question a specified number of times.", + version="0.1.0", + api_version=1, + parse_settings=parse_settings, + run=run, +) diff --git a/examples/plugins/tools/source_note/README.md b/examples/plugins/tools/source_note/README.md new file mode 100644 index 00000000..f3c37ee1 --- /dev/null +++ b/examples/plugins/tools/source_note/README.md @@ -0,0 +1,30 @@ +# Source note + +Select one complete indexed `.md` or `.txt` fragment from a selected source. +When several eligible sources exist, use the recorded-choice helper; if no +choice can be made or the user cancels, save nothing. When only one is offered, +choose it deterministically. Return exact indexed evidence and save an excerpt +with its original location under a non-overwriting name in `outputs/`. + +Settings (defaults in `defaults.json` and parser): + +- `max_options`: integer 1–20, default 5. The supplied project type uses 3. +- `max_chars`: integer 100–10000, default 2000. Longer complete fragments + are skipped, not truncated. This is a bound on the selected excerpt, + not on overall source-index size. + +`MODEL_CALLS.THINKING` is `inherit`; no model calls are made. The copied +`templates/source_note/source_note_guide.md` is an explanatory workspace resource, not a +runtime prompt. Edits to the guide do not change the runner. The tool does not +perform exhaustive search or summarize a complete source, and does not infer +unindexed evidence. Source content is copied to the workspace output only. + +Create a Source notes project with small text files and ask `Save a source +note`. If several candidates are eligible, choose a source. The chat cites the +original excerpt; the output records the source path and line range. + +The tool uses `require_source_services` with an explicit physical lookup +view and a restricted view for the chosen excerpt. It does not use the +unscoped chunk or rank APIs. Missing scoped services fail explicitly; +empty views offer no choices. The host validates the generation before +publishing the note. diff --git a/examples/plugins/tools/source_note/__init__.py b/examples/plugins/tools/source_note/__init__.py new file mode 100644 index 00000000..25d9270f --- /dev/null +++ b/examples/plugins/tools/source_note/__init__.py @@ -0,0 +1,19 @@ +"""Expose the source-note example's versioned tool descriptor. + +The implementation imports only the public host contract and its own +package-local module. Merely importing it does not read or write a workspace. + +""" + +from kilin.tools import Tool +from .tool import parse_settings, run, workspace_resources + +PLUGIN = Tool( + name="source_note", + summary="Save one complete indexed excerpt as a source-linked note.", + version="0.1.0", + api_version=1, + parse_settings=parse_settings, + run=run, + workspace_resources=workspace_resources, +) diff --git a/examples/plugins/tools/source_note/defaults.json b/examples/plugins/tools/source_note/defaults.json new file mode 100644 index 00000000..b88195fc --- /dev/null +++ b/examples/plugins/tools/source_note/defaults.json @@ -0,0 +1,9 @@ +{ + "SETTINGS": { + "MAX_OPTIONS": 5, + "MAX_CHARS": 2000 + }, + "MODEL_CALLS": { + "THINKING": "inherit" + } +} diff --git a/examples/plugins/tools/source_note/settings_info.json b/examples/plugins/tools/source_note/settings_info.json new file mode 100644 index 00000000..acf87979 --- /dev/null +++ b/examples/plugins/tools/source_note/settings_info.json @@ -0,0 +1,15 @@ +{ + "format": "settings-info-v1", + "settings": { + "max_options": { + "title": "Maximum source options", + "summary": "Limits the number of eligible sources offered.", + "description": "From 1 to 20; sources are ordered by relative path. The default is 5." + }, + "max_chars": { + "title": "Maximum excerpt length", + "summary": "Skips complete indexed fragments above this length.", + "description": "From 100 to 10000 characters. The default is 2000. Quotes are never truncated to fit." + } + } +} diff --git a/examples/plugins/tools/source_note/templates/source_note_guide.md b/examples/plugins/tools/source_note/templates/source_note_guide.md new file mode 100644 index 00000000..024bff0e --- /dev/null +++ b/examples/plugins/tools/source_note/templates/source_note_guide.md @@ -0,0 +1,8 @@ +# Source note guide + +The tool saves one complete indexed text fragment with its original source path +and line range. The note is an excerpt, not a model-written summary or a claim +of exhaustive coverage. The chat cites the original indexed evidence. + +This file is an explanatory workspace resource, not a runtime prompt or an +editable formatting template. Editing it does not change the tool's logic. diff --git a/examples/plugins/tools/source_note/tool.py b/examples/plugins/tools/source_note/tool.py new file mode 100644 index 00000000..538e561f --- /dev/null +++ b/examples/plugins/tools/source_note/tool.py @@ -0,0 +1,191 @@ +"""Demonstrate exact evidence, resource ownership and recorded choices. + +Choose one complete indexed excerpt from a selected source. Keep model +services unused and publish a new output without changing source files. + +""" + +from dataclasses import dataclass +from pathlib import Path + +from kilin.tools import ( + Chunk, + ToolContext, + ToolRequest, + ToolResult, + WorkspaceResource, + template_resource, + ask_choice, + check_int, + reject_unknown, + save_output_file, + SourcePolicy, + SourceScope, + ToolSourceServices, + require_source_services, +) + + +@dataclass(frozen=True, slots=True) +class Settings: + """Validated limits for the source-note operation. + + Attributes + ---------- + max_options: int + Maximum number of eligible sources offered to the user. + max_chars: int + Maximum length of a complete excerpt in characters. + + """ + + max_options: int = 5 + max_chars: int = 2000 + + +def parse_settings(data: dict, where: str) -> Settings: + """Reject unknown settings and validate the two numeric limits. + + Parameters + ---------- + data: dict + Raw tool settings, excluding the tool name. + where: str + Configuration location used in errors. + + Returns + ------- + Settings + Validated limits. + + """ + + reject_unknown(where, data, ("max_options", "max_chars")) + return Settings( + max_options=check_int(where, data, "max_options", 5, 1, 20), + max_chars=check_int(where, data, "max_chars", 2000, 100, 10000), + ) + + +def workspace_resources(settings: Settings) -> tuple[WorkspaceResource, ...]: + """Declare an explanatory guide copied into each new workspace. + + Parameters + ---------- + settings: Settings + Validated limits; the guide is the same for every configuration. + + Returns + ------- + tuple[WorkspaceResource, ...] + One package-owned resource and its workspace destination. + + """ + + return (template_resource( + Path(__file__).parent / "templates" / "source_note_guide.md", + "source_note", + ),) + + +def _eligible( + settings: Settings, services: ToolSourceServices, +) -> list[Chunk]: + """Select at most one complete eligible chunk per selected file. + + Parameters + ---------- + settings: Settings + Validated limits. + services: ToolSourceServices + Bound lookup view of selected physical files. + + Returns + ------- + list[Chunk] + Complete excerpts in deterministic source-path order. + + """ + + first: dict[Path, Chunk] = {} + for chunk in services.chunks: + if ( + chunk.path.is_absolute() + or ".." in chunk.path.parts + or not chunk.path.parts + or chunk.path.suffix.lower() not in (".md", ".txt") + or not chunk.text.strip() + or len(chunk.text) > settings.max_chars + ): + continue + # Keep the original fragment, not a truncated or synthesized quote. + first.setdefault(chunk.path, chunk) + paths = sorted(first, key=lambda path: path.as_posix()) + return [first[path] for path in paths[:settings.max_options]] + + +def run( + settings: Settings, request: ToolRequest, context: ToolContext, +) -> ToolResult: + """Save one exact excerpt after an explicit selection when necessary. + + Parameters + ---------- + settings: Settings + Validated limits. + request: ToolRequest + User request; selection is made from the current source inventory. + context: ToolContext + Indexed source data, recorded-choice and output services. + + Returns + ------- + ToolResult + A source-linked note, or an explanation that no note was saved. + + """ + + policy = SourcePolicy(purpose="lookup") + services = require_source_services(context, policy) + excerpts = _eligible(settings, services) + if not excerpts: + return ToolResult( + "No eligible indexed excerpt is available.", (), + {"saved": None, "reason": "no_excerpt"}, + ) + options = tuple(chunk.path.as_posix() for chunk in excerpts) + if len(options) == 1: + choice = 0 + else: + choice = ask_choice("Which source should I excerpt?", options, + context) + if choice is None: + return ToolResult( + "No source was selected; no note was saved.", (), + {"saved": None, "reason": "no_selection"}, + ) + chunk = excerpts[choice] + chosen = require_source_services( + context, policy, SourceScope("restricted", (chunk.path,)), + ) + if chunk not in chosen.chunks: + raise RuntimeError("Selected excerpt is no longer available.") + chosen.validate() + location = f"{chunk.path.as_posix()}:{chunk.start_line}-{chunk.end_line}" + note = f"# Source note\n\nSource: {location}\n\n{chunk.text}\n" + saved = save_output_file(context.project_root, "source_note.md", note) + context.done("Saved one source note") + evidence = ({ + "citation": 1, + "path": chunk.path, + "start_line": chunk.start_line, + "end_line": chunk.end_line, + "symbol": chunk.symbol, + "text": chunk.text, + "cell": chunk.cell, + },) + return ToolResult( + f"Saved {saved.as_posix()} from {chunk.path.as_posix()} [1].", + evidence, + {"saved": saved.as_posix(), "source": chunk.path.as_posix()}, + ) diff --git a/examples/plugins/tools/word_count/README.md b/examples/plugins/tools/word_count/README.md new file mode 100644 index 00000000..360db122 --- /dev/null +++ b/examples/plugins/tools/word_count/README.md @@ -0,0 +1,15 @@ +# Word count + +Count whitespace-separated words in a UTF-8 Markdown output, using a bounded +read of at most 1 MiB plus one byte. Report the most frequent case-folded +words. This is not a linguistic tokenizer; punctuation remains part of a word. +No model, external source or network service is used. It reads a direct regular +file under `outputs/`, rejects path traversal, symlinks and linked output +folders, and does not modify the file. The checks are not a security sandbox. + +`top_words` is an integer from 1 to 50, default 5; the accompanying project +type selects 3. Use a request such as `count words in source_note.md` with an +existing Markdown output of that name, or supply only the basename. A missing, +invalid or oversized output yields a diagnostic with no evidence claim. +The tool is useful in an intent added to a project type that generates reports; +Tutorial 180 demonstrates this with a generated paper summary. diff --git a/examples/plugins/tools/word_count/__init__.py b/examples/plugins/tools/word_count/__init__.py new file mode 100644 index 00000000..23cc2da4 --- /dev/null +++ b/examples/plugins/tools/word_count/__init__.py @@ -0,0 +1,120 @@ +"""A deterministic word counter for a Markdown file in workspace outputs. + +This example accompanies Tutorial 180. It uses no private KíLín imports, +models or external services. It accepts an exact output basename. + +""" + +from collections import Counter +from dataclasses import dataclass +from pathlib import Path + +from kilin.tools import ( + Tool, ToolContext, ToolRequest, ToolResult, check_int, reject_unknown, +) + + +@dataclass(frozen=True, slots=True) +class WordCountSettings: + """Settings for reporting frequent words. + + Attributes + ---------- + top_words: int + Number of frequent words to include, from one to fifty. + + """ + + top_words: int = 5 + + +def parse_settings(data: dict, where: str) -> WordCountSettings: + """Validate settings from an intent or workspace. + + Parameters + ---------- + data: dict + Raw settings, excluding the name. + where: str + Diagnostic location of the configuration. + + Returns + ------- + WordCountSettings + Validated settings. + + """ + + reject_unknown(where, data, ("top_words",)) + return WordCountSettings( + top_words=check_int(where, data, "top_words", 5, 1, 50) + ) + + +def run( + settings: WordCountSettings, request: ToolRequest, context: ToolContext, +) -> ToolResult: + """Count whitespace-separated words in a bounded Markdown output. + + Parameters + ---------- + settings: WordCountSettings + Validated number of frequent words to report. + request: ToolRequest + Exact output basename, optionally after "count words in ". + context: ToolContext + Workspace root and progress service. + + Returns + ------- + ToolResult + Word counts or a diagnostic, with no source-evidence claim. + + """ + + name = request.question.strip() + prefix = "count words in " + if name.lower().startswith(prefix): + name = name[len(prefix):].strip() + path = Path(name) + # Restrict the example to a direct, regular Markdown output, never a + # user-supplied absolute path, subdirectory or symlink. + if (path.name != name or "/" in name or "\\" in name + or path.suffix.lower() != ".md" or ":" in name): + return ToolResult("Choose a Markdown output basename.", (), {}) + folder = context.project_root / "outputs" + file = folder / name + try: + if ( + folder.is_symlink() or folder.is_junction() + or file.is_symlink() or not file.is_file() + or file.resolve().parent != folder.resolve() + or folder.resolve().parent != context.project_root.resolve() + ): + return ToolResult("That output is unavailable.", (), {}) + with file.open("rb") as stream: + content = stream.read(1024 * 1024 + 1) + if len(content) > 1024 * 1024: + return ToolResult("Output exceeds the 1 MiB limit.", (), {}) + words = content.decode("utf-8").split() + except (OSError, UnicodeError, ValueError): + return ToolResult("Could not read the Markdown output.", (), {}) + top = Counter(word.casefold() for word in words).most_common( + settings.top_words + ) + context.done(f"Counted {len(words)} words") + answer = f"{name} has {len(words):,} whitespace-separated words." + answer += "\nFrequent words: " + ", ".join( + f"{word} ({count})" for word, count in top + ) + return ToolResult(answer, (), {"count": len(words), "top": top}) + + +PLUGIN = Tool( + name="word_count", + summary="Count words in a Markdown output file.", + version="0.1.0", + api_version=1, + parse_settings=parse_settings, + run=run, +) diff --git a/kilin/__init__.py b/kilin/__init__.py index 2355ef47..60893825 100644 --- a/kilin/__init__.py +++ b/kilin/__init__.py @@ -5,7 +5,8 @@ KíLín documentation use this namespace when an object is exported here. Objects exported only by a submodule must be accessed through that submodule. -Importing this package does not construct a model session or start the GUI. +Importing this package does not construct a tool or project-type catalog, +construct a model session, or start the GUI. Model sessions load their backend dependencies when instantiated; the GUI has a separate entry point. Imported submodules may nevertheless require non-model dependencies such as NumPy. @@ -33,7 +34,7 @@ Examples -------- >>> import kilin ->>> isinstance(kilin.PROJECT_TYPE_IDS, tuple) +>>> isinstance(kilin.project_type_ids(), tuple) True """ @@ -96,9 +97,10 @@ format_qwen3_query, ) from .project import ( - PROJECT_TYPE_IDS, + project_type_ids, ProjectTypeId, ProjectProfile, + ProjectCreationProvenance, QAProject, initialize_project, ProjectAlreadyExistsError, @@ -123,6 +125,59 @@ MACHINE_STATE_CHOICES, MachineState, ) +from .source_views import ( + ScopeMode, + SourcePurpose, + SourceScope, + SourcePolicy, + SourceFileState, + SourceInventory, + SourceOperation, + SourceView, + SourceGroup, + UnavailableMember, + SourceViewConflict, + capture_source_inventory, + resolve_source_view, + validate_source_view, + read_source_bytes, +) +from .source_manifest import ( + SOURCE_MANIFEST_FILE, + SOURCE_ORGANIZATION_FORMAT, + SourceRoot, + OrganizationIdentity, + AcceptedOrganization, + SourceRole, + RelationKey, + SourceRelation, + UnresolvedSource, + SourceManifest, + SourceManifestSnapshot, + SourceManifestInspection, + SourceManifestPreview, + SourceManifestResult, + SourceLifecycleResult, + SourceManifestConflict, + DiscoveryDiagnostic, + SourceDiscovery, + RoleEdit, + RelationEdit, + ResolveSourceEdit, + SourceManifestEdit, + initialize_source_manifest, + read_source_manifest, + inspect_source_manifest, + preview_source_manifest, + apply_source_manifest, + refresh_source_manifest, +) +from .source_organization import ( + DiscoveryRule, + RelationType, + SourceOrganization, + parse_source_organization, +) from .project_type import ( MEMORY_ANSWER_CHOICES, MEMORY_INDEXING_CHOICES, @@ -146,10 +201,14 @@ MemoryIndexingPolicy, MemoryQuestionPolicy, ProjectType, + ProjectTypeInfo, + PROJECT_TYPE_SCHEMA_VERSION, RetrievalMode, RetrievalStrategy, load_project_types, project_type, + project_type_catalog, + project_type_raw, ) from .tools import ( CONFIRMATION_ALWAYS, @@ -161,11 +220,13 @@ PLAN_CHOICE_CONTINUE, PLAN_CHOICE_QUICK, TOOL_BATCH_CLASSIFY, - TOOL_CHOICES, + tool_choices, TOOL_SCAN_AND_LIST, ConfirmationPolicy, PlanChoice, ToolContext, + ToolSourceServices, + require_source_services, ToolName, ToolPlan, ToolRequest, @@ -190,6 +251,7 @@ ProgressCallback, ProgressEvent, RAGSession, + SourceMetadataRefresh, ) from .repository import ( build_repository_manifest, @@ -198,6 +260,7 @@ repository_has_changed, scan_repository, ) +from .retrievals.requests import SourceGroupCoverage, group_coverage from .retrievals import ( DOCUMENT_REASON_CHOICES, DOCUMENT_REASON_NAMED_FILE, @@ -251,6 +314,7 @@ read_repository_files, ) from .trace_logging import ( + TRACE_FORMAT_VERSION, FAILURE_POLICY_CHOICES, FAILURE_POLICY_RAISE, FAILURE_POLICY_WARN, @@ -268,6 +332,7 @@ ) from .project_files import ( add_project_files, + create_project_folder, list_project_files, remove_project_files, replace_project_file, @@ -286,11 +351,16 @@ sync_project_sources, ) +from .versioning import version_info + __all__ = [ + "project_type_ids", + "tool_choices", "get_setting_info", "get_settings_info", "get_tool_settings_info", "__version__", + "version_info", "ANSWER_PHASE_CHOICES", "ANSWER_PHASE_COMPLETED", "ANSWER_PHASE_EVIDENCE_READY", @@ -339,17 +409,18 @@ "LexicalResult", "PersistentIndexes", "PROJECT_BEHAVIOR_FILE", - "PROJECT_TYPE_IDS", "ProjectTypeId", "QUERY_FORMAT_CHOICES", "QUERY_FORMAT_PLAIN", "QUERY_FORMAT_QWEN3", "QueryFormat", "ProjectProfile", + "ProjectCreationProvenance", "ProgressCallback", "ProgressEvent", "QAProject", "RAGSession", + "SourceMetadataRefresh", "ContextExpansionPlan", "SYSTEM_ROLE", "SelectedBackend", @@ -357,6 +428,7 @@ "SemanticResult", "SourceFile", "SourceUnit", + "TRACE_FORMAT_VERSION", "TRACE_EVENT_ANSWER_ACTIVITY", "TRACE_EVENT_EMBEDDING_TOKENS_PREPARED", "TRACE_EVENT_LLM_CALL_INPUT", @@ -423,6 +495,7 @@ "SourceChanges", "SourceVersion", "add_project_files", + "create_project_folder", "replace_project_file", "remove_project_files", "list_project_files", @@ -449,11 +522,12 @@ "PLAN_CHOICE_CONTINUE", "PLAN_CHOICE_QUICK", "TOOL_BATCH_CLASSIFY", - "TOOL_CHOICES", "TOOL_SCAN_AND_LIST", "ConfirmationPolicy", "PlanChoice", "ToolContext", + "ToolSourceServices", + "require_source_services", "ToolName", "ToolPlan", "ToolRequest", @@ -480,10 +554,63 @@ "MemoryIndexingPolicy", "MemoryQuestionPolicy", "ProjectType", + "ProjectTypeInfo", + "DiscoveryRule", + "RelationType", + "SourceOrganization", + "SOURCE_MANIFEST_FILE", + "SOURCE_ORGANIZATION_FORMAT", + "SourceRoot", + "OrganizationIdentity", + "AcceptedOrganization", + "SourceRole", + "RelationKey", + "SourceRelation", + "UnresolvedSource", + "SourceManifest", + "SourceManifestSnapshot", + "SourceManifestInspection", + "ScopeMode", + "SourcePurpose", + "SourceScope", + "SourcePolicy", + "SourceFileState", + "SourceInventory", + "SourceOperation", + "SourceView", + "SourceGroup", + "UnavailableMember", + "SourceViewConflict", + "capture_source_inventory", + "resolve_source_view", + "validate_source_view", + "read_source_bytes", + "SourceGroupCoverage", + "group_coverage", + "SourceManifestPreview", + "SourceManifestResult", + "SourceLifecycleResult", + "SourceManifestConflict", + "DiscoveryDiagnostic", + "SourceDiscovery", + "RoleEdit", + "RelationEdit", + "ResolveSourceEdit", + "SourceManifestEdit", + "initialize_source_manifest", + "read_source_manifest", + "inspect_source_manifest", + "preview_source_manifest", + "apply_source_manifest", + "refresh_source_manifest", + "parse_source_organization", + "PROJECT_TYPE_SCHEMA_VERSION", "RetrievalMode", "RetrievalStrategy", "load_project_types", "project_behavior_settings", "save_project_behavior", "project_type", + "project_type_catalog", + "project_type_raw", ] diff --git a/kilin/_latex_sources.py b/kilin/_latex_sources.py new file mode 100644 index 00000000..87c21c29 --- /dev/null +++ b/kilin/_latex_sources.py @@ -0,0 +1,179 @@ +"""Extract literal LaTeX bibliography names and resolve selected paths. + +This neutral core module never opens files, follows TeX input commands, +parses bibliography entries or determines which bibliography a tool uses. + +Key Features +------------ +- Literal directive parsing without expansion or file access. +- Deterministic, selection-only companion resolution. +- Comment and verbatim-example masking for discovery. + +Module Structure +---------------- +- ``bibliography_names`` extracts literal directive arguments in order. +- ``resolve_companion`` resolves only names in an authorized collection. +- ``discovery_text`` masks comments and verbatim examples for discovery. + +Examples +-------- +>>> bibliography_names(r"\\bibliography{first,second.bib}") +('first', 'second.bib') + +""" + +from __future__ import annotations + +from collections.abc import Collection +from pathlib import Path, PurePosixPath, PureWindowsPath +import posixpath +import re +from typing import Final + +__all__ = [] + +_BIB_FILES: Final[re.Pattern[str]] = re.compile( + r"(? tuple[str, ...]: + """Return nonempty literal bibliography arguments in directive order. + + Parameters + ---------- + text: str + LaTeX with comments and examples already masked by the caller. + top_level_only: bool, optional + Ignore directives nested in brace groups for conservative discovery. + + Returns + ------- + tuple[str, ...] + Names from ``bibliography`` and ``addbibresource`` directives. + No macro expansion or file access is performed. + + """ + names = [] + depth, position = 0, 0 + for match in _BIB_FILES.finditer(text): + if top_level_only: + # Do not infer dependencies from macro definitions or examples + # nested in argument groups. Escaped braces are not groups. + for token in _BRACE.finditer(text, position, match.start()): + if token.group() == "{": + depth += 1 + elif token.group() == "}": + depth = max(depth - 1, 0) + position = match.end() + if depth: + continue + names.extend(name.strip() for name in match.group(1).split(",") + if name.strip()) + return tuple(names) + + +def discovery_text(text: str) -> str: + """Mask comments and verbatim examples before literal discovery. + + Parameters + ---------- + text: str + Complete selected LaTeX source text. + + Returns + ------- + str + Text suitable for conservative directive recognition. Lines in + verbatim-like environments are ignored, including their boundaries. + + """ + lines = [] + inside = None + for line in text.splitlines(): + if inside is not None: + if re.search(r"\\end\s*\{" + re.escape(inside) + r"\}", line): + inside = None + lines.append("") + continue + line = _COMMENT.sub("", _INLINE_VERB.sub("", line)) + match = _VERBATIM.search(line) + if match: + name = match.group(1) + if not re.search(r"\\end\s*\{" + re.escape(name) + r"\}", + line[match.end():]): + inside = name + lines.append("") + else: + lines.append(line) + return "\n".join(lines) + + +def resolve_companion( + name: str, + paper: Path, + available: Collection[Path], +) -> tuple[Path | None, str]: + """Find a selected companion, preferring the paper's own directory. + + Parameters + ---------- + name: str + A LaTeX bibliography argument or expected compiled bibliography. + paper: pathlib.Path + Source-relative path of the referring LaTeX document. + available: Collection[pathlib.Path] + Authorized source-relative bibliography paths. + + Returns + ------- + tuple[pathlib.Path | None, str] + Chosen source-relative path and an empty diagnostic, or ``None`` + and an explanation. Duplicate basenames without a local match + remain ambiguous instead of selecting an unrelated bibliography. + + """ + + raw = name.strip() + posix = PurePosixPath(raw) + windows = PureWindowsPath(raw) + if ( + not raw or not posix.name or posix.name == ".." + or any(ord(character) < 32 for character in raw) + or ":" in raw or "\\" in raw or posix.is_absolute() + or windows.is_absolute() or windows.drive + ): + return None, f"{name} (invalid path)" + suffix = posix.suffix.lower() + if suffix not in {".bib", ".bbl"}: + posix = posix.with_name(posix.name + ".bib") + relative = PurePosixPath(posixpath.normpath( + (PurePosixPath(paper.parent.as_posix()) / posix).as_posix() + )) + if ".." in relative.parts or relative.is_absolute(): + return None, f"{name} (outside sources)" + local = Path(relative.as_posix()) + if local in available: + return local, "" + if "/" in raw: + return None, name + matches = [ + path for path in available + if path.name.casefold() == posix.name.casefold() + ] + if len(matches) == 1: + return matches[0], "" + if len(matches) > 1: + return None, f"{name} (ambiguous)" + return None, name diff --git a/kilin/_source_access.py b/kilin/_source_access.py new file mode 100644 index 00000000..0c99689b --- /dev/null +++ b/kilin/_source_access.py @@ -0,0 +1,100 @@ +"""Resolve authorized source files within a project workspace. + +Share the selected-file raw-read boundary between core discovery and +reference tools. No filename mentioned in a document grants access. + +Key Features +------------ +- Explicit selection membership and regular-file validation. +- Workspace containment without fallback to external originals. + +Module Structure +---------------- +- ``selected_source_file``: resolve a selected regular workspace file. + +Examples +-------- +>>> from pathlib import Path +>>> selected_source_file(Path("/missing"), Path("/missing/sources"), +... Path("paper.tex"), {Path("paper.tex")}) is None +True + +""" + +from __future__ import annotations + +from collections.abc import Collection +from pathlib import Path + +from kilin.workspace_resources import PROJECT_SOURCES_DIRECTORY + +__all__ = [] + + +def selected_source_file( + project_root: Path, + source_root: Path, + path: Path, + selected: Collection[Path], +) -> Path | None: + """Locate one selected regular file under the project source root. + + Parameters + ---------- + project_root: pathlib.Path + Workspace root, containing project state and managed sources. + source_root: pathlib.Path + Canonical real ``sources`` directory inside the workspace. + path: pathlib.Path + Source-relative file path, as recorded by the source inventory. + selected: Collection[pathlib.Path] + Explicitly selected source-relative file paths. + + Returns + ------- + pathlib.Path | None + Validated source file path, or ``None`` if the selection, file, + source root, containment or symlink conditions fail. + + Notes + ----- + No fallback searches the workspace root or an original import folder. + 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. + + """ + + if not isinstance(path, Path) or path.is_absolute(): + return None + if not path.parts or any(part in ("", ".", "..") for part in path.parts): + return None + if path.as_posix() not in {item.as_posix() for item in selected}: + 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 / PROJECT_SOURCES_DIRECTORY + or not source.is_dir() + ): + return None + candidate = source + for part in path.parts: + candidate = candidate / part + if candidate.is_symlink() or candidate.is_junction(): + return None + target = candidate.resolve(strict=True) + if target.is_relative_to(source) and target.is_file(): + return candidate + except (OSError, ValueError): + pass + return None diff --git a/kilin/_source_discovery.py b/kilin/_source_discovery.py new file mode 100644 index 00000000..38794002 --- /dev/null +++ b/kilin/_source_discovery.py @@ -0,0 +1,336 @@ +"""Reconcile deterministic relationships under accepted project settings. + +Discovery is a pure semantic proposal over the selected inventory. It never +writes files, runs TeX, reads bibliography entries, infers primary roles, +or calls a model. Manual links and exact suppressions outrank detectors. + +Key Features +------------ +- Accepted detector identities and deterministic rule reconciliation. +- Manual precedence, suppression and unavailable-source diagnostics. +- Immutable applied deltas and nonpersistent proposals. + +Module Structure +---------------- +- ``DiscoveryDiagnostic`` and ``SourceDiscovery`` expose immutable deltas. +- ``detector_versions`` identifies the available implementations. +- ``reconcile_discovery`` reconciles active automatic relationships. + +Examples +-------- +>>> detector_versions(SourceOrganization(("document",), "document")) +() + +""" + +from __future__ import annotations + +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Final + +from kilin._latex_sources import ( + bibliography_names, discovery_text, resolve_companion, +) +from kilin._source_access import selected_source_file +from kilin._source_manifest import ( + RelationKey, SourceManifest, SourceRelation, _MAX_LINKS, + active_relations, active_roles, manifest_data, parse_manifest, +) +from kilin.source_organization import SourceOrganization + +__all__ = [] + +# Increment when resolution semantics change, even within a prerelease. +_DETECTOR_VERSIONS: Final[dict[str, str]] = {"latex_bibliography": "1"} + + +@dataclass(frozen=True, slots=True, order=True) +class DiscoveryDiagnostic: + """One deterministic discovery limitation or conflict. + + Attributes + ---------- + rule: str + Accepted rule identifier. + target: str + Referring source path, or an empty string for a rule-wide issue. + reason: str + Machine-readable diagnostic category. + detail: str + Human-readable explanation or unresolved declaration. + + """ + + rule: str + target: str + reason: str + detail: str + + +@dataclass(frozen=True, slots=True) +class SourceDiscovery: + """Automatic changes and uncommitted proposals from one reconciliation. + + Attributes + ---------- + added: tuple[SourceRelation, ...] + Newly applied rule-owned edges. + removed: tuple[SourceRelation, ...] + Reconciled rule-owned edges no longer supported by the detector. + proposed: tuple[SourceRelation, ...] + Eligible edges from rules in propose mode, not saved as links. + diagnostics: tuple[DiscoveryDiagnostic, ...] + Unavailable inputs, unresolved names, or blocked relationships. + + """ + + added: tuple[SourceRelation, ...] = () + removed: tuple[SourceRelation, ...] = () + proposed: tuple[SourceRelation, ...] = () + diagnostics: tuple[DiscoveryDiagnostic, ...] = () + + +def detector_versions( + declaration: SourceOrganization, +) -> tuple[tuple[str, str], ...]: + """Return installed identities for exactly the declared detectors. + + Parameters + ---------- + declaration: SourceOrganization + Accepted or proposed discovery declarations. + + Returns + ------- + tuple[tuple[str, str], ...] + Sorted detector names and implementation versions. + + """ + return tuple(sorted((rule.detector, _DETECTOR_VERSIONS[rule.detector]) + for rule in declaration.automatic_rules)) + + +def _latex_links( + project_root: Path, source_root: Path, paths: set[str], + selected_paths: tuple[str, ...], rule_id: str, relation: str, + max_file_bytes: int, +) -> tuple[set[SourceRelation], set[str], list[DiscoveryDiagnostic]]: + """Detect literal bibliography dependencies among active source paths. + + Parameters + ---------- + project_root: pathlib.Path + Workspace root; external raw reads remain disallowed. + source_root: pathlib.Path + Configured source directory. + paths: set[str] + Active authorized source-relative paths. + selected_paths: tuple[str, ...] + Full selection, including unresolved paths. Name resolution must + not substitute another file for an inactive local companion. + rule_id: str + Accepted rule that owns any inferred edges. + relation: str + Declared dependency relation. + max_file_bytes: int + Profile limit on bytes read from one source. + + Returns + ------- + tuple + Detected relationships, targets whose text could not be read, and + diagnostics. A read failure is not evidence that a link vanished. + + """ + selected = {Path(name) for name in paths} + bibliographies = {Path(name) for name in selected_paths + if Path(name).suffix.lower() in {".bib", ".bbl"}} + compiled_by_paper = {path.with_suffix(".tex"): path + for path in bibliographies + if path.suffix.lower() == ".bbl"} + links: set[SourceRelation] = set() + unavailable: set[str] = set() + diagnostics = [] + for paper in sorted(selected): + if paper.suffix.lower() != ".tex": + continue + target = paper.as_posix() + file = selected_source_file(project_root, source_root, paper, + selected) + try: + if file is None: + raise OSError("Source is not authorized for raw reading.") + with file.open("rb") as stream: + content = stream.read(max_file_bytes + 1) + if len(content) > max_file_bytes: + raise OSError("Source exceeds the configured size limit.") + text = content.decode("utf-8", errors="strict") + except (OSError, UnicodeError): + unavailable.add(target) + diagnostics.append(DiscoveryDiagnostic( + rule_id, target, "source_unavailable", + "Cannot read selected LaTeX source safely as UTF-8.", + )) + continue + companions = set() + # Compiled output is implicit, so require an exact local match; + # a distant same-stem file alone is not enough to infer a link. + compiled = compiled_by_paper.get(paper.with_suffix(".tex")) + if compiled is not None and compiled in selected: + companions.add(compiled) + for name in bibliography_names(discovery_text(text), + top_level_only=True): + path, problem = resolve_companion(name, paper, bibliographies) + if path is None: + diagnostics.append(DiscoveryDiagnostic( + rule_id, target, "unresolved_bibliography", problem, + )) + elif path not in selected: + diagnostics.append(DiscoveryDiagnostic( + rule_id, target, "inactive_bibliography", path.as_posix(), + )) + else: + companions.add(path) + for path in companions: + links.add(SourceRelation( + RelationKey(path.as_posix(), target, relation), + "rule", rule_id, + )) + if len(links) > _MAX_LINKS or len(diagnostics) > _MAX_LINKS: + raise ValueError("Source discovery exceeds the manifest limit.") + return links, unavailable, diagnostics + + +def _reaches(outgoing: dict[str, set[str]], start: str, end: str) -> bool: + """Check whether a proposed dependency would close a directed cycle. + + Parameters + ---------- + outgoing: dict[str, set[str]] + Accepted dependent-to-parent adjacency. + start: str + Proposed parent, where traversal starts. + end: str + Proposed dependent, which must not be reachable from the parent. + + Returns + ------- + bool + Whether a path exists from start to end. + + """ + pending = [start] + seen = set() + while pending: + path = pending.pop() + if path == end: + return True + if path not in seen: + seen.add(path) + pending.extend(outgoing.get(path, ())) + return False + + +def reconcile_discovery( + project_root: Path, source_root: Path, max_file_bytes: int, + manifest: SourceManifest, selected: tuple[str, ...], *, + retained_versions: tuple[str, ...] = (), +) -> tuple[SourceManifest, SourceDiscovery]: + """Apply accepted discovery rules to a manually edited proposal. + + Parameters + ---------- + project_root: pathlib.Path + Workspace root. + source_root: pathlib.Path + Configured source directory. + max_file_bytes: int + Maximum bytes allowed per LaTeX source. + manifest: SourceManifest + Candidate state after selection reconciliation and explicit edits. + selected: tuple[str, ...] + Complete authorized source inventory. + retained_versions: tuple[str, ...], optional + Selected historical copies, not automatic current-document targets. + + Returns + ------- + tuple[SourceManifest, SourceDiscovery] + Validated semantic proposal and its automatic changes. Existing + manual and inactive edges are retained. Unaccepted implementations + do not reinterpret old automatic records. + + """ + organization = manifest.organization + declaration = organization.declaration + if not declaration.automatic_rules: + return parse_manifest(manifest_data(manifest)), SourceDiscovery() + retained = set(retained_versions) + all_active = {role.path for role in active_roles(manifest, set(selected))} + active = all_active - retained + current = tuple(path for path in selected if path not in retained) + links = {item.key: item for item in manifest.relations} + original = dict(links) + suppressed = set(manifest.suppressed_automatic) + diagnostics = [] + candidates = [] + versions = dict(organization.detector_versions) + for rule in declaration.automatic_rules: + version = _DETECTOR_VERSIONS[rule.detector] + if versions[rule.detector] != version: + diagnostics.append(DiscoveryDiagnostic( + rule.id, "", "detector_version_mismatch", + f"Accepted {versions[rule.detector]!r}; installed " + f"{version!r}. Preview explicit detector adoption.", + )) + continue + found, unavailable, problems = _latex_links( + project_root, source_root, active, current, rule.id, + rule.relation, max_file_bytes, + ) + diagnostics.extend(problems) + # Re-evaluate only active edges owned by this rule. Retain inactive + # and unreadable records for explicit resolution or a later scan. + links = {key: item for key, item in links.items() if not ( + item.origin == "rule" and item.rule == rule.id + and key.source in active and key.target in active + and key.target not in unavailable + )} + candidates.extend((item, rule.mode) for item in found) + base = parse_manifest(manifest_data(replace( + manifest, relations=tuple(links.values()), + ))) + # Manual dependencies are validated first. A detected edge may not + # force a user to remove a valid manual decision just to reconcile. + dependency = {r.id for r in declaration.relation_types + if r.behavior == "dependency"} + outgoing: dict[str, set[str]] = {} + for item in active_relations(base, all_active): + key = item.key + if key.type in dependency: + outgoing.setdefault(key.source, set()).add(key.target) + proposals = [] + for item, mode in sorted(candidates, key=lambda pair: pair[0].key): + key = item.key + if key in links or key in suppressed: + continue + if _reaches(outgoing, key.target, key.source): + diagnostics.append(DiscoveryDiagnostic( + item.rule, key.target, "dependency_cycle", key.source, + )) + continue + if mode == "propose": + proposals.append(item) + continue + links[key] = item + outgoing.setdefault(key.source, set()).add(key.target) + after = parse_manifest(manifest_data(replace( + base, relations=tuple(links.values()), + ))) + report = SourceDiscovery( + tuple(links[key] for key in sorted(links.keys() - original.keys())), + tuple(original[key] for key in sorted(original.keys() - links.keys())), + tuple(proposals), tuple(sorted(set(diagnostics))), + ) + return after, report diff --git a/kilin/_source_manifest.py b/kilin/_source_manifest.py new file mode 100644 index 00000000..84776774 --- /dev/null +++ b/kilin/_source_manifest.py @@ -0,0 +1,674 @@ +"""Define the immutable semantic source-manifest format and its validator. + +The persisted record describes accepted organization, not file contents or +permission to read them. Parsing is independent of a workspace, installed +project types, and models. Live availability is resolved by source_manifest. + +Key Features +------------ +- Strict, bounded JSON records with canonical paths and stable ordering. +- Directed acyclic dependencies, symmetric associations and orphan records. + +Module Structure +---------------- +- Immutable records represent the accepted vocabulary, assignments and links. +- ``parse_manifest`` and ``manifest_data`` own the disk representation. + +Examples +-------- +>>> from kilin.source_manifest import SOURCE_ORGANIZATION_FORMAT +>>> SOURCE_ORGANIZATION_FORMAT +'kilin-source-manifest-v2' + +""" + +from __future__ import annotations + +from collections import deque +from dataclasses import asdict, dataclass +from pathlib import PureWindowsPath +import re +from typing import Final +import unicodedata + +from kilin.plugins._versioning import _require_semver +from kilin.source_organization import ( + SourceOrganization, _identifier, parse_source_organization, +) + +__all__ = [] + +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 +_MAX_LINKS: Final[int] = 40_000 +_MAX_DECLARATIONS: Final[int] = 256 +_MAX_REVISION: Final[int] = 2**63 - 1 + + +@dataclass(frozen=True, slots=True) +class SourceRoot: + """Bind accepted file identities to the canonical project sources. + + Attributes + ---------- + base: str + ``project``; other source-root bases are unsupported. + path: str + ``sources``; identities remain relative when the workspace moves. + + """ + + base: str + path: str + + +@dataclass(frozen=True, slots=True) +class OrganizationIdentity: + """Capture the exact project-type definition from which settings derive. + + Attributes + ---------- + project_type: str + Registered identifier at acceptance time. + project_type_version: str + Implementation SemVer. + schema_version: int + Definition schema generation. + origin: str + Distribution or user definition. + sha256: str + SHA-256 of the captured definition bytes. + + """ + + project_type: str + project_type_version: str + schema_version: int + origin: str + sha256: str + + +@dataclass(frozen=True, slots=True) +class AcceptedOrganization: + """Store project-local organization independently of installed defaults. + + Attributes + ---------- + derived_from: OrganizationIdentity + Origin of the accepted vocabulary, not the current runtime catalog. + declaration: SourceOrganization + Accepted roles, relationship behaviors and discovery settings. + detector_versions: tuple[tuple[str, str], ...] + Accepted implementation identities by declared detector name. + + """ + + derived_from: OrganizationIdentity + declaration: SourceOrganization + detector_versions: tuple[tuple[str, str], ...] + + +@dataclass(frozen=True, slots=True, order=True) +class SourceRole: + """One materialized assignment, including an accepted default. + + Attributes + ---------- + path: str + Canonical source-relative path. + role: str + Accepted role identifier. + origin: str + ``default`` or ``user``. + + """ + + path: str + role: str + origin: str + + +@dataclass(frozen=True, slots=True, order=True) +class RelationKey: + """Identify a relationship independently of its provenance. + + Attributes + ---------- + source, target: str + Canonical source-relative endpoint paths, dependent first for a + dependency and lexically ordered for an association. + type: str + Relationship identifier in the accepted vocabulary. + + """ + + source: str + target: str + type: str + + +@dataclass(frozen=True, slots=True) +class SourceRelation: + """One accepted graph edge with user or deterministic-rule provenance. + + Attributes + ---------- + key: RelationKey + Endpoints and relation identifier. + origin: str + ``user`` or ``rule``. + rule: str | None + Rule identifier for automatic edges; None for manual edges. + + """ + + key: RelationKey + origin: str + rule: str | None = None + + +@dataclass(frozen=True, slots=True, order=True) +class UnresolvedSource: + """Retain a previously accepted path without reactivating its meaning. + + Attributes + ---------- + path: str + Path whose prior assignment is retained. + reason: str + ``removed`` or ``missing_assignment``. + + """ + + path: str + reason: str + + +@dataclass(frozen=True, slots=True) +class SourceManifest: + """Immutable semantic state, independent of live source availability. + + Attributes + ---------- + revision: int + Monotonic semantic revision; initialization starts at zero. + source_root: SourceRoot + Accepted source-root binding. + organization: AcceptedOrganization + Accepted declarations and captured provenance. + files: tuple[SourceRole, ...] + Materialized roles, including unresolved assignments. + relations: tuple[SourceRelation, ...] + Stored graph edges, including inactive edges. + suppressed_automatic: tuple[RelationKey, ...] + Edges which automatic discovery may not recreate. + unresolved: tuple[UnresolvedSource, ...] + Previously accepted paths requiring explicit resolution. + + """ + + revision: int + source_root: SourceRoot + organization: AcceptedOrganization + files: tuple[SourceRole, ...] = () + relations: tuple[SourceRelation, ...] = () + suppressed_automatic: tuple[RelationKey, ...] = () + unresolved: tuple[UnresolvedSource, ...] = () + + +def _exact(value: object, fields: str, where: str) -> dict: + """Require exactly the declared object fields. + + Parameters + ---------- + value: object + Candidate object. + fields: str + Space-separated required keys. + where: str + Diagnostic location. + + Returns + ------- + dict + Checked object. + + """ + if not isinstance(value, dict) or set(value) != set(fields.split()): + raise ValueError(f"Invalid fields in {where}; expected {fields}.") + return value + + +def _bounded(value: object, kind: type, limit: int, where: str) -> object: + """Reject invalid or excessive collection sizes. + + Parameters + ---------- + value: object + Candidate collection. + kind: type + Required container type. + limit: int + Maximum record count. + where: str + Diagnostic location. + + Returns + ------- + object + Checked collection. + + """ + if type(value) is not kind or len(value) > limit: + raise ValueError(f"Invalid or excessive {where} (limit {limit}).") + return value + + +def _text(value: object, where: str, limit: int = 4096) -> str: + """Validate bounded Unicode text without control characters. + + Parameters + ---------- + value: object + Candidate text. + where: str + Diagnostic location. + limit: int, optional + Maximum UTF-8 bytes. + + Returns + ------- + str + Unmodified text. + + """ + if not isinstance(value, str) or not value or any( + unicodedata.category(char) in ("Cc", "Cs") for char in value + ) or len(value.encode("utf-8")) > limit: + raise ValueError(f"Invalid text in {where}.") + return value + + +def canonical_path(value: object) -> str: + """Require a portable, canonical source-relative path without traversal. + + Parameters + ---------- + value: object + Unmodified POSIX relative path string. + + Returns + ------- + str + Validated path. + + """ + name = _text(value, "source path") + parts = name.split("/") + if ("\\" in name or ":" in name or PureWindowsPath(name).drive + or any(p in ("", ".", "..") or p.endswith((" ", ".")) + for p in parts)): + raise ValueError(f"Noncanonical source path: {name!r}.") + return name + + +def check_aliases(paths: object) -> None: + """Reject path aliases conservatively across portable filesystems. + + Parameters + ---------- + paths: Iterable[str] + Canonical path spellings; identical paths may repeat as references. + + """ + spellings: dict[str, str] = {} + for path in paths: + # Check directory components as well as complete names. + parts = path.split("/") + for end in range(1, len(parts) + 1): + prefix = "/".join(parts[:end]) + key = unicodedata.normalize("NFC", prefix).casefold() + previous = spellings.setdefault(key, prefix) + if previous != prefix: + raise ValueError( + f"Source path alias: {previous!r}, {prefix!r}." + ) + + +def root_binding(value: object) -> SourceRoot: + """Validate the saved root identity without opening its path. + + Parameters + ---------- + value: object + JSON root binding. + + Returns + ------- + SourceRoot + Validated binding to the project's ``sources`` directory. + + """ + raw = _exact(value, "base path", "source_root") + 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: + """Validate captured type provenance independently of today's catalog. + + Parameters + ---------- + value: object + JSON identity record. + + Returns + ------- + OrganizationIdentity + Validated historical identity. + + """ + raw = _exact(value, ( + "project_type project_type_version schema_version origin sha256" + ), "derived_from") + _identifier(raw["project_type"], "project_type") + _require_semver(raw["project_type_version"], "project_type_version") + if (type(raw["schema_version"]) is not int + or not 1 <= raw["schema_version"] <= _MAX_REVISION + or raw["origin"] not in ("distribution", "user") + or not isinstance(raw["sha256"], str) + or not re.fullmatch(r"[0-9a-f]{64}", raw["sha256"])): + raise ValueError("Invalid captured project-type identity.") + return OrganizationIdentity(**raw) + + +def _organization(value: object) -> AcceptedOrganization: + """Parse the complete saved vocabulary and detector identities. + + Parameters + ---------- + value: object + JSON organization record. + + Returns + ------- + AcceptedOrganization + Validated accepted settings. + + """ + raw = _exact(value, ( + "derived_from roles default_role relation_types automatic_rules " + "detector_versions" + ), "organization") + data = {k: raw[k] for k in ( + "roles", "default_role", "relation_types", "automatic_rules", + )} + for key, kind in (("roles", list), ("relation_types", dict), + ("automatic_rules", list)): + _bounded(data[key], kind, _MAX_DECLARATIONS, key) + data["relation_types"] = dict(sorted(data["relation_types"].items())) + declaration = parse_source_organization(data) + if set(declaration.relation_ids) != set(data["relation_types"]): + raise ValueError("Saved organization must declare generic relations.") + versions = _bounded(raw["detector_versions"], dict, + _MAX_DECLARATIONS, "detector_versions") + if set(versions) != {r.detector for r in declaration.automatic_rules}: + raise ValueError("Detector identities must match accepted rules.") + return AcceptedOrganization( + _identity(raw["derived_from"]), declaration, + tuple(sorted((key, _text(val, key, 128)) + for key, val in versions.items())), + ) + + +def relation_key( + source: object, target: object, type_id: object, + declaration: SourceOrganization, *, normalize: bool = False, +) -> RelationKey: + """Validate edge identity, canonicalizing symmetric user operations. + + Parameters + ---------- + source: object + Candidate dependent or first endpoint path. + target: object + Candidate parent or second endpoint path. + type_id: object + Candidate relation identifier. + declaration: SourceOrganization + Accepted graph vocabulary. + normalize: bool, optional + Sort association endpoints for user commands, rather than rejecting + noncanonical persisted spelling. + + Returns + ------- + RelationKey + Validated edge key, even if its syntactically valid ID is unknown. + + """ + first, second = canonical_path(source), canonical_path(target) + kind = _identifier(type_id, "Relation type") + if first == second: + raise ValueError("A source cannot be related to itself.") + behaviors = {item.id: item.behavior for item in declaration.relation_types} + if behaviors.get(kind) == "association" and first > second: + if not normalize: + raise ValueError("Association endpoints must be canonical.") + first, second = second, first + return RelationKey(first, second, kind) + + +def active_roles( + manifest: SourceManifest, selected: set[str], +) -> tuple[SourceRole, ...]: + """Select available accepted assignments, never unresolved records. + + Parameters + ---------- + manifest: SourceManifest + Saved state. + selected: set[str] + Current authorized source inventory. + + Returns + ------- + tuple[SourceRole, ...] + Active assignments under the saved declarations. + + """ + unresolved = {item.path for item in manifest.unresolved} + roles = set(manifest.organization.declaration.roles) + return tuple(item for item in manifest.files + if item.path in selected and item.path not in unresolved + and item.role in roles) + + +def active_relations( + manifest: SourceManifest, selected: set[str], +) -> tuple[SourceRelation, ...]: + """Resolve graph edges using accepted endpoints and relation types. + + Parameters + ---------- + manifest: SourceManifest + Saved state. + selected: set[str] + Current authorized source inventory. + + Returns + ------- + tuple[SourceRelation, ...] + Active links; unknown or unavailable endpoints stay inspectable. + + """ + paths = {item.path for item in active_roles(manifest, selected)} + declaration = manifest.organization.declaration + kinds = set(declaration.relation_ids) + rules = {item.id: item.relation for item in declaration.automatic_rules} + suppressed = set(manifest.suppressed_automatic) + return tuple(item for item in manifest.relations + if item.key.source in paths and item.key.target in paths + and item.key.type in kinds + and (item.origin == "user" or ( + item.key not in suppressed + and rules.get(item.rule) == item.key.type))) + + +def _check_graph(manifest: SourceManifest) -> None: + """Reject dependency cycles using an iterative topological traversal. + + Parameters + ---------- + manifest: SourceManifest + Structurally decoded state, including inactive records. + + """ + paths = {item.path for item in manifest.files} + kinds = {r.id for r in manifest.organization.declaration.relation_types + if r.behavior == "dependency"} + incoming: dict[str, int] = {} + outgoing: dict[str, list[str]] = {} + for item in active_relations(manifest, paths): + key = item.key + if key.type not in kinds: + continue + incoming.setdefault(key.source, 0) + incoming[key.target] = incoming.get(key.target, 0) + 1 + outgoing.setdefault(key.source, []).append(key.target) + queue = deque(path for path, count in incoming.items() if count == 0) + visited = 0 + while queue: + path = queue.popleft() + visited += 1 + for parent in outgoing.get(path, ()): + incoming[parent] -= 1 + if incoming[parent] == 0: + queue.append(parent) + if visited != len(incoming): + raise ValueError("Source dependencies contain a directed cycle.") + + +def parse_manifest(value: object) -> SourceManifest: + """Decode a strict semantic manifest, retaining inactive orphan records. + + Parameters + ---------- + value: object + JSON-compatible data with duplicate keys already rejected. + + Returns + ------- + SourceManifest + Structurally valid immutable state. + + """ + raw = _exact(value, ( + "format revision source_root organization files relations " + "suppressed_automatic unresolved" + ), "source manifest") + if raw["format"] != SOURCE_ORGANIZATION_FORMAT: + raise ValueError("Unsupported semantic source-manifest format.") + revision = raw["revision"] + if type(revision) is not int or not 0 <= revision <= _MAX_REVISION: + raise ValueError("Invalid source-manifest revision.") + binding = root_binding(raw["source_root"]) + organization = _organization(raw["organization"]) + declaration = organization.declaration + files = [] + for name, value in _bounded(raw["files"], dict, _MAX_FILES, + "files").items(): + row = _exact(value, "role origin", "file assignment") + role = _identifier(row["role"], "File role") + if row["origin"] not in ("default", "user"): + raise ValueError("Invalid role origin.") + files.append(SourceRole(canonical_path(name), role, row["origin"])) + relations = [] + for value in _bounded(raw["relations"], list, _MAX_LINKS, "relations"): + row = _exact(value, "source target type origin rule", "relation") + key = relation_key(row["source"], row["target"], row["type"], + declaration) + if row["origin"] == "rule": + _identifier(row["rule"], "Relation rule") + elif row["origin"] != "user" or row["rule"] is not None: + raise ValueError("Invalid relation provenance.") + relations.append(SourceRelation(key, row["origin"], row["rule"])) + suppressed = [] + for value in _bounded(raw["suppressed_automatic"], list, _MAX_LINKS, + "suppressions"): + row = _exact(value, "source target type", "suppression") + suppressed.append(relation_key( + row["source"], row["target"], row["type"], declaration, + )) + unresolved = [] + for value in _bounded(raw["unresolved"], list, _MAX_FILES, "unresolved"): + row = _exact(value, "path reason", "unresolved source") + path = canonical_path(row["path"]) + if row["reason"] not in ( + "removed", "missing_assignment" + ): + raise ValueError("Invalid unresolved reason.") + unresolved.append(UnresolvedSource(path, row["reason"])) + keys = [item.key for item in relations] + paths = {item.path for item in files} + inactive = {item.path for item in unresolved} + if (len(set(keys)) != len(keys) + or len(set(suppressed)) != len(suppressed) + or len(inactive) != len(unresolved)): + raise ValueError("Duplicate source relation, suppression or orphan.") + if not inactive <= paths: + raise ValueError("Unresolved path has no retained assignment.") + check_aliases((*paths, *(p for key in (*keys, *suppressed) + for p in (key.source, key.target)))) + manifest = SourceManifest( + revision, binding, organization, tuple(sorted(files)), + tuple(sorted(relations, key=lambda item: item.key)), + tuple(sorted(suppressed)), tuple(sorted(unresolved)), + ) + _check_graph(manifest) + return manifest + + +def manifest_data(manifest: SourceManifest) -> dict: + """Produce the complete JSON representation without runtime dependencies. + + Parameters + ---------- + manifest: SourceManifest + Semantic state. + + Returns + ------- + dict + Fresh JSON-compatible data. + + """ + org = manifest.organization + declaration = org.declaration + return { + "format": SOURCE_ORGANIZATION_FORMAT, + "revision": manifest.revision, + "source_root": asdict(manifest.source_root), + "organization": { + "derived_from": asdict(org.derived_from), + "roles": list(declaration.roles), + "default_role": declaration.default_role, + "relation_types": {r.id: {"behavior": r.behavior} + for r in declaration.relation_types}, + "automatic_rules": [ + asdict(r) for r in declaration.automatic_rules + ], + "detector_versions": dict(org.detector_versions), + }, + "files": {r.path: {"role": r.role, "origin": r.origin} + for r in manifest.files}, + "relations": [{**asdict(r.key), "origin": r.origin, "rule": r.rule} + for r in manifest.relations], + "suppressed_automatic": [ + asdict(k) for k in manifest.suppressed_automatic + ], + "unresolved": [asdict(r) for r in manifest.unresolved], + } 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 new file mode 100644 index 00000000..48fd590e --- /dev/null +++ b/kilin/_tool_sources.py @@ -0,0 +1,244 @@ +"""Bind trusted tool services to a single accepted source generation. + +A tool can use several policies, for example one citing document and a +separate set of candidate publications. Resolve every view against one +frozen semantic and physical state. Reuse query embeddings across views, +without scoring excluded passages, and return verified bytes rather than +paths that could be reopened after their content changed. + +Key Features +------------ +- Lazy operation capture only for tools requesting scoped services. +- Exact membership and generation validation for every bound service. +- Independent policy views and shared query vectors within one tool run. + +Module Structure +---------------- +- ``ToolSourceHost``: capture and bind source services for one tool run. + +Examples +-------- +>>> from kilin._tool_sources import ToolSourceHost +>>> callable(ToolSourceHost.bind) +True + +""" + +from __future__ import annotations + +from dataclasses import asdict, replace +from pathlib import Path +from typing import TYPE_CHECKING + +from kilin.retrievals._scope import rank_members +from kilin.retrievals.requests import RetrievalRequest, RetrievalResult +from kilin.source_views import ( + SourcePolicy, SourceScope, SourceView, SourceViewConflict, + read_source_bytes, resolve_source_view, +) +from kilin.tools._contract import ToolSourceServices +from kilin.trace_logging import NullTraceLogger + +if TYPE_CHECKING: + from kilin.rag import RAGSession + +__all__ = [] + + +class ToolSourceHost: + """Capture and serve source views for one trusted tool operation. + + Parameters + ---------- + session: RAGSession + Prepared session owning the physical indexes and accepted project. + turn_id: str | None + Active turn identifier for retrieval and view diagnostics. + + """ + + def __init__(self, session: RAGSession, turn_id: str | None) -> None: + """Defer inspection until the first scoped service is requested. + + Parameters + ---------- + session: RAGSession + Prepared session owning accepted metadata and indexes. + turn_id: str | None + Active trace turn identifier. + + """ + self._session = session + self._turn_id = turn_id + self._state = None + self._services = {} + self._vectors: dict[str, list[float]] = {} + + def validate(self) -> None: + """Reject any change to a captured operation before using results. + + Raises + ------ + SourceViewConflict + If the accepted semantic or physical state no longer agrees. + + """ + if self._state is not None: + current = self._session._source_operation_state() + if current != self._state: + raise SourceViewConflict( + "Tool source operation changed; restart it." + ) + + def bind( + self, policy: SourcePolicy, scope: SourceScope, + ) -> ToolSourceServices: + """Resolve and bind a policy against the operation's frozen state. + + Parameters + ---------- + policy: SourcePolicy + Requested role, relation and purpose constraints. + scope: SourceScope + Explicit scope and canonical operands. + + Returns + ------- + ToolSourceServices + Immutable view and original physical services for its members. + + """ + if self._state is None: + self._state = self._session._source_operation_state() + else: + self.validate() + inspection, inventory = self._state + if not inspection.binding_matches: + 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) + key = (policy, scope.mode, tuple(p.as_posix() for p in scope.paths)) + if key not in self._services: + self._services[key] = self._bind_view(view) + getattr(self._session, "trace", NullTraceLogger()).emit( + "tool.source_view.resolved", component="tool", + data={ + "revision": view.operation.revision, + "manifest_sha256": view.operation.manifest_sha256, + "index_generation": inventory.index_generation, + "policy": asdict(policy), + "scope_mode": scope.mode, + "scope_operands": list(scope.paths), + "targets": list(view.targets), + "candidates": list(view.candidates), + "evidence": list(view.evidence), + "lookup": list(view.lookup), + "groups": [asdict(group) for group in view.groups], + }, turn_id=self._turn_id, + ) + return self._services[key] + + def _bind_view(self, view: SourceView) -> ToolSourceServices: + """Construct callbacks that cannot widen the captured membership. + + Parameters + ---------- + view: SourceView + Validated immutable view of the captured state. + + Returns + ------- + ToolSourceServices + Bound original passage, file, ranking and retrieval services. + + """ + session = self._session + raw = view.operation.policy.purpose == "raw" + allowed = frozenset() if raw else frozenset(rank_members(view)) + names = {path.as_posix() for path in allowed} + chunks = tuple(chunk for chunk in session.chunks + if chunk.path.as_posix() in names) + candidates = {path.as_posix() for path in view.candidates} + scope = view.operation.scope + + def rank(text: str) -> list: + """Rank authorized passages using this operation's query cache. + + Parameters + ---------- + text: str + Query to rank. + + """ + self.validate() + if raw: + raise ValueError("Raw-file views cannot rank passages.") + result = session._rank_everything( + text, self._turn_id, allowed=allowed, + _query_vectors=self._vectors, + ) + self.validate() + return result + + def retrieve(request: RetrievalRequest) -> RetrievalResult: + """Require the exact bound view and scope for bounded retrieval. + + Parameters + ---------- + request: RetrievalRequest + Bounded retrieval request for this view. + + """ + self.validate() + if not isinstance(request, RetrievalRequest): + raise TypeError("Expected a RetrievalRequest.") + if raw: + raise ValueError("Raw-file views cannot retrieve passages.") + if (request.scope_mode != scope.mode + or tuple(p.as_posix() for p in request.scope) + != tuple(p.as_posix() for p in scope.paths) + or (request.view is not None and request.view != view)): + raise ValueError("Request differs from the bound source view.") + result = session._retrieve_for_tool( + replace(request, view=view), self._turn_id, + _query_vectors=self._vectors, + ) + self.validate() + return result + + def card(path: Path) -> dict[str, str] | None: + """Expose cards only for eligible independent candidates. + + Parameters + ---------- + path: pathlib.Path + Exact independent candidate. + + """ + self.validate() + if path.as_posix() not in candidates: + raise SourceViewConflict("Card is outside the source view.") + return session._card_fields(path) + + def read_bytes(path: Path) -> bytes: + """Return verified bytes of an authorized physical member. + + Parameters + ---------- + path: pathlib.Path + Exact authorized physical member. + + """ + self.validate() + data = read_source_bytes( + session.project.root, session.project.source, view, path, + ) + self.validate() + return data + + return ToolSourceServices( + view, chunks, rank, retrieve, card, read_bytes, self.validate, + ) diff --git a/kilin/_trace_configuration.py b/kilin/_trace_configuration.py new file mode 100644 index 00000000..0b566665 --- /dev/null +++ b/kilin/_trace_configuration.py @@ -0,0 +1,164 @@ +"""Define compact representations of effective project configurations. + +Only project-opening configuration observations use this representation. +A reference preserves the original event identity and identifies the latest +complete configuration by sequence number and a digest of its canonical JSON. +References retain the exact observed project path inline while sharing all +other configuration content with the latest complete snapshot. + +Key Features +------------ +- Canonical JSON equality independent of mapping order. +- Direct references to complete snapshots, never to other references. +- One path-preserving reference format for identical settings. + +Module Structure +---------------- +- ``CONFIGURATION_EVENT`` and ``CONFIGURATION_CONTENT_REFERENCE`` identify + the configuration observation and its compact payload. +- ``configuration_content_bytes`` encodes path-independent content. +- ``configuration_content_reference`` constructs a compact reference without + changing the observed configuration. +- ``resolve_configuration_reference`` verifies and expands a reference. + +Examples +-------- +>>> from kilin._trace_configuration import configuration_content_reference +>>> reference = configuration_content_reference(12, b"{}", "workspace") +>>> reference["configuration_content_reference"]["sequence"] +12 + +""" + +from collections.abc import Mapping +from copy import deepcopy +from typing import Final + +from kilin._trace_snapshots import snapshot_bytes, snapshot_reference + +__all__ = [ + "CONFIGURATION_EVENT", + "CONFIGURATION_CONTENT_REFERENCE", + "configuration_content_bytes", + "configuration_content_reference", + "resolve_configuration_reference", +] + +CONFIGURATION_EVENT: Final[str] = "gui.project.configuration.effective" +CONFIGURATION_CONTENT_REFERENCE: Final[str] = "configuration_content_reference" +_CONFIGURATION_FIELDS: Final[frozenset[str]] = frozenset({ + "profile", "effort_levels", "router_models", "search_depth", + "source_cards", "behavior", "tools", +}) + + +def configuration_content_bytes(configuration: Mapping[str, object]) -> bytes: + """Encode every configuration value except the observed project path. + + Parameters + ---------- + configuration: mapping of str to object + Complete JSON-ready effective configuration. The ``behavior`` mapping + must contain ``project``; absence never means a null or empty path. + + Returns + ------- + bytes + Canonical JSON preserving all other settings and unknown fields. + + Raises + ------ + ValueError + If the configuration is incomplete, compact, or has no project path. + TypeError + If a retained value cannot be serialized as JSON. + + """ + + behavior = configuration.get("behavior") + if (CONFIGURATION_CONTENT_REFERENCE in configuration + or not _CONFIGURATION_FIELDS <= configuration.keys() + or not isinstance(behavior, dict) or "project" not in behavior): + raise ValueError("Expected a configuration with a project path.") + content = dict(configuration) + content["behavior"] = {key: value for key, value in behavior.items() + if key != "project"} + return snapshot_bytes(content) + + +def configuration_content_reference( + sequence: int, encoded: bytes, project: object, +) -> dict: + """Reference shared settings while retaining the exact observed path. + + Parameters + ---------- + sequence: int + Project-wide sequence number of the complete snapshot. + encoded: bytes + Canonical configuration content with only ``behavior.project`` absent. + project: object + Original JSON value of ``behavior.project`` in the current event. + Explicit null remains present and is never confused with absence. + + Returns + ------- + dict + Direct content reference and an independent copy of the current path. + + """ + + return { + **snapshot_reference(CONFIGURATION_CONTENT_REFERENCE, sequence, + encoded), + "project": deepcopy(project), + } + + +def resolve_configuration_reference( + details: dict, sequence: int, latest: tuple[int, dict] | None, +) -> dict: + """Resolve only a direct, backward reference to the latest full snapshot. + + Parameters + ---------- + details: dict + Compact payload of the current configuration observation. + sequence: int + Sequence number of that observation. + latest: tuple of int and dict or None + Sequence and details of the most recent preceding full observation in + this project trace. References do not replace this candidate. + + Returns + ------- + dict + Independent copy of the complete configuration. + + Raises + ------ + ValueError + If the payload is malformed, the target is missing or not the latest + complete observation, or the digest does not match the target. + + """ + + key = CONFIGURATION_CONTENT_REFERENCE + reference = details.get(key) + if (set(details) != {key, "project"} + or not isinstance(reference, dict) + or set(reference) != {"sequence", "sha256"} + or type(reference["sequence"]) is not int + or not 0 < reference["sequence"] < sequence + or not isinstance(reference["sha256"], str)): + raise ValueError("Invalid project configuration reference.") + if latest is None or latest[0] != reference["sequence"]: + raise ValueError( + "Configuration reference does not identify the latest snapshot." + ) + encoded = configuration_content_bytes(latest[1]) + if reference != snapshot_reference(key, latest[0], encoded)[key]: + raise ValueError("Project configuration reference digest mismatch.") + resolved = deepcopy(latest[1]) + resolved["behavior"]["project"] = deepcopy(details["project"]) + return resolved diff --git a/kilin/_trace_json.py b/kilin/_trace_json.py new file mode 100644 index 00000000..f85930d5 --- /dev/null +++ b/kilin/_trace_json.py @@ -0,0 +1,95 @@ +"""Format diagnostic JSON without expanding every token onto its own line. + +The standard JSON encoder remains responsible for every value, escape and +validation rule. A formatting pass groups long integer arrays into rows of +sixteen values while retaining the ordinary two-space layout elsewhere. +Only whitespace changes; readers and canonical event digests are unchanged. + +Key Features +------------ +- Preserve standard JSON serialization, including scalar types and ordering. +- Share one readable format between project and conversation trace writers. + +Module Structure +---------------- +- ``trace_json_dumps`` serializes and formats a complete diagnostic payload. + +Examples +-------- +>>> import json +>>> from kilin._trace_json import trace_json_dumps +>>> payload = {"token_ids": list(range(32))} +>>> json.loads(trace_json_dumps(payload)) == payload +True + +""" + +import json +import re +from typing import Final + +__all__ = ["trace_json_dumps"] + +_INTEGERS_PER_LINE: Final[int] = 16 +_INTEGER_ARRAY: Final[re.Pattern[str]] = re.compile( + r"\[\n(?P +)" + r"(?P-?[0-9]+(?:,\n +-?[0-9]+){15,})\n *\]" +) + + +def _compact_integer_array(match: re.Match[str]) -> str: + """Replace only the inter-value whitespace of one encoded integer array. + + Parameters + ---------- + match: re.Match[str] + An array produced by the two-space standard JSON encoder. + + Returns + ------- + str + The same bracketed integer lexemes and commas, in rows of sixteen. + + """ + + indentation = match["indent"] + values = match["integers"].split() + rows = [ + " ".join(values[start:start + _INTEGERS_PER_LINE]) + for start in range(0, len(values), _INTEGERS_PER_LINE) + ] + return ("[\n" + indentation + + ("\n" + indentation).join(rows) + + "\n" + indentation[:-2] + "]") + + +def trace_json_dumps(payload: object) -> str: + """Serialize a trace with compact rows for arrays of at least 16 integers. + + Parameters + ---------- + payload: object + JSON-ready diagnostic payload accepted by ``json.dumps``. + + Returns + ------- + str + Two-space JSON with unescaped Unicode and no trailing newline. + Integer arrays use sixteen values per line. All other formatting + and the standard encoder's validation behavior are preserved. + + Raises + ------ + TypeError + If the standard encoder cannot serialize a payload value or key. + ValueError + If the standard encoder detects a circular reference or an integer + exceeds Python's configured conversion limit. + + """ + + encoded = json.dumps(payload, indent=2, ensure_ascii=False) + # Literal ASCII newlines cannot occur inside JSON strings: the standard + # encoder escapes them. Requiring those newlines keeps this whitespace + # pass outside strings without interpreting user text or JSON escapes. + return _INTEGER_ARRAY.sub(_compact_integer_array, encoded) diff --git a/kilin/_trace_project.py b/kilin/_trace_project.py new file mode 100644 index 00000000..d0754b56 --- /dev/null +++ b/kilin/_trace_project.py @@ -0,0 +1,748 @@ +"""Coordinate project-wide numbering and shared project-trace persistence. + +Conversation traces retain their exclusive, long-lived write leases. The +project trace and its small sequence counter instead use short-lived leases: +no process owns the entire workspace for the duration of a conversation. +The counter contains only allocation and recording-health metadata, not a +second copy of any diagnostic event. + +Key Features +------------ +- **Project-wide sequence allocation** + + Allocate positive, monotonically increasing numbers across logger runs + and processes, including archived conversations. +- **Shared project trace** + + Publish one logger run's hierarchical sessions without overwriting the + sessions of another writer. + +Module Structure +---------------- +- ``TRACE_FORMAT_VERSION`` and ``OPERATION_RECORDING_VERSION`` + + Structural trace version and full command-recording contract version. +- ``ProjectTraceSequence`` + + Allocate and persist project-wide event numbers. +- ``project_trace_directory`` + + Resolve the managed trace directory for a workspace trace. +- ``write_project_trace`` + + Update the shared project trace under short-lived ownership. +- ``project_trace_publication`` + + Coordinate a snapshot observation with a single publication lease. +- ``compact_project_configuration`` and ``compact_project_source_snapshot`` + + Compare new observations with the latest persisted full snapshots. +- ``compact_project_semantic_snapshot`` + + Share exact semantic manifests across supported operation types. + +Examples +-------- +>>> from pathlib import Path +>>> from tempfile import TemporaryDirectory +>>> from kilin._trace_project import ProjectTraceSequence +>>> with TemporaryDirectory() as directory: +... counter = ProjectTraceSequence(Path(directory) / "logs" / "traces") +... assert counter.next() == 1 +... assert counter.next() == 2 + +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator, Mapping +from contextlib import contextmanager +import json +from pathlib import Path +from time import monotonic, sleep +from typing import Final, TypeAlias + +from kilin.atomic_writes import atomic_write_text +from kilin._trace_json import trace_json_dumps +from kilin._trace_configuration import ( + CONFIGURATION_CONTENT_REFERENCE, + CONFIGURATION_EVENT, + configuration_content_bytes, + configuration_content_reference, +) +from kilin._trace_snapshots import ( + SEMANTIC_SNAPSHOT_EVENTS, SEMANTIC_SNAPSHOT_REFERENCE, + SEMANTIC_SNAPSHOT_WRITERS, + SOURCE_SNAPSHOT_REFERENCE, snapshot_bytes, snapshot_reference, + semantic_snapshot, source_snapshot, +) +from kilin.conversation_ownership import ( + ConversationFileLock, + ConversationLockedError, +) + +__all__ = [ + "TRACE_FORMAT_VERSION", + "OPERATION_RECORDING_VERSION", + "ProjectTraceSequence", + "project_trace_directory", + "ProjectTracePublisher", + "compact_project_configuration", + "compact_project_source_snapshot", + "compact_project_semantic_snapshot", + "project_trace_publication", + "write_project_trace", +] + +TRACE_FORMAT_VERSION: Final[int] = 1 +# Mark fresh projects recorded with complete engine command provenance. +# Do not stamp existing projects as complete when they are reopened. +OPERATION_RECORDING_VERSION: Final[int] = 1 +_SEQUENCE_NAME: Final[str] = ".sequence.json" +_LOCK_TIMEOUT: Final[float] = 5.0 +_LOCK_POLL: Final[float] = 0.01 + +ProjectTracePublisher: TypeAlias = Callable[ + [str, Mapping[str, object], Mapping[str, object]], None +] + + +def project_trace_directory( + output_path: Path, project_directory: str | Path | None = None +) -> Path | None: + """Find the common trace directory for a workspace-owned trace. + + Parameters + ---------- + output_path: pathlib.Path + Path of the trace to be written. + project_directory: str | pathlib.Path | None, optional + Explicit workspace root, including a reserved project that does + not yet have its profile. Otherwise infer an existing workspace + from its logs directory and profile. + + Returns + ------- + pathlib.Path | None + Common ``logs/traces`` directory, or None for a standalone logger. + + Raises + ------ + ValueError + If an explicit workspace does not own the trace, or a managed + directory or trace is a symbolic link. + + """ + + path = output_path.expanduser().absolute() + if project_directory is None: + root = next( + ( + parent.parent + for parent in path.parents + if parent.name == "logs" + and (parent.parent / "profile.ini").is_file() + ), + None, + ) + if root is None: + return None + else: + root = Path(project_directory).expanduser().resolve() + logs = root / "logs" + directory = logs / "traces" + if logs.is_symlink() or directory.is_symlink() or path.is_symlink(): + raise ValueError("Project trace paths must not be symbolic links.") + if not path.resolve().is_relative_to(logs.resolve()): + raise ValueError("A project trace must stay inside project logs.") + return directory.resolve() + + +@contextmanager +def _short_ownership(path: Path) -> Iterator[None]: + """Acquire a short write lease without changing conversation ownership. + + Parameters + ---------- + path: pathlib.Path + Shared project metadata or project trace file. + + Yields + ------ + None + The caller may read and atomically replace the protected file. + + Raises + ------ + OSError + If ownership cannot be obtained within the bounded wait or the + target is a symbolic link. + + Notes + ----- + Ordinary publication and sequence allocation take separate leases. + Compactable observations may reserve a sequence while holding the + project publication lease; no path holds the sequence lease while + acquiring the project lease. The lock companion is never removed. + + """ + + if path.is_symlink() or path.parent.is_symlink(): + raise OSError(f"Shared trace path cannot be a link: {path}") + owner = ConversationFileLock(path) + deadline = monotonic() + _LOCK_TIMEOUT + while True: + try: + owner.acquire() + except ConversationLockedError as error: + if monotonic() >= deadline: + raise OSError( + f"Timed out locking trace file: {path}" + ) from error + sleep(_LOCK_POLL) + else: + break + try: + if path.is_symlink(): + raise OSError(f"Shared trace path cannot be a link: {path}") + yield + finally: + owner.release() + + +def _read_object(path: Path) -> dict[str, object]: + """Read a JSON object without silently replacing malformed data. + + Parameters + ---------- + path: pathlib.Path + Existing regular JSON file. + + Returns + ------- + dict[str, object] + Decoded object. + + Raises + ------ + OSError + If the file is not readable or its JSON is not an object. + + """ + + if path.is_symlink() or not path.is_file(): + raise OSError(f"Invalid project trace file: {path}") + try: + value = json.loads(path.read_text(encoding="utf-8")) + except (ValueError, UnicodeError) as error: + raise OSError(f"Invalid project trace JSON: {path}") from error + if not isinstance(value, dict): + raise OSError(f"Invalid project trace JSON: {path}") + return value + + +def _raise_scan_error(error: OSError) -> None: + """Abort history discovery when a directory cannot be inspected. + + Parameters + ---------- + error: OSError + Directory traversal failure reported by ``Path.walk``. + + Raises + ------ + OSError + The original failure; inaccessible history is not absent history. + + """ + + raise error + + +class ProjectTraceSequence: + """Allocate a shared event number for a workspace trace. + + Parameters + ---------- + directory: pathlib.Path + Managed ``logs/traces`` directory of a single workspace. + + Methods + ------- + next() + Persist and return the next event number. + mark_incomplete() + Persist a recording-health flag after an optional trace failure. + + Notes + ----- + The high-water mark is allocated before the event is published. Gaps + may therefore identify failed or unflushed writes; allocated numbers + are never reused. Counter corruption is not repaired automatically. + The counter is small and does not contain event payloads. + + """ + + def __init__(self, directory: Path) -> None: + """Remember the shared metadata path without writing it. + + Parameters + ---------- + directory: pathlib.Path + Managed trace directory of a single workspace. + + """ + + self.path = directory / _SEQUENCE_NAME + + def _read(self) -> dict[str, object]: + """Read the counter under ownership, or initialize a new one. + + Returns + ------- + dict[str, object] + Validated counter and recording-health metadata. + + Raises + ------ + OSError + If the counter is malformed or missing for a versioned project. + + Notes + ----- + Missing-counter discovery recognizes project-numbered records under + any supported JSON filename. Canonical trace names remain strict; + malformed unrelated JSON is ignored. Unreadable or linked candidates + and history directories cannot establish that history is absent, so + they block initialization. Existing counters require no history scan. + + """ + + if not self.path.exists(): + # Never recycle numbers if the counter disappeared. Older, + # unversioned diagnostic traces do not certify a sequence. + logs = self.path.parent.parent + if logs.is_symlink(): + raise OSError(f"Linked trace directory: {logs}") + for folder, directories, files in logs.walk( + on_error=_raise_scan_error, follow_symlinks=False + ): + for name in directories + files: + candidate = folder / name + linked = candidate.is_symlink() + if linked and candidate.is_dir(): + raise OSError(f"Linked trace directory: {candidate}") + if candidate.suffix.lower() != ".json": + continue + if linked: + raise OSError(f"Linked trace file: {candidate}") + if candidate.name == "project.json" or ( + candidate.name.startswith("conversation_") + ): + payload = _read_object(candidate) + else: + if not candidate.is_file(): + continue + try: + payload = json.loads( + candidate.read_text(encoding="utf-8") + ) + except (ValueError, UnicodeError): + # Unrelated logs need not be trace objects. + continue + if not isinstance(payload, dict): + continue + if payload.get("sequence_scope") == "project": + raise OSError( + "Project trace sequence counter is missing." + ) + return { + "format_version": TRACE_FORMAT_VERSION, + "last_sequence": 0, + "incomplete": False, + } + state = _read_object(self.path) + if ( + set(state) != {"format_version", "last_sequence", "incomplete"} + or type(state["format_version"]) is not int + or state["format_version"] != TRACE_FORMAT_VERSION + or type(state["last_sequence"]) is not int + or state["last_sequence"] < 0 + or type(state["incomplete"]) is not bool + ): + raise OSError("Invalid project trace sequence counter.") + return state + + def next(self) -> int: + """Reserve the next project-wide event number durably. + + Returns + ------- + int + Newly reserved positive sequence number. + + """ + + with _short_ownership(self.path): + state = self._read() + number = int(state["last_sequence"]) + 1 + state["last_sequence"] = number + atomic_write_text(self.path, json.dumps(state) + "\n") + return number + + def mark_incomplete(self) -> None: + """Record that at least one optional diagnostic write failed.""" + + with _short_ownership(self.path): + state = self._read() + state["incomplete"] = True + atomic_write_text(self.path, json.dumps(state) + "\n") + + +def compact_project_configuration( + previous: Mapping[str, object], configuration: dict, sequence: int, +) -> dict: + """Compare a configuration with the latest published complete snapshot. + + Parameters + ---------- + previous: mapping of str to object + Shared project trace read under the current publication lease. + configuration: dict + Complete JSON-ready effective configuration for the new event. + sequence: int + Newly reserved sequence number of the current observation. + + Returns + ------- + dict + Original full configuration or a direct reference to the latest + configuration with identical path-independent content. Keep the + exact current path inline whether or not it has changed. Ineligible + or ambiguous history is not used for compaction. + + Notes + ----- + Inspect only project-level operation nodes, not arbitrary event payloads. + Session names are not chronological across logger runs, so compare + sequence numbers. No disk reads or writes are performed here. + + """ + + latest = None + seen = set() + sessions = previous.get("sessions", {}) + if not isinstance(sessions, dict): + return configuration + for session in sessions.values(): + if (not isinstance(session, dict) + or session.get("category") != "project"): + continue + operations = session.get("operations", {}) + if not isinstance(operations, dict): + return configuration + for node in operations.values(): + if not isinstance(node, dict): + continue + event = node.get("event") + if (not isinstance(event, dict) + or event.get("event_type") != CONFIGURATION_EVENT): + continue + number = event.get("sequence") + details = node.get("details") + if (type(number) is not int or not 0 < number < sequence + or number in seen or not isinstance(details, dict) + or event.get("status") != "completed" + or "turn_id" in event): + return configuration + seen.add(number) + if CONFIGURATION_CONTENT_REFERENCE in details: + continue + if latest is None or number > latest[0]: + latest = (number, details) + if latest is not None: + try: + content = configuration_content_bytes(configuration) + if content == configuration_content_bytes(latest[1]): + compact = configuration_content_reference( + latest[0], content, configuration["behavior"]["project"] + ) + if len(snapshot_bytes(compact)) < len( + snapshot_bytes(configuration) + ): + return compact + except (ValueError, TypeError, RecursionError): + # Keep full evidence rather than guessing when a configuration + # cannot be compared. Inspection still validates the history. + pass + return configuration + + +def _latest_project_snapshot( + previous: Mapping[str, object], event_types: frozenset[str], + sequence: int, reference_fields: tuple[str, ...], +) -> tuple[int, dict, dict] | None: + """Find the latest full snapshot without traversing arbitrary payloads. + + Parameters + ---------- + previous: mapping of str to object + Project trace read under the current publication lease. + event_types: frozenset of str + Event types sharing this snapshot's namespace. + sequence: int + New allocation under the project publication lease. + reference_fields: tuple of str + Reserved reference markers. Compact nodes never become targets. + + Returns + ------- + tuple of int, dict and dict or None + Latest number, metadata and full details, or no usable candidate. + + Notes + ----- + Retain the latest full node even when its payload or status is invalid: + the caller must then store new full evidence rather than skipping it. + + """ + + latest = None + seen = set() + sessions = previous.get("sessions", {}) + if not isinstance(sessions, dict): + return None + for session in sessions.values(): + if not isinstance(session, dict): + return None + operations = session.get("operations", {}) + if not isinstance(operations, dict): + return None + for node in operations.values(): + if not isinstance(node, dict): + continue + event = node.get("event") + if (not isinstance(event, dict) + or event.get("event_type") not in event_types): + continue + number = event.get("sequence") + payload = node.get("details", {}) + if (type(number) is not int or not 0 < number < sequence + or number in seen or not isinstance(payload, dict) + or "turn_id" in event): + return None + seen.add(number) + if any(key in payload for key in reference_fields): + continue + if latest is None or number > latest[0]: + latest = (number, event, payload) + return latest + + +def compact_project_source_snapshot( + previous: Mapping[str, object], event_type: str, details: dict, + sequence: int, +) -> dict: + """Replace unchanged source snapshot fields with a direct reference. + + Parameters + ---------- + previous: mapping of str to object + Project trace read under the current publication lease. + event_type: str + Source observation type. References never cross event types. + details: dict + New complete JSON-ready observation. + sequence: int + Newly allocated sequence under the publication lease. + + Returns + ------- + dict + Full observation or smaller compact observation with all independent + fields intact. Invalid full observations reset the candidate. + + """ + + latest = _latest_project_snapshot( + previous, frozenset({event_type}), sequence, + (SOURCE_SNAPSHOT_REFERENCE,), + ) + if latest is None or latest[1].get("status") != "completed": + return details + try: + snapshot = source_snapshot(event_type, details) + encoded = snapshot_bytes(snapshot) + if encoded != snapshot_bytes(source_snapshot(event_type, latest[2])): + return details + reference = snapshot_reference( + SOURCE_SNAPSHOT_REFERENCE, latest[0], encoded, + ) + if len(snapshot_bytes(reference)) >= len(encoded): + return details + except (ValueError, TypeError, RecursionError): + return details + return {**{key: value for key, value in details.items() + if key not in snapshot}, **reference} + + +def compact_project_semantic_snapshot( + previous: Mapping[str, object], event_type: str, details: dict, + sequence: int, +) -> dict: + """Share a semantic manifest without eliding an operation or its result. + + Parameters + ---------- + previous: mapping of str to object + Project trace read under the current publication lease. + event_type: str + Supported semantic commit, reconciliation or application event. + details: dict + Full JSON-ready event details, including its operation context. + sequence: int + Newly allocated sequence number under the same publication lease. + + Returns + ------- + dict + Original details or a smaller representation referencing the latest + raw full semantic manifest. No historical event is rewritten. + + """ + + if event_type not in SEMANTIC_SNAPSHOT_WRITERS: + return details + latest = _latest_project_snapshot( + previous, SEMANTIC_SNAPSHOT_EVENTS, sequence, + (SOURCE_SNAPSHOT_REFERENCE, SEMANTIC_SNAPSHOT_REFERENCE), + ) + if latest is None or latest[1].get("status") != "completed": + return details + try: + snapshot = semantic_snapshot(event_type, details) + encoded = snapshot_bytes(snapshot) + target = semantic_snapshot(latest[1]["event_type"], latest[2]) + if encoded != snapshot_bytes(target): + return details + reference = snapshot_reference( + SEMANTIC_SNAPSHOT_REFERENCE, latest[0], encoded, + ) + if len(snapshot_bytes(reference)) >= len(encoded): + return details + except (ValueError, TypeError, RecursionError): + return details + return {**{key: value for key, value in details.items() + if key not in snapshot}, **reference} + + +@contextmanager +def project_trace_publication( + path: Path, +) -> Iterator[tuple[dict, ProjectTracePublisher]]: + """Read and publish a shared project trace under one ownership lease. + + Parameters + ---------- + path: pathlib.Path + Shared ``project.json`` trace path. + + Yields + ------ + tuple of dict and ProjectTracePublisher + Persisted trace (empty on first publication) and a publisher for one + logger run. The publisher is used only within this context. + + Notes + ----- + Compactable observations reserve their sequence and choose their payload + inside this context. This prevents another snapshot writer from + publishing an intervening full snapshot. Other operations continue to + allocate numbers before separately acquiring the publication lease. + + """ + + with _short_ownership(path): + previous = {} + if path.exists(): + previous = _read_object(path) + if ( + type(previous.get("trace_format_version")) is not int + or previous["trace_format_version"] != TRACE_FORMAT_VERSION + or previous.get("trace_scope") != "project" + or previous.get("sequence_scope") != "project" + or not isinstance(previous.get("sessions"), dict) + ): + raise OSError("Invalid shared project trace format.") + + def publish( + trace_id: str, + sessions: Mapping[str, object], + metadata: Mapping[str, object], + ) -> None: + """Merge this run and atomically replace the owned project trace. + + Parameters + ---------- + trace_id: str + Unique identifier of the publishing logger run. + sessions: mapping of str to object + Current hierarchical sessions of that run. + metadata: mapping of str to object + Trace header and current run's event counts. + + """ + + if (type(metadata.get("trace_format_version")) is not int + or metadata["trace_format_version"] + != TRACE_FORMAT_VERSION): + raise ValueError("Unsupported project trace format version.") + saved = dict(previous.get("sessions", {})) + # Preserve other runs, including their full snapshots. + for key, value in sessions.items(): + saved[f"{key}_{trace_id}"] = value + payload = { + **metadata, + "trace_incomplete": bool( + metadata.get("trace_incomplete") + or previous.get("trace_incomplete") + ), + "sessions": dict(sorted(saved.items())), + } + atomic_write_text( + path, trace_json_dumps(payload) + "\n" + ) + + yield previous, publish + + +def write_project_trace( + path: Path, + trace_id: str, + sessions: Mapping[str, object], + metadata: Mapping[str, object], +) -> None: + """Publish one run's hierarchical project-trace projection. + + Parameters + ---------- + path: pathlib.Path + Shared ``project.json`` trace path. + trace_id: str + Unique identifier of this logger run. + sessions: mapping of str to object + Hierarchical sessions projected from this run's events. + metadata: mapping of str to object + Trace header including the current run's event counts. + + Notes + ----- + Stable run-specific session keys allow each writer to replace its own + projection while preserving other writers' sessions. Read, validation, + merge and atomic publication use one short lease. The project trace + never contains a resumable conversation checkpoint. + + """ + + with project_trace_publication(path) as (_, publish): + publish(trace_id, sessions, metadata) diff --git a/kilin/_trace_snapshots.py b/kilin/_trace_snapshots.py new file mode 100644 index 00000000..597ea2c3 --- /dev/null +++ b/kilin/_trace_snapshots.py @@ -0,0 +1,306 @@ +"""Encode repeated source observations without discarding event context. + +Key Features +------------ +- Exact canonical JSON equality shared with configuration observations. +- Direct, digest-checked references to complete source snapshot fields. +- Event-specific snapshot boundaries that retain paths, decisions, errors, + and other operation-specific details in their original observations. + +Module Structure +---------------- +- ``snapshot_bytes`` and ``snapshot_reference`` encode snapshots and their + direct references. +- ``source_snapshot`` extracts the supported source observation fields. +- ``resolve_source_reference`` verifies and expands a compact observation. +- ``semantic_snapshot`` and ``resolve_semantic_reference`` share the exact + semantic manifest between supported project event types. + +Examples +-------- +>>> from kilin._trace_snapshots import snapshot_bytes +>>> snapshot_bytes({"b": 2, "a": 1}) +b'{"a":1,"b":2}' + +""" + +from collections.abc import Mapping +from copy import deepcopy +from hashlib import sha256 +import json +from typing import Final + +__all__ = [ + "SOURCE_SNAPSHOT_REFERENCE", + "SOURCE_SNAPSHOT_FIELDS", + "snapshot_bytes", + "snapshot_reference", + "source_snapshot", + "resolve_source_reference", + "SEMANTIC_SNAPSHOT_REFERENCE", + "SEMANTIC_SNAPSHOT_EVENTS", + "SEMANTIC_SNAPSHOT_WRITERS", + "semantic_snapshot", + "resolve_semantic_reference", +] + +SOURCE_SNAPSHOT_REFERENCE: Final[str] = "source_snapshot_reference" +SOURCE_SNAPSHOT_FIELDS: Final[Mapping[str, tuple[str, ...]]] = { + "source.scan.completed": ("selected_files", "entries"), + "index.check.completed": ( + "source_manifest", "expected_metadata", "saved_metadata", + ), + "gui.source_organization.observed": ( + "source_organization", "selected", "pending", "pending_roles", + "retained_versions", + ), +} +SEMANTIC_SNAPSHOT_REFERENCE: Final[str] = "semantic_snapshot_reference" +SEMANTIC_SNAPSHOT_WRITERS: Final[frozenset[str]] = frozenset({ + "source_organization.committed", + "source_organization.reconciled", + "gui.source_organization.apply.completed", +}) +# Opening observations retain their existing whole-group compaction. They +# may supply a full manifest, but never acquire an indirect group reference. +SEMANTIC_SNAPSHOT_EVENTS: Final[frozenset[str]] = ( + SEMANTIC_SNAPSHOT_WRITERS | {"gui.source_organization.observed"} +) + + +def snapshot_bytes(snapshot: Mapping[str, object]) -> bytes: + """Encode JSON-ready snapshot fields for exact comparison. + + Parameters + ---------- + snapshot: mapping of str to object + Complete snapshot data, with JSON-compatible values. + + Returns + ------- + bytes + Canonical UTF-8 JSON. Mapping order is ignored; scalar types and + array order remain significant. Nonfinite numbers are rejected. + + """ + + return json.dumps( + dict(snapshot), sort_keys=True, separators=(",", ":"), + ensure_ascii=False, allow_nan=False, + ).encode("utf-8") + + +def snapshot_reference(key: str, sequence: int, encoded: bytes) -> dict: + """Construct a reference to an already published full snapshot. + + Parameters + ---------- + key: str + Reserved reference field in the observation payload. + sequence: int + Project-wide allocation number of the full snapshot. + encoded: bytes + Canonical snapshot bytes. + + Returns + ------- + dict + Reference containing the target sequence and SHA-256 digest. + + """ + + return {key: {"sequence": sequence, "sha256": sha256(encoded).hexdigest()}} + + +def source_snapshot(event_type: str, details: Mapping[str, object]) -> dict: + """Extract only complete, supported source snapshot fields. + + Parameters + ---------- + event_type: str + Physical scan, index check, or semantic observation event type. + details: mapping of str to object + Full observation payload. Operation-specific fields are not extracted. + + Returns + ------- + dict + Exact fields eligible for compaction. + + Raises + ------ + ValueError + If the event is unsupported, incomplete, or already compact. + + """ + + fields = SOURCE_SNAPSHOT_FIELDS.get(event_type) + if (fields is None or SOURCE_SNAPSHOT_REFERENCE in details + or any(field not in details for field in fields) + or (event_type == "source.scan.completed" + and details.get("complete") is not True) + or (event_type == "gui.source_organization.observed" + and details.get("error") is not None)): + raise ValueError("Expected a complete source snapshot.") + snapshot = {field: details[field] for field in fields} + if event_type == "index.check.completed": + valid = (isinstance(snapshot["source_manifest"], dict) + and isinstance(snapshot["expected_metadata"], dict) + and (snapshot["saved_metadata"] is None + or isinstance(snapshot["saved_metadata"], dict))) + elif event_type == "source.scan.completed": + valid = all(isinstance(value, list) for value in snapshot.values()) + else: + valid = (isinstance(snapshot["source_organization"], dict) + and all(isinstance(snapshot[field], list) + for field in fields[1:]) + and details.get("trace_error") is None) + if not valid: + raise ValueError("Invalid source snapshot fields.") + return snapshot + + +def resolve_source_reference( + event_type: str, details: dict, sequence: int, + latest: tuple[int, dict] | None, +) -> dict: + """Verify and expand a direct reference to the latest full observation. + + Parameters + ---------- + event_type: str + Type of the current observation and its required target. + details: dict + Compact observation, including its independent inline fields. + sequence: int + Sequence number of the current observation. + latest: tuple of int and dict or None + Latest preceding complete observation of this type, not a reference. + + Returns + ------- + dict + Independent copy of the complete observation. + + Raises + ------ + ValueError + If the reference or snapshot is invalid, the target is unavailable, + inline fields overlap the snapshot, or the digest differs. + + """ + + key = SOURCE_SNAPSHOT_REFERENCE + reference = details.get(key) + fields = SOURCE_SNAPSHOT_FIELDS.get(event_type) + if (fields is None or any(field in details for field in fields) + or not isinstance(reference, dict) + or set(reference) != {"sequence", "sha256"} + or type(reference["sequence"]) is not int + or not 0 < reference["sequence"] < sequence + or not isinstance(reference["sha256"], str)): + raise ValueError("Invalid source snapshot reference.") + if latest is None or latest[0] != reference["sequence"]: + raise ValueError("Source reference does not identify latest snapshot.") + snapshot = source_snapshot(event_type, latest[1]) + if {key: reference} != snapshot_reference( + key, latest[0], snapshot_bytes(snapshot)): + raise ValueError("Source snapshot reference digest mismatch.") + expanded = {field: value for field, value in details.items() + if field != key} + expanded.update(deepcopy(snapshot)) + # A compact observation must itself satisfy the snapshot preconditions. + source_snapshot(event_type, expanded) + return expanded + + +def semantic_snapshot( + event_type: str, details: Mapping[str, object], +) -> dict: + """Extract a complete semantic manifest from a supported full event. + + Parameters + ---------- + event_type: str + Semantic commit, reconciliation, application or opening observation. + details: mapping of str to object + Original payload. Revisions, command inputs, inspection results and + operation outcomes remain separate from the shared manifest. + + Returns + ------- + dict + The exact ``source_organization`` field, without normalization. + + Raises + ------ + ValueError + If the event is unsupported, incomplete, failed or already compact. + + """ + + if (event_type not in SEMANTIC_SNAPSHOT_EVENTS + or SEMANTIC_SNAPSHOT_REFERENCE in details + or SOURCE_SNAPSHOT_REFERENCE in details + or not isinstance(details.get("source_organization"), dict) + or details.get("error") is not None + or details.get("trace_error") is not None): + raise ValueError("Expected a complete semantic snapshot.") + if event_type == "gui.source_organization.observed": + source_snapshot(event_type, details) + return {"source_organization": details["source_organization"]} + + +def resolve_semantic_reference( + event_type: str, details: dict, sequence: int, + latest: tuple[int, str, dict] | None, +) -> dict: + """Expand a direct semantic reference across supported event types. + + Parameters + ---------- + event_type: str + Semantic event whose manifest was omitted. + details: dict + Compact payload with all independent operation details still inline. + sequence: int + Sequence number of the current event. + latest: tuple of int, str and dict or None + Number, type and full details of the most recent eligible semantic + observation. A compact event never becomes a reference target. + + Returns + ------- + dict + Independent reconstruction of the original full event details. + + Raises + ------ + ValueError + If the reference is malformed, mixed, chained, forward, superseded, + or inconsistent with the full target's canonical digest. + + """ + + key = SEMANTIC_SNAPSHOT_REFERENCE + reference = details.get(key) + if (event_type not in SEMANTIC_SNAPSHOT_WRITERS + or "source_organization" in details + or SOURCE_SNAPSHOT_REFERENCE in details + or not isinstance(reference, dict) + or set(reference) != {"sequence", "sha256"} + or type(reference["sequence"]) is not int + or not 0 < reference["sequence"] < sequence + or not isinstance(reference["sha256"], str)): + raise ValueError("Invalid semantic snapshot reference.") + if latest is None or latest[0] != reference["sequence"]: + raise ValueError("Semantic reference does not identify latest state.") + snapshot = semantic_snapshot(latest[1], latest[2]) + if {key: reference} != snapshot_reference( + key, latest[0], snapshot_bytes(snapshot)): + raise ValueError("Semantic snapshot reference digest mismatch.") + expanded = {field: value for field, value in details.items() + if field != key} + expanded.update(deepcopy(snapshot)) + semantic_snapshot(event_type, expanded) + return expanded diff --git a/kilin/answering.py b/kilin/answering.py index b567fd72..7f217f8e 100644 --- a/kilin/answering.py +++ b/kilin/answering.py @@ -34,7 +34,9 @@ - **Router decision** ``route_question`` asks the router model for one line of JSON and - validates it; anything unusable falls back to the default intent. + validates it. Intents requiring an earlier turn are unavailable when + no eligible turn exists. Unusable replies fall back to an allowed + intent. - **Related-turn checks** @@ -181,7 +183,14 @@ HistoryPolicy, ProjectType, ) -from kilin.tools._registry import TOOL_REGISTRY +from kilin.source_eligibility import without_source_filenames +from kilin.tools._registry import ( + TOOL_GENERATE_PAPER_SUMMARY, TOOL_PROJECT_SUMMARY, registered_tools, +) +from kilin.tools._shared.report_selection import ( + qualified_references, + report_intent_override, +) __all__ = [ "HISTORY_CITATION_MARKER", @@ -974,7 +983,14 @@ def route_question( ------- RouteDecision Validated decision. Errors and unusable replies fall back to the - project type's default intent with no related turns. + project type's default intent with no related turns when allowed, + otherwise to an eligible ordinary alternative. + + Raises + ------ + ValueError + No intent is available for the current history, or routing needs a + fallback but no suitable ordinary alternative exists. Notes ----- @@ -990,12 +1006,15 @@ def route_question( question points back (``refers_back``) or shares a distinctive term with the turn's question, sources, or summary. Turns whose intent neither reads history nor retrieves (small talk) are not listed to the - router and are never related. A question left with no related turns - is standalone. An intent whose cue the question matches replaces the - router's choice ("give me an overview of the Smith paper"). Otherwise, - when the wording rules out the router's choice, the router is asked - once more without the ruled-out intents, and the default intent is - used when that fails: an intent with ``requires`` patterns needs one + router and are never related. With no non-skipped earlier turn, + intents with ``reuse`` retrieval or an unconditional ``follows_up`` + tool are unavailable to every routing path. Conditional follow-up + tools can still act on a new question. A matching cue for an eligible + intent replaces the router's choice ("give me an overview of the Smith + paper"). Otherwise, when the router chooses an unavailable intent or + the wording rules out its choice, the router is asked once more + without the excluded intents, with an allowed ordinary fallback when + that fails. An intent with ``requires`` patterns needs one of them to match, and a tool that works on an earlier answer (``follows_up``) is not meant when the question names a file and says nothing of earlier answers ("In Figure 1G of smith20.pdf, what does @@ -1003,17 +1022,6 @@ def route_question( """ - # Obvious messages such as greetings skip the router model. - message = re.sub(r"[\s!?.,]+$", "", question.strip()) - for intent_id, intent in project.intents.items(): - for pattern in intent.shortcuts: - if pattern.fullmatch(message): - return RouteDecision( - intent=intent_id, - standalone=True, - shortcut=pattern.pattern, - ) - representations = [ ( {"turn_id": index, "skip": True} @@ -1025,18 +1033,36 @@ def route_question( ) for index, turn in enumerate(turns, 1) ] + # History prerequisites are independent of wording and must apply + # even to shortcuts and saved routes that bypass model classification. + unavailable = _history_exclusions(project, representations) + + # Obvious messages such as greetings skip the router model. + message = re.sub(r"[\s!?.,]+$", "", question.strip()) + for intent_id, intent in project.intents.items(): + if intent_id in unavailable: + continue + for pattern in intent.shortcuts: + if pattern.fullmatch(message): + return RouteDecision( + intent=intent_id, + standalone=True, + shortcut=pattern.pattern, + ) + # A question asked again is not routed by rule: the router reads that # it repeats an earlier turn, with that turn's intent, and decides. repeated = _repeated_turn(turns, question, excluded_turn_ids) if repeated == len(turns) and choose is not None: chosen = _repeat_choice( - chat, project, representations, question, turns, choose + chat, project, representations, question, turns, choose, + unavailable, ) if chosen is not None: return chosen pointing = refers_back(question) system, prompt = _router_prompt( - project, representations, question, + project, representations, question, frozenset(unavailable), note=_repeat_note(turns, repeated) if repeated else "", ) @@ -1045,8 +1071,20 @@ def route_question( chat, system, prompt, max_new_tokens=_ROUTER_MAX_TOKENS ) except Exception as error: # A routing failure must not stop answers. + explicit = ( + report_intent_override(project, question, ()) + if qualified_references(question) else None + ) + fallback_intent = ( + explicit if explicit is not None and explicit not in unavailable + else project.default_intent + ) + if fallback_intent in unavailable: + fallback_intent = _alternative_intent( + project, question, unavailable + ) return RouteDecision( - intent=project.default_intent, + intent=fallback_intent, standalone=not any( not item["skip"] for item in representations ), @@ -1074,7 +1112,7 @@ def route_question( intent = project.intents.get(decision.intent) fallback = decision.fallback - cued = _cued_intent(project, question) + cued = _cued_intent(project, question, frozenset(unavailable)) if cued is not None and cued != decision.intent: # Clear wording decides the intent; the router judged the history. fallback = ( @@ -1084,10 +1122,10 @@ def route_question( decision = RouteDecision(**{**_fields(decision), "intent": cued}) intent = project.intents[cued] elif intent is not None and cued is None: - excluded = _unmeant_intents(project, question) + excluded = {**_unmeant_intents(project, question), **unavailable} if decision.intent in excluded: - # The wording rules out the router's choice: ask once more - # without it, and use the default intent when that fails. + # Retry once without the unavailable or unmeant intents; + # an invalid retry must not restore an excluded default. replaced = decision.intent retry = _reroute( chat, project, representations, question, len(turns), @@ -1245,6 +1283,7 @@ def _repeat_choice( question: str, turns: list[object], choose: Callable[[str, tuple[str, ...]], int | None], + unavailable: Mapping[str, str], ) -> RouteDecision | None: """Ask the user how to answer a question asked twice in a row. @@ -1266,6 +1305,8 @@ def _repeat_choice( Earlier conversation turns; the last one asked the same question. choose: Callable[[str, tuple[str, ...]], int | None] Asks the user to pick one option. + unavailable: Mapping[str, str] + Intents whose history prerequisites are not met. Returns ------- @@ -1273,8 +1314,8 @@ def _repeat_choice( The last turn's saved route for "Same way again", or the router's choice for "Try another way", without the last intent and without intents that reuse earlier passages (``reuse`` retrieval). None when - the user cancels or the last turn's saved route is unusable; the - router then decides. + the user cancels or the last turn's saved route is unusable or + unavailable; the router then decides. """ @@ -1288,6 +1329,7 @@ def _repeat_choice( if ( not isinstance(intent, str) or intent not in project.intents + or intent in unavailable or type(standalone) is not bool or not isinstance(related, list) or not all(type(item) is int and 0 < item < number for item in related) @@ -1317,6 +1359,7 @@ def _repeat_choice( if setting.retrieval_mode == RETRIEVAL_MODE_REUSE } excluded[intent] = "the user asked for another way" + excluded.update(unavailable) retry = _reroute( chat, project, representations, question, number, excluded ) @@ -1378,8 +1421,50 @@ def another_way_guidance(number: int) -> str: ) -def _cued_intent(project: ProjectType, question: str) -> str | None: - """Return the first intent whose cue the question matches, if any. +def _history_exclusions( + project: ProjectType, representations: list[dict[str, object]], +) -> dict[str, str]: + """Exclude intents that require a missing eligible earlier turn. + + Parameters + ---------- + project: ProjectType + Current project type with its intents. + representations: list[dict[str, object]] + Earlier turns, with small talk and rejected turns marked ``skip``. + + Returns + ------- + dict[str, str] + Unavailable intent IDs and their exclusion reasons. Empty when + at least one earlier turn can be used. + + Notes + ----- + Only unconditional follow-up tools require history for every request. + A conditional ``follows_up_when`` tool may operate on a new source + without an earlier turn. Individual tools still validate the actual + evidence or results they need. + + """ + + if any(not item["skip"] for item in representations): + return {} + tools = registered_tools() + return { + key: "there is no eligible earlier turn" + for key, intent in project.intents.items() + if intent.retrieval_mode == RETRIEVAL_MODE_REUSE + or (intent.tool is not None and tools[intent.tool.name].follows_up) + } + + +def _cued_intent( + project: ProjectType, + question: str, + exclude: frozenset[str] = frozenset(), +) -> str | None: + """Prefer eligible report references, otherwise the first matching cue. Parameters ---------- @@ -1387,22 +1472,27 @@ def _cued_intent(project: ProjectType, question: str) -> str | None: Current project type with its intents. question: str The new question. + exclude: frozenset[str], optional + Intent IDs whose history prerequisites are not met. Defaults to + none when only checking the wording rules. Returns ------- str | None - The intent ID, in the project type's order; None without a match. + The eligible intent ID, in the project type's order; None without + an eligible match. """ - return next( - ( - intent_id - for intent_id, intent in project.intents.items() - if any(pattern.search(question) for pattern in intent.cues) - ), - None, + matched = tuple( + intent_id for intent_id, intent in project.intents.items() + if intent_id not in exclude + and any(pattern.search(question) for pattern in intent.cues) ) + explicit = report_intent_override(project, question, matched) + if explicit is not None and explicit not in exclude: + return explicit + return matched[0] if matched else None def _unmeant_intents(project: ProjectType, question: str) -> dict[str, str]: @@ -1429,15 +1519,22 @@ def _unmeant_intents(project: ProjectType, question: str) -> dict[str, str]: _NAMED_FILE.search(question) and not _EARLIER_ANSWER.search(question) ) excluded: dict[str, str] = {} + report_wording = without_source_filenames(question) for intent_id, intent in project.intents.items(): + wording = ( + report_wording + if intent.tool is not None and intent.tool.name in ( + TOOL_GENERATE_PAPER_SUMMARY, TOOL_PROJECT_SUMMARY, + ) else question + ) if intent.requires and not any( - pattern.search(question) for pattern in intent.requires + pattern.search(wording) for pattern in intent.requires ): excluded[intent_id] = "the question lacks its required words" elif ( new_about_file and intent.tool is not None - and TOOL_REGISTRY[intent.tool.name].follows_up + and registered_tools()[intent.tool.name].follows_up ): excluded[intent_id] = ( "the question names a file and no earlier answer" @@ -1445,6 +1542,48 @@ def _unmeant_intents(project: ProjectType, question: str) -> dict[str, str]: return excluded +def _alternative_intent( + project: ProjectType, question: str, excluded: Mapping[str, str], +) -> str: + """Select an ordinary fallback without reinstating excluded intents. + + Parameters + ---------- + project: ProjectType + Available intents and configured default. + question: str + Current question, used to check wording constraints. + excluded: Mapping[str, str] + Intent IDs that must not be selected. + + Returns + ------- + str + The first suitable ordinary, non-reuse intent, preferring the + configured default. + + Raises + ------ + ValueError + No suitable ordinary fallback exists. + + """ + + excluded_by_words = _unmeant_intents(project, question) + fallback = next( + ( + key for key in (project.default_intent, *project.intents) + if key not in excluded and key not in excluded_by_words + and project.intents[key].tool is None + and project.intents[key].retrieval_mode != RETRIEVAL_MODE_REUSE + ), + None, + ) + if fallback is None: + raise ValueError("No suitable alternative intent is available.") + return fallback + + def _reroute( chat: _Chat, project: ProjectType, @@ -1459,7 +1598,8 @@ def _reroute( fails or ignores the allowed intent list. A deterministic fallback prefers the configured default when allowed, otherwise a non-tool, non-reuse intent not contradicted by the wording. If there is no - suitable alternative, the request fails explicitly. + suitable fallback and the model cannot select an allowed intent, the + request fails explicitly. Parameters ---------- @@ -1488,23 +1628,8 @@ def _reroute( """ - available = tuple( - key for key in project.intents if key not in excluded - ) - if not available: + if not any(key not in excluded for key in project.intents): raise ValueError("No alternative intent is available.") - excluded_by_words = _unmeant_intents(project, question) - fallback = next( - ( - key for key in (project.default_intent, *available) - if key in available and key not in excluded_by_words - and project.intents[key].tool is None - and project.intents[key].retrieval_mode != RETRIEVAL_MODE_REUSE - ), - None, - ) - if fallback is None: - raise ValueError("No suitable alternative intent is available.") system, prompt = _router_prompt( project, representations, question, frozenset(excluded) ) @@ -1515,13 +1640,13 @@ def _reroute( decision = _parse_route(raw, project, turn_count) except Exception: return RouteDecision( - intent=fallback, + intent=_alternative_intent(project, question, excluded), standalone=not refers_back(question), fallback="router failed; used an allowed alternative", ) if decision.fallback is not None or decision.intent in excluded: return RouteDecision( - intent=fallback, + intent=_alternative_intent(project, question, excluded), standalone=not refers_back(question), raw=decision.raw, fallback="router did not select an allowed intent", @@ -1548,7 +1673,7 @@ def _tool_follows_up(name: str, question: str) -> bool: """ - tool = TOOL_REGISTRY[name] + tool = registered_tools()[name] return tool.follows_up or ( tool.follows_up_when is not None and tool.follows_up_when(question) ) @@ -1890,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/atomic_writes.py b/kilin/atomic_writes.py index 346c7eed..aedaa086 100644 --- a/kilin/atomic_writes.py +++ b/kilin/atomic_writes.py @@ -46,9 +46,48 @@ import os from pathlib import Path from tempfile import NamedTemporaryFile +from time import monotonic, sleep +from typing import Final __all__ = ["atomic_write_text", "atomic_create_text"] +_WINDOWS_REPLACE_TIMEOUT: Final[float] = 1.0 +_WINDOWS_REPLACE_POLL: Final[float] = 0.01 + + +def _replace(temporary: Path, path: Path) -> None: + """Retry briefly when Windows denies replacement of a closed file. + + Parameters + ---------- + temporary: pathlib.Path + Fully written, closed temporary file owned by the caller. + path: pathlib.Path + Destination to replace atomically. + + Notes + ----- + Windows readers and file scanners can deny a rename even when all + cooperating writers obey the application's file lease. Only Windows + access-denied, sharing-violation and lock-violation errors are retried. + The caller retains its existing lease and the same temporary file; + persistent failures propagate without deleting the destination. + + """ + + deadline = monotonic() + _WINDOWS_REPLACE_TIMEOUT + while True: + try: + temporary.replace(path) + return + except PermissionError as error: + if getattr(error, "winerror", None) not in (5, 32, 33): + raise + remaining = deadline - monotonic() + if remaining <= 0: + raise + sleep(min(_WINDOWS_REPLACE_POLL, remaining)) + def atomic_write_text(path: Path, content: str) -> None: """Replace one text file using a unique sibling temporary file. @@ -71,6 +110,8 @@ def atomic_write_text(path: Path, content: str) -> None: conflicts with pre-existing ``.tmp`` files and symbolic links. The temporary file is removed even if writing or replacement fails. This helper does not acquire a file lock or force data to stable storage. + Transient Windows replacement denials are retried for at most one + second; other errors and persistent denials propagate to the caller. """ @@ -87,7 +128,7 @@ def atomic_write_text(path: Path, content: str) -> None: try: with stream: stream.write(content) - temporary.replace(path) + _replace(temporary, path) finally: temporary.unlink(missing_ok=True) 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/cli.py b/kilin/cli.py index 33b4793a..95b0face 100644 --- a/kilin/cli.py +++ b/kilin/cli.py @@ -1,6 +1,7 @@ -"""Launch KíLín's optional graphical interface from the command line. +"""Launch KíLín or inspect its versions from the command line. -``main`` parses the GUI and backend options. Without ``--gui`` it prints help. +``main`` parses GUI, backend and version-reporting options. Without a +selected command it prints help. Before a GUI launch it checks for the requested dependency modules and may run ``uv sync`` in a development checkout to install missing extras. This preparation may modify the environment and require network access. @@ -54,8 +55,10 @@ from argparse import ArgumentParser from collections.abc import Sequence +from contextlib import redirect_stdout import importlib from importlib.util import find_spec +import json from pathlib import Path import platform import shutil @@ -152,8 +155,50 @@ def _ensure_gui_environment(backend: Backend) -> None: importlib.invalidate_caches() +def _print_versions(info: dict) -> None: + """Display a readable version inventory without re-reading the runtime. + + Parameters + ---------- + info: dict + Structured snapshot from ``kilin.version_info()``. + + """ + + print(f"KíLín {info['application']['version']}") + for title, key in ( + ("Compatibility contracts", "contracts"), + ("Persistent formats", "persistent_formats"), + ): + print(f"\n{title}") + for name, value in info[key].items(): + print(f" {name}: {value}") + for title, key in ( + ("Tools", "tools"), ("Project types", "project_types"), + ("Installed user plugins", "installed"), + ("Pending plugin changes", "pending"), + ): + print(f"\n{title}") + if not info[key]: + print(" None") + for record in info[key]: + name = record.get("name", record.get("type_id")) + print(f" {name}") + for field, value in record.items(): + if field in ("name", "type_id"): + continue + if value is None: + value = "unknown" + print(f" {field}: {value}") + print(f"\nPlugin directory: {info['directory'] or 'unknown'}") + if info["errors"]: + print("\nInventory diagnostics") + for name, error in info["errors"].items(): + print(f" {name}: {error}") + + def main(arguments: Sequence[str] | None = None) -> int: - """Launch the selected KíLín interface. + """Launch the selected KíLín interface or report versions. Parameters ---------- @@ -164,7 +209,7 @@ def main(arguments: Sequence[str] | None = None) -> int: Returns ------- int - Interface exit code, or zero after displaying help. + Interface exit code, or zero after displaying help or versions. Notes ----- @@ -178,11 +223,27 @@ def main(arguments: Sequence[str] | None = None) -> int: prog="kilin", description="Run KíLín locally against your own project.", ) - parser.add_argument( + actions = parser.add_mutually_exclusive_group() + actions.add_argument( "--gui", action="store_true", help="open the desktop interface", ) + actions.add_argument( + "--version", + action="store_true", + help="show the application version without discovering plugins", + ) + actions.add_argument( + "--versions", + action="store_true", + help="show application, plugin and persistent-format versions", + ) + parser.add_argument( + "--json", + action="store_true", + help="write the complete --versions inventory as JSON", + ) parser.add_argument( "--backend", choices=BACKEND_CHOICES, @@ -190,6 +251,26 @@ def main(arguments: Sequence[str] | None = None) -> int: help="backend to prepare for the desktop interface", ) options = parser.parse_args(arguments) + if options.json and not options.versions: + parser.error("--json requires --versions") + if options.version: + import kilin + + print(f"KíLín {kilin.__version__}") + return 0 + if options.versions: + import kilin + + # A trusted installed plugin can print during ordinary discovery. + # Keep the machine-readable report separate from such messages. + with redirect_stdout(sys.stderr): + info = kilin.version_info() + if options.json: + # Escape paths and diagnostics for restrictive stream encodings. + print(json.dumps(info, ensure_ascii=True, indent=2)) + else: + _print_versions(info) + return 0 if not options.gui: parser.print_help() return 0 diff --git a/kilin/conversation_format.py b/kilin/conversation_format.py index 6f40c55e..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,8 +63,20 @@ 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", "CONVERSATION_SESSION_TITLE", @@ -63,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" @@ -71,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]: @@ -119,21 +177,32 @@ def conversation_state( Raises ------ ValueError - If the payload is malformed, contains obsolete conversation fields, - reserves the session key for another purpose, or has an ambiguous - conversation category. Reading never modifies the supplied payload. + If the payload is malformed, declares an unsupported trace version, + contains obsolete conversation fields, reserves the session key for + another purpose, or has an ambiguous conversation category. Reading + never modifies the supplied payload. 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. """ invalid = "The saved conversation is invalid." if not isinstance(payload, dict) or "conversation" in payload: raise ValueError(invalid) + # State-only conversation files may not yet have a trace header. A + # declared trace version must be understood before any reader or writer + # interprets the stored sessions. + if "trace_format_version" in payload and ( + type(payload["trace_format_version"]) is not int + or payload["trace_format_version"] != TRACE_FORMAT_VERSION + ): + raise ValueError(f"{invalid} Unsupported trace format version.") trace = payload.get("trace") if isinstance(trace, dict) and "sessions" in trace: raise ValueError(invalid) @@ -189,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/conversation_memory/retrieval.py b/kilin/conversation_memory/retrieval.py index a0343112..f85533f9 100644 --- a/kilin/conversation_memory/retrieval.py +++ b/kilin/conversation_memory/retrieval.py @@ -14,7 +14,7 @@ - **Distinct provenance** - Provide conversation, turn UUID, role, time, and source-free memory labels. + Keep durable identities in records and use local labels in the prompt. - **Bounded context** @@ -173,15 +173,14 @@ def render_memory_hits(hits: tuple[MemoryHit, ...]) -> str: parts = [ "CONVERSATION MEMORY (previous discussion, NOT source evidence):" ] + turns: dict[str, int] = {} for number, hit in enumerate(hits, 1): record = hit.record - origins = ", ".join( - f"{origin.conversation_id} turn {origin.turn_number}" - for origin in record.origins - ) + # The UUID establishes pairing only; its value never enters the + # model context. Labels depend on the selected message order. + turn = turns.setdefault(record.turn_uuid, len(turns) + 1) parts.append( - f"Memory M{number} | {record.role} | " - f"UUID {record.turn_uuid} | {record.timestamp} | {origins}\n" + f"Memory M{number} | {record.role} | Turn T{turn}\n" + "\n".join( " " + line for line in hit.text.splitlines() ) @@ -189,6 +188,46 @@ def render_memory_hits(hits: tuple[MemoryHit, ...]) -> str: return "\n\n".join(parts) +def _turn_order(records: list[MemoryRecord]) -> dict[str, tuple]: + """Resolve relevance ties without sorting on UUIDs or wall-clock time. + + Parameters + ---------- + records: list of MemoryRecord + Eligible occurrences after exclusions. + + Returns + ------- + dict + Per-turn ordering keys derived from branch-local positions and + eligible message content/priority. Identical semantic turns share + a key prefix; a group ordinal keeps their two roles together. + + Notes + ----- + A UUID is only a dictionary key for grouping a question and its reply. + Completely indistinguishable turns may differ in navigational origin, + but choosing either leaves the model-facing text and pairing unchanged. + + """ + groups: dict[str, list[MemoryRecord]] = {} + for record in records: + groups.setdefault(record.turn_uuid, []).append(record) + result = {} + for ordinal, (uid, group) in enumerate(groups.items()): + positions = tuple(sorted({ + origin.turn_number + for record in group for origin in record.origins + })) + signature = tuple(sorted( + (record.role, record.fingerprint, record.text, record.priority, + tuple(sorted(origin.turn_number for origin in record.origins))) + for record in group + )) + result[uid] = (positions, signature, ordinal) + return result + + def _historical_groups( records: list[MemoryRecord], topic: str, ) -> tuple[tuple[_RankedRecord, ...], ...]: @@ -224,7 +263,9 @@ def _historical_groups( relevance = overlap / len(topic_terms) matches.append((relevance, relevance, record)) - def key(item: _RankedRecord) -> tuple[float, str, str, str]: + order = _turn_order(records) + + def key(item: _RankedRecord) -> tuple[float, tuple, str]: """Make relevance ties stable across index reconstruction. Parameters @@ -234,13 +275,13 @@ def key(item: _RankedRecord) -> tuple[float, str, str, str]: Returns ------- - tuple[float, str, str, str] + tuple Stable sort key preferring high relevance. """ score, _, record = item - return (-score, record.timestamp, record.turn_uuid, record.role) + return (-score, order[record.turn_uuid], record.role) pairs: list[tuple[_RankedRecord, ...]] = [] singles: list[_RankedRecord] = [] @@ -434,7 +475,7 @@ def search_memory( document_terms = [_terms(item.text) for item in candidates] term_frequency = { term: sum(term in words for words in document_terms) - for term in terms + for term in sorted(terms) } weights = { term: log1p((len(candidates) + 1) / (count + 1)) @@ -450,7 +491,7 @@ def search_memory( continue semantic = max(0.0, _similarity(query_vector, vector)) lexical = ( - sum(weights[term] for term in terms & record_terms) + sum(weights[term] for term in sorted(terms & record_terms)) / denominator if denominator else 0.0 ) if semantic < _MIN_SEMANTIC and lexical < _MIN_LEXICAL: @@ -475,9 +516,9 @@ def search_memory( if (anchor_semantic is None or lexical >= 0.05 or semantic > anchor_semantic + 0.10) ] + order = _turn_order(candidates) ranked.sort(key=lambda item: ( - -item[0], -item[1], item[2].timestamp, - item[2].turn_uuid, item[2].role, + -item[0], -item[1], order[item[2].turn_uuid], item[2].role, )) result: list[MemoryHit] = [] displayed_fingerprints: set[str] = set() @@ -489,7 +530,7 @@ def search_memory( if (recall_topic is None and record.fingerprint in displayed_fingerprints): continue - # Account for the rendered header and origin metadata, not only text. + # Account for prompt-local labels as well as message text. hit = MemoryHit(record, record.text, relevance, score) if estimate_tokens(render_memory_hits((*result, hit))) > max_tokens: # Allow a shorter last message, but never an orphaned header. 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 73279613..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). @@ -102,7 +106,12 @@ preserving explicit line breaks and indentation. Other code blocks retain their horizontal scrolling behavior. Files attached to a message are first added to the project's sources and indexed, without the add dialog; the question then lists their `sources/` -paths. The question shows them as chips that open the workspace tree there. +paths under `Attached files:`. The question shows valid managed-relative +paths as chips that open the workspace tree there. Other attachment text is +displayed literally, without workspace actions. +If an attached source still needs a role, KíLín instead opens the source +organization editor and keeps the question and imported paths in the composer. +Review the roles, close the editor, and send the draft explicitly. ## Source selection and workspace preparation @@ -129,7 +138,7 @@ reject drops. A confirmation explains the copy and index update before any import command is sent. Direct empty and oversized files are left out, missing or linked source paths are rejected, and same-name imports show their distinct destination names. Confirmed imports use saved filters, -update the source manifest and indexes, and restore the active conversation. +update the managed import inventory and indexes, and restore the active conversation. On resume, the GUI checks imported originals for changes and asks which files to update, preserve as versions, keep, or remove. A kept copy whose original has disappeared remains detached; restoring the original offers @@ -137,7 +146,8 @@ explicit reconciliation without silently overwriting the kept copy. Sync rejects updates that exceed the project's saved file-size limit. Right-clicking a file or folder inside `sources` (not `sources` itself or any -other workspace item) offers deletion. After confirmation the workspace copy +other workspace item) offers deletion. Selected source files also offer +**Organize this source** when the source-root binding matches the tree. After confirmation the workspace copy is deleted and the project is reopened, so the index drops the removed files; originals outside the workspace and saved chats are untouched. @@ -180,15 +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. -For installed versions upgraded from before 7 November 2026, KíLín also -checks the previous user-data `workspaces/` location for a direct subfolder -containing `profile.ini`. If found, setup offers **Use existing projects** -and displays the old directory; the user must explicitly select it. The -folder is rechecked before saving and the engine restarts to discover its -projects normally. This only changes the saved projects-folder preference: -there is no automatic copy, deletion, or migration of sources, indexes, or -conversations. A saved choice (or `KILIN_WORKSPACES_DIR`) remains authoritative. -Projects with outdated or invalid profiles may still require separate repair. +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. @@ -233,16 +238,73 @@ downloaded from Settings with their Download buttons. Literature defaults permit larger files than code defaults; the profile and current GUI fields remain the effective configuration. +## Source organization + +Use **Organize sources** in Workspace, right-click an eligible source file, +or choose **Source organization settings** in Settings > General. This edits +semantic metadata, not the source files or physical indexes. The Workspace +entry shows the number of selected files and pending role assignments. +Role labels beside selected source files reflect accepted state only. A chain +button identifies active relationships; hover to see the other files, +directions, types and origins, or activate it to manage those relationships. +Dependent files have subdued names while remaining visible and openable in +the same physical folders. A symmetric association alone does not dim a file. +A dependent shared by several parents remains subdued until its last active +dependency is disconnected. + +- Right-click a selected source for **Set role**, **Link to** (choose the other + source, type and dependency direction), **Disconnect from** (choose an + individual active relationship), or **Manage relationships**. Role and + disconnect shortcuts open a focused preview, not an immediate mutation. + Disconnecting an automatic relationship suppresses its recreation. +- When creating a project or adding or synchronizing sources introduces new + pending role assignments, a compact assignment dialog opens after the + engine reports that the project is ready. Select roles individually or in + batches. Sources with accepted defaults need no prompt. Closing without + applying leaves the pending roles visible; reopening alone does not repeat + the prompt. Pending attachments return the unsent question to the composer. +- In the full editor, filter paths or show only pending assignments; select + multiple files to stage a shared explicit role or reset to the accepted + default. Select one source to inspect stored and suppressed relationships. + Stage links, disconnects, manual pins, or restoration of automatic + eligibility. Selected unresolved paths require explicit restoration or + reset before assignment. Inactive records and retained historical versions + remain visible. +- Accepted organization settings provide a role list, default-role selector + and a mode selector for each configured discovery rule (apply, propose or + 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 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 + engine validates the batch and reports canonical differences, discovery + diagnostics and proposed automatic links. Stage a proposal as a manual link + if desired, then preview again. Only **Apply preview** commits changes; + closing or discarding the draft does not alter accepted metadata. A stale + preview or uncertain outcome requires fresh inspection, never automatic retry. + +The editor can initialize genuinely missing metadata only after confirmation. +It does not overwrite malformed metadata. Opening and refreshing inspection +are read-only; a semantic commit does not rebuild physical indexes. Role and +relationship choices survive reopening and synchronization according to the +[manifest lifecycle](../../docs/source_manifest.md). Ordinary nested workspace +imports, version retention, removal, and output/template operations continue +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 @@ -265,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 @@ -289,7 +353,7 @@ is loaded, and unknown settings are rejected. The tools are: - `project_inventory` (intent `project_inventory`): exact counts and lists of the project's files by type and folder, and which have no searchable - text, from the source manifest and index. + text, from the index source state and retrieval index. - `scan_and_list` (intent `mention_listing`): every exact mention of the question's terms, counted and listed with clickable lines, across all files or the one file the question names or describes. @@ -350,6 +414,12 @@ Tutorial 160 explains project types and intents and builds a new type; tutorial 170 shows how to write and register a new tool. +Ordinary source-first intents can opt into **Logical document groups** in +the intent settings. Source limits then count logical anchors; the final +passage and estimated-token limits continue to count physical evidence +once. Grouping is off in the bundled defaults and does not alter the +source files, physical indexes or card generation. + ## Models and generation settings KíLín setup sits at the top of Settings. Below it, settings are grouped in @@ -363,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 @@ -509,13 +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. -Earlier KíLín versions stored effort levels, router models, and search depth -in `effort_levels.json`, and model substitutions in `model_choices.json`. -When opening an older project, the GUI imports compatible values into -`profile.ini` and removes the legacy files after saving the settings. -Customized per-level retrieval counts in legacy data can supply the new -search-depth steps; unchanged legacy defaults do not override the current -search-depth defaults. 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. @@ -543,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 @@ -551,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 @@ -608,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 @@ -680,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 b7642d10..dee6a23d 100644 --- a/kilin/gui/_paths.py +++ b/kilin/gui/_paths.py @@ -39,10 +39,6 @@ Select an installer and an explicit backend extra for the current checkout, installed environment, or macOS application runtime. -- ``available_legacy_workspace_directory`` - - Find an older installed-application project directory without moving it. - - ``projects_folder_confirmed`` Tell whether the user confirmed a projects folder that still exists. @@ -70,7 +66,6 @@ from kilin.runtime import BACKEND_MLX, BACKEND_TORCH __all__ = [ - "available_legacy_workspace_directory", "default_workspace_directory", "gui_install_command", "preferences_path", @@ -79,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 @@ -200,74 +195,6 @@ def _user_projects_directory() -> Path: return _documents_directory() / "KíLín" -def _previous_installed_workspace_directory() -> Path | None: - """Return the pre-November 7 installed GUI workspace parent. - - Returns - ------- - pathlib.Path | None - Old application-data workspace directory, or None for a checkout - or an explicit environment override. - - Notes - ----- - This is a discovery location, never a default or migration target. - Paths match the old installed-app policy on each supported platform. - - """ - - if _development_checkout() is not None or os.environ.get( - WORKSPACES_ENVIRONMENT - ): - return None - home = Path.home() - if sys.platform == "darwin": - base = home / "Library" / "Application Support" / "kilin" - elif sys.platform == "win32": - value = os.environ.get("LOCALAPPDATA") - base = Path(value) / "kilin" if value else ( - home / "AppData" / "Local" / "kilin" - ) - else: - configured = Path(os.environ.get("XDG_DATA_HOME", "")) - base = (configured if configured.is_absolute() else - home / ".local" / "share") / "kilin" - return base / "workspaces" - - -def available_legacy_workspace_directory() -> Path | None: - """Find old installed projects that a user may choose to keep using. - - Returns - ------- - pathlib.Path | None - Existing legacy parent containing at least one candidate project, - or None if no suitable old directory exists. - - Notes - ----- - Only immediate, real subdirectories with a regular ``profile.ini`` - are considered. The actual project schema is checked by the engine - when listing or opening projects. This function never creates, - deletes, copies, or modifies project data. - - """ - - root = _previous_installed_workspace_directory() - if root is None or root.is_symlink() or not root.is_dir(): - return None - try: - for folder in root.iterdir(): - if not folder.is_dir() or folder.is_symlink(): - continue - profile = folder / "profile.ini" - if profile.is_file() and not profile.is_symlink(): - return root.resolve() - except OSError: - return None - return None - - def _development_checkout() -> Path | None: """Find the KíLín source root only when running from its source tree. @@ -300,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/_plugin_management.py b/kilin/gui/_plugin_management.py new file mode 100644 index 00000000..73bbb3e3 --- /dev/null +++ b/kilin/gui/_plugin_management.py @@ -0,0 +1,177 @@ +"""Translate application-level plugin management into GUI protocol data. + +The core owns all installation paths, validation and lifecycle decisions. +This adapter only validates command envelopes, serializes public records, +and correlates replies. It does not open a project or initialize models. + +Key Features +------------ +- Separate installed, runtime, and pending inventories. +- Explicit trust for candidate Python execution. +- Independent diagnostics when one inventory cannot be read. + +Module Structure +---------------- +- ``plugin_inventory`` describes current and pending installations. +- ``plugin_command`` dispatches one correlated management request. + +Examples +-------- +>>> from kilin.gui._plugin_management import plugin_command +>>> reply = plugin_command({"request_id": "1", "operation": "list"}) +>>> reply["request_id"] +'1' + +""" + +from __future__ import annotations + +from pathlib import Path + +from kilin import plugins +from kilin.versioning import _plugin_inventory, _plugin_record as _record + +__all__ = [] + +_KINDS = ("tool", "project_type") +_PATH_OPERATIONS = ("structure", "validate", "install", "update") + + +def plugin_inventory() -> dict: + """Describe installed entries, runtime registrations and pending work. + + Returns + ------- + dict + Independent arrays of public core records plus per-inventory + errors. Installed entries remain manageable if registration fails. + + """ + + return _plugin_inventory() + + +def _candidate(request: dict, kind: str, operation: str) -> Path: + """Extract the selected source and guard row-specific updates. + + Parameters + ---------- + request: dict + Decoded management command. + kind: str + Validated plugin category. + operation: str + Requested candidate operation. + + Returns + ------- + pathlib.Path + Absolute candidate selected by the native file chooser. + + """ + + value = request.get("path") + if not isinstance(value, str) or not value.strip(): + raise ValueError("Choose a plugin source first.") + path = Path(value) + if not path.is_absolute(): + raise ValueError("Choose an absolute plugin source path.") + if operation == "update": + name = path.name if kind == "tool" else path.stem + if request.get("name") != name: + raise ValueError("The replacement must have the same plugin ID.") + return path + + +def _apply(request: dict, operation: str) -> dict: + """Call the public management API for one validated operation. + + Parameters + ---------- + request: dict + Decoded request including kind, source or name and explicit trust. + operation: str + Requested operation, other than listing. + + Returns + ------- + dict + Validation result or published pending-operation record. + + """ + + kind = request.get("kind") + if kind not in _KINDS: + raise ValueError("Unknown plugin category.") + if operation in _PATH_OPERATIONS: + path = _candidate(request, kind, operation) + if kind == "tool": + trusted = request.get("trusted", False) + if operation != "structure" and trusted is not True: + raise ValueError("Confirm trust before executing Python.") + if operation in ("structure", "validate"): + info = plugins.validate_tool( + path, trusted=operation == "validate", + ) + return {"validation": _record(info)} + method = (plugins.install_tool if operation == "install" + else plugins.update_tool) + change = method(path, trusted=True) + elif operation in ("structure", "validate"): + info = plugins.validate_project_type( + path, bind_tools=operation == "validate", + ) + return {"validation": _record(info)} + else: + method = (plugins.install_project_type if operation == "install" + else plugins.update_project_type) + change = method(path) + return {"change": _record(change)} + if operation in ("remove", "cancel"): + name = request.get("name") + if not isinstance(name, str) or not name: + raise ValueError("A plugin ID is required.") + if operation == "cancel": + plugins.cancel_pending_change(kind, name) + return {"canceled": True} + method = (plugins.uninstall_tool if kind == "tool" + else plugins.uninstall_project_type) + return {"change": _record(method(name))} + raise ValueError("Unknown plugin management operation.") + + +def plugin_command(request: object) -> dict: + """Return a correlated reply without touching any open workspace. + + Parameters + ---------- + request: object + JSON-decoded frontend request with a string request_id, operation + and operation-specific fields. + + Returns + ------- + dict + Reply envelope. Mutations refresh the inventory even on failure; + validation reports only on the candidate and never stages it. + + """ + + reply = {"request_id": "", "operation": ""} + try: + if not isinstance(request, dict): + raise ValueError("Expected a plugin management request object.") + for field in ("request_id", "operation"): + value = request.get(field) + if not isinstance(value, str) or not value: + raise ValueError(f"Invalid plugin request {field}.") + reply[field] = value + if reply["operation"] != "list": + reply.update(_apply(request, reply["operation"])) + except Exception as error: + reply["error"] = str(error) + if reply["operation"] in ( + "list", "install", "update", "remove", "cancel", + ): + reply["inventory"] = plugin_inventory() + return reply diff --git a/kilin/gui/_source_organization.py b/kilin/gui/_source_organization.py new file mode 100644 index 00000000..5a67fbb8 --- /dev/null +++ b/kilin/gui/_source_organization.py @@ -0,0 +1,480 @@ +"""Adapt accepted source organization to the headless engine protocol. + +The engine holds one server-side preview, never trusts a client-supplied +manifest, and delegates validation and publication to the core. Semantic +command recording is separate from physical index provenance. + +Key Features +------------ +- Read-only inspection and transactional, single-use previews. +- Correlated command outcomes and separate post-commit diagnostics. +- Explicit semantic identities for lifecycle observations. + +Module Structure +---------------- +- ``SourceOrganizationCommands`` handles the active project's commands. +- Payload helpers serialize validated core records. +- ``record`` emits diagnostics without retrying durable mutations. + +Examples +-------- +>>> from kilin.gui._source_organization import SourceOrganizationCommands +>>> commands = SourceOrganizationCommands() +>>> commands.clear() + +""" + +from __future__ import annotations + +from dataclasses import asdict +import json +from pathlib import Path +import re +from typing import TYPE_CHECKING +from uuid import uuid4 + +from kilin._source_manifest import manifest_data +from kilin.source_manifest import ( + _current_project, + RelationEdit, + ResolveSourceEdit, + RoleEdit, + SourceLifecycleResult, + SourceManifestConflict, + SourceManifestInspection, + SourceManifestPreview, + SourceManifestSnapshot, + apply_source_manifest, + initialize_source_manifest, + inspect_source_manifest, + preview_source_manifest, + refresh_source_manifest, +) +from kilin.source_organization import parse_source_organization + +if TYPE_CHECKING: + from kilin.gui.engine import ChatEngine + from kilin.project import QAProject + from kilin.trace_logging import TraceSink + +__all__ = [] + + +def snapshot_payload(snapshot: SourceManifestSnapshot) -> dict: + """Serialize the exact saved identity and canonical semantic state. + + Parameters + ---------- + snapshot: SourceManifestSnapshot + Validated saved state and original-byte digest. + + Returns + ------- + dict + Revision, digest and canonical organization. + + """ + return { + "revision": snapshot.manifest.revision, + "sha256": snapshot.sha256, + "source_organization": manifest_data(snapshot.manifest), + } + + +def inspection_payload(inspection: SourceManifestInspection) -> dict: + """Serialize a read-only inspection, including unresolved selection. + + Parameters + ---------- + inspection: SourceManifestInspection + Saved state and current selected inventory. + + Returns + ------- + dict + Semantic identity and active, inactive and pending records. + + """ + return { + **snapshot_payload(inspection.snapshot), + "source_root": asdict(inspection.source_root), + "binding_matches": inspection.binding_matches, + "selected": list(inspection.selected), + "active_files": [asdict(item) for item in inspection.active_files], + "current_files": [asdict(item) for item in inspection.current_files], + "active_relations": [asdict(r) for r in inspection.active_relations], + "inactive_files": [asdict(r) for r in inspection.inactive_files], + "inactive_relations": [asdict(r) + for r in inspection.inactive_relations], + "pending": list(inspection.pending), + "pending_roles": list(inspection.pending_roles), + "retained_versions": list(inspection.retained_versions), + } + + +def inspect_payload(project: QAProject) -> dict: + """Expose inspection failures without repairing or blocking activation. + + Parameters + ---------- + project: QAProject + Active workspace to inspect. + + Returns + ------- + dict + Inspection or diagnostic; neither writes metadata. + + """ + try: + return {"inspection": inspection_payload( + inspect_source_manifest(project)), "error": None} + except (OSError, ValueError) as error: + return {"inspection": None, "error": str(error), + "error_type": type(error).__name__} + + +def lifecycle_payload(result: SourceLifecycleResult) -> dict: + """Keep semantic errors distinct from completed physical operations. + + Parameters + ---------- + result: SourceLifecycleResult + Outcome of reconciliation after a physical source operation. + + Returns + ------- + dict + Current inspection, additions, discovery and independent errors. + + """ + inspection = result.inspection + added = [asdict(item) for item in result.added_files] + pending = set(inspection.pending_roles) if inspection else set() + return { + "inspection": inspection_payload(inspection) if inspection else None, + "changed": result.changed, + "added_files": added, + "new_pending_roles": [item["path"] for item in added + if item["path"] in pending], + "discovery": asdict(result.discovery), + "error": result.error, + "trace_error": result.trace_error, + } + + +def record(trace: TraceSink, event: str, data: dict, *, + status: str = "completed") -> str | None: + """Report recording failures without reclassifying a durable mutation. + + Parameters + ---------- + trace: TraceSink + Caller-owned project trace. + event: str + Machine-readable event name. + data: dict + JSON-compatible event details. + status: str, optional + Event status, defaulting to completed. + + Returns + ------- + str | None + Recording failure, if any. + + """ + try: + trace.emit(event, component="gui_engine", data=data, status=status) + if (getattr(trace, "_closed", False) is True or + getattr(trace, "_failed", False) is True): + return "Trace logger is closed or incomplete." + except Exception as error: + return f"{type(error).__name__}: {error}" + return None + + +def _edits(data: object) -> tuple: + """Decode explicit edit discriminators without accepting extra fields. + + Parameters + ---------- + data: object + JSON list of ordered edit records. + + Returns + ------- + tuple + Core role, relation and resolution edit records. + + """ + if not isinstance(data, list): + raise ValueError("Source edits must be a list.") + edits = [] + for item in data: + if not isinstance(item, dict): + raise ValueError("Each source edit must be an object.") + kind = item.get("kind") + if kind == "role" and set(item) == {"kind", "path", "role"}: + if (not isinstance(item["path"], str) or + item["role"] is not None and + not isinstance(item["role"], str)): + raise ValueError("Invalid role edit.") + edits.append(RoleEdit(item["path"], item["role"])) + elif kind == "relation" and set(item) == { + "kind", "source", "target", "relation", "action", + }: + if not all(isinstance(item[key], str) for key in ( + "source", "target", "relation", "action", + )): + raise ValueError("Invalid relation edit.") + edits.append(RelationEdit(item["source"], item["target"], + item["relation"], item["action"])) + elif kind == "resolve" and set(item) == {"kind", "path", "restore"}: + if (not isinstance(item["path"], str) or + type(item["restore"]) is not bool): + raise ValueError("Invalid source resolution edit.") + edits.append(ResolveSourceEdit(item["path"], item["restore"])) + else: + raise ValueError("Unknown or malformed source edit.") + return tuple(edits) + + +def _preview(project: QAProject, request: dict) -> SourceManifestPreview: + """Bind a core preview to the revision and digest shown to the editor. + + Parameters + ---------- + project: QAProject + Active project, not a client-selected destination. + request: dict + Validated envelope with revision, digest and proposed edits. + + Returns + ------- + SourceManifestPreview + Core proposal bound to the inspected state. + + """ + revision, digest = request.get("revision"), request.get("sha256") + if (type(revision) is not int or revision < 0 or + not isinstance(digest, str) or + re.fullmatch(r"[0-9a-f]{64}", digest) is None): + 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", + "adopt_detector_versions", + ) if key in request} + if "organization" in request: + options["organization"] = parse_source_organization( + request["organization"]) + result = preview_source_manifest(project, edits, **options) + before = result.before.snapshot + if (before.manifest.revision != revision or before.sha256 != digest): + raise SourceManifestConflict("Source manifest changed; inspect again.") + return result + + +class SourceOrganizationCommands: + """Own one opaque, single-use preview for the active engine project. + + Preview state is private to the engine process. The core revalidates + the saved bytes, inventory, binding and discovery before publication. + The adapter neither implements a second graph validator nor accepts + an arbitrary destination workspace from the frontend. + + """ + + def __init__(self) -> None: + """Start without a pending preview.""" + self.pending: tuple[ + str, SourceManifestPreview, dict, str, + ] | None = None + + def clear(self) -> None: + """Discard the pending preview on project or inventory changes.""" + self.pending = None + + def execute(self, engine: ChatEngine, request: object) -> None: + """Dispatch a correlated JSON command to the active core project. + + Parameters + ---------- + engine: ChatEngine + Owner of the active session, trace and event sink. + request: object + JSON request containing project, operation and request ID. + + Notes + ----- + Validation and mutation failures emit a failed command outcome. + A committed mutation is never retried or rolled back because a + subsequent metadata refresh or trace notification failed. + + """ + fields = request if isinstance(request, dict) else {} + operation = fields.get("operation") + response = {key: fields.get(key) for key in ( + "operation", "project", "request_id", + )} + trace = engine.project_trace + command = None + name = "gui.source_organization" + trace_error = None + try: + if (engine.session is None or engine._answering or + getattr(engine.session, "_closed", False) is True): + raise RuntimeError("Open an idle project first.") + project = engine.session.project + path = fields.get("project") + if (not isinstance(path, str) or not path or + not Path(path).is_absolute() or + Path(path).resolve() != project.root): + raise ValueError("A different project is now open.") + request_id = fields.get("request_id") + if type(request_id) is not int or request_id < 1: + raise ValueError("Invalid source organization request ID.") + allowed = {"inspect": set(), "initialize": set(), + "reconcile": set(), "apply": {"preview_id"}, + "preview": { + "revision", "sha256", "edits", "organization", + "adopt_type_defaults", "role_mapping", + "relation_mapping", + "adopt_detector_versions", + }} + if (not isinstance(operation, str) or operation not in allowed + or set(fields) - set(response) - allowed[operation]): + raise ValueError("Unknown or malformed organization command.") + # Keep replay inputs independent of mutable caller dictionaries. + 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]): + command["preview_request"] = self.pending[2] + command["preview_command_id"] = self.pending[3] + trace_error = record(trace, name + ".requested", command, + status="started") + if operation == "inspect": + data = {"inspection": inspection_payload( + inspect_source_manifest(project))} + elif operation == "preview": + self.clear() + preview = _preview(project, fields) + token = uuid4().hex + self.pending = (token, preview, fields, + command["command_id"]) + data = { + "preview_id": token, + "inspection": inspection_payload(preview.before), + "proposed_source_organization": manifest_data( + preview.after), + "changed": preview.changed, + "discovery": asdict(preview.discovery), + } + else: + data = self._mutate(engine, project, operation, fields) + except Exception as error: + data = {"error": str(error), "error_type": type(error).__name__, + "conflict": isinstance(error, SourceManifestConflict)} + if command is not None: + trace_error = record(trace, name + ".failed", { + **command, **data, + }, status="failed") or trace_error + else: + failed = bool(data.get("error")) + trace_error = record( + trace, name + (".failed" if failed else ".completed"), + {**command, **data}, status="failed" if failed else + "completed", + ) or trace_error + if trace_error: + data["trace_error"] = data.get("trace_error") or trace_error + engine._send("source_organization", **response, **data) + + def _mutate(self, engine: ChatEngine, project: QAProject, + operation: str, request: dict) -> dict: + """Run a core mutation, then refresh metadata without indexing. + + Parameters + ---------- + engine: ChatEngine + Active engine and its project trace. + project: QAProject + Verified active workspace. + operation: str + Apply, initialize or reconcile. + request: dict + Validated command envelope. + + Returns + ------- + dict + Durable outcome and independent refresh diagnostics. + + """ + pending = self.pending + self.clear() + if operation == "apply": + if (pending is None or request.get("preview_id") != pending[0] + or pending[1].project_root != project.root): + raise SourceManifestConflict("Preview expired; preview again.") + result = apply_source_manifest(project, pending[1], + trace=engine.project_trace) + elif operation == "initialize": + result = initialize_source_manifest(project, + trace=engine.project_trace) + else: + lifecycle = refresh_source_manifest(project, + trace=engine.project_trace) + data = lifecycle_payload(lifecycle) + if lifecycle.error: + return data + if lifecycle.inspection is not None: + data.update(snapshot_payload(lifecycle.inspection.snapshot)) + self._refresh(engine, data) + return data + data = {**snapshot_payload(result.snapshot), "changed": result.changed, + "discovery": asdict(result.discovery), + "trace_error": result.trace_error} + self._refresh(engine, data) + return data + + @staticmethod + def _refresh(engine: ChatEngine, data: dict) -> None: + """Report post-publication refresh failure separately from commit. + + Parameters + ---------- + engine: ChatEngine + Active engine and loaded session. + data: dict + Durable outcome, augmented in place with current inspection + and any post-commit refresh error. + + """ + try: + result = engine.session.refresh_source_metadata() + data["inspection"] = inspection_payload(result.inspection) + engine._send( + "question_suggestions", + project=str(engine.session.project.root), + questions=[asdict(item) for item in result.suggestions], + welcome=list(result.welcome_prompts), + ) + except Exception as error: + data["refresh_error"] = f"{type(error).__name__}: {error}" + # Keep the committed identity distinct from current inspection. + # Never downgrade a successful commit to a failed command. + if "inspection" not in data: + try: + current = inspect_payload(engine.session.project) + data["inspection"] = current["inspection"] + if current.get("error"): + data["refresh_error"] += f"; {current['error']}" + except Exception as failure: + data["inspection"] = None + data["refresh_error"] += f"; {failure}" diff --git a/kilin/gui/app.py b/kilin/gui/app.py index b80e7565..26fd48e5 100644 --- a/kilin/gui/app.py +++ b/kilin/gui/app.py @@ -62,7 +62,7 @@ def main(arguments: Sequence[str] | None = None) -> int: """ try: - from PySide6.QtWidgets import QApplication + from PySide6.QtWidgets import QApplication, QMessageBox from kilin.gui._activation import ask_passkey from kilin.gui.window import ChatWindow @@ -81,6 +81,15 @@ def main(arguments: Sequence[str] | None = None) -> int: app.setApplicationName("KíLín") if not ask_passkey(): return 0 + from kilin.plugins import PluginManagementError + from kilin.plugins._lifecycle import _ensure_runtime + + try: + _ensure_runtime() + except (PluginManagementError, OSError, ValueError) as error: + QMessageBox.critical(None, "KíLín plugin startup", str(error)) + return 1 window = ChatWindow() + app.aboutToQuit.connect(window._shutdown_engine) window.show() return app.exec() diff --git a/kilin/gui/engine.py b/kilin/gui/engine.py index a22b0cfa..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 ------------ @@ -82,11 +84,12 @@ from threading import Event, Lock, Thread from time import perf_counter from typing import Callable, Final +from uuid import uuid4 from kilin._model_completion import GenerationCancelled +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, ) @@ -120,6 +123,13 @@ write_defaults, ) from kilin.gui._report_pdf import write_report_pdf +from kilin.gui._source_organization import ( + SourceOrganizationCommands, + inspect_payload, + lifecycle_payload, + record, +) +from kilin.source_manifest import SourceLifecycleResult, read_source_manifest from kilin.gui.model_settings import ( DEFAULT_LEVEL, LEVEL_COUNT, @@ -142,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, @@ -150,6 +161,7 @@ sync_project_sources, ) from kilin.tool_settings import project_tool_settings, save_tool_settings +from kilin.plugins import _project_plugin_snapshot from kilin.settings_info import get_settings_info from kilin.project_behavior import ( PROJECT_BEHAVIOR_FILE, @@ -160,11 +172,15 @@ from kilin.workspace_resources import PROJECT_SOURCES_DIRECTORY from kilin.project_files import ( add_project_files, + create_project_folder, list_project_files, 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, @@ -177,9 +193,11 @@ from kilin.conversation_ownership import ConversationFileLock from kilin.conversations import ConversationInfo, ConversationStore from kilin.huggingface import download_model -from kilin.project_type import load_project_types, project_type +from kilin.project_type import ( + _ID_PATTERN, load_project_types, project_type, project_type_catalog, +) from kilin.project import ( - PROJECT_TYPE_IDS, + project_type_ids, ProjectAlreadyExistsError, WorkspaceOccupiedError, QAProject, @@ -188,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, @@ -214,6 +233,7 @@ TraceLogger, TraceSink, TraceTextStream, + _project_trace_logger, ) __all__ = [ @@ -316,18 +336,17 @@ class ChatEngine: active_conversation: ConversationInfo | None Metadata for the active conversation. project_trace: TraceSink - Active diagnostic sink, or a null sink when tracing is disabled. + Shared project-level diagnostic sink, or a null sink. + conversation_trace: TraceSink + Active conversation diagnostic and checkpoint sink, or a null sink. active_trace: TraceSink - Property exposing the current project trace to redirected backend - output. + Property exposing the active conversation trace to backend output. Methods ------- **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() @@ -346,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) @@ -363,6 +380,8 @@ class ChatEngine: Delete managed source copies through the core and reindex. sync_sources(decisions) Apply the user's choice for each changed source, then reindex. + source_organization(request) + Inspect or explicitly edit accepted semantic source organization. edit_folder(folder, operation) Delegate editing outputs/ and templates/ to the core API. rename_project(name) @@ -382,12 +401,15 @@ 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. - **Tools.** + **Application plugins and project tools.** + plugin_management(request) + Handle a correlated application-level plugin management request. + versions(request_id) + Report the application inventory and active project origin. tool_settings() Send the tools the open project can use, with their settings. save_tool_settings(name, settings) @@ -486,114 +508,137 @@ def __init__( # Set from the input thread by Stop; checked by every model call. self._answer_stop = Event() self._answering = False + self._source_organization_commands = SourceOrganizationCommands() self.project_trace: TraceSink = NullTraceLogger() + self._creation_defaults: tuple[str, dict[str, object]] | None = None + self.conversation_trace: TraceSink = NullTraceLogger() self.session: RAGSession | None = None self.conversation_store: ConversationStore | None = None self.active_conversation: ConversationInfo | None = None @property def active_trace(self) -> TraceSink: - """Return the active project trace or a harmless no-op trace. + """Return the active conversation trace or a harmless no-op trace. Returns ------- TraceSink - The active project trace or a harmless no-op trace. + The active conversation trace or a harmless no-op trace. """ - return self.project_trace + return self.conversation_trace - def _start_project_trace( + def _start_conversation_trace( self, project_directory: Path, conversation: ConversationInfo | None = None, ) -> None: - """Open the single trace file owned by one conversation. + """Open a conversation trace and its shared project trace. Parameters ---------- project_directory: pathlib.Path - Resolved managed-project directory associated with the conversation - trace. + Managed project owning both trace files. conversation: ConversationInfo | None, optional - Registered conversation metadata for the state to activate or - trace. Defaults to ``None``. - - Raises - ------ - RuntimeError - If tracing is enabled without a conversation and opened store. - ValueError - If the stored conversation trace is invalid. + Registered conversation metadata for the state to activate. + Defaults to None. Notes ----- - With tracing disabled, this selects a null sink. Otherwise it opens a - logger using full diagnostic recording at the conversation state path - and emits trace_ready. - The path comes from the store, keeping GUI trace and resume state - aligned. + The conversation file has an exclusive session lease. The shared + project file survives conversation switches and takes only short + write leases. Both use the same project sequence. """ if not self.trace_enabled: - self.project_trace = NullTraceLogger() + self.conversation_trace = NullTraceLogger() return if conversation is None or self.conversation_store is None: raise RuntimeError("Conversation store is not open.") trace_path = self.conversation_store.state_path(conversation) - scope = "conversation" - self.project_trace = TraceLogger( + project_path = project_directory / "logs" / "traces" / "project.json" + old_conversation = self.conversation_trace + old_project = self.project_trace + conversation_trace = TraceLogger( TraceConfig( enabled=True, output_path=trace_path, failure_policy=FAILURE_POLICY_WARN, ), default_directory=trace_path.parent, + project_directory=project_directory, ) - self.project_trace.emit( - f"{scope}.trace.started", - component="gui_engine", - data={ - "scope": scope, - "entrypoint": "gui", - "project_directory": str(project_directory), - "conversation": ( - asdict(conversation) if conversation is not None else None - ), - }, - ) - self._send( - "trace_ready", - trace_path=str(self.project_trace.readable_path), - scope=scope, - conversation_id=( - conversation.conversation_id - if conversation is not None - else None - ), - ) + project_trace = old_project + try: + if not project_trace.enabled: + project_trace = _project_trace_logger( + TraceConfig( + enabled=True, failure_policy=FAILURE_POLICY_WARN + ), + project_directory, + ) + elif Path(project_trace.output_path).resolve() != ( + project_path.resolve() + ): + raise RuntimeError("The project trace belongs elsewhere.") + self.conversation_trace = conversation_trace + self.project_trace = project_trace + conversation_trace.emit( + "conversation.trace.started", + component="gui_engine", + data={ + "scope": "conversation", + "entrypoint": "gui", + "project_directory": str(project_directory), + "conversation": asdict(conversation), + }, + ) + self._send( + "trace_ready", + trace_path=str(conversation_trace.readable_path), + scope="conversation", + conversation_id=conversation.conversation_id, + ) + except BaseException: + self.conversation_trace = old_conversation + self.project_trace = old_project + try: + conversation_trace.close(emit_event=False) + finally: + if project_trace is not old_project: + project_trace.close() + raise - def _close_project_trace(self) -> None: - """Finish the current project trace without closing the GUI trace.""" + def _close_conversation_trace(self) -> None: + """Close the current conversation trace and release its lease.""" - if self.project_trace.enabled: - self.project_trace.close() - self.project_trace = NullTraceLogger() + trace = self.conversation_trace + self.conversation_trace = NullTraceLogger() + trace.close() + + def _close_traces(self) -> None: + """Close both owned sinks, even if conversation cleanup fails.""" + + try: + self._close_conversation_trace() + finally: + trace = self.project_trace + self.project_trace = NullTraceLogger() + trace.close() - def _detach_project_trace(self) -> None: - """Close an archived trace and release its file lock without writing. + def _detach_conversation_trace(self) -> None: + """Release the already archived conversation trace without writing. - GUI conversation deletion archives a trace whose accepted events and - resume state have already been written. Closing without a final event - avoids rewriting the moved JSON and releases the exclusive file lock. + Its numbered events remain in the archive. The project trace stays + open for the replacement conversation. """ - if isinstance(self.project_trace, TraceLogger): - self.project_trace.close(emit_event=False) - self.project_trace = NullTraceLogger() + if isinstance(self.conversation_trace, TraceLogger): + self.conversation_trace.close(emit_event=False) + self.conversation_trace = NullTraceLogger() def _store_ownership( self, conversation_id: str @@ -625,8 +670,8 @@ def _store_ownership( or conversation_id != self.active_conversation.conversation_id ): return None - if isinstance(self.project_trace, TraceLogger): - return self.project_trace._file_lock + if isinstance(self.conversation_trace, TraceLogger): + return self.conversation_trace._file_lock if self.session is not None: return self.session._active_conversation_lock() return None @@ -710,7 +755,16 @@ def _report_error( """ - trace = self.active_trace + project_event = event_type.startswith(( + "gui.project.", "gui.project_", "gui.sources.", + "gui.indexing.", "gui.models.", "gui.model.", "gui.folder.", + "gui.tool_settings.", "gui.source_cards.", + "gui.answer_settings.", "gui.conversation_", + )) + trace = ( + self.project_trace if project_event and self.project_trace.enabled + else self.active_trace + ) trace.exception( event_type, error, @@ -727,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. @@ -1043,111 +1087,58 @@ def heartbeat() -> None: return perf_counter() - model_started def list_saved_projects(self, workspace: str) -> None: - """Report valid projects of all registered types, newest first. + """List recognized projects, including unavailable types, newest first. Parameters ---------- workspace: str - Workspace containing saved projects. + Explicit workspace path, or an empty string to discover saved + projects in the engine workspace root. """ - self._send( - "projects", - projects=[ - { - "project": str(folder), - "name": folder.name, - "type_id": type_id, - "updated_at": updated_at, - } - for updated_at, folder, type_id - in self._saved_projects(workspace) - ], - ) - - 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. - - """ - - projects = self._saved_projects(workspace, type_id) - if not projects: - return None - _, folder, saved_type_id = max( - projects, key=lambda item: (item[0], str(item[1])) - ) - return folder, saved_type_id + catalog = project_type_catalog() + projects = [] + for updated_at, folder, type_id in self._saved_projects(workspace): + info = catalog.get(type_id) + reason = ( + f"Project type {type_id!r} is not installed." + if info is None else info.error + ) + projects.append({ + "project": str(folder), + "name": folder.name, + "type_id": type_id, + "updated_at": updated_at, + "available": reason is None, + "unavailable_reason": reason, + }) + self._send("projects", projects=projects) def _saved_projects( - self, workspace: str, type_id: str | None = None + self, workspace: str ) -> list[tuple[float, Path, str]]: - """Return valid saved projects ordered from newest to oldest. + """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]] - valid saved projects ordered from newest to oldest. + 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 type_id is not None and type_id not in PROJECT_TYPE_IDS: - return [] if workspace.strip(): folders = [Path(workspace).expanduser()] elif self.sandbox.is_dir(): @@ -1159,6 +1150,9 @@ def _saved_projects( for folder in folders: if not folder.is_dir() or folder.is_symlink(): continue + marker = folder / ".kilin-creating" + if marker.exists() or marker.is_symlink(): + continue profile_path = folder / "profile.ini" if not profile_path.is_file() or profile_path.is_symlink(): continue @@ -1167,18 +1161,11 @@ def _saved_projects( parser.read(profile_path, encoding="utf-8") saved_type_id = parser.get("project", "type_id") source_text = parser.get("project", "source") - if saved_type_id not in PROJECT_TYPE_IDS: + 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") ) @@ -1200,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: @@ -1217,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 @@ -1225,8 +1258,16 @@ def resume_project( conversation = self._open_conversation_store( project, conversation_id ) - self._start_project_trace(project.root, conversation) - self._activate_project(project, conversation) + self._start_conversation_trace(project.root, conversation) + with self.project_trace.span( + "gui.project.open", component="gui_engine", + data={ + "reason": "resume", + "conversation_id": conversation.conversation_id, + "requested_conversation_id": conversation_id, + }, + ): + self._activate_project(project, conversation) self._report_source_changes(project) except Exception as error: self._report_error( @@ -1240,7 +1281,7 @@ def resume_project( if previous_released: self.close() elif self.session is None: - self._close_project_trace() + self._close_traces() def _report_source_changes(self, project: QAProject) -> None: """Tell the frontend which originals changed since their import. @@ -1262,11 +1303,11 @@ def _report_source_changes(self, project: QAProject) -> None: try: changes = find_source_changes(project) except Exception as error: - self.active_trace.exception( + self.project_trace.exception( "gui.sources.changes.failed", error, component="gui_engine" ) return - self.active_trace.emit( + self.project_trace.emit( "gui.sources.changes.found", component="gui_engine", data=changes ) if changes["added"] or changes["changed"] or changes["deleted"]: @@ -1417,8 +1458,40 @@ def settings(self, type_id: str, workspace: str) -> None: """ try: - # Before the page knows the types, use the first one in the file. - type_id = type_id or next(iter(load_project_types())) + # Before the page knows the types, use the first available one. + types = load_project_types() + if not types: + self._creation_defaults = None + self._send( + "settings", profile=None, project_types=[], + project_type_error="No project types are available. " + "Restore a valid project type and restart KíLín.", + ) + return + type_items = [ + { + "type_id": item.id, + "label": item.display_name, + "intents": { + intent_id: intent_id.replace("_", " ").capitalize() + for intent_id in item.intents + }, + "welcome_prompts": list(item.welcome_prompts), + "suggestions": list(item.suggestions), + } + for item in types.values() + ] + type_id = type_id or next(iter(types)) + if not workspace.strip() and type_id not in types: + self._creation_defaults = None + try: + project_type(type_id) + except ValueError as error: + self._send( + "settings", profile=None, project_types=type_items, + project_type_error=str(error), + ) + return profile_path = Path(workspace).expanduser() / "profile.ini" profile = ( open_project(profile_path.parent).profile @@ -1444,30 +1517,42 @@ def settings(self, type_id: str, workspace: str) -> None: ) entries = downloaded_models() cached = {str(item["model_id"]) for item in entries} + root = profile_path.parent if profile_path.is_file() else None + levels = _effort_levels_by_backend(root, profile) + depth = read_search_depth(root) + routers = _router_models_by_backend(root) + cards = self._source_card_settings(root, type_id) + backend_preference = default_backend() + if not workspace.strip(): + defaults = { + **asdict(profile), + "backend": backend_preference, + "allow_download": False, + "max_new_tokens": profile.max_new_tokens + if profile.max_new_tokens is not None else "none", + "_gui_effort_levels": levels, + "_gui_search_depth": depth, + "_gui_router_models": routers, + "_gui_source_cards": cards, + } + self._creation_defaults = ( + type_id, json.loads(json.dumps(defaults)) + ) self._send( "settings", profile=asdict(profile), - effort_levels=_effort_levels_by_backend( - profile_path.parent if profile_path.is_file() else None, - profile, - ), + effort_levels=levels, default_effort_levels={ backend: default_effort_levels(backend) for backend in (BACKEND_MLX, BACKEND_TORCH) }, - search_depth=( - read_search_depth(profile_path.parent) - if profile_path.is_file() - else default_search_depth() - ), + search_depth=depth, appearance=default_appearance(), # The backend chosen in KíLín setup for new projects. - backend_preference=default_backend(), + backend_preference=backend_preference, preferences=_preference_payload(), default_search_depth=default_search_depth(), - router_models=_router_models_by_backend( - profile_path.parent if profile_path.is_file() else None - ), + router_models=routers, default_embedding_models={ backend: default_embedding_model(backend) for backend in (BACKEND_MLX, BACKEND_TORCH) @@ -1476,23 +1561,8 @@ def settings(self, type_id: str, workspace: str) -> None: backend: default_router_model(backend) for backend in (BACKEND_MLX, BACKEND_TORCH) }, - source_cards=self._source_card_settings( - profile_path.parent if profile_path.is_file() else None, - type_id, - ), - project_types=[ - { - "type_id": item.id, - "label": item.display_name, - "intents": { - intent_id: intent_id.replace("_", " ").capitalize() - for intent_id in item.intents - }, - "welcome_prompts": list(item.welcome_prompts), - "suggestions": list(item.suggestions), - } - for item in load_project_types().values() - ], + source_cards=cards, + project_types=type_items, backend=choose_backend(BACKEND_AUTO), installed_backends=installed_backends(), supported_extensions=list(DEFAULT_EXTENSIONS), @@ -1628,7 +1698,7 @@ def apply_model_settings(self, request: dict[str, object]) -> None: encoding="utf-8" ) conversation_id = self.active_conversation.conversation_id - self.active_trace.emit( + self.project_trace.emit( "gui.models.change.requested", component="gui_engine", data={ @@ -1638,11 +1708,13 @@ def apply_model_settings(self, request: dict[str, object]) -> None: "embedding_model": embedding_model, "query_format": query_format, "effort_levels": levels, + "search_depth": depth, + "router_model": router_model, "downloads": missing, }, ) for model_id in missing: - self.active_trace.emit( + self.project_trace.emit( "gui.model.download.started", component="gui_engine", data={"model_id": model_id}, @@ -1651,7 +1723,7 @@ def apply_model_settings(self, request: dict[str, object]) -> None: elapsed = self._download_with_progress( model_id, progress_event="model_download_progress" ) - self.active_trace.emit( + self.project_trace.emit( "gui.model.download.completed", component="gui_engine", data={"model_id": model_id}, @@ -1701,7 +1773,7 @@ def apply_model_settings(self, request: dict[str, object]) -> None: ) # Explicitly confirm the change in the trace before releasing # the models; the replacement uses the same conversation file. - self.active_trace.emit( + self.project_trace.emit( "gui.models.change.confirmed", component="gui_engine", data={**settings, "reindex_required": rebuilt}, @@ -1718,7 +1790,7 @@ def apply_model_settings(self, request: dict[str, object]) -> None: self.session.use_chat_model(chat_model) changed_runtime = True project = configure_project( - root, settings, trace=self.active_trace + root, settings, trace=self.project_trace ) changed_profile = True if levels is not None: @@ -1735,13 +1807,14 @@ def apply_model_settings(self, request: dict[str, object]) -> None: self.session.project = project if router_model is not None: self.session.use_router_model(router_model) - self.active_trace.emit( + self.project_trace.emit( "gui.models.change.applied", component="gui_engine", data={ **settings, "effort_levels": levels, "search_depth": depth, + "router_model": router_model, "reindexed": rebuilt, }, ) @@ -1940,7 +2013,8 @@ def open_project( Notes ----- The core reserves the final destination and completes creation before - the current session is closed or any new conversation/trace is created. + the current session is closed or a new conversation is created. + Initial imports are traced only after the core claims the destination. Default collisions receive a fresh name. Explicit collisions emit workspace_conflict without modifying the destination or current session; the frontend may request a separate resume operation. @@ -1949,9 +2023,29 @@ def open_project( switched = False try: - if type_id not in PROJECT_TYPE_IDS: + if not type_id: raise ValueError("Choose a project type.") + if type_id not in project_type_ids(): + project_type(type_id) settings = dict(settings or {}) + full_snapshot = settings.pop("_gui_full_snapshot", False) + if type(full_snapshot) is not bool: + raise ValueError("Invalid creation-settings provenance.") + requested = dict(settings) + explicit = requested + provenance = "explicit_request" + displayed_defaults = None + if full_snapshot: + baseline = self._creation_defaults + if baseline is not None and baseline[0] == type_id: + displayed_defaults = baseline[1] + explicit = _creation_overrides( + displayed_defaults, requested + ) + provenance = "displayed_defaults" + else: + explicit = None + provenance = "unavailable" created_levels = settings.pop("_gui_effort_levels", None) created_depth = settings.pop("_gui_search_depth", None) created_routers = settings.pop("_gui_router_models", None) @@ -1997,8 +2091,8 @@ def open_project( ] if missing: raise ValueError("Choose files for every added source.") - # Creation must succeed before touching the current session or - # creating conversation/trace files in the destination. + # The core reserves the destination before creating its trace. + # Do not close the previous project until creation succeeds. self._send("status", message="Preparing the new project...") options: dict[str, object] = {} if selected_files is not None: @@ -2007,6 +2101,10 @@ def open_project( options["settings"] = settings if not workspace.strip(): options["workspace_root"] = self.sandbox + if self.trace_enabled: + options["trace"] = TraceConfig(enabled=True) + organization_outcomes = [] + options["on_organization"] = organization_outcomes.append project = prepare_sources_workspace( sources, type_id, workspace if workspace.strip() else None, **options, @@ -2030,14 +2128,33 @@ def open_project( self.close() switched = True conversation = self._open_conversation_store(project) - self._start_project_trace(project.root, conversation) + self._start_conversation_trace(project.root, conversation) + self.project_trace.emit( + "gui.project.creation.settings", component="gui_engine", + data={ + "operation_recording_version": OPERATION_RECORDING_VERSION, + "requested_settings": requested, + "explicit_settings": explicit, + "provenance": provenance, + "displayed_defaults": displayed_defaults, + }, + ) + for outcome in organization_outcomes: + self._publish_source_organization( + project, "create", outcome + ) if created_levels: - self.active_trace.emit( + self.project_trace.emit( "gui.models.effort_levels.saved", component="gui_engine", data=created_levels, ) - self._activate_project(project, conversation) + with self.project_trace.span( + "gui.project.open", component="gui_engine", + data={"reason": "create", "conversation_id": + conversation.conversation_id}, + ): + self._activate_project(project, conversation) except WorkspaceOccupiedError as error: # Do not append even an error trace to the protected project. # Resuming requires a separate explicit frontend command. @@ -2056,7 +2173,7 @@ def open_project( else: self._send("error", message=message, trace_path=None) if self.session is None: - self._close_project_trace() + self._close_traces() def _open_conversation_store( self, @@ -2124,25 +2241,70 @@ def _activate_project( """ + _source_records(project.root, allow_mirror=True) options: dict[str, object] = { "progress_callback": lambda progress: self._send( "progress", **asdict(progress) ) } - options["trace"] = self.project_trace + options["trace"] = self.conversation_trace + if self.trace_enabled: + options["project_trace"] = self.project_trace if self.conversation_store is None: raise RuntimeError("Conversation store is not open.") # The project keeps every setting from now on, so it resumes as it # was set up even when the defaults or preferences change. if save_project_settings(project.root): - self.active_trace.emit( + self.project_trace.emit( "gui.project.settings.saved", component="gui_engine", data={"path": str(project.root / PROFILE_FILE)}, ) + if self.project_trace.enabled: + # Failure to inspect optional diagnostics must not prevent an + # otherwise valid project from opening. + try: + effective = { + "profile": asdict(open_project(project.root).profile), + "effort_levels": _effort_levels_by_backend( + project.root, project.profile + ), + "router_models": _router_models_by_backend(project.root), + "search_depth": read_search_depth(project.root), + "source_cards": self._source_card_settings( + project.root, project.profile.type_id + ), + "behavior": project_behavior_settings(project.root), + "tools": project_tool_settings(project.root), + "plugins": _project_plugin_snapshot( + project.profile.type_id + ), + } + except (OSError, ValueError, TypeError, KeyError) as error: + self.project_trace.exception( + "gui.project.configuration.snapshot.failed", error, + component="gui_engine", + ) + else: + self.project_trace.emit( + "gui.project.configuration.effective", + component="gui_engine", data=effective, + ) + if self.project_trace.enabled: + self.project_trace.emit( + "gui.conversation.catalog.opened", component="gui_engine", + data={ + "active_conversation_id": conversation.conversation_id, + "conversations": [ + self._conversation_trace_record(item) + for item in self.conversation_store.conversations() + ], + }, + ) options["conversation_path"] = self.conversation_store.state_path( conversation ) + self._source_organization_commands.clear() session = RAGSession(project.root, **options) # RAGSession resolves the same saved router setting in the core. self.session = session @@ -2170,8 +2332,11 @@ def _announce_project( session = self.session behavior = effective_project_type(project.root) self._send_question_suggestions(project) + organization = inspect_payload(project) + self._record_source_organization(project, "opened", organization) self._send( "opened", + source_organization=organization, project=str(project.root), source=str(project.source), type_id=project.profile.type_id, @@ -2301,7 +2466,7 @@ def _save_answer_settings(self, settings: dict[str, object]) -> None: key: "none" if value is None else value for key, value in changes.items() }, - trace=self.active_trace, + trace=self.project_trace, ) def save_answer_settings( @@ -2391,12 +2556,12 @@ def save_answer_settings( } verified = True except Exception as recovery_error: - self.active_trace.exception( + self.project_trace.exception( "gui.answer_settings.reconcile_failed", recovery_error, component="gui_engine", ) - self.active_trace.exception( + self.project_trace.exception( "gui.answer_settings.failed", error, component="gui_engine", @@ -2507,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. @@ -2546,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. """ @@ -2567,15 +2757,40 @@ 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) - snapshot = FeedbackStore(root).update( - identity["conversation_id"], identity["turn_uuid"], - identity["role"], saved=identity["saved"], - reaction=identity["reaction"], - expected_revision=identity["revision"], - ) + with self.project_trace.span( + "gui.conversation.feedback", component="gui_engine", + data={ + "conversation_id": identity["conversation_id"], + "turn_uuid": identity["turn_uuid"], + "role": identity["role"], + "saved": identity["saved"], + "reaction": identity["reaction"], + "expected_revision": identity["revision"], + }, + ): + snapshot = FeedbackStore(root).update( + identity["conversation_id"], identity["turn_uuid"], + identity["role"], saved=identity["saved"], + reaction=identity["reaction"], + expected_revision=identity["revision"], + ) + self.project_trace.emit( + "gui.conversation.feedback.saved", + component="gui_engine", + data={ + "conversation_id": identity["conversation_id"], + "turn_uuid": identity["turn_uuid"], + "role": identity["role"], + "revision": snapshot.revision, + "rating": asdict(snapshot.get( + identity["turn_uuid"], identity["role"] + )), + }, + ) self._send( "message_feedback", **response, revision=snapshot.revision, @@ -2662,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. """ @@ -2683,15 +2899,39 @@ 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"]) - snapshot = FeedbackStore(root).update( - data["conversation_id"], data["turn_uuid"], - data["role"], saved=None, reaction=None, - excluded=data["excluded"], - expected_revision=data["revision"], - ) + with self.project_trace.span( + "gui.conversation.memory_exclusion", component="gui_engine", + data={ + "conversation_id": data["conversation_id"], + "turn_uuid": data["turn_uuid"], + "role": data["role"], + "excluded": data["excluded"], + "expected_revision": data["revision"], + }, + ): + snapshot = FeedbackStore(root).update( + data["conversation_id"], data["turn_uuid"], + data["role"], saved=None, reaction=None, + excluded=data["excluded"], + expected_revision=data["revision"], + ) + self.project_trace.emit( + "gui.conversation.memory_exclusion.saved", + component="gui_engine", + data={ + "conversation_id": data["conversation_id"], + "turn_uuid": data["turn_uuid"], + "role": data["role"], + "revision": snapshot.revision, + "rating": asdict(snapshot.get( + data["turn_uuid"], data["role"] + )), + }, + ) self._send( "memory_exclusion", **response, revision=snapshot.revision, @@ -2760,7 +3000,22 @@ def sync_memory_index(self, project: str) -> None: if self._answering: raise RuntimeError("Finish the current answer first.") self._send("memory_sync_started", project=project) - index = self.session.sync_conversation_memory() + with self.project_trace.span( + "gui.conversation.memory.sync", component="gui_engine", + data={"trigger": "manual"}, + ): + index = self.session.sync_conversation_memory() + self.project_trace.emit( + "gui.conversation.memory.sync.result", + component="gui_engine", + data={ + "model_identity": index.model_identity, + "record_count": len(index.records), + "vector_count": len(index.vectors), + "embedded_count": index.embedded_count, + "changed": index.changed, + }, + ) self._send( "memory_synced", project=project, embedded_count=index.embedded_count, @@ -2821,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 = ( @@ -2828,13 +3093,13 @@ def save_behavior_settings( ) updated = save_project_behavior( root, scope, values, intent_id=intent_id, - expected_revision=revision, trace=self.active_trace, + expected_revision=revision, trace=self.project_trace, ) if scope == "capabilities": self._send("status", message="Rebuilding the index…") refreshed = open_project(root) - self.session.refresh_sources(refreshed) - self.active_trace.emit( + self._refresh_source_indexes(refreshed, "capabilities") + self.project_trace.emit( "gui.indexing.capabilities.refreshed", component="gui_engine", data={"index_status": self.session.index_status}, @@ -2863,8 +3128,9 @@ def save_behavior_settings( path, previous_content.decode("utf-8") ) # Revalidate the old indexes after a failed build. - self.session.refresh_sources( - open_project(recovery_root) + self._refresh_source_indexes( + open_project(recovery_root), + "capabilities_recovery", ) except Exception as failure: recovery_error = failure @@ -2881,7 +3147,7 @@ def save_behavior_settings( "to revalidate its saved configuration." ), ) - self.active_trace.exception( + self.project_trace.exception( "gui.project_behavior.save.failed", error, component="gui_engine", ) @@ -2897,6 +3163,55 @@ def save_behavior_settings( request_id=request_id, ) + def plugin_management(self, request: object) -> None: + """Handle application-level plugin requests without a project. + + Parameters + ---------- + request: object + Correlated plugin management request from the local interface. + + """ + + from kilin.gui._plugin_management import plugin_command + + self._send("plugins", **plugin_command(request)) + + def versions(self, request_id: object) -> None: + """Send a correlated version report without opening a workspace. + + Parameters + ---------- + request_id: object + Nonempty string identifying the frontend request. + + Notes + ----- + Read the active project's captured creation provenance separately + from the application inventory. No model or tool is run. + + """ + + import kilin + + reply: dict[str, object] = { + "request_id": request_id if isinstance(request_id, str) else "", + "project": "", "creation_provenance": None, + } + try: + if not isinstance(request_id, str) or not request_id: + raise ValueError("Invalid version report request ID.") + if self.session is not None: + project = self.session.project + reply["project"] = str(project.root) + reply["creation_provenance"] = asdict( + project.creation_provenance + ) + reply["inventory"] = kilin.version_info() + except Exception as error: + reply["error"] = str(error) + self._send("versions", **reply) + def tool_settings(self) -> None: """Send the tools the open project can use, with their settings. @@ -2948,7 +3263,7 @@ def save_tool_settings(self, name: str, settings: object) -> None: root = self.session.project.root try: tools = save_tool_settings( - root, name, settings, trace=self.active_trace + root, name, settings, trace=self.project_trace ) except ValueError as error: self._send( @@ -2966,6 +3281,94 @@ def save_tool_settings(self, name: str, settings: object) -> None: f"Could not save the tool settings: {error}", ) + def source_organization(self, request: object) -> None: + """Inspect, preview, apply or reconcile accepted source metadata. + + Parameters + ---------- + request: object + Project-scoped JSON request with operation and request ID. + The adapter holds one validated preview until application. + + """ + self._source_organization_commands.execute(self, request) + + def _record_source_organization( + self, project: QAProject, reason: str, payload: dict, + ) -> None: + """Record an observation without changing physical trace fields. + + Parameters + ---------- + project: QAProject + Workspace that produced the observation. + reason: str + Opening or lifecycle operation responsible for the outcome. + payload: dict + Semantic outcome, augmented with any recording failure. + + """ + inspection = payload.get("inspection") + identity = ({key: inspection[key] for key in ( + "revision", "sha256", "source_organization", + "source_root", "binding_matches", "selected", "pending", + "pending_roles", "retained_versions", + )} if inspection is not None else {}) + details = {key: value for key, value in payload.items() + if key != "inspection"} + error = record( + self.project_trace, "gui.source_organization.observed", + {"project": str(project.root), "reason": reason, + **identity, **details}, + status="failed" if payload.get("error") else "completed", + ) + if error and not payload.get("trace_error"): + payload["trace_error"] = error + + def _publish_source_organization( + self, project: QAProject, operation: str, + outcome: SourceLifecycleResult, + ) -> None: + """Publish one semantic outcome independently of indexing. + + Parameters + ---------- + project: QAProject + Workspace that produced the outcome. + operation: str + Lifecycle operation responsible for reconciliation. + outcome: SourceLifecycleResult + Core result, including independent semantic and trace errors. + + """ + self._source_organization_commands.clear() + payload = lifecycle_payload(outcome) + self._record_source_organization(project, operation, payload) + self._send("source_organization_lifecycle", project=str(project.root), + operation=operation, **payload) + + def _organization_observer( + self, project: QAProject, operation: str, + ) -> Callable[[SourceLifecycleResult], None]: + """Bind a lifecycle observer to the original project and command. + + Parameters + ---------- + project: QAProject + Workspace undergoing physical changes. + operation: str + Name of the triggering operation. + + Returns + ------- + Callable[[SourceLifecycleResult], None] + Observer called after semantic reconciliation. + + """ + return lambda result: self._publish_source_organization( + project, operation, result, + ) + def check_sources(self, sources: list[str]) -> None: """Tell the user what adding these sources would copy. @@ -2987,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) @@ -2995,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 = [ @@ -3033,7 +3441,8 @@ def check_sources(self, sources: list[str]) -> None: ) def add_project_sources( - self, sources: list[str], decisions: object = None + self, sources: list[str], decisions: object = None, + selected_files: dict[str, list[str]] | None = None, ) -> None: """Add confirmed sources and restore the active chat. @@ -3045,6 +3454,9 @@ def add_project_sources( For sources already in the project, sync actions keyed by the ``sources/`` paths reported by ``check_sources``. Defaults to ``None``: copies already in the project stay as they are. + selected_files: dict of str to list of str | None, optional + Exact file selections for new sources, as accepted by the core. + Defaults to None, using the ordinary scan selection. Notes ----- @@ -3058,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) @@ -3066,12 +3484,15 @@ 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.active_trace.emit( + self.project_trace.emit( "gui.sources.add.requested", component="gui_engine", - data={"sources": sources}, + data={ + "sources": sources, "decisions": decisions, + "selected_files": selected_files, + }, ) self._send( "status", message="Adding sources and updating the index…" @@ -3087,27 +3508,43 @@ 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"]) if item["state"] != "existing" ] + if selected_files is not None and not new: + if selected_files: + raise ValueError("Selections require new sources.") if new: - add_project_sources(root, new, trace=self.active_trace) + options = { + "trace": self.project_trace, + "on_organization": self._organization_observer( + project, "add"), + } + if selected_files is not None: + options["selected_files"] = selected_files + add_project_sources(root, new, **options) if decisions: - done = sync_project_sources( - open_project(root), decisions=decisions - ) - self.active_trace.emit( - "gui.sources.synced", component="gui_engine", data=done - ) + options = { + "decisions": decisions, + "on_organization": self._organization_observer( + project, "sync"), + } + if self.project_trace.enabled: + options["trace"] = self.project_trace + sync_project_sources(open_project(root), **options) if new or decisions: self._refresh_sources(open_project(root)) else: self._announce_project( self.session.project, self.active_conversation ) + self.project_trace.emit( + "gui.sources.add.completed", component="gui_engine", + data={"new_sources": new, "decisions": decisions}, + ) except Exception as error: # A failed copy may have written some files: index what is there, # so an old in-memory index is never used. @@ -3151,9 +3588,14 @@ 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.active_trace.emit( + self.project_trace.emit( "gui.sources.remove.requested", component="gui_engine", data={"paths": paths}, @@ -3161,7 +3603,15 @@ def remove_project_sources(self, paths: list[str]) -> None: self._send( "status", message="Removing sources and updating the index…" ) - remove_workspace_sources(self.session.project, paths) + removed = remove_workspace_sources( + project, paths, trace=self.project_trace, + on_organization=self._organization_observer( + project, "remove"), + ) + self.project_trace.emit( + "gui.sources.remove.completed", component="gui_engine", + data={"paths": removed}, + ) self._refresh_sources(open_project(root)) except Exception as error: # Refresh after a partial deletion to match the files on disk. @@ -3213,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( @@ -3221,15 +3677,18 @@ 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…" ) try: - done = sync_project_sources(project, decisions=decisions) - self.active_trace.emit( - "gui.sources.synced", component="gui_engine", data=done - ) + options = { + "decisions": decisions, + "on_organization": self._organization_observer( + project, "sync"), + } + if self.project_trace.enabled: + options["trace"] = self.project_trace + sync_project_sources(project, **options) finally: self._refresh_sources(open_project(project.root)) except Exception as error: @@ -3247,9 +3706,9 @@ def edit_folder( Parameters ---------- folder: str - User-editable project folder. + Workspace-relative editable directory. operation: str - One of ``add``, ``replace`` or ``remove``. + One of ``add``, ``mkdir``, ``replace`` or ``remove``. **arguments: object File paths and optional replacement policy from the GUI. @@ -3266,6 +3725,11 @@ def edit_folder( _path_list(arguments.get("paths")), replace=arguments.get("replace") is True, ) + elif operation == "mkdir": + name = arguments.get("name") + if not isinstance(name, str): + raise ValueError("Choose a new directory name.") + changed = [create_project_folder(project, folder, name)] elif operation == "replace": path = arguments.get("path") source = arguments.get("source") @@ -3285,7 +3749,7 @@ def edit_folder( changed = remove_project_files(project, values) else: raise ValueError(f"Unknown operation: {operation}.") - self.active_trace.emit( + self.project_trace.emit( f"gui.folder.{operation}", component="gui_engine", data={"folder": folder, "paths": changed}, @@ -3304,6 +3768,26 @@ def edit_folder( f"Could not change {folder}/: {error}", ) + def _refresh_source_indexes( + self, project: QAProject, reason: str, + ) -> None: + """Publish reconciliation before physical index preparation. + + Parameters + ---------- + project: QAProject + Reopened project after changes to sources or settings. + reason: str + 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( + project, reason), + ) + def _refresh_sources(self, project: QAProject) -> None: """Re-index changed sources, keeping the models and the chat. @@ -3317,8 +3801,8 @@ def _refresh_sources(self, project: QAProject) -> None: """ - self.session.refresh_sources(project) - self.active_trace.emit( + self._refresh_source_indexes(project, "refresh") + self.project_trace.emit( "gui.sources.refreshed", component="gui_engine", data={ @@ -3342,14 +3826,20 @@ def _reopen_project_conversation( """ - self._close_project_trace() + _source_records(project.root, allow_mirror=True) + self._close_traces() store = ConversationStore(project.root) store.ensure() conversation = store.select(conversation_id) self.conversation_store = store self.active_conversation = conversation - self._start_project_trace(project.root, conversation) - self._activate_project(project, conversation) + self._start_conversation_trace(project.root, conversation) + with self.project_trace.span( + "gui.project.open", component="gui_engine", + data={"reason": "internal_reopen", "conversation_id": + conversation.conversation_id}, + ): + self._activate_project(project, conversation) def _name_active_conversation( self, question: str, answer: str = "" @@ -3429,6 +3919,10 @@ def _name_active_conversation( ), ) self.active_conversation = renamed + self.active_trace.emit( + "conversation.title.generated", component="gui_engine", + data=asdict(renamed), + ) self._send_conversations("conversations") def ask( @@ -3473,91 +3967,163 @@ def ask( if self.session is None: raise RuntimeError("Open a project before asking a question.") generation_settings = dict(generation_settings or {}) + full_form = "_title_question" in generation_settings title_question = str( generation_settings.pop("_title_question", question) ) - # Answer settings belong to the project; every chat uses them. - self._save_answer_settings(generation_settings) - backend = self.session.backend - levels = read_effort_levels(self.session.project.root, backend) - indexes = _effort_indexes(effort) - is_mlx = self.session.chat_session.backend == BACKEND_MLX - # Name a new chat after its first answer, from question and answer. - name_after_answer = ( - indexes is not None - and not self.session.turns - and self.conversation_store is not None - and self.active_conversation is not None - and self.active_conversation.name.startswith("Conversation ") - ) - if indexes is not None: - model_index, depth_index = indexes - depth = read_search_depth(self.session.project.root) - retrieval_count = depth[depth_index] - model_id = str(levels[model_index]["model"]) - # RAGSession switches chat models in place only on MLX. - if is_mlx: - if model_id != self.session.chat_session.model_id: - # Loading can take seconds; show it as its own stage. - self._send( - "answer_phase", - phase=ENGINE_PHASE_LOADING_MODEL, - model_id=model_id, - ) - self.session.use_chat_model(model_id) - self._send("status", message="Finding evidence and answering…") - options: dict[str, object] = {} - if retrieval_count is not None: - options["retrieval_count"] = retrieval_count - if generation_settings: - options["generation_settings"] = generation_settings - # The RAG core resolves project-type and intent guidance. - stream = _AnswerStream(self._send) - options["token_callback"] = stream.add - options["phase_callback"] = lambda phase, details: self._send( - "answer_phase", - phase=phase, - **details, - ) - options["activity_callback"] = lambda event: self._send( - "answer_activity", **event - ) - if self.read_command is not None: - options["confirm_callback"] = self._confirm_plan - options["choice_callback"] = self._choose_option - # Reports such as research briefings also get a one-page PDF. - options["pdf_writer"] = write_report_pdf - options["stop_requested"] = self._answer_stop.is_set - self._answer_stop.clear() - self._answering = True - try: - with self._live_usage(): - self.session.ask(question, **options) - finally: - self._answering = False - self._answer_stop.clear() - stream.flush() - if ( - self.conversation_store is not None - and self.active_conversation is not None + profile = self.session.project.profile + requested = { + "question": question, + "title_question": title_question, + "retrieval_count": retrieval_count, + "generation_settings": generation_settings, + "profile_generation_settings": { + key: getattr(profile, key) + for key in ("temperature", "thinking", "max_new_tokens") + }, + "generation_provenance": ( + "profile_difference" if full_form else "explicit_request" + ), + "explicit_generation_settings": { + key: value for key, value in generation_settings.items() + if not full_form or value != getattr(profile, key, None) + }, + "effort": effort, + "conversation_id": ( + self.active_conversation.conversation_id + if self.active_conversation is not None else None + ), + } + if self.active_trace.enabled: + try: + snapshot = read_source_manifest(self.session.project) + requested.update({ + "source_organization_revision": + snapshot.manifest.revision, + "source_organization_sha256": snapshot.sha256, + }) + except (OSError, ValueError) as error: + requested["source_organization_error"] = str(error) + with self.active_trace.span( + "gui.question.request", component="gui_engine", + data=requested, ): - self.active_conversation = self.conversation_store.touch( - self.active_conversation.conversation_id, - ownership=self._store_ownership( - self.active_conversation.conversation_id - ), - state_writer=self._store_state_writer( - self.active_conversation.conversation_id - ), + # Answer settings belong to the project; every chat uses them. + self._save_answer_settings(generation_settings) + backend = self.session.backend + levels = read_effort_levels(self.session.project.root, backend) + indexes = _effort_indexes(effort) + is_mlx = self.session.chat_session.backend == BACKEND_MLX + # Name a new chat from its first question and answer. + name_after_answer = ( + indexes is not None + and not self.session.turns + and self.conversation_store is not None + and self.active_conversation is not None + and self.active_conversation.name.startswith( + "Conversation " + ) + ) + if indexes is not None: + model_index, depth_index = indexes + depth = read_search_depth(self.session.project.root) + retrieval_count = depth[depth_index] + model_id = str(levels[model_index]["model"]) + # RAGSession switches chat models in place only on MLX. + if is_mlx: + if model_id != self.session.chat_session.model_id: + # Loading can take seconds; show its own stage. + self._send( + "answer_phase", + phase=ENGINE_PHASE_LOADING_MODEL, + model_id=model_id, + ) + self.session.use_chat_model(model_id) + if self.active_trace.enabled: + self.active_trace.emit( + "gui.question.settings.resolved", + component="gui_engine", + data={ + "effort_indexes": ( + list(indexes) if indexes else None + ), + "selected_model": model_id if indexes else None, + "model_selection_applied": bool( + indexes and is_mlx + ), + "retrieval_count": ( + retrieval_count if retrieval_count is not None + else profile.retrieval_count + ), + "chat_model": self.session.chat_session.model_id, + }, + ) + self._send("status", message="Finding evidence and answering…") + options: dict[str, object] = {} + if retrieval_count is not None: + options["retrieval_count"] = retrieval_count + if generation_settings: + options["generation_settings"] = generation_settings + # The RAG core resolves project-type and intent guidance. + stream = _AnswerStream(self._send) + options["token_callback"] = stream.add + options["phase_callback"] = lambda phase, details: self._send( + "answer_phase", + phase=phase, + **details, + ) + options["activity_callback"] = lambda event: self._send( + "answer_activity", **event + ) + if self.read_command is not None: + options["confirm_callback"] = self._confirm_plan + options["choice_callback"] = self._choose_option + # Reports such as research briefings also get a one-page PDF. + options["pdf_writer"] = write_report_pdf + options["stop_requested"] = self._answer_stop.is_set + self._answer_stop.clear() + self._answering = True + try: + with self._live_usage(): + self.session.ask(question, **options) + finally: + self._answering = False + self._answer_stop.clear() + stream.flush() + if ( + self.conversation_store is not None + and self.active_conversation is not None + ): + self.active_conversation = self.conversation_store.touch( + self.active_conversation.conversation_id, + ownership=self._store_ownership( + self.active_conversation.conversation_id + ), + state_writer=self._store_state_writer( + self.active_conversation.conversation_id + ), + ) + if self.active_trace.enabled: + self.active_trace.emit( + "gui.question.saved", component="gui_engine", + data={ + "conversation_turn_uuid": ( + self.session.turns[-1].conversation_turn_uuid + ), + "turn_count": len(self.session.turns), + "checkpoint_id": getattr( + self.session, "_checkpoint_id", None + ), + }, + ) + # An answer can add files (a tool's report in outputs/, the + # conversation log), so the workspace tree is refreshed too. + self._send( + "answered", + turn=asdict(self.session.turns[-1]), + usage=self._usage_totals(), + workspace_files=list_project_files(self.session.project), ) - # An answer can add files (a tool's report in outputs/, the - # conversation log), so the workspace tree is refreshed too. - self._send( - "answered", - turn=asdict(self.session.turns[-1]), - usage=self._usage_totals(), - workspace_files=list_project_files(self.session.project), - ) except GenerationCancelled: # Stop: no turn is saved, and models and project stay loaded. self.active_trace.emit( @@ -3650,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 @@ -3660,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 = ( @@ -3668,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) @@ -3679,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: @@ -3724,6 +4300,10 @@ def _confirm_plan(self, plan: ToolPlan) -> PlanChoice: while True: command = self.read_command() if command is None: + self.active_trace.emit( + "gui.interaction.input.ended", component="gui_engine", + status="failed", data={"kind": "plan"}, + ) return PLAN_CHOICE_CANCEL if command.get("action") == "cancel_answer": raise GenerationCancelled("Stopped by the user.") @@ -3731,6 +4311,10 @@ def _confirm_plan(self, plan: ToolPlan) -> PlanChoice: choice = command.get("choice") if choice in PLAN_CHOICE_CHOICES: return choice + self.active_trace.emit( + "gui.interaction.input.invalid", component="gui_engine", + status="failed", data={"kind": "plan", "choice": choice}, + ) return PLAN_CHOICE_CANCEL self._send( "error", @@ -3768,6 +4352,10 @@ def _choose_option( while True: command = self.read_command() if command is None: + self.active_trace.emit( + "gui.interaction.input.ended", component="gui_engine", + status="failed", data={"kind": "option"}, + ) return None if command.get("action") == "cancel_answer": raise GenerationCancelled("Stopped by the user.") @@ -3776,7 +4364,14 @@ def _choose_option( number = choice.removeprefix("option:") if choice.startswith("option:") and number.isdigit(): index = int(number) - return index if index < len(options) else None + if index < len(options): + return index + if choice != PLAN_CHOICE_CANCEL: + self.active_trace.emit( + "gui.interaction.input.invalid", + component="gui_engine", status="failed", + data={"kind": "option", "choice": choice}, + ) return None self._send( "error", @@ -3843,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. @@ -3904,24 +4504,49 @@ def create_conversation( or self.active_conversation is None ): raise RuntimeError("Open a project first.") - unused = None if branch else self._unused_empty_conversation() - if unused is not None: - self.conversation_store.select(unused.conversation_id) - self._switch_with_store_rollback(unused) - return - parent_id = ( - self.active_conversation.conversation_id if branch else None - ) - conversation = self.conversation_store.create( - branch_from=parent_id, - turn_count=turn_count, - ownership=( - self._store_ownership(parent_id) - if parent_id is not None - else None - ), - ) - self._switch_with_store_rollback(conversation) + with self.project_trace.span( + "gui.conversation.create", component="gui_engine", + data={ + "previous_conversation_id": ( + self.active_conversation.conversation_id + ), + "branch": branch, "turn_count": turn_count, + }, + ): + unused = None if branch else self._unused_empty_conversation() + if unused is not None: + self.conversation_store.select(unused.conversation_id) + self.project_trace.emit( + "gui.conversation.create.result", + component="gui_engine", + data={ + **self._conversation_trace_record(unused), + "reused": True, + }, + ) + self._switch_with_store_rollback(unused) + return + parent_id = ( + self.active_conversation.conversation_id + if branch else None + ) + conversation = self.conversation_store.create( + branch_from=parent_id, + turn_count=turn_count, + ownership=( + self._store_ownership(parent_id) + if parent_id is not None + else None + ), + ) + self.project_trace.emit( + "gui.conversation.create.result", component="gui_engine", + data={ + **self._conversation_trace_record(conversation), + "reused": False, + }, + ) + self._switch_with_store_rollback(conversation) except Exception as error: self._report_error( "gui.conversation_create.failed", @@ -3929,6 +4554,31 @@ def create_conversation( str(error), ) + def _conversation_trace_record( + self, conversation: ConversationInfo + ) -> dict[str, object]: + """Describe a registered record without reading its saved turns. + + Parameters + ---------- + conversation: ConversationInfo + Registered conversation, including branch origin metadata. + + Returns + ------- + dict[str, object] + Metadata and its workspace-relative state path. + + """ + + path = self.conversation_store.state_path(conversation) + return { + **asdict(conversation), + "path": path.relative_to( + self.conversation_store.project_directory + ).as_posix(), + } + def _unused_empty_conversation(self) -> ConversationInfo | None: """Find an empty conversation other than the active one. @@ -3972,14 +4622,23 @@ def select_conversation(self, conversation_id: str) -> None: try: if self.conversation_store is None: raise RuntimeError("Open a project first.") - conversation = self.conversation_store.select(conversation_id) - if ( - self.active_conversation is not None - and conversation.conversation_id - == self.active_conversation.conversation_id + with self.project_trace.span( + "gui.conversation.select", component="gui_engine", + data={"conversation_id": conversation_id}, ): - return - self._switch_with_store_rollback(conversation) + conversation = self.conversation_store.select(conversation_id) + if ( + self.active_conversation is not None + and conversation.conversation_id + == self.active_conversation.conversation_id + ): + self.project_trace.emit( + "gui.conversation.select.unchanged", + component="gui_engine", + data={"conversation_id": conversation_id}, + ) + return + self._switch_with_store_rollback(conversation) except Exception as error: self._report_error( "gui.conversation_select.failed", @@ -4010,24 +4669,27 @@ def rename_conversation(self, conversation_id: str, name: str) -> None: try: if self.conversation_store is None: raise RuntimeError("Open a project first.") - renamed = self.conversation_store.rename( - conversation_id, - name, - ownership=self._store_ownership(conversation_id), - state_writer=self._store_state_writer(conversation_id), - ) - if ( - self.active_conversation is not None - and renamed.conversation_id - == self.active_conversation.conversation_id + with self.project_trace.span( + "gui.conversation.rename", component="gui_engine", + data={"conversation_id": conversation_id, "name": name}, ): - self.active_conversation = renamed - self.active_trace.emit( - "conversation.renamed", - component="gui_engine", - data=asdict(renamed), - ) - self._send_conversations("conversations") + renamed = self.conversation_store.rename( + conversation_id, + name, + ownership=self._store_ownership(conversation_id), + state_writer=self._store_state_writer(conversation_id), + ) + if ( + self.active_conversation is not None + and renamed.conversation_id + == self.active_conversation.conversation_id + ): + self.active_conversation = renamed + self.project_trace.emit( + "gui.conversation.renamed", component="gui_engine", + data=self._conversation_trace_record(renamed), + ) + self._send_conversations("conversations") except Exception as error: self._report_error( "gui.conversation_rename.failed", @@ -4057,32 +4719,52 @@ def delete_conversation(self, conversation_id: str) -> None: or self.active_conversation is None ): raise RuntimeError("Open a project first.") - deleting_active = ( - conversation_id == self.active_conversation.conversation_id - ) - self._send( - "conversation_delete_started", - conversation_id=conversation_id, - ) - replacement, archived_path = self.conversation_store.archive( - conversation_id, - ownership=self._store_ownership(conversation_id), - ) - if deleting_active: - self._detach_project_trace() - self._switch_conversation( - replacement, close_current_trace=False + with self.project_trace.span( + "gui.conversation.delete", component="gui_engine", + data={"conversation_id": conversation_id}, + ): + deleting_active = ( + conversation_id == self.active_conversation.conversation_id ) - else: - self._send_conversations("conversations") - self.active_trace.emit( - "conversation.deleted", - component="gui_engine", - data={ - "conversation_id": conversation_id, - "archived_path": str(archived_path), - }, - ) + self._send( + "conversation_delete_started", + conversation_id=conversation_id, + ) + if deleting_active and isinstance( + self.conversation_trace, TraceLogger + ): + self.conversation_trace.flush() + catalog_ids = { + item.conversation_id + for item in self.conversation_store.conversations() + } + replacement, archived_path = self.conversation_store.archive( + conversation_id, + ownership=self._store_ownership(conversation_id), + ) + self.project_trace.emit( + "gui.conversation.deleted", component="gui_engine", + data={ + "conversation_id": conversation_id, + "archived_path": archived_path.relative_to( + self.conversation_store.project_directory + ).as_posix(), + "replacement": self._conversation_trace_record( + replacement + ), + "replacement_created": ( + replacement.conversation_id not in catalog_ids + ), + "deleted_active": deleting_active, + }, + ) + if deleting_active: + self._detach_conversation_trace() + self._switch_conversation( + replacement, close_current_trace=False + ) + else: + self._send_conversations("conversations") except Exception as error: if self.conversation_store is not None: try: @@ -4101,6 +4783,13 @@ def rename_project(self, name: str) -> None: name: str Filename or project name to use. + Notes + ----- + The rename request is recorded before releasing the old trace leases. + Its matching completion is recorded only after successful activation + in the renamed directory. The two point events share an identity; + no span or file lease crosses the filesystem move. + """ source = destination = None @@ -4125,15 +4814,29 @@ def rename_project(self, name: str) -> None: if destination.exists(): raise ValueError(f"A folder named {clean!r} already exists.") conversation_id = self.active_conversation.conversation_id + rename = { + "rename_id": uuid4().hex, + "source_directory": str(source), + "destination_directory": str(destination), + "conversation_id": conversation_id, + } + self.project_trace.emit( + "gui.project.rename.requested", + component="gui_engine", data=rename, + ) self.close() source.rename(destination) moved = True project = open_project(destination) self._reopen_project_conversation(project, conversation_id) + self.project_trace.emit( + "gui.project.rename.completed", + component="gui_engine", data=rename, + ) except Exception as error: if source is not None and self.session is None: try: - self._close_project_trace() + self._close_traces() if moved: destination.rename(source) self._reopen_project_conversation( @@ -4201,11 +4904,19 @@ 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 path = root / PROFILE_FILE original = path.read_text(encoding="utf-8") + before = self._source_card_settings( + root, session.project.profile.type_id + ) self._send("status", message="Updating source cards…") try: write_source_card_policy(root, policy) @@ -4226,11 +4937,17 @@ def save_source_card_settings(self, request: object) -> None: f"Source-card recovery failed: {recovery!r}" ) raise + effective = self._source_card_settings( + root, session.project.profile.type_id + ) + self.project_trace.emit( + "gui.source_cards.settings.saved", component="gui_engine", + data={"requested": request, "before": before, + "effective": effective}, + ) self._send( "source_cards_applied", - source_cards=self._source_card_settings( - root, session.project.profile.type_id - ), + source_cards=effective, source_card_summary=self._card_summary(session), ) except Exception as error: @@ -4252,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( @@ -4293,19 +5015,24 @@ 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…") # Validation precedes the core's atomic profile replacement. project = configure_project( - root, settings, trace=self.active_trace + root, settings, trace=self.project_trace ) reopen_started = True self.close() @@ -4419,31 +5146,39 @@ def _switch_conversation( if self.session is None or self.conversation_store is None: raise RuntimeError("Open a project first.") - previous_trace = self.project_trace + previous_trace = self.conversation_trace + previous = self.active_conversation try: # Acquiring the target first leaves the active writer untouched # if the conversation is locked by another KíLín process. - self._start_project_trace( + self._start_conversation_trace( self.session.project.root, conversation ) turns = self.session.switch_conversation( self.conversation_store.state_path(conversation), - trace=self.project_trace, + trace=self.conversation_trace, ) except BaseException: - if self.project_trace is not previous_trace: - if isinstance(self.project_trace, TraceLogger): - self.project_trace.close(emit_event=False) - self.project_trace = previous_trace + if self.conversation_trace is not previous_trace: + if isinstance(self.conversation_trace, TraceLogger): + self.conversation_trace.close(emit_event=False) + self.conversation_trace = previous_trace raise - if close_current_trace and previous_trace is not self.project_trace: + if ( + close_current_trace + and previous_trace is not self.conversation_trace + ): previous_trace.close() self.active_conversation = conversation self._use_project_answer_settings() - self.active_trace.emit( - "conversation.selected", - component="gui_engine", - data=asdict(conversation), + self.project_trace.emit( + "gui.conversation.selected", component="gui_engine", + data={ + **self._conversation_trace_record(conversation), + "previous_conversation_id": ( + previous.conversation_id if previous is not None else None + ), + }, ) if not turns: # A new chat gets its own fresh suggested questions. @@ -4519,9 +5254,20 @@ def reset(self) -> None: try: if self.session is None or self.conversation_store is None: raise RuntimeError("Open a project first.") - conversation = self.conversation_store.create() - self._switch_with_store_rollback(conversation) - self._send("reset", archived=None) + with self.project_trace.span( + "gui.conversation.reset", component="gui_engine", + data={"previous_conversation_id": ( + self.active_conversation.conversation_id + if self.active_conversation is not None else None + )}, + ): + conversation = self.conversation_store.create() + self.project_trace.emit( + "gui.conversation.reset.result", component="gui_engine", + data=self._conversation_trace_record(conversation), + ) + self._switch_with_store_rollback(conversation) + self._send("reset", archived=None) except Exception as error: self._report_error( "gui.conversation_reset.failed", @@ -4540,10 +5286,18 @@ def close(self) -> None: """ + self._source_organization_commands.clear() if self.session is not None: self.session.close() self.session = None - self._close_project_trace() + self.project_trace.emit( + "gui.project.closed", component="gui_engine", + data={"conversation_id": ( + self.active_conversation.conversation_id + if self.active_conversation is not None else None + )}, + ) + self._close_traces() self.conversation_store = None self.active_conversation = None @@ -4977,6 +5731,43 @@ def _effort_levels_by_backend( } +def _creation_overrides( + defaults: dict[str, object], requested: dict[str, object] +) -> dict[str, object]: + """Return the sparse differences from displayed creation defaults. + + Parameters + ---------- + defaults: dict[str, object] + JSON-compatible settings sent to the new-project screen. + requested: dict[str, object] + Full settings snapshot supplied by the frontend. + + Returns + ------- + dict[str, object] + Changed or additional fields, preserving nested mapping structure. + Lists are atomic settings (for example the five effort levels). + + Notes + ----- + A value equal to the displayed default is inherited. An API caller + supplying an explicit mapping does not use this comparison. + + """ + + changes = {} + for key, value in requested.items(): + previous = defaults.get(key) + if isinstance(value, dict) and isinstance(previous, dict): + nested = _creation_overrides(previous, value) + if nested: + changes[key] = nested + elif key not in defaults or value != previous: + changes[key] = value + return changes + + def _effort_indexes(effort: object) -> tuple[int, int] | None: """Read the effort level and search-depth step chosen for one answer. @@ -5088,6 +5879,17 @@ def emit(data: dict[str, object]) -> None: protocol_output.write(json.dumps(data, default=str) + "\n") protocol_output.flush() + from kilin.plugins._lifecycle import _ensure_runtime + + # A standalone protocol process is also a runtime, even before its + # first command. A desktop parent already holds its own independent + # lease so replacing this child cannot change the active installation. + try: + _ensure_runtime() + except (OSError, RuntimeError, ValueError) as error: + emit({"event": "error", "message": str(error)}) + return + sandbox = default_workspace_directory() # A reader thread passes stdin lines on through this queue (None ends # input), so Stop reaches a busy answer at once. One iterator over the @@ -5196,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": @@ -5254,7 +6050,8 @@ def read_input() -> None: engine.check_sources(command["sources"]) elif action == "add_project_sources": engine.add_project_sources( - command["sources"], command.get("decisions") + command["sources"], command.get("decisions"), + command.get("selected_files"), ) elif action == "remove_project_sources": engine.remove_project_sources(command["paths"]) @@ -5288,6 +6085,8 @@ def read_input() -> None: ) elif action == "settings_info": engine.settings_info() + elif action == "source_organization": + engine.source_organization(command.get("request")) elif action == "project_behavior": engine.behavior_settings() elif action == "save_project_behavior": @@ -5317,6 +6116,10 @@ def read_input() -> None: engine.memory_status(command.get("project")) elif action == "sync_memory_index": engine.sync_memory_index(command.get("project")) + elif action == "plugin_management": + engine.plugin_management(command.get("request")) + elif action == "versions": + engine.versions(command.get("request_id")) elif action == "tool_settings": engine.tool_settings() elif action == "save_tool_settings": 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/model_settings.py b/kilin/gui/model_settings.py index 4f470d65..0b61aaa6 100644 --- a/kilin/gui/model_settings.py +++ b/kilin/gui/model_settings.py @@ -25,14 +25,14 @@ mlx = Qwen/Qwen3-4B-MLX-4bit torch = Qwen/Qwen3-4B -``save_project_settings`` writes them when a project is created or first -opened, from the defaults, or from the ``effort_levels.json`` and -``model_choices.json`` files earlier versions kept, which it then removes. +``save_project_settings`` initializes genuinely missing settings when a +project is created or first activated in the GUI, from the effective +application preferences. Historical sidecars are ignored and retained. GUI effort and search defaults live in ``kilin.gui.preferences``. Router model validation, persistence, and packaged defaults live in KíLín core. The GUI supplies its application preference only when a project has no -saved or legacy router choice. +saved router choice. Key Features ------------ @@ -42,9 +42,10 @@ Read and update effort levels and search-depth steps in the project's ``profile.ini``. Router read/write functions are imported from core. -- **Legacy migration** +- **Current initialization** - Import compatible settings from earlier project files when they exist. + Fill absent settings from current defaults without replacing saved + values or reading historical sidecars. Module Structure ---------------- @@ -63,7 +64,7 @@ - ``save_project_settings`` - Write missing settings or migrate compatible legacy values. + Initialize missing settings without overriding saved values. Examples -------- @@ -75,7 +76,6 @@ from configparser import ConfigParser from io import StringIO -import json from pathlib import Path from kilin.atomic_writes import atomic_write_text @@ -87,7 +87,6 @@ default_router_model, default_search_depth, validate_effort_levels, - validate_model_id, validate_search_depth, ) from kilin.model_settings import read_router_model, write_router_model @@ -117,11 +116,6 @@ _SEARCH_SECTION = "search" _ROUTER_SECTION = "router" _SEPARATOR = " | " -# Files of earlier versions, migrated into profile.ini and removed. -_LEGACY_EFFORT_FILE = "effort_levels.json" -_LEGACY_CHOICES_FILE = "model_choices.json" -# Per-level reference counts of earlier versions, before search depth. -_LEGACY_RETRIEVAL = (5, 20, 20, 50, 50) def read_effort_levels( @@ -140,8 +134,8 @@ def read_effort_levels( ------- list[dict[str, object]] Five ``{"name", "model"}`` levels from ``profile.ini``; for a - project that has not saved them yet, from an earlier version's - files, otherwise the defaults. + project that has not saved them yet, from current application + preferences. """ @@ -157,22 +151,7 @@ def read_effort_levels( ).partition(_SEPARATOR.strip()) levels.append({"name": name.strip(), "model": model.strip()}) return validate_effort_levels(levels) - legacy = _legacy(root) - if backend in legacy: - return validate_effort_levels( - [ - {"name": level["name"], "model": level["model"]} - for level in legacy[backend] - ] - ) - levels = default_effort_levels(backend) - choices = _read_json(root / _LEGACY_CHOICES_FILE) - replacements = choices if isinstance(choices, dict) else {} - for level in levels: - replacement = replacements.get(level["model"]) - if isinstance(replacement, str) and replacement.strip(): - level["model"] = validate_model_id(replacement) - return levels + return default_effort_levels(backend) def write_effort_levels( @@ -197,8 +176,6 @@ def write_effort_levels( """ levels = validate_effort_levels(levels) - if any(_SEPARATOR.strip() in str(level["name"]) for level in levels): - raise ValueError("Effort level names cannot contain '|'.") profile = _read(root) section = _EFFORT_SECTION.format(backend=backend) if not profile.has_section(section): @@ -224,7 +201,7 @@ def read_search_depth(root: Path | None) -> list[int]: ------- list[int] Five steps from ``profile.ini``; for a project that has not saved - them yet, from an earlier version's files, otherwise the defaults. + them yet, from current application preferences. Raises ------ @@ -247,10 +224,7 @@ def read_search_depth(root: Path | None) -> list[int]: "Search depth steps must be whole numbers." ) from error return validate_search_depth(steps) - legacy = _legacy(root) - if "search_depth" in legacy: - return validate_search_depth(legacy["search_depth"]) - return _legacy_depth(legacy) or default_search_depth() + return default_search_depth() def write_search_depth(root: Path, steps: list[int]) -> None: @@ -284,35 +258,49 @@ def save_project_settings(root: Path) -> bool: Returns ------- bool - Whether anything was written. Saved values are never changed; - missing ones come from an earlier version's ``effort_levels.json`` - and ``model_choices.json`` (then removed) or the defaults, so the - project no longer follows later changes to the defaults. + Whether missing settings were written. Saved values are never + changed; missing ones come from current application preferences. + A core-created project may legitimately lack GUI settings. + + Raises + ------ + ValueError + If a current saved setting or a required default is invalid. + + Notes + ----- + Validate current values and the defaults needed for initialization + before writing any missing settings. Historical sidecars are neither + read nor removed. A fully initialized profile is not rewritten. """ profile = _read(root) - changed = False + pending_levels = {} + pending_routers = {} + # Read current settings first, so invalid settings cannot trigger a + # partial initialization of other missing settings. for backend in (BACKEND_MLX, BACKEND_TORCH): + levels = read_effort_levels(root, backend) if not profile.has_section(_EFFORT_SECTION.format(backend=backend)): - levels = read_effort_levels(root, backend) - write_effort_levels(root, backend, levels) - changed = True - if not profile.has_option(_ROUTER_SECTION, backend): - initial_router = read_router_model( - root, backend, - default_model=default_router_model(backend), + pending_levels[backend] = levels + if profile.has_option(_ROUTER_SECTION, backend): + read_router_model(root, backend) + else: + pending_routers[backend] = read_router_model( + root, backend, default_model=default_router_model(backend), ) - write_router_model(root, backend, initial_router) - changed = True - if not profile.has_option(_SEARCH_SECTION, "depth"): - write_search_depth(root, read_search_depth(root)) - changed = True - for name in (_LEGACY_EFFORT_FILE, _LEGACY_CHOICES_FILE): - if (root / name).exists(): - (root / name).unlink() - changed = True - return changed + depth = read_search_depth(root) + pending_depth = not profile.has_option(_SEARCH_SECTION, "depth") + # Preserve the profile section order used during initialization. + for backend in (BACKEND_MLX, BACKEND_TORCH): + if backend in pending_levels: + write_effort_levels(root, backend, pending_levels[backend]) + if backend in pending_routers: + write_router_model(root, backend, pending_routers[backend]) + if pending_depth: + write_search_depth(root, depth) + return bool(pending_levels or pending_routers or pending_depth) def _read(root: Path) -> ConfigParser: @@ -352,79 +340,3 @@ def _write(root: Path, profile: ConfigParser) -> None: stream = StringIO() profile.write(stream) atomic_write_text(path, stream.getvalue()) - - -def _read_json(path: Path) -> object: - """Read a JSON file, returning None if the file is absent. - - Parameters - ---------- - path: Path - Optional JSON file to parse. - - Returns - ------- - object - Parsed JSON object, or None when the file does not exist. - - Raises - ------ - json.JSONDecodeError - If the file does not contain valid JSON. - - """ - - if not path.is_file(): - return None - return json.loads(path.read_text(encoding="utf-8")) - - -def _legacy(root: Path) -> dict: - """The ``effort_levels.json`` an earlier version kept, if any. - - Parameters - ---------- - root: Path - Project or workspace root directory. - - Returns - ------- - dict - Earlier-version effort settings, or an empty mapping. - - """ - - saved = _read_json(root / _LEGACY_EFFORT_FILE) - return saved if isinstance(saved, dict) else {} - - -def _legacy_depth(saved: dict) -> list[int] | None: - """Customized per-level counts saved by even earlier versions. - - Parameters - ---------- - saved: dict - Settings loaded from an earlier profile format. - - Returns - ------- - list[int] | None - Earlier per-level retrieval counts, or None when unavailable. - - """ - - for key, levels in saved.items(): - if key in ("router", "search_depth") or not isinstance(levels, list): - continue - counts = [ - level.get("retrieval") for level in levels - if isinstance(level, dict) - ] - if ( - len(counts) == LEVEL_COUNT - and all(type(c) is int and 1 <= c <= MAX_SEARCH_DEPTH - for c in counts) - and tuple(counts) != _LEGACY_RETRIEVAL - ): - return counts - return None diff --git a/kilin/gui/preferences.py b/kilin/gui/preferences.py index 8029eef8..8cdbc1f4 100644 --- a/kilin/gui/preferences.py +++ b/kilin/gui/preferences.py @@ -128,7 +128,7 @@ def validate_effort_levels(value: object) -> list[dict[str, object]]: - """Check five levels of name and model ID. + """Check five levels, each containing only a name and model ID. Parameters ---------- @@ -138,14 +138,14 @@ def validate_effort_levels(value: object) -> list[dict[str, object]]: Returns ------- list[dict[str, object]] - Levels with names collapsed to single spaces. A ``retrieval`` - count saved by earlier versions is ignored; see - ``kilin.gui.model_settings.read_search_depth``. + Levels with names collapsed to single spaces. Each record has + exactly ``name`` and ``model``; search depth is independent. Raises ------ ValueError - If there are not five levels or a field is invalid. + If there are not five levels, a record has missing or extra fields, + or a field is invalid. """ @@ -153,19 +153,23 @@ def validate_effort_levels(value: object) -> list[dict[str, object]]: raise ValueError(f"Expected {LEVEL_COUNT} effort levels.") levels = [] for item in value: - if not isinstance(item, dict): - raise ValueError("Invalid effort level.") - name = item.get("name") + if not isinstance(item, dict) or set(item) != {"name", "model"}: + raise ValueError( + "Each effort level must contain only 'name' and 'model'." + ) + name = item["name"] if not isinstance(name, str) or not name.strip(): raise ValueError("Give every effort level a name.") name = " ".join(name.split()) + if "|" in name: + raise ValueError("Effort level names cannot contain '|'.") if len(name) > MAX_LEVEL_NAME: raise ValueError( f"Effort level names can have at most {MAX_LEVEL_NAME} " "characters." ) levels.append( - {"name": name, "model": validate_model_id(item.get("model"))} + {"name": name, "model": validate_model_id(item["model"])} ) return levels @@ -375,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/app.js b/kilin/gui/web/app.js index b5275aee..d2a55037 100644 --- a/kilin/gui/web/app.js +++ b/kilin/gui/web/app.js @@ -236,7 +236,7 @@ function setQuestionDraft(text) { * @param types Project types sent by the engine. */ function renderProjectTypes(types) { - if (!Array.isArray(types) || !types.length) return; + if (!Array.isArray(types)) return; projectTypes = Object.fromEntries(types.map((item) => [item.type_id, item])); if (savedProjects.length) renderSavedProjects(savedProjects); if (openProjectPath) renderSidebarProjects(savedProjects, openProjectPath); @@ -249,7 +249,8 @@ function renderProjectTypes(types) { return option; })); // The first type in registry filename order is the initial default. - select.value = projectTypes[current] ? current : types[0].type_id; + select.value = Object.hasOwn(projectTypes, current) ? current : (types[0]?.type_id || ""); + select.disabled = !types.length; activeProjectTypeId = ready ? activeProjectTypeId : select.value; } @@ -359,6 +360,7 @@ function renderSavedProjects(projects) { // jump a scrolled list back to the top. const shown = JSON.stringify(projects.map((project) => [ project.project, project.name, projectTypes[project.type_id]?.label || project.type_id, + project.available, project.unavailable_reason, ])); if (host.dataset.shown === shown) { host.classList.toggle("hidden", !host.children.length); @@ -387,10 +389,14 @@ function renderSavedProjects(projects) { typeLabel.className = "saved-project-type"; // The type's own name, or its ID until the types have arrived. typeLabel.textContent = projectTypes[project.type_id]?.label || project.type_id; + const unavailable = project.available === false; + if (unavailable) typeLabel.textContent += " (unavailable)"; button.append(name, typeLabel); - button.title = `Open ${project.type_id} project from ${project.project}`; + button.title = unavailable ? project.unavailable_reason + : `Open ${project.type_id} project from ${project.project}`; button.addEventListener("click", () => { if (busy) return; + if (unavailable) return showError(project.unavailable_reason); setBusy(true, "Opening project…"); bridge.resumeProject(project.project); }); @@ -554,14 +560,17 @@ function renderSidebarProjects(projects, current) { const type = document.createElement("span"); type.className = "project-item-type"; type.textContent = projectTypes[project.type_id]?.label || project.type_id || ""; + const unavailable = project.available === false; + if (unavailable) type.textContent += " (unavailable)"; button.append(name, type); - button.title = project.project; + button.title = unavailable ? project.unavailable_reason : project.project; const active = project.project === current; button.classList.toggle("active", active); if (active) button.setAttribute("aria-current", "true"); button.disabled = busy; const open = () => { if (busy || active) return; + if (unavailable) return showError(project.unavailable_reason); setBusy(true, `Opening ${project.name}…`); bridge.resumeProject(project.project); }; @@ -579,7 +588,7 @@ function renderSidebarProjects(projects, current) { event.preventDefault(); showWorkspaceMenu(event.clientX, event.clientY, active ? [["Rename", () => renameProjectInSidebar(button, project)], ["Settings", openModels]] - : [["Open", open]]); + : [[unavailable ? "Why unavailable?" : "Open", open]]); }); row.append(button); if (active) row.append(settings); @@ -709,7 +718,7 @@ function projectFileTypes() { * Request a backend metadata scan for the current source selection. */ function previewSources() { - if (bridge && selectedSources.length) { + if (bridge && profile && selectedSources.length) { setBusy(true, "Scanning selected sources…"); bridge.previewSources( JSON.stringify(selectedSources), JSON.stringify(projectFileTypes()), @@ -754,19 +763,22 @@ function showFolderCount(folder) { * @param selectable True gives each row a checkbox (the source preview). * False gives plain rows (the workspace tree), so clicking a file's * name does not also click its delete button. + * @param workspacePath Explicit workspace path, including empty folders. * @returns New details element containing the branch. */ -function branch(name, children, paths, selection, depth = 0, enabled = null, reasons = {}, selectable = true) { +function branch(name, children, paths, selection, depth = 0, enabled = null, reasons = {}, selectable = true, workspacePath = null) { const details = document.createElement("details"); details.className = "tree-folder"; - const key = `${name}|${paths[0] || ""}`; + const ownPath = workspacePath ?? (selectable ? null : name); + const key = `${name}|${paths[0] || ownPath || ""}`; if (depth < 1 || expandedFolders.has(key)) details.open = true; details.addEventListener("toggle", () => { if (!details.isConnected) return; details.open ? expandedFolders.add(key) : expandedFolders.delete(key); }); // Root-relative trees (the workspace) can recover the folder's own path. - if (paths[0]) details.dataset.path = paths[0].split("/").slice(0, depth + 1).join("/"); + if (ownPath !== null) details.dataset.path = ownPath; + else if (paths[0]) details.dataset.path = paths[0].split("/").slice(0, depth + 1).join("/"); // Direct contents only (not nested levels), shown by the workspace tree. details.dataset.folders = String(children.directories.size); details.dataset.files = String(children.files.length); @@ -790,7 +802,8 @@ function branch(name, children, paths, selection, depth = 0, enabled = null, rea const content = document.createElement("div"); content.className = "tree-children"; for (const [folder, node] of [...children.directories].sort()) { - content.append(branch(folder, node, allFiles(node), selection, depth + 1, enabled, reasons, selectable)); + const childPath = ownPath === null ? null : `${ownPath}/${folder}`; + content.append(branch(folder, node, allFiles(node), selection, depth + 1, enabled, reasons, selectable, childPath)); } for (const file of children.files.sort()) { // A label forwards clicks to its first control, so plain rows are divs. @@ -1864,7 +1877,7 @@ function behaviorValues(editor) { if (values.retrieval.mode !== "search" || values.retrieval.strategy !== "source_first") { for (const name of ["max_sources", "passages_per_source", - "max_passages", "evidence_tokens", "coverage"]) { + "max_passages", "evidence_tokens", "coverage", "grouped"]) { delete values.retrieval[name]; } } @@ -2182,6 +2195,10 @@ function createBehaviorEditor(scope, record, id = "") { valuesLimits[key] ?? defaults[key], "number", { min, max, ...restricted })); } + if (!record.tool) { + limits.append(behaviorField("retrieval.grouped", "Logical document groups", + valuesLimits.grouped ?? false, "checkbox")); + } limits.append(behaviorField("retrieval.coverage", "Coverage", valuesLimits.coverage ?? defaults.coverage, "select", { choices: [ ["bounded", "Bounded"], ["exhaustive", "Exhaustive"]], ...restricted })); @@ -2539,6 +2556,8 @@ function openModels() { } byId("models-panel").classList.remove("hidden"); byId("close-models").focus(); + globalThis.kilinPluginPanel?.opened(); + globalThis.kilinVersionPanel?.opened(); } /** @@ -2822,7 +2841,6 @@ function showSetupLock() { install.textContent = installingModels ? "Stop downloading" : "Install required models"; install.disabled = installingModels ? false : busy || !readinessEnvironmentReady || !readinessMissingCount; byId("use-installed").disabled = busy || !readinessEnvironmentReady; - byId("use-legacy-workspace").disabled = busy || ready; byId("open").disabled = busy || !bridge || !kilinReady; byId("close-models").disabled = false; byId("close-models").title = ""; @@ -3103,6 +3121,17 @@ function showModelFields() { * metadata. */ function showSettings(data) { + if (data.project_type_error) { + // There is no creation profile; keep saved workspaces visible. + if (!ready) profile = null; + renderProjectTypes(data.project_types); + showError(data.project_type_error); + // A stale creation selection can now choose from the available types. + if (!ready && data.project_types.length) { + bridge?.requestSettings(byId("type-id").value, ""); + } + return; + } if (!data.selection_reason_codes || typeof data.selection_reason_codes.FILE_TOO_LARGE !== "string") { throw new Error("Missing file-selection codes in GUI settings."); @@ -3172,6 +3201,7 @@ function collectSettings() { saveModelFields(); return { ...newProjectAnswerSettings(), + _gui_full_snapshot: true, backend: byId("backend").value, _gui_effort_levels: { [activeBackend]: cloneLevels(currentLevels()) }, _gui_search_depth: [...currentDepth()], @@ -3550,7 +3580,7 @@ function renderWorkspace(paths) { // control, or clicking a file's name would also ask to delete it. const item = branch(name, node, files, new Set(), 0, null, {}, false); // Sources and outputs start open; the other folders stay folded. - const key = `${name}|${files[0] || ""}`; + const key = `${name}|${files[0] || name}`; const startsOpen = name === "sources" || name === "outputs"; item.open = startsOpen ? !collapsedWorkspaceFolders.has(key) : expandedFolders.has(key); item.addEventListener("toggle", () => { @@ -3627,7 +3657,7 @@ function renderWorkspace(paths) { }); const hint = document.createElement("p"); hint.className = "source-drop-hint"; - hint.textContent = "Right-click to add, replace, or delete; never indexed"; + hint.textContent = "Right-click to add files, create folders, replace, or delete; never indexed"; item.querySelector("summary").append(hint); item.addEventListener("contextmenu", (event) => { const row = event.target.closest(".tree-file, .tree-folder > summary"); @@ -3650,6 +3680,7 @@ function renderWorkspace(paths) { host.append(line); } markActiveConversationFile(); + globalThis.kilinSourceOrganizationPanel?.decorateWorkspace(); } /** @@ -3705,10 +3736,16 @@ function visibleRect(target) { */ function syncSourceDropTarget() { if (!bridge?.setSourceDropTarget) return; + if (globalThis.kilinSourceOrganizationPanel?.dialog.open) { + sendSourceDropBounds(JSON.stringify({folders: []})); + return; + } const sources = visibleRect(ready ? byId("workspace-source-drop") : byId("drop-zone")); - const folders = ready ? EDITABLE_FOLDERS.flatMap((name) => { - const rect = visibleRect(document.querySelector(`#workspace-tree details[data-path="${name}"]`)); - return rect ? [{ name, ...rect }] : []; + const folders = ready ? [...document.querySelectorAll("#workspace-tree details[data-path]")].flatMap((folder) => { + const name = folder.dataset.path; + if (!EDITABLE_FOLDERS.some((root) => name === root || name.startsWith(`${root}/`))) return []; + const rect = visibleRect(folder); + return rect?.width && rect?.height ? [{ name, ...rect }] : []; }) : []; sendSourceDropBounds(JSON.stringify({ ...(sources || {}), folders })); } @@ -3780,10 +3817,14 @@ document.body.append(sourceMenu); * @param isFile Whether the path is a file rather than a folder. */ function showSourceMenu(x, y, path, isFile) { - showWorkspaceMenu(x, y, [[ - isFile ? "Delete file from project…" : "Delete folder from project…", - () => removeSource(path, isFile), - ]]); + const items = []; + const panel = globalThis.kilinSourceOrganizationPanel; + const relative = isFile ? panel?.workspaceSource(path) : null; + if (relative) items.push(...panel.workspaceActions(relative, (choices) => + showWorkspaceMenu(x, y, choices))); + items.push([isFile ? "Delete file from project…" : "Delete folder from project…", + () => removeSource(path, isFile)]); + showWorkspaceMenu(x, y, items); } /** @@ -3800,7 +3841,10 @@ function showWorkspaceMenu(x, y, items) { button.type = "button"; button.setAttribute("role", "menuitem"); button.textContent = label; - button.addEventListener("click", () => { + button.addEventListener("click", (event) => { + // A submenu replaces the clicked button; do not let the document's + // outside-click handler mistake that detached node for an outside click. + event.stopPropagation(); hideSourceMenu(); action(); }); @@ -3809,8 +3853,8 @@ function showWorkspaceMenu(x, y, items) { sourceMenu.replaceChildren(...buttons); sourceMenu.classList.remove("hidden"); const { width, height } = sourceMenu.getBoundingClientRect(); - sourceMenu.style.left = `${Math.min(x, window.innerWidth - width - 8)}px`; - sourceMenu.style.top = `${Math.min(y, window.innerHeight - height - 8)}px`; + sourceMenu.style.left = `${Math.max(8, Math.min(x, window.innerWidth - width - 8))}px`; + sourceMenu.style.top = `${Math.max(8, Math.min(y, window.innerHeight - height - 8))}px`; buttons[0]?.focus(); } @@ -3824,7 +3868,11 @@ function showWorkspaceMenu(x, y, items) { * @param isFile Whether the path is a file rather than a folder. */ function showFolderMenu(x, y, folder, path, isFile) { - const items = [[`Add files to ${folder}…`, () => bridge.chooseFolderFiles(folder, "add")]]; + const destination = isFile ? path.slice(0, path.lastIndexOf("/")) : path; + const items = [ + [`Add files to ${destination}…`, () => bridge.chooseFolderFiles(destination, "add")], + ["Create folder…", () => createWorkspaceFolder(destination)], + ]; if (isFile) { items.push(["Replace with another file…", () => bridge.chooseFolderFiles(folder, path)]); items.push(["Copy to sources (and index it)…", () => copyToSources(path)]); @@ -3836,6 +3884,29 @@ function showFolderMenu(x, y, folder, path, isFile) { showWorkspaceMenu(x, y, items); } +/** + * Ask for a new directory name without leaving the workspace. + * @param folder Existing workspace-relative editable directory. + */ +async function createWorkspaceFolder(folder) { + if (busy || !bridge) return; + const input = document.createElement("input"); + input.type = "text"; + input.placeholder = "Folder name"; + input.setAttribute("aria-label", "Folder name"); + byId("kilin-ask-message").after(input); + try { + const choice = askKilin(`Create folder in ${folder}?`, "Enter a name for the new folder.", "Create"); + input.focus(); + if (!await choice || busy) return; + const name = input.value.trim(); + if (!name) return; + editFolder({ folder, operation: "mkdir", name }, `Creating folder in ${folder}…`); + } finally { + input.remove(); + } +} + /** * Confirm, then delete a file or folder in outputs or templates. * @param folder Editable workspace folder name. @@ -3888,7 +3959,8 @@ async function folderFilesChosen(folder, purpose, paths) { return; } const names = paths.map((path) => String(path).split(/[\\/]/).pop()); - const taken = names.filter((name) => workspacePaths.has(`${folder}/${name}`)); + const taken = names.filter((name) => workspacePaths.has(`${folder}/${name}`) + || workspacePaths.has(`${folder}/${name}/`)); let replace = false; if (taken.length) { const what = taken.length === 1 ? `“${taken[0]}” is` : `${taken.map((name) => `“${name}”`).join(", ")} are`; @@ -4445,6 +4517,9 @@ function setBusy(value, message = "") { } if (!byId("models-panel").classList.contains("hidden")) renderModelsPanel(); if (!value) focusComposer(); + globalThis.kilinPluginPanel?.refreshIfOpen(); + globalThis.kilinVersionPanel?.refreshIfOpen(); + globalThis.kilinSourceOrganizationPanel?.updateControls(); } /** @@ -5900,9 +5975,8 @@ function branchFromMessage(item, withAnswer, draft) { bridge.branchConversation(withAnswer ? index + 1 : index); } -// The list KíLín adds under a question with attached files; older chats -// listed the original paths under "Attached paths to consider". -const ATTACHED_LIST = /\n\nAttached (?:files|paths to consider):\n((?:- [^\n]+(?:\n|$))+)$/; +// The list KíLín adds under a question with managed source attachments. +const ATTACHED_LIST = /\n\nAttached files:\n((?:- [^\n]+(?:\n|$))+)$/; /** * Split a saved question into the user's text and its attached files. @@ -5914,17 +5988,23 @@ function splitAttached(text) { const value = String(text || ""); const match = value.match(ATTACHED_LIST); if (!match) return { question: value, files: [] }; - return { - question: value.slice(0, match.index), - files: match[1].trim().split("\n").map((line) => line.slice(2).trim()), - }; + const files = match[1].replace(/\n$/, "").split("\n").map((line) => line.slice(2)); + // Only normalized managed-relative paths may become workspace actions. + // Keep an unsupported or malformed list as literal question text. + if (files.some((path) => { + const parts = path.replace(/\/$/, "").split("/"); + return parts[0] !== "sources" || parts.length < 2 + || /[\\\x00]/.test(path) + || parts.some((part) => !part || part === "." || part === ".."); + })) return { question: value, files: [] }; + return { question: value.slice(0, match.index), files }; } /** * Show a question with its attached files as chips under the text. * - * A file in sources opens its place in the workspace tree; a path from an - * older chat, never copied, is shown by name only. + * A managed file or folder opens its place in the workspace tree. Text + * without a valid current attachment list is displayed unchanged. * * @param element The question bubble. * @param text Question as sent to the engine. @@ -5936,15 +6016,12 @@ function fillQuestion(element, text) { const row = document.createElement("div"); row.className = "question-attachments"; for (const path of files) { - const inSources = path.startsWith("sources/"); - const chip = document.createElement(inSources ? "button" : "span"); + const chip = document.createElement("button"); chip.className = "question-attachment"; - chip.textContent = path.replace(/\/$/, "").split(/[\\/]/).pop() || path; - chip.title = inSources ? `Show ${path} in the workspace` : path; - if (inSources) { - chip.type = "button"; - chip.addEventListener("click", () => revealWorkspacePath(path)); - } + chip.textContent = path.replace(/\/$/, "").split("/").pop(); + chip.title = `Show ${path} in the workspace`; + chip.type = "button"; + chip.addEventListener("click", () => revealWorkspacePath(path)); row.append(chip); } element.append(row); @@ -7223,6 +7300,29 @@ function appendAnswerText(text) { */ function onEvent(raw) { const data = JSON.parse(raw); + if (data.event === "plugins") { + globalThis.kilinPluginPanel?.handleEvent(data); + if (data.inventory) globalThis.kilinVersionPanel?.invalidate(); + return; + } + if (data.event === "versions") { + globalThis.kilinVersionPanel?.handleEvent(data); + return; + } + if (data.event === "source_organization") { + globalThis.kilinSourceOrganizationPanel?.handleEvent(data); + return; + } + if (data.event === "source_organization_lifecycle") { + globalThis.kilinSourceOrganizationPanel?.lifecycle(data); + return; + } + if (["stopped", "backend_failed", "backend_restarted"].includes(data.event) + || (data.event === "projects_folder" && switchingProjectsFolder)) { + globalThis.kilinPluginPanel?.interrupted(); + globalThis.kilinVersionPanel?.interrupted(); + globalThis.kilinSourceOrganizationPanel?.interrupted(); + } if (data.event === "trace_ready") { activeTracePath = data.trace_path || ""; markActiveConversationFile(); @@ -7630,6 +7730,7 @@ function onEvent(raw) { sourceWelcome = pending?.welcome || []; pendingSourceQuestions = null; openProjectPath = data.project; + globalThis.kilinSourceOrganizationPanel?.opened(data.project, data.source_organization); projectPresentation = data.behavior_presentation || null; requestProjectBehavior(); messageAttachments = []; @@ -7672,6 +7773,7 @@ function onEvent(raw) { attachedAsk = null; sendQuestion(ask); } + globalThis.kilinSourceOrganizationPanel?.promptNewPending(); } else if (data.event === "question_suggestions") { const questions = (data.questions || []).filter((item) => item?.question); const welcome = (data.welcome || []).filter((text) => typeof text === "string" && text); @@ -7902,6 +8004,7 @@ function onEvent(raw) { setBusy(true, "Reopening the project after backend recovery…"); bridge.resumeProjectConversation(openProjectPath, activeConversationId); } + globalThis.kilinVersionPanel?.invalidate(); } else if (data.event === "workspace_conflict") { // Creation never reuses a project; opening one is a separate decision. setBusy(false); @@ -7922,6 +8025,11 @@ function onEvent(raw) { } }); } else if (data.event === "error") { + // A transport failure may not have a correlated plugin reply. Do not + // retry a mutation; allow an explicit inventory refresh instead. + if (globalThis.kilinPluginPanel?.request) globalThis.kilinPluginPanel.interrupted(false); + if (globalThis.kilinVersionPanel?.request) globalThis.kilinVersionPanel.interrupted(); + globalThis.kilinSourceOrganizationPanel?.transportFailed(data.message); // A failed switch may already have released the previous session. // Do not show its stale conversation or claim it is still active. if (data.resume_released) returnToLaunch(); @@ -7979,9 +8087,6 @@ byId("memory-next").addEventListener("click", () => { }); byId("browse-workspace").addEventListener("click", () => changeProjectsFolder(false)); byId("default-workspace").addEventListener("click", () => changeProjectsFolder(true)); -byId("use-legacy-workspace").addEventListener( - "click", useLegacyProjectsFolder, -); byId("confirm-workspace").addEventListener("click", () => { if (!bridge || busy) return; if (ready) return changeProjectsFolder(false); @@ -8057,6 +8162,10 @@ dropZone.addEventListener("drop", (event) => { }); byId("stop").addEventListener("click", () => { if (!busy || !bridge) return; + if (globalThis.kilinPluginPanel?.blocking() && ready && activeConversationId) { + // Preserve the open conversation if a plugin validation is interrupted. + resumeAfterStop = true; + } byId("stop").disabled = true; byId("activity-text").textContent = "Stopping…"; bridge.stopOperation(); @@ -8126,6 +8235,7 @@ byId("cancel-model-download").addEventListener("click", () => { byId("project-form").addEventListener("submit", (event) => { event.preventDefault(); if (busy || !bridge || needsNewProjectSetup()) return; + if (!byId("type-id").value) return showError("No project types are available."); if (!profile) return showError("Settings are still loading. Try again in a moment."); if (!installedBackends[activeBackend]) { openModels(); @@ -8258,8 +8368,6 @@ function showProjectSettings() { // saved folder, Confirm projects folder confirms the one in use. byId("default-workspace").disabled = ready || !projectsFolderInfo?.saved || projectsFolderInfo.saved === projectsFolderInfo.standard; - byId("use-legacy-workspace").disabled = ready || busy; - byId("use-legacy-workspace").title = why; byId("browse-workspace").title = why; byId("default-workspace").title = why; // A note only when the chosen folder is missing. @@ -8268,18 +8376,6 @@ function showProjectSettings() { ? `${projectsFolderInfo.saved} is not available, so KíLín uses the default folder.` : ""; byId("workspace-note").classList.toggle("hidden", !missing); - const legacy = projectsFolderInfo?.legacy || ""; - const canReuseLegacy = Boolean( - legacy && legacy !== projectsFolderInfo?.folder, - ); - byId("legacy-workspace-choice").classList.toggle( - "hidden", !canReuseLegacy, - ); - byId("legacy-workspace-note").textContent = canReuseLegacy - ? `Existing KíLín projects may be at ${legacy}. Use that folder to ` - + "keep working with them, or confirm a different folder. " - + "No project files will be moved." - : ""; showSetupConfirmations(); // An open project keeps the backend it was made with. byId("backend").title = ready ? "Set when the project was created." : ""; @@ -8367,19 +8463,6 @@ function changeProjectsFolder(useDefault) { bridge.useDefaultProjectsFolder(); } -/** - * Reuse a previous installed-app projects directory without moving files. - * - * Qt rechecks the old folder before saving it as the user's choice. - */ -function useLegacyProjectsFolder() { - if (!bridge || busy || !projectsFolderInfo?.legacy) return; - if (ready) return changeProjectsFolder(false); - switchingProjectsFolder = true; - setBusy(true, "Opening the previous projects folder…"); - bridge.useLegacyProjectsFolder(); -} - /** * Restore the start screen after a cancelled or failed folder selection. * @@ -8412,6 +8495,23 @@ function sendQuestion(ask) { answeringConversationId = activeConversationId; const listed = ask.files.map((path) => `- ${path}`).join("\n"); const text = listed ? `${ask.question}\n\nAttached files:\n${listed}` : ask.question; + const organization = globalThis.kilinSourceOrganizationPanel; + const pendingAttachments = organization?.pendingAttachments(ask.files) || []; + const pendingRoles = [...new Set([...pendingAttachments, + ...(organization?.newPendingPaths?.() || [])])]; + if (pendingRoles.length) { + // The copies are already saved. Preserve their exact paths in the + // draft rather than silently asking before their roles are reviewed. + unansweredQuestion = ""; + answeringConversationId = ""; + setQuestionDraft(text); + error.textContent = (pendingAttachments.length ? "Some attached files need source roles." : "Newly imported files need source roles.") + + " Review their organization, then send the draft when ready." + + (ask.leftOut.length ? ` Not added: ${ask.leftOut.join(", ")}.` : ""); + error.classList.remove("hidden"); + organization.open("pending", "", pendingRoles); + return; + } addPendingTurn(text); showAskingConversation(ask.question); setBusy(true, "Finding evidence and answering…"); @@ -8486,6 +8586,7 @@ function returnToLaunch() { answerSettingsSave.uncertain = false; bridge.closeProject(); openProjectPath = ""; + globalThis.kilinSourceOrganizationPanel?.interrupted(); projectPresentation = null; sourceQuestions = []; sourceWelcome = []; @@ -8699,6 +8800,25 @@ new QWebChannel(qt.webChannelTransport, (channel) => { bridge = channel.objects.kilin; bridge.setAppearance(document.documentElement.dataset.appearance || "system"); bridge.event.connect(onEvent); + if (globalThis.PluginPanel) { + globalThis.kilinPluginPanel = new globalThis.PluginPanel( + bridge, () => busy, setBusy, askKilin, + ); + } + if (globalThis.VersionPanel) { + globalThis.kilinVersionPanel = new globalThis.VersionPanel( + bridge, () => busy, () => openProjectPath, + ); + bridge.applicationVersion?.((version) => { + globalThis.kilinVersionPanel.applicationVersion(version); + }); + } + if (globalThis.SourceOrganizationPanel) { + globalThis.kilinSourceOrganizationPanel = new globalThis.SourceOrganizationPanel( + bridge, () => busy, setBusy, () => ready ? openProjectPath : "", askKilin, + syncSourceDropTarget, + ); + } bridge.pathsSelected.connect(addSources); bridge.folderFilesSelected.connect(folderFilesChosen); bridge.sourceDragChanged.connect(showNativeSourceDrag); diff --git a/kilin/gui/web/index.html b/kilin/gui/web/index.html index e5f7a24f..9fa7a8eb 100644 --- a/kilin/gui/web/index.html +++ b/kilin/gui/web/index.html @@ -7,12 +7,15 @@ + + +
@@ -189,10 +197,6 @@

Projects folder
-

Projects remain in the folder you choose. iCloud, OneDrive, or another service may synchronize that folder; choose a non-synchronized location for sensitive data.

@@ -204,6 +208,44 @@

+
+
+

Plugins

+

Application-wide tools and project types, independent of the current project.

+

+
+ + + +
+ +

+
+
+
+
+
+

Versions

+

Application, compatibility contracts, tools, project types, persistent formats and current project origin.

+
+ + +
+

Reports include local plugin paths and diagnostics; review before sharing.

+

+
+
+

Project

@@ -272,6 +314,12 @@

Source-card generation

+
+

Source organization

+

Manage the accepted role vocabulary, relationships and automatic discovery for this project, separately from indexing.

+ +

Open a project to edit source organization.

+
@@ -352,6 +400,92 @@

Manage remembered messages

+ +
+

Source organization

+ +
+

Roles and relationships describe sources, not their physical location. Edits are saved only after an engine-validated preview and Apply.

+

+
+ + + +
+ +

Original files changed

diff --git a/kilin/gui/web/plugin_panel.js b/kilin/gui/web/plugin_panel.js new file mode 100644 index 00000000..76d63b37 --- /dev/null +++ b/kilin/gui/web/plugin_panel.js @@ -0,0 +1,379 @@ +/** + * Application-level plugin management. This controller owns only transient + * selection and request state; the engine and core own files and activation. + * Candidate paths and diagnostics are always rendered as text. + */ +"use strict"; + +class PluginPanel { + /** + * Bind the independent Settings section to the existing engine transport. + * @param bridge Qt web channel object. + * @param isBusy Whether the engine is doing another operation. + * @param setBusy Existing application activity controller. + * @param confirm Existing cancel-first confirmation dialog. + */ + constructor(bridge, isBusy, setBusy, confirm) { + this.bridge = bridge; + this.isBusy = isBusy; + this.setBusy = setBusy; + this.confirm = confirm; + this.sequence = 0; + this.request = null; + this.candidate = null; + this.inventory = null; + this.choosing = false; + this.confirming = false; + this.needsRefresh = true; + this.interruptionNotice = false; + this.panel = document.getElementById("plugin-panel"); + const bind = (id, handler) => this.element(id).addEventListener("click", handler); + bind("plugin-refresh", () => this.refresh()); + bind("plugin-choose-tool", () => this.choose("tool")); + bind("plugin-choose-type", () => this.choose("project_type")); + bind("plugin-structure", () => this.candidateAction("structure")); + bind("plugin-validate", () => this.candidateAction("validate")); + bind("plugin-stage", () => this.candidateAction(this.candidate?.operation)); + bind("plugin-clear", () => this.clearCandidate()); + this.panel.addEventListener("toggle", () => this.refreshIfOpen()); + this.updateControls(); + } + + /** Find a fixed plugin section element. */ + element(id) { return document.getElementById(id); } + + /** Whether another command or native/confirmation dialog owns the panel. */ + locked() { return this.isBusy() || Boolean(this.request) || this.choosing || this.confirming; } + + /** Keep plugin actions disabled during other engine operations. */ + updateControls() { + const locked = this.locked(); + this.panel.querySelectorAll("[data-plugin-action]").forEach((button) => { + button.disabled = locked; + }); + this.panel.setAttribute("aria-busy", String(Boolean(this.request))); + } + + /** Request fresh state when Settings and the section are visible. */ + refreshIfOpen() { + this.updateControls(); + if (this.panel.open && !this.element("models-panel").classList.contains("hidden") && this.needsRefresh && !this.locked()) this.refresh(); + } + + /** Mark the inventory stale when Settings is reopened. */ + opened() { + this.needsRefresh = true; + this.refreshIfOpen(); + } + + /** Refresh queued operations and current runtime diagnostics. */ + refresh() { + if (this.locked()) return; + this.needsRefresh = false; + this.send({ operation: "list" }); + } + + /** + * Issue a correlated request. Only candidate checks and mutations reserve + * the global busy state; the short inventory request never closes a chat. + * @param payload Management request, without request_id. + */ + send(payload) { + if (this.locked()) return; + const request_id = String(++this.sequence); + const blocking = payload.operation !== "list"; + if (blocking) this.interruptionNotice = false; + this.request = { request_id, operation: payload.operation, blocking }; + this.element("plugin-status").textContent = blocking + ? "Working on plugin request…" : "Reading plugin inventory…"; + if (blocking) this.setBusy(true, "Checking or managing plugin…"); + this.updateControls(); + this.bridge.managePlugins(JSON.stringify({ ...payload, request_id })); + } + + /** + * Choose a source with no automatic validation or installation. An update + * remains tied to the selected installed entry, not a new filename. + * @param kind Plugin category. + * @param name Optional installed ID when explicitly updating. + */ + choose(kind, name = "") { + if (this.locked()) return; + this.choosing = true; + this.updateControls(); + this.bridge.choosePluginPath(kind, (path) => { + this.choosing = false; + if (path) { + this.candidate = { kind, name, path, operation: name ? "update" : "install" }; + this.element("plugin-candidate-title").textContent = name + ? `Update ${name}` : `Install ${kind === "tool" ? "tool" : "project type"}`; + this.element("plugin-candidate-path").textContent = path; + this.element("plugin-stage").textContent = name ? "Update" : "Install"; + this.element("plugin-validation").textContent = ""; + this.element("plugin-candidate").classList.remove("hidden"); + } + this.updateControls(); + }); + } + + /** Clear an unsubmitted candidate without affecting pending operations. */ + clearCandidate() { + if (this.locked()) return; + this.candidate = null; + this.element("plugin-candidate").classList.add("hidden"); + this.element("plugin-validation").textContent = ""; + } + + /** + * Ask explicitly before executing candidate Python with user permissions. + * The exact chosen path is part of the confirmation, and trust is not + * remembered across operations or transferred to another candidate. + * @param operation Candidate check or stage operation. + */ + async candidateAction(operation) { + if (this.locked() || !this.candidate || !operation) return; + const candidate = this.candidate; + let trusted = false; + if (candidate.kind === "tool" && operation !== "structure") { + this.confirming = true; + this.updateControls(); + try { + trusted = await this.confirm("Trust this Python plugin?", + `Selected source: ${candidate.path}. Validation executes Python code with your account's permissions. It is not a security sandbox. Only continue if you trust this code. Installed tools can execute again whenever KíLín starts.`, + operation === "validate" ? "Trust and validate" : "Trust and queue"); + } finally { + this.confirming = false; + this.updateControls(); + } + if (trusted !== true || this.candidate !== candidate || this.locked()) return; + } + this.element("plugin-validation").textContent = ""; + this.send({ ...candidate, operation, trusted: trusted === true }); + } + + /** + * Confirm removal or cancellation of a queued operation. Neither action + * deletes a project or changes an active catalog. + * @param operation remove or cancel. + * @param kind Plugin category. + * @param name Stable plugin ID. + */ + async entryAction(operation, kind, name) { + if (this.locked()) return; + this.confirming = true; + this.updateControls(); + let confirmed; + try { + confirmed = await this.confirm(operation === "remove" ? `Remove ${name}?` : `Cancel pending change for ${name}?`, + operation === "remove" + ? "Removal takes effect only at an eligible startup. Workspaces are preserved, but projects requiring this plugin may become unavailable." + : "The queued operation will be discarded. Installed plugins remain unchanged.", + operation === "remove" ? "Queue removal" : "Cancel change"); + } finally { + this.confirming = false; + this.updateControls(); + } + if (confirmed === true && !this.locked()) this.send({ operation, kind, name }); + } + + /** + * Construct a paragraph using plain text, including hostile diagnostics. + * @param text Content. + * @param className CSS class. + */ + note(text, className = "hint") { + const node = document.createElement("p"); + node.className = className; + node.textContent = text; + return node; + } + + /** + * Create an action whose availability follows the current request state. + * @param label Button text. + * @param handler Click callback. + */ + button(label, handler) { + const node = document.createElement("button"); + node.type = "button"; + node.className = "secondary"; + node.dataset.pluginAction = ""; + node.textContent = label; + node.addEventListener("click", handler); + return node; + } + + /** + * Render one runtime or disk-only entry. Distribution records have no + * mutation controls, including when a user copy conflicts with them. + * @param row Serialized catalog record. + * @param kind Plugin category. + * @param installed Whether this is an installed user entry. + * @param pending Whether an operation is pending for that ID. + */ + entry(row, kind, installed, pending) { + const entry = document.createElement("div"); + entry.className = "plugin-entry"; + const name = row.name ?? row.type_id; + const header = document.createElement("div"); + header.className = "plugin-entry-header"; + const id = document.createElement("code"); + id.textContent = name; + const status = document.createElement("span"); + status.className = "hint"; + status.textContent = row.available ? "Available" : "Unavailable"; + header.append(id, status); + entry.append(header); + const details = kind === "tool" + ? [`Version ${row.version ?? "unknown"}`, `API ${row.api_version ?? "unknown"}`] + : [`Version ${row.version ?? "unknown"}`, `Schema ${row.schema_version ?? "unknown"}`]; + if (row.sha256) details.push(`SHA-256 ${row.sha256.slice(0, 12)}…`); + const identity = this.note(details.join(" · ")); + if (row.sha256) identity.title = row.sha256; + entry.append(identity); + if (row.path) entry.append(this.note(row.path, "hint plugin-path")); + if (row.required_tools?.length) entry.append(this.note(`Requires: ${row.required_tools.join(", ")}`)); + if (row.error) entry.append(this.note(row.error, "hint plugin-diagnostic")); + for (const warning of row.warnings || []) entry.append(this.note(`Warning: ${warning}`, "hint plugin-diagnostic")); + if (installed && !pending) { + const actions = document.createElement("div"); + actions.className = "plugin-actions"; + actions.append(this.button("Update…", () => this.choose(kind, name)), + this.button("Remove…", () => this.entryAction("remove", kind, name))); + entry.append(actions); + } else if (pending) entry.append(this.note("Change pending; see queued operations above.")); + return entry; + } + + /** + * Render current availability separately from durable pending operations. + * @param inventory Engine-provided arrays and per-inventory diagnostics. + */ + render(inventory) { + this.inventory = inventory; + const host = this.element("plugin-inventory"); + const expanded = new Map(Array.from(host.querySelectorAll("details[data-plugin-group]"), + (group) => [group.dataset.pluginGroup, group.open])); + host.replaceChildren(); + this.element("plugin-directory").textContent = inventory.directory ? `User directory: ${inventory.directory}` : "User directory unavailable"; + const pending = inventory.pending || []; + const installed = inventory.installed || []; + const errors = inventory.errors || {}; + const key = (kind, name) => `${kind}:${name}`; + const pendingKeys = new Set(pending.map((row) => key(row.kind, row.name))); + const installedKeys = new Set(installed.map((row) => key(row.kind, row.name))); + this.element("plugin-summary").textContent = pending.length + ? `${pending.length} pending` : Object.keys(errors).length ? "Diagnostics" : `${installed.length} user plugins`; + for (const [section, message] of Object.entries(errors)) host.append(this.note(`${section}: ${message}`, "hint plugin-diagnostic")); + if (pending.length) { + const queue = document.createElement("section"); + queue.className = "plugin-pending"; + const heading = document.createElement("strong"); + heading.textContent = "Pending changes"; + queue.append(heading, this.note("Quit every KíLín application and Python or notebook runtime using this plugin directory, then start KíLín again. Closing a project or restarting only the engine is not enough.")); + for (const row of pending) { + const line = document.createElement("div"); + line.className = "plugin-entry"; + line.append(this.note(`${row.action}: ${row.name} (${row.kind === "tool" ? "tool" : "project type"})`)); + if (row.action !== "remove") { + line.append(this.note(`Version ${row.version ?? "unknown"}`)); + if (row.kind === "tool") line.append(this.note(`API ${row.api_version ?? "unknown"}`)); + else line.append(this.note(`Schema ${row.schema_version ?? "unknown"}`)); + } + if (row.sha256) { + const digest = this.note(`SHA-256 ${row.sha256.slice(0, 12)}…`); + digest.title = row.sha256; + line.append(digest); + } + if (row.error) line.append(this.note(row.error, "hint plugin-diagnostic")); + line.append(this.button("Cancel pending change…", () => this.entryAction("cancel", row.kind, row.name))); + queue.append(line); + } + host.append(queue); + } + for (const [kind, label, catalog] of [["tool", "tools", inventory.tools || []], ["project_type", "project types", inventory.project_types || []]]) { + const rows = [...catalog]; + for (const disk of installed.filter((row) => row.kind === kind)) { + if (!rows.some((row) => row.origin === "user" && (row.name ?? row.type_id) === disk.name)) { + rows.push({ ...disk, origin: "user", available: false, error: "Not registered in the current runtime." }); + } + } + for (const origin of ["user", "distribution"]) { + const matching = rows.filter((row) => row.origin === origin); + const group = document.createElement("details"); + group.className = "plugin-group"; + group.dataset.pluginGroup = key(kind, origin); + group.open = expanded.get(group.dataset.pluginGroup) ?? (origin === "user" || matching.some((row) => !row.available)); + const summary = document.createElement("summary"); + summary.textContent = `${origin === "user" ? "User" : "Bundled"} ${label} (${matching.length})`; + group.append(summary); + if (!matching.length) group.append(this.note("None")); + for (const row of matching) { + const id = key(kind, row.name ?? row.type_id); + group.append(this.entry(row, kind, origin === "user" && installedKeys.has(id), origin === "user" && pendingKeys.has(id))); + } + host.append(group); + } + } + this.updateControls(); + } + + /** + * Consume the correlated plugin response, ignoring late responses after + * interruption. A validation result never claims activation or install. + * @param data Engine event. + * @returns Whether this is a plugin-specific event. + */ + handleEvent(data) { + if (data.event !== "plugins") return false; + if (!this.request || data.request_id !== this.request.request_id || data.operation !== this.request.operation) return true; + const request = this.request; + this.request = null; + if (data.inventory) this.render(data.inventory); + let message = data.error || ""; + if (data.validation) { + const result = data.validation; + const structural = result.runtime_checked === false || result.bound === false; + const identity = result.name !== undefined + ? [result.name, `Version ${result.version ?? "unknown"}`, `API ${result.api_version ?? "unknown"}`] + : [result.type_id, `Version ${result.version ?? "unknown"}`, `Schema ${result.schema_version ?? "unknown"}`]; + if (result.sha256) identity.push(`SHA-256 ${result.sha256}`); + const description = result.error || (structural + ? (result.runtime_checked === false ? "Structure valid. Candidate Python was not executed." : "Structure valid. Required tools were not checked.") + : "Validation passed. No installation has been made."); + const lines = [description, identity.join(" · ")]; + if (result.required_tools?.length) lines.push(`Requires: ${result.required_tools.join(", ")}`); + this.element("plugin-validation").textContent = [...lines, ...(result.warnings || [])].join("\n"); + } else if (data.change) { + message = `${data.change.name}: ${data.change.action} queued. Changes activate only after all runtimes close and a new one starts.`; + this.candidate = null; + this.element("plugin-candidate").classList.add("hidden"); + } else if (data.canceled) message = "Pending change canceled."; + else if (!message && request.operation === "list" && this.interruptionNotice) { + message = "Inventory refreshed after an interrupted request. Check pending changes before retrying."; + } + this.element("plugin-status").textContent = message; + if (request.blocking) this.setBusy(false); + this.updateControls(); + return true; + } + + /** Whether Stop is interrupting a plugin check or mutation. */ + blocking() { return Boolean(this.request?.blocking); } + + /** + * Forget an uncertain request without retrying a possible mutation. + * @param refresh Whether the recovered engine can refresh automatically. + */ + interrupted(refresh = true) { + if (this.request) { + this.interruptionNotice = true; + this.element("plugin-status").textContent = "Plugin request interrupted. Refresh to check the actual pending changes before retrying."; + } + this.request = null; + this.needsRefresh = refresh; + this.updateControls(); + } +} + +globalThis.PluginPanel = PluginPanel; diff --git a/kilin/gui/web/source_organization_panel.js b/kilin/gui/web/source_organization_panel.js new file mode 100644 index 00000000..222b5b4d --- /dev/null +++ b/kilin/gui/web/source_organization_panel.js @@ -0,0 +1,926 @@ +/** + * Edit accepted source organization through the engine's transaction protocol. + * The page stages explicit commands only; it does not validate graph semantics, + * write a manifest, or derive the roles of files from names or folders. + */ +"use strict"; + +class SourceOrganizationPanel { + /** Connect the shared editor to the active project and global busy state. */ + constructor(bridge, isBusy, setBusy, currentProject, confirm, dropTargetsChanged = () => {}) { + this.bridge = bridge; + this.isBusy = isBusy; + this.setBusy = setBusy; + this.currentProject = currentProject; + this.confirm = confirm; + this.dropTargetsChanged = dropTargetsChanged; + this.sequence = 0; + this.epoch = 0; + this.project = ""; + this.inspection = null; + this.request = null; + this.preview = null; + this.edits = []; + this.notice = ""; + this.lifecycleNotice = ""; + this.lastLifecycle = null; + this.pendingScope = null; + this.mode = "files"; + this.errorType = ""; + this.dialog = this.element("dialog"); + this.bind("open", "click", () => this.open()); + this.bind("settings-open", "click", () => this.open("settings")); + this.bind("close", "click", () => this.close()); + this.dialog.addEventListener("cancel", (event) => { + event.preventDefault(); + this.close(); + }); + this.bind("inspect", "click", () => this.reload()); + this.bind("initialize", "click", () => this.initialize()); + this.bind("filter", "input", () => this.renderFiles()); + this.bind("pending-only", "change", () => this.renderFiles()); + this.bind("files", "change", () => this.renderSelection(true)); + this.bind("role", "change", () => this.updateControls()); + this.bind("full-editor", "click", () => this.showFullEditor()); + this.bind("default-role-choice", "change", () => { + if (!this.available() || this.element("adopt-type").checked) return; + this.element("default-role").value = this.element("default-role-choice").value; + this.invalidatePreview(); + }); + this.bind("relation", "change", () => this.updateControls()); + this.bind("target", "change", () => this.updateControls()); + this.bind("stage-role", "click", () => this.stageRoles(this.element("role").value)); + this.bind("reset-role", "click", () => this.stageRoles(null)); + this.bind("restore-file", "click", () => this.stageResolutions(true)); + this.bind("reset-file", "click", () => this.stageResolutions(false)); + this.bind("stage-link", "click", () => this.stageLink()); + for (const id of this.settingsFields()) { + const changed = () => { + this.invalidatePreview(); + if (["roles", "rules", "adopt-type"].includes(id)) this.renderOrdinarySettings(); + }; + this.bind(id, "input", changed); + this.bind(id, "change", changed); + } + this.bind("discard", "click", () => this.discard()); + this.bind("preview", "click", () => this.requestPreview()); + this.bind("apply", "click", () => this.apply()); + this.updateControls(); + } + + /** Resolve one fixed element; no source path is used as a DOM selector. */ + element(id) { return document.getElementById(`source-org-${id}`); } + + /** Attach a control listener. */ + bind(id, event, callback) { this.element(id).addEventListener(event, callback); } + + /** List fields that participate in a prospective settings change. */ + settingsFields() { + return ["roles", "default-role", "relation-types", "rules", "role-mapping", + "relation-mapping", "adopt-type", "adopt-detectors"]; + } + + /** Read only the saved, canonical state supplied by the engine. */ + manifest() { return this.inspection?.source_organization || null; } + + /** Return selected source-relative identities exactly as sent by the core. */ + selection() { return Array.from(this.element("files").selectedOptions, (o) => o.value); } + + /** Indicate whether this panel can issue another project operation. */ + available() { + return Boolean(this.project && this.project === this.currentProject() + && !this.isBusy() && !this.request); + } + + /** A malformed or missing manifest is never treated as an empty manifest. */ + usable() { return Boolean(this.manifest()); } + + /** Only accept workspace-tree paths whose root identity is exact. */ + workspaceSource(path) { + const root = this.inspection?.source_root; + if (!this.inspection?.binding_matches || root?.base !== "project" + || root.path !== "sources" || !path.startsWith("sources/")) return null; + const relative = path.slice("sources/".length); + return this.selectedPaths.has(relative) ? relative : null; + } + + /** Find pending attached paths (folders include descendants). */ + pendingAttachments(paths) { + const root = this.inspection?.source_root; + if (!this.inspection?.binding_matches || root?.base !== "project" + || root.path !== "sources") return []; + return (this.inspection.pending_roles || []).filter((name) => paths.some((path) => { + if (!path.startsWith("sources/")) return false; + const relative = path.slice("sources/".length); + return name === relative || (relative.endsWith("/") && name.startsWith(relative)); + })); + } + + /** Replace local state on open/reopen; do not retain an old preview. */ + opened(project, payload) { + const lifecycle = this.lastLifecycle?.project === project ? this.lastLifecycle : null; + this.interrupted(); + this.project = project; + this.lastLifecycle = lifecycle; + this.lifecycleNotice = lifecycle?.notice || ""; + this.accept(payload || {}, this.lifecycleNotice); + } + + /** Drop all local authority when the project or engine is released. */ + interrupted() { + this.epoch++; + this.request = null; + this.preview = null; + this.inspection = null; + this.project = ""; + this.edits = []; + this.notice = ""; + this.lifecycleNotice = ""; + this.lastLifecycle = null; + this.pendingScope = null; + this.errorType = ""; + this.selectedPaths = new Set(); + this.dialog.close(); + this.dropTargetsChanged(); + this.resetSettings(); + this.render(); + } + + /** Refresh a lifecycle observation without claiming indexing has finished. */ + lifecycle(data) { + const warnings = []; + if (data.error) warnings.push(`Source reconciliation: ${data.error}`); + if (data.trace_error) warnings.push(`Recording: ${data.trace_error}`); + if (data.new_pending_roles?.length) { + warnings.push(`${data.new_pending_roles.length} newly added files need roles.`); + } + // A physical import can emit several observations before the final + // opened event (including a refresh with no additional files). + const queued = this.lastLifecycle?.project === data.project ? this.lastLifecycle.pending : []; + this.lastLifecycle = {project: data.project, notice: warnings.join(" "), + pending: [...new Set([...(queued || []), ...(data.new_pending_roles || [])])]}; + if (data.project !== this.project || data.project !== this.currentProject()) return; + this.lifecycleNotice = this.lastLifecycle.notice; + this.epoch++; + // A lifecycle observation is not a command completion. If an earlier + // queued observation arrived late, keep waiting for the correlated reply. + if (this.request) this.request.invalidated = true; + this.accept(data, this.lifecycleNotice); + } + + /** Adopt an inspection, dropping all drafts tied to the previous identity. */ + accept(data, notice = "") { + this.inspection = data.inspection || null; + this.selectedPaths = new Set(this.inspection?.selected || []); + const manifest = this.manifest(); + this.resolutionPaths = new Set((manifest?.unresolved || []).map((item) => item.path)); + if (manifest) for (const edge of manifest.relations) { + for (const path of [edge.source, edge.target]) { + if (!Object.hasOwn(manifest.files, path)) this.resolutionPaths.add(path); + } + } + this.errorType = data.error_type || ""; + this.notice = [notice, data.error && !notice.includes(data.error) && data.error, + data.refresh_error && `Metadata refresh: ${data.refresh_error}`, + data.trace_error && `Recording: ${data.trace_error}`].filter(Boolean).join(" "); + this.preview = null; + this.edits = []; + this.resetSettings(); + this.render(); + } + + /** Restrict import notifications to paths still pending in this project. */ + newPendingPaths() { + if (this.lastLifecycle?.project !== this.project) return []; + const current = new Set(this.inspection?.pending_roles || []); + return (this.lastLifecycle.pending || []).filter((path) => current.has(path)); + } + + /** Consume newly pending paths only once, after the physical operation. */ + promptNewPending() { + if (!this.available() || this.lastLifecycle?.project !== this.project) return; + const pending = this.newPendingPaths(); + this.lastLifecycle = null; + if (pending.length && !this.dialog.open) this.open("pending", "", pending); + } + + /** Display the editor without performing a mutation. */ + open(section = "files", path = "", pendingPaths = null) { + if (!this.available() || this.dialog.open) return false; + this.mode = section; + this.pendingScope = section === "pending" + ? new Set(pendingPaths || this.inspection?.pending_roles || []) : null; + if (this.pendingScope && this.lastLifecycle?.project === this.project) { + const current = new Set(this.inspection?.pending_roles || []); + for (const name of this.lastLifecycle.pending || []) { + if (current.has(name)) this.pendingScope.add(name); + } + this.lastLifecycle = null; + } + this.element("direction").value = "outgoing"; + this.element("settings-section").open = section === "settings"; + this.element("files-section").open = section !== "settings"; + this.element("links-section").open = section !== "settings" && !this.pendingScope; + this.element("filter").value = ""; + this.element("pending-only").checked = section === "pending"; + this.renderMode(); + this.dialog.showModal(); + this.dropTargetsChanged(); + this.render(); + if (path) this.element("files").value = path; + if (this.pendingScope) { + for (const option of this.element("files").options) option.selected = true; + this.element("role").value = ""; + } + if (path || this.pendingScope) this.renderSelection(Boolean(path)); + if (!this.usable() && !this.errorType) this.send("inspect"); + return true; + } + + /** Focus shortcuts on their requested task without changing authority. */ + renderMode() { + const pending = this.mode === "pending"; + const linking = this.mode === "link"; + const quick = this.mode === "quick"; + const focused = pending || linking || quick; + this.dialog.classList.toggle("source-org-pending-dialog", focused); + this.element("title").textContent = pending ? "Assign source roles" + : linking ? "Link source files" : quick ? "Review source change" : "Source organization"; + this.element("full-editor").classList.toggle("hidden", !focused); + this.element("links-section").classList.toggle("hidden", pending || quick); + this.element("settings-section").classList.toggle("hidden", focused); + this.element("files-section").classList.toggle("hidden", linking || quick); + this.element("file-filters").classList.toggle("hidden", pending); + } + + /** Expand the focused editor without discarding staged edits. */ + showFullEditor() { + if (!this.available()) return; + this.pendingScope = null; + this.mode = "files"; + this.renderMode(); + this.element("pending-only").checked = false; + this.element("files-section").open = true; + this.element("links-section").open = true; + this.render(); + } + + /** Close and abandon only unsaved edits; a running request cannot be closed. */ + async close() { + if (this.request) return; + const epoch = this.epoch; + if (this.hasDraft() && !await this.confirm("Discard staged source changes?", + "The accepted source organization will not change.", "Discard")) return; + if (epoch !== this.epoch || this.request) return; + this.discard(); + this.dialog.close(); + this.pendingScope = null; + this.dropTargetsChanged(); + this.render(); + } + + /** Refresh inspection explicitly; a changed inventory invalidates a draft. */ + async reload() { + if (!this.available()) return; + const epoch = this.epoch; + if (this.hasDraft() && !await this.confirm("Refresh source organization?", + "This discards the current staged changes and preview.", "Refresh")) return; + if (epoch !== this.epoch || !this.available()) return; + this.discard(); + this.send("inspect"); + } + + /** Missing metadata may be initialized only with explicit confirmation. */ + async initialize() { + if (!this.available() || this.errorType !== "FileNotFoundError") return; + const epoch = this.epoch; + if (!await this.confirm("Initialize source organization?", + "Create missing metadata using this project's current type defaults. Existing source files are not changed.", "Initialize")) return; + if (epoch === this.epoch && this.available() && this.errorType === "FileNotFoundError") this.send("initialize"); + } + + /** Correlate the entire sequential command before handing it to Qt. */ + send(operation, fields = {}) { + if (!this.available()) return false; + const request = {operation, project: this.project, request_id: ++this.sequence, ...fields}; + this.request = request; + this.notice = `${operation[0].toUpperCase()}${operation.slice(1)} in progress…`; + this.setBusy(true, "Updating source organization…"); + this.updateControls(); + try { + this.bridge.sourceOrganization(JSON.stringify(request)); + } catch (error) { + // Publication may have occurred; never retry an uncertain mutation. + this.request = null; + this.accept({}, `Command outcome uncertain. Refresh inspection. ${error}`); + this.setBusy(false); + return false; + } + return true; + } + + /** Ignore stale, foreign, duplicate or differently typed acknowledgements. */ + handleEvent(data) { + const request = this.request; + if (!request || data.project !== request.project || data.project !== this.currentProject() + || data.request_id !== request.request_id || data.operation !== request.operation) return; + this.request = null; + if (request.invalidated && request.operation === "preview") { + this.accept({}, "Source inventory changed. Refresh inspection and preview again."); + } else if (data.error) { + this.preview = null; + if (data.conflict || request.operation !== "preview") { + this.accept(data, data.conflict ? "State changed. Refresh inspection and preview again." : ""); + } else { + // Invalid draft: retain it for correction but never reuse its token. + this.notice = data.error; + this.renderPreview(); + } + } else if (request.operation === "preview") { + this.preview = data; + this.notice = data.changed ? "Review the proposed changes before applying." : "No changes to apply."; + this.renderPreview(); + this.element("preview-result").scrollIntoView?.({block: "nearest"}); + } else { + const notice = request.operation === "inspect" ? "Inspection refreshed." + : data.changed ? `Saved source organization revision ${data.revision ?? data.inspection?.revision}.` + : "Source organization unchanged."; + this.lifecycleNotice = ""; + this.lastLifecycle = null; + this.accept(data, notice); + } + this.setBusy(false); + this.updateControls(); + } + + /** A transport error is not proof that a mutation failed or rolled back. */ + transportFailed(message) { + this.lastLifecycle = null; + if (!this.request) return; + this.request = null; + this.accept({}, `Command outcome uncertain. Refresh inspection. ${message || ""}`); + } + + /** Restore declaration input fields from the accepted manifest only. */ + resetSettings() { + const org = this.manifest()?.organization; + this.element("roles").value = (org?.roles || []).join("\n"); + this.element("default-role").value = org?.default_role || ""; + this.element("relation-types").value = JSON.stringify(org?.relation_types || {}, null, 2); + this.element("rules").value = JSON.stringify(org?.automatic_rules || [], null, 2); + for (const id of ["role-mapping", "relation-mapping"]) this.element(id).value = "{}"; + for (const id of ["adopt-type", "adopt-detectors"]) this.element(id).checked = false; + this.savedSettings = this.settingsFingerprint(); + } + + /** Render ordinary settings from the same draft used for core validation. */ + renderOrdinarySettings() { + const roles = this.element("roles").value.split("\n").map((role) => role.trim()).filter(Boolean); + const current = this.element("default-role").value; + const options = [...new Set(roles)].map((role) => [role, role]); + if (!roles.includes(current)) options.unshift([current, current ? `${current} (not declared)` : "Choose default…"]); + this.options("default-role-choice", options, false); + this.element("default-role-choice").value = current; + const host = this.element("rule-controls"); + host.replaceChildren(); + let rules; + try { + rules = JSON.parse(this.element("rules").value); + if (!Array.isArray(rules) || rules.some((rule) => !rule || typeof rule.id !== "string" + || !["apply", "propose"].includes(rule.mode)) + || new Set(rules.map((rule) => rule.id)).size !== rules.length) throw new Error(); + } catch { + host.textContent = "Correct the discovery-rule JSON in Advanced settings first."; + return; + } + // A rule removed in the draft can be restored before saving. Rules + // already absent from the accepted declaration are not guessed. + const declared = this.manifest()?.organization.automatic_rules || []; + const catalog = new Map([...declared, ...rules].map((rule) => [rule.id, rule])); + for (const [id, rule] of catalog) { + const label = document.createElement("label"); + label.className = "source-org-rule"; + label.textContent = `${id} (${rule.relation})`; + const select = document.createElement("select"); + select.className = "source-org-rule-mode"; + for (const [value, name] of [["apply", "Apply automatically"], ["propose", "Propose for review"], ["", "Disabled"]]) { + const option = document.createElement("option"); + option.value = value; option.textContent = name; select.append(option); + } + select.value = rules.find((item) => item.id === id)?.mode || ""; + select.addEventListener("change", () => { + if (!this.available() || this.element("adopt-type").checked) return; + const next = rules.filter((item) => item.id !== id); + if (select.value) { + const index = rules.findIndex((item) => item.id === id); + next.splice(index < 0 ? next.length : index, 0, {...rule, mode: select.value}); + } + this.element("rules").value = JSON.stringify(next, null, 2); + this.invalidatePreview(); + this.renderOrdinarySettings(); + }); + label.append(select); host.append(label); + } + if (!catalog.size) host.textContent = "No discovery rules configured. Add rules in Advanced settings or adopt type defaults."; + this.updateControls(); + } + + /** Detect all draft edits, including currently invalid JSON text. */ + settingsFingerprint() { + return JSON.stringify(this.settingsFields().map((id) => { + const field = this.element(id); + return field.type === "checkbox" ? field.checked : field.value; + })); + } + + /** Check whether closing would abandon staged edits or settings. */ + hasDraft() { + return this.edits.length > 0 || (this.usable() && this.settingsFingerprint() !== this.savedSettings); + } + + /** Build a preview with explicit options, never a replacement manifest. */ + previewFields() { + const org = this.manifest().organization; + const fields = {revision: this.inspection.revision, sha256: this.inspection.sha256, + edits: this.edits.map((edit) => ({...edit}))}; + if (this.element("adopt-type").checked) fields.adopt_type_defaults = true; + else { + const declaration = {roles: this.element("roles").value.split("\n").map((role) => role.trim()).filter(Boolean), + default_role: this.element("default-role").value.trim(), + relation_types: JSON.parse(this.element("relation-types").value), + automatic_rules: JSON.parse(this.element("rules").value)}; + const accepted = {roles: org.roles, default_role: org.default_role, + relation_types: org.relation_types, automatic_rules: org.automatic_rules}; + if (JSON.stringify(declaration) !== JSON.stringify(accepted)) fields.organization = declaration; + } + for (const [id, key] of [["role-mapping", "role_mapping"], ["relation-mapping", "relation_mapping"]]) { + const mapping = JSON.parse(this.element(id).value); + if (!mapping || typeof mapping !== "object" || Array.isArray(mapping)) throw new Error("Mappings must be JSON objects."); + if (Object.keys(mapping).length) fields[key] = mapping; + } + if (this.element("adopt-detectors").checked) fields.adopt_detector_versions = true; + return fields; + } + + /** Ask the core to validate the exact draft and base identity. */ + requestPreview() { + if (!this.available() || !this.usable() || !Number.isSafeInteger(this.inspection.revision)) return; + this.preview = null; + this.renderPreview(); + try { + this.send("preview", this.previewFields()); + } catch (error) { + this.notice = `Invalid declaration or mapping: ${error.message}`; + this.updateControls(); + } + } + + /** Apply only the engine-issued opaque identifier for the current draft. */ + apply() { + if (!this.available() || !this.preview?.changed || !this.preview.preview_id) return; + const preview_id = this.preview.preview_id; + this.preview = null; + this.renderPreview(); + this.send("apply", {preview_id}); + } + + /** Invalidate preview on every edit, not only on successful parsing. */ + invalidatePreview() { + this.preview = null; + this.notice = "Draft changed; preview again before applying."; + this.renderPreview(); + this.updateControls(); + } + + /** Reset all staged changes without invoking the engine. */ + discard() { + this.edits = []; + this.preview = null; + this.resetSettings(); + this.notice = "Draft discarded. Accepted source organization unchanged."; + this.render(); + } + + /** Append ordered commands, leaving the accepted display unchanged. */ + stage(edits) { + if (!this.available() || !this.usable() || !edits.length) return; + this.edits.push(...edits); + this.invalidatePreview(); + this.renderDraft(); + this.renderSelection(); + } + + /** Explicit assignment and reset are distinct commands even for same role. */ + stageRoles(role) { + if (!this.selection().every((path) => this.canEditRole(path))) return; + this.stage(this.selection().map((path) => ({kind: "role", path, role}))); + } + + /** Resolve only currently selected unresolved identities. */ + stageResolutions(restore) { + if (!this.selection().every((path) => this.canResolve(path))) return; + this.stage(this.selection().map((path) => ({kind: "resolve", path, restore}))); + } + + /** A resolution must precede any subsequent edit of an unresolved identity. */ + canResolve(path) { + if (!this.inspection?.binding_matches || !this.selectedPaths.has(path)) return false; + return this.resolutionPaths.has(path) && !this.edits.some((edit) => edit.kind === "resolve" && edit.path === path); + } + + /** Offer roles only for selected, bound paths; core checks all semantics. */ + canEditRole(path) { + return Boolean(this.inspection?.binding_matches && this.selectedPaths.has(path) + && !this.canResolve(path)); + } + + /** Create text-only options to preserve unusual and nested path spellings. */ + options(id, pairs, keep = true) { + const select = this.element(id); + const old = new Set(keep ? Array.from(select.selectedOptions, (item) => item.value) : []); + const fragment = document.createDocumentFragment(); + for (const [value, label] of pairs) { + const option = document.createElement("option"); + option.value = value; + option.textContent = label; + option.selected = old.has(value); + fragment.append(option); + } + select.replaceChildren(fragment); + if (!select.multiple && !old.has(select.value) && pairs.length) select.selectedIndex = 0; + } + + /** Display selected and retained records; never substitute physical paths. */ + renderFiles() { + const manifest = this.manifest(); + if (!manifest) return; + const selected = new Set(this.inspection.selected); + const pending = new Set(this.inspection.pending_roles); + const retained = new Set(this.inspection.retained_versions); + const active = new Set(this.inspection.active_files.map((item) => item.path)); + const paths = new Set([...selected, ...Object.keys(manifest.files)]); + for (const link of [...manifest.relations, ...manifest.suppressed_automatic]) { + paths.add(link.source); paths.add(link.target); + } + const filter = this.element("filter").value.toLowerCase(); + const onlyPending = this.element("pending-only").checked; + this.options("files", [...paths].sort().filter((path) => path.toLowerCase().includes(filter) + && (!onlyPending || pending.has(path)) + && (!this.pendingScope || this.pendingScope.has(path))).map((path) => { + const assignment = Object.hasOwn(manifest.files, path) ? manifest.files[path] : null; + const status = retained.has(path) ? "retained version" + : pending.has(path) ? "pending" : !selected.has(path) ? "inactive" + : !active.has(path) ? "unresolved" : assignment?.origin || "selected"; + return [path, `${path} — ${assignment?.role || "no assignment"} (${status})`]; + })); + this.renderSelection(); + } + + /** Render the current file's incident links and explicit suppression state. */ + renderSelection(selectRole = false) { + const manifest = this.manifest(); + if (!manifest) return; + const paths = this.selection(); + const [path] = paths; + const single = paths.length === 1; + const info = this.element("file-info"); + const assignment = single && Object.hasOwn(manifest.files, path) ? manifest.files[path] : null; + const reason = single && manifest.unresolved.find((item) => item.path === path)?.reason; + if (selectRole) { + const staged = single && [...this.edits].reverse().find((edit) => edit.kind === "role" && edit.path === path); + const role = staged ? staged.role ?? manifest.organization.default_role : assignment?.role; + this.element("role").value = manifest.organization.roles.includes(role) ? role : ""; + } + info.textContent = single ? `${path}: ${assignment ? `${assignment.role} (${assignment.origin})` : "no saved assignment"}${reason ? `; unresolved: ${reason}` : ""}` + : paths.length ? `${paths.length} files selected.` : "Select one or more sources."; + this.element("link-source").textContent = single ? `Selected source: ${path}` : "Select one source."; + this.options("target", [["", "Choose target…"], ...this.inspection.selected.filter((p) => p !== path).map((p) => [p, p])]); + const host = this.element("links"); + host.replaceChildren(); + if (single) { + const active = new Set(this.inspection.active_relations.map((link) => this.edgeKey(link.key))); + for (const link of manifest.relations.filter((edge) => edge.source === path || edge.target === path)) { + const state = active.has(this.edgeKey(link)) ? "active" : "inactive"; + const row = this.linkRow(link, `${state}; ${link.origin}${link.rule ? ` (${link.rule})` : ""}`); + this.linkAction(row, link, "unlink", "Stage disconnect"); + if (link.origin === "rule" && state === "active") this.linkAction(row, link, "link", "Stage manual pin"); + host.append(row); + } + for (const link of manifest.suppressed_automatic.filter((edge) => edge.source === path || edge.target === path)) { + const row = this.linkRow(link, "automatic recreation suppressed"); + this.linkAction(row, link, "restore_suppression", "Stage restore automatic eligibility"); + host.append(row); + } + } + if (!host.children.length) host.textContent = single ? "No stored incident relationships." : "Select one file to inspect its relationships."; + this.updateControls(); + } + + /** Stage either direction of a dependency; core validates the edge. */ + stageLink() { + const paths = this.selection(); + const relation = this.element("relation").value; + const target = this.element("target").value; + const behavior = this.manifest()?.organization.relation_types[relation]?.behavior; + if (!this.available() || paths.length !== 1 || !behavior + || !this.canEditRole(paths[0]) || !this.canEditRole(target) + || target === paths[0]) return; + const incoming = behavior === "dependency" && this.element("direction").value === "incoming"; + this.stage([{kind: "relation", source: incoming ? target : paths[0], + target: incoming ? paths[0] : target, relation, action: "link"}]); + } + + /** A stable edge identity for presentation; the core normalizes links. */ + edgeKey(edge) { return JSON.stringify([edge.source, edge.target, edge.type]); } + + /** Render an edge using the accepted behavior, not a filename heuristic. */ + linkRow(edge, state, organization = this.manifest().organization) { + const row = document.createElement("div"); + row.className = "source-org-edge"; + const text = document.createElement("span"); + const behavior = Object.hasOwn(organization.relation_types, edge.type) + ? organization.relation_types[edge.type].behavior : null; + text.textContent = `${edge.source} ${behavior === "association" ? "↔" : "→"} ${edge.target} — ${edge.type} (${state})`; + row.append(text); + return row; + } + + /** Stage an explicit graph operation using the server's stored identity. */ + linkAction(row, edge, action, label) { + const button = document.createElement("button"); + button.type = "button"; + button.className = "secondary source-org-edit-action"; + button.dataset.requiresBinding = "true"; + button.textContent = label; + button.addEventListener("click", () => this.stage([{kind: "relation", source: edge.source, + target: edge.target, relation: edge.type, action}])); + row.append(button); + } + + /** Summarize the ordered, removable edit queue. */ + renderDraft() { + const host = this.element("draft"); + const fragment = document.createDocumentFragment(); + this.edits.forEach((edit, i) => { + const row = document.createElement("li"); + const label = document.createElement("span"); + label.textContent = edit.kind === "role" ? `${edit.path}: ${edit.role ?? "accepted default"}` + : edit.kind === "resolve" ? `${edit.path}: ${edit.restore ? "restore" : "reset"} retained assignment` + : `${edit.action}: ${edit.source} — ${edit.relation} — ${edit.target}`; + const remove = document.createElement("button"); + remove.type = "button"; remove.className = "secondary source-org-edit-action"; + remove.textContent = "Remove"; + remove.addEventListener("click", () => { + if (!this.available()) return; + this.edits.splice(i, 1); this.invalidatePreview(); this.renderDraft(); this.renderSelection(); + }); + row.append(label, remove); + fragment.append(row); + }); + host.replaceChildren(fragment); + this.element("draft-count").textContent = `(${this.edits.length})`; + this.updateControls(); + } + + /** Describe every changed canonical record, including provenance and rules. */ + diff(before, after) { + const lines = []; + const compare = (title, oldEntries, newEntries) => { + const old = new Map(oldEntries), next = new Map(newEntries); + for (const key of new Set([...old.keys(), ...next.keys()])) { + const a = old.get(key), b = next.get(key); + if (JSON.stringify(a) === JSON.stringify(b)) continue; + lines.push(`${title}: ${key}`, ` Before: ${a === undefined ? "absent" : JSON.stringify(a)}`, + ` After: ${b === undefined ? "absent" : JSON.stringify(b)}`); + } + }; + compare("Source", Object.entries(before.files), Object.entries(after.files)); + for (const [field, label] of [["relations", "Relationship"], ["suppressed_automatic", "Suppression"]]) { + compare(label, before[field].map((edge) => [this.edgeKey(edge), edge]), + after[field].map((edge) => [this.edgeKey(edge), edge])); + } + compare("Unresolved", before.unresolved.map((item) => [item.path, item.reason]), + after.unresolved.map((item) => [item.path, item.reason])); + compare("Settings", Object.entries(before.organization), Object.entries(after.organization)); + compare("Binding", Object.entries(before.source_root), Object.entries(after.source_root)); + return lines; + } + + /** Present validated changes, automatic proposals and diagnostic messages. */ + renderPreview() { + const host = this.element("preview-result"); + const preview = this.preview; + host.classList.toggle("hidden", !preview); + const proposals = this.element("proposals"); + proposals.replaceChildren(); + if (!preview) { + this.element("diff").textContent = ""; + this.element("preview-summary").textContent = ""; + return; + } + const before = preview.inspection.source_organization; + const after = preview.proposed_source_organization; + this.element("preview-summary").textContent = `Revision ${before.revision} → ${after.revision}. ${preview.changed ? "No changes saved yet." : "No persistent changes."}`; + const lines = this.diff(before, after); + const discovery = preview.discovery || {}; + for (const [kind, name] of [["added", "Automatic addition"], ["removed", "Automatic removal"], ["proposed", "Automatic proposal"]]) { + for (const link of discovery[kind] || []) lines.push(`${name}: ${this.edgeKey(link.key)} (${link.rule})`); + } + for (const item of discovery.diagnostics || []) lines.push(`${item.rule}: ${item.target} — ${item.reason}: ${item.detail}`); + if (preview.trace_error) lines.push(`Recording: ${preview.trace_error}`); + this.element("diff").textContent = lines.join("\n") || "No changes or discovery diagnostics."; + for (const link of discovery.proposed || []) { + const row = this.linkRow(link.key, `proposal: ${link.rule}`, after.organization); + this.linkAction(row, link.key, "link", "Stage manual link from proposal"); + proposals.append(row); + } + } + + /** Refresh accepted settings, role choices, staged queue and preview. */ + render() { + const manifest = this.manifest(); + this.element("body").classList.toggle("hidden", !manifest); + if (manifest && this.dialog.open) { + const org = manifest.organization; + const root = this.inspection.source_root; + this.element("identity").textContent = `Revision ${this.inspection.revision}; source root ${root.base}: ${root.path}. ${this.inspection.binding_matches ? "Binding matches." : "Source root is invalid; inspect the project sources directory."}`; + this.element("provenance").textContent = `Accepted default: ${org.default_role}. Type provenance: ${org.derived_from.project_type} ${org.derived_from.project_type_version}. Detector versions: ${JSON.stringify(org.detector_versions)}.`; + this.options("role", [["", "Choose role…"], ...org.roles.map((role) => [role, role])]); + this.options("relation", Object.entries(org.relation_types).map(([id, spec]) => [id, `${id} (${spec.behavior})`])); + this.renderFiles(); + this.renderDraft(); + this.renderOrdinarySettings(); + } else { + for (const id of ["files", "role", "target", "relation", "draft", "links"]) this.element(id).replaceChildren(); + for (const id of ["file-info", "identity", "provenance"]) this.element(id).textContent = ""; + } + this.renderPreview(); + this.updateControls(); + this.decorateWorkspace(); + } + + /** Return active incident edges using the core's accepted inspection. */ + incidentRelations(path) { + return (this.inspection?.active_relations || []).filter(({key}) => + key.source === path || key.target === path); + } + + /** Describe direction, type and origin without inferring graph semantics. */ + relationLabel(path, {key, origin, rule}) { + const behavior = this.manifest()?.organization.relation_types[key.type]?.behavior; + const other = key.source === path ? key.target : key.source; + const direction = behavior === "association" ? "Associated with" + : key.source === path ? "Depends on" : "Has dependent"; + return `${direction} ${other} (${key.type}; ${origin === "rule" ? `automatic: ${rule}` : "manual"})`; + } + + /** Bind menu callbacks to the displayed project and accepted inspection. */ + workspaceActions(path, showMenu) { + if (!this.usable() || !this.available() || this.dialog.open) return []; + const inspection = this.inspection, epoch = this.epoch; + const guard = (action) => () => { + if (this.available() && !this.dialog.open && this.inspection === inspection + && this.epoch === epoch && this.selectedPaths.has(path)) action(); + }; + const stage = (edit) => guard(() => { + if (!this.open("quick", path)) return; + this.stage([edit]); + this.requestPreview(); + }); + const items = []; + if (this.canEditRole(path)) { + const choices = this.manifest().organization.roles.map((role) => [role, + stage({kind: "role", path, role})]); + choices.push(["Reset to accepted default", stage({kind: "role", path, role: null})]); + items.push(["Set role…", guard(() => showMenu(choices))]); + if (this.inspection.selected.some((target) => target !== path && this.canEditRole(target))) { + items.push(["Link to…", guard(() => { + if (this.open("link", path)) this.element("relation").focus(); + })]); + } + } + const incident = this.incidentRelations(path); + if (incident.length) items.push(["Disconnect from…", guard(() => showMenu( + incident.map((link) => [this.relationLabel(path, link), stage({kind: "relation", + source: link.key.source, target: link.key.target, relation: link.key.type, action: "unlink"})]) + ))]); + items.push(["Manage relationships…", guard(() => this.open("files", path))]); + return items; + } + + /** Add presentation-only role labels and active relationship indicators. */ + decorateWorkspace() { + const manifest = this.manifest(); + const pending = new Set(this.inspection?.pending_roles || []); + const retained = new Set(this.inspection?.retained_versions || []); + const active = new Map((this.inspection?.active_files || []).map((item) => [item.path, item])); + // Build one adjacency map for the entire tree, not one scan per row. + const incident = new Map(); + const dependent = new Set(); + for (const link of this.inspection?.active_relations || []) { + const {source, target, type} = link.key; + for (const path of [source, target]) { + if (!incident.has(path)) incident.set(path, []); + incident.get(path).push(link); + } + if (manifest?.organization.relation_types[type]?.behavior === "dependency") dependent.add(source); + } + for (const row of document.querySelectorAll("#workspace-tree .tree-file")) { + row.querySelector(".source-org-role-badge")?.remove(); + row.querySelector(".source-org-chain")?.remove(); + row.classList.remove("source-org-dependent"); + const relative = this.workspaceSource(row.dataset.path || ""); + if (!relative || !manifest) continue; + row.classList.toggle("source-org-dependent", dependent.has(relative)); + const links = incident.get(relative) || []; + if (links.length) { + const chain = document.createElement("button"); + chain.className = "source-org-chain"; + chain.type = "button"; + chain.innerHTML = ''; + chain.title = links.map((link) => this.relationLabel(relative, link)).join("\n"); + chain.setAttribute("aria-label", `Manage relationships for ${relative}: ${chain.title}`); + chain.disabled = !this.available() || this.dialog.open; + // Pointer and keyboard activation of the icon must not open the file. + const inspection = this.inspection; + chain.addEventListener("keydown", (event) => event.stopPropagation()); + chain.addEventListener("click", (event) => { + event.stopPropagation(); + if (inspection === this.inspection) this.open("files", relative); + }); + row.append(chain); + } + const assignment = active.get(relative); + const label = pending.has(relative) ? "Pending role" : retained.has(relative) + ? "Retained version" : assignment?.role; + if (!label) continue; + const badge = document.createElement("span"); + badge.className = "source-org-role-badge" + (pending.has(relative) ? " pending" : ""); + badge.textContent = label; + badge.title = label; + row.append(badge); + } + } + + /** Reflect busy state and pending roles without changing source tree layout. */ + updateControls() { + const available = this.available(); + const openProject = Boolean(this.project && this.project === this.currentProject()); + const usable = this.usable(); + const editable = available && usable; + const binding = this.inspection?.binding_matches; + const pending = this.inspection?.pending_roles?.length || 0; + const summary = !openProject ? "Open a project to edit source organization." + : !usable ? "Source organization unavailable; inspect before editing." + : !binding ? "Source root is invalid; inspect the project sources directory." + : `${this.inspection.selected.length} selected files · ${pending} pending roles`; + this.element("workspace").classList.toggle("hidden", !openProject); + this.element("workspace-status").textContent = [summary, this.lifecycleNotice, + !usable && this.notice].filter(Boolean).join(" "); + this.element("settings-status").textContent = [summary, this.lifecycleNotice].filter(Boolean).join(" "); + this.element("open").disabled = !available; + this.element("settings-open").disabled = !available; + for (const chain of document.querySelectorAll("#workspace-tree .source-org-chain")) + chain.disabled = !available || this.dialog.open; + if (!this.dialog.open) return; + const status = usable && !Number.isSafeInteger(this.inspection.revision) + ? "Revision exceeds the browser's exact integer range; use the Python API to edit." + : this.notice || summary; + this.element("status").textContent = status; + this.element("footer-status").textContent = `${this.edits.length} staged edits · ${status}`; + this.element("dialog").setAttribute("aria-busy", String(Boolean(this.request))); + this.element("close").disabled = Boolean(this.request); + this.element("inspect").disabled = !available; + this.element("initialize").classList.toggle("hidden", this.errorType !== "FileNotFoundError"); + this.element("initialize").disabled = !available || this.errorType !== "FileNotFoundError"; + for (const id of ["filter", "pending-only", "files", "role", "relation", "target", "discard"]) this.element(id).disabled = !editable; + for (const id of this.settingsFields()) { + this.element(id).disabled = !editable || (this.element("adopt-type").checked + && ["roles", "default-role", "relation-types", "rules"].includes(id)); + } + this.element("default-role-choice").disabled = !editable || this.element("adopt-type").checked; + for (const select of this.element("rule-controls").querySelectorAll("select")) + select.disabled = !editable || this.element("adopt-type").checked; + this.element("full-editor").disabled = !available; + const paths = usable ? this.selection() : []; + const roles = editable && paths.length > 0 && paths.every((path) => this.canEditRole(path)); + this.element("stage-role").disabled = !roles || !this.element("role").value; + this.element("reset-role").disabled = !roles; + const resolve = editable && paths.length > 0 && paths.every((path) => this.canResolve(path)); + this.element("restore-file").disabled = !resolve; + this.element("reset-file").disabled = !resolve; + this.element("direction").disabled = !editable || + this.manifest()?.organization.relation_types[this.element("relation").value]?.behavior !== "dependency"; + this.element("stage-link").disabled = !editable || !binding || paths.length !== 1 + || !this.canEditRole(paths[0]) || !this.element("relation").value + || !this.canEditRole(this.element("target").value); + this.element("preview").disabled = !editable || !binding + || !Number.isSafeInteger(this.inspection?.revision); + this.element("apply").disabled = !editable || !this.preview?.changed || !this.preview.preview_id; + for (const button of this.dialog.querySelectorAll(".source-org-edit-action")) { + button.disabled = !editable || (!binding && button.dataset.requiresBinding === "true"); + } + } +} + +globalThis.SourceOrganizationPanel = SourceOrganizationPanel; diff --git a/kilin/gui/web/styles.css b/kilin/gui/web/styles.css index 50cecac8..e66f1c95 100644 --- a/kilin/gui/web/styles.css +++ b/kilin/gui/web/styles.css @@ -1,17 +1,9 @@ :root { - /* Brand colours are shared by the artwork and the application controls. */ - --kilin-orange: #f46b32; - --kilin-yellow: #ffd438; - --kilin-red: #e52935; - --kilin-blue: #377cf6; - --kilin-teal: #14b8a6; - --kilin-ink: #102744; --dropdown-arrow: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='m3 6 5 5 5-5' fill='none' stroke='%23324c64' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); --page: #f3f6fb; --surface: #ffffff; --surface-soft: #fffaf1; --logo-image: url("../icons/kilin-qilin.png"); - --sidebar-head-image: url("../icons/kilin-qilin-head.png"); --wordmark-image: url("../icons/kilin-wordmark-light.svg"); --mosaic-image: url("../icons/kilin-mosaic-accent.svg"); --text: #102744; @@ -58,7 +50,6 @@ --surface: #142b42; --surface-soft: #10253a; --logo-image: url("../icons/kilin-qilin-dark.png"); - --sidebar-head-image: url("../icons/kilin-qilin-head-dark.png"); --wordmark-image: url("../icons/kilin-wordmark-dark.svg"); --text: #eff6ff; --muted: #adc2d5; @@ -103,7 +94,6 @@ --surface: #142b42; --surface-soft: #10253a; --logo-image: url("../icons/kilin-qilin-dark.png"); - --sidebar-head-image: url("../icons/kilin-qilin-head-dark.png"); --wordmark-image: url("../icons/kilin-wordmark-dark.svg"); --text: #eff6ff; --muted: #adc2d5; @@ -189,7 +179,6 @@ button, input, select, textarea { font: inherit; } .topbar #toggle-conversations { margin-right: auto; } .topbar #toggle-workspace { margin-left: auto; } .chat-open .topbar-project { position: absolute; left: 50%; max-width: calc(100% - 96px); transform: translateX(-50%); } -.brand { color: var(--muted); font-size: 13px; font-weight: 750; letter-spacing: .13em; text-transform: uppercase; } .top-status, .hint { color: var(--muted); font-size: 13px; line-height: 1.5; } .readiness-card { border: 1px solid var(--line); border-radius: 14px; padding: 16px; background: var(--surface-soft); } .readiness-card > h3 { margin-top: 0; } @@ -213,7 +202,6 @@ button, input, select, textarea { font: inherit; } .visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } .workspace:has(> .activity:not(.hidden)) .setup, .workspace:has(> .error:not(.hidden)) .setup { margin: 0 auto; padding-bottom: 0; } -.eyebrow { color: var(--eyebrow); font-size: 12px; font-weight: 750; letter-spacing: .14em; } h1 { margin: 10px 0 12px; color: var(--text); font-size: clamp(35px, 6vw, 56px); letter-spacing: -.05em; } .intro { max-width: 520px; margin: 0 0 18px; color: var(--muted); line-height: 1.55; } .models-hint { margin: 0 0 14px; color: var(--control); font-size: 13px; } @@ -330,7 +318,6 @@ input:focus, select:focus, textarea:focus { border-color: var(--focus); box-shad .sidebar-logo:disabled { opacity: .55; } /* In an open project, use the full mascot only, without a wordmark. */ .sidebar-logo-mark { display: block; flex: 0 0 118px; height: 66px; background: var(--logo-image) center / contain no-repeat; } -.sidebar-logo-wordmark { display: none; } .sidebar-section { display: flex; flex-direction: column; min-height: 0; } /* Conversations take the space left, down to three rows; only then does the project list shrink. */ @@ -623,8 +610,6 @@ button.question-attachment:hover, button.question-attachment:focus-visible { bor .model-row > div { min-width: 0; overflow-wrap: anywhere; } .model-row small { display: block; margin-top: 3px; color: var(--muted); font-size: 12px; } .model-row button { min-height: 32px; flex: none; } -.other-models { padding-top: 10px; border-top: 1px solid var(--line); color: var(--control); font-size: 13px; } -.other-models summary { cursor: pointer; } .sync-dialog { width: min(calc(100% - 32px), 620px); padding: 24px; border: 1px solid var(--line); border-radius: 16px; color: var(--text); background: var(--surface); box-shadow: 0 20px 60px rgb(25 36 44 / 18%); } .sync-dialog::backdrop { background: rgb(0 0 0 / 25%); } .sync-dialog h2 { margin: 0 0 8px; font-size: 18px; } @@ -692,7 +677,6 @@ button.question-attachment:hover, button.question-attachment:focus-visible { bor @media (max-width: 1100px) { .app-shell { --left-width: 210px; --right-width: 290px; } } -.other-model-id { padding: 5px 0; overflow-wrap: anywhere; } @media (max-width: 640px) { .app-shell, .app-shell.chat-open, .app-shell.chat-open.sidebar-open { display: block; } .conversations-panel { position: static; width: 100%; height: auto; padding: 10px 18px; border-right: 0; border-bottom: 1px solid var(--line); } @@ -702,7 +686,6 @@ button.question-attachment:hover, button.question-attachment:focus-visible { bor .sidebar-section-action { opacity: 1; } .sidebar-logo { width: 82px; margin: 0 0 6px; padding: 4px; } .sidebar-logo-mark { flex-basis: 74px; height: 58px; } - .sidebar-logo-wordmark { display: none; } .setup-brand { flex-direction: column; align-items: center; padding: 16px 16px 22px; text-align: center; } .setup-brand-figure { flex: none; width: min(100%, 270px); } .setup-brand-copy { width: 100%; } @@ -835,9 +818,6 @@ button.effort-title { display: flex; align-items: center; justify-content: cente .usage-legend span::before { content: ""; display: inline-block; width: 8px; height: 8px; margin-right: 5px; border-radius: 2px; vertical-align: 0; } .usage-legend .read::before { background: var(--usage-read); } .usage-legend .written::before { background: var(--accent); } -.usage-detail { text-align: left; } -.usage-note { margin: 10px 0 2px; padding-top: 10px; border-top: 1px solid var(--line); color: var(--muted); font-size: 11px; line-height: 1.45; } -.usage-note b { color: var(--text); font-weight: 500; } .readiness-heading { display: flex; align-items: center; gap: 10px; cursor: pointer; list-style: none; } .readiness-heading::-webkit-details-marker { display: none; } @@ -1002,3 +982,76 @@ details[open]::details-content { block-size: auto; } .memory-manage-state { font-size: 11px; color: var(--muted); } .memory-manage-action { flex: 0 0 auto; font-size: 12px; } .memory-messages-pages { margin-top: 8px; } + +/* Application-level plugin management, independent of project Tools. */ +#settings-plugins { margin: 12px 0; padding: 0; border: 0; } +.plugin-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } +.plugin-actions button { min-width: 0; } +.plugin-path, .plugin-diagnostic { overflow-wrap: anywhere; white-space: pre-wrap; } +.plugin-candidate { margin-top: 12px; padding: 10px; border: 1px solid var(--line); border-radius: 8px; } +.plugin-candidate p { margin: 6px 0; font-size: 12px; overflow-wrap: anywhere; white-space: pre-wrap; } +.plugin-group { border-top: 1px solid var(--line); padding: 9px 0; } +.plugin-group > summary { cursor: pointer; font-size: 13px; font-weight: 650; } +.plugin-entry { padding: 8px 0; border-bottom: 1px solid var(--line); } +.plugin-entry:last-child { border-bottom: 0; } +.plugin-entry-header { display: flex; justify-content: space-between; gap: 10px; align-items: baseline; flex-wrap: wrap; } +.plugin-entry-header code { font-weight: 650; overflow-wrap: anywhere; } +.plugin-entry .hint { margin: 4px 0; } +.plugin-entry .plugin-actions { margin-top: 6px; } +.plugin-pending { margin: 10px 0; } + +/* Version reporting is read-only and follows the application settings layout. */ +#settings-versions { margin: 12px 0; padding: 0; border: 0; } +.application-version { color: var(--muted); font-size: 12px; margin: 4px 0 0; } +.sidebar-logo { flex-direction: column; } +.sidebar-logo .sidebar-logo-mark { flex: 0 0 auto; width: 118px; } +.version-group { border-top: 1px solid var(--line); padding: 9px 0; } +.version-group > summary { cursor: pointer; font-size: 13px; font-weight: 650; } +.version-row { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; margin: 5px 0; font-size: 12px; } +.version-row > span { flex: 1 1 35%; color: var(--muted); } +.version-row > code { flex: 1 1 65%; min-width: 0; text-align: right; overflow-wrap: anywhere; white-space: pre-wrap; } +.version-entry { padding: 9px 0; border-bottom: 1px solid var(--line); } +.version-entry > strong { overflow-wrap: anywhere; } +.version-entry:last-child { border-bottom: 0; } +@media (max-width: 640px) { + .sidebar-logo .sidebar-logo-mark { width: 74px; } +} + +/* Semantic editing is a separate modal; physical tree/drop targets stay put. */ +.source-org-entry { margin: 6px 0 10px; } +.source-org-entry .hint { margin: 4px 0; overflow-wrap: anywhere; } +.source-org-entry button { width: 100%; font-size: 12px; } +.source-org-dialog { width: min(calc(100% - 32px), 820px); max-height: calc(100vh - 32px); overflow-y: auto; } +.source-org-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; } +.source-org-heading h2 { margin: 0; } +.source-org-dialog details { margin: 12px 0; padding: 10px 12px; border: 1px solid var(--line); border-radius: 9px; } +.source-org-dialog summary { font-size: 14px; font-weight: 650; cursor: pointer; } +.source-org-dialog label:not(.check-row) { display: block; margin: 10px 0 4px; } +.source-org-dialog select, .source-org-dialog input:not([type="checkbox"]), .source-org-dialog textarea { width: 100%; min-width: 0; max-width: 100%; } +.source-org-dialog textarea { padding: 8px; resize: vertical; font: 12px monospace; color: var(--text); background: var(--surface); border: 1px solid var(--line); border-radius: 6px; } +.source-org-dialog select[multiple] { min-height: 145px; } +.source-org-status { overflow-wrap: anywhere; white-space: pre-wrap; font-size: 13px; } +.source-org-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 7px; margin: 10px 0; } +.source-org-actions select { flex: 1 1 180px; width: auto; } +.source-org-actions button { flex: 0 1 auto; } +.source-org-edge, .source-org-list li { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; padding: 6px 0; border-bottom: 1px solid var(--line); font-size: 12px; } +.source-org-edge span, .source-org-list li span { flex: 1 1 220px; min-width: 0; overflow-wrap: anywhere; } +.source-org-list { padding: 0; margin: 8px 0; } +.source-org-dialog pre { padding: 10px; max-height: 40vh; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; border: 1px solid var(--line); border-radius: 6px; background: var(--surface-soft); font-size: 12px; } +.source-org-dialog button { white-space: normal; } +.source-org-role-badge { flex: 0 1 auto; max-width: min(100px, 40%); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--muted); font-size: 10px; border: 1px solid var(--line); border-radius: 5px; padding: 1px 4px; } +.source-org-role-badge.pending { color: var(--accent); } +.source-org-dialog select[multiple] { background-image: none; padding-right: 8px; } +.source-org-footer { position: sticky; bottom: -24px; z-index: 1; padding: 10px 0 12px; margin: 12px 0 -12px; border-top: 1px solid var(--line); background: var(--surface); } +.source-org-footer .hint { flex: 1 1 200px; min-width: 0; max-height: 4.5em; overflow-y: auto; margin: 0; overflow-wrap: anywhere; } + +/* Accepted relationships affect presentation only, not file accessibility. */ +.workspace-panel .tree-file.source-org-dependent { color: var(--muted); } +.workspace-panel .tree-file.source-org-dependent:hover, +.workspace-panel .tree-file.source-org-dependent:focus-visible { color: var(--text); } +.source-org-chain { display: inline-flex; flex: 0 0 auto; align-items: center; justify-content: center; min-height: 0; padding: 2px; border: 0; background: transparent; color: var(--muted); cursor: pointer; } +.source-org-chain:hover, .source-org-chain:focus-visible { color: var(--text); background: var(--hover); } +.source-org-pending-dialog { width: min(calc(100% - 32px), 560px); } +.source-org-dialog .source-org-rule { display: flex; align-items: center; gap: 8px; overflow-wrap: anywhere; } +.source-org-rule select { flex: 0 1 190px; margin-left: auto; } +.context-menu { max-width: calc(100vw - 16px); max-height: calc(100vh - 16px); overflow: auto; overflow-wrap: anywhere; } diff --git a/kilin/gui/web/version_panel.js b/kilin/gui/web/version_panel.js new file mode 100644 index 00000000..bb5244b0 --- /dev/null +++ b/kilin/gui/web/version_panel.js @@ -0,0 +1,241 @@ +/** + * Read-only version reporting. The engine owns the inventory and project + * creation provenance; this controller only correlates and presents them. + */ +"use strict"; + +class VersionPanel { + /** + * Connect the application-wide Versions section to the existing bridge. + * @param bridge Qt web channel object. + * @param isBusy Whether an engine operation is in progress. + * @param project Current open project path, or an empty string. + */ + constructor(bridge, isBusy, project) { + this.bridge = bridge; + this.isBusy = isBusy; + this.project = project; + this.panel = this.element("version-panel"); + this.sequence = 0; + this.request = null; + this.snapshot = null; + this.projectPath = project(); + this.needsRefresh = true; + this.element("version-refresh").addEventListener("click", () => this.refresh()); + this.element("version-copy").addEventListener("click", () => this.copy()); + this.panel.addEventListener("toggle", () => this.refreshIfOpen()); + this.updateControls(); + } + + /** Find a fixed element in the Settings panel. */ + element(id) { return document.getElementById(id); } + + /** Display the version obtained from the executing application. */ + applicationVersion(version) { + for (const element of document.querySelectorAll("[data-kilin-version]")) { + element.textContent = typeof version === "string" ? version : ""; + } + } + + /** Keep requests and clipboard reports separate from stale state. */ + updateControls() { + this.element("version-refresh").disabled = this.isBusy() || Boolean(this.request); + this.element("version-copy").disabled = !this.snapshot || Boolean(this.request); + this.panel.setAttribute("aria-busy", String(Boolean(this.request))); + } + + /** Discard the previous report when the project or plugin state changes. */ + invalidate() { + this.request = null; + this.snapshot = null; + this.needsRefresh = true; + this.element("version-inventory").replaceChildren(); + this.element("version-status").textContent = "Refresh to inspect the current versions."; + this.refreshIfOpen(); + } + + /** Re-read the report when Settings becomes visible again. */ + opened() { this.invalidate(); } + + /** Request fresh state only when the panel is visible and the engine idle. */ + refreshIfOpen() { + const path = this.project(); + if (path !== this.projectPath) { + this.projectPath = path; + this.request = null; + this.snapshot = null; + this.needsRefresh = true; + this.element("version-inventory").replaceChildren(); + } + this.updateControls(); + if (this.panel.open && !this.element("models-panel").classList.contains("hidden") + && this.needsRefresh && !this.isBusy() && !this.request) this.refresh(); + } + + /** Read the inventory without reserving the global answer controls. */ + refresh() { + if (this.isBusy() || this.request) return; + this.needsRefresh = false; + this.snapshot = null; + this.request = { id: String(++this.sequence), project: this.project() }; + this.element("version-inventory").replaceChildren(); + this.element("version-status").textContent = "Reading versions…"; + this.updateControls(); + this.bridge.requestVersions(this.request.id); + } + + /** Drop an interrupted request without automatically retrying it. */ + interrupted() { + this.request = null; + this.snapshot = null; + this.needsRefresh = false; + this.element("version-inventory").replaceChildren(); + this.element("version-status").textContent = "Version report interrupted. Refresh to inspect again."; + this.updateControls(); + } + + /** + * Make a plain-text label/value row. Plugin-controlled values never become + * markup, including diagnostics and local paths. + * @param label Human-readable field name. + * @param value JSON-compatible value or unknown. + * @returns The new row. + */ + row(label, value) { + const row = document.createElement("div"); + row.className = "version-row"; + const name = document.createElement("span"); + name.textContent = label; + const content = document.createElement("code"); + content.textContent = value == null ? "Unknown" + : Array.isArray(value) ? value.join(", ") || "None" : String(value); + row.append(name, content); + return row; + } + + /** + * Build a collapsible group of plain-text fields or plugin records. + * @param title Displayed section heading. + * @param open Whether the section is initially expanded. + * @returns A details element ready for content. + */ + group(title, open = false) { + const group = document.createElement("details"); + group.className = "version-group"; + group.open = open; + const heading = document.createElement("summary"); + heading.textContent = title; + group.append(heading); + return group; + } + + /** + * Display one registered, installed or pending plugin record. + * @param record JSON-compatible record from the core inventory. + * @returns A version entry with its full identity and diagnostics. + */ + entry(record) { + const item = document.createElement("div"); + item.className = "version-entry"; + const heading = document.createElement("strong"); + heading.textContent = record.name ?? record.type_id ?? "Unknown plugin"; + item.append(heading); + for (const [key, value] of Object.entries(record)) { + if (key === "name" || key === "type_id") continue; + const label = key === "api_version" ? "API generation" + : key === "schema_version" ? "Schema generation" + : key === "available" ? "Availability" + : key === "sha256" ? "SHA-256" : key.replaceAll("_", " "); + item.append(this.row(label, key === "available" + ? value ? "Active" : "Unavailable" : value)); + } + return item; + } + + /** + * Present the complete core report, without inferring any plugin version. + * @param snapshot Correlated report with current project provenance. + */ + render(snapshot) { + const info = snapshot.inventory; + const host = this.element("version-inventory"); + host.replaceChildren(); + this.applicationVersion(info.application.version); + host.append(this.row("KíLín application", info.application.version)); + const contracts = this.group("Compatibility contracts", true); + for (const [key, value] of Object.entries(info.contracts)) { + contracts.append(this.row(key.replaceAll("_", " "), value)); + } + host.append(contracts); + for (const [key, label] of [["tools", "Tools"], ["project_types", "Project types"], + ["installed", "Installed user entries"], ["pending", "Pending plugin changes"]]) { + const records = info[key]; + const group = this.group(`${label} (${records.length})`, key === "pending" && records.length > 0); + if (records.length === 0) group.append(this.row("Entries", "None")); + for (const record of records) group.append(this.entry(record)); + host.append(group); + } + const formats = this.group("Persistent formats"); + for (const [key, value] of Object.entries(info.persistent_formats)) { + formats.append(this.row(key.replaceAll("_", " "), value)); + } + host.append(formats); + const provenance = this.group("Project creation provenance", Boolean(snapshot.project)); + if (!snapshot.project) provenance.append(this.row("Project", "No open project")); + else for (const [key, value] of Object.entries(snapshot.creation_provenance)) { + provenance.append(this.row(key.replaceAll("_", " "), value)); + } + host.append(provenance); + const diagnostics = this.group("Inventory diagnostics", Object.keys(info.errors).length > 0); + diagnostics.append(this.row("Plugin directory", info.directory || null)); + for (const [key, value] of Object.entries(info.errors)) diagnostics.append(this.row(key, value)); + host.append(diagnostics); + } + + /** + * Accept only the current request and project, ignoring late replies. + * @param data Engine version-report event. + */ + handleEvent(data) { + if (!this.request || data.request_id !== this.request.id) return; + const request = this.request; + this.request = null; + const origin = data.creation_provenance; + const originTextFields = [ + "created_with_kilin", "created_with_project_type", + "created_with_project_type_version", "created_with_project_type_sha256", + ]; + // The engine validates version semantics; the page requires its complete + // current protocol record rather than presenting an unknown older origin. + const validOrigin = !data.project ? origin === null : ( + origin && typeof origin === "object" && !Array.isArray(origin) && + Object.keys(origin).length === 5 && + originTextFields.every((key) => Object.hasOwn(origin, key) && + typeof origin[key] === "string" && origin[key].trim()) && + Object.hasOwn(origin, "created_with_project_type_schema_version") && + Number.isInteger(origin.created_with_project_type_schema_version) && + origin.created_with_project_type_schema_version > 0 + ); + if (request.project !== this.project() || data.project !== request.project) { + this.element("version-status").textContent = "Project changed. Refresh the version report."; + } else if (data.error || !data.inventory || !validOrigin) { + this.element("version-status").textContent = data.error || "Version report unavailable."; + } else { + this.snapshot = { inventory: data.inventory, project: data.project, + creation_provenance: data.creation_provenance }; + this.render(this.snapshot); + this.element("version-status").textContent = Object.keys(data.inventory.errors).length + ? "Report contains inventory diagnostics." : "Version report ready."; + } + this.updateControls(); + } + + /** Copy the complete snapshot, including collapsed sections, as JSON. */ + copy() { + if (!this.snapshot || this.request) return; + this.bridge.copyText(JSON.stringify(this.snapshot, null, 2)); + this.element("version-status").textContent = "Version report copied."; + } +} + +globalThis.VersionPanel = VersionPanel; diff --git a/kilin/gui/window.py b/kilin/gui/window.py index f03d9022..8b61b57f 100644 --- a/kilin/gui/window.py +++ b/kilin/gui/window.py @@ -7,8 +7,11 @@ The page's local-content access to remote URLs is disabled. This setting is not a network prohibition for the engine, which may download model files. -Stopping a task kills the engine process, discards queued commands, and -starts a fresh process; it is not a resumable model-generation pause. +Stopping an answer requests cooperative cancellation, retaining the engine +and loaded models when cancellation succeeds. If no terminal answer event +arrives within the grace period, the window stops and restarts the engine. +A process-level stop kills the engine, discards queued commands, and starts +a fresh process; it is not a resumable model-generation pause. Key Features ------------ @@ -60,6 +63,7 @@ from PySide6.QtCore import ( QObject, QProcess, + QProcessEnvironment, QRectF, Qt, QTimer, @@ -84,9 +88,12 @@ from PySide6.QtWidgets import QFileDialog, QMainWindow, QMenu, QWidget from kilin._project_creation import cleanup_stopped_creation -from kilin.conversation_format import conversation_state +from kilin.conversation_format import ( + conversation_state, + read_conversation_json, +) +from kilin.plugins._lifecycle import _ensure_runtime from kilin.gui._paths import ( - available_legacy_workspace_directory, default_workspace_directory, saved_workspace_folder, standard_workspace_directory, @@ -109,6 +116,8 @@ # How long Stop waits for the engine to end an answer before restarting it, # as a last resort for an engine that no longer responds. CANCEL_GRACE_MS = 30_000 +# Let the engine finalize its project on EOF before forceful termination. +SHUTDOWN_GRACE_MS = 3000 ICONS = Path(__file__).resolve().parent / "icons" @@ -173,8 +182,6 @@ class ChatBridge(QObject): Choose the folder where KíLín keeps its projects. useDefaultProjectsFolder() Choose the standard projects folder. - useLegacyProjectsFolder() - Reuse the previous installed-app folder, without moving projects. confirmProjectsFolder() Confirm the projects folder in use, as KíLín setup asks. acceptTerms(version) @@ -225,12 +232,12 @@ class ChatBridge(QObject): Delete confirmed workspace source copies and reindex. syncProjectSources(decisions_json) Apply the user's choice for each changed source and reindex. + sourceOrganization(request_json) + Forward a correlated semantic source command to the engine. renameProject(name) Ask the backend to rename the active project directory. - findSavedProject(type_id, workspace) - Refresh Resume for the selected project type and workspace. listSavedProjects(workspace) - List all valid saved projects without loading their models. + List recognized saved projects without loading their models. resumeProject(directory) Open a saved project without changing its source snapshot. resumeProjectConversation(directory, conversation_id) @@ -255,9 +262,9 @@ class ChatBridge(QObject): previewReference(turn_index, citation) Request source context for one saved answer citation. resetConversation() - Archive the current conversation in the backend process. + Open a new empty conversation, retaining the previous one. newConversation() - Create and open a separate empty conversation. + Open an unused empty conversation, creating one if needed. branchConversation(turn_count) Branch the active conversation, keeping its first turns. viewConversation(conversation_id) @@ -299,8 +306,16 @@ class ChatBridge(QObject): saveProjectBehavior(project, scope, intent_id, ...) Submit one revision-checked project behavior editor. - **Tool settings.** + **Application plugins and project tool settings.** + choosePluginPath(kind) + Select a tool package folder or project-type JSON file. + managePlugins(request_json) + Forward a correlated application-level plugin management request. + applicationVersion() + Return the executing application version. + requestVersions(request_id) + Request the complete version inventory and active project origin. requestToolSettings() Ask for the open project's tools and their settings. saveToolSettings(name, settings_json) @@ -395,7 +410,7 @@ def chooseFolderFiles(self, folder: str, purpose: str) -> None: Parameters ---------- folder: str - Name of the workspace folder whose files are requested. + Workspace-relative directory whose files are requested. purpose: str Reason for choosing the files, supplied to the page. @@ -426,7 +441,7 @@ def folderDropped(self, folder: str, paths: list) -> None: @Slot(str) def editFolder(self, request_json: str) -> None: - """Add, replace, or delete files in outputs or templates. + """Edit entries within the user-editable workspace directories. Parameters ---------- @@ -475,29 +490,6 @@ def useDefaultProjectsFolder(self) -> None: return self.projectsFolderChosen.emit(folder) - @Slot() - def useLegacyProjectsFolder(self) -> None: - """Reuse an existing legacy projects folder, without moving data. - - Notes - ----- - Resolve and validate the candidate again when clicked; the folder - may have changed since the frontend received its suggestion. - - """ - - folder = available_legacy_workspace_directory() - if folder is None: - self.event.emit(json.dumps({ - "event": "projects_folder_failed", - "message": ( - "The previous projects folder is no longer available. " - "Choose a folder with Browse instead." - ), - })) - return - self.projectsFolderChosen.emit(str(folder)) - @Slot() def confirmProjectsFolder(self) -> None: """Confirm the projects folder in use, as KíLín setup asks.""" @@ -566,8 +558,7 @@ def requestProjectsFolder(self) -> None: Notes ----- Sends ``projects_folder`` with the effective, standard, and saved - folders; ``missing`` reports an unavailable saved folder, while - ``legacy`` offers an existing old installed-app directory. No + folders; ``missing`` reports an unavailable saved folder. No project is moved or selected without user confirmation. """ @@ -581,7 +572,6 @@ def requestProjectsFolder(self) -> None: ) return saved = saved_workspace_folder() - legacy = available_legacy_workspace_directory() self.event.emit( json.dumps( { @@ -589,7 +579,6 @@ def requestProjectsFolder(self) -> None: "folder": folder, "standard": standard, "saved": saved, - "legacy": str(legacy) if legacy else "", "missing": bool(saved) and not Path(saved).expanduser().is_dir(), } @@ -845,12 +834,12 @@ def previewReference(self, turn_index: int, citation: int) -> None: @Slot() def resetConversation(self) -> None: - """Archive the current conversation in the backend process. + """Open a new empty conversation in the backend process. Notes ----- - The engine reset action creates a new conversation rather than erasing - the previous one. + The engine reset action creates a new registered conversation. The + previous conversation remains selectable and is not archived. """ @@ -858,7 +847,7 @@ def resetConversation(self) -> None: @Slot() def newConversation(self) -> None: - """Create and open a separate empty conversation.""" + """Open an unused empty conversation, creating one if needed.""" self.commandRequested.emit({"action": "new_conversation"}) @@ -1241,6 +1230,79 @@ def saveProjectBehavior( "request_id": request_id, }) + @Slot(str, result=str) + def choosePluginPath(self, kind: str) -> str: + """Select a candidate without importing or installing its code. + + Parameters + ---------- + kind: str + Tool package folder or project_type JSON file. + + Returns + ------- + str + Selected source path, or an empty string on cancellation. + + """ + + if kind == "tool": + return QFileDialog.getExistingDirectory( + None, "Choose a tool package folder" + ) + if kind == "project_type": + path, _ = QFileDialog.getOpenFileName( + None, "Choose a project type", "", "JSON files (*.json)" + ) + return path + return "" + + @Slot(str) + def managePlugins(self, request_json: str) -> None: + """Forward one plugin management request to the engine. + + Parameters + ---------- + request_json: str + JSON request envelope with its operation and explicit trust. + + """ + + self.commandRequested.emit({ + "action": "plugin_management", + "request": json.loads(request_json), + }) + + @Slot(result=str) + def applicationVersion(self) -> str: + """Return the application version without initializing catalogs. + + Returns + ------- + str + Authoritative version of the executing KíLín application. + + """ + + import kilin + + return kilin.__version__ + + @Slot(str) + def requestVersions(self, request_id: str) -> None: + """Forward a read-only version report request to the engine. + + Parameters + ---------- + request_id: str + Frontend correlation identifier. + + """ + + self.commandRequested.emit({ + "action": "versions", "request_id": request_id, + }) + @Slot() def requestToolSettings(self) -> None: """Ask for the open project's tools and their settings.""" @@ -1327,6 +1389,27 @@ def syncProjectSources(self, decisions_json: str) -> None: } ) + @Slot(str) + def sourceOrganization(self, request_json: str) -> None: + """Forward semantic source commands without interpreting edits. + + Parameters + ---------- + request_json: str + JSON-encoded project-bound command from the editor. + + """ + try: + request = json.loads(request_json) + except (ValueError, TypeError): + self.event.emit(json.dumps({ + "event": "error", "message": "Invalid source command JSON.", + })) + return + self.commandRequested.emit({ + "action": "source_organization", "request": request, + }) + @Slot(str) def renameProject(self, name: str) -> None: """Ask the backend to rename the active project directory. @@ -1384,36 +1467,15 @@ def copyText(self, text: str) -> None: QGuiApplication.clipboard().setText(text) - @Slot(str, str) - def findSavedProject(self, type_id: str, workspace: str) -> None: - """Refresh Resume for the selected project type and workspace. - - Parameters - ---------- - type_id: str - Project category string forwarded to the backend engine. - workspace: str - Workspace path string, possibly empty when the engine should - discover or allocate a default. - - """ - - self.commandRequested.emit( - { - "action": "saved_project", - "type_id": type_id, - "workspace": workspace, - } - ) - @Slot(str) def listSavedProjects(self, workspace: str) -> None: - """List all valid saved projects without loading their models. + """List recognized saved projects without loading their models. Parameters ---------- workspace: str - Workspace containing saved projects. + Explicit workspace path, or an empty string to discover saved + projects in the engine workspace root. """ @@ -1602,17 +1664,13 @@ def saved_conversation_turns( continue 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 turns = state.get("turns", []) if state.get("conversation_id") != conversation_id: continue - if not isinstance(turns, list): - return None - if not all(isinstance(turn, dict) for turn in turns): - return None return turns return None @@ -1692,7 +1750,7 @@ def rect(item: dict) -> QRectF: ] def _target(self, event) -> str | None: - """``"sources"``, a folder name, or None at the event position. + """Return the deepest editable drop target at the event position. Parameters ---------- @@ -1709,10 +1767,11 @@ def _target(self, event) -> str | None: position = event.position() if self.drop_target.contains(position): return "sources" - for name, rect in self.folder_targets: - if rect.contains(position): - return name - return None + # Parent and child rectangles overlap. Prefer the deepest visible + # directory, independently of the order supplied by the page. + matches = [name for name, rect in self.folder_targets + if rect.contains(position)] + return max(matches, key=lambda name: name.count("/"), default=None) def _local_drag(self, event) -> bool: """Check whether the drag contains only local file URLs. @@ -1823,7 +1882,7 @@ class ChatWindow(QMainWindow): Methods ------- closeEvent(event) - Stop only this window's backend child process on exit. + Gracefully shut down only this window's child process on exit. Notes ----- @@ -1875,7 +1934,13 @@ def __init__(self) -> None: self._update_icon() # Model work belongs in a child process so Stop can interrupt it. + # Keep the application, not just its replaceable engine, in the + # runtime cohort. Engine recovery must never activate pending code. + plugin_root = _ensure_runtime() self.process = QProcess(self) + environment = QProcessEnvironment.systemEnvironment() + environment.insert("KILIN_PLUGINS_DIR", str(plugin_root)) + self.process.setProcessEnvironment(environment) self.process.setWorkingDirectory(str(ROOT)) self.process.started.connect(self._send_pending) self.process.started.connect(self._process_started) @@ -1990,7 +2055,7 @@ def _start_engine(self) -> None: def _process_started(self) -> None: """Report a successful automatic restart after an unexpected exit.""" - if self._recovery_event is not None: + if not self._closing and self._recovery_event is not None: self.bridge.event.emit(json.dumps(self._recovery_event)) self._recovery_event = None @@ -2005,6 +2070,8 @@ def _send_command(self, command: dict[str, object]) -> None: """ + if self._closing: + return self._pending.append(command) if self.process.state() == QProcess.ProcessState.NotRunning: self._start_engine() @@ -2014,7 +2081,10 @@ def _send_command(self, command: dict[str, object]) -> None: def _send_pending(self) -> None: """Write queued commands as one JSON object per line.""" - if self.process.state() != QProcess.ProcessState.Running: + if ( + self._closing + or self.process.state() != QProcess.ProcessState.Running + ): return while self._pending: command = self._pending.pop(0) @@ -2026,8 +2096,8 @@ def _read_events(self) -> None: Notes ----- Buffers incomplete stdout lines until newline, parses complete JSON - events, and ignores malformed lines. Events arriving during a stop are - discarded. + events, and ignores malformed lines. Events arriving during a stop or + shutdown are discarded. """ @@ -2038,7 +2108,7 @@ def _read_events(self) -> None: try: event = json.loads(line) if ( - not self._stopping + not (self._stopping or self._closing) and isinstance(event, dict) and "event" in event ): @@ -2108,7 +2178,7 @@ def _stop_operation(self) -> None: """ - if self._stopping: + if self._stopping or self._closing: return self._stopping = True self._stopped_pid = int(self.process.processId()) @@ -2198,24 +2268,40 @@ def _process_error(self, _error) -> None: ) ) + def _shutdown_engine(self) -> None: + """End engine input and allow its existing cleanup path to finish. + + Notes + ----- + Window closure and application exit can both invoke this method. + Discard unsent commands, suppress restarts, and deliver EOF after + already written input. The engine closes its session and traces in + its command-loop finally block. An unresponsive child is killed + after the bounded grace period; incomplete recordings remain possible. + + """ + + if self._closing: + return + self._closing = True + self._cancel_timer.stop() + self._pending.clear() + if self.process.state() != QProcess.ProcessState.NotRunning: + self.process.closeWriteChannel() + if not self.process.waitForFinished(SHUTDOWN_GRACE_MS): + if self.process.state() != QProcess.ProcessState.NotRunning: + self.process.kill() + self.process.waitForFinished(SHUTDOWN_GRACE_MS) + def closeEvent(self, event: QCloseEvent) -> None: - """Stop only this window's backend child process on exit. + """Gracefully shut down the backend and close the window. Parameters ---------- event: QCloseEvent Qt event delivered by the corresponding widget event handler. - Notes - ----- - Marks shutdown, kills a running child, waits up to the existing 3000 ms - bound, and delegates the event to QMainWindow. This is process - termination, not a graceful checkpoint request. - """ - self._closing = True - if self.process.state() != QProcess.ProcessState.NotRunning: - self.process.kill() - self.process.waitForFinished(3000) + self._shutdown_engine() super().closeEvent(event) diff --git a/kilin/huggingface.py b/kilin/huggingface.py index 012c4279..c54c5e3a 100644 --- a/kilin/huggingface.py +++ b/kilin/huggingface.py @@ -7,11 +7,11 @@ Repository presence does not prove that a particular revision is complete or loadable. Offline lookup accepts a resolved snapshot only when ``config.json`` -is present. Older ``huggingface_hub`` versions can report partial snapshots -through ``IncompleteSnapshotError``; newer versions may simply return the -cached directory. KíLín supports both behaviors while leaving model-specific -file validation to the downstream loader. Custom cache directories are -accepted by listing and availability checks, not by snapshot/download wrappers. +is present. When ``huggingface_hub`` reports an incomplete snapshot through +``IncompleteSnapshotError``, KíLín applies the same check to its local path. +Model-specific file validation remains the responsibility of the downstream +loader. Custom cache directories are accepted by listing and availability +checks, not by snapshot/download wrappers. Key Features ------------ @@ -71,17 +71,9 @@ from pathlib import Path from huggingface_hub import CacheNotFound, scan_cache_dir, snapshot_download +from huggingface_hub.errors import IncompleteSnapshotError import huggingface_hub.utils.tqdm as _HubTqdm -try: - from huggingface_hub.errors import ( - IncompleteSnapshotError as _IncompleteSnapshotError, - ) -except ImportError: - - class _IncompleteSnapshotError(Exception): - """Compatibility placeholder for newer huggingface_hub versions.""" - __all__ = [ "available_models", @@ -204,10 +196,10 @@ def cached_model_snapshot( """Return a locally cached model snapshot without downloading files. The lookup is delegated to ``huggingface_hub.snapshot_download`` with - ``local_files_only=True``. Across supported Hub versions, KíLín accepts - the resolved snapshot only when ``config.json`` is available. Older Hub - versions may signal a partial snapshot with ``IncompleteSnapshotError``; - newer versions can return the cached snapshot directory directly. + ``local_files_only=True``. The Hub may return a cached directory or + report an incomplete snapshot through ``IncompleteSnapshotError``. + In both cases, KíLín accepts the resolved snapshot only when + ``config.json`` is available. Parameters ---------- @@ -227,7 +219,8 @@ def cached_model_snapshot( ValueError If ``model_id`` is not a non-empty string. FileNotFoundError - If Hugging Face resolves a local snapshot without ``config.json``. + If the resolved local snapshot lacks ``config.json`` or the Hub + cannot locate a cached snapshot. Notes ----- @@ -254,7 +247,8 @@ def cached_model_snapshot( revision=revision, local_files_only=True, ) - except _IncompleteSnapshotError as error: + except IncompleteSnapshotError as error: + # The loader may need only a subset of the repository's files. path = error.snapshot_path snapshot = Path(path) diff --git a/kilin/model_settings.py b/kilin/model_settings.py index c85b9fd6..3358f02c 100644 --- a/kilin/model_settings.py +++ b/kilin/model_settings.py @@ -8,8 +8,8 @@ The GUI may use a different application-wide preference when first saving settings for a project. Once saved, the project value is authoritative. -Older ``effort_levels.json`` router selections are read without mutating the -workspace; the GUI's existing migration workflow owns their removal. +Only the current profile supplies saved router selections. Historical +sidecars are neither read nor modified. Key Features ------------ @@ -100,7 +100,6 @@ _ROUTER_SECTION: Final[str] = "router" _PROFILE_FILE: Final[str] = "profile.ini" -_LEGACY_FILE: Final[str] = "effort_levels.json" _SOURCE_CARD_SECTION: Final[str] = "source_card_generation" _MAX_SOURCE_CARD_TOKENS: Final[int] = 200_000 _SOURCE_CARD_DEFAULTS = load_defaults_section("SOURCE_CARD_GENERATION") @@ -189,26 +188,25 @@ def read_router_model( backend: str Selected calculation backend, ``"mlx"`` or ``"torch"``. default_model: str | None, optional - Initial choice when neither current nor legacy settings specify a - router. GUI project setup may provide its user preference; core - callers default to the packaged model. Defaults to ``None``. + Initial choice when the project profile has no saved router. GUI + setup may provide its user preference; core callers default to the + packaged model. Defaults to ``None``. Returns ------- str - Validated saved router, legacy router, or default in that order. + Validated saved router, supplied initial choice, or packaged default + in that order. Raises ------ ValueError If the backend or a present model identifier is invalid. - json.JSONDecodeError - If the legacy router settings contain malformed JSON. Notes ----- - This reader does not migrate or write project files. Consequently a - model selection made through the GUI is respected by a core-only + This reader does not read historical sidecars or write project files. + A model selection made through the GUI is respected by a core-only session without first initializing a GUI engine. """ @@ -222,15 +220,6 @@ def read_router_model( return validate_model_id( profile.get(_ROUTER_SECTION, backend) ) - legacy_path = directory / _LEGACY_FILE - if legacy_path.is_file(): - legacy = json.loads(legacy_path.read_text(encoding="utf-8")) - if isinstance(legacy, dict): - routers = legacy.get("router") - if isinstance(routers, dict) and isinstance( - routers.get(backend), str - ): - return validate_model_id(routers[backend]) return ( validate_model_id(default_model) if default_model is not None diff --git a/kilin/plugins/__init__.py b/kilin/plugins/__init__.py new file mode 100644 index 00000000..957ba068 --- /dev/null +++ b/kilin/plugins/__init__.py @@ -0,0 +1,195 @@ +"""Discover and inspect trusted KíLín plugins independently of the GUI. + +The runtime catalogs initialize lazily and use one user storage directory. +Placing Python code in its tools folder is an explicit trust decision. +Candidate validation never imports replacement code in the active runtime. +Managed changes are staged and activated before the next runtime cohort. + +Key Features +------------ +- Distribution and user-level discovery, with independent diagnostics. +- Structural checks without executing candidate code. +- Optional runtime validation in a fresh interpreter, not a sandbox. +- Recoverable, deferred installation, updating and removal. + +Module Structure +---------------- +- ``plugin_directory`` resolves the configured user directory. +- ``list_tools`` and ``list_project_types`` inspect the runtime catalogs. +- ``validate_tool`` and ``validate_project_type`` check candidates. +- ``ToolPluginInfo`` describes an individual tool candidate. +- ``install_tool`` and ``install_project_type`` stage new plugins. +- ``update_tool``, ``update_project_type`` and the uninstall operations + stage replacements or removals. +- ``list_installed_plugins``, ``pending_changes`` and + ``cancel_pending_change`` inspect and manage queued changes. + +Examples +-------- +>>> from kilin.plugins import plugin_directory +>>> plugin_directory().is_absolute() +True + +""" + +from __future__ import annotations + +from dataclasses import replace +from pathlib import Path +from typing import TYPE_CHECKING + +from kilin.plugins._discovery import ToolPluginInfo +from kilin.plugins._paths import plugin_directory +from kilin.plugins._management import ( + InstalledPlugin, + PendingPluginChange, + PluginManagementError, + cancel_pending_change, + install_project_type, + install_tool, + list_installed_plugins, + pending_changes, + uninstall_project_type, + uninstall_tool, + update_project_type, + update_tool, +) + +if TYPE_CHECKING: + from kilin.project_type import ProjectTypeInfo + +__all__ = [ + "ToolPluginInfo", "plugin_directory", "list_tools", + "list_project_types", "validate_tool", "validate_project_type", + "InstalledPlugin", "PendingPluginChange", "PluginManagementError", + "install_tool", "update_tool", "uninstall_tool", "install_project_type", + "update_project_type", "uninstall_project_type", "list_installed_plugins", + "pending_changes", "cancel_pending_change", +] + + +def list_tools() -> tuple[ToolPluginInfo, ...]: + """Return immutable information about available and rejected tools. + + Returns + ------- + tuple[ToolPluginInfo, ...] + Registered entries followed by rejected user candidates, including + ID conflicts. Initializes the runtime tool catalog if needed. + + """ + + from kilin.tools._registry import _tool_plugin_infos + + return _tool_plugin_infos() + + +def list_project_types() -> tuple[ProjectTypeInfo, ...]: + """Return available and unavailable project types, including conflicts. + + Returns + ------- + tuple[ProjectTypeInfo, ...] + Immutable diagnostics for all discovered definitions, including + user definitions whose identifiers conflict with bundled ones. + + """ + + from kilin.project_type import _project_type_infos + + return _project_type_infos() + + +def validate_tool(path: Path, *, trusted: bool = False) -> ToolPluginInfo: + """Inspect a tool candidate without changing the active registry. + + Parameters + ---------- + path: pathlib.Path + Candidate tool source folder, named after its descriptor ID. + trusted: bool, optional + Allow importing the candidate in a fresh interpreter. False only + checks layout, syntax and JSON; it never executes candidate code. + + Returns + ------- + ToolPluginInfo + Structural or runtime validation result. The runtime_checked flag + distinguishes an inspected folder from a verified descriptor. + + Notes + ----- + A successful check is not installation, security auditing, or proof + of correct tool execution. Runtime validation executes trusted code + with the user's permissions. + + """ + + from kilin.plugins._validation import _validate_tool + + return _validate_tool(Path(path), trusted=trusted) + + +def validate_project_type( + path: Path, *, bind_tools: bool = True, +) -> ProjectTypeInfo: + """Validate one JSON candidate without adding it to the runtime catalog. + + Parameters + ---------- + path: pathlib.Path + Candidate project-type JSON file. + bind_tools: bool, optional + Resolve required tools against the runtime registry. False checks + only the JSON structure, even if a required tool is absent. + + Returns + ------- + ProjectTypeInfo + Captured implementation version, schema, required tools and any + error. The bound flag distinguishes structural checks from fully + bound types. + + """ + + from kilin.project_type import PROJECT_TYPES_DIR, _type_record + + if type(bind_tools) is not bool: + raise TypeError("bind_tools must be a boolean.") + path = Path(path) + if (PROJECT_TYPES_DIR / path.name).is_file(): + record = _type_record(path, "user", bind_tools=False) + return replace( + record.info, + error=f"Project type ID {path.stem!r} is already registered.", + ) + return _type_record(path, "user", bind_tools=bind_tools).info + + +def _project_plugin_snapshot(type_id: str) -> dict: + """Capture the identities of a type and its configured tool packages. + + Parameters + ---------- + type_id: str + Selected project type in the current runtime. + + Returns + ------- + dict + Portable project-type identity and tool identities keyed by ID. + Unknown identities are None, including synthetic test descriptors. + No source files are rehashed and no absolute paths are recorded. + + """ + + from kilin.project_type import project_type_catalog + from kilin.tools._registry import _tool_identity + + info = project_type_catalog().get(type_id) + if info is None or not info.available: + return {"project_type": None, "tools": {}} + return { + "project_type": info.identity(), + "tools": {name: _tool_identity(name) for name in info.required_tools}, + } diff --git a/kilin/plugins/_discovery.py b/kilin/plugins/_discovery.py new file mode 100644 index 00000000..6031b325 --- /dev/null +++ b/kilin/plugins/_discovery.py @@ -0,0 +1,336 @@ +"""Load trusted user packages and identify captured plugin resources. + +Key Features +------------ +- Separate import namespaces without adding user paths to ``sys.path``. +- Source-only loading avoids stale bytecode after a restart. +- Deterministic SHA-256 identity over relative paths and file contents. +- Immutable diagnostics, including rejected candidates. + +Module Structure +---------------- +- ``ToolPluginInfo`` describes one tool candidate. +- ``_package_digest`` and ``_load_user_package`` implement discovery. + +Examples +-------- +>>> from kilin.plugins import ToolPluginInfo +>>> ToolPluginInfo.__name__ +'ToolPluginInfo' + +""" + +from dataclasses import dataclass +from hashlib import sha256 +from importlib.machinery import ( + PathFinder, SourceFileLoader, SourcelessFileLoader, +) +from importlib.util import module_from_spec, spec_from_file_location +import json +import os +from pathlib import Path +import re +import sys +from types import CodeType, ModuleType + +__all__ = ["ToolPluginInfo"] + +_PREFIX = "kilin.plugins._user_" + + +@dataclass(frozen=True, slots=True) +class ToolPluginInfo: + """Describe a discovered or validated tool package. + + Attributes + ---------- + name: str + Candidate directory name. + path: pathlib.Path + Resolved package location, or the attempted path on failure. + origin: str + Distribution or user storage scope. + version: str | None + Declared individual version, when validated. + api_version: int | None + Declared API generation, when validated. + sha256: str | None + Deterministic digest of captured source and resource files. + error: str | None + Diagnostic for an unavailable candidate. + warnings: tuple[str, ...] + Nonfatal diagnostics, including malformed optional help. + runtime_checked: bool + Whether runtime validation was attempted rather than structural checks + only. A failed runtime check does not imply code was executed. + + """ + + name: str + path: Path + origin: str + version: str | None = None + api_version: int | None = None + sha256: str | None = None + error: str | None = None + warnings: tuple[str, ...] = () + runtime_checked: bool = True + + @property + def available(self) -> bool: + """Report whether the candidate has no validation error.""" + + return self.error is None and self.runtime_checked + + def identity(self) -> dict[str, object]: + """Return portable execution identity without absolute user paths.""" + + return { + "name": self.name, "origin": self.origin, + "version": self.version, "api_version": self.api_version, + "sha256": self.sha256, + } + + +def _scan_error(error: OSError) -> None: + """Propagate a directory traversal failure rather than omit files. + + Parameters + ---------- + error: OSError + Error reported by os.walk. + + """ + + raise error + + +def _package_digest(directory: Path) -> str: + """Hash regular source/resource files with unambiguous path framing. + + Parameters + ---------- + directory: pathlib.Path + Resolved plugin package directory. + + Returns + ------- + str + SHA-256 over sorted relative paths and per-file SHA-256 hashes. + + Raises + ------ + ValueError + If an owned file or directory is linked or not a regular file. + + """ + + paths = [] + for folder, dirs, names in os.walk(directory, onerror=_scan_error): + root = Path(folder) + dirs[:] = sorted(d for d in dirs if d != "__pycache__") + for name in dirs: + if ((root / name).is_symlink() + or (root / name).is_junction()): + raise ValueError(f"Linked plugin directory: {root / name}") + for name in names: + path = root / name + if path.suffix in (".pyc", ".pyo"): + continue + if path.is_symlink() or not path.is_file(): + raise ValueError(f"Invalid plugin file: {path}") + paths.append(path) + digest = sha256() + ordered = sorted(paths, key=lambda p: p.relative_to(directory).as_posix()) + for path in ordered: + relative = path.relative_to(directory).as_posix().encode("utf-8") + content = sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + content.update(block) + digest.update(len(relative).to_bytes(8, "big")) + digest.update(relative) + digest.update(content.digest()) + return digest.hexdigest() + + +def _check_package(directory: Path) -> Path: + """Validate a candidate package without importing it. + + Parameters + ---------- + directory: pathlib.Path + User-supplied package location. + + Returns + ------- + pathlib.Path + Resolved directory with a regular package initializer. + + """ + + if not re.fullmatch(r"[a-z][a-z0-9_]*", directory.name): + raise ValueError(f"Invalid tool package ID: {directory.name!r}.") + if (directory.is_symlink() or directory.is_junction() + or not directory.is_dir()): + raise ValueError(f"Expected a regular plugin directory: {directory}") + directory = directory.resolve() + initial = directory / "__init__.py" + if initial.is_symlink() or not initial.is_file(): + raise ValueError(f"Missing regular package initializer: {initial}") + return directory + + +def _unique_pairs(pairs: list[tuple[str, object]]) -> dict[str, object]: + """Reject duplicate keys in user-owned execution defaults. + + Parameters + ---------- + pairs: list[tuple[str, object]] + JSON object members before conversion to a dictionary. + + Returns + ------- + dict[str, object] + Object without duplicate keys. + + """ + + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate plugin default key: {key!r}.") + result[key] = value + return result + + +def _check_defaults(directory: Path) -> None: + """Check optional user defaults without invoking plugin code. + + Parameters + ---------- + directory: pathlib.Path + Validated candidate package root. + + """ + + path = directory / "defaults.json" + if path.exists(): + value = json.loads(path.read_text(encoding="utf-8"), + object_pairs_hook=_unique_pairs) + if not isinstance(value, dict): + raise ValueError(f"{path} must contain a JSON object.") + # JSON's nonstandard NaN and infinity extensions are not accepted. + json.dumps(value, allow_nan=False) + + +class _SourceLoader(SourceFileLoader): + """Compile plugin source directly instead of trusting bytecode caches.""" + + def get_code(self, fullname: str) -> CodeType: + """Compile the current source for a module in the plugin namespace. + + Parameters + ---------- + fullname: str + Qualified module name selected by the import system. + + Returns + ------- + types.CodeType + Code compiled from the source file. + + """ + + path = self.get_filename(fullname) + return self.source_to_code(self.get_data(path), path) + + +class _UserSourceFinder: + """Apply source-only loading to descendants of user tool packages.""" + + def find_spec(self, fullname, path=None, target=None): + """Find a source module inside an already loaded user package. + + Parameters + ---------- + fullname: str + Requested qualified name. + path: Sequence[str] | None + Parent package search locations. + target: ModuleType | None + Existing module during reload (not supported by KíLín). + + Returns + ------- + ModuleSpec | None + Source-only specification or None for unrelated modules. + + """ + + if not fullname.startswith(_PREFIX) or path is None: + return None + if "__pycache__" in fullname.split("."): + raise ImportError("Plugin bytecode-cache folders are reserved.") + spec = PathFinder.find_spec(fullname, path, target) + if spec is not None and isinstance(spec.loader, SourcelessFileLoader): + raise ImportError("User tools require Python source modules.") + if spec is not None and isinstance(spec.loader, SourceFileLoader): + spec.loader = _SourceLoader(fullname, spec.origin) + return spec + + +_FINDER = _UserSourceFinder() + + +def _discard_user_package(name: str) -> None: + """Remove a failed package and its descendants from the import cache. + + Parameters + ---------- + name: str + Candidate tool identifier. + + """ + + prefix = _PREFIX + name + for key in tuple(sys.modules): + if key == prefix or key.startswith(prefix + "."): + sys.modules.pop(key, None) + + +def _load_user_package(directory: Path) -> ModuleType: + """Import one trusted package under its own qualified name. + + Parameters + ---------- + directory: pathlib.Path + Validated package directory. + + Returns + ------- + ModuleType + Imported package with its package-local relative imports enabled. + + """ + + name = _PREFIX + directory.name + if name in sys.modules: + raise ValueError(f"Plugin namespace already loaded: {name}.") + if _FINDER not in sys.meta_path: + sys.meta_path.insert(0, _FINDER) + initial = directory / "__init__.py" + spec = spec_from_file_location( + name, initial, loader=_SourceLoader(name, str(initial)), + submodule_search_locations=[str(directory)], + ) + if spec is None: + raise ValueError(f"Cannot load plugin package: {directory}.") + module = module_from_spec(spec) + sys.modules[name] = module + try: + spec.loader.exec_module(module) + except BaseException: + _discard_user_package(directory.name) + raise + return module diff --git a/kilin/plugins/_lifecycle.py b/kilin/plugins/_lifecycle.py new file mode 100644 index 00000000..4905def9 --- /dev/null +++ b/kilin/plugins/_lifecycle.py @@ -0,0 +1,292 @@ +"""Coordinate plugin activation across cooperating KíLín processes. + +A short exclusive gate serializes management operations and runtime startup. +Each runtime holds a separate OS-locked lease file until process exit. This +allows concurrent readers on POSIX and Windows without a PID-based registry. +Pending changes activate only before the first lease of a new runtime cohort. +The lease survives a POSIX fork through the inherited open-file description; +executing a new program closes the noninheritable descriptor. + +Key Features +------------ +- Stable coordination files outside discovered plugin packages. +- Crash-released OS locks and deterministic stale-lease collection. +- No disk access on importing the authoring API or resolving its path. + +Module Structure +---------------- +- ``_gate`` serializes changes to management state. +- ``_ensure_runtime`` acquires the process-lifetime lease before discovery. +- ``_active_leases`` checks for cooperating live runtimes under the gate. + +Examples +-------- +>>> from kilin.plugins import plugin_directory +>>> plugin_directory().is_absolute() +True + +""" + +from contextlib import contextmanager +import errno +import os +from pathlib import Path +import stat +from threading import RLock +from time import monotonic, sleep +from typing import Iterator +from uuid import uuid4 + +from kilin.plugins._paths import _runtime_directory + +if os.name == "nt": + import msvcrt +else: + import fcntl + +__all__ = [] + + +class PluginManagementError(RuntimeError): + """Indicate a plugin operation or lifecycle coordination failure.""" + + +_MUTEX = RLock() +_GATE_FD: int | None = None +_LEASE_FD: int | None = None +_LEASE_PATH: Path | None = None +_LEASE_ROOT: Path | None = None +_GATE_TIMEOUT = 15.0 + + +def _linked(path: Path) -> bool: + """Recognize symbolic links and Windows directory junctions. + + Parameters + ---------- + path: pathlib.Path + Entry to inspect without following it. + + Returns + ------- + bool + Whether the entry is a link or junction. + + """ + + return path.is_symlink() or path.is_junction() + + +def _directory(path: Path) -> Path: + """Create or verify an ordinary owned directory. + + Parameters + ---------- + path: pathlib.Path + Directory beneath an already verified parent. + + Returns + ------- + pathlib.Path + The verified directory. + + """ + + if _linked(path): + raise PluginManagementError(f"Linked plugin directory: {path}") + path.mkdir(exist_ok=True) + if _linked(path) or not path.is_dir(): + raise PluginManagementError(f"Expected plugin directory: {path}") + return path + + +def _try_lock(path: Path) -> int | None: + """Lock a stable companion file, returning None only on contention. + + Parameters + ---------- + path: pathlib.Path + Regular coordination file under a verified directory. + + Returns + ------- + int | None + Owned descriptor, or None when another owner holds the lock. + + Notes + ----- + Close descriptors to release locks. In particular do not explicitly + unlock a POSIX lease inherited by another process through fork. + + """ + + if _linked(path): + raise PluginManagementError(f"Linked plugin lock: {path}") + flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) + fd = os.open(path, flags, 0o600) + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise PluginManagementError(f"Invalid plugin lock: {path}") + try: + if os.name == "nt": + os.lseek(fd, 0, os.SEEK_SET) + msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) + else: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError as error: + if (error.errno in (errno.EACCES, errno.EAGAIN, errno.EDEADLK) + or getattr(error, "winerror", None) in (32, 33)): + os.close(fd) + return None + raise + return fd + except BaseException: + os.close(fd) + raise + + +@contextmanager +def _gate(root: Path) -> Iterator[Path]: + """Serialize short filesystem transactions for the captured store. + + Parameters + ---------- + root: pathlib.Path + Canonical user plugin directory. + + Yields + ------ + pathlib.Path + Verified private management directory while the gate is held. + + """ + + global _GATE_FD + with _MUTEX: + if _GATE_FD is not None: + raise PluginManagementError("Recursive plugin management gate.") + try: + root.mkdir(parents=True, exist_ok=True) + state = _directory(root / ".management") + deadline = monotonic() + _GATE_TIMEOUT + while (fd := _try_lock(state / "gate.lock")) is None: + if monotonic() >= deadline: + raise PluginManagementError( + "Plugin management is busy in another process." + ) + sleep(0.025) + _GATE_FD = fd + except OSError as error: + raise PluginManagementError( + f"Cannot coordinate plugin directory {root}: {error}" + ) from error + try: + yield state + finally: + _GATE_FD = None + os.close(fd) + + +def _active_leases(state: Path) -> bool: + """Collect abandoned leases and detect active readers under the gate. + + Parameters + ---------- + state: pathlib.Path + Verified management directory while the gate is held. + + Returns + ------- + bool + Whether any runtime lease remains locked. + + """ + + active = False + leases = _directory(state / "leases") + for path in sorted(leases.iterdir()): + if path.suffix != ".lease" or _linked(path) or not path.is_file(): + raise PluginManagementError(f"Invalid runtime lease: {path}") + if path == _LEASE_PATH and _LEASE_FD is not None: + active = True + continue + fd = _try_lock(path) + if fd is None: + active = True + else: + os.close(fd) + # No new lease can appear at this name while the gate is held. + path.unlink() + return active + + +def _ensure_runtime() -> Path: + """Reserve the current installation for the entire process lifetime. + + Returns + ------- + pathlib.Path + Captured plugin directory, with pending changes applied only if + no earlier runtime is still using it. + + Notes + ----- + Catalog access and desktop startup share this boundary. Do not release + the lease when a workspace or engine closes: lazy imports and resource + reads remain possible until the process exits. + + """ + + global _LEASE_FD, _LEASE_PATH, _LEASE_ROOT + root = _runtime_directory() + with _MUTEX: + if _LEASE_FD is not None: + if root != _LEASE_ROOT: + raise PluginManagementError("Cannot switch plugin stores.") + return root + with _gate(root) as state: + if not _active_leases(state): + from kilin.plugins._management import _activate_pending + + _activate_pending(root, state) + path = _directory(state / "leases") / (uuid4().hex + ".lease") + fd = _try_lock(path) + if fd is None: + raise PluginManagementError("Cannot acquire runtime lease.") + _LEASE_FD, _LEASE_PATH, _LEASE_ROOT = fd, path, root + return root + + +def _before_fork() -> None: + """Avoid inheriting a gate or lease halfway through acquisition.""" + + _MUTEX.acquire() + + +def _after_fork_parent() -> None: + """Resume management in the parent after creating a child.""" + + _MUTEX.release() + + +def _after_fork() -> None: + """Reset the gate mutex but retain any inherited runtime lease. + + The child may still use the parent's imported code. Keep the shared + open-file description until both processes exit; close an inherited + short gate descriptor without unlocking the parent's lock. + + """ + + global _MUTEX, _GATE_FD + _MUTEX = RLock() + if _GATE_FD is not None: + os.close(_GATE_FD) + _GATE_FD = None + + +if hasattr(os, "register_at_fork"): + os.register_at_fork( + before=_before_fork, after_in_parent=_after_fork_parent, + after_in_child=_after_fork, + ) diff --git a/kilin/plugins/_management.py b/kilin/plugins/_management.py new file mode 100644 index 00000000..59a2fb4f --- /dev/null +++ b/kilin/plugins/_management.py @@ -0,0 +1,931 @@ +"""Stage and activate validated user plugin changes without hot reloading. + +Installed packages retain their original paths. A complete staged operation +is published by an atomic directory rename under the lifecycle gate. Only a +runtime starting with no live leases may apply pending operations. Moving the +old entry to a private backup before publishing the replacement allows +recovery after interruption, without exposing incomplete packages. + +Key Features +------------ +- Explicit trusted installation and updating of Python source packages. +- Structural installation of declarative project types in any order. +- Deferred, recoverable activation and nonexecuting inventory inspection. + +Module Structure +---------------- +- ``InstalledPlugin`` and ``PendingPluginChange`` describe on-disk state. +- ``install_tool``, ``update_tool``, ``uninstall_tool`` manage tools. +- The corresponding project-type operations manage JSON definitions. +- ``list_installed_plugins``, ``pending_changes`` and ``cancel_pending_change`` + inspect or cancel operations without initializing the runtime catalog. + +Examples +-------- +>>> from kilin import plugins +>>> callable(plugins.install_tool) +True + +""" + +from dataclasses import asdict, dataclass, replace +from hashlib import sha256 +import json +import os +from pathlib import Path +import re +import shutil +from typing import Final +from uuid import uuid4 + +from kilin.atomic_writes import atomic_write_text +from kilin.plugins._discovery import ( + _check_package, _package_digest, _unique_pairs, +) +from kilin.plugins._lifecycle import ( + PluginManagementError, _directory, _gate, _linked, _try_lock, +) +from kilin.plugins._paths import _runtime_directory +from kilin.plugins._versioning import _is_semver + +__all__ = [ + "InstalledPlugin", "PendingPluginChange", "PluginManagementError", + "install_tool", "update_tool", "uninstall_tool", "install_project_type", + "update_project_type", "uninstall_project_type", "list_installed_plugins", + "pending_changes", "cancel_pending_change", +] + +# The private journal is independent of the application and plugin API. +PENDING_OPERATION_FORMAT_VERSION: Final[int] = 1 + +_FOLDERS = {"tool": "tools", "project_type": "project_types"} +_ACTIONS = ("install", "update", "remove") + + +@dataclass(frozen=True, slots=True) +class InstalledPlugin: + """Identify a user-owned entry without importing or validating it. + + Attributes + ---------- + kind: str + ``tool`` or ``project_type``. + name: str + Package directory name or JSON filename stem. + path: pathlib.Path + Actual entry under the user plugin directory. + + """ + + kind: str + name: str + path: Path + + +@dataclass(frozen=True, slots=True) +class PendingPluginChange: + """Describe a complete queued operation, including activation errors. + + Attributes + ---------- + kind: str + ``tool`` or ``project_type``. + name: str + Plugin identifier. + action: str + ``install``, ``update`` or ``remove``. + sha256: str | None + Validated replacement content digest; None for removal. + api_version: int | None + Validated tool API generation, if applicable. + error: str | None + Most recent recoverable activation failure, if any. + version: str | None + Validated replacement implementation version; None for removal. + schema_version: int | None + Validated project-type schema generation, if applicable. + + Notes + ----- + A published install or update has a complete replacement identity + captured during candidate validation. Removal has no replacement + identity. These fields do not describe the still-active installation. + + """ + + kind: str + name: str + action: str + sha256: str | None = None + api_version: int | None = None + error: str | None = None + version: str | None = None + schema_version: int | None = None + + +def _check_name(kind: str, name: str) -> None: + """Validate an identifier before using it as a filesystem component. + + Parameters + ---------- + kind: str + Plugin category. + name: str + Requested stable identifier. + + """ + + if kind not in _FOLDERS: + raise ValueError(f"Unknown plugin category: {kind!r}.") + pattern = (r"[a-z][a-z0-9_]*" if kind == "tool" + else r"[a-z][a-z0-9_-]{0,31}") + if not isinstance(name, str) or not re.fullmatch(pattern, name): + raise ValueError(f"Invalid {kind} plugin ID: {name!r}.") + + +def _present(path: Path) -> bool: + """Check existence without ignoring a broken symlink. + + Parameters + ---------- + path: pathlib.Path + Managed entry to inspect. + + Returns + ------- + bool + Whether the entry exists, including links. + + """ + + return _linked(path) or path.exists() + + +def _filename(kind: str, name: str) -> str: + """Map a validated identifier to its installed entry name. + + Parameters + ---------- + kind: str + Plugin category. + name: str + Validated identifier. + + Returns + ------- + str + Package directory name or JSON filename. + + """ + + return name if kind == "tool" else name + ".json" + + +def _pending_folder(state: Path, kind: str) -> Path: + """Resolve the queue directory for one category under the gate. + + Parameters + ---------- + state: pathlib.Path + Verified management root. + kind: str + Plugin category. + + Returns + ------- + pathlib.Path + Ordinary category queue directory. + + """ + + return _directory(_directory(state / "pending") / _FOLDERS[kind]) + + +def _target(root: Path, kind: str, name: str) -> Path: + """Resolve an entry without following the installed entry itself. + + Parameters + ---------- + root: pathlib.Path + Captured user plugin directory. + kind: str + Plugin category. + name: str + Validated identifier. + + Returns + ------- + pathlib.Path + Entry under a verified category directory. + + """ + + return _directory(root / _FOLDERS[kind]) / _filename(kind, name) + + +def _check_operation(root: Path, state: Path, + change: PendingPluginChange) -> Path: + """Check installation preconditions immediately before publication. + + Parameters + ---------- + root: pathlib.Path + User plugin directory. + state: pathlib.Path + Verified management root while the gate is held. + change: PendingPluginChange + Proposed operation. + + Returns + ------- + pathlib.Path + Unoccupied queue destination. + + """ + + queue = _pending_folder(state, change.kind) / change.name + if _present(queue): + raise PluginManagementError( + f"A change is already pending for {change.kind} {change.name!r}." + ) + exists = _present(_target(root, change.kind, change.name)) + if change.action == "install" and exists: + raise PluginManagementError( + f"Plugin {change.name!r} is installed; use an explicit update." + ) + if change.action != "install" and not exists: + raise PluginManagementError( + f"No installed user {change.kind} {change.name!r}." + ) + return queue + + +def _copy_candidate(kind: str, source: Path, payload: Path) -> None: + """Copy only ordinary source and resource files into staging. + + Parameters + ---------- + kind: str + Plugin category. + source: pathlib.Path + Original candidate path, never modified. + payload: pathlib.Path + Private staged entry with the original filename. + + """ + + if kind == "tool": + directory = _check_package(source) + if _linked(source) or payload.resolve().is_relative_to(directory): + raise ValueError("Invalid or recursively nested plugin source.") + # Reject special files before copytree can open them. Ignore caches + # exactly as the discovery digest does; never copy generated code. + _package_digest(directory) + shutil.copytree( + directory, payload, symlinks=True, + ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.pyo"), + ) + else: + if _linked(source) or not source.is_file(): + raise ValueError(f"Expected a regular JSON file: {source}") + shutil.copyfile(source, payload) + + +def _validate_payload(change: PendingPluginChange, + payload: Path, *, runtime: bool) -> PendingPluginChange: + """Check staged bytes, never an active installation or cached module. + + Parameters + ---------- + change: PendingPluginChange + Operation identifying the staged candidate. + payload: pathlib.Path + Staged entry with its original identifier. + runtime: bool + Execute trusted tool validation when initially staging. Activation + only rechecks structure, compatibility and the captured digest. + + Returns + ------- + PendingPluginChange + Validated digest, implementation version, and compatibility + generation appropriate to the plugin kind. + + """ + + from kilin.plugins import validate_project_type, validate_tool + from kilin.project_type import PROJECT_TYPE_SCHEMA_VERSION + from kilin.tools import PLUGIN_API_VERSION + + if change.kind == "tool": + info = validate_tool(payload, trusted=runtime) + if info.error is not None: + raise ValueError(info.error) + # Nonexecuting structural validation cannot inspect a Python + # descriptor. Reuse the trusted identity, bound to the same digest. + version = info.version if runtime else change.version + api = info.api_version if runtime else change.api_version + schema = None + if type(api) is not int or api != PLUGIN_API_VERSION: + raise ValueError("Staged tool API is no longer compatible.") + else: + info = validate_project_type(payload, bind_tools=False) + if info.error is not None: + raise ValueError(info.error) + version = info.version + api = None + schema = info.schema_version + if type(schema) is not int or schema != PROJECT_TYPE_SCHEMA_VERSION: + raise ValueError("Staged project-type schema is incompatible.") + if not _is_semver(version): + raise ValueError("Invalid staged implementation version.") + if (not isinstance(info.sha256, str) + or not re.fullmatch(r"[0-9a-f]{64}", info.sha256)): + raise ValueError("Invalid staged replacement digest.") + if change.sha256 is not None: + if info.sha256 != change.sha256: + raise ValueError("Staged plugin changed after validation.") + if (version, api, schema) != (change.version, change.api_version, + change.schema_version): + raise ValueError("Staged plugin identity differs from validation.") + return replace(change, sha256=info.sha256, version=version, + api_version=api, schema_version=schema) + + +def _stage(kind: str, name: str, action: str, + source: Path | None = None) -> PendingPluginChange: + """Validate a private copy and publish one complete pending operation. + + Parameters + ---------- + kind: str + Plugin category. + name: str + Requested identifier. + action: str + Installation, explicit update, or removal. + source: pathlib.Path | None, optional + Candidate path for install/update; None for removal. + + Returns + ------- + PendingPluginChange + Published immutable operation description. + + """ + + _check_name(kind, name) + change = PendingPluginChange(kind, name, action) + root = _runtime_directory() + with _gate(root) as state: + _check_operation(root, state, change) + staging = _directory(state / "staging") + # A stable reservation per category and ID excludes concurrent + # updates even if another runtime activates a published operation + # before the slower validator finishes. + key = sha256(f"{kind}:{name}".encode()).hexdigest()[:32] + operation = staging / ("stage-" + key) + lock = operation.with_suffix(".lock") + fd = _try_lock(lock) + if fd is None: + raise PluginManagementError( + f"A change is being prepared for {kind} {name!r}." + ) + try: + if _present(operation): + if _linked(operation) or not operation.is_dir(): + raise PluginManagementError( + f"Invalid staging directory: {operation}" + ) + _retire(state, operation) + operation.mkdir() + except BaseException: + os.close(fd) + lock.unlink() + raise + # Copy and trusted validation may take time. Do not hold the gate while + # running user Python or while copying an arbitrarily large candidate. + # The separate staging lock distinguishes live work from orphaned copies. + try: + if source is not None: + payload = _directory(operation / "payload") / source.name + _copy_candidate(kind, source, payload) + change = _validate_payload(change, payload, runtime=True) + manifest = {"format": PENDING_OPERATION_FORMAT_VERSION, + **asdict(change)} + (operation / "change.json").write_text( + json.dumps(manifest, sort_keys=True), encoding="utf-8", + ) + with _gate(root) as state: + queue = _check_operation(root, state, change) + if source is not None: + _validate_payload(change, payload, runtime=False) + # Same-filesystem publication: discovery never sees staging. + operation.rename(queue) + finally: + # Release even if gate acquisition fails; the next eligible startup + # can then collect any unpublished copy left behind by this process. + try: + with _gate(root) as state: + os.close(fd) + fd = None + if operation.exists(): + _retire(state, operation) + lock.unlink(missing_ok=True) + finally: + if fd is not None: + os.close(fd) + return change + + +def _read_change(operation: Path, kind: str) -> PendingPluginChange: + """Read and validate a pending journal without executing candidate code. + + Parameters + ---------- + operation: pathlib.Path + Queued operation directory. + kind: str + Category selected by the queue location. + + Returns + ------- + PendingPluginChange + Validated operation and optional activation diagnostic. + + """ + + try: + if _linked(operation) or not operation.is_dir(): + raise ValueError("Expected an ordinary operation directory.") + manifest = operation / "change.json" + if _linked(manifest) or not manifest.is_file(): + raise ValueError("Missing regular operation manifest.") + data = json.loads(manifest.read_text(encoding="utf-8"), + object_pairs_hook=_unique_pairs) + version = data.pop("format") + if (type(version) is not int + or version != PENDING_OPERATION_FORMAT_VERSION): + raise ValueError("Unsupported operation format.") + if set(data) != {"kind", "name", "action", "sha256", "version", + "api_version", "schema_version", "error"}: + raise ValueError("Invalid operation fields.") + change = PendingPluginChange(**data) + _check_name(kind, operation.name) + if (change.kind != kind or change.name != operation.name + or change.action not in _ACTIONS or change.error is not None): + raise ValueError("Operation does not match its queue location.") + if change.action == "remove": + if any(value is not None for value in ( + change.sha256, change.version, change.api_version, + change.schema_version, + )): + raise ValueError("Unexpected removal identity.") + elif (not isinstance(change.sha256, str) + or not re.fullmatch(r"[0-9a-f]{64}", change.sha256)): + raise ValueError("Invalid replacement digest.") + elif not _is_semver(change.version): + raise ValueError("Invalid staged implementation version.") + elif kind == "tool": + if (type(change.api_version) is not int + or change.api_version < 1 + or change.schema_version is not None): + raise ValueError("Invalid staged API generation.") + elif (type(change.schema_version) is not int + or change.schema_version < 1 + or change.api_version is not None): + raise ValueError("Invalid staged schema generation.") + error = operation / "error.txt" + if _present(error): + if _linked(error) or not error.is_file(): + raise ValueError("Invalid activation diagnostic file.") + change = replace(change, error=error.read_text(encoding="utf-8")) + return change + except (OSError, ValueError, TypeError, KeyError, AttributeError) as error: + raise PluginManagementError( + f"Cannot recover plugin operation {operation}: {error}" + ) from error + + +def _queued(state: Path) -> list[tuple[Path, PendingPluginChange]]: + """Return validated queue entries in deterministic activation order. + + Parameters + ---------- + state: pathlib.Path + Verified management root while the gate is held. + + Returns + ------- + list[tuple[pathlib.Path, PendingPluginChange]] + Tool operations first, then project types, sorted by identifier. + + """ + + return [ + (path, _read_change(path, kind)) + for kind in _FOLDERS + for path in sorted(_pending_folder(state, kind).iterdir()) + ] + + +def _retire(state: Path, operation: Path) -> None: + """Atomically remove a completed operation from the visible queue. + + Parameters + ---------- + state: pathlib.Path + Verified management root. + operation: pathlib.Path + Completed or safely canceled operation directory. + + Notes + ----- + Cleanup after retirement can be interrupted without losing the journal + of any uncompleted operation. Retired entries are no longer active. + + """ + + destination = _directory(state / "retired") / uuid4().hex + operation.rename(destination) + shutil.rmtree(destination, ignore_errors=True) + + +def _digest(kind: str, path: Path) -> str: + """Identify a published candidate during interrupted-commit recovery. + + Parameters + ---------- + kind: str + Plugin category. + path: pathlib.Path + Published entry to inspect without executing code. + + Returns + ------- + str + Current content digest. + + """ + + if _linked(path): + raise ValueError(f"Linked published plugin: {path}") + if kind == "tool": + return _package_digest(_check_package(path)) + if not path.is_file(): + raise ValueError(f"Missing published JSON plugin: {path}") + return sha256(path.read_bytes()).hexdigest() + + +def _apply_change(root: Path, state: Path, operation: Path, + change: PendingPluginChange) -> None: + """Apply or recover a queued change with no active runtime leases. + + Parameters + ---------- + root: pathlib.Path + Captured plugin directory. + state: pathlib.Path + Verified management root while the gate is held. + operation: pathlib.Path + Published operation directory. + change: PendingPluginChange + Validated journal entry. + + Notes + ----- + A backup with no target is an interrupted replacement/removal. A + replacement with no payload but the expected target digest has already + committed. Ambiguous states fail closed rather than overwrite data. + + """ + + target = _target(root, change.kind, change.name) + backup = operation / "backup" + payload_dir = operation / "payload" + if _present(payload_dir) and (_linked(payload_dir) + or not payload_dir.is_dir()): + raise PluginManagementError(f"Invalid staged directory: {payload_dir}") + payload = payload_dir / _filename(change.kind, change.name) + old = _present(backup) + installed = _present(target) + staged = _present(payload) + + # Recognize the commit point before attempting any new rename. + if change.action == "remove" and old and not installed: + _retire(state, operation) + return + if change.action != "remove" and not staged and installed: + if ((change.action == "install" and not old) + or (change.action == "update" and old)): + if _digest(change.kind, target) == change.sha256: + _retire(state, operation) + return + if old: + raise PluginManagementError( + f"Ambiguous interrupted replacement: {operation}" + ) + if old and (installed or change.action == "install"): + raise PluginManagementError( + f"Ambiguous interrupted plugin operation: {operation}" + ) + + try: + if change.action == "remove": + if not installed: + raise ValueError("Installed entry is missing.") + target.rename(backup) + else: + if not staged: + raise ValueError("Validated staged entry is missing.") + if change.action == "install" and installed: + raise ValueError("Installation destination already exists.") + if change.action == "update" and not (old or installed): + raise ValueError("Update destination is missing.") + _validate_payload(change, payload, runtime=False) + if change.action == "update" and not old: + target.rename(backup) + payload.rename(target) + except (OSError, ValueError) as error: + # Restore the former entry if publication did not reach its commit + # point. Do not continue into discovery if restoration itself fails. + if _present(backup) and not _present(target): + try: + backup.rename(target) + except OSError as failure: + raise PluginManagementError( + f"Cannot restore plugin backup {backup}: {failure}" + ) from failure + elif _present(backup): + raise PluginManagementError( + f"Ambiguous failed activation: {operation}" + ) from error + atomic_write_text(operation / "error.txt", + f"{type(error).__name__}: {error}") + return + # Once published, recovery must roll forward rather than restore over + # the new installation. Atomic retirement makes cleanup idempotent. + _retire(state, operation) + + +def _collect_staging(state: Path) -> None: + """Retire abandoned private copies without touching a live validator. + + Parameters + ---------- + state: pathlib.Path + Verified management root while the gate is held. + + """ + + staging = _directory(state / "staging") + names = {path.stem if path.suffix == ".lock" else path.name + for path in staging.iterdir()} + for name in sorted(names): + if not re.fullmatch(r"stage-[0-9a-f]{32}", name): + raise PluginManagementError(f"Invalid staging entry: {name}") + operation = staging / name + lock = operation.with_suffix(".lock") + fd = _try_lock(lock) + if fd is None: + continue + try: + if _present(operation): + if _linked(operation) or not operation.is_dir(): + raise PluginManagementError( + f"Invalid staging directory: {operation}" + ) + _retire(state, operation) + finally: + os.close(fd) + lock.unlink(missing_ok=True) + + +def _activate_pending(root: Path, state: Path) -> None: + """Apply complete pending changes before admitting a new reader. + + Parameters + ---------- + root: pathlib.Path + User plugin directory. + state: pathlib.Path + Management root under the exclusive gate, with no active leases. + + """ + + _collect_staging(state) + for operation, change in _queued(state): + _apply_change(root, state, operation, change) + retired = _directory(state / "retired") + for path in retired.iterdir(): + if not _linked(path) and path.is_dir(): + shutil.rmtree(path, ignore_errors=True) + + +def install_tool(path: Path, *, trusted: bool = False) -> PendingPluginChange: + """Queue installation of a new trusted source package. + + Parameters + ---------- + path: pathlib.Path + Candidate package directory named after its descriptor ID. + trusted: bool, optional + Explicit permission to execute its Python code during validation. + Must be True; the default refuses execution. + + Returns + ------- + PendingPluginChange + Validated, published operation; activation is deferred. + + """ + + if trusted is not True: + raise ValueError("Installing Python tools requires trusted=True.") + source = Path(path).absolute() + return _stage("tool", source.name, "install", source) + + +def update_tool(path: Path, *, trusted: bool = False) -> PendingPluginChange: + """Queue replacement of an existing trusted user source package. + + Parameters + ---------- + path: pathlib.Path + Replacement package directory with the existing identifier. + trusted: bool, optional + Explicit permission to execute candidate code; must be True. + + Returns + ------- + PendingPluginChange + Validated, published update; active files are unchanged. + + """ + + if trusted is not True: + raise ValueError("Updating Python tools requires trusted=True.") + source = Path(path).absolute() + return _stage("tool", source.name, "update", source) + + +def uninstall_tool(name: str) -> PendingPluginChange: + """Queue removal of a user package, including a broken candidate. + + Parameters + ---------- + name: str + User-level tool identifier; never a distribution package path. + + Returns + ------- + PendingPluginChange + Published removal, effective at the next eligible startup. + + """ + + return _stage("tool", name, "remove") + + +def install_project_type(path: Path) -> PendingPluginChange: + """Queue installation of a structurally valid project-type JSON file. + + Parameters + ---------- + path: pathlib.Path + Candidate JSON file; its stem is the new identifier. + + Returns + ------- + PendingPluginChange + Published installation; tool binding occurs at runtime discovery. + + """ + + source = Path(path).absolute() + if source.suffix != ".json": + raise ValueError("A project type must be a .json file.") + return _stage("project_type", source.stem, "install", source) + + +def update_project_type(path: Path) -> PendingPluginChange: + """Queue replacement of an existing user project type. + + Parameters + ---------- + path: pathlib.Path + Replacement JSON file with the existing identifier. + + Returns + ------- + PendingPluginChange + Published update; active definitions are unchanged. + + """ + + source = Path(path).absolute() + if source.suffix != ".json": + raise ValueError("A project type must be a .json file.") + return _stage("project_type", source.stem, "update", source) + + +def uninstall_project_type(name: str) -> PendingPluginChange: + """Queue removal of a user JSON definition without touching workspaces. + + Parameters + ---------- + name: str + User-level project-type identifier. + + Returns + ------- + PendingPluginChange + Published removal, effective at the next eligible startup. + + """ + + return _stage("project_type", name, "remove") + + +def list_installed_plugins() -> tuple[InstalledPlugin, ...]: + """Inspect user-owned on-disk entries without loading any plugin. + + Returns + ------- + tuple[InstalledPlugin, ...] + Installed user candidates, including broken entries and conflicts. + Pending installations are listed separately by pending_changes. + + """ + + root = _runtime_directory() + with _gate(root): + result = [] + for kind, folder in _FOLDERS.items(): + for path in sorted( + _directory(root / folder).iterdir() + ): + name = path.name if kind == "tool" else path.stem + if kind == "project_type" and path.suffix != ".json": + continue + if kind == "tool" and not ( + path.is_dir() or _linked(path) + ): + continue + try: + _check_name(kind, name) + except ValueError: + continue + result.append(InstalledPlugin(kind, name, path)) + return tuple(result) + + +def pending_changes() -> tuple[PendingPluginChange, ...]: + """Inspect the durable operation queue without activating it. + + Returns + ------- + tuple[PendingPluginChange, ...] + Pending operations in deterministic order, including validated + replacement identities and recoverable activation errors. No plugin + code is imported by this operation. + + """ + + with _gate(_runtime_directory()) as state: + return tuple(change for _, change in _queued(state)) + + +def cancel_pending_change(kind: str, name: str) -> None: + """Cancel an uncommitted operation without touching installed entries. + + Parameters + ---------- + kind: str + ``tool`` or ``project_type``. + name: str + Identifier of the pending operation. + + Notes + ----- + An interrupted activation with a backup must first be recovered by + startup. Cancellation does not undo a change already published. + + """ + + _check_name(kind, name) + root = _runtime_directory() + with _gate(root) as state: + operation = _pending_folder(state, kind) / name + change = _read_change(operation, kind) + if _present(operation / "backup"): + raise PluginManagementError( + "Recover interrupted activation first." + ) + payload = operation / "payload" / _filename(kind, name) + if (change.action == "install" and not _present(payload) + and _present(_target(root, kind, name))): + raise PluginManagementError( + "Recover published installation first." + ) + _retire(state, operation) diff --git a/kilin/plugins/_paths.py b/kilin/plugins/_paths.py new file mode 100644 index 00000000..a165b68b --- /dev/null +++ b/kilin/plugins/_paths.py @@ -0,0 +1,87 @@ +"""Resolve the user-level plugin directory without creating files. + +Key Features +------------ +- Platform-specific application data, independent of workspaces and Qt. +- An absolute override for explicit installations and isolated tests. +- One captured runtime directory for both plugin categories. + +Module Structure +---------------- +- ``plugin_directory`` resolves the configured location. +- ``_runtime_directory`` captures it on first use by either API. + +Examples +-------- +>>> from kilin.plugins import plugin_directory +>>> plugin_directory().is_absolute() +True + +""" + +from functools import lru_cache +import os +from pathlib import Path +import sys + +__all__ = ["plugin_directory"] + + +def _resolve_directory() -> Path: + """Resolve the user plugin directory without reading any plugin code. + + Returns + ------- + pathlib.Path + Absolute user-level directory; it need not exist. + + Raises + ------ + ValueError + If the explicit KILIN_PLUGINS_DIR override is relative. + + """ + + override = os.environ.get("KILIN_PLUGINS_DIR") + if override: + path = Path(override) + if not path.is_absolute(): + raise ValueError("KILIN_PLUGINS_DIR must be an absolute path.") + return path.resolve() + home = Path.home() + if sys.platform == "darwin": + base = home / "Library" / "Application Support" + elif sys.platform == "win32": + base = Path(os.environ.get("LOCALAPPDATA", "")) + if not base.is_absolute(): + base = home / "AppData" / "Local" + else: + base = Path(os.environ.get("XDG_DATA_HOME", "")) + if not base.is_absolute(): + base = home / ".local" / "share" + return (base / "kilin" / "plugins").resolve() + + +@lru_cache(maxsize=1) +def _runtime_directory() -> Path: + """Capture the directory for the lifetime of this process.""" + + return _resolve_directory() + + +def plugin_directory() -> Path: + """Return the configured directory captured for this process. + + Returns + ------- + pathlib.Path + Absolute user-level directory, not created by this query. + + Notes + ----- + Set the override before first use of this function, the catalogs or + the management API. Changing it afterwards requires a restart. + + """ + + return _runtime_directory() diff --git a/kilin/plugins/_validation.py b/kilin/plugins/_validation.py new file mode 100644 index 00000000..e83b676d --- /dev/null +++ b/kilin/plugins/_validation.py @@ -0,0 +1,168 @@ +"""Validate candidate tool folders without changing the active registry. + +Structural checks inspect files and compile source without executing it. +Trusted runtime checks use a disposable interpreter with the current +KíLín package and Python environment. This is not a security sandbox. + +Key Features +------------ +- Separate nonexecuting and explicitly trusted validation. +- Runtime checks do not replace active plugin modules or cached defaults. +- A bounded worker lifetime and structured diagnostic results. + +Module Structure +---------------- +- ``_validate_tool`` checks a candidate package. +- ``_worker`` imports a trusted candidate in a fresh process. + +Examples +-------- +>>> from kilin.plugins import validate_tool +>>> callable(validate_tool) +True + +""" + +from dataclasses import asdict, replace +import json +import os +from pathlib import Path +import subprocess +import sys +from tempfile import TemporaryDirectory + +from kilin.plugins._discovery import ( + ToolPluginInfo, _check_defaults, _check_package, _package_digest, +) + +__all__: list[str] = [] + +_TIMEOUT = 30 + + +def _structural_check(path: Path) -> ToolPluginInfo: + """Check a candidate's layout, source syntax and defaults JSON. + + Parameters + ---------- + path: pathlib.Path + Candidate package folder, not necessarily installed. + + Returns + ------- + ToolPluginInfo + Structural diagnostic and content digest, without executing code. + + """ + + info = ToolPluginInfo( + path.name, path.absolute(), "user", runtime_checked=False, + ) + try: + directory = _check_package(path) + bundled = Path(__file__).resolve().parents[1] / "tools" + if (bundled / directory.name / "__init__.py").is_file(): + raise ValueError( + f"Tool ID {directory.name!r} is already registered." + ) + digest = _package_digest(directory) + for source in sorted(directory.rglob("*.py")): + if "__pycache__" not in source.relative_to(directory).parts: + compile(source.read_bytes(), str(source), "exec") + _check_defaults(directory) + return replace(info, path=directory, sha256=digest) + except (OSError, ValueError, SyntaxError, RuntimeError) as error: + return replace(info, error=f"{type(error).__name__}: {error}") + + +def _worker(path: Path, output: Path) -> None: + """Import and register a trusted candidate in the disposable process. + + Parameters + ---------- + path: pathlib.Path + Candidate package folder. + output: pathlib.Path + Private result file used instead of the plugin's stdout. + + """ + + from kilin.tools._registry import _register_user_tool + + try: + tool = _register_user_tool(path) + info = tool._info + except (Exception, SystemExit) as error: + info = ToolPluginInfo( + path.name, path, "user", + error=f"{type(error).__name__}: {error}", + ) + data = asdict(info) + data["path"] = str(info.path) + output.write_text(json.dumps(data), encoding="utf-8") + + +def _validate_tool(path: Path, *, trusted: bool) -> ToolPluginInfo: + """Perform structural and optionally isolated runtime validation. + + Parameters + ---------- + path: pathlib.Path + Candidate package location. + trusted: bool + Explicit permission to execute candidate code in a subprocess. + + Returns + ------- + ToolPluginInfo + Validation outcome, not a change to the runtime catalog. + + """ + + if type(trusted) is not bool: + raise TypeError("trusted must be a boolean.") + info = _structural_check(path) + if info.error is not None or not trusted: + return info + script = ( + "import sys; from pathlib import Path; " + "sys.path.insert(0, sys.argv[1]); " + "from kilin.plugins._validation import _worker; " + "_worker(Path(sys.argv[2]), Path(sys.argv[3]))" + ) + host = Path(__file__).resolve().parents[2] + try: + with TemporaryDirectory(prefix="kilin-plugin-check-") as temp: + output = Path(temp).resolve() / "result.json" + # A candidate may accidentally query a runtime catalog during + # import. Never let the disposable worker activate or reserve + # the real user's pending installation. + env = dict(os.environ, KILIN_PLUGINS_DIR=str( + output.parent / "plugins" + )) + process = subprocess.run( + [sys.executable, "-B", "-c", script, str(host), + str(info.path), str(output)], + cwd=temp, env=env, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, timeout=_TIMEOUT, check=False, + ) + if process.returncode != 0 or not output.is_file(): + raise ValueError( + "Plugin validation worker did not return a result " + f"(exit status {process.returncode})." + ) + data = json.loads(output.read_text(encoding="utf-8")) + data["path"] = Path(data["path"]) + data["warnings"] = tuple(data["warnings"]) + result = ToolPluginInfo(**data) + if result.error is not None: + return replace(info, error=result.error, + runtime_checked=True) + if result.sha256 != info.sha256: + raise ValueError("Plugin changed during validation.") + return result + except subprocess.TimeoutExpired: + error = f"Plugin runtime validation exceeded {_TIMEOUT} seconds." + except (OSError, ValueError, TypeError, KeyError) as failure: + error = f"{type(failure).__name__}: {failure}" + return replace(info, error=error, runtime_checked=True) diff --git a/kilin/plugins/_versioning.py b/kilin/plugins/_versioning.py new file mode 100644 index 00000000..d88d14d8 --- /dev/null +++ b/kilin/plugins/_versioning.py @@ -0,0 +1,91 @@ +"""Validate independent tool and project-type implementation versions. + +The plugin contracts use strict Semantic Versioning 2.0.0, independent of +KíLín's PEP 440 application release and integer compatibility generations. +Validation never infers a missing version or normalizes its spelling. + +Key Features +------------ +- Exactly three ASCII numeric components without leading zeroes. +- Optional SemVer prerelease and build identifiers. +- Shared validation without loading a runtime catalog. + +Module Structure +---------------- +- ``_is_semver`` checks a candidate declaration without raising. +- ``_require_semver`` reports an invalid declaration at its owning field. + +Examples +-------- +>>> from kilin.plugins._versioning import _is_semver +>>> _is_semver("0.1.0-beta.2+build.5") +True +>>> _is_semver("0.1.0b2") +False + +""" + +from __future__ import annotations + +import re + +__all__ = [] + +_NUMBER = r"(?:0|[1-9][0-9]*)" +# Numeric prerelease identifiers cannot have leading zeroes. Identifiers +# containing a letter or hyphen are nonnumeric and may start with zero. +_PRERELEASE = rf"(?:{_NUMBER}|[0-9]*[A-Za-z-][0-9A-Za-z-]*)" +_BUILD = r"[0-9A-Za-z-]+" +_SEMVER = re.compile( + rf"{_NUMBER}\.{_NUMBER}\.{_NUMBER}" + rf"(?:-{_PRERELEASE}(?:\.{_PRERELEASE})*)?" + rf"(?:\+{_BUILD}(?:\.{_BUILD})*)?" +) + + +def _is_semver(value: object) -> bool: + """Check a declaration against Semantic Versioning 2.0.0. + + Parameters + ---------- + value: object + Untrusted declaration, without coercion or whitespace stripping. + + Returns + ------- + bool + Whether the value is a valid SemVer string. + + """ + + return isinstance(value, str) and _SEMVER.fullmatch(value) is not None + + +def _require_semver(value: object, where: str) -> str: + """Return a valid declared implementation version or report failure. + + Parameters + ---------- + value: object + Candidate version string. + where: str + Component and field location for the validation diagnostic. + + Returns + ------- + str + The original version string, unchanged. + + Raises + ------ + ValueError + If the declaration is missing or is not a valid SemVer string. + + """ + + if not _is_semver(value): + raise ValueError( + f"{where} requires an explicit Semantic Versioning 2.0.0 " + f"version; got {value!r}." + ) + return value diff --git a/kilin/project.py b/kilin/project.py index 2e8d1d48..fdc3c073 100644 --- a/kilin/project.py +++ b/kilin/project.py @@ -26,7 +26,9 @@ - **Validated profiles** Read backend, model, query-format, scan, chunk, retrieval, and generation - settings. + settings. Require every current core field and the immutable creation + provenance captured independently of the editable profile. Missing + persisted fields are errors, not requests for creation defaults. - **GUI-independent workspace layout** @@ -43,9 +45,9 @@ Module Structure ---------------- -- ``PROJECT_TYPE_IDS`` +- ``project_type_ids`` - All packaged type IDs in deterministic filename order, not an enum. + Available project-type IDs in catalog order, not an enum. - ``ProjectTypeId`` @@ -55,9 +57,13 @@ Settings loaded from one project's profile.ini. +- ``ProjectCreationProvenance`` + + Immutable application and project-type identity captured at creation. + - ``QAProject`` - Resolved paths and settings for one KíLín project. + Resolved paths, settings, and creation provenance for one project. - ``initialize_project`` @@ -105,14 +111,13 @@ >>> import kilin.project >>> profile = kilin.project.default_project_profile( -... kilin.PROJECT_TYPE_IDS[0] +... kilin.project_type_ids()[0] ... ) """ from __future__ import annotations -from collections.abc import Mapping from configparser import ConfigParser from contextlib import contextmanager from dataclasses import asdict, dataclass @@ -122,9 +127,13 @@ from pathlib import Path import re import shutil -from typing import Final, Iterator, cast +from tempfile import NamedTemporaryFile +from typing import Callable, Final, Iterator, Literal, TYPE_CHECKING, cast from kilin.atomic_writes import atomic_create_text, atomic_write_text +from kilin._source_ownership import ( + read_mirror_manifest, source_ownership, validate_mirror_manifest, +) from kilin._project_creation import ( ProjectAlreadyExistsError, WorkspaceOccupiedError, @@ -144,12 +153,17 @@ DEFAULT_EMBEDDING_MODEL_MLX, DEFAULT_EMBEDDING_MODEL_TORCH, ) -from kilin.project_type import ProjectTypeId, load_project_types +from kilin.plugins._versioning import _require_semver +from kilin.project_type import ( + _ID_PATTERN, ProjectTypeId, load_project_types, project_type, + project_type_catalog, +) from kilin.project_layout import ( CORE_PROJECT_FOLDERS, ensure_project_folders, install_project_resources, plan_project_layout, + validate_project_sources, ) from kilin.query_formats import ( QUERY_FORMAT_CHOICES, @@ -158,7 +172,6 @@ ) from kilin.repository import ( build_repository_manifest, - compare_repository_manifests, normalize_extensions, scan_repository, ) @@ -172,10 +185,15 @@ from kilin.trace_logging import NullTraceLogger, TraceSink from kilin.workspace_resources import PROJECT_SOURCES_DIRECTORY +if TYPE_CHECKING: + from kilin.source_manifest import SourceLifecycleResult + + __all__ = [ - "PROJECT_TYPE_IDS", + "project_type_ids", "ProjectTypeId", "ProjectProfile", + "ProjectCreationProvenance", "QAProject", "initialize_project", "ProjectAlreadyExistsError", @@ -191,22 +209,6 @@ # Deleted projects are moved here, beside the projects themselves. DELETED_PROJECTS_FOLDER: Final[str] = ".deleted" -# Loading rejects an empty or invalid registry before projects can open. -PROJECT_TYPE_IDS: Final[tuple[ProjectTypeId, ...]] = tuple( - load_project_types() -) - -_PROJECT_EXTENSIONS: Final[dict[ProjectTypeId, str]] = { - type_id: ", ".join(item.extensions) - for type_id, item in load_project_types().items() -} -_DEFAULT_FILE_LIMITS: Final[dict[ProjectTypeId, int]] = { - type_id: item.max_file_bytes - for type_id, item in load_project_types().items() -} -# Registered type identifiers as listed in error messages. -_TYPE_ID_CHOICE_TEXT: Final[str] = ", ".join(PROJECT_TYPE_IDS) - # These defaults are used only when generating a missing project profile; # existing ``profile.ini`` values always take precedence. _PROFILE_DEFAULTS = load_defaults_section("PROJECT_PROFILE") @@ -300,7 +302,6 @@ def _default_profile_text( type_id: ProjectTypeId, - source: str, extensions: str, ) -> str: """Format the built-in profile with shared core defaults. @@ -309,8 +310,6 @@ def _default_profile_text( ---------- type_id: ProjectTypeId Project category written to the profile. - source: str - Source path written to the profile. extensions: str Comma-separated source extensions written to the profile. @@ -335,9 +334,9 @@ def _default_profile_text( ) return _DEFAULT_PROFILE.format( type_id=type_id, - source=source, + source=PROJECT_SOURCES_DIRECTORY, extensions=extensions, - max_file_bytes=_DEFAULT_FILE_LIMITS[type_id], + max_file_bytes=definition.max_file_bytes, allow_download=str(_PROFILE_ALLOW_DOWNLOAD).lower(), target_tokens=_PROFILE_TARGET_TOKENS, max_tokens=_PROFILE_MAX_TOKENS, @@ -356,13 +355,51 @@ def _default_profile_text( ) +def project_type_ids() -> tuple[ProjectTypeId, ...]: + """Return available project identifiers without an import-time snapshot. + + Returns + ------- + tuple[ProjectTypeId, ...] + Available project-type identifiers in catalog order. + + """ + + return tuple(load_project_types()) + + +def _require_project_type(type_id: ProjectTypeId, field: str) -> None: + """Reject unknown or unavailable types before touching a workspace. + + Parameters + ---------- + type_id: ProjectTypeId + Type requested for creation or read from a saved profile. + field: str + Setting name used for validation diagnostics. + + """ + + available = project_type_ids() + if type_id in available: + return + try: + project_type(type_id) + except ValueError as error: + raise ValueError( + f"{field} must be one of: {', '.join(available) or ''}. " + f"{error}" + ) from error + raise ValueError(f"{field} is not available: {type_id!r}.") + + def default_project_profile(type_id: ProjectTypeId) -> ProjectProfile: """Return the default profile for one registered project type. Parameters ---------- type_id: ProjectTypeId - Registered project-type identifier from ``PROJECT_TYPE_IDS``. + Registered project-type identifier from ``project_type_ids()``. Returns ------- @@ -372,7 +409,7 @@ def default_project_profile(type_id: ProjectTypeId) -> ProjectProfile: Raises ------ ValueError - If ``type_id`` is not one of ``PROJECT_TYPE_IDS``. + If ``type_id`` is not one of ``project_type_ids()``. Notes ----- @@ -381,12 +418,11 @@ def default_project_profile(type_id: ProjectTypeId) -> ProjectProfile: """ - if type_id not in PROJECT_TYPE_IDS: - raise ValueError(f"type_id must be one of: {_TYPE_ID_CHOICE_TEXT}.") - extensions = _PROJECT_EXTENSIONS[type_id] + _require_project_type(type_id, "type_id") + extensions = ", ".join(load_project_types()[type_id].extensions) parser = ConfigParser() parser.read_string( - _default_profile_text(type_id, PROJECT_SOURCES_DIRECTORY, extensions) + _default_profile_text(type_id, extensions) ) return _read_profile(parser) @@ -487,8 +523,8 @@ class ProjectProfile: ---------- type_id: ProjectTypeId Registered project-type identifier. - source: str - Source folder, relative to the project or absolute. + source: "sources" + Canonical project source directory; no other value is supported. extensions: tuple[str, ...] File extensions included during scanning. max_file_bytes: int @@ -524,15 +560,15 @@ class ProjectProfile: block_unrequested_cjk: bool Whether to suppress unsolicited Chinese, Japanese, and Korean script tokens on a best-effort basis, using original user text for - permission. Profiles without the setting use - ``PROJECT_PROFILE.BLOCK_UNREQUESTED_CJK``. + permission. Required in every saved profile; the packaged default + is used only when creating a new project. Attributes ---------- type_id: ProjectTypeId Registered project-type identifier. - source: str - Source folder, relative to the project or absolute. + source: "sources" + Canonical project source directory; no other value is supported. extensions: tuple[str, ...] File extensions included during scanning. max_file_bytes: int @@ -568,8 +604,8 @@ class ProjectProfile: block_unrequested_cjk: bool Whether to suppress unsolicited Chinese, Japanese, and Korean script tokens on a best-effort basis, using original user text for - permission. Profiles without the setting use - ``PROJECT_PROFILE.BLOCK_UNREQUESTED_CJK``. + permission. Required in every saved profile; the packaged default + is used only when creating a new project. Methods ------- @@ -581,14 +617,16 @@ class ProjectProfile: Notes ----- Values normally come from the validated INI reader. Direct dataclass - construction is not validated. Model accessors return the configured MLX - value only for backend="mlx" and the PyTorch value otherwise. Changes - require constructing a new profile; the dataclass fields are frozen. + construction requires every field and validates the source layout name. + Other setting values are validated by the INI reader. Model accessors + return the configured MLX value only for backend="mlx" and the PyTorch + value otherwise. Changes require constructing a new profile; the + dataclass fields are frozen. """ type_id: ProjectTypeId - source: str + source: Literal["sources"] extensions: tuple[str, ...] max_file_bytes: int backend: Backend @@ -605,7 +643,20 @@ class ProjectProfile: thinking: bool temperature: float max_new_tokens: int | None - block_unrequested_cjk: bool = _PROFILE_BLOCK_UNREQUESTED_CJK + block_unrequested_cjk: bool + + def __post_init__(self) -> None: + """Reject noncanonical source names in directly constructed profiles. + + Raises + ------ + ValueError + If the source directory name is not exactly ``sources``. + + """ + + if self.source != PROJECT_SOURCES_DIRECTORY: + raise ValueError("project.source must be exactly 'sources'.") def chat_model(self, backend: SelectedBackend) -> str: """Return the chat model configured for one selected backend. @@ -648,6 +699,37 @@ def embedding_model(self, backend: SelectedBackend) -> str: ) +@dataclass(frozen=True, slots=True) +class ProjectCreationProvenance: + """Describe the immutable origin of a project, not its current settings. + + Attributes + ---------- + created_with_kilin: str + Application version of the executing runtime at creation. + created_with_project_type: ProjectTypeId + Identifier of the originating project type. + created_with_project_type_version: str + Implementation version of the captured project-type definition. + created_with_project_type_schema_version: int + Schema generation of the captured definition. + created_with_project_type_sha256: str + SHA-256 digest of the captured definition's exact JSON bytes. + + Notes + ----- + These fields are historical evidence, not a request to pin a plugin or + require compatibility with a particular runtime. + + """ + + created_with_kilin: str + created_with_project_type: ProjectTypeId + created_with_project_type_version: str + created_with_project_type_schema_version: int + created_with_project_type_sha256: str + + @dataclass(frozen=True, slots=True) class QAProject: """Resolved paths and settings for one KíLín project. @@ -664,6 +746,8 @@ class QAProject: Folder containing persistent conversation records. profile: ProjectProfile Parsed project settings. + creation_provenance: ProjectCreationProvenance + Required recorded origin, captured when the project was created. Attributes ---------- @@ -677,6 +761,8 @@ class QAProject: Folder containing persistent conversation records. profile: ProjectProfile Parsed project settings. + creation_provenance: ProjectCreationProvenance + Recorded origin, independent of the editable profile. """ @@ -685,11 +771,29 @@ class QAProject: indexes: Path logs: Path profile: ProjectProfile + creation_provenance: ProjectCreationProvenance + + def __post_init__(self) -> None: + """Require a recorded creation identity for every project object. + + Raises + ------ + TypeError + If creation provenance is absent or is not the declared record. + + """ + + if not isinstance(self.creation_provenance, ProjectCreationProvenance): + raise TypeError( + "creation_provenance must be a ProjectCreationProvenance." + ) def initialize_project( directory: str | Path, type_id: ProjectTypeId, + *, + on_organization: Callable[[SourceLifecycleResult], None] | None = None, ) -> QAProject: """Create one project in a nonexistent or empty directory. @@ -702,6 +806,9 @@ def initialize_project( Registered project type. Every type gets the same ``sources/`` subdirectory. + on_organization: Callable[[SourceLifecycleResult], None] | None, optional + Receive the semantic outcome after publication. Defaults to None. + Returns ------- QAProject @@ -728,10 +835,9 @@ def initialize_project( """ - if type_id not in PROJECT_TYPE_IDS: - raise ValueError(f"type_id must be one of: {_TYPE_ID_CHOICE_TEXT}.") + _require_project_type(type_id, "type_id") root = destination_path(directory) - return _initialize_profile(root, type_id) + return _initialize_profile(root, type_id, on_organization=on_organization) class _InitializationJournal: @@ -804,30 +910,63 @@ def rollback(self) -> None: continue +def _creation_provenance( + type_id: ProjectTypeId, +) -> ProjectCreationProvenance: + """Capture the executing application and selected catalog identity. + + Parameters + ---------- + type_id: ProjectTypeId + Available project type selected for creation. + + Returns + ------- + ProjectCreationProvenance + Complete origin of the new project. + + Raises + ------ + ValueError + If the application version is malformed or the catalog does not + provide a complete available identity. + + """ + + import kilin + + info = project_type_catalog().get(type_id) + if (info is None or not info.available or info.version is None + or info.schema_version is None or info.sha256 is None): + raise ValueError(f"Missing creation identity for {type_id!r}.") + app = _require_creation_application_version(kilin.__version__) + return ProjectCreationProvenance( + app, type_id, info.version, info.schema_version, info.sha256, + ) + + def _prepared_profile( type_id: ProjectTypeId, - source: str, settings: dict[str, object] | None, -) -> tuple[str, ProjectProfile]: +) -> tuple[str, ProjectProfile, ProjectCreationProvenance]: """Validate and render the complete profile before filesystem writes. Parameters ---------- type_id: ProjectTypeId Validated project-type identifier. - source: str - Initial source folder recorded in the profile. settings: dict[str, object] | None Optional overrides accepted by ``configure_project``. Returns ------- - tuple[str, ProjectProfile] - Final profile text and parsed settings. + tuple[str, ProjectProfile, ProjectCreationProvenance] + Final profile text, parsed settings, and captured creation identity. """ - text = _default_profile_text(type_id, source, _PROJECT_EXTENSIONS[type_id]) + extensions = ", ".join(load_project_types()[type_id].extensions) + text = _default_profile_text(type_id, extensions) parser = ConfigParser() parser.read_string(text) if settings: @@ -839,10 +978,14 @@ def _prepared_profile( if key == "extensions" and isinstance(value, (list, tuple)): value = ", ".join(value) parser.set(section, option, str(value)) - stream = StringIO() - parser.write(stream) - text = stream.getvalue() - return text, _read_profile(parser) + profile = _read_profile(parser) + provenance = _creation_provenance(type_id) + parser["metadata"] = { + key: str(value) for key, value in asdict(provenance).items() + } + stream = StringIO() + parser.write(stream) + return stream.getvalue(), profile, provenance @contextmanager @@ -852,6 +995,7 @@ def _preparing_project( *, settings: dict[str, object] | None = None, allocate: bool = False, + on_organization: Callable[[SourceLifecycleResult], None] | None = None, ) -> Iterator[tuple[QAProject, _InitializationJournal]]: """Reserve a new project, initialize resources, and publish its profile. @@ -870,6 +1014,9 @@ def _preparing_project( Reserve a fresh numbered sibling if root already exists. Defaults to False, requiring root itself to be nonexistent or empty. + on_organization: Callable[[SourceLifecycleResult], None] | None, optional + Receive the semantic outcome after publication. Defaults to None. + Yields ------ tuple[QAProject, _InitializationJournal] @@ -883,8 +1030,10 @@ def _preparing_project( """ - text, profile = _prepared_profile( - type_id, PROJECT_SOURCES_DIRECTORY, settings + if on_organization is not None and not callable(on_organization): + raise TypeError("on_organization must be callable or None.") + text, profile, provenance = _prepared_profile( + type_id, settings ) layout = plan_project_layout(type_id) with claim_workspace(root, allocate=allocate) as actual_root: @@ -907,8 +1056,17 @@ def _preparing_project( indexes=root / "indexes", logs=root / "logs", profile=profile, + creation_provenance=provenance, ) yield provisional, journal + # Accept the final copied source inventory inside this creation + # transaction, before publishing the profile to other readers. + from kilin.source_manifest import ( + SOURCE_MANIFEST_FILE, _initialize_during_creation, + ) + + journal.note(root / SOURCE_MANIFEST_FILE) + organization = _initialize_during_creation(provisional) try: atomic_create_text(profile_path, text) except FileExistsError as error: @@ -916,9 +1074,17 @@ def _preparing_project( except BaseException: journal.rollback() raise + # Call adapters only after profile publication and creation ownership. + if on_organization is not None: + from kilin.source_manifest import _report_lifecycle + _report_lifecycle(organization, on_organization) -def _initialize_profile(root: Path, type_id: ProjectTypeId) -> QAProject: + +def _initialize_profile( + root: Path, type_id: ProjectTypeId, *, + on_organization: Callable[[SourceLifecycleResult], None] | None = None, +) -> QAProject: """Create a project profile after successful resource initialization. Parameters @@ -928,6 +1094,9 @@ def _initialize_profile(root: Path, type_id: ProjectTypeId) -> QAProject: type_id: ProjectTypeId Expected project type. + on_organization: Callable[[SourceLifecycleResult], None] | None, optional + Receive the semantic outcome after publication. Defaults to None. + Returns ------- QAProject @@ -935,7 +1104,7 @@ def _initialize_profile(root: Path, type_id: ProjectTypeId) -> QAProject: """ - with _preparing_project(root, type_id): + with _preparing_project(root, type_id, on_organization=on_organization): pass return open_project(root) @@ -944,6 +1113,8 @@ def prepare_project_workspace( source_directory: str | Path, type_id: ProjectTypeId, workspace_root: str | Path, + *, + on_organization: Callable[[SourceLifecycleResult], None] | None = None, ) -> QAProject: """Create a fresh single-source mirror without reusing any workspace. @@ -957,6 +1128,9 @@ def prepare_project_workspace( Parent for project_, then -2, -3, and subsequent free names. Existing directories are skipped even for the same source. + on_organization: Callable[[SourceLifecycleResult], None] | None, optional + Receive the semantic outcome after publication. Defaults to None. + Returns ------- QAProject @@ -980,8 +1154,7 @@ def prepare_project_workspace( """ - if type_id not in PROJECT_TYPE_IDS: - raise ValueError(f"type_id must be one of: {_TYPE_ID_CHOICE_TEXT}.") + _require_project_type(type_id, "type_id") source = Path(source_directory).expanduser().resolve(strict=True) if not source.is_dir(): raise NotADirectoryError(f"Choose a source folder: {source}") @@ -996,27 +1169,32 @@ def prepare_project_workspace( safe_name = safe_name or "project" preferred = sandbox / f"project_{safe_name}" with _preparing_project( - preferred, type_id, allocate=True + preferred, type_id, allocate=True, on_organization=on_organization, ) as (project, journal): - _synchronize_snapshot(project, source, sandbox, journal) + plan = _plan_snapshot(project, source, sandbox, None) + _synchronize_snapshot(project, source, plan, journal) return open_project(project.root) def synchronize_project_workspace( - source_directory: str | Path, project_directory: str | Path + source_directory: str | Path, project_directory: str | Path, + *, + on_organization: Callable[[SourceLifecycleResult], None] | None = None, ) -> QAProject: """Deliberately synchronize a single-source mirror, not a new project. Parameters ---------- source_directory: str | pathlib.Path - Original repository to scan. Its identity must match any valid saved - provenance. An unreadable manifest may be rebuilt from this explicit - source after profile and layout validation. + Original repository to scan. Its identity must match valid saved + mirror provenance. Missing or invalid provenance is never rebuilt. project_directory: str | pathlib.Path Existing mirror workspace. Missing or invalid profiles are errors; this operation never creates or changes the project profile. + on_organization: Callable[[SourceLifecycleResult], None] | None, optional + Receive the semantic outcome after publication. Defaults to None. + Returns ------- QAProject @@ -1031,40 +1209,155 @@ def synchronize_project_workspace( Notes ----- - Unlike cumulative add_project_sources, this explicit operation may replace - local snapshot edits and remove copies deleted from the original. The - copy is the project's saved source folder: ``sources/`` for new mirrors, - the original's name for older ones, which are never renamed. Existing - resource templates are not restored. Synchronization is not atomic across - all files; a failure may leave earlier snapshot changes in place. + This explicit operation may replace tracked local edits and remove + tracked copies deleted from the original. Untracked files are preserved; + an original added at an untracked local path is a conflict. Only the + canonical ``sources/`` directory is supported. Import ownership cannot + coexist with mirror ownership. Validation and collision checks precede + all writes. A later I/O failure preserves completed operations and their + provenance; synchronization is not atomic across the whole file batch. """ requested = Path(project_directory).expanduser() - if requested.is_symlink(): + if requested.is_symlink() or requested.is_junction(): raise ValueError("Managed workspace root must not be a symbolic link.") project = open_project(project_directory) + saved = read_mirror_manifest(project.root) source = Path(source_directory).expanduser().resolve(strict=True) if not source.is_dir(): raise NotADirectoryError(f"Choose a source folder: {source}") if source == project.root or source.is_relative_to(project.root): raise ValueError("The source must be outside the mirror workspace.") - saved = _read_json_if_possible(project.root / "source_snapshot.json") - if saved is not None and saved.get("source_directory") not in ( - None, str(source) - ): + if saved["source_directory"] != str(source): raise ValueError("The source conflicts with saved mirror provenance.") - _synchronize_snapshot(project, source, project.root.parent, None) + plan = _plan_snapshot(project, source, project.root.parent, saved) + from kilin.source_manifest import _reconcile_source_operation + + with _reconcile_source_operation(project, callback=on_organization): + _synchronize_snapshot(project, source, plan, None) return open_project(project.root) -def _synchronize_snapshot( +@dataclass(frozen=True) +class _MirrorPlan: + """Record validated per-file mirror operations before any mutation. + + Attributes + ---------- + previous: dict[str, object] | None + Validated saved provenance, or None only during fresh creation. + current: dict[str, object] + Complete current inventory and original identity. + copies: tuple[str, ...] + Selected paths whose local bytes need creating or replacing. + removed: tuple[str, ...] + Previously owned paths no longer selected in the original. + + """ + + previous: dict[str, object] | None + current: dict[str, object] + copies: tuple[str, ...] + removed: tuple[str, ...] + + +def _mirror_target( + snapshot: Path, relative: str, *, allow_directory: bool = False, +) -> Path: + """Check a mirror destination without traversing linked directories. + + Parameters + ---------- + snapshot: pathlib.Path + Canonical managed source directory. + relative: str + Validated source-relative filename from a mirror inventory. + allow_directory: bool, optional + Permit an ordinary leaf directory during read-only preflight. The + caller must establish that planned removals own all its contents. + + Returns + ------- + pathlib.Path + Missing, regular, or leaf-symlink target. An owned leaf symlink may + be replaced or unlinked without accessing its external target. + + Raises + ------ + ValueError + If a parent is linked or not a directory, or the target is neither + a regular file, a missing entry, nor a leaf symlink. + + """ + current = snapshot + if (current.is_symlink() or current.is_junction() + or not current.is_dir()): + raise ValueError("Managed sources must be an ordinary directory.") + parts = Path(relative).parts + for part in parts[:-1]: + current = current / part + if current.is_symlink() or current.is_junction(): + raise ValueError(f"Mirror parent cannot be a link: {relative}") + if current.exists() and not current.is_dir(): + raise ValueError(f"Mirror parent is not a folder: {relative}") + target = current / parts[-1] + directory = allow_directory and target.is_dir() + if target.is_junction() or ( + target.exists() and not target.is_file() and not target.is_symlink() + and not directory + ): + raise ValueError(f"Mirror destination is not a file: {relative}") + return target + + +def _removable_mirror_directory( + snapshot: Path, target: Path, removed: set[str], +) -> bool: + """Check whether planned owned deletions will vacate a target folder. + + Parameters + ---------- + snapshot: pathlib.Path + Canonical managed source directory. + target: pathlib.Path + Ordinary directory occupying a newly selected original filename. + removed: set[str] + Previously tracked files scheduled for deletion. + + Returns + ------- + bool + True only when every file is a planned removal and each directory + is an ancestor of a planned removal. Untracked empty folders block + replacement just as untracked files do. + + """ + files = {snapshot / name for name in removed} + directories = {parent for path in files for parent in path.parents + if parent.is_relative_to(snapshot) and parent != snapshot} + pending = [target] + while pending: + directory = pending.pop() + if directory not in directories: + return False + for path in directory.iterdir(): + if path.is_junction(): + return False + if not path.is_symlink() and path.is_dir(): + pending.append(path) + elif path not in files: + return False + return True + + +def _plan_snapshot( project: QAProject, source: Path, sandbox: Path, - journal: _InitializationJournal | None, -) -> None: - """Apply the existing selected-file mirroring algorithm explicitly. + saved: dict[str, object] | None, +) -> _MirrorPlan: + """Scan and validate all mirror operations without modifying anything. Parameters ---------- @@ -1073,140 +1366,203 @@ def _synchronize_snapshot( source: pathlib.Path Original source directory. sandbox: pathlib.Path - Workspace parent excluded when it lies inside the original source. - journal: _InitializationJournal | None - New-project rollback journal, or None for an intentional update. + Workspace parent excluded when inside the original directory. + saved: dict[str, object] | None + Complete saved provenance, or None during reserved fresh creation. - """ + Returns + ------- + _MirrorPlan + Checked tracked-file changes and copied-content repairs. - root = project.root - # New mirrors copy into sources/; mirrors created before that convention - # keep the original's name and are never renamed. No other folder is - # accepted, because a rebuild replaces the whole copy. - snapshot = next( - ( - path - for path in (root / PROJECT_SOURCES_DIRECTORY, root / source.name) - if path.resolve() == project.source - ), - None, - ) - if snapshot is None: - raise ValueError( - "Managed workspace project.source must be " - f"{PROJECT_SOURCES_DIRECTORY}/ or, for an older mirror, " - f"{source.name}/." - ) - if snapshot.is_symlink(): - raise ValueError("Managed source copy must not be a symbolic link.") - excludes: tuple[str, ...] = () + """ + snapshot = validate_project_sources(project.root, project.source) + if saved is None and source_ownership(project.root) is not None: + raise ValueError("New mirror already has source ownership metadata.") + excludes = (".kilin_versions",) if sandbox.is_relative_to(source): - excludes = (sandbox.relative_to(source).as_posix(),) - + excluded = project.root if sandbox == source else sandbox + excludes += (excluded.relative_to(source).as_posix(),) report = scan_repository( source, extensions=project.profile.extensions, exclude_paths=excludes, max_file_bytes=project.profile.max_file_bytes, ) - current_manifest = build_repository_manifest(report) - snapshot_manifest_path = root / "source_snapshot.json" - saved_manifest = _read_json_if_possible(snapshot_manifest_path) - try: - changes = compare_repository_manifests( - saved_manifest, - current_manifest, - ) - except ValueError: - saved_manifest = None - changes = compare_repository_manifests(None, current_manifest) - - # The saved source manifest alone cannot detect edits to the managed - # copy. Verify selected copied bytes before using the incremental diff. - # A divergent snapshot is rebuilt, not synchronized on top of untrusted - # content (including unexpected selected files and symbolic links). - if saved_manifest is not None and not _snapshot_matches_manifest( - snapshot, project.profile, saved_manifest - ): - saved_manifest = None - changes = compare_repository_manifests(None, current_manifest) - - if not bool(changes["matches"]): - if saved_manifest is None: - shutil.rmtree(snapshot) - snapshot.mkdir(parents=True, exist_ok=True) - - for relative in changes["removed"]: - target = snapshot / str(relative) - if target.is_file() or target.is_symlink(): - target.unlink() - - for relative in [*changes["added"], *changes["modified"]]: - source_path = source / str(relative) - target = snapshot / str(relative) - if journal is not None: - journal.note(target) - target.parent.mkdir(parents=True, exist_ok=True) - shutil.copy2(source_path, target) - - _remove_empty_directories(snapshot) - - # Always record ownership, including the zero-file case. This lets the - # next open distinguish different sources with the same basename. - manifest_payload = { - **current_manifest, + current = validate_mirror_manifest({ + **build_repository_manifest(report), "source_directory": str(source), - } - if journal is not None: - journal.note(snapshot_manifest_path) - _write_json(snapshot_manifest_path, manifest_payload) + }) + previous_files = {} if saved is None else saved["files"] + current_files = current["files"] + removed = set(previous_files) - set(current_files) + for relative in previous_files: + _mirror_target(snapshot, relative) + for relative in sorted(current_files): + if any(parent.as_posix() in removed + for parent in Path(relative).parents): + # A checked, tracked file will be removed before its name is + # used as a directory. Do not follow a replaced leaf symlink. + continue + target = _mirror_target(snapshot, relative, allow_directory=True) + if target.is_dir() and not target.is_symlink(): + if not _removable_mirror_directory(snapshot, target, removed): + raise ValueError( + f"Mirror destination is not a file: {relative}" + ) + continue + if relative not in previous_files and ( + target.exists() or target.is_symlink() + ): + raise ValueError( + f"New mirror source conflicts with untracked file: {relative}" + ) + # Scan completeness remains required, but untracked bytes never grant + # ownership and need not be hashed to authorize tracked-file repairs. + copied = _snapshot_content( + snapshot, project.profile, set(previous_files) & set(current_files), + ) + return _MirrorPlan( + saved, current, + tuple(name for name in sorted(current_files) + if copied.get(name) != current_files[name]), + tuple(sorted(removed)), + ) -def _snapshot_matches_manifest( - snapshot: Path, - profile: ProjectProfile, - manifest: dict[str, object], -) -> bool: - """Verify that selected copied files still match their saved hashes. +def _snapshot_content( + snapshot: Path, profile: ProjectProfile, tracked: set[str], +) -> dict[str, object]: + """Hash only selected owned copies after a complete directory scan. Parameters ---------- snapshot: pathlib.Path - Managed copy of the original source directory. + Canonical managed source directory. profile: ProjectProfile - Profile defining the literal extensions and file-size limit. - manifest: dict[str, object] - Previously validated source manifest used to construct the copy. + Current selected extensions and maximum file size. + tracked: set[str] + Owned paths still selected from the current original. Returns ------- - bool - True when the selected copied content exactly matches the manifest. - - Raises - ------ - ValueError - If the snapshot cannot be scanned completely. - OSError - If files cannot be read or change while their hashes are computed. - - Notes - ----- - Selected files are rehashed on each workspace preparation, including - when the source manifest is unchanged. Unselected files are not part of - this integrity contract. A mismatched copy is rebuilt by the caller. + dict[str, object] + Content records for present, selected, regular tracked files. """ - report = scan_repository( snapshot, extensions=profile.extensions, + exclude_paths=(".kilin_versions",), max_file_bytes=profile.max_file_bytes, ) - copied_manifest = build_repository_manifest(report) - return bool(compare_repository_manifests(manifest, copied_manifest)[ - "matches" - ]) + report["selected_files"] = [ + name for name in report["selected_files"] if name in tracked + ] + return build_repository_manifest(report)["files"] + + +def _synchronize_snapshot( + project: QAProject, + source: Path, + plan: _MirrorPlan, + journal: _InitializationJournal | None, +) -> None: + """Apply a validated mirror plan and preserve completed provenance. + + Parameters + ---------- + project: QAProject + New provisional or explicitly opened mirror project. + source: pathlib.Path + Validated original source directory. + plan: _MirrorPlan + Read-only scan, ownership, collision and integrity decisions. + journal: _InitializationJournal | None + Fresh-project rollback journal, or None during explicit updates. + + """ + snapshot = project.root / PROJECT_SOURCES_DIRECTORY + manifest_path = project.root / "source_snapshot.json" + if plan.previous is not None: + if read_mirror_manifest(project.root) != plan.previous: + raise ValueError("Mirror provenance changed; synchronize again.") + elif journal is None or source_ownership(project.root) is not None: + raise ValueError("Missing reserved mirror creation ownership.") + previous = {} if plan.previous is None else plan.previous["files"] + completed = dict(previous) + current = plan.current["files"] + for relative in set(current) - set(plan.copies): + completed[relative] = current[relative] + + def persist() -> None: + """Save the successful portion without claiming failed copies. + + """ + payload = {**plan.current, "files": completed} + if payload == plan.previous: + return + if plan.previous is not None: + if read_mirror_manifest(project.root) != plan.previous: + raise ValueError("Mirror provenance changed during sync.") + elif source_ownership(project.root) is not None: + raise ValueError("Mirror ownership appeared during creation.") + if journal is not None: + journal.note(manifest_path) + _write_json(manifest_path, payload) + + try: + for relative in plan.removed: + target = _mirror_target(snapshot, relative) + target.unlink(missing_ok=True) + completed.pop(relative) + _remove_empty_directories(snapshot, (relative,)) + for relative in plan.copies: + target = _mirror_target(snapshot, relative) + if relative not in previous and ( + target.exists() or target.is_symlink() + ): + raise ValueError( + "New mirror source conflicts with untracked file: " + f"{relative}" + ) + if journal is not None: + journal.note(target) + target.parent.mkdir(parents=True, exist_ok=True) + with NamedTemporaryFile( + dir=target.parent, prefix=f".{target.name}.", + suffix=".tmp", delete=False, + ) as stream: + temporary = Path(stream.name) + try: + original = _mirror_target(source, relative) + if original.is_symlink(): + raise ValueError(f"Original became a link: {relative}") + shutil.copy2(original, temporary) + copied = build_repository_manifest({ + "repository": str(temporary.parent), "complete": True, + "selected_files": [temporary.name], + })["files"][temporary.name] + if copied != current[relative]: + raise OSError(f"Original changed during copy: {relative}") + _mirror_target(snapshot, relative) + if relative in previous: + temporary.replace(target) + else: + # Publishing a new owned name must not overwrite an + # untracked file appearing after the collision check. + target.hardlink_to(temporary) + completed[relative] = current[relative] + finally: + temporary.unlink(missing_ok=True) + except BaseException as error: + try: + persist() + except BaseException as failure: + error.add_note(f"Mirror provenance update failed: {failure!r}") + raise + else: + persist() def open_project(directory: str | Path) -> QAProject: @@ -1233,12 +1589,39 @@ def open_project(directory: str | Path) -> QAProject: Notes ----- - The root and configured source must already be directories and profile.ini - must exist. A profile may name an absolute source outside the project. The - function validates any existing managed folders, rejecting links and - nondirectories, but never creates missing folders or restores templates. - It loads no models. A pending creation marker is an error, not permission - to finish or repair a partial project. + The project and its real ``sources`` directory must already exist, and + ``project.source`` must be exactly ``sources``. Alternative roots and + linked sources are rejected without moving or changing files. The + function validates every current core field, complete creation metadata, + and any existing managed folders. It rejects links and nondirectories + without creating missing folders or restoring templates. It loads no + models. A pending creation marker is an error, not permission to finish + or repair a partial project. + + """ + + return _read_project(directory, require_registered_type=True) + + +def _read_project( + directory: str | Path, *, require_registered_type: bool, +) -> QAProject: + """Inspect a project with an explicit execution-eligibility policy. + + Parameters + ---------- + directory: str | pathlib.Path + Existing workspace containing a saved profile. + require_registered_type: bool + Require the current runtime's available project type. False is + reserved for read-only project inspection; it still validates + the identifier syntax, settings and filesystem layout, but must + not initialize the current plugin catalogs. + + Returns + ------- + QAProject + Resolved paths and validated saved profile, not an active session. """ @@ -1256,13 +1639,11 @@ def open_project(directory: str | Path) -> QAProject: parser = ConfigParser() parser.read(profile_path, encoding="utf-8") - profile = _read_profile(parser) - source = Path(profile.source).expanduser() - if not source.is_absolute(): - source = root / source - source = source.resolve(strict=True) - if not source.is_dir(): - raise NotADirectoryError(f"Choose a source folder: {source}") + profile = _read_profile( + parser, require_registered_type=require_registered_type, + ) + provenance = _read_creation_provenance(parser) + source = validate_project_sources(root) for name in CORE_PROJECT_FOLDERS: folder = root / name @@ -1278,6 +1659,7 @@ def open_project(directory: str | Path) -> QAProject: indexes=indexes, logs=logs, profile=profile, + creation_provenance=provenance, ) @@ -1337,36 +1719,6 @@ def delete_project(directory: str | Path) -> Path: return destination -def _read_json_if_possible(path: Path) -> dict[str, object] | None: - """Return one JSON object, or ``None`` when it is missing or invalid. - - Parameters - ---------- - path: pathlib.Path - Local JSON path to read or replace. - - Returns - ------- - dict[str, object] | None - Decoded dictionary when an existing file can be read as a JSON object, - otherwise None. - - Notes - ----- - This helper deliberately treats missing, unreadable, and malformed JSON as - an unavailable baseline. - - """ - - if not path.is_file(): - return None - try: - value = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - return None - return value if isinstance(value, dict) else None - - def _write_json(path: Path, value: dict[str, object]) -> None: """Atomically write one readable JSON object. @@ -1390,40 +1742,49 @@ def _write_json(path: Path, value: dict[str, object]) -> None: ) -def _remove_empty_directories(root: Path) -> None: - """Remove empty snapshot directories left after deleted source files. +def _remove_empty_directories(root: Path, removed: tuple[str, ...]) -> None: + """Prune empty parents of removed owned files, preserving other folders. Parameters ---------- root: pathlib.Path - Directory whose empty descendant directories should be removed. + Canonical source directory, which is never removed. + removed: tuple[str, ...] + Source-relative owned files successfully removed by this operation. Notes ----- - Directories are attempted deepest first. Nonempty or otherwise unremovable - directories are left in place; OSError is suppressed. + Only affected parents are considered, deepest first. Unrelated empty + folders and nonempty parents are preserved. Cleanup failures are benign. """ - - directories = sorted( - (path for path in root.rglob("*") if path.is_dir()), - key=lambda path: len(path.parts), - reverse=True, - ) - for directory in directories: + directories = { + parent for name in removed for parent in (root / name).parents + if parent != root and parent.is_relative_to(root) + } + for directory in sorted( + directories, key=lambda path: len(path.parts), reverse=True, + ): + if directory.is_symlink() or directory.is_junction(): + continue try: directory.rmdir() except OSError: pass -def _read_profile(parser: ConfigParser) -> ProjectProfile: +def _read_profile( + parser: ConfigParser, *, require_registered_type: bool = True, +) -> ProjectProfile: """Read and validate every supported project setting. Parameters ---------- parser: ConfigParser ConfigParser containing the profile sections and values. + require_registered_type: bool, optional + Validate against the live catalog (default). False checks only the + identifier grammar, for offline historical inspection. Returns ------- @@ -1444,11 +1805,15 @@ def _read_profile(parser: ConfigParser) -> ProjectProfile: """ + source = _required(parser, "project", "source") + if source != PROJECT_SOURCES_DIRECTORY: + raise ValueError("project.source must be exactly 'sources'.") + type_id_value = _required(parser, "project", "type_id") - if type_id_value not in PROJECT_TYPE_IDS: - raise ValueError( - f"project.type_id must be one of: {_TYPE_ID_CHOICE_TEXT}." - ) + if require_registered_type: + _require_project_type(type_id_value, "project.type_id") + elif not _ID_PATTERN.fullmatch(type_id_value): + raise ValueError("Invalid project.type_id in saved profile.") type_id = cast("ProjectTypeId", type_id_value) extensions = tuple( @@ -1507,7 +1872,7 @@ def _read_profile(parser: ConfigParser) -> ProjectProfile: return ProjectProfile( type_id=type_id, - source=_required(parser, "project", "source"), + source=cast('Literal["sources"]', source), extensions=extensions, max_file_bytes=_positive_integer( parser, @@ -1540,15 +1905,101 @@ def _read_profile(parser: ConfigParser) -> ProjectProfile: "generation", "max_new_tokens", ), - # Optional, so profiles written before this setting stay valid. - block_unrequested_cjk=( - _boolean(parser, "generation", "block_unrequested_cjk") - if parser.has_option("generation", "block_unrequested_cjk") - else _PROFILE_BLOCK_UNREQUESTED_CJK + block_unrequested_cjk=_boolean( + parser, "generation", "block_unrequested_cjk", ), ) +def _require_creation_application_version(value: object) -> str: + """Validate the application release recorded in project provenance. + + Parameters + ---------- + value: object + Application version to capture or read from saved metadata. + + Returns + ------- + str + Original canonical release string, without normalization. + + Raises + ------ + ValueError + If the value is not a supported canonical release spelling. + + Notes + ----- + Historical versions are not compared with the current runtime or the + native build limits. Only the canonical stable, beta and RC syntax + defined in the versioning policy is required. + + """ + + number = r"(?:0|[1-9][0-9]*)" + pattern = rf"{number}\.{number}\.{number}(?:(?:b|rc)[1-9][0-9]*)?" + if not isinstance(value, str) or re.fullmatch(pattern, value) is None: + raise ValueError( + "Invalid metadata.created_with_kilin: " + f"{value!r} is not a canonical KíLín release version." + ) + return value + + +def _read_creation_provenance( + parser: ConfigParser, +) -> ProjectCreationProvenance: + """Read historical creation metadata without consulting the catalog. + + Parameters + ---------- + parser: ConfigParser + Existing project profile, already read without modifying files. + + Returns + ------- + ProjectCreationProvenance + Complete recorded identity required by every persisted project. + + Raises + ------ + ValueError + If the creation record is absent, incomplete, or malformed. + + Notes + ----- + Historical versions need not equal the currently supported versions. + Absent or invalid records are rejected without rewriting or replacing + them with the active identity. + + """ + + section = "metadata" + app = _require_creation_application_version( + _required(parser, section, "created_with_kilin"), + ) + type_id = _required(parser, section, "created_with_project_type") + if _ID_PATTERN.fullmatch(type_id) is None: + raise ValueError("Invalid metadata.created_with_project_type.") + version = _require_semver( + _required(parser, section, "created_with_project_type_version"), + "metadata.created_with_project_type_version", + ) + schema = _required( + parser, section, "created_with_project_type_schema_version", + ) + if re.fullmatch(r"[1-9][0-9]*", schema) is None: + raise ValueError( + "Invalid metadata.created_with_project_type_schema_version." + ) + digest = _required(parser, section, "created_with_project_type_sha256") + if re.fullmatch(r"[0-9a-f]{64}", digest) is None: + raise ValueError("Invalid metadata.created_with_project_type_sha256.") + return ProjectCreationProvenance(app, type_id, version, int(schema), + digest) + + def _required(parser: ConfigParser, section: str, option: str) -> str: """Return one required, non-empty profile value. diff --git a/kilin/project_behavior.py b/kilin/project_behavior.py index b827cc2e..d7a09259 100644 --- a/kilin/project_behavior.py +++ b/kilin/project_behavior.py @@ -57,12 +57,12 @@ from kilin.atomic_writes import atomic_write_text from kilin.project import open_project from kilin.project_type import ( - PROJECT_TYPES_DIR, Intent, ProjectType, _parse_project_type, _unique_keys, project_type, + project_type_raw, ) from kilin.trace_logging import NullTraceLogger, TraceSink @@ -99,7 +99,8 @@ _RETRIEVAL_FIELDS: Final[frozenset[str]] = frozenset(( "mode", "strategy", "include_related_evidence", "prefer_source_code", "max_tokens", "max_sources", "passages_per_source", "max_passages", - "evidence_tokens", "coverage", + "evidence_tokens", "coverage", "related_evidence", "related_lookup", + "grouped", )) @@ -220,6 +221,11 @@ def _intent_values(intent: Intent) -> dict[str, object]: "prefer_source_code": intent.prefer_source_code, "max_tokens": intent.max_tokens, } + if intent.tool is None: + retrieval.update({ + "related_evidence": list(intent.related_evidence), + "related_lookup": list(intent.related_lookup), + }) if ( intent.retrieval_mode == "search" and intent.retrieval_strategy == "source_first" @@ -232,6 +238,7 @@ def _intent_values(intent: Intent) -> dict[str, object]: "max_passages": limits.max_passages, "evidence_tokens": limits.max_tokens, "coverage": limits.coverage, + "grouped": intent.grouped, }) return { "description": intent.description, @@ -501,9 +508,7 @@ def _resolved(root: Path, type_id: str) -> tuple[ProjectType, str]: "global", "intents", "capabilities", "memory" )): return project_type(type_id), revision - path = PROJECT_TYPES_DIR / f"{type_id}.json" - raw = json.loads(path.read_text(encoding="utf-8"), - object_pairs_hook=_unique_keys) + raw = project_type_raw(type_id) return _parse_project_type( type_id, _merge(raw, _merged_overrides(saved)) ), revision @@ -643,6 +648,7 @@ def save_project_behavior( project = open_project(directory) defaults = project_type(project.profile.type_id) saved, revision = _state(project.root, defaults.id) + before = json.loads(json.dumps(saved)) if expected_revision is not None and expected_revision != revision: raise ValueError( "Project behavior changed since it was loaded. Reload and " @@ -705,9 +711,7 @@ def save_project_behavior( "Choose a global, indexing, memory, or intent editor." ) _check_override_shape(saved, defaults) - path = PROJECT_TYPES_DIR / f"{defaults.id}.json" - raw = json.loads(path.read_text(encoding="utf-8"), - object_pairs_hook=_unique_keys) + raw = project_type_raw(defaults.id) _parse_project_type(defaults.id, _merge(raw, _merged_overrides(saved))) state = { "format": _FORMAT, @@ -725,7 +729,10 @@ def save_project_behavior( sink = trace if trace is not None else NullTraceLogger() sink.emit( "project.behavior.saved", component="project", - data={"scope": scope, "intent": intent_id, - "revision": updated["revision"]}, + data={ + "scope": scope, "intent": intent_id, + "revision": updated["revision"], "previous_revision": revision, + "requested": values, "before": before, "saved": state, + }, ) return updated diff --git a/kilin/project_files.py b/kilin/project_files.py index b90f9f0f..cef3ea4d 100644 --- a/kilin/project_files.py +++ b/kilin/project_files.py @@ -10,7 +10,7 @@ - **Explicit operations** - Copy new files, replace existing files, and remove project-owned entries. + Copy new files, create folders, replace files, and remove entries. - **Constrained destinations** @@ -25,6 +25,7 @@ ---------------- - ``add_project_files`` +- ``create_project_folder`` - ``replace_project_file`` - ``remove_project_files`` - ``list_project_files`` @@ -49,8 +50,10 @@ from tempfile import NamedTemporaryFile from typing import Sequence -from kilin.project import QAProject -from kilin.project_layout import CORE_PROJECT_FOLDERS +from kilin.project import QAProject, _read_project +from kilin.project_layout import ( + CORE_PROJECT_FOLDERS, validate_project_sources, +) from kilin.workspace_resources import ( OUTPUTS_FOLDER, PROJECT_SOURCES_DIRECTORY, @@ -59,6 +62,7 @@ __all__ = [ "add_project_files", + "create_project_folder", "replace_project_file", "remove_project_files", "list_project_files", @@ -94,19 +98,19 @@ def _project_root(project: QAProject) -> Path: def _managed_directory(root: Path, folder: str) -> Path: - """Require one of the two real, editable project directories. + """Require a real directory within either editable workspace folder. Parameters ---------- root: pathlib.Path Canonical project root. folder: str - User-editable folder name. + Workspace-relative POSIX directory path. Returns ------- pathlib.Path - The folder, without following a final symbolic link. + The folder, without following symbolic links at any level. Raises ------ @@ -115,11 +119,14 @@ def _managed_directory(root: Path, folder: str) -> Path: """ - if folder not in _EDITABLE_FOLDERS: + relative = _relative_path(folder) + if relative.parts[0] not in _EDITABLE_FOLDERS: raise ValueError("Only outputs/ and templates/ can be edited.") - directory = root / folder - if directory.is_symlink() or not directory.is_dir(): - raise ValueError(f"Invalid project folder: {directory}") + directory = root + for part in relative.parts: + directory = directory / part + if directory.is_symlink() or not directory.is_dir(): + raise ValueError(f"Invalid project folder: {directory}") return directory @@ -151,6 +158,8 @@ def _relative_path(value: str) -> PurePosixPath: or PureWindowsPath(value).drive or "\\" in value or ":" in value + or "\x00" in value + or any(part.endswith((".", " ")) for part in value.split("/")) or any(part in ("", ".", "..") for part in value.split("/")) ): raise ValueError(f"Invalid workspace path: {value}") @@ -183,13 +192,8 @@ def _target(root: Path, value: str) -> Path: relative = _relative_path(value) if len(relative.parts) < 2: raise ValueError("Select an item inside outputs/ or templates/.") - directory = _managed_directory(root, relative.parts[0]) - current = directory - for part in relative.parts[1:-1]: - current = current / part - if current.is_symlink() or not current.is_dir(): - raise ValueError(f"Invalid project subfolder: {current}") - destination = current / relative.parts[-1] + directory = _managed_directory(root, relative.parent.as_posix()) + destination = directory / relative.name if destination.is_symlink(): raise ValueError(f"Do not follow a project link: {destination}") return destination @@ -294,14 +298,14 @@ def add_project_files( *, replace: bool = False, ) -> list[str]: - """Copy selected files or folders into outputs/ or templates/. + """Copy files or folders into an existing editable directory. Parameters ---------- project: QAProject Project owning the destination. folder: str - Either ``outputs`` or ``templates``. + Workspace-relative directory within ``outputs`` or ``templates``. paths: Sequence[str | pathlib.Path] External file or directory paths to copy. replace: bool, optional @@ -339,6 +343,10 @@ def add_project_files( for source in sources: if source == directory or source.is_relative_to(directory): raise ValueError(f"{source.name} is already in {folder}/.") + # An ancestor directory would recursively copy the destination + # into itself, even when the destination is a nested folder. + if source.is_dir() and directory.is_relative_to(source): + raise ValueError(f"Cannot copy {source} into its own subtree.") changed = [] for source in sources: destination = directory / source.name @@ -357,6 +365,51 @@ def add_project_files( return changed +def create_project_folder( + project: QAProject, folder: str, name: str, +) -> str: + """Create one new directory in an existing editable project folder. + + Parameters + ---------- + project: QAProject + Project owning the destination. + folder: str + Existing workspace-relative directory within outputs or templates. + name: str + New directory basename, without path separators. + + Returns + ------- + str + Workspace-relative path of the created directory. + + Raises + ------ + ValueError + If the parent or basename is invalid, or the name is taken. + OSError + If directory creation fails. + + Notes + ----- + No source indexing takes place. Existing files and directories are + never replaced or adopted by this operation. + + """ + + root = _project_root(project) + directory = _managed_directory(root, folder) + relative = _relative_path(name) + if len(relative.parts) != 1: + raise ValueError("Choose a single directory name.") + destination = directory / relative.name + if destination.exists() or destination.is_symlink(): + raise ValueError(f"Project entry already exists: {destination}") + destination.mkdir() + return destination.relative_to(root).as_posix() + + def replace_project_file( project: QAProject, path: str, source: str | Path ) -> str: @@ -484,26 +537,51 @@ def list_project_files(project: QAProject) -> list[str]: Workspace-relative paths. Directory entries end with ``/``, so empty folders remain visible. Inventory is capped at 10,000 entries. + Raises + ------ + ValueError + If the saved profile or captured source directory is invalid. + OSError + If the project profile or canonical sources directory is absent. + + Notes + ----- + Listing revalidates the current layout without loading project types or + models, creating missing folders, or changing files. Linked directories, + including junctions, are pruned before their contents are enumerated. + """ root = _project_root(project) + validate_project_sources(root, project.source) + _read_project(root, require_registered_type=False) names = set(CORE_PROJECT_FOLDERS) names.add(PROJECT_SOURCES_DIRECTORY) - if project.source.is_relative_to(root) and project.source != root: - names.add(project.source.relative_to(root).parts[0]) found = ["profile.ini"] for name in sorted(names): directory = root / name - if not directory.is_dir() or directory.is_symlink(): + if (not directory.is_dir() or directory.is_symlink() + or directory.is_junction()): continue found.append(f"{name}/") - for entry in directory.rglob("*"): - if entry.is_symlink(): - continue - if entry.is_dir(): - found.append(entry.relative_to(root).as_posix() + "/") - elif entry.is_file(): - found.append(entry.relative_to(root).as_posix()) + for current, folders, files in directory.walk(top_down=True): + # Prune before descent: filtering a yielded junction alone does + # not stop recursive globbing from enumerating its target. + folders[:] = sorted( + name for name in folders + if not (current / name).is_symlink() + and not (current / name).is_junction() + ) + for name in (*folders, *sorted(files)): + entry = current / name + if entry.is_symlink() or entry.is_junction(): + continue + if entry.is_dir(): + found.append(entry.relative_to(root).as_posix() + "/") + elif entry.is_file(): + found.append(entry.relative_to(root).as_posix()) + if len(found) >= _INVENTORY_LIMIT: + break if len(found) >= _INVENTORY_LIMIT: break return sorted(set(found))[:_INVENTORY_LIMIT] diff --git a/kilin/project_layout.py b/kilin/project_layout.py index ec1c1423..38756c63 100644 --- a/kilin/project_layout.py +++ b/kilin/project_layout.py @@ -5,7 +5,8 @@ select tools through their intents; each registered tool may declare packaged resources for its validated settings. Only those resources are installed when a new profile is created. Opening an existing project never -reinstalls deleted or edited templates. +reinstalls deleted or edited templates. Templates are installed under +``templates//``. The planner performs no writes. Materialization validates paths, preserves existing project files, and does not execute tool code. A project workspace @@ -52,7 +53,7 @@ - ``source_scan_exclusions`` - Exclude managed folders only when the workspace root is also its source. + Exclude managed project paths from the configured source scan. Examples -------- @@ -66,18 +67,18 @@ from __future__ import annotations from dataclasses import dataclass -from importlib.resources import files from pathlib import Path, PurePosixPath, PureWindowsPath import shutil from typing import Final from kilin.project_type import project_type -from kilin.tools._registry import TOOL_REGISTRY +from kilin.tools import Tool, registered_tools from kilin.workspace_resources import ( OUTPUTS_FOLDER, PROJECT_SOURCES_DIRECTORY, TEMPLATES_FOLDER, WorkspaceResource, + _template_owner, ) __all__ = [ @@ -87,6 +88,7 @@ "install_project_resources", "plan_project_layout", "source_scan_exclusions", + "validate_project_sources", ] CORE_PROJECT_FOLDERS: Final[tuple[str, ...]] = ( @@ -95,12 +97,6 @@ _RESERVED_RESOURCE_ROOTS: Final[frozenset[str]] = frozenset( (PROJECT_SOURCES_DIRECTORY, "indexes", "logs", "memory", "outputs") ) -_PROJECT_SOURCE_EXCLUDES: Final[tuple[str, ...]] = ( - *CORE_PROJECT_FOLDERS, - "profile.ini", - "sources.json", - "source_snapshot.json", -) @dataclass(frozen=True, slots=True) @@ -147,11 +143,20 @@ def _safe_destination(destination: str) -> PurePosixPath: or "\\" in destination or len(parts) < 2 or any(part in ("", ".", "..") for part in parts) - or parts[0] in _RESERVED_RESOURCE_ROOTS - or parts[0] == "profile.ini" + or parts[0].casefold() in _RESERVED_RESOURCE_ROOTS + or parts[0].casefold() == "profile.ini" or ":" in destination + or "\x00" in destination + or any(part.endswith((".", " ")) for part in parts) ): raise ValueError(f"Unsafe tool resource destination: {destination}") + if parts[0].casefold() == TEMPLATES_FOLDER: + if parts[0] != TEMPLATES_FOLDER or len(parts) < 3: + raise ValueError( + "Template resources must use templates//: " + f"{destination}" + ) + _template_owner(parts[1]) return path @@ -181,15 +186,15 @@ def _validated_source(source: Path) -> Path: return path.resolve(strict=True) -def _tool_owned_source(source: Path, tool_name: str) -> Path: +def _tool_owned_source(source: Path, tool: Tool) -> Path: """Require a declared file to belong to its registered tool package. Parameters ---------- source: pathlib.Path Packaged file declared by the tool. - tool_name: str - Registered name of the declaring executable tool. + tool: Tool + Registered declaring tool with its loader-assigned resource root. Returns ------- @@ -204,10 +209,10 @@ def _tool_owned_source(source: Path, tool_name: str) -> Path: """ path = _validated_source(source) - package = Path(files(f"kilin.tools.{tool_name}")).resolve() + package = tool.resource_root if not path.is_relative_to(package): raise ValueError( - f"Tool {tool_name!r} declared a resource outside " + f"Tool {tool.name!r} declared a resource outside " f"its package: {source}" ) return path @@ -236,23 +241,46 @@ def plan_project_layout(type_id: str) -> ProjectLayout: definition = project_type(type_id) resources: dict[str, WorkspaceResource] = {} + spellings: dict[str, str] = {} for intent in definition.intents.values(): use = intent.tool if use is None: continue - declaration = TOOL_REGISTRY[use.name].workspace_resources + tool = registered_tools()[use.name] + declaration = tool.workspace_resources if declaration is None: continue for resource in declaration(use.settings): destination = _safe_destination(resource.destination) - source = _tool_owned_source(resource.source, use.name) + source = _tool_owned_source(resource.source, tool) + if ( + destination.parts[0] == TEMPLATES_FOLDER + and destination.parts[1] != tool.name + ): + raise ValueError( + f"Tool {tool.name!r} must declare templates under " + f"templates/{tool.name}/, not {destination}." + ) key = destination.as_posix() + # Resource paths must also be unambiguous on case-insensitive + # filesystems. Check directory prefixes as well as leaves. + for length in range(1, len(destination.parts) + 1): + prefix = "/".join(destination.parts[:length]) + previous = spellings.setdefault(prefix.casefold(), prefix) + if previous != prefix: + raise ValueError( + f"Conflicting resource paths: {previous}, {prefix}." + ) old = resources.get(key) if old is not None and old.source != source: raise ValueError( f"Conflicting project resources for {key}." ) resources[key] = WorkspaceResource(source, key) + for key in resources: + for parent in PurePosixPath(key).parents: + if parent.as_posix() in resources: + raise ValueError(f"Conflicting project resources for {key}.") return ProjectLayout(tuple(resources[key] for key in sorted(resources))) @@ -357,38 +385,94 @@ def install_project_resources(root: Path, layout: ProjectLayout) -> None: ) from None +def validate_project_sources( + root: Path, source: Path | None = None, +) -> Path: + """Validate the single source directory owned by a current project. + + Parameters + ---------- + root: pathlib.Path + Existing project directory. Workspace aliases are resolved first. + source: pathlib.Path | None, optional + Previously captured source path to check against the current layout. + Ancestor aliases are accepted when the real directory is the same. + Defaults to None, validating the canonical directory alone. + + Returns + ------- + pathlib.Path + Absolute, real ``sources`` directory inside the project. + + Raises + ------ + FileNotFoundError + If the project or its sources directory is absent. + NotADirectoryError + If the project or its sources entry is not a directory. + ValueError + If the source path is noncanonical, a symbolic link, or a junction. + + Notes + ----- + This read-only check never repairs missing folders. Validate before + resolving the sources entry so links cannot become accepted aliases. + + """ + + resolved_root = Path(root).resolve(strict=True) + if not resolved_root.is_dir(): + raise NotADirectoryError(f"Choose a project folder: {resolved_root}") + canonical = resolved_root / PROJECT_SOURCES_DIRECTORY + if source is not None: + captured = Path(source) + # Resolve ancestors only; the source entry must still be canonical. + if ( + captured.name != PROJECT_SOURCES_DIRECTORY + or not captured.parent.is_dir() + or captured.parent.resolve(strict=True) != resolved_root + ): + raise ValueError( + "Project source must be the project's sources folder." + ) + if canonical.is_symlink() or canonical.is_junction(): + raise ValueError(f"Project sources must not be a link: {canonical}") + canonical = canonical.resolve(strict=True) + if not canonical.is_dir(): + raise NotADirectoryError(f"Choose a source folder: {canonical}") + return canonical + + def source_scan_exclusions(root: Path, source: Path) -> tuple[str, ...]: - """Exclude managed project folders when scanning the project root. + """Exclude unrecorded versions from a canonical project source scan. Parameters ---------- root: pathlib.Path Absolute root of an opened KíLín project. source: pathlib.Path - Resolved source folder recorded in the project profile. + Canonical source folder recorded in the project profile. Returns ------- tuple[str, ...] - Managed top-level folders to exclude when source is the project - root; the reserved version folder for managed sources; otherwise - an empty tuple. + The reserved version folder. Recorded retained copies are selected + separately using their ownership metadata. + + Raises + ------ + ValueError + If the project source layout is noncanonical or linked. + OSError + If the canonical source directory is absent or not a directory. Notes ----- - Source folders of unrelated repositories named ``templates`` or - ``outputs`` are not excluded globally. Managed version files are added - separately from ``sources.json`` so only recorded versions are indexed. + General repository scans remain independent of project layout and have + no project-specific exclusions. Names such as ``templates`` or + ``sources.json`` inside sources are ordinary user source names. """ - resolved_root = Path(root).resolve() - resolved_source = Path(source).resolve() - if resolved_root == resolved_source: - return _PROJECT_SOURCE_EXCLUDES - if ( - resolved_source == resolved_root / PROJECT_SOURCES_DIRECTORY - and (resolved_root / "sources.json").is_file() - ): - return (".kilin_versions",) - return () + validate_project_sources(root, source) + return (".kilin_versions",) diff --git a/kilin/project_type.py b/kilin/project_type.py index 87af756f..0028789c 100644 --- a/kilin/project_type.py +++ b/kilin/project_type.py @@ -9,10 +9,10 @@ conversation history. Restart KíLín afterwards. Saved conversations keep the system prompt they were answered with. -Files are read once per folder and cached for the process. A malformed -file stops loading with a ``ValueError``; no type is skipped silently. This -module accepts any nonempty collection of valid definitions. The standard -``code`` and ``literature`` definitions are not mandatory. +The runtime catalog captures the raw and validated definitions once per +process. Invalid definitions remain visible with diagnostics, but cannot +be selected for execution. Explicit folder validation is strict and cached +separately. The standard ``code`` and ``literature`` types are not mandatory. Key Features ------------ @@ -22,7 +22,8 @@ ``code.json`` and ``literature.json`` sit in ``kilin/project_types/``, a folder that holds only data. The file name is the type's ID, and types are listed in file-name order. Add or remove packaged definitions - to specialize a distribution; at least one valid definition is required. + to specialize a distribution. Runtime discovery retains invalid types + as unavailable; explicit folder validation requires a nonempty folder. - **Tools by name** @@ -49,11 +50,19 @@ An omitted or null setting inherits the configured chat setting. Tools own their model calls and cannot declare a thinking override. +- **Source organization declarations** + + A type may declare roles, relationship behaviors and deterministic + discovery defaults. Ordinary intents may declare separate linked + evidence and lookup policies. These immutable records are validated + before tool binding and do not yet drive workspace or retrieval IO. + - **Validated on load** - A malformed file or an unknown field at any configuration level raises - ``ValueError`` naming the type and field. Tool-specific settings are - checked by their registered tool. + Structural validation is independent of tool availability. The + runtime catalog then binds each tool reference and records failures + with the type and field. Every definition declares its implementation + version and the independent JSON schema generation explicitly. Module Structure ---------------- @@ -141,6 +150,10 @@ One validated project type. +- ``SourceOrganization`` + + Validated immutable source-organization defaults of the type. + - ``RetrievalMode`` Type alias for ``"search"``, ``"document"``, ``"reuse"``, or @@ -150,10 +163,18 @@ Type alias for ``"hybrid"`` or ``"source_first"``. +- ``PROJECT_TYPE_SCHEMA_VERSION`` + + Supported project-type JSON schema version, independent of KíLín. + +- ``ProjectTypeInfo``, ``project_type_catalog``, and ``project_type_raw`` + + Inspect availability and captured source definitions. + - ``load_project_types`` - Read and validate every project type in a folder, cached for the - process. + Return available runtime definitions, or strictly validate an explicit + folder. - ``project_type`` @@ -179,12 +200,17 @@ from __future__ import annotations +from collections.abc import Iterator, Mapping +from copy import deepcopy from dataclasses import dataclass, replace from functools import lru_cache +from hashlib import sha256 import json from math import isfinite from pathlib import Path import re +from threading import RLock +from types import MappingProxyType from typing import Final, Literal, TypeAlias from kilin.defaults import ( @@ -192,12 +218,20 @@ require_default_int, require_default_nonnegative_int, ) +from kilin.plugins._lifecycle import _ensure_runtime +from kilin.plugins._versioning import _is_semver, _require_semver from kilin.retrievals.evidence_budget import ( COVERAGE_MODES, EvidenceLimits, ) from kilin.repository import normalize_extensions -from kilin.tools._contract import reject_unknown -from kilin.tools._registry import TOOL_REGISTRY, ToolUse, parse_tool +from kilin.source_organization import ( + DEFAULT_SOURCE_ORGANIZATION, SourceOrganization, + parse_source_organization, +) +from kilin.tools._contract import ( + ToolUse, reject_unknown, _validate_tool_policies, +) +from kilin.tools._registry import parse_tool, registered_tools __all__ = [ "CODE_GRAPH_AUTO", @@ -211,6 +245,7 @@ "HISTORY_POLICY_RECENT", "HISTORY_POLICY_RELEVANT", "PROJECT_TYPES_DIR", + "PROJECT_TYPE_SCHEMA_VERSION", "RETRIEVAL_MODE_CHOICES", "RETRIEVAL_MODE_DOCUMENT", "RETRIEVAL_MODE_NONE", @@ -229,10 +264,14 @@ "MemoryQuestionPolicy", "ProjectType", "ProjectTypeId", + "ProjectTypeInfo", + "SourceOrganization", "RetrievalMode", "RetrievalStrategy", "load_project_types", "project_type", + "project_type_catalog", + "project_type_raw", "with_project_routing", ] @@ -240,6 +279,7 @@ # One JSON file per project type; the file name is the type's ID. PROJECT_TYPES_DIR: Final[Path] = Path(__file__).parent / "project_types" +PROJECT_TYPE_SCHEMA_VERSION: Final[int] = 1 # Project type and intent IDs are short, lowercase, and safe in file names # and in ``profile.ini``. _ID_PATTERN: Final[re.Pattern[str]] = re.compile(r"[a-z][a-z0-9_-]{0,31}") @@ -433,6 +473,15 @@ class Intent: coverage: "bounded" | "exhaustive" Whether ordinary questions require all indexed sources. Explicit questions asking about all sources always request exhaustive mode. + related_evidence: tuple[str, ...] + Declared relation types for including linked original evidence. + Defaults to empty; distinct from related conversation evidence. + related_lookup: tuple[str, ...] + Declared relation types for linked lookup material. Defaults to + empty. Lookup material is not automatically scientific evidence. + grouped: bool + Opt into logical-group source-first quotas for an ordinary search. + False preserves physical-file quotas. memory_indexing: "automatic" | "explicit" | "never" Whether this intent can enter long-term memory automatically, only when selected, or never. Applies independently to questions/answers. @@ -463,6 +512,9 @@ class Intent: coverage: str = "bounded" memory_indexing: MemoryIndexingPolicy = "automatic" memory_read: bool = True + related_evidence: tuple[str, ...] = () + related_lookup: tuple[str, ...] = () + grouped: bool = False def source_limits(self) -> EvidenceLimits: """Resolve the validated source-first limits for this intent. @@ -497,6 +549,10 @@ class ProjectType: ---------- id: ProjectTypeId Identifier written to ``profile.ini``. + version: str + Explicit independent implementation version (SemVer 2.0.0). + schema_version: int + Declared JSON schema generation implemented by the definition. display_name: str Name shown when choosing a type. description: str @@ -556,10 +612,15 @@ class ProjectType: New-project thinking default, or None to use the packaged setting. generation_temperature: float | None New-project sampling temperature, or None to use the packaged value. + source_organization: SourceOrganization + Immutable role, relationship and discovery defaults, not assignments + to individual files. """ id: ProjectTypeId + version: str + schema_version: int display_name: str description: str extensions: tuple[str, ...] @@ -583,6 +644,7 @@ class ProjectType: source_cards_automatic: bool = False generation_thinking: bool | None = None generation_temperature: float | None = None + source_organization: SourceOrganization = DEFAULT_SOURCE_ORGANIZATION @property def label(self) -> str: @@ -848,7 +910,96 @@ def _object(type_id: str, data: dict, field: str) -> dict: return value -def _parse_intent(type_id: str, intent_id: object, data: object) -> Intent: +def _tool_reference(where: str, data: object) -> ToolUse: + """Validate the declarative part of a tool reference. + + Parameters + ---------- + where: str + Intent location for diagnostics. + data: object + Raw tool reference from the JSON definition. + + Returns + ------- + ToolUse + Unbound reference carrying raw settings. Never execute it before + binding to the registered tool and validating those settings. + + """ + + if not isinstance(data, dict): + raise ValueError(f"Intent {where!r} tool must be an object.") + name = data.get("name") + if not isinstance(name, str) or not re.fullmatch( + r"[a-z][a-z0-9_]*", name + ): + raise ValueError(f"Intent {where!r} has an invalid tool name.") + settings = {key: value for key, value in data.items() if key != "name"} + return ToolUse(name, deepcopy(settings)) + + +def _schema_version(data: dict) -> int: + """Check the independently versioned project-type JSON schema. + + Parameters + ---------- + data: dict + Raw project-type object. + + Returns + ------- + int + Explicit supported schema generation. + + """ + + if "schema_version" not in data: + raise ValueError("Project type requires explicit schema_version.") + version = data["schema_version"] + if type(version) is not int or version != PROJECT_TYPE_SCHEMA_VERSION: + raise ValueError( + f"Project type schema_version {version!r} is unsupported; " + f"supported version is {PROJECT_TYPE_SCHEMA_VERSION}." + ) + return version + + +def _relation_policy( + where: str, value: object, organization: SourceOrganization, +) -> tuple[str, ...]: + """Validate an ordinary intent's declared relation selection. + + Parameters + ---------- + where: str + Intent and policy field for diagnostics. + value: object + JSON list of relation IDs. + organization: SourceOrganization + Vocabulary of the enclosing project-type definition. + + Returns + ------- + tuple[str, ...] + Unique declared relation IDs in their supplied order. + + """ + if not isinstance(value, list) or not all( + isinstance(item, str) and item in organization.relation_ids + for item in value + ): + raise ValueError(f"{where} must list declared relation IDs.") + if len(set(value)) != len(value): + raise ValueError(f"{where} contains duplicate relation IDs.") + return tuple(value) + + +def _parse_intent( + type_id: str, intent_id: object, data: object, *, + organization: SourceOrganization, + bind_tools: bool = True, +) -> Intent: """Validate one intent of a project type. Missing settings take their defaults: history policy ``relevant``, @@ -864,6 +1015,11 @@ def _parse_intent(type_id: str, intent_id: object, data: object) -> Intent: Key of the intent in the type's ``intents`` object. data: object Parsed JSON value of the intent. + organization: SourceOrganization + Enclosing type's declared relation vocabulary. + bind_tools: bool, optional + Validate settings against installed tools. False validates only + the reference shape; the result must not be used for execution. Returns ------- @@ -926,6 +1082,9 @@ def _parse_intent(type_id: str, intent_id: object, data: object) -> Intent: "mode", "strategy", "include_related_evidence", + "related_evidence", + "related_lookup", + "grouped", "prefer_source_code", "max_tokens", "max_sources", @@ -944,7 +1103,29 @@ def _parse_intent(type_id: str, intent_id: object, data: object) -> Intent: ) # A tool replaces retrieval, so its intent defaults to no retrieval. - tool = parse_tool(where, data["tool"]) if "tool" in data else None + tool = None + if "tool" in data: + tool = ( + parse_tool(where, data["tool"]) if bind_tools + else _tool_reference(where, data["tool"]) + ) + if bind_tools and tool is not None: + _validate_tool_policies( + registered_tools()[tool.name], tool.settings, organization, + ) + relation_fields = ("related_evidence", "related_lookup") + if tool is not None and any( + key in retrieval for key in (*relation_fields, "grouped") + ): + raise ValueError( + f"Intent {where!r} relation policies belong to ordinary " + "intents; tool-backed intents use tool-owned policies." + ) + related_evidence, related_lookup = ( + _relation_policy(f"{where}.retrieval.{key}", retrieval.get(key, []), + organization) + for key in relation_fields + ) thinking = data.get("thinking") if thinking is not None and type(thinking) is not bool: raise ValueError( @@ -977,6 +1158,18 @@ def _parse_intent(type_id: str, intent_id: object, data: object) -> Intent: f"{', '.join(RETRIEVAL_STRATEGY_CHOICES)}." ) + grouped = retrieval.get("grouped", False) + if type(grouped) is not bool: + raise ValueError( + f"Intent {where!r} retrieval.grouped must be boolean." + ) + if grouped and (mode != RETRIEVAL_MODE_SEARCH + or strategy != RETRIEVAL_STRATEGY_SOURCE_FIRST): + raise ValueError( + f"Intent {where!r} retrieval.grouped requires source_first " + "search." + ) + numeric_limits = ( ("max_sources", 1, _MAX_SOURCES_LIMIT), ("passages_per_source", 1, _PASSAGES_PER_SOURCE_LIMIT), @@ -1068,10 +1261,15 @@ def _parse_intent(type_id: str, intent_id: object, data: object) -> Intent: coverage=coverage, memory_indexing=memory_indexing, memory_read=memory_read, + related_evidence=related_evidence, + related_lookup=related_lookup, + grouped=grouped, ) -def _parse_project_type(type_id: object, data: object) -> ProjectType: +def _parse_project_type( + type_id: object, data: object, *, bind_tools: bool = True, +) -> ProjectType: """Validate one project type file. Parameters @@ -1080,6 +1278,9 @@ def _parse_project_type(type_id: object, data: object) -> ProjectType: Project type ID (the file name without ``.json``). data: object Parsed JSON value of the file. + bind_tools: bool, optional + Resolve and validate tool settings. False checks the declarative + schema without requiring the tools to be installed. Returns ------- @@ -1103,10 +1304,16 @@ def _parse_project_type(type_id: object, data: object) -> ProjectType: if not isinstance(data, dict): raise ValueError(f"Project type {type_id!r} must be an object.") + schema_version = _schema_version(data) + version = _require_semver( + data.get("version"), f"Project type {type_id!r} version", + ) reject_unknown( type_id, data, ( + "schema_version", + "version", "display_name", "description", "extensions", @@ -1124,6 +1331,7 @@ def _parse_project_type(type_id: object, data: object) -> ProjectType: "welcome_templates", "suggestions", "suggestion_templates", + "source_organization", ), ) extensions = _texts(type_id, data, "extensions") @@ -1295,17 +1503,27 @@ def _parse_project_type(type_id: object, data: object) -> ProjectType: "be a finite nonnegative number." ) + organization = ( + parse_source_organization( + data["source_organization"], + where=f"{type_id}.source_organization", + ) if "source_organization" in data else DEFAULT_SOURCE_ORGANIZATION + ) raw_intents = _object(type_id, data, "intents") if not raw_intents: raise ValueError( f"Project type {type_id!r} needs at least one intent." ) intents = { - intent_id: _parse_intent(type_id, intent_id, value) + intent_id: _parse_intent( + type_id, intent_id, value, organization=organization, + bind_tools=bind_tools, + ) for intent_id, value in raw_intents.items() } default_intent = data.get("default_intent", next(iter(intents))) - if default_intent not in intents: + if (not isinstance(default_intent, str) + or default_intent not in intents): raise ValueError( f"Project type {type_id!r} default_intent " f"{default_intent!r} is not " @@ -1314,6 +1532,8 @@ def _parse_project_type(type_id: object, data: object) -> ProjectType: return ProjectType( id=type_id, + version=version, + schema_version=schema_version, display_name=_text(type_id, data, "display_name"), description=_text(type_id, data, "description"), extensions=extensions, @@ -1339,6 +1559,7 @@ def _parse_project_type(type_id: object, data: object) -> ProjectType: source_cards_automatic=source_cards_automatic, generation_thinking=thinking, generation_temperature=temperature, + source_organization=organization, ) @@ -1373,56 +1594,474 @@ def _unique_keys(pairs: list[tuple[str, object]]) -> dict[str, object]: return dict(pairs) +@dataclass(frozen=True, slots=True) +class ProjectTypeInfo: + """Describe a discovered project type without exposing mutable settings. + + Attributes + ---------- + type_id: str + Identifier derived from the JSON filename. + path: pathlib.Path + Resolved source of the captured definition, or its absolute path + when resolution itself failed. + origin: str + Distribution or user-level source of the definition. + version: str | None + Declared implementation version, if readable and valid SemVer. + schema_version: int | None + Declared schema generation, if readable and an integer. + required_tools: tuple[str, ...] + Tool IDs from the structurally valid definition, in sorted order. + error: str | None + Diagnostic if the type is unavailable; otherwise None. + sha256: str | None + Digest of the captured JSON bytes, if readable. + bound: bool + False for structural-only validation without tool resolution. + + """ + + type_id: str + path: Path + origin: str + version: str | None + schema_version: int | None + required_tools: tuple[str, ...] + error: str | None + sha256: str | None = None + bound: bool = True + + @property + def available(self) -> bool: + """Report whether the definition can be selected for execution.""" + + return self.error is None and self.bound + + def identity(self) -> dict[str, object]: + """Return portable provenance without an absolute user path.""" + + return { + "type_id": self.type_id, "origin": self.origin, + "version": self.version, + "schema_version": self.schema_version, "sha256": self.sha256, + } + + +@dataclass(frozen=True, slots=True) +class _ProjectTypeRecord: + """Own a catalog entry and its captured raw and parsed definitions. + + The registry never returns this private record or its parsed object + directly. Tool settings can contain mutable JSON-compatible values. + + """ + + info: ProjectTypeInfo + raw: dict | None + definition: ProjectType | None + + +def _read_type_json(path: Path, content: bytes | None = None) -> dict: + """Read one JSON object with duplicate-key validation. + + Parameters + ---------- + path: pathlib.Path + Project-type definition file. + content: bytes | None, optional + Captured bytes, if already read by the catalog builder. + + Returns + ------- + dict + Parsed JSON object before tool binding. + + """ + + try: + value = json.loads( + (path.read_bytes() if content is None else content).decode( + "utf-8" + ), object_pairs_hook=_unique_keys, + ) + except (UnicodeError, json.JSONDecodeError) as error: + raise ValueError(f"{path} is not valid JSON: {error}") from error + if not isinstance(value, dict): + raise ValueError(f"{path} must contain one project type object.") + return value + + +def _bind_tools(definition: ProjectType) -> ProjectType: + """Resolve every tool reference in a structurally validated type. + + Parameters + ---------- + definition: ProjectType + Structurally validated type with unbound tool references. + + Returns + ------- + ProjectType + Fully bound definition with validated settings. + + """ + + names = {intent.tool.name for intent in definition.intents.values() + if intent.tool is not None} + if not names: + return definition + missing = names - registered_tools().keys() + if missing: + raise ValueError( + "Required tools unavailable: " + ", ".join(sorted(missing)) + ) + intents = {} + for key, intent in definition.intents.items(): + use = intent.tool + if use is not None: + use = parse_tool( + f"{definition.id}.intents.{key}", + {"name": use.name, **deepcopy(use.settings)}, + ) + intent = replace(intent, tool=use) + intents[key] = intent + return replace(definition, intents=intents) + + +def _type_record( + path: Path, origin: str, *, bind_tools: bool = True, +) -> _ProjectTypeRecord: + """Capture and validate one definition independently of other files. + + Parameters + ---------- + path: pathlib.Path + Candidate JSON file; its stem is the project type ID. + origin: str + Storage scope of the candidate. + bind_tools: bool, optional + Resolve tool references and settings after structural validation. + + Returns + ------- + _ProjectTypeRecord + Captured definition, raw JSON and individual diagnostic. + + """ + + raw = None + definition = None + version = None + schema_version = None + required = () + error = None + digest = None + source = path.absolute() + try: + if origin == "user" and (path.is_symlink() or not path.is_file()): + raise ValueError(f"Expected a regular JSON file: {path}.") + if path.suffix != ".json": + raise ValueError(f"Expected a .json project type: {path}.") + source = path.resolve() + content = source.read_bytes() + digest = sha256(content).hexdigest() + raw = _read_type_json(source, content) + declared = raw.get("version") + if _is_semver(declared): + version = declared + declared_schema = raw.get("schema_version") + if type(declared_schema) is int: + schema_version = declared_schema + structure = _parse_project_type(path.stem, raw, bind_tools=False) + required = tuple(sorted({ + intent.tool.name for intent in structure.intents.values() + if intent.tool is not None + })) + if bind_tools: + definition = _bind_tools(structure) + except (Exception, SystemExit) as failure: + error = str(failure) or type(failure).__name__ + info = ProjectTypeInfo( + path.stem, source, origin, version, schema_version, required, + error, digest, bind_tools, + ) + return _ProjectTypeRecord(info, raw, definition) + + +def _build_project_type_catalog( + directory: Path, origin: str = "distribution", *, + reserved: frozenset[str] = frozenset(), +) -> dict[str, _ProjectTypeRecord]: + """Discover each definition independently and capture diagnostics. + + Parameters + ---------- + directory: pathlib.Path + Folder containing JSON definitions. + origin: str, optional + Storage scope of discovered definitions. + reserved: frozenset[str], optional + IDs already owned by the distribution. Do not bind duplicates. + + Returns + ------- + dict[str, _ProjectTypeRecord] + Entries in deterministic filename order, including failures. + + """ + + registered_tools() + records = {} + for path in sorted(Path(directory).glob("*.json")): + if path.stem in reserved: + info = ProjectTypeInfo( + path.stem, path.absolute(), origin, None, None, (), + f"Project type ID {path.stem!r} is already registered.", + ) + record = _ProjectTypeRecord(info, None, None) + else: + record = _type_record(path, origin) + records[path.stem] = record + return records + + +_catalog: dict[str, _ProjectTypeRecord] | None = None +_catalog_lock = RLock() +_catalog_initializing = False +_rejected_types: tuple[ProjectTypeInfo, ...] = () + + +def _runtime_catalog() -> dict[str, _ProjectTypeRecord]: + """Initialize exactly one process-local catalog, on first use.""" + + global _catalog, _catalog_initializing, _rejected_types + # Tool discovery precedes type discovery, including lock acquisition. + registered_tools() + with _catalog_lock: + if _catalog is None: + if _catalog_initializing: + raise RuntimeError("Recursive project-type initialization.") + _catalog_initializing = True + try: + records = _build_project_type_catalog(PROJECT_TYPES_DIR) + user_dir = _ensure_runtime() / "project_types" + rejected = [] + try: + if user_dir.is_symlink() or user_dir.is_junction(): + raise ValueError("Linked project types directory.") + # Access failures remain inspectable rather than + # hiding other types. + if user_dir.exists(): + if not user_dir.is_dir(): + raise ValueError("Expected a directory.") + list(user_dir.iterdir()) + user_records = _build_project_type_catalog( + user_dir, "user", reserved=frozenset(records), + ) + for name, record in user_records.items(): + if name in records: + rejected.append(record.info) + else: + records[name] = record + except (OSError, ValueError) as error: + rejected.append(ProjectTypeInfo( + "", user_dir, "user", + None, None, (), str(error), + )) + _rejected_types = tuple(rejected) + _catalog = records + finally: + _catalog_initializing = False + return _catalog + + +def project_type_catalog() -> Mapping[str, ProjectTypeInfo]: + """Inspect all discovered runtime types, including unavailable ones. + + Returns + ------- + Mapping[str, ProjectTypeInfo] + Read-only map of immutable diagnostics in discovery order. + + """ + + return MappingProxyType({ + key: record.info for key, record in _runtime_catalog().items() + }) + + +def _project_type_infos() -> tuple[ProjectTypeInfo, ...]: + """Return discovered entries and rejected ID conflicts for inspection.""" + + return tuple(record.info for record in _runtime_catalog().values()) + ( + _rejected_types + ) + + +def _project_type_identity(type_id: str) -> dict[str, object] | None: + """Return the captured project-type identity, if present. + + Parameters + ---------- + type_id: str + Selected project type identifier. + + Returns + ------- + dict[str, object] | None + Portable provenance from the catalog, or None for unknown types. + + """ + + record = _runtime_catalog().get(type_id) + return record.info.identity() if record is not None else None + + +def _available_record(type_id: ProjectTypeId) -> _ProjectTypeRecord: + """Return a usable runtime entry or report why it cannot be selected. + + Parameters + ---------- + type_id: ProjectTypeId + Requested project type ID. + + Returns + ------- + _ProjectTypeRecord + Entry with both a raw and a fully bound definition. + + """ + + catalog = _runtime_catalog() + record = catalog.get(type_id) if isinstance(type_id, str) else None + if record is None: + available = (key for key, item in catalog.items() + if item.info.available) + raise ValueError( + f"Unknown project type {type_id!r}. Choose one of: " + f"{', '.join(available) or ''}." + ) + if not record.info.available: + raise ValueError( + f"Project type {type_id!r} is unavailable: {record.info.error}" + ) + return record + + +class _AvailableProjectTypes(Mapping[str, ProjectType]): + """Read-only runtime mapping returning defensive definition copies. + + This is a view of one captured catalog, not a second registry. A + caller may edit its own parsed intent dictionary or tool settings + without changing the catalog or another caller's definition. + + """ + + def __init__(self, records: dict[str, _ProjectTypeRecord]) -> None: + """Capture the available entries of an already built catalog. + + Parameters + ---------- + records: dict[str, _ProjectTypeRecord] + Private runtime entries, not published directly to callers. + + """ + + self._records = { + key: value for key, value in records.items() + if value.info.available + } + + def __getitem__(self, key: str) -> ProjectType: + """Return a copy of the validated definition. + + Parameters + ---------- + key: str + Available project type ID. + + Returns + ------- + ProjectType + Independent copy of the captured definition. + + """ + + return deepcopy(self._records[key].definition) + + def __iter__(self) -> Iterator[str]: + """Iterate available type IDs in discovery order.""" + + return iter(self._records) + + def __len__(self) -> int: + """Return the number of available types.""" + + return len(self._records) + + def __contains__(self, key: object) -> bool: + """Check availability without copying a parsed definition. + + Parameters + ---------- + key: object + Candidate type ID. + + Returns + ------- + bool + Whether the ID is present in this available catalog view. + + """ + + return isinstance(key, str) and key in self._records + + @lru_cache(maxsize=None) def load_project_types( - directory: Path = PROJECT_TYPES_DIR, -) -> dict[str, ProjectType]: - """Read and validate every project type in a folder. + directory: Path | None = None, +) -> Mapping[str, ProjectType]: + """List available runtime types or validate an explicit folder. Parameters ---------- - directory: pathlib.Path, optional - Folder with one ``.json`` per project type. Defaults to the - packaged ``kilin/project_types``. + directory: pathlib.Path | None, optional + When None, use the captured runtime catalog. An explicit folder is + checked strictly and cached separately; it never registers types. Returns ------- - dict[str, ProjectType] - Types keyed by ID (the file name without ``.json``), in file-name - order. The result is cached for the process. + Mapping[str, ProjectType] + Types keyed by ID in filename order. Runtime values are defensive + copies; an explicit folder retains its original cached mapping. Raises ------ ValueError - If the folder has no project types, a file is not valid JSON, or a - type contains invalid or unknown fields. Every JSON file is checked; - loading stops at the first invalid definition. No particular type ID - is required. + If an explicit folder is empty or contains an invalid definition. + Runtime discovery retains per-type diagnostics instead. + + Notes + ----- + Clearing the function cache refreshes explicit folder validation, not + the process-local runtime catalog. Restart to activate changes. """ + if directory is None: + return _AvailableProjectTypes(_runtime_catalog()) files = sorted(Path(directory).glob("*.json")) if not files: raise ValueError(f"{directory} has no project type files.") - - types: dict[str, ProjectType] = {} - for path in files: - try: - value = json.loads( - path.read_text(encoding="utf-8"), - object_pairs_hook=_unique_keys, - ) - except json.JSONDecodeError as error: - raise ValueError(f"{path} is not valid JSON: {error}") from error - if not isinstance(value, dict): - raise ValueError(f"{path} must contain one project type object.") - types[path.stem] = _parse_project_type(path.stem, value) - - return types + return { + path.stem: _parse_project_type(path.stem, _read_type_json(path)) + for path in files + } def project_type(type_id: ProjectTypeId) -> ProjectType: - """Return one packaged project type by ID. + """Return a defensive copy of one available runtime project type. Parameters ---------- @@ -1432,30 +2071,42 @@ def project_type(type_id: ProjectTypeId) -> ProjectType: Returns ------- ProjectType - The validated type. + Fully validated type, independent of other callers' copies. Raises ------ ValueError - If no type has that ID. + If the type is unknown or unavailable. """ - types = load_project_types() - if type_id not in types: - raise ValueError( - f"Unknown project type {type_id!r}. Choose one of: " - f"{', '.join(types)}." - ) + return deepcopy(_available_record(type_id).definition) + + +def project_type_raw(type_id: ProjectTypeId) -> dict: + """Return the captured raw JSON of an available runtime type. + + Parameters + ---------- + type_id: ProjectTypeId + Project type ID, as written in ``profile.ini``. + + Returns + ------- + dict + Defensive copy of the original JSON for resolving overrides, not a + fresh filesystem read. Changes cannot affect the runtime catalog. + + """ - return types[type_id] + return deepcopy(_available_record(type_id).raw) def with_project_routing(config: ProjectType, root: Path) -> ProjectType: """Return a project type with the routing its tools derive per project. A registered tool with ``routing`` (``generate_paper_summary``, from - the project's ``templates/``) adds cues and a router description to + its project template namespace) adds cues and a router description to its intent, so a template file added to the project is routed to without editing the project type. @@ -1479,7 +2130,7 @@ def with_project_routing(config: ProjectType, root: Path) -> ProjectType: intents: dict[str, Intent] = {} changed = False for intent_id, intent in config.intents.items(): - tool = TOOL_REGISTRY[intent.tool.name] if intent.tool else None + tool = registered_tools()[intent.tool.name] if intent.tool else None routing = None if tool is not None and tool.routing is not None: others = tuple( diff --git a/kilin/project_types/code.CHANGELOG.md b/kilin/project_types/code.CHANGELOG.md new file mode 100644 index 00000000..ceadfb97 --- /dev/null +++ b/kilin/project_types/code.CHANGELOG.md @@ -0,0 +1,5 @@ +# code changelog + +This changelog records changes to the `code` project type. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/kilin/project_types/code.json b/kilin/project_types/code.json index acc5510e..b02c4fbc 100644 --- a/kilin/project_types/code.json +++ b/kilin/project_types/code.json @@ -1,4 +1,26 @@ { + "version": "0.1.0", + "schema_version": 1, + "source_organization": { + "roles": [ + "source", + "test", + "documentation", + "example", + "configuration", + "data" + ], + "default_role": "source", + "relation_types": { + "attached_to": { + "behavior": "dependency" + }, + "related_to": { + "behavior": "association" + } + }, + "automatic_rules": [] + }, "display_name": "Code Repository", "description": "A software repository with source code and documentation.", "extensions": [ diff --git a/kilin/project_types/creative_brainstorming.CHANGELOG.md b/kilin/project_types/creative_brainstorming.CHANGELOG.md new file mode 100644 index 00000000..3ff32254 --- /dev/null +++ b/kilin/project_types/creative_brainstorming.CHANGELOG.md @@ -0,0 +1,5 @@ +# creative_brainstorming changelog + +This changelog records changes to the `creative_brainstorming` project type. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/kilin/project_types/creative_brainstorming.json b/kilin/project_types/creative_brainstorming.json index cac1f4ab..e8700d58 100644 --- a/kilin/project_types/creative_brainstorming.json +++ b/kilin/project_types/creative_brainstorming.json @@ -1,4 +1,25 @@ { + "version": "0.1.0", + "schema_version": 1, + "source_organization": { + "roles": [ + "material", + "notes", + "background", + "data", + "supporting" + ], + "default_role": "material", + "relation_types": { + "attached_to": { + "behavior": "dependency" + }, + "related_to": { + "behavior": "association" + } + }, + "automatic_rules": [] + }, "display_name": "Brainstorming (Creative)", "description": "A creativity-first scientific brainstorming workspace for bold hypotheses, unexpected connections, radical thought experiments, and optional evidence-grounded exploration.", "extensions": [ @@ -90,6 +111,8 @@ "grounded_ideation": { "description": "Create surprising and speculative research ideas using the indexed papers, notes, or source code as creative raw material, not boundaries. Examples: \"brainstorm wild ideas based on these papers\", \"use the project sources to find unexpected directions\", \"what new theories might explain these results?\". Cite premises, then explore beyond them. Not for reporting the literature alone or checking a specific claim.", "cues": [ + "\\b(?:brainstorm|propose|design|suggest|generate|devise|develop|invent|elaborate|refine|ideas?|hypothes(?:is|es)|experiment)\\b[^\\n]{0,220}\\b(?:using|based\\s+on|from|drawing\\s+on|grounded\\s+in|according\\s+to|in\\s+light\\s+of)\\s+[^\\n]{0,100}?[\\w./\\\\-]+\\.(?:pdf|md|txt|tex|bib|bbl|docx?|ipynb|py|m|json|js|html?|r|csv|tsv|rst)\\b", + "\\b(?:brainstorm|propose|design|suggest|generate|devise|develop|invent|elaborate|refine|ideas?|hypothes(?:is|es)|experiment)\\b[^\\n]{0,220}\\b(?:using|based\\s+on|from|drawing\\s+on|grounded\\s+in|in\\s+light\\s+of)\\s+(?:(?:the|my|our|these|project|indexed)\\s+){0,3}(?:sources|papers|studies|documents|literature|references|evidence)\\b", "\\b(?:brainstorm|ideas?|hypothes(?:is|es)|proposals?|suggest|generate|devise)\\b.{0,170}\\b(?:using|based on|grounded in|drawing on|from|in light of)\\s+(?:(?:the|my|our|these|project|indexed)\\s+){0,2}(?:sources|papers|studies|documents|literature|references|evidence)\\b", "\\b(?:based on|using|drawing on|in light of)\\s+(?:(?:the|my|our|these|project|indexed)\\s+){0,2}(?:sources|papers|studies|documents|literature|references|evidence)\\b.{0,170}\\b(?:brainstorm|ideas?|hypothes(?:is|es)|proposals?|suggest|generate)\\b" ], diff --git a/kilin/project_types/grounded_brainstorming.CHANGELOG.md b/kilin/project_types/grounded_brainstorming.CHANGELOG.md new file mode 100644 index 00000000..cd4b0bd3 --- /dev/null +++ b/kilin/project_types/grounded_brainstorming.CHANGELOG.md @@ -0,0 +1,5 @@ +# grounded_brainstorming changelog + +This changelog records changes to the `grounded_brainstorming` project type. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/kilin/project_types/grounded_brainstorming.json b/kilin/project_types/grounded_brainstorming.json index 30956a0f..cc901940 100644 --- a/kilin/project_types/grounded_brainstorming.json +++ b/kilin/project_types/grounded_brainstorming.json @@ -1,4 +1,26 @@ { + "version": "0.1.0", + "schema_version": 1, + "source_organization": { + "roles": [ + "material", + "paper", + "background", + "notes", + "data", + "supporting" + ], + "default_role": "material", + "relation_types": { + "attached_to": { + "behavior": "dependency" + }, + "related_to": { + "behavior": "association" + } + }, + "automatic_rules": [] + }, "display_name": "Brainstorming (Grounded)", "description": "An evidence-led scientific brainstorming workspace that develops original hypotheses, cross-disciplinary connections, and testable experiments from indexed research sources.", "extensions": [ diff --git a/kilin/project_types/literature.CHANGELOG.md b/kilin/project_types/literature.CHANGELOG.md new file mode 100644 index 00000000..cd4af5c4 --- /dev/null +++ b/kilin/project_types/literature.CHANGELOG.md @@ -0,0 +1,5 @@ +# literature changelog + +This changelog records changes to the `literature` project type. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/kilin/project_types/literature.json b/kilin/project_types/literature.json index 79f483bf..989843c9 100644 --- a/kilin/project_types/literature.json +++ b/kilin/project_types/literature.json @@ -1,4 +1,39 @@ { + "version": "0.1.0", + "schema_version": 1, + "source_organization": { + "roles": [ + "document", + "paper", + "supplementary", + "reference", + "bibliography", + "background" + ], + "default_role": "document", + "relation_types": { + "attached_to": { + "behavior": "dependency" + }, + "related_to": { + "behavior": "association" + }, + "bibliography_for": { + "behavior": "dependency" + }, + "supplement_to": { + "behavior": "dependency" + } + }, + "automatic_rules": [ + { + "id": "latex_bibliography", + "detector": "latex_bibliography", + "relation": "bibliography_for", + "mode": "apply" + } + ] + }, "display_name": "Literature Collection", "description": "A collection of scientific literature and related documents.", "extensions": [ @@ -49,6 +84,8 @@ "policy": "relevant" }, "retrieval": { + "related_evidence": ["supplement_to"], + "related_lookup": ["bibliography_for"], "mode": "search", "strategy": "source_first", "max_sources": 8, @@ -90,6 +127,8 @@ "policy": "relevant" }, "retrieval": { + "related_evidence": ["supplement_to"], + "related_lookup": ["bibliography_for"], "mode": "search", "strategy": "source_first", "max_sources": 12, @@ -124,7 +163,7 @@ "description": "A short summary or overview of one paper, in the chat ('give me a short summary of the Smith paper', 'what is the Lee paper about?', 'summarize another paper', 'a quick summary of one of the papers'). Asks which paper when none is named. Not for a named report format (research_briefing, popular_science_summary, technical_summary, or experimental_protocol), whether or not the user asks to save a file, and not for what several papers say about a topic (question_answering).", "cues": [ "^(?!.*\\b(?:briefing|report|templates?|popular|technical|protocol|papers|articles|studies|documents|project|collection)\\b).*\\b(?:an?\\s+)?(?:short\\s+|brief\\s+|quick\\s+)?overview\\s+of\\b", - "^(?!.*\\b(?:briefing|report|templates?|popular|technical|protocol|papers|articles|studies|documents|project|collection)\\b)(?!.*\\b(?:its|their|main|contributions|limitations|results|methods|findings)\\b)\\s*(?:now\\s+)?summari[sz]e\\s+(?:the|this|that|[\\w-]+\\.pdf)\\b", + "^(?!.*\\b(?:briefing|report|templates?|popular|technical|protocol|papers|articles|studies|documents|project|collection)\\b)(?!.*\\b(?:its|their|main|contributions|limitations|results|methods|findings)\\b)\\s*(?:now\\s+)?summari[sz]e\\s+(?:(?:the|this|that)\\s+(?:[\\w-]+\\s+){0,5}(?:paper|article|study|document|manuscript)\\b|(?:(?:the|this|that)\\s+)?[\\w.-]+\\.(?:pdf|md|txt|tex|docx?)\\b(?![\\w-]|\\.[\\w.-]|['’]s)|(?:this|that)\\s*[.?!]?\\s*$)", "^(?!.*\\b(?:briefing|report|templates?|popular|technical|protocol|papers|articles|studies|documents|project|collection)\\b)\\s*(?:now\\s+)?tell\\s+me\\s+about\\s+(?:the|this|that)\\s+[\\w\\s-]+?\\s(?:paper|article|study)[.?!]?\\s*$" ], "history": { @@ -155,6 +194,7 @@ }, "tool": { "name": "reference_check", + "related_lookup": ["bibliography_for"], "max_listed": 20 } }, @@ -265,7 +305,7 @@ } }, "templated_report": { - "description": "Write a report on one document with one of the project's report templates (Markdown files in templates/), named by its title or file name, and save it to outputs/; also list the project's templates or check one. Examples: \"write a journal club summary of smith20\", \"fill the lab notes template for patil25\", \"which templates do I have?\", \"check my journal_club template\". When no template is named, the user chooses one. Not for a short informal summary (paper_overview).", + "description": "Write a report on one document with one of the project's report templates (Markdown files in templates/generate_paper_summary/), named by its title or file name, and save it to outputs/; also list the project's templates or check one. Examples: \"write a journal club summary of smith20\", \"fill the lab notes template for patil25\", \"which templates do I have?\", \"check my journal_club template\". When no template is named, the user chooses one. Not for a short informal summary (paper_overview).", "history": { "policy": "none" }, @@ -282,17 +322,17 @@ "large_batches": 3 }, "cues": [ - "\\b(?:using|with|from|in|into|per)\\s+(?:the\\s+|my\\s+|our\\s+|this\\s+|a\\s+)?[\\w\\s-]{0,40}?\\btemplate\\b", - "\\btemplate\\b[\\s\\S]{0,40}?\\b(?:for|of|on)\\b", - "\\b(?:list|which|what|show|available)\\b[^\\n]{0,40}\\btemplates\\b|\\btemplates\\b[^\\n]{0,40}\\b(?:do\\s+(?:i|we)\\s+have|available)\\b", - "\\b(?:check|validate|test|verify)\\b[^\\n]{0,40}\\btemplate\\b" + "\\b(?:use|using|with|from|in|into|per)\\s+(?:the\\s+|my\\s+|our\\s+|this\\s+|a\\s+)?[\\w\\s-]{0,40}?(? None: """Open a project, its models, indexes, and saved conversation. @@ -1117,6 +1186,9 @@ def __init__( loaded beside the answering model, or is shared with it when both are the same model. Defaults to ``None``, which uses the project's saved router model or the packaged router default. + project_trace: TraceSink | None, optional + Caller-owned shared project diagnostic sink. Defaults to None, + creating one when conversation tracing is enabled. Raises ------ @@ -1127,7 +1199,8 @@ def __init__( Notes ----- Attempts to close partially constructed model sessions after a - preparation exception. Trace construction occurs before model loading. + preparation exception, including failed readiness notifications. + Trace construction occurs before model loading. Heavy dependencies and model downloads are governed by the selected profile. @@ -1135,6 +1208,7 @@ def __init__( self._conversation_ownership: ConversationFileLock | None = None self._owns_trace = False + self._owns_project_trace = False try: self._initialize( project_directory, @@ -1142,6 +1216,7 @@ def __init__( trace=trace, conversation_path=conversation_path, router_model=router_model, + project_trace=project_trace, ) except BaseException as error: ownership = self._conversation_ownership @@ -1154,6 +1229,13 @@ def __init__( f"Trace cleanup failed: {cleanup_error!r}" ) finally: + if self._owns_project_trace: + try: + self.project_trace.close() + except BaseException as cleanup_error: + error.add_note( + f"Project trace cleanup failed: {cleanup_error!r}" + ) if ownership is not None: try: ownership.release() @@ -1172,6 +1254,7 @@ def _initialize( trace: TraceConfig | TraceSink | None, conversation_path: str | Path | None, router_model: str | None, + project_trace: TraceSink | None, ) -> None: """Prepare the owned trace, conversation history, indexes and models. @@ -1187,12 +1270,15 @@ def _initialize( Path of the conversation record, or None for a new one. router_model: str | None Optional separate model identifier used to route questions. + project_trace: TraceSink | None + Optional caller-owned shared project diagnostic sink. Notes ----- - ``__init__`` is responsible for releasing the acquired conversation - ownership and an owned logger if any preparation step raises, even - before model construction begins. + Model cleanup includes final readiness diagnostics and callbacks. + ``__init__`` releases acquired conversation ownership and owned + loggers if any preparation step raises, including steps before + model construction begins. """ @@ -1204,6 +1290,7 @@ def _initialize( self._progress_last_emit: dict[str, float] = {} self._progress_last_trace_percent: dict[str, float] = {} self.project = open_project(project_directory) + _source_records(self.project.root, allow_mirror=True) self.conversation_path = self._resolve_conversation_path( conversation_path ) @@ -1215,7 +1302,32 @@ def _initialize( ownership = ConversationFileLock(self.conversation_path) ownership.acquire() self._conversation_ownership = ownership - self.trace.emit( + # Reject invalid persisted state under ownership before project + # diagnostics, index preparation, or inference model construction. + messages, turns, checkpoint_id = self._load_conversation() + if project_trace is not None: + if project_trace.enabled != self.trace.enabled: + raise ValueError( + "Project and conversation tracing must agree." + ) + if project_trace.enabled and ( + not isinstance(project_trace, TraceLogger) + or project_trace.scope != "project" + or project_trace.output_path.resolve() != ( + self.project.logs / "traces" / "project.json" + ).resolve() + ): + raise ValueError("Invalid shared project trace.") + self.project_trace = project_trace + elif isinstance(self.trace, TraceLogger): + self.project_trace = _project_trace_logger( + replace(self.trace.config, output_path=None), + self.project.root, + ) + self._owns_project_trace = True + elif isinstance(self.trace, NullTraceLogger): + self.project_trace = self.trace + self._project_diagnostics().emit( "session.started", component="rag", data={ @@ -1244,7 +1356,7 @@ def _initialize( if router_model is not None else read_router_model(self.project.root, self.backend) ) - self.trace.emit( + self._project_diagnostics().emit( "backend.selected", component="rag", data={ @@ -1267,9 +1379,9 @@ def _initialize( embedding_model, backend=self.backend, allow_download=profile.allow_download, - trace=self.trace, + trace=self._project_diagnostics(), ) - with self.trace.span( + with self._project_diagnostics().span( "indexing", component="rag", data={"project_directory": str(self.project.root)}, @@ -1295,15 +1407,18 @@ def _initialize( max_new_tokens=profile.max_new_tokens, system_prompt=self._behavior_config().system_prompt, allow_download=profile.allow_download, - trace=self.trace, + trace=self._project_diagnostics(), block_unrequested_cjk=profile.block_unrequested_cjk, ) + # Initialization diagnostics belong to the project, but model + # calls made while answering belong to the active conversation. + chat_session.trace = self.trace + embedding_session.trace = self.trace self._emit_progress( "loading_conversation", 97.0, - "Loading saved conversation...", + "Restoring saved conversation...", ) - messages, turns, checkpoint_id = self._load_conversation() self._checkpoint_id = checkpoint_id self.trace.emit( "conversation.restored", @@ -1311,6 +1426,9 @@ def _initialize( data={ "message_count": len(messages), "turn_count": len(turns), + "turn_uuids": [ + turn.conversation_turn_uuid for turn in turns + ], "path": str(self.conversation_path), "checkpoint_id": checkpoint_id, }, @@ -1330,9 +1448,42 @@ def _initialize( if key in previous } ) + self.embedding_session = embedding_session + self.chat_session = chat_session + self.chunks = chunks + self.source_cards = source_cards + self.source_card_vectors = source_card_vectors + self.indexes = indexes + self.index_status = status + self.source_changes = source_changes + self.turns = turns + self.router_model = resolved_router_model + self._router_session: ChatSession | None = None + # Keep the pool with its passages and router model. A GUI read + # of saved words does not cache an empty fallback as a generated + # pool. + self._suggestion_pool: ( + tuple[list[Chunk], str | None, SuggestionWords] | None + ) = None + self._closed = False + self._project_diagnostics().emit( + "session.ready", + component="rag", + data={ + "index_status": self.index_status, + "chunk_count": len(self.chunks), + "turn_count": len(self.turns), + }, + duration_ms=(perf_counter() - session_started_at) * 1000, + ) + self._emit_progress( + "ready", + 100.0, + f"KíLín ready. Index {self.index_status}.", + ) except BaseException as error: try: - self.trace.exception( + self._project_diagnostics().exception( "session.open.failed", error, component="rag", @@ -1355,39 +1506,46 @@ def _initialize( # every construction failure, including this one. raise - self.embedding_session = embedding_session - self.chat_session = chat_session - self.chunks = chunks - self.source_cards = source_cards - self.source_card_vectors = source_card_vectors - self.indexes = indexes - self.index_status = status - self.source_changes = source_changes - self.turns = turns - self.router_model = resolved_router_model - self._router_session: ChatSession | None = None - # Keep the pool with its passages and router model. A GUI read of - # saved words does not cache an empty fallback as a generated pool. - self._suggestion_pool: ( - tuple[list[Chunk], str | None, SuggestionWords] | None - ) = None - self._closed = False - self.trace.emit( - "session.ready", - component="rag", - data={ - "index_status": self.index_status, - "chunk_count": len(self.chunks), - "turn_count": len(self.turns), - }, - duration_ms=(perf_counter() - session_started_at) * 1000, - ) - self._emit_progress( - "ready", - 100.0, - f"KíLín ready. Index {self.index_status}.", + def _project_diagnostics(self: RAGSession) -> TraceSink: + """Return the shared project sink for preparation diagnostics. + + Returns + ------- + TraceSink + Project sink, or the session's conversation/no-op sink when + no separate project sink was installed. + + """ + + return getattr( + self, "project_trace", getattr(self, "trace", NullTraceLogger()) ) + @contextmanager + def _project_embedding_diagnostics(self: RAGSession) -> Iterator[None]: + """Route shared embedding calls to the project during indexing. + + Yields + ------ + None + Index preparation can use the shared model without recording + its embedding calls in the active conversation. + + Notes + ----- + The command owner executes indexing and answering sequentially. + Restore the conversation sink even when preparation raises. + + """ + + model = self.embedding_session + previous = getattr(model, "trace", self.trace) + model.trace = self._project_diagnostics() + try: + yield + finally: + model.trace = previous + def _emit_progress( self: RAGSession, stage: str, @@ -1445,7 +1603,7 @@ def _emit_progress( elapsed_seconds=elapsed_seconds, eta_seconds=eta_seconds, ) - trace = getattr(self, "trace", NullTraceLogger()) + trace = self._project_diagnostics() last_trace_percent = self._progress_last_trace_percent.get(stage) completed_count = ( current is not None and total is not None and current == total @@ -1802,6 +1960,13 @@ def stream_token(text: str) -> None: "question_characters": len(question), "retrieval_count_override": retrieval_count, "generation_settings_override": generation_settings, + "answer_guidance_override": answer_guidance, + "retrieval_query_override": retrieval_query, + "reuse_evidence": reuse_evidence, + "use_router": use_router, + "confirm_callback_available": confirm_callback is not None, + "choice_callback_available": choice_callback is not None, + "pdf_writer_available": pdf_writer is not None, "conversation_state": conversation_state, } if trace.include_content: @@ -1840,6 +2005,11 @@ def stream_token(text: str) -> None: ) effective = self._parameters(retrieval_count) + type_id = effective.get("project_type_id") + if isinstance(type_id, str): + identity = _project_type_identity(type_id) + if identity is not None: + effective["project_type_plugin"] = identity previous_retrieval_count = ( self.turns[-1].parameters.get( "retrieval_count", @@ -1898,16 +2068,24 @@ def ask_user( """ - report_phase( - ANSWER_PHASE_PROCESSING, - message="Waiting for your choice", - choice={ - "question": text, - "options": list(options), - "allow_cancel": False, - }, + def notify() -> None: + """Display the routing clarification before waiting.""" + report_phase( + ANSWER_PHASE_PROCESSING, + message="Waiting for your choice", + choice={ + "question": text, + "options": list(options), + "allow_cancel": False, + }, + ) + + return _record_choice( + text, options, choice_callback, notify, + trace=trace, turn_id=turn_id, + prefix="routing.choice", component="rag", + allow_cancel=False, ) - return choice_callback(text, options) route_options["choose"] = ask_user decision = self._route( @@ -1965,6 +2143,10 @@ def ask_user( effective["intent_history_policy"] = intent.history_policy effective["intent_retrieval_mode"] = intent.retrieval_mode effective["intent_tool_used"] = intent.tool is not None + if intent.tool is not None: + identity = _tool_identity(intent.tool.name) + if identity is not None: + effective["tool_plugin"] = identity path = Path(self.project.root) / PROJECT_BEHAVIOR_FILE if path.is_file(): effective["project_behavior_revision"] = sha256( @@ -2121,13 +2303,32 @@ def ask_user( retrieval_started = perf_counter() coverage_notice = "" + operation_view = None + answer_groups: tuple[SourceGroupCoverage, ...] = () + live_workspace = isinstance(self.project, QAProject) if mode == RETRIEVAL_MODE_REUSE: + previous_turns = [self.turns[number - 1] + for number in source_turns] + if live_workspace and intent.tool is None: + operation_view = self._ordinary_source_view( + ToolRequest( + question, question, + earlier=self._earlier_turns( + decision, excluded_turn_ids=excluded_turn_ids + ), + ), intent, + ) + previous_turns = self._current_evidence_turns( + previous_turns, operation_view, + ) evidence = _merge_evidence( - [ - self.turns[number - 1].evidence - for number in source_turns - ] + [turn.evidence for turn in previous_turns] ) + if operation_view is not None and not evidence: + coverage_notice = ( + "No previous references match the current source " + "view and indexed content. Search again for evidence." + ) effective["evidence_reused"] = True effective["evidence_from_turns"] = source_turns report_phase( @@ -2146,38 +2347,52 @@ def ask_user( # A document the question names, or the one the earlier # turns discussed, limits the search (see ``_retrieve``). # The candidates are the indexed files in index order. - scope, _ = document_scope( - ToolRequest( - question, - search_text, - earlier=self._earlier_turns( - decision, excluded_turn_ids=excluded_turn_ids - ), + request = ToolRequest( + question, search_text, + earlier=self._earlier_turns( + decision, excluded_turn_ids=excluded_turn_ids ), - self._ask_router, - list(dict.fromkeys(chunk.path for chunk in self.chunks)), - self._card_metadata(), ) source_limits = None source_report: dict[str, object] = {} - if ( - intent.retrieval_strategy - == RETRIEVAL_STRATEGY_SOURCE_FIRST - ): + if intent.grouped and not live_workspace: + raise ValueError("Grouping requires a prepared workspace.") + if (intent.retrieval_strategy + == RETRIEVAL_STRATEGY_SOURCE_FIRST): source_limits = intent.source_limits() if asks_for_all_sources(question): source_limits = replace( source_limits, coverage=COVERAGE_EXHAUSTIVE ) - if ( - source_limits is not None - and source_limits.coverage == COVERAGE_EXHAUSTIVE - and asks_for_all_sources(question) - and len(scope) == 1 - ): - # A single inferred focus must not silently narrow an - # explicit request about every source in the project. - scope = () + comparison = bool( + intent.intent_id == "compare_sources" + or _COMPARISON.search(question) + or _MULTIPLE_TARGETS.search(question) + ) + if live_workspace and intent.tool is None: + operation_view = self._ordinary_source_view( + request, intent, route_scope=True, compare=comparison, + ) + scope = operation_view.operation.scope.paths + scope_mode = operation_view.operation.scope.mode + else: + scope, _ = document_scope( + request, self._ask_router, + list(dict.fromkeys( + chunk.path for chunk in self.chunks + )), + self._card_metadata(), + ) + if (source_limits is not None + and source_limits.coverage == COVERAGE_EXHAUSTIVE + and asks_for_all_sources(question) + and len(scope) == 1): + scope = () + scope_mode = ( + "project" if not scope else + "preferred" if comparison and len(scope) == 1 else + "restricted" + ) # The query embedding is shared by initial and wider # hybrid retrieval. Source-first already selects passages # within its full hard budget, so it never widens here. @@ -2197,12 +2412,16 @@ def ask_user( ANSWER_PHASE_RETRIEVING, message=message ), scope=scope, + scope_mode=scope_mode, + **({"view": operation_view} if operation_view is not None + else {}), prefer_source_code=intent.prefer_source_code, **( { "source_first": ( source_limits.max_sources, - source_limits.passages_per_source > 1, + comparison if operation_view is not None + else source_limits.passages_per_source > 1, ) } if getattr(intent, "retrieval_strategy", None) @@ -2213,6 +2432,9 @@ def ask_user( { "source_limits": source_limits, "source_report": source_report, + "include_bibliographies": bibliography_lookup( + question, scope + ), } if source_limits is not None else {} @@ -2285,22 +2507,53 @@ def ask_user( ): # Follow-ups keep the sources their earlier answers # cited, whatever intent the router chose. + earlier = [self.turns[number - 1] + for number in related_turns] + if operation_view is not None: + earlier = self._current_evidence_turns( + earlier, operation_view, + ) + grouped = (operation_view is not None + and operation_view.operation.policy.grouped) + if grouped: + selected = _selected_groups( + operation_view, + source_report.get("selected_sources", ()), + ) + members = {path for group in selected + for path in group.evidence} + earlier = [replace(turn, evidence=tuple( + item for item in turn.evidence + if item.path in members + )) for turn in earlier] evidence = _add_related_evidence( - evidence, - [self.turns[number - 1] for number in related_turns], + evidence, earlier, + **({"exact_identity": True} if grouped else {}), ) effective["related_evidence_count"] = len(evidence) - found effective["evidence_from_turns"] = related_turns + if operation_view is None and ( + source_limits is not None or paper_request(question) + ) and not bibliography_lookup(question, scope): + evidence = tuple(item for item in evidence + if document_candidate(item.path)) if source_limits is not None: # This *final* limit includes context expansion and # related turns; neither can bypass the hard budget. chosen_sources = tuple( source_report.get("selected_sources", ()) ) - limited = allocate_evidence( - evidence, - source_limits, - priority_sources=chosen_sources, + grouped = (operation_view is not None + and operation_view.operation.policy.grouped) + groups = (_selected_groups(operation_view, chosen_sources) + if grouped else ()) + limited = ( + allocate_group_evidence( + evidence, source_limits, groups, + ) if grouped else allocate_evidence( + evidence, source_limits, + priority_sources=chosen_sources, + ) ) evidence = tuple( replace(item, citation=index) @@ -2311,7 +2564,23 @@ def ask_user( ) # Exhaustive mode means *all requested sources*, not # merely those retained by the source-count cap. - if source_limits.coverage == COVERAGE_EXHAUSTIVE: + if grouped: + requested = ( + tuple(group.anchor + for group in operation_view.groups) + if source_limits.coverage == COVERAGE_EXHAUSTIVE + else tuple(dict.fromkeys( + (*scope, *chosen_sources) + )) + ) + elif operation_view is not None: + if source_limits.coverage == COVERAGE_EXHAUSTIVE: + requested = rank_members(operation_view) + else: + requested = tuple(dict.fromkeys( + (*scope, *chosen_sources) + )) + elif source_limits.coverage == COVERAGE_EXHAUSTIVE: if len(scope) > 1: requested = tuple(dict.fromkeys(scope)) elif len(scope) == 1 and not ( @@ -2326,6 +2595,11 @@ def ask_user( ) else: requested = chosen_sources or tuple(scope) + if operation_view is None and not bibliography_lookup( + question, scope + ): + requested = tuple(path for path in requested + if document_candidate(path)) unreadable = tuple( path for path in requested if path not in set(indexed) ) @@ -2337,23 +2611,28 @@ def ask_user( if len(candidates) > len(chosen_sources): if len(chosen_sources) >= source_limits.max_sources: source_hits.append("sources") - if len(chosen_sources) >= source_limits.max_passages: + if (not grouped and len(chosen_sources) + >= source_limits.max_passages): source_hits.append("passages") hits = tuple( dict.fromkeys( (*raw_hits, *source_hits, *limited.limits_hit) ) ) - coverage = coverage_report( - requested, - evidence, - mode=source_limits.coverage, - unavailable=unreadable, - limits_hit=hits, - ) + if grouped: + coverage, answer_groups = grouped_coverage_report( + operation_view, evidence, groups, requested, + mode=source_limits.coverage, limits_hit=hits, + ) + else: + coverage = coverage_report( + requested, evidence, mode=source_limits.coverage, + unavailable=unreadable, limits_hit=hits, + ) + represented = (coverage["represented_anchors"] if grouped + else len({item.path for item in evidence})) specified = requested_source_count(question) if specified: - represented = len({item.path for item in evidence}) coverage["specified_source_count"] = specified coverage["specified_count_met"] = ( represented >= specified @@ -2366,7 +2645,24 @@ def ask_user( data=coverage, turn_id=turn_id, ) - if ( + if grouped and (coverage["missing_anchors"] or ( + source_limits.coverage == COVERAGE_EXHAUSTIVE + and not coverage["complete"] + )): + coverage_notice = ( + "Coverage incomplete: original anchor evidence " + f"represents {represented} of " + f"{coverage['requested_groups']} requested " + "logical documents. Supporting passages do not " + "establish " + "that an unrepresented anchor was read." + ) + if not coverage["physical_complete"]: + coverage_notice += ( + " Some physical evidence members were omitted " + "or unavailable." + ) + elif ( source_limits.coverage == COVERAGE_EXHAUSTIVE and not coverage["complete"] ): @@ -2382,7 +2678,6 @@ def ask_user( " Some sources had no searchable text." ) if specified and not coverage["specified_count_met"]: - represented = len({item.path for item in evidence}) shortfall = ( f"The question requested {specified} sources; " f"evidence represents only {represented}. " @@ -2407,11 +2702,22 @@ def ask_user( ANSWER_PHASE_RETRIEVING, message="Finding the document to read", ) + if live_workspace and intent.tool is None: + operation_view = self._ordinary_source_view( + ToolRequest( + question, search_text, + earlier=self._earlier_turns( + decision, excluded_turn_ids=excluded_turn_ids + ), + ), intent, + ) selection = self._read_document( search_text, intent.max_tokens, retrieval_count, trace_turn_id=turn_id, + **({"view": operation_view} if operation_view is not None + else {}), ) if selection is None: evidence = () @@ -2435,6 +2741,19 @@ def ask_user( skipped=True, ) + if operation_view is not None: + self._check_index_generation(operation_view) + allowed = set(rank_members(operation_view)) + paths = {item.path for item in evidence} + if not paths <= allowed: + raise SourceViewConflict( + "Evidence exceeded the source view." + ) + effective["evidence_source_sha256"] = { + item.path.as_posix(): item.sha256 + for item in operation_view.operation.inventory.files + if item.path in paths and item.sha256 is not None + } trace.emit( "retrieval.result", component="rag", @@ -2464,7 +2783,9 @@ def ask_user( ANSWER_PHASE_MEMORY_RETRIEVING, message="Retrieving conversation memories", ) - memory_index = self.sync_conversation_memory() + memory_index = self.sync_conversation_memory( + trace_turn_id=turn_id + ) memory_recall_checked = historical_topic is not None previously_shown = frozenset( self.turns[number - 1].conversation_turn_uuid @@ -2627,12 +2948,15 @@ def ask_user( ), ] ) + if operation_view is not None: + self._check_index_generation(operation_view) prompt = _answer_prompt( question, evidence, resolved_guidance, memory_hits=memory_hits, memory_recall_checked=memory_recall_checked, + **({"groups": answer_groups} if answer_groups else {}), ) trace.emit( "generation.input.prepared", @@ -2866,6 +3190,7 @@ def switch_conversation( trace: TraceSink Caller-owned trace sink associated with the target conversation. When enabled, its output path must be the target conversation path. + Its enabled state must match the session's shared project sink. Returns ------- @@ -2877,8 +3202,8 @@ def switch_conversation( RuntimeError If the session has already been closed. ValueError - If the path, saved state, restored history, or saved generation - settings are invalid. + If tracing activation differs, or the path, saved state, restored + history, or saved generation settings are invalid. OSError If saved state or trace writes cannot be accessed. @@ -2886,14 +3211,24 @@ def switch_conversation( ----- Loaded models and indexes are reused. The target file's exclusive ownership is validated or acquired before releasing the old path. - A failed acquisition or JSON read leaves the active session unchanged. - Later model/history reconfiguration is not fully transactional. + Failed acquisition, JSON reads, or persisted schema/checkpoint + validation leave the active session unchanged. Later model/history + reconfiguration is not fully transactional. Generation settings come from the last saved turn or profile defaults. + Switching preserves the shared project sink and its ownership. + A tracing mismatch is rejected before resolving the target path + or changing conversation state or file ownership. """ if self._closed: raise RuntimeError("This RAG session is closed.") + project_trace = getattr(self, "project_trace", None) + if ( + project_trace is not None + and project_trace.enabled != trace.enabled + ): + raise ValueError("Project and conversation tracing must agree.") target_path = self._resolve_conversation_path(conversation_path) _check_conversation_trace(trace, target_path) old_ownership = getattr(self, "_conversation_ownership", None) @@ -2935,6 +3270,9 @@ def switch_conversation( self._conversation_ownership = target_ownership self.chat_session.trace = trace self.embedding_session.trace = trace + router = getattr(self, "_router_session", None) + if router is not None: + router.trace = trace self.conversation_path = target_path self.chat_session.reset() if messages: @@ -2961,6 +3299,7 @@ def switch_conversation( data={ "message_count": len(messages), "turn_count": len(turns), + "turn_uuids": [turn.conversation_turn_uuid for turn in turns], "path": str(self.conversation_path), "checkpoint_id": checkpoint_id, "models_reused": True, @@ -2990,19 +3329,31 @@ def reset(self: RAGSession) -> Path | None: turns/checkpoint identity, and resets the chat history to its system instruction. An enabled trace then discards conversation-specific retained state before recording the reset in a fresh active file. - Loaded models, indexes, and non-conversation trace context are reused. + Project-numbered events remain only in the archived trace; standalone + traces retain their earlier non-conversation context. Loaded models + and indexes are reused. """ if self._closed: raise RuntimeError("This RAG session is closed.") archived_checkpoint_id = getattr(self, "_checkpoint_id", None) + trace = getattr(self, "trace", NullTraceLogger()) + if ( + isinstance(trace, TraceLogger) + and trace.sequence_scope == "project" + ): + trace.flush() archived_path = self._archive_conversation() self.chat_session.reset() self.turns = [] self._checkpoint_id = None - trace = getattr(self, "trace", NullTraceLogger()) - trace.reset_conversation_state() + if isinstance(trace, TraceLogger): + trace.reset_conversation_state( + archived=archived_path is not None + ) + else: + trace.reset_conversation_state() trace.emit( "conversation.reset", component="rag", @@ -3073,17 +3424,18 @@ def close(self: RAGSession) -> None: return self._closed = True trace = getattr(self, "trace", NullTraceLogger()) + project_trace = self._project_diagnostics() errors = self._close_model_sessions() try: if errors: - trace.emit( + project_trace.emit( "session.closed", component="rag", status="failed", data={"model_cleanup_errors": len(errors)}, ) else: - trace.emit("session.closed", component="rag") + project_trace.emit("session.closed", component="rag") except BaseException as error: errors.append(error) try: @@ -3092,6 +3444,11 @@ def close(self: RAGSession) -> None: except BaseException as error: errors.append(error) finally: + if getattr(self, "_owns_project_trace", False): + try: + project_trace.close() + except BaseException as error: + errors.append(error) ownership = getattr(self, "_conversation_ownership", None) if ownership is not None: self._conversation_ownership = None @@ -3104,7 +3461,10 @@ def close(self: RAGSession) -> None: errors[0].add_note(f"Additional cleanup failure: {error!r}") raise errors[0] - def refresh_sources(self: RAGSession, project: QAProject) -> None: + def refresh_sources( + self: RAGSession, project: QAProject, *, + on_organization: Callable[[SourceLifecycleResult], None] | None = None, + ) -> SourceLifecycleResult: """Update the indexes after sources were added, changed, or removed. The loaded models and the conversation stay; only the indexes are @@ -3114,7 +3474,16 @@ def refresh_sources(self: RAGSession, project: QAProject) -> None: Parameters ---------- project: QAProject - The project reopened after its sources changed. + The project after its sources changed. The saved profile is + reopened and the captured source directory validated first. + on_organization: Callable or None, optional + Observe the semantic outcome before indexing starts, including + when subsequent indexing fails. Defaults to None. + + Returns + ------- + SourceLifecycleResult + Semantic reconciliation outcome independent of indexing. Notes ----- @@ -3124,26 +3493,84 @@ def refresh_sources(self: RAGSession, project: QAProject) -> None: """ + if on_organization is not None and not callable(on_organization): + raise TypeError("on_organization must be callable or None.") + # Reject stale or fabricated layouts before changing the session, + # publishing semantic state, or opening an indexing trace. + validate_project_sources(project.root, project.source) + project = open_project(project.root) + _source_records(project.root, allow_mirror=True) self.project = project - with self.trace.span( - "indexing", - component="rag", - data={"project_directory": str(project.root), "refresh": True}, - ): - chunks, indexes, status, source_changes = self._prepare_retrieval( - self.embedding_session - ) - cards, vectors = self._prepare_source_cards( - chunks, - indexes, - self.embedding_session, + organization = refresh_source_manifest( + project, trace=self._project_diagnostics(), + ) + _report_lifecycle(organization, on_organization) + self._suggestion_pool = None + self._progress_last_trace_percent.clear() + identity_fields = ( + "_current_index_source_state", "_prepared_index_metadata", + "_prepared_source_root", ) + previous = {name: getattr(self, name, None) + for name in identity_fields} + try: + with self._project_embedding_diagnostics(): + with self._project_diagnostics().span( + "indexing", component="rag", + data={"project_directory": str(project.root), + "refresh": True}, + ): + chunks, indexes, status, source_changes = ( + self._prepare_retrieval(self.embedding_session) + ) + cards, vectors = self._prepare_source_cards( + chunks, indexes, self.embedding_session, + ) + except BaseException: + # Keep the generation identity of the still-loaded indexes. + for name, value in previous.items(): + setattr(self, name, value) + raise self.chunks = chunks self.indexes = indexes self.index_status = status self.source_changes = source_changes self.source_cards = cards self.source_card_vectors = vectors + return organization + + def refresh_source_metadata(self: RAGSession) -> SourceMetadataRefresh: + """Refresh accepted semantics and suggestions without indexing. + + Returns + ------- + SourceMetadataRefresh + Fresh inspection (including selected/current and pending paths) + and regenerated headings using only the saved word pool. + + Raises + ------ + RuntimeError + If the session is closed. + ValueError, OSError + If the saved semantic metadata cannot be inspected. + + Notes + ----- + Intended after a committed role/link edit, not a physical source + change. Do not change the active profile, chunks, vectors, cards, + conversation or models. Role-aware retrieval views are a separate + boundary; suggestions retain the existing physical-file policy. + + """ + if self._closed: + raise RuntimeError("This RAG session is closed.") + inspection = inspect_source_manifest(self.project) + self._suggestion_pool = None + return SourceMetadataRefresh( + inspection, tuple(self.question_suggestions(generate=False)), + tuple(self.welcome_prompts(generate=False)), + ) def regenerate_source_cards(self: RAGSession) -> None: """Regenerate selected cards without rebuilding ordinary indexes. @@ -3152,6 +3579,8 @@ def regenerate_source_cards(self: RAGSession) -> None: ------ RuntimeError If the session is closed or source cards are disabled. + ValueError, OSError + If the current source layout or ownership cannot be validated. Notes ----- @@ -3163,17 +3592,24 @@ def regenerate_source_cards(self: RAGSession) -> None: if self._closed: raise RuntimeError("This RAG session is closed.") + validate_project_sources(self.project.root, self.project.source) + current = open_project(self.project.root) + _source_records(current.root, allow_mirror=True) policy = read_source_card_policy( self.project.root, self._behavior_config() ) if not policy.enabled: raise RuntimeError("Enable source cards before regenerating.") - cards, vectors = self._prepare_source_cards( - self.chunks, - self.indexes, - self.embedding_session, - force_regenerate=True, - ) + with ( + self._project_embedding_diagnostics(), + self._project_diagnostics().span( + "project.source_cards.regenerate", component="rag" + ), + ): + cards, vectors = self._prepare_source_cards( + self.chunks, self.indexes, self.embedding_session, + force_regenerate=True, + ) self.source_cards = cards self.source_card_vectors = vectors @@ -3184,6 +3620,8 @@ def refresh_source_cards(self: RAGSession) -> None: ------ RuntimeError If the session is closed. + ValueError, OSError + If the current source layout or ownership cannot be validated. Notes ----- @@ -3194,11 +3632,13 @@ def refresh_source_cards(self: RAGSession) -> None: if self._closed: raise RuntimeError("This RAG session is closed.") - cards, vectors = self._prepare_source_cards( - self.chunks, - self.indexes, - self.embedding_session, - ) + validate_project_sources(self.project.root, self.project.source) + current = open_project(self.project.root) + _source_records(current.root, allow_mirror=True) + with self._project_embedding_diagnostics(): + cards, vectors = self._prepare_source_cards( + self.chunks, self.indexes, self.embedding_session, + ) self.source_cards = cards self.source_card_vectors = vectors @@ -3266,11 +3706,18 @@ def _card_generation_guard(self: RAGSession) -> Iterator[None]: "Reopen the project." ) from release_error try: - self.trace.emit("source_cards.chat.released", component="rag") + self._project_diagnostics().emit( + "source_cards.chat.released", component="rag" + ) yield finally: try: - restored = self._new_chat_session(previous.model_id, **options) + restored = self._new_chat_session( + previous.model_id, + trace=self._project_diagnostics(), + **options, + ) + restored.trace = self.trace try: restored.restore_history(messages) restored.input_token_total = totals[0] @@ -3279,7 +3726,9 @@ def _card_generation_guard(self: RAGSession) -> Iterator[None]: restored.close() raise self.chat_session = restored - self.trace.emit("source_cards.chat.restored", component="rag") + self._project_diagnostics().emit( + "source_cards.chat.restored", component="rag" + ) except BaseException as error: self.chat_session = None try: @@ -3724,7 +4173,7 @@ def _prepare_source( selected_count, reading_started, ) - with self.trace.span( + with self._project_diagnostics().span( "source.read", component="rag", data={"selected_file_count": selected_count}, @@ -3766,7 +4215,7 @@ def _prepare_source( for name in selected if name in reused or name in read ] - self.trace.emit( + self._project_diagnostics().emit( "source.read.summary", component="rag", data={ @@ -3796,7 +4245,7 @@ def _prepare_source( source_file_count, extracting_started, ) - with self.trace.span( + with self._project_diagnostics().span( "source.extract", component="rag", data={"file_count": source_file_count}, @@ -3841,7 +4290,7 @@ def _prepare_source( "max_tokens": profile.max_tokens, "overlap_tokens": profile.overlap_tokens, } - with self.trace.span( + with self._project_diagnostics().span( "source.chunk", component="rag", data={"unit_count": unit_count, **chunk_settings}, @@ -3876,7 +4325,7 @@ def _prepare_source( Path(name), fresh_by_path.get(Path(name), []) ) ] - self.trace.emit( + self._project_diagnostics().emit( "source.chunk.summary", component="rag", data={ @@ -3897,7 +4346,7 @@ def _prepare_source( current=len(chunks), total=len(chunks), ) - with self.trace.span( + with self._project_diagnostics().span( "index.code_graph.build", component="rag", data={"chunk_count": len(chunks)}, @@ -3953,7 +4402,7 @@ def _prepare_retrieval( Notes ----- - A selected-source manifest and stored configuration metadata control + The index source state and stored configuration metadata control reuse. Existing vectors are loaded only if the stored bundle is accepted. Source completeness is not checked here; index and metadata files are written separately rather than as one transaction. @@ -3984,7 +4433,7 @@ def _prepare_retrieval( "selected_files": report.get("selected_files", []), "entries": report.get("entries", []), } - self.trace.emit( + self._project_diagnostics().emit( "source.scan.completed", component="rag", data=report_data, @@ -4000,13 +4449,13 @@ def _prepare_retrieval( current_manifest = build_repository_manifest(report) index_path = self.project.indexes / "retrieval.json" metadata_path = self.project.indexes / "settings.json" - manifest_path = self.project.indexes / "source_manifest.json" + state_path = self.project.indexes / "index_source_state.json" expected_metadata = self._index_metadata() saved_manifest: dict[str, object] | None = None saved_metadata: dict[str, object] | None = None - if manifest_path.is_file(): + if state_path.is_file(): try: - value = json.loads(manifest_path.read_text(encoding="utf-8")) + value = json.loads(state_path.read_text(encoding="utf-8")) if isinstance(value, dict): saved_manifest = value except (OSError, json.JSONDecodeError): @@ -4034,7 +4483,10 @@ def _prepare_retrieval( saved_metadata.get(key) != value for key, value in expected_metadata.items() ) - return self._empty_retrieval(changes, current_manifest) + result = self._empty_retrieval(changes, current_manifest) + self._prepared_index_metadata = expected_metadata + self._prepared_source_root = self.project.source.resolve() + return result # Bind the saved vectors to the actual loaded model, not merely to # its configured ID or directory path. Cache identity on the loaded @@ -4055,13 +4507,14 @@ def _prepare_retrieval( configuration_changed = saved_metadata != expected_metadata changes["configuration_changed"] = configuration_changed - self.trace.emit( + self._project_diagnostics().emit( "index.check.completed", component="rag", data={ "index_path": str(index_path), "metadata_path": str(metadata_path), - "manifest_path": str(manifest_path), + "manifest_path": str(state_path), + "source_manifest": current_manifest, "expected_metadata": expected_metadata, "saved_metadata": saved_metadata, "changes": changes, @@ -4077,7 +4530,7 @@ def _prepare_retrieval( self._emit_progress( "validating_index", 28.0, - "Validating saved index metadata and source manifest...", + "Validating saved index metadata and index source state...", ) if ( @@ -4093,7 +4546,7 @@ def _prepare_retrieval( 32.0, "Source unchanged; loading the saved retrieval index...", ) - with self.trace.span( + with self._project_diagnostics().span( "index.load", component="rag", data={"index_path": str(index_path)}, @@ -4103,7 +4556,7 @@ def _prepare_retrieval( raise ValueError( "Saved index embedding model identity differs." ) - self.trace.emit( + self._project_diagnostics().emit( "index.reused", component="rag", data={ @@ -4117,7 +4570,9 @@ def _prepare_retrieval( 85.0, "Saved retrieval index loaded.", ) - self._current_source_manifest = current_manifest + self._current_index_source_state = current_manifest + self._prepared_index_metadata = expected_metadata + self._prepared_source_root = self.project.source.resolve() return ( list(indexes.semantic.chunks), indexes, @@ -4130,7 +4585,7 @@ def _prepare_retrieval( ValueError, json.JSONDecodeError, ) as error: - self.trace.exception( + self._project_diagnostics().exception( "index.load.failed", error, component="rag", @@ -4186,7 +4641,10 @@ def _prepare_retrieval( cached_chunks=cached_chunks, ) if not chunks: - return self._empty_retrieval(changes, current_manifest) + result = self._empty_retrieval(changes, current_manifest) + self._prepared_index_metadata = expected_metadata + self._prepared_source_root = self.project.source.resolve() + return result # A chunk is embedded unless an identical saved chunk has a vector. pending_chunks = [ chunk @@ -4195,7 +4653,7 @@ def _prepare_retrieval( ] embedding_started = perf_counter() chunk_count = len(pending_chunks) - self.trace.emit( + self._project_diagnostics().emit( "index.incremental.plan", component="rag", data={ @@ -4216,7 +4674,7 @@ def _prepare_retrieval( chunk_count, embedding_started, ) - with self.trace.span( + with self._project_diagnostics().span( "index.semantic.build", component="rag", data={ @@ -4285,7 +4743,7 @@ def _prepare_retrieval( current=len(chunks), total=len(chunks), ) - with self.trace.span( + with self._project_diagnostics().span( "index.lexical.build", component="rag", data={"chunk_count": len(chunks)}, @@ -4306,27 +4764,27 @@ def _prepare_retrieval( self._emit_progress( "saving_index", 82.0, - "Saving retrieval index and manifests...", + "Saving retrieval index and source state...", ) - with self.trace.span( + with self._project_diagnostics().span( "index.save", component="rag", data={ "index_path": str(index_path), "metadata_path": str(metadata_path), - "manifest_path": str(manifest_path), + "manifest_path": str(state_path), }, ): save_indexes(indexes, index_path) _write_json(metadata_path, expected_metadata) - _write_json(manifest_path, current_manifest) - self.trace.emit( + _write_json(state_path, current_manifest) + self._project_diagnostics().emit( "index.rebuilt", component="rag", data={ "index_path": str(index_path), "metadata_path": str(metadata_path), - "manifest_path": str(manifest_path), + "manifest_path": str(state_path), "fingerprint": indexes.fingerprint, "chunk_count": len(chunks), "changes": changes, @@ -4337,7 +4795,9 @@ def _prepare_retrieval( 85.0, "Retrieval index saved.", ) - self._current_source_manifest = current_manifest + self._current_index_source_state = current_manifest + self._prepared_index_metadata = expected_metadata + self._prepared_source_root = self.project.source.resolve() return chunks, indexes, "rebuilt", changes def _empty_retrieval( @@ -4368,17 +4828,20 @@ def _empty_retrieval( """ - self._current_source_manifest = manifest + self._current_index_source_state = manifest indexes = PersistentIndexes( fingerprint="", semantic=SemanticIndex((), ()), lexical=LexicalIndex((), (), {}), code_graph=CodeGraph((), ()), ) - self.trace.emit( + self._project_diagnostics().emit( "index.empty", component="rag", - data={"chunk_count": 0, "changes": changes}, + data={ + "chunk_count": 0, "changes": changes, + "source_manifest": manifest, + }, ) self._emit_progress( "index_ready", @@ -4387,6 +4850,259 @@ def _empty_retrieval( ) return [], indexes, "empty", changes + def _index_generation(self: RAGSession) -> str: + """Identify the loaded physical index, not the current profile. + + Returns + ------- + str + Digest of indexed file identities, index fingerprint, model + identity and settings accepted during index preparation. + + """ + data = { + "state": getattr(self, "_current_index_source_state", None), + "settings": getattr(self, "_prepared_index_metadata", None), + "fingerprint": self.indexes.fingerprint, + "embedding_model": getattr( + self.indexes, "embedding_model_identity", None + ), + } + return sha256(json.dumps(data, sort_keys=True, separators=(",", ":")) + .encode("utf-8")).hexdigest() + + def _source_operation_state( + self: RAGSession, + ) -> tuple[SourceManifestInspection, SourceInventory]: + """Capture current accepted metadata against the loaded generation. + + Returns + ------- + tuple[SourceManifestInspection, SourceInventory] + Live selection and matching physical inventory. No reconciliation + or embedding is performed. + + Raises + ------ + SourceViewConflict + If the loaded index and current source binding disagree. + + """ + validate_project_sources(self.project.root, self.project.source) + inspection = inspect_source_manifest(self.project) + binding = inspection.source_root + source = (self.project.root / binding.path).resolve() + if source != getattr(self, "_prepared_source_root", + self.project.source.resolve()): + raise SourceViewConflict("Source root changed; refresh sources.") + state = getattr(self, "_current_index_source_state", None) + if not isinstance(state, Mapping): + raise SourceViewConflict( + "No captured index state; refresh sources." + ) + inventory = capture_source_inventory( + inspection, state, {chunk.path for chunk in self.chunks}, + self._index_generation(), + ) + return inspection, inventory + + def source_view( + self: RAGSession, policy: SourcePolicy = SourcePolicy(), + scope: SourceScope = SourceScope(), + ) -> SourceView: + """Resolve a view against this session's live accepted source state. + + Parameters + ---------- + policy: SourcePolicy, optional + Operation purpose, role filters, and permitted relationships. + Defaults to independent-document discovery. + scope: SourceScope, optional + Project-wide, preferred or restricted physical operands. + Defaults to project-wide. + + Returns + ------- + SourceView + Frozen operation membership suitable for a retrieval request. + + Notes + ----- + This read-only method does not initialize or reconcile metadata, + load models, or rebuild indexes. Stale or invalid metadata fails + explicitly. Call again after a committed change to obtain a new view. + + """ + inspection, inventory = self._source_operation_state() + return resolve_source_view(inspection, inventory, policy, scope) + + def _check_index_generation( + self: RAGSession, view: SourceView, + ) -> None: + """Reject a physical index change during a frozen operation. + + Parameters + ---------- + view: SourceView + Operation captured at the start of retrieval. + + Raises + ------ + SourceViewConflict + If a refresh replaced the indexed generation. + + """ + if self._index_generation() != ( + view.operation.inventory.index_generation + ): + raise SourceViewConflict( + "Index generation changed; restart operation." + ) + + def _ordinary_source_view( + self: RAGSession, request: ToolRequest, intent: Intent, + *, compare: bool = False, route_scope: bool = False, + ) -> SourceView: + """Resolve one ordinary answer's scope and accepted intent policy. + + Parameters + ---------- + request: ToolRequest + Current question, retrieval text and related turns. + intent: Intent + Effective ordinary-intent retrieval settings. + compare: bool, optional + Existing source-first comparison preference. Defaults to False. + route_scope: bool, optional + Use the existing document-scope router for search. Document + reading and reuse need no additional model call. Defaults to False. + + Returns + ------- + SourceView + Frozen evidence or explicit lookup membership. + + """ + inspection, inventory = self._source_operation_state() + policy = SourcePolicy( + related_evidence=intent.related_evidence, + related_lookup=intent.related_lookup, + grouped=route_scope and intent.grouped, + ) + project_view = resolve_source_view(inspection, inventory, policy) + selected = inventory.selected + known = tuple(dict.fromkeys((*selected, *( + Path(item.path) for item in inspection.inactive_files + )))) + # Include unavailable selected operands (and known removed paths) + # in naming, so an unavailable target does not become project-wide. + named = named_paths(request.question, known, authors=True) + if any(path not in selected for path in named): + raise SourceViewConflict("Named source is no longer selected.") + # An explicit physical operand may be a dependent file even in a + # paper-oriented question. Keep document discovery strict, but use + # physical lookup for the named operands of this ordinary answer. + if bibliography_lookup(request.question, named): + policy = replace(policy, purpose="lookup", grouped=False) + project_view = resolve_source_view(inspection, inventory, policy) + elif named and any(path not in project_view.targets for path in named): + policy = replace(policy, purpose="lookup", grouped=False, + related_evidence=(), related_lookup=()) + return resolve_source_view( + inspection, inventory, policy, + SourceScope("restricted", tuple(named)), + ) + scope, _ = document_scope( + request, self._ask_router if route_scope else _all_documents, + list(known), self._card_metadata(view=project_view), + ) + if named and not set(named) <= set(scope): + # An unresolved comparison target must not erase the known + # operand. Ineligible explicit documentary targets fail below. + scope = named + if asks_for_all_sources(request.question) and not named: + scope = () + if not scope: + return project_view + if any(path not in selected for path in scope): + raise SourceViewConflict( + "Referenced source is no longer selected." + ) + if (policy.purpose == "document" + and not paper_request(request.question) + and any(path not in project_view.targets for path in scope)): + policy = replace(policy, purpose="lookup", grouped=False) + mode = ("preferred" if compare and len(scope) == 1 + and policy.purpose == "document" else "restricted") + return resolve_source_view( + inspection, inventory, policy, SourceScope(mode, tuple(scope)), + ) + + def _current_evidence_turns( + self: RAGSession, turns: Sequence[ConversationTurn], view: SourceView, + ) -> list[ConversationTurn]: + """Prepare current-evidence copies of earlier turns, not history edits. + + Parameters + ---------- + turns: Sequence[ConversationTurn] + Original saved turns, with their historical citations. + view: SourceView + Current accepted operation, including physical content identities. + + Returns + ------- + list[ConversationTurn] + Temporary copies containing only current, authorized evidence. + Old records without source-content identity are not reused. + + """ + self._check_index_generation(view) + allowed = set(rank_members(view)) + state = {item.path: item.sha256 + for item in view.operation.inventory.files if item.indexed} + keys = {_evidence_identity(chunk) for chunk in self.chunks + if chunk.path in allowed} + verified: dict[Path, bool] = {} + source = self.project.source.resolve() + copies = [] + for turn in turns: + digests = turn.parameters.get("evidence_source_sha256", {}) + retained = [] + for item in turn.evidence: + path = item.path + digest = state.get(path) + if (path not in allowed or not digest + or not isinstance(digests, Mapping) + or digests.get(path.as_posix()) != digest + or _evidence_identity(item) not in keys): + continue + if path not in verified: + # Verify only the earlier files actually reused. No + # full-corpus hashing or second query embedding. + try: + candidate = source / path + current = source + for part in path.parts: + current = current / part + if current.is_symlink() or current.is_junction(): + raise OSError("Linked source") + if not candidate.resolve(strict=True).is_relative_to( + source + ): + raise OSError("Source escaped its root") + actual = build_repository_manifest({ + "complete": True, "repository": str(source), + "selected_files": [path.as_posix()], + })["files"][path.as_posix()]["sha256"] + verified[path] = actual == digest + except (OSError, ValueError): + verified[path] = False + if verified[path]: + retained.append(item) + copies.append(replace(turn, evidence=tuple(retained))) + return copies + def _retrieve( self: RAGSession, question: str, @@ -4400,7 +5116,10 @@ def _retrieve( source_limits: EvidenceLimits | None = None, source_report: dict[str, object] | None = None, card_kinds: tuple[str, ...] = (), + include_bibliographies: bool | None = None, _query_vectors: dict[str, list[float]] | None = None, + view: SourceView | None = None, + scope_mode: ScopeMode, ) -> tuple[Evidence, ...]: """Run hybrid retrieval and deterministic context expansion. @@ -4419,10 +5138,9 @@ def _retrieve( Receives a short message before and after each search step, for progress display. Defaults to ``None``. scope: Sequence[pathlib.Path], optional - Preferred documents from ``document_scope``. A single path - supplies the initial passages when available, but cross-file - expansion remains allowed. Requested sources are prioritized - and evidence provenance is labeled. Defaults to ``()``. + Explicit operands of the normalized scope. Preferred operands + are ranked first; restricted operands limit physical membership + when no resolved view is supplied. Defaults to ``()``. prefer_source_code: bool, optional Let each channel rank ``SOURCE_SEARCH_DEPTH`` times deeper and keep its best source-code results (``prefer_source_results``), @@ -4446,6 +5164,15 @@ def _retrieve( card_kinds: tuple[str, ...], optional Only these card kinds participate in source-first discovery. Empty permits every kind. Defaults to ``()``. + include_bibliographies: bool | None, optional + Source-first bibliography lookup policy. None recognizes an + explicit bibliography query or scope; False excludes containers + from independent-document discovery. Defaults to None. + view: SourceView | None, optional + Frozen operation. Only its ranked physical members participate. + scope_mode: ScopeMode + Normalized project, preferred or restricted mode. A resolved + view supplies the authoritative scope and physical membership. _query_vectors: dict[str, list[float]] | None, optional Request-local cache of embeddings for repeated retrieval of the exact same formatted question. Never persisted or reused @@ -4464,12 +5191,12 @@ def _retrieve( apply after expansion; other strategies keep their prior expansion behavior. Trace details use previews and evidence keeps full text. - The semantic loop already scores every chunk. Retain that complete - ranking for related-passage scoring and for ``_rank_everything`` - when focusing on one document, without an additional query embedding. - This keeps the document's best passages available even when outside - the project-wide top results. Query scores are local to this call; - they are never reused across different queries or indexes. + The semantic loop already scores every eligible chunk. Retain that + ranking for source selection and related-passage scoring. Preferred + scopes rank eligible passages before prioritizing their operands; + restricted scopes rank only authorized physical members. Query + scores are local to this call and are never reused across different + queries or indexes. """ @@ -4487,6 +5214,8 @@ def report(message: str) -> None: if status_callback is not None: status_callback(message) + if scope_mode not in ("project", "preferred", "restricted"): + raise ValueError("Unknown source scope mode.") if source_first is not None and ( type(source_first) is not tuple or len(source_first) != 2 @@ -4499,9 +5228,74 @@ def report(message: str) -> None: raise ValueError("Source limits require source_first retrieval.") if card_kinds and source_first is None: raise ValueError("Card filters require source_first retrieval.") - if not self.chunks: + grouped = view is not None and view.operation.policy.grouped + if grouped and (source_first is None or source_limits is None): + raise ValueError("Grouped retrieval requires source_first limits.") + allowed = None + if view is not None: + self._check_index_generation(view) + scope_mode = view.operation.scope.mode + scope = view.operation.scope.paths + allowed = frozenset(rank_members(view)) + # An explicit lookup view is authoritative over lexical cues. + include_bibliographies = view.operation.policy.purpose == "lookup" + elif scope_mode == "restricted": + allowed = frozenset(scope) + if grouped and not any( + chunk.path in allowed for chunk in self.chunks + ): + # Named/unindexed anchors and exhaustive membership remain + # visible without embedding a query against an empty index. + self._source_passages( + (), (), (), (), count=source_limits.max_passages, + max_sources=source_limits.max_sources, + compare=source_first[1], scope=scope, + trace_turn_id=trace_turn_id, + per_source=source_limits.passages_per_source, + metadata=source_report, + exhaustive=source_limits.coverage == COVERAGE_EXHAUSTIVE, + requested=requested_source_count(question), + view=view, + ) + report("No indexed group evidence; skipping retrieval") + return () + if not self.chunks or allowed == frozenset(): report("No indexed source passages; skipping retrieval") return () + # Keep bibliography lookup distinct from independent discovery. + # Filter complete rankings before their channel positions or limits. + if include_bibliographies is None: + include_bibliographies = bibliography_lookup(question, scope) + exclude_bibliographies = ( + not include_bibliographies + and (source_first is not None or paper_request(question)) + ) + if exclude_bibliographies and allowed is not None: + allowed = frozenset(path for path in allowed + if document_candidate(path)) + if exclude_bibliographies and ( + (scope and not any(document_candidate(path) for path in scope)) + or not any(document_candidate(chunk.path) for chunk in self.chunks) + ): + report("No eligible independent documents; skipping retrieval") + return () + if allowed is not None and not any( + chunk.path in allowed for chunk in self.chunks + ): + report("No indexed passages in the source scope") + return () + scoped = scoped_indexes( + self.chunks, self.indexes.semantic, self.indexes.lexical, + self.indexes.code_graph, allowed, + ) + chunks, graph = scoped.chunks, scoped.code_graph + card_paths = {chunk.path for chunk in chunks + if document_candidate(chunk.path)} + if view is not None: + card_paths.intersection_update(view.candidates) + # Preferred operands are prioritized only after all eligible + # channels have had a chance to contribute their ranks. + preferred = scope_mode == "preferred" and bool(scope) count = retrieval_count or self.project.profile.retrieval_count if source_limits is not None: count = source_limits.max_passages @@ -4563,7 +5357,8 @@ def keep(results: list) -> list: has_source_cards = isinstance( vector_index, SourceCardVectorIndex ) and any( - not card_kinds or entry.kind in card_kinds + entry.path in card_paths + and (not card_kinds or entry.kind in card_kinds) for entry in vector_index.records ) if query_vector is None and ( @@ -4579,13 +5374,13 @@ def keep(results: list) -> list: ) if _query_vectors is not None: _query_vectors[query_text] = query_vector - # The loop scorer already ranks every chunk. Retain its scores - # for focused retrieval and expansion, without embedding again. + # Retain complete eligible semantic scores for source selection + # and context expansion, without embedding the query again. semantic_results = semantic_search( - self.indexes.semantic, + scoped.semantic, query_text, self.embedding_session, - count=max(depth, len(self.chunks)), + count=max(depth, len(chunks)), trace_turn_id=trace_turn_id, **( {"query_vector": query_vector} @@ -4593,7 +5388,13 @@ def keep(results: list) -> list: else {} ), ) - semantic = keep(semantic_results[:depth]) + if exclude_bibliographies: + semantic_results = [ + item for item in semantic_results + if document_candidate(item.chunk.path) + ] + semantic = (list(semantic_results) if preferred + else keep(semantic_results[:depth])) trace.emit( "retrieval.semantic.ranked", component="retrieval", @@ -4611,15 +5412,22 @@ def keep(results: list) -> list: ): report("Running lexical search") lexical_results = lexical_search( - self.indexes.lexical, + scoped.lexical, question, count=( - max(depth, len(self.chunks)) - if source_first is not None + max(depth, len(chunks)) + if (source_first is not None or exclude_bibliographies + or preferred) else depth ), ) - lexical = keep(lexical_results[:depth]) + if exclude_bibliographies: + lexical_results = [ + item for item in lexical_results + if document_candidate(item.chunk.path) + ] + lexical = (list(lexical_results) if preferred + else keep(lexical_results[:depth])) trace.emit( "retrieval.lexical.ranked", component="retrieval", @@ -4636,12 +5444,12 @@ def keep(results: list) -> list: turn_id=trace_turn_id, ): code_results: list[CodeResult] = [] - if not self.indexes.code_graph.entities: + if not graph.entities: code = [] report( "No source relationships indexed; skipping graph search" ) - elif not names_code(question, self.indexes.code_graph): + elif not names_code(question, graph): # The graph channel follows named code; matching the words # of a prose question to identifiers only adds noise. code = [] @@ -4649,16 +5457,23 @@ def keep(results: list) -> list: else: report("Searching relationships between source entities") code_results = code_search( - self.indexes.code_graph, - self.chunks, + graph, + chunks, question, count=( - max(depth, len(self.chunks)) - if source_first is not None + max(depth, len(chunks)) + if (source_first is not None or exclude_bibliographies + or preferred) else depth ), ) - code = keep(code_results[:depth]) + if exclude_bibliographies: + code_results = [ + item for item in code_results + if document_candidate(item.chunk.path) + ] + code = (list(code_results) if preferred + else keep(code_results[:depth])) report("Relationship search ranked " f"{len(code)} results") trace.emit( "retrieval.code.ranked", @@ -4684,7 +5499,10 @@ def keep(results: list) -> list: kept = ( max(count, SOURCE_SEARCH_RESULTS) if prefer_source_code else count ) - combined = demote_test_results(candidates, question)[:kept] + candidates = demote_test_results(candidates, question) + if preferred: + candidates.sort(key=lambda item: item.chunk.path not in scope) + combined = candidates[:kept] trace.emit( "retrieval.hybrid.ranked", component="retrieval", @@ -4698,23 +5516,26 @@ def keep(results: list) -> list: # Source-first ranking can prioritize one or several named files. named = list(scope) - sources_chosen = False chosen_source_paths: tuple[Path, ...] = () source_metadata: dict[str, object] = {} + selected_groups: tuple[SourceGroup, ...] = () + group_candidates: list[HybridResult] = [] if source_first is not None: card_matches = ( search_source_cards( vector_index, query_vector, count=len(vector_index.records), + allowed_paths=frozenset(card_paths), ) if query_vector is not None and has_source_cards else () ) - if card_kinds: - card_matches = tuple( - match for match in card_matches if match.kind in card_kinds - ) + card_matches = tuple( + match for match in card_matches + if match.path in card_paths + and (not card_kinds or match.kind in card_kinds) + ) chosen = self._source_passages( semantic_results, lexical_results, @@ -4740,45 +5561,37 @@ def keep(results: list) -> list: and source_limits.coverage == COVERAGE_EXHAUSTIVE ), requested=requested_source_count(question), + include_bibliographies=include_bibliographies, + **({"view": view} if grouped else {}), ) chosen_source_paths = tuple( source_metadata.get("selected_sources", ()) ) if source_report is not None: source_report.update(source_metadata) - if chosen: - combined = chosen - sources_chosen = True - report( - f"Selected {len(combined)} original passages from " - f"{len({r.chunk.path for r in combined})} sources" - ) - # A named document supplies the primary passages; expansion may - # still add useful context from elsewhere in the repository. - if len(named) == 1 and not sources_chosen: - focused = [ - result - for result in self._rank_everything( - question, - trace_turn_id, - semantic_results=semantic_results, - ) - if result.chunk.path == named[0] - ][:count] - if focused: - combined = focused - report(f"Kept the passages of {named[0].name}") - trace.emit( - "retrieval.named_file.focused", - component="retrieval", - data={"path": str(named[0]), "count": len(focused)}, - turn_id=trace_turn_id, - ) + if grouped: + selected_groups = _selected_groups(view, chosen_source_paths) + # Keep the complete group ranking as a fallback for the + # budgeter (a top anchor passage may be too large). Expand + # only bounded seeds within the selected physical members. + group_candidates = chosen + chosen = chosen[:count] + allowed = frozenset(path for group in selected_groups + for path in group.evidence) + candidates = [item for item in candidates + if item.chunk.path in allowed] + chunks = [chunk for chunk in chunks if chunk.path in allowed] + graph = scoped_graph(graph, allowed) + combined = chosen + report( + f"Selected {len(combined)} original passages from " + f"{len({r.chunk.path for r in combined})} sources" + ) # Every fused candidate, not only the kept top results, may lead to # code: retrieved documentation, module headers, and tests. plan = plan_context_expansion( - question, self.indexes.code_graph, candidates + question, graph, candidates ) plan_data = asdict(plan) expansion_requested = any( @@ -4824,7 +5637,7 @@ def keep(results: list) -> list: if self._uses_document_headers() and plan.paths: documents = { chunk.path - for chunk in self.chunks + for chunk in chunks if chunk.kind in DOCUMENT_KINDS } expansion_plan = replace( @@ -4835,31 +5648,34 @@ def keep(results: list) -> list: ) expanded = expand_retrieval_context( combined, - self.chunks, - self.indexes.code_graph, + chunks, + graph, expansion_plan, relevance, ) if source_first is not None and source_limits is not None: - # Expansion must not bypass the selected source set. - allowed = set(chosen_source_paths) + # Expansion must not bypass the selected source set. Group + # anchors authorize their evidence members, not lookup text. + if not grouped: + allowed = set(chosen_source_paths) expanded = [chunk for chunk in expanded if chunk.path in allowed] - elif source_first is not None and len(named) > 1: - # Retain explicit scopes for direct calls without evidence limits. - allowed = set(named) + if allowed is not None: expanded = [chunk for chunk in expanded if chunk.path in allowed] + if exclude_bibliographies: + expanded = [chunk for chunk in expanded + if document_candidate(chunk.path)] direct_paths = set(plan.paths) | set(scope) direct_ids = { chunk.identifier for chunk in _chunks_for_functions( - self.chunks, self.indexes.code_graph, plan.functions + chunks, graph, plan.functions ) } alternative_ids = { chunk.identifier for chunk in _chunks_for_functions( - self.chunks, - self.indexes.code_graph, + chunks, + graph, plan.alternative_functions, ) } @@ -4913,6 +5729,14 @@ def context_role( data=expansion_data, turn_id=trace_turn_id, ) + if grouped: + # Consider every ranked eligible original passage, not just + # the initial seed count. This lets the allocator reserve a + # lower-ranked fitting anchor instead of losing it to long SI. + seen = {chunk.identifier for chunk in expanded} + expanded.extend(item.chunk for item in group_candidates + if item.chunk.identifier not in seen) + expanded.sort(key=lambda chunk: priorities[context_role(chunk)]) evidence = tuple( Evidence( citation=index, @@ -4927,10 +5751,13 @@ def context_role( for index, chunk in enumerate(expanded, start=1) ) if source_limits is not None: - selected = allocate_evidence( - evidence, - source_limits, - priority_sources=chosen_source_paths, + selected = ( + allocate_group_evidence(evidence, source_limits, + selected_groups) + if grouped else allocate_evidence( + evidence, source_limits, + priority_sources=chosen_source_paths, + ) ) evidence = tuple( replace(item, citation=index) @@ -4966,12 +5793,15 @@ def context_role( }, turn_id=trace_turn_id, ) + if view is not None: + self._check_index_generation(view) return evidence def _retrieve_for_tool( self: RAGSession, request: RetrievalRequest, trace_turn_id: str | None = None, + *, _query_vectors: dict[str, list[float]] | None = None, ) -> RetrievalResult: """Return bounded original chunks through the shared tool API. @@ -4981,6 +5811,8 @@ def _retrieve_for_tool( Tool-owned retrieval strategy, source scope, and hard limits. trace_turn_id: str | None, optional Active tool turn, used for retrieval trace events. + _query_vectors: dict[str, list[float]] | None, optional + Operation-local cache of formatted query embeddings. Returns ------- @@ -4993,6 +5825,10 @@ def _retrieve_for_tool( If the request is not a validated retrieval request. RuntimeError If returned evidence cannot be located in the source index. + ValueError + If explicit scope operands are outside the selected inventory. + SourceViewConflict + If a supplied view no longer matches the live operation. Notes ----- @@ -5008,8 +5844,53 @@ def _retrieve_for_tool( limits = request.limits for kind in request.card_kinds: SOURCE_CARD_KINDS.get(kind) + view = request.view + if view is not None: + # Reject raw ranking independently of data availability. + members = rank_members(view) + if (request.include_bibliographies is False + and any(not document_candidate(path) for path in members)): + raise ValueError("Bibliography policy conflicts with view.") + if (request.include_bibliographies is True + and view.operation.policy.purpose == "document"): + raise ValueError("Bibliography policy conflicts with view.") + inspection, inventory = self._source_operation_state() + validate_source_view(view, inspection, inventory, + view.operation.policy, request.source_scope) + elif isinstance(self.project, QAProject): + inspection, inventory = self._source_operation_state() + lookup = request.include_bibliographies is True or ( + request.include_bibliographies is None + and bibliography_lookup(request.query, request.scope) + ) + document = (request.strategy == "source_first" + or paper_request(request.query)) and not lookup + policy = SourcePolicy(purpose="document" if document else "lookup") + view = resolve_source_view( + inspection, inventory, policy, request.source_scope, + ) + elif request.scope: + # Path equality is case-insensitive on Windows, whereas the + # selected source inventory uses exact portable identities. + selected = {path.as_posix() for path in self._source_files()} + if not {path.as_posix() for path in request.scope} <= selected: + raise ValueError("Source scope contains unselected operands.") + grouped = view is not None and view.operation.policy.grouped + if request.scope_mode == "restricted" and not request.scope: + coverage = ( + grouped_coverage_report(view, (), (), (), + mode=limits.coverage)[0] + if grouped else coverage_report((), (), mode=limits.coverage) + ) + coverage.update(scope_mode="restricted", scope_operands=[]) + getattr(self, "trace", NullTraceLogger()).emit( + "retrieval.tool.coverage", component="retrieval", + data=coverage, turn_id=trace_turn_id, + ) + return RetrievalResult((), (), coverage, view=view) source_first = ( - (limits.max_sources, request.compare) + (limits.max_sources, request.compare + and request.scope_mode != "restricted") if request.strategy == "source_first" else None ) @@ -5023,15 +5904,31 @@ def _retrieve_for_tool( source_limits=(limits if source_first is not None else None), source_report=details, card_kinds=request.card_kinds, + include_bibliographies=request.include_bibliographies, + scope_mode=request.scope_mode, view=view, + **({"_query_vectors": _query_vectors} + if _query_vectors is not None else {}), ) - if request.scope and (len(request.scope) > 1 or not request.compare): - allowed = set(request.scope) - evidence = tuple(item for item in evidence if item.path in allowed) chosen_sources = tuple(details.get("selected_sources", ())) - final = allocate_evidence( - evidence, - limits, - priority_sources=chosen_sources or request.scope, + if view is not None: + allowed = set(rank_members(view)) + elif request.scope_mode == "restricted": + allowed = set(request.scope) + else: + allowed = None + if allowed is not None and ( + any(item.path not in allowed for item in evidence) + or not set(chosen_sources) <= allowed + ): + raise SourceViewConflict("Retrieval exceeded the source view.") + selected_groups = (_selected_groups(view, chosen_sources) + if grouped else ()) + final = ( + allocate_group_evidence(evidence, limits, selected_groups) + if grouped else allocate_evidence( + evidence, limits, + priority_sources=chosen_sources or request.scope, + ) ) evidence = final.items keys = { @@ -5060,11 +5957,19 @@ def _retrieve_for_tool( "Retrieved evidence is absent from indexed chunks." ) passages.append(keys[key]) - if request.strategy == "source_first": + if request.strategy == "source_first" and not grouped: sources = chosen_sources else: sources = tuple(dict.fromkeys(item.path for item in passages)) - if limits.coverage == COVERAGE_EXHAUSTIVE: + if grouped: + requested = ( + tuple(group.anchor for group in view.groups) + if limits.coverage == COVERAGE_EXHAUSTIVE else + tuple(dict.fromkeys((*request.scope, *chosen_sources))) + ) + elif view is not None and limits.coverage == COVERAGE_EXHAUSTIVE: + requested = rank_members(view) + elif limits.coverage == COVERAGE_EXHAUSTIVE: requested = request.scope or tuple( dict.fromkeys( ( @@ -5074,24 +5979,42 @@ def _retrieve_for_tool( ) ) else: - requested = sources or request.scope + requested = tuple(dict.fromkeys((*request.scope, *sources))) + if view is None and ( + request.strategy == "source_first" or paper_request(request.query) + ) and not ( + request.include_bibliographies is True + or (request.include_bibliographies is None + and bibliography_lookup(request.query, request.scope)) + ): + requested = tuple(path for path in requested + if document_candidate(path)) indexed = {item.path for item in self.chunks} candidates = details.get("candidate_sources", ()) hits = set(final.limits_hit) hits.update(details.get("budget_limits_hit", ())) - if len(candidates) > len(sources): - if len(sources) >= limits.max_sources: + selected_count = len(chosen_sources) if grouped else len(sources) + if len(candidates) > selected_count: + if selected_count >= limits.max_sources: hits.add("sources") - if len(sources) >= limits.max_passages: + if not grouped and selected_count >= limits.max_passages: hits.add("passages") - coverage = coverage_report( - requested, - evidence, - mode=limits.coverage, - unavailable=tuple( - path for path in requested if path not in indexed - ), - limits_hit=tuple(sorted(hits)), + if grouped: + coverage, group_rows = grouped_coverage_report( + view, evidence, selected_groups, requested, + mode=limits.coverage, limits_hit=tuple(sorted(hits)), + ) + else: + group_rows = () + coverage = coverage_report( + requested, evidence, mode=limits.coverage, + unavailable=tuple(path for path in requested + if path not in indexed), + limits_hit=tuple(sorted(hits)), + ) + coverage.update( + scope_mode=request.scope_mode, + scope_operands=[path.as_posix() for path in request.scope], ) getattr(self, "trace", NullTraceLogger()).emit( "retrieval.tool.coverage", @@ -5099,7 +6022,10 @@ def _retrieve_for_tool( data=coverage, turn_id=trace_turn_id, ) - return RetrievalResult(tuple(passages), sources, coverage) + if view is not None: + self._check_index_generation(view) + return RetrievalResult(tuple(passages), sources, coverage, + groups=group_rows, view=view) def _run_tool( self: RAGSession, @@ -5158,6 +6084,7 @@ def _run_tool( """ trace = getattr(self, "trace", NullTraceLogger()) + source_host = ToolSourceHost(self, trace_turn_id) # The project may have changed the tool's settings in profile.ini. use = with_project_settings(Path(self.project.root), use) language_context = ( @@ -5173,7 +6100,7 @@ def _run_tool( ) tool_thoughts: list[str] = [] - model_policy = TOOL_REGISTRY[use.name].model_calls + model_policy = registered_tools()[use.name].model_calls model_calls: list[dict[str, object]] = [] def ask_model(system: str, prompt: str, tokens: int | None) -> str: @@ -5358,6 +6285,7 @@ def write(system: str, prompt: str, tokens: int | None) -> str: if item.intent != decision.intent ], fixed_suggestions=self._behavior_config().suggestions, + source_view=source_host.bind, ) request = ToolRequest( @@ -5381,17 +6309,19 @@ def write(system: str, prompt: str, tokens: int | None) -> str: component="tool", data={ "name": use.name, + "plugin": _tool_identity(use.name), "settings": ( asdict(use.settings) if is_dataclass(use.settings) else repr(use.settings) ), - "internal": TOOL_REGISTRY[use.name].internal_defaults, + "internal": registered_tools()[use.name].internal_defaults, }, turn_id=trace_turn_id, ): try: result = run_tool(use, request, context) + source_host.validate() except IncompleteModelResponse as error: trace.emit( "tool.generation.incomplete", @@ -5524,7 +6454,7 @@ def _earlier_turns( return tuple(earlier) def _source_files(self: RAGSession) -> dict[Path, int]: - """Return selected source files and sizes from the source manifest. + """Return selected files and sizes from the index source state. Prefer the current in-memory scan, including an empty collection, over an older saved manifest. A missing or unreadable manifest gives @@ -5538,11 +6468,11 @@ def _source_files(self: RAGSession) -> dict[Path, int]: """ - manifest = self.project.indexes / "source_manifest.json" + state_path = self.project.indexes / "index_source_state.json" try: - current = getattr(self, "_current_source_manifest", None) + current = getattr(self, "_current_index_source_state", None) if current is None: - current = json.loads(manifest.read_text(encoding="utf-8")) + current = json.loads(state_path.read_text(encoding="utf-8")) files = current["files"] return { Path(name): int(entry.get("size_bytes", 0)) @@ -5572,8 +6502,16 @@ def _unsearchable_sources( known = set(indexed) return [path for path in self._source_files() if path not in known] - def _card_metadata(self: RAGSession) -> dict[Path, dict[str, str]]: - """Return each source's card metadata, for described documents. + def _card_metadata( + self: RAGSession, *, view: SourceView | None = None, + ) -> dict[Path, dict[str, str]]: + """Return each eligible source's card metadata for descriptions. + + Parameters + ---------- + view: SourceView | None, optional + Limit discovery to the operation's independent candidates. + None retains the existing unscoped tool-host contract. Returns ------- @@ -5584,24 +6522,33 @@ def _card_metadata(self: RAGSession) -> dict[Path, dict[str, str]]: """ + eligible = (None if view is None else { + item.path for item in view.operation.inventory.files + if item.indexed and item.path in view.candidates + }) records = getattr(getattr(self, "source_cards", None), "records", ()) merged: dict[Path, dict[str, str]] = {} for record in records or (): card = getattr(record.result, "card", None) - if card is None: + if (card is None or not document_candidate(card.path) + or (eligible is not None and card.path not in eligible)): continue fields = merged.setdefault(card.path, {}) for key, value in card.metadata: fields.setdefault(key, value) return merged - def _card_fields(self: RAGSession, path: Path) -> dict[str, str] | None: + def _card_fields( + self: RAGSession, path: Path, *, view: SourceView | None = None, + ) -> dict[str, str] | None: """Return the fields of one source's cards, for tools. Parameters ---------- path: pathlib.Path The source's indexed path. + view: SourceView | None, optional + Restrict metadata to eligible independent document candidates. Returns ------- @@ -5613,6 +6560,13 @@ def _card_fields(self: RAGSession, path: Path) -> dict[str, str] | None: """ + if not document_candidate(path) or ( + view is not None and (path not in view.candidates or not any( + item.indexed and item.path == path + for item in view.operation.inventory.files + )) + ): + return None records = getattr(getattr(self, "source_cards", None), "records", ()) fields: dict[str, str] = {} found = False @@ -5648,6 +6602,8 @@ def _source_passages( metadata: dict[str, object] | None = None, exhaustive: bool = False, requested: int = 0, + include_bibliographies: bool = False, + view: SourceView | None = None, ) -> list[HybridResult]: """Select sources by four-channel RRF, then original passages. @@ -5666,9 +6622,10 @@ def _source_passages( max_sources: int Maximum sources to consider, within the passage count. compare: bool - Whether a single named source may include additional sources. + Whether to target at least two relevant sources when available. scope: Sequence[pathlib.Path] - Explicit source selections; several form a strict restriction. + Explicit operands to prioritize within eligible ranked sources. + Physical membership has already been resolved by the caller. trace_turn_id: str | None Trace identifier for this retrieval turn. per_source: int, optional @@ -5682,16 +6639,21 @@ def _source_passages( requested: int, optional How many sources the question asks about ("the five articles"); at least that many are kept. Defaults to ``0``. + include_bibliographies: bool, optional + Allow bibliography text in explicit lookup. Defaults to False. + + view: SourceView | None, optional + Grouped document operation. Returns the complete ranking of + selected groups' original evidence for final budget allocation. Returns ------- list[HybridResult] Original chunks selected from independently ranked sources. - Unless ``exhaustive`` or several sources are named, only - sources the question is about are used (``relevant_sources``: - a passage among the first ``count``, a named source, or the - best card match), at least two for a comparison and at least - ``requested``. + Unless ``exhaustive``, use sources relevant to the question + (``relevant_sources``: a passage among the first ``count``, a + named source, or the best card match), targeting at least two + for a comparison and at least ``requested`` when available. Notes ----- @@ -5700,53 +6662,74 @@ def _source_passages( """ + if not include_bibliographies: + semantic = [item for item in semantic + if document_candidate(item.chunk.path)] + lexical = [item for item in lexical + if document_candidate(item.chunk.path)] + code = [item for item in code + if document_candidate(item.chunk.path)] + groups = view.groups if view is not None else None ranked_sources = source_first_search( semantic=semantic, lexical=lexical, code=code, cards=cards, - count=max(len(self.chunks), len(cards), 1), + count=max(len(self.chunks), len(cards), len(groups or ()), 1), + include_bibliographies=include_bibliographies, + **({"groups": groups} if groups is not None else {}), ) indexed_paths = {chunk.path for chunk in self.chunks} - available = [ - item for item in ranked_sources if item.path in indexed_paths - ] named = list(dict.fromkeys(scope)) - if len(named) > 1: - allowed = set(named) - available = [item for item in available if item.path in allowed] - elif len(named) == 1: - target = [item for item in available if item.path == named[0]] - others = [item for item in available if item.path != named[0]] - available = [*target, *others] if compare else target + if groups is not None: + ranked_paths = {item.path for item in ranked_sources} + # Explicit or exhaustive requests retain unavailable anchors. + # A member can rank a group even when its anchor is unindexed. + ranked_sources.extend( + SourceResult(group.anchor, 0.0, ()) for group in groups + if group.anchor not in ranked_paths and ( + exhaustive or group.anchor in named or not ranked_paths + ) + ) + available = list(ranked_sources) + else: + available = [item for item in ranked_sources + if item.path in indexed_paths] + available.sort(key=lambda item: item.path not in named) full_passages = hybrid_search( semantic=semantic, lexical=lexical, code=code, - count=len(self.chunks), + count=max(len(self.chunks), 1), ) unrelated: list[Path] = [] - if not exhaustive and len(named) < 2: + if not exhaustive: relevant = relevant_sources( available, full_passages, depth=count, keep=named, minimum=max(2 if compare else 1, requested), + **({"groups": groups} if groups is not None else {}), ) unrelated = [ item.path for item in available if item not in relevant ] available = relevant - limit = min(max_sources, count) + limit = (max_sources if groups is not None + else min(max_sources, count)) chosen = [item.path for item in available[:limit]] - passages = select_source_passages( - full_passages, - chosen, - count=count, - per_source=per_source, - ) + if groups is not None: + selected_groups = _selected_groups(view, chosen) + members = {path for group in selected_groups + for path in group.evidence} + passages = [item for item in full_passages + if item.chunk.path in members] + else: + passages = select_source_passages( + full_passages, chosen, count=count, per_source=per_source, + ) if metadata is not None: metadata.update( { @@ -5777,6 +6760,11 @@ def _source_passages( "passage_count": len(passages), "scope": named, "unrelated": unrelated, + **({ + "grouped": True, + "source_operation": group_operation_data(view), + "groups": [asdict(group) for group in selected_groups], + } if groups is not None else {}), }, turn_id=trace_turn_id, ) @@ -5788,6 +6776,8 @@ def _rank_everything( trace_turn_id: str | None = None, *, semantic_results: Sequence[SemanticResult] | None = None, + allowed: frozenset[Path] | None = None, + _query_vectors: dict[str, list[float]] | None = None, ) -> list[HybridResult]: """Rank every chunk for a text with the fused search channels. @@ -5802,6 +6792,11 @@ def _rank_everything( and index. ``None`` performs semantic search. This private reuse boundary avoids another model call. Defaults to ``None``. + allowed: frozenset[pathlib.Path] | None, optional + Exact physical membership, or None for unscoped ranking. + _query_vectors: dict[str, list[float]] | None, optional + Share formatted query embeddings across views of one operation. + Returns ------- list[HybridResult] @@ -5812,27 +6807,47 @@ def _rank_everything( if not self.chunks: return [] - everything = len(self.chunks) + scoped = scoped_indexes( + self.chunks, self.indexes.semantic, self.indexes.lexical, + self.indexes.code_graph, allowed, + ) + everything = len(scoped.chunks) + if not everything: + return [] + query_text = self._format_query(text) + vector = None + if semantic_results is None and _query_vectors is not None: + if query_text not in _query_vectors: + _query_vectors[query_text] = ( + self.embedding_session.embed_query(query_text) + if trace_turn_id is None else + self.embedding_session.embed_query( + query_text, trace_turn_id=trace_turn_id, + ) + ) + vector = _query_vectors[query_text] semantic = ( semantic_search( - self.indexes.semantic, - self._format_query(text), + scoped.semantic, + query_text, self.embedding_session, count=everything, trace_turn_id=trace_turn_id, + **({"query_vector": vector} if vector is not None else {}), ) if semantic_results is None - else list(semantic_results) + else [item for item in semantic_results + if allowed is None or item.chunk.path in allowed] ) - lexical = lexical_search(self.indexes.lexical, text, count=everything) + lexical = lexical_search(scoped.lexical, text, count=everything) code = ( code_search( - self.indexes.code_graph, - self.chunks, + scoped.code_graph, + scoped.chunks, text, count=everything, ) - if self.indexes.code_graph.entities + if scoped.code_graph.entities else [] ) return hybrid_search( @@ -5846,6 +6861,7 @@ def _read_document( retrieval_count: int | None = None, *, trace_turn_id: str | None = None, + view: SourceView | None = None, ) -> DocumentSelection | None: """Choose one document for a question and select its chunks. @@ -5862,6 +6878,11 @@ def _read_document( trace_turn_id: str | None, optional Turn identifier for trace events. Defaults to ``None``. + view: SourceView | None, optional + Frozen source scope; only eligible target documents can be + selected for complete-document reading. Grouped views require + source-first retrieval, not complete-document reading. + Returns ------- DocumentSelection | None @@ -5876,24 +6897,53 @@ def _read_document( """ + if view is not None and view.operation.policy.grouped: + raise ValueError("Grouped views require source-first retrieval.") trace = getattr(self, "trace", NullTraceLogger()) - everything = len(self.chunks) - if not everything: + if not self.chunks or ( + view is None and not bibliography_lookup(question) and not any( + document_candidate(chunk.path) for chunk in self.chunks + ) + ): return None + allowed = None + if view is not None: + self._check_index_generation(view) + members = set(rank_members(view)) + allowed = frozenset((*view.targets, *view.candidates)) & members + if not allowed or not any(chunk.path in allowed + for chunk in self.chunks): + return None + scoped = scoped_indexes( + self.chunks, self.indexes.semantic, self.indexes.lexical, + self.indexes.code_graph, allowed, + ) with trace.span( "retrieval.document", component="retrieval", data={"max_tokens": max_tokens}, turn_id=trace_turn_id, ): - ranked = self._rank_everything(question, trace_turn_id) + ranked = self._rank_everything( + question, trace_turn_id, + **({"allowed": allowed} if view is not None else {}), + ) + if view is not None and view.operation.scope.mode == "preferred": + ranked.sort( + key=lambda item: item.chunk.path not in view.targets + ) selection = read_document( question, - self.chunks, - self.indexes.code_graph, + scoped.chunks, + scoped.code_graph, ranked, max_tokens=max_tokens, top=retrieval_count or self.project.profile.retrieval_count, + **({"path": next(iter(allowed))} if allowed is not None + and len(allowed) == 1 else {}), + **({"include_bibliographies": + view.operation.policy.purpose == "lookup"} + if view is not None else {}), ) trace.emit( "retrieval.document.selected", @@ -5905,11 +6955,22 @@ def _read_document( ), turn_id=trace_turn_id, ) + if view is not None: + self._check_index_generation(view) return selection - def sync_conversation_memory(self: RAGSession) -> MemoryIndex: + def sync_conversation_memory( + self: RAGSession, *, trace_turn_id: str | None = None + ) -> MemoryIndex: """Synchronize derived project conversation memory on demand. + Parameters + ---------- + trace_turn_id: str | None, optional + Turn correlation ID for automatic synchronization during an + answer. None denotes an explicit update outside an answer. + Defaults to None. + Returns ------- MemoryIndex @@ -5922,24 +6983,63 @@ def sync_conversation_memory(self: RAGSession) -> MemoryIndex: The next memory search catches up after conversation commits, archiving, feedback edits, or project policy changes. A GUI may call this method during idle time without changing those guarantees. + Explicit updates use project diagnostics; automatic updates retain + their turn correlation. The index is never copied into the trace. """ - config = self._behavior_config() - if not config.conversation_memory.enabled: - return MemoryIndex("", (), {}) - identity = getattr(self.indexes, "embedding_model_identity", None) - if not identity: - identity = ( - f"{self.embedding_session.model_id}@" - f"{self.embedding_session.model_source}" - ) - return synchronize_memory( - self.project.root, - config, - self.embedding_session, - model_identity=identity, + manual = trace_turn_id is None + trace = self._project_diagnostics() if manual else self.trace + prefix = "project.memory.sync" if manual else "memory.sync" + diagnostics = ( + self._project_embedding_diagnostics() if manual else nullcontext() ) + with diagnostics, trace.span( + prefix, component="rag", turn_id=trace_turn_id, + data={"trigger": "manual" if manual else "answer"}, + ): + config = self._behavior_config() + enabled = config.conversation_memory.enabled + if enabled: + identity = getattr( + self.indexes, "embedding_model_identity", None + ) + if not identity: + identity = ( + f"{self.embedding_session.model_id}@" + f"{self.embedding_session.model_source}" + ) + index = synchronize_memory( + self.project.root, config, self.embedding_session, + model_identity=identity, + ) + else: + index = MemoryIndex("", (), {}) + if trace.enabled: + trace.emit( + f"{prefix}.result", component="rag", + turn_id=trace_turn_id, + data={ + "enabled": enabled, + "model_identity": index.model_identity, + "embedded_count": index.embedded_count, + "changed": index.changed, + "vector_count": len(index.vectors), + "records": [ + { + "turn_uuid": record.turn_uuid, + "role": record.role, + "fingerprint": record.fingerprint, + "priority": record.priority, + "origins": [ + asdict(origin) for origin in record.origins + ], + } + for record in index.records + ], + }, + ) + return index def _format_memory_query(self: RAGSession, question: str) -> str: """Format an embedding query for remembered discussions. @@ -6330,7 +7430,8 @@ def _ask_check( ) def _new_chat_session( - self: RAGSession, model_id: str, **settings: object + self: RAGSession, model_id: str, *, trace: TraceSink | None = None, + **settings: object, ) -> ChatSession: """Load a chat model with this project's system prompt and trace. @@ -6338,6 +7439,8 @@ def _new_chat_session( ---------- model_id: str Hugging Face model ID or local model directory. + trace: TraceSink | None, optional + Sink for model initialization. Defaults to the conversation. **settings: object Optional ``thinking``, ``temperature``, and ``max_new_tokens`` passed to ``ChatSession``. @@ -6354,7 +7457,7 @@ def _new_chat_session( backend=self.backend, system_prompt=self._system_prompt(), allow_download=self.project.profile.allow_download, - trace=self.trace, + trace=self.trace if trace is None else trace, block_unrequested_cjk=(self.project.profile.block_unrequested_cjk), **settings, ) @@ -6587,7 +7690,7 @@ def _prepare_source_cards( """ - manifest = getattr(self, "_current_source_manifest", None) or {} + manifest = getattr(self, "_current_index_source_state", None) or {} started = perf_counter() def report(current: int, total: int) -> None: @@ -6626,7 +7729,7 @@ def report(current: int, total: int) -> None: and indexes.semantic.embeddings else None ), - trace=self.trace, + trace=self._project_diagnostics(), progress=report, force_regenerate=force_regenerate, generation_guard=( @@ -6709,24 +7812,27 @@ def _load_conversation( Notes ----- Reads only the canonical grouped conversation record. The caller - holds file ownership while restoring or staging a switch. This does - not validate that saved turns, evidence, profile, and indexes are - mutually consistent. + holds file ownership while restoring or staging a switch. Validation + checks the saved structure and checkpoint content digest, without + resolving historical evidence against current sources or indexes. """ path = self.conversation_path if path is None else path - if not path.is_file(): + if not path.exists(): return [], [], None + if not path.is_file(): + raise ValueError("The saved conversation must be a regular file.") try: - payload = json.loads(path.read_text(encoding="utf-8")) - conversation = conversation_state(payload) - saved_turns = conversation.get("turns", []) - require_saved_turn_ids(saved_turns) - turns = [_turn_from_data(item) for item in saved_turns] - system_prompt = str( - conversation.get("system_prompt", _SYSTEM_PROMPT) + payload = read_conversation_json( + path.read_text(encoding="utf-8") ) + conversation = conversation_state(payload) + if "turns" not in conversation: + return [], [], None + turns = [_turn_from_data(item) + for item in conversation["turns"]] + system_prompt = conversation["system_prompt"] messages = [{"role": SYSTEM_ROLE, "content": system_prompt}] # Earlier evidence stays with its turn; history is Q/A only. messages.extend( @@ -6738,10 +7844,7 @@ def _load_conversation( ) except (KeyError, TypeError, json.JSONDecodeError) as error: raise ValueError("The saved conversation is invalid.") from error - checkpoint_id = conversation.get("checkpoint_id") - if not isinstance(checkpoint_id, str) or not checkpoint_id: - checkpoint_id = None - return messages, turns, checkpoint_id + return messages, turns, conversation.get("checkpoint_id") def _save_conversation( self, @@ -6827,6 +7930,7 @@ def _save_conversation( "checkpoint_id": checkpoint_id, "checkpoint": checkpoint_state, } + validate_conversation_state(saved_state) if self.trace.enabled: self.trace.update_conversation(saved_state) else: @@ -6834,12 +7938,17 @@ def _save_conversation( path, ownership=self._active_conversation_lock() ): payload: dict[str, object] = {"sessions": {}} - if path.is_file(): - loaded = json.loads(path.read_text(encoding="utf-8")) - if not isinstance(loaded, dict): - raise ValueError("The saved conversation is invalid.") - payload = loaded + if path.exists(): + if not path.is_file(): + raise ValueError( + "The saved conversation must be a regular file." + ) + payload = read_conversation_json( + path.read_text(encoding="utf-8") + ) stored = conversation_state(payload, create=True) + candidate = {**stored, **saved_state} + validate_conversation_state(candidate) stored.update(saved_state) _write_json(path, payload) # The checkpoint write is the commit boundary. Diagnostic events @@ -6856,6 +7965,10 @@ def _save_conversation( "immutable_state_saved": True, "conversation_path": str(path), "turn_count": len(turns), + "conversation_turn_uuid": ( + pending_turn.conversation_turn_uuid + if pending_turn is not None else None + ), "index_fingerprint": self.indexes.fingerprint, }, turn_id=trace_turn_id, @@ -7209,9 +8322,71 @@ def _document_message(selection: DocumentSelection | None) -> str: ) +def _all_documents(system: str, prompt: str, tokens: int) -> str: + """Use deterministic document scope without asking another model. + + Parameters + ---------- + system: str + Unused scope-router system instruction. + prompt: str + Unused ambiguous-scope question. + tokens: int + Unused response length limit. + + Returns + ------- + str + Project-wide scope for unresolved, non-explicit wording. + + """ + return "ALL" + + +def _selected_groups( + view: SourceView, anchors: Sequence[Path], +) -> tuple[SourceGroup, ...]: + """Resolve selected group anchors without changing their ranking order. + + Parameters + ---------- + view: SourceView + Frozen operation containing all eligible logical groups. + anchors: Sequence[pathlib.Path] + Ranked selected anchors, possibly without indexed passages. + + Returns + ------- + tuple[SourceGroup, ...] + Exact resolved memberships of the selected anchors. + + """ + by_anchor = {group.anchor: group for group in view.groups} + return tuple(by_anchor[anchor] for anchor in anchors) + + +def _evidence_identity(item: Evidence | Chunk) -> tuple: + """Identify exact indexed text and its original physical coordinates. + + Parameters + ---------- + item: Evidence | Chunk + An original indexed chunk or previously supplied evidence. + + Returns + ------- + tuple + Comparison key excluding citation number and context role. + + """ + return (item.path, item.start_line, item.end_line, item.symbol, + item.cell, item.text) + + def _add_related_evidence( fresh: tuple[Evidence, ...], turns: list[ConversationTurn], + *, exact_identity: bool = False, ) -> tuple[Evidence, ...]: """Append the evidence earlier related turns relied on. @@ -7221,6 +8396,9 @@ def _add_related_evidence( Evidence just retrieved for the new question; it keeps its numbers. turns: list[ConversationTurn] Earlier turns the router marked as related, oldest first. + exact_identity: bool, optional + Preserve distinct physical cells and exact text for grouped evidence. + False retains the existing ungrouped deduplication rule. Returns ------- @@ -7232,7 +8410,24 @@ def _add_related_evidence( """ - seen = {(str(item.path), item.start_line, item.end_line) for item in fresh} + def identity(item: Evidence) -> tuple: + """Return the applicable physical passage comparison key. + + Parameters + ---------- + item: Evidence + Original physical evidence. + + Returns + ------- + tuple + Physical identity under the selected deduplication rule. + + """ + return (_evidence_identity(item) if exact_identity else + (str(item.path), item.start_line, item.end_line)) + + seen = {identity(item) for item in fresh} extra: list[Evidence] = [] for turn in reversed(turns): cited = { @@ -7244,7 +8439,7 @@ def _add_related_evidence( if not cited: chosen = list(turn.evidence[:_UNCITED_RELATED_EVIDENCE]) for item in chosen: - key = (str(item.path), item.start_line, item.end_line) + key = identity(item) if key not in seen and len(extra) < _MAX_RELATED_EVIDENCE: seen.add(key) extra.append(item) @@ -7354,6 +8549,7 @@ def _answer_prompt( *, memory_hits: tuple[MemoryHit, ...] = (), memory_recall_checked: bool = False, + groups: Sequence[SourceGroupCoverage] = (), ) -> str: """Combine a question with separate documentary and memory contexts. @@ -7373,6 +8569,9 @@ def _answer_prompt( memory_recall_checked: bool, optional Whether the project memory was checked for an explicit historical topic; include cautious interpretation even when no match is found. + groups: Sequence[SourceGroupCoverage], optional + Selected logical groups with actual physical evidence representation. + Defaults to empty, preserving the ungrouped prompt. Returns ------- @@ -7395,6 +8594,12 @@ def _answer_prompt( """ + if groups: + instructions = _group_answer_instruction(groups, evidence) + guidance = "\n\n".join(filter(None, ( + guidance.strip() if isinstance(guidance, str) else "", + instructions, + ))) if memory_recall_checked and not memory_hits and not evidence: sections = [ f"CURRENT REQUEST:\n{question}", @@ -7458,7 +8663,7 @@ def _answer_prompt( ) if isinstance(guidance, str) and guidance.strip(): sections[-1] += " " + guidance.strip() - per_source = _per_source_instruction(question, evidence) + per_source = "" if groups else _per_source_instruction(question, evidence) if per_source: sections[-1] += " " + per_source if memory_hits: @@ -7485,6 +8690,41 @@ def _answer_prompt( return "\n\n".join(sections) +def _group_answer_instruction( + groups: Sequence[SourceGroupCoverage], evidence: Sequence[Evidence], +) -> str: + """Describe group membership using original citation numbers only. + + Parameters + ---------- + groups: Sequence[SourceGroupCoverage] + Selected logical documents and their represented members. + evidence: Sequence[Evidence] + Final deduplicated original passages in citation order. + + Returns + ------- + str + Non-evidentiary prompt instructions, not merged document text. + + """ + lines = [ + "LOGICAL DOCUMENT GROUPS (membership, not evidence):", + "Use physical citations as given. Shared members may support " + "multiple groups; do not count a supplement as another paper or " + "claim that an absent anchor was read. Do not claim to have read " + "groups omitted from the supplied context.", + ] + for row in groups: + numbers = [f"[{item.citation}]" for item in evidence + if item.path in row.group.evidence] + anchor = ("anchor represented" if row.anchor_represented + else "anchor NOT represented") + lines.append(f"{row.group.anchor.as_posix()}: {anchor}; " + f"evidence {', '.join(numbers) or 'none'}.") + return "\n".join(lines) + + def _per_source_instruction( question: str, evidence: Sequence[Evidence] ) -> str: @@ -7562,97 +8802,57 @@ def _turn_to_data(turn: ConversationTurn) -> dict[str, object]: def _turn_from_data(data: dict[str, object]) -> ConversationTurn: - """Restore one conversation turn from JSON data. + """Restore one strictly validated conversation turn from JSON data. Parameters ---------- data: dict[str, object] - Dictionary decoded from or prepared for persisted conversation JSON. + Complete current turn record decoded from persisted conversation JSON. Returns ------- ConversationTurn - Reconstructed ConversationTurn with evidence, copied parameters, - and the validated optional execution timeline. + Reconstructed turn with evidence, copied parameters, and an optional + execution timeline represented explicitly in the saved record. Raises ------ ValueError - If evidence, parameters, or timeline data has an invalid structure, - or numeric conversion fails. - KeyError - If required turn/evidence fields are absent. - TypeError - If a saved value cannot be converted as expected. + If a required field is absent or a stored value violates the current + turn, evidence, parameter, or timeline schema. Notes ----- - This is structural reconstruction and coercion, not validation of the - original answer or current source content. + Values are validated without scalar coercion. Historical evidence is not + resolved against the current filesystem and may name removed sources. """ - evidence_data = data["evidence"] - if not isinstance(evidence_data, list): - raise ValueError("Saved evidence must be a list.") + validate_conversation_turn(data) evidence = tuple( Evidence( - citation=int(item["citation"]), - path=Path(str(item["path"])), - start_line=int(item["start_line"]), - end_line=int(item["end_line"]), - symbol=( - str(item["symbol"]) if item["symbol"] is not None else None - ), - text=str(item["text"]), - cell=(int(item["cell"]) if item.get("cell") is not None else None), - context_role=_evidence_context_role(item.get("context_role")), + citation=item["citation"], + path=Path(item["path"]), + start_line=item["start_line"], + end_line=item["end_line"], + symbol=item["symbol"], + text=item["text"], + cell=item["cell"], + context_role=item["context_role"], ) - for item in evidence_data + for item in data["evidence"] ) - parameters = data["parameters"] - if not isinstance(parameters, dict): - raise ValueError("Saved parameters must be a mapping.") return ConversationTurn( - conversation_turn_uuid=require_turn_uuid( - data["conversation_turn_uuid"] - ), - timestamp=str(data["timestamp"]), - question=str(data["question"]), - answer=str(data["answer"]), + conversation_turn_uuid=data["conversation_turn_uuid"], + timestamp=data["timestamp"], + question=data["question"], + answer=data["answer"], evidence=evidence, - parameters=parameters, - timeline=_timeline_from_data(data.get("timeline")), + parameters=dict(data["parameters"]), + timeline=_timeline_from_data(data["timeline"]), ) -def _evidence_context_role( - value: object, -) -> Literal["direct", "related", "alternative"] | None: - """Validate optional evidence provenance when restoring saved turns. - - Parameters - ---------- - value: object - Stored context role, or ``None`` for older evidence records. - - Returns - ------- - "direct" | "related" | "alternative" | None - Recognized provenance category. - - Raises - ------ - ValueError - If the saved category is unknown. - - """ - - if value is None or value in ("direct", "related", "alternative"): - return value - raise ValueError("Saved evidence has an invalid context_role.") - - def _resume_checkpoint_id(snapshot: dict[str, object]) -> str: """Return a stable identity for one complete restorable session state. diff --git a/kilin/repository.py b/kilin/repository.py index 925c5f60..7e7c087d 100644 --- a/kilin/repository.py +++ b/kilin/repository.py @@ -916,7 +916,7 @@ def detect_repository_changes( -------- >>> import kilin >>> changes = kilin.detect_repository_changes( - ... "/path/to/repository", "/path/to/source_manifest.json", + ... "/path/to/repository", "/path/to/repository_manifest.json", ... ) """ diff --git a/kilin/retrievals/__init__.py b/kilin/retrievals/__init__.py index 99ee3ef9..771d0a1e 100644 --- a/kilin/retrievals/__init__.py +++ b/kilin/retrievals/__init__.py @@ -185,6 +185,8 @@ from kilin.retrievals.requests import ( RetrievalRequest, RetrievalResult, + SourceGroupCoverage, + group_coverage, ) from kilin.retrievals.persistence import ( PersistentIndexes, @@ -257,6 +259,8 @@ "PersistentIndexes", "RetrievalRequest", "RetrievalResult", + "SourceGroupCoverage", + "group_coverage", "ContextExpansionPlan", "SemanticIndex", "SemanticResult", diff --git a/kilin/retrievals/_scope.py b/kilin/retrievals/_scope.py new file mode 100644 index 00000000..1839f81e --- /dev/null +++ b/kilin/retrievals/_scope.py @@ -0,0 +1,165 @@ +"""Project existing retrieval indexes onto an operation's physical members. + +A source view authorizes original physical passages. Apply that membership +before scoring and rank fusion, not just to the resulting evidence. The +projection borrows existing vectors, term statistics, and chunk identities; +it does not build a new index, change document frequency, or embed text. + +Key Features +------------ +- Restrict all passage channels and the code graph to one membership set. +- Preserve independent lookup and documentary evidence purposes. +- Keep the evidence membership independent of logical-group quotas. + +Module Structure +---------------- +- ``rank_members``: interpret the resolved operation's ranking membership. +- ``scoped_indexes``: project physical chunks, vectors and code graph. + +Examples +-------- +>>> from kilin.retrievals._scope import scoped_indexes +>>> from kilin.retrievals import CodeGraph, LexicalIndex, SemanticIndex +>>> empty = scoped_indexes([], SemanticIndex((), ()), +... LexicalIndex((), (), {}), CodeGraph((), ()), +... frozenset()) +>>> len(empty.chunks) +0 + +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path + +from kilin.chunking import Chunk +from kilin.retrievals.code_graph import CodeGraph +from kilin.retrievals.strategies.retrieval_lexical import LexicalIndex +from kilin.retrievals.strategies.retrieval_semantic import SemanticIndex +from kilin.source_views import SourceView + +__all__ = ["rank_members", "scoped_graph", "scoped_indexes"] + + +@dataclass(frozen=True, slots=True) +class _ScopedIndexes: + """Borrow the original physical index components for one operation.""" + + chunks: Sequence[Chunk] + semantic: SemanticIndex + lexical: LexicalIndex + code_graph: CodeGraph + + +def rank_members(view: SourceView) -> tuple[Path, ...]: + """Return members eligible for the operation's ranked passages. + + Parameters + ---------- + view: SourceView + Validated operation, independent of the ranking strategy. + + Returns + ------- + tuple[pathlib.Path, ...] + Documentary evidence, or lookup members for a lookup operation. + + Raises + ------ + ValueError + If the view is intended for raw-file access, not retrieval. + + """ + policy = view.operation.policy + if policy.purpose == "raw": + raise ValueError("Raw-file views cannot rank indexed evidence.") + return view.evidence if policy.purpose == "document" else view.lookup + + +def scoped_indexes( + chunks: Sequence[Chunk], semantic: SemanticIndex, lexical: LexicalIndex, + graph: CodeGraph, allowed: frozenset[Path] | None, +) -> _ScopedIndexes: + """Borrow only authorized index entries and graph endpoints. + + Parameters + ---------- + chunks: Sequence[Chunk] + Original chunks in index order. + semantic: SemanticIndex + Existing semantic index and document vectors. + lexical: LexicalIndex + Existing lexical index, including corpus-wide IDF weights. + graph: CodeGraph + Original code-entity graph, separate from the semantic manifest. + allowed: frozenset[pathlib.Path] | None + Authorized physical paths. None is unrestricted; an empty set + permits no passages or graph entities. + + Returns + ------- + _ScopedIndexes + Read-only operation projection, with unchanged chunk identities. + + Notes + ----- + Excluded code entities cannot seed a graph search or bridge two + allowed entities. The original document-frequency weights remain + fixed; restriction changes ranking membership, not index generation. + + """ + if allowed is None: + return _ScopedIndexes(chunks, semantic, lexical, graph) + selected = [chunk for chunk in chunks if chunk.path in allowed] + semantic_pairs = tuple( + (chunk, vector) for chunk, vector in zip( + semantic.chunks, semantic.embeddings, strict=True, + ) if chunk.path in allowed + ) + lexical_pairs = tuple( + (chunk, vector) for chunk, vector in zip( + lexical.chunks, lexical.vectors, strict=True, + ) if chunk.path in allowed + ) + return _ScopedIndexes( + selected, + SemanticIndex(tuple(pair[0] for pair in semantic_pairs), + tuple(pair[1] for pair in semantic_pairs)), + LexicalIndex(tuple(pair[0] for pair in lexical_pairs), + tuple(pair[1] for pair in lexical_pairs), + lexical.inverse_document_frequency), + scoped_graph(graph, allowed), + ) + + +def scoped_graph(graph: CodeGraph, allowed: frozenset[Path]) -> CodeGraph: + """Restrict graph endpoints to selected physical membership. + + Parameters + ---------- + graph: CodeGraph + Original or already scoped code graph. + allowed: frozenset[pathlib.Path] + Physical evidence members eligible for context expansion. + + Returns + ------- + CodeGraph + Graph with excluded physical endpoints removed. + + """ + entities = tuple(entity for entity in graph.entities + if entity.path in allowed) + # With no excluded graph entities, retain the original graph, + # including references to external symbols without physical chunks. + if len(entities) == len(graph.entities): + projected_graph = graph + else: + names = {entity.name for entity in entities} + relations = tuple(relation for relation in graph.relations + if relation.source in names + and relation.target in names) + projected_graph = CodeGraph(entities, relations) + return projected_graph diff --git a/kilin/retrievals/document_reading.py b/kilin/retrievals/document_reading.py index c61ae1cc..6962020a 100644 --- a/kilin/retrievals/document_reading.py +++ b/kilin/retrievals/document_reading.py @@ -91,6 +91,7 @@ import re from typing import Final, Literal, TypeAlias +from kilin.source_eligibility import bibliography_lookup, document_candidate from kilin.chunking import Chunk from kilin.defaults import load_defaults_section, require_default_int from kilin.retrievals.code_graph import CodeGraph @@ -217,6 +218,7 @@ def read_document( max_tokens: int, top: int = 20, path: Path | None = None, + include_bibliographies: bool | None = None, ) -> DocumentSelection | None: """Choose one document for a question and fit it to a token budget. @@ -242,6 +244,10 @@ def read_document( the user did). Takes precedence over named functions and search ranking. Defaults to ``None``. + include_bibliographies: bool | None, optional + Explicit lookup eligibility from a resolved operation. None retains + deterministic bibliography recognition from the question and path. + Returns ------- DocumentSelection | None @@ -250,6 +256,14 @@ def read_document( """ + if include_bibliographies is None: + include_bibliographies = bibliography_lookup( + question, (path,) if path else () + ) + if not include_bibliographies: + chunks = [item for item in chunks if document_candidate(item.path)] + ranked = [item for item in ranked + if document_candidate(item.chunk.path)] if not chunks: return None diff --git a/kilin/retrievals/evidence_budget.py b/kilin/retrievals/evidence_budget.py index 6027a25f..ca993e32 100644 --- a/kilin/retrievals/evidence_budget.py +++ b/kilin/retrievals/evidence_budget.py @@ -38,6 +38,10 @@ Reserve source coverage and select whole evidence items within limits. +- ``allocate_group_evidence`` + + Reserve anchors and share a physical evidence budget across groups. + - ``evidence_block`` Render one numbered evidence block, also used in answer prompts. @@ -62,6 +66,7 @@ from typing import Final, Generic, Literal, Protocol, TypeVar from kilin.retrievals.document_reading import estimate_tokens +from kilin.source_views import SourceGroup __all__ = [ "COVERAGE_BOUNDED", @@ -70,6 +75,7 @@ "EvidenceLimits", "EvidenceSelection", "allocate_evidence", + "allocate_group_evidence", "coverage_report", "evidence_block", "evidence_tokens", @@ -121,9 +127,11 @@ class EvidenceLimits: Parameters ---------- max_sources: int - Maximum number of represented sources. + Maximum selected logical anchors in grouped mode; otherwise the + maximum number of represented physical sources. passages_per_source: int - Desired passages per selected source; a target, not a guarantee. + Desired passages per selected group or physical source; a target, + not a guarantee. max_passages: int Hard number of evidence passages. max_tokens: int @@ -356,6 +364,133 @@ def add(index: int) -> bool: ) +def allocate_group_evidence( + items: Sequence[_EvidenceT], limits: EvidenceLimits, + groups: Sequence[SourceGroup], +) -> EvidenceSelection[_EvidenceT]: + """Reserve anchor passages and allocate one shared physical budget. + + Parameters + ---------- + items: Sequence[_EvidenceT] + Original candidate passages in retrieval priority order. Evidence + members of the selected groups only are eligible; lookup-only + members never enter documentary context. + limits: EvidenceLimits + Hard logical-source, physical-passage and estimated-token limits. + groups: Sequence[SourceGroup] + Selected groups in ranking order, including unindexed anchors. + + Returns + ------- + EvidenceSelection[_EvidenceT] + Deduplicated original passages and applicable budget diagnostics. + + Notes + ----- + The anchor's best fitting passage is reserved for each selected group + before attachments consume capacity. A shared passage counts toward + each selected parent's desired quota but costs only one physical slot + and one evidence block. After attempting each quota, remaining space + can be filled in retrieval order, as in physical-source allocation. + The token estimate includes headers and conservative citation widths. + + """ + anchors = tuple(group.anchor for group in groups) + if len(set(anchors)) != len(anchors): + raise ValueError("Duplicate group anchor.") + if len(groups) > limits.max_sources: + raise ValueError("Selected groups exceed the logical source limit.") + members: dict[Path, list[Path]] = {} + for group in groups: + for path in group.evidence: + members.setdefault(path, []).append(group.anchor) + ordered = [] + seen = set() + for item in items: + # Coordinates include notebook cell/page information and exact + # text, not the citation number or context label of a past turn. + key = (item.path, item.start_line, item.end_line, item.symbol, + getattr(item, "cell", None), item.text) + if item.path in members and key not in seen: + seen.add(key) + ordered.append(item) + by_path: dict[Path, list[int]] = {} + by_group: dict[Path, list[int]] = {anchor: [] for anchor in anchors} + for index, item in enumerate(ordered): + by_path.setdefault(item.path, []).append(index) + for anchor in members[item.path]: + by_group[anchor].append(index) + chosen: list[int] = [] + used: set[int] = set() + represented = dict.fromkeys(anchors, 0) + hit: set[str] = set() + token_total = 0 + number = int("9" * len(str(limits.max_passages))) + + def add(index: int) -> bool: + """Add one physical item and update every selected membership. + + Parameters + ---------- + index: int + Original candidate index to consider. + + Returns + ------- + bool + Whether the item was newly accepted within the hard limits. + + """ + nonlocal token_total + if index in used: + return False + if len(chosen) >= limits.max_passages: + hit.add("passages") + return False + item = ordered[index] + cost = estimate_tokens("\n\n" + evidence_block(item, number)) + if token_total + cost > limits.max_tokens: + hit.add("tokens") + return False + chosen.append(index) + used.add(index) + token_total += cost + for anchor in members[item.path]: + represented[anchor] += 1 + return True + + # Do not let long attachments consume the initial anchor reservation. + for anchor in anchors: + if any(index in used for index in by_path.get(anchor, ())): + continue + for index in by_path.get(anchor, ()): + if add(index): + break + # An unindexed or oversized anchor can still have supporting evidence; + # coverage must continue to distinguish that from the anchor itself. + for anchor in anchors: + if represented[anchor]: + continue + for index in by_group[anchor]: + if add(index): + break + for anchor in anchors: + for index in by_group[anchor]: + if represented[anchor] >= limits.passages_per_source: + break + add(index) + for index in range(len(ordered)): + add(index) + retained = tuple(ordered[index] for index in chosen) + return EvidenceSelection( + items=retained, + estimated_tokens=evidence_tokens(retained), + omitted=len(ordered) - len(retained), + limits_hit=tuple(sorted(hit)) if len(used) < len(ordered) else (), + ) + + def coverage_report( requested: Sequence[Path], items: Sequence[_EvidenceItem], diff --git a/kilin/retrievals/requests.py b/kilin/retrievals/requests.py index 1d996ce4..c462253b 100644 --- a/kilin/retrievals/requests.py +++ b/kilin/retrievals/requests.py @@ -40,18 +40,23 @@ from __future__ import annotations +from collections.abc import Sequence from dataclasses import dataclass -from pathlib import Path, PureWindowsPath +from pathlib import Path from typing import TYPE_CHECKING, Final, Literal from kilin.retrievals.evidence_budget import EvidenceLimits +from kilin.source_views import ScopeMode, SourceGroup, SourceScope, SourceView if TYPE_CHECKING: from kilin.chunking import Chunk + from kilin.retrievals.evidence_budget import _EvidenceItem __all__ = [ "RetrievalRequest", "RetrievalResult", + "SourceGroupCoverage", + "group_coverage", ] RetrievalStrategy = Literal["hybrid", "source_first"] @@ -72,14 +77,27 @@ class RetrievalRequest: Tool- or caller-owned hard evidence limits. strategy: "hybrid" | "source_first", optional Retrieval strategy, defaulting to ``source_first``. - scope: tuple[pathlib.Path, ...], optional - Explicit source-relative paths. Multiple paths restrict the search. + scope: tuple[pathlib.Path, ...] | None, optional + Source-relative operands. Omission means project-wide; an explicit + empty tuple means restricted empty. Stored as a tuple after validation. compare: bool, optional - Allow other sources alongside a single named source. Defaults to - ``False``. + Comparison request, independent of logical grouping. Defaults to + False. Without an explicit scope mode, a single comparison operand + is preferred; other explicit operands are restricted. card_kinds: tuple[str, ...], optional Restrict card discovery to these registered kind identifiers. Empty means all kinds. Valid only for ``source_first``. + include_bibliographies: bool | None, optional + Include bibliography passages in source-first lookup. None resolves + explicit lookup from the query/scope; False restricts discovery to + independent documents. Defaults to None. + scope_mode: ScopeMode | None, optional + Explicit project, preferred or restricted mode. If omitted, resolve + from scope and comparison as described above. Stored as a mode. + view: SourceView | None, optional + Frozen resolved operation. Its scope must match the request, or + supplies the scope when both scope arguments are omitted. Hosts + without view-aware retrieval must reject it, not widen the request. Raises ------ @@ -93,9 +111,12 @@ class RetrievalRequest: query: str limits: EvidenceLimits strategy: RetrievalStrategy = "source_first" - scope: tuple[Path, ...] = () + scope: tuple[Path, ...] | None = None compare: bool = False card_kinds: tuple[str, ...] = () + include_bibliographies: bool | None = None + scope_mode: ScopeMode | None = None + view: SourceView | None = None def __post_init__(self) -> None: """Reject ambiguous requests before indexing or model operations. @@ -117,45 +138,142 @@ def __post_init__(self) -> None: raise ValueError("Unknown retrieval strategy.") if type(self.compare) is not bool: raise ValueError("compare must be boolean.") - if type(self.scope) is not tuple: - raise ValueError("scope must be a tuple of relative paths.") - for path in self.scope: - if not isinstance(path, Path) or not _relative_path(path): - raise ValueError("scope requires valid relative paths.") + if self.view is not None and type(self.view) is not SourceView: + raise ValueError("view must be a resolved SourceView.") + if (self.view is not None and self.view.operation.policy.grouped + and self.strategy != "source_first"): + raise ValueError("Grouped retrieval requires source_first.") + if self.scope is None and self.scope_mode is None and self.view: + scope = self.view.operation.scope + else: + paths = () if self.scope is None else self.scope + mode = self.scope_mode + if mode is None: + if self.scope is None: + mode = "project" + elif (self.compare and type(paths) is tuple + and len(paths) == 1): + mode = "preferred" + else: + mode = "restricted" + scope = SourceScope(mode, paths) + if self.view is not None and scope != self.view.operation.scope: + raise ValueError("Request scope differs from the resolved view.") + object.__setattr__(self, "scope", scope.paths) + object.__setattr__(self, "scope_mode", scope.mode) if type(self.card_kinds) is not tuple or any( not isinstance(kind, str) or not kind.strip() for kind in self.card_kinds ): raise ValueError("card_kinds must contain nonempty names.") + if (self.include_bibliographies is not None + and type(self.include_bibliographies) is not bool): + raise ValueError("include_bibliographies must be boolean.") + if (self.include_bibliographies is not None + and self.strategy != "source_first"): + raise ValueError("Bibliography policy requires source_first.") if self.card_kinds and self.strategy != "source_first": raise ValueError("Card filters require source_first retrieval.") + @property + def source_scope(self) -> SourceScope: + """Return the validated explicit scope for operation resolution.""" + return SourceScope(self.scope_mode, self.scope) -def _relative_path(path: Path) -> bool: - """Check portable source-relative paths without filesystem access. + +@dataclass(frozen=True, slots=True) +class SourceGroupCoverage: + """Physical representation of one logical group in returned passages. + + Attributes + ---------- + group: SourceGroup + Frozen membership including unavailable members. + represented: tuple[pathlib.Path, ...] + Members having at least one original returned passage. This does + not establish complete reading or scientific support. + + """ + + group: SourceGroup + represented: tuple[Path, ...] + + def __post_init__(self) -> None: + """Reject representations that are not distinct group members.""" + if type(self.group) is not SourceGroup: + raise ValueError("Coverage requires a SourceGroup.") + SourceScope("restricted", self.represented) + if not {p.as_posix() for p in self.represented} <= { + p.as_posix() for p in (*self.group.evidence, *self.group.lookup) + }: + raise ValueError("Coverage contains nonmembers.") + if any(item.path in self.represented and item.reason == "unindexed" + for item in self.group.unavailable): + raise ValueError("Unindexed members cannot be represented.") + + @property + def anchor_represented(self) -> bool: + """Return whether the anchor itself has a returned passage.""" + return self.group.anchor in self.represented + + @property + def evidence_represented(self) -> tuple[Path, ...]: + """Return represented evidence members, excluding lookup-only paths.""" + return tuple(p for p in self.group.evidence if p in self.represented) + + @property + def omitted(self) -> tuple[Path, ...]: + """Return available members not represented in returned passages.""" + unavailable = {item.path for item in self.group.unavailable + if item.reason != "raw_unavailable"} + return tuple(path for path in dict.fromkeys( + (*self.group.evidence, *self.group.lookup) + ) if path not in unavailable and path not in self.represented) + + def data(self) -> dict[str, object]: + """Return JSON-compatible representation, not content coverage.""" + return { + "anchor": self.group.anchor.as_posix(), + "anchor_represented": self.anchor_represented, + "evidence_members": [p.as_posix() for p in self.group.evidence], + "lookup_members": [p.as_posix() for p in self.group.lookup], + "represented_members": [p.as_posix() for p in self.represented], + "represented_evidence_members": [ + p.as_posix() for p in self.evidence_represented + ], + "omitted_members": [p.as_posix() for p in self.omitted], + "unavailable_members": [ + {"path": item.path.as_posix(), "reason": item.reason} + for item in self.group.unavailable + ], + } + + +def group_coverage( + group: SourceGroup, passages: Sequence[Chunk | _EvidenceItem], +) -> SourceGroupCoverage: + """Report which group members have actual returned original passages. Parameters ---------- - path: pathlib.Path - Candidate source path. + group: SourceGroup + Resolved anchor and physical members. + passages: Sequence[Chunk | _EvidenceItem] + Final original indexed chunks or evidence with physical paths, + shared passages included only once. Returns ------- - bool - True for nonempty relative paths without parent traversal. + SourceGroupCoverage + Representation of physical members of this group; a shared member + can appear in the coverage of each of its parents. """ - - windows = PureWindowsPath(str(path)) - return ( - not path.is_absolute() - and not windows.is_absolute() - and not windows.drive - and not windows.root - and bool(path.parts) - and all(part not in ("", ".", "..") for part in path.parts) - and all(part not in ("", ".", "..") for part in windows.parts) - ) + represented = {item.path.as_posix() for item in passages} + return SourceGroupCoverage(group, tuple( + path for path in dict.fromkeys((*group.evidence, *group.lookup)) + if path.as_posix() in represented + )) @dataclass(frozen=True, slots=True) @@ -170,12 +288,81 @@ class RetrievalResult: sources: tuple[pathlib.Path, ...] Sources chosen by the strategy, ordered by source relevance. A selected source can have no fitting evidence under the token budget. + In grouped mode these are the distinct physical paths actually + represented; selected anchors are recorded separately in groups. coverage: dict[str, object] JSON-compatible source-representation report. Coverage does not establish that the complete content of a source was examined. + When a view is provided, group coverage is also serialized here. + groups: tuple[SourceGroupCoverage, ...], optional + Selected logical group representation, independent of physical paths. + view: SourceView | None, optional + Captured operation membership for scoped/grouped retrieval. """ passages: tuple[Chunk, ...] sources: tuple[Path, ...] coverage: dict[str, object] + groups: tuple[SourceGroupCoverage, ...] = () + view: SourceView | None = None + + def __post_init__(self) -> None: + """Validate coverage without changing original chunk identity.""" + if type(self.groups) is not tuple or any( + type(item) is not SourceGroupCoverage for item in self.groups + ): + raise ValueError("groups requires a tuple of SourceGroupCoverage.") + if self.view is None: + if self.groups or "groups" in self.coverage: + raise ValueError("Group coverage requires a resolved view.") + return + if type(self.view) is not SourceView: + raise ValueError("view must be a resolved SourceView.") + members = {p.as_posix() for p in (*self.view.evidence, + *self.view.lookup)} + SourceScope("restricted", self.sources) + if not {p.as_posix() for p in self.sources} <= members or any( + item.path.as_posix() not in members for item in self.passages + ): + raise ValueError("Retrieval result exceeds the resolved view.") + indexed = {item.path.as_posix() + for item in self.view.operation.inventory.files + if item.indexed} + if type(self.passages) is not tuple or any( + item.path.as_posix() not in indexed for item in self.passages + ): + raise ValueError("Passage is outside captured index generation.") + keys = {(item.path.as_posix(), item.identifier) + for item in self.passages} + if len(keys) != len(self.passages): + raise ValueError("Duplicate physical retrieval passages.") + anchors = tuple(item.group.anchor for item in self.groups) + if len(set(anchors)) != len(anchors): + raise ValueError("Duplicate group coverage anchors.") + by_anchor = {item.anchor: item for item in self.view.groups} + for item in self.groups: + if by_anchor.get(item.group.anchor) != item.group or ( + item != group_coverage(item.group, self.passages) + ): + raise ValueError("Group coverage disagrees with passages.") + if self.view.operation.policy.grouped: + grouped_members = { + path.as_posix() for item in self.groups + for path in item.group.evidence + } + if (not {p.as_posix() for p in self.sources} <= grouped_members + or any(item.path.as_posix() not in grouped_members + for item in self.passages)): + raise ValueError("Grouped retrieval requires group coverage " + "of eligible evidence members.") + represented = tuple(dict.fromkeys( + item.path for item in self.passages + )) + if self.sources != represented: + raise ValueError("Grouped sources must match represented " + "physical paths in citation order.") + data = [item.data() for item in self.groups] + if "groups" in self.coverage and self.coverage["groups"] != data: + raise ValueError("Conflicting serialized group coverage.") + object.__setattr__(self, "coverage", {**self.coverage, "groups": data}) diff --git a/kilin/retrievals/source_cards/index.py b/kilin/retrievals/source_cards/index.py index 69f7212a..0e75d0d8 100644 --- a/kilin/retrievals/source_cards/index.py +++ b/kilin/retrievals/source_cards/index.py @@ -67,6 +67,7 @@ from pathlib import Path from typing import TypeAlias +from kilin.source_eligibility import document_candidate from kilin.chunking import Chunk from kilin.retrievals.source_cards.models import ( CARD_STATUS_FAILED, @@ -469,6 +470,8 @@ def plan_source_card_updates( _check_descriptor(source) _check_hash(source_hashes.get(path), "Source SHA-256") kind = registry.get(kind_id) + if kind_id == "scientific_paper" and not document_candidate(path): + continue record = existing.get((path, kind_id)) key = (path, kind_id) if record is None or ( @@ -681,6 +684,7 @@ def search_source_cards( query_vector: Sequence[float], *, count: int = 5, + allowed_paths: frozenset[Path] | None = None, ) -> tuple[SourceCardMatch, ...]: """Rank source-card groups by their best cosine similarity to a query. @@ -693,6 +697,10 @@ def search_source_cards( count: int, optional Maximum cards to return. Defaults to ``5``. + allowed_paths: frozenset[pathlib.Path] | None, optional + Only these physical files may participate in ranking. None permits + all eligible cards; an empty set permits none. + Returns ------- tuple[SourceCardMatch, ...] @@ -714,6 +722,11 @@ def search_source_cards( raise ValueError("Query and card vector dimensions do not match.") results = [] for record in vectors.records: + if allowed_paths is not None and record.path not in allowed_paths: + continue + if (record.kind == "scientific_paper" + and not document_candidate(record.path)): + continue score = max( _cosine(query_vector, norm, vector) for vector in record.embeddings diff --git a/kilin/retrievals/source_cards/indexing.py b/kilin/retrievals/source_cards/indexing.py index 6a2eab80..3c35247d 100644 --- a/kilin/retrievals/source_cards/indexing.py +++ b/kilin/retrievals/source_cards/indexing.py @@ -3,8 +3,8 @@ The coordinator selects one registered card kind per source, validates saved outcomes and reuse plans, generates only missing cards with an isolated model, and embeds only missing vector groups with the existing embedding session. -Source-card failures do not affect ordinary passage retrieval. No old paper -cache is imported or migrated. +Source-card failures do not affect ordinary passage retrieval. Invalid saved +card content cannot establish reusable card state. Key Features ------------ diff --git a/kilin/retrievals/source_cards/kinds/scientific_paper.py b/kilin/retrievals/source_cards/kinds/scientific_paper.py index 951e06d9..c7aa362a 100644 --- a/kilin/retrievals/source_cards/kinds/scientific_paper.py +++ b/kilin/retrievals/source_cards/kinds/scientific_paper.py @@ -1,22 +1,21 @@ """Generate provenance-linked source cards for scientific papers. -The first registered card kind follows the original paper-card approach: -read opening passages, add lexical matches for methods, data, findings and -limitations, then request a compact JSON card in one model call. Unlike the -old ``PaperCard`` representation, substantive fields cite original chunk IDs -and the model's eligibility decision is recorded as a distinct result. +The scientific-paper kind reads opening passages, adds lexical matches for +methods, data, findings and limitations, then requests a compact JSON card +in one model call. Substantive fields cite original chunk identifiers, and +the model's eligibility decision is recorded as a distinct result. Scientific papers include original studies, reviews, preprints, conference papers, methods papers and scientific-software papers. File suffixes do not -establish eligibility. Other document kinds may be registered later without -changing the generic source-card records or their independent indexes. +establish eligibility. The generic source-card records and independent +indexes are not specific to scientific papers. Key Features ------------ -- **Original field coverage** +- **Structured field coverage** - Preserve the abstract, aim, methods, data, findings and limitations. + Record the abstract, aim, methods, data, findings and limitations. - **Bounded reading** @@ -80,6 +79,7 @@ _check_path, validate_source_card, ) +from kilin.source_eligibility import document_candidate from kilin.retrievals.strategies.retrieval_lexical import ( build_lexical_index, lexical_search, @@ -161,7 +161,7 @@ class ScientificPaperKind: validation_version: Final[int] = 1 def precheck(self, source: SourceDescriptor) -> bool: - """Admit sources with extracted chunks, regardless of file format. + """Admit extracted text except intrinsic bibliography containers. Parameters ---------- @@ -175,7 +175,7 @@ def precheck(self, source: SourceDescriptor) -> bool: """ - return bool(source.chunk_ids) + return bool(source.chunk_ids) and document_candidate(source.path) def validate(self, card: SourceCard) -> None: """Check scientific-paper fields after generic provenance checks. @@ -232,8 +232,7 @@ def card_texts(card: SourceCard) -> tuple[str, ...]: ------- tuple[str, ...] Title-led abstract/aim, methods/data, and findings/limitations. - Empty groups are omitted except for the first, matching the - original paper-card search projection. + Empty groups are omitted except for the first. Raises ------ @@ -285,10 +284,10 @@ def card_passages( Notes ----- - Selection follows the original paper-card ordering: three opening - chunks, then the two best lexical matches for each field query. The - budget includes instructions, JSON keys, labels and passage text. A - clipped excerpt still cites the original full chunk via its ID. + Selection prioritizes three opening chunks, then the two best lexical + matches for each field query. The budget includes instructions, JSON + keys, labels and passage text. A clipped excerpt still cites the + original full chunk via its ID. """ @@ -450,9 +449,9 @@ def parse_card( Notes ----- - Unsupported fields are discarded as in the original paper-card - parser. Every retained substantive statement must cite an excerpt the - model actually received, mapped to an original chunk identifier. + Unsupported fields are discarded. Every retained substantive statement + must cite an excerpt the model actually received, mapped to an original + chunk identifier. """ @@ -550,7 +549,8 @@ def generate_card( if not ScientificPaperKind().precheck(source): return SourceCardResult( source.path, "scientific_paper", CARD_STATUS_NOT_APPLICABLE, - reason="No extracted text chunks.", + reason=("No extracted text chunks." if not source.chunk_ids + else "Bibliography container, not a scientific paper."), ) permitted = set(source.chunk_ids) if any( @@ -771,7 +771,7 @@ def _failed(source: SourceDescriptor, reason: str) -> SourceCardResult: def _reading_position(chunk: Chunk) -> tuple[int, int]: - """Return the paper-card patch's page and line reading order. + """Return a chunk's page and source-line reading order. Parameters ---------- diff --git a/kilin/retrievals/source_cards/models.py b/kilin/retrievals/source_cards/models.py index 35cddcf3..cb779895 100644 --- a/kilin/retrievals/source_cards/models.py +++ b/kilin/retrievals/source_cards/models.py @@ -7,7 +7,7 @@ Cards are not answer evidence: later retrieval stages must return the original chunks before making supported claims. This module performs no model calls, -file I/O, or indexing, and does not replace the active paper-card pipeline. +file I/O, or indexing. Key Features ------------ diff --git a/kilin/retrievals/source_cards/persistence.py b/kilin/retrievals/source_cards/persistence.py index f015db45..cd18fcb7 100644 --- a/kilin/retrievals/source_cards/persistence.py +++ b/kilin/retrievals/source_cards/persistence.py @@ -9,8 +9,9 @@ Files are atomically replaced one at a time using the existing core writer. There is no cross-file transaction or inter-process writer coordination. If indexing stops between writes, card content remains readable and vector -groups inconsistent with that content are discarded on load. Missing files -are empty indexes, not an invitation to read obsolete paper-card formats. +groups inconsistent with that content are discarded on load. A missing card +file represents an empty content index; a missing vector file provides no +reusable vectors. Key Features ------------ @@ -24,9 +25,9 @@ Reject malformed or incorrectly checksummed payloads, and ignore stale vector groups. -- **No migration** +- **Format validation** - Read only the new source-card formats; older paper caches are unaffected. + Accept only supported source-card formats and reject incompatible data. Module Structure ---------------- diff --git a/kilin/retrievals/source_coverage.py b/kilin/retrievals/source_coverage.py index a4904c59..cabf74f0 100644 --- a/kilin/retrievals/source_coverage.py +++ b/kilin/retrievals/source_coverage.py @@ -26,6 +26,10 @@ How many sources a question asks about ("the five articles"). +- ``grouped_coverage_report`` and ``group_operation_data`` + + Distinguish logical selection from physical evidence representation. + Examples -------- >>> asks_for_all_sources("Compare all five papers") @@ -37,10 +41,22 @@ from __future__ import annotations +from collections.abc import Sequence +from dataclasses import asdict +from pathlib import Path import re from typing import Final -__all__ = ["asks_for_all_sources", "requested_source_count"] +from kilin.retrievals.evidence_budget import ( + COVERAGE_BOUNDED, CoverageMode, _EvidenceItem, coverage_report, +) +from kilin.retrievals.requests import SourceGroupCoverage, group_coverage +from kilin.source_views import SourceGroup, SourceView + +__all__ = [ + "asks_for_all_sources", "requested_source_count", + "grouped_coverage_report", "group_operation_data", +] _DOCUMENTS: Final[str] = ( r"(?:papers?|articles?|stud(?:y|ies)|documents?|sources?|pdfs?|works?)" @@ -128,3 +144,117 @@ def requested_source_count(question: str) -> int: _NUMBER_WORDS[token] if token in _NUMBER_WORDS else int(token) ) return max(counts, default=0) + + +def group_operation_data(view: SourceView) -> dict[str, object]: + """Describe a captured grouped operation without source contents. + + Parameters + ---------- + view: SourceView + Frozen source organization and policy used by the retrieval call. + + Returns + ------- + dict[str, object] + Semantic revision and digest, index/selection identity and policy. + + """ + operation = view.operation + return { + "semantic_revision": operation.revision, + "manifest_sha256": operation.manifest_sha256, + "selected_generation": operation.selected_generation, + "index_generation": operation.inventory.index_generation, + "policy": { + key: list(value) if isinstance(value, tuple) else value + for key, value in asdict(operation.policy).items() + }, + "scope_mode": operation.scope.mode, + "scope_operands": [p.as_posix() for p in operation.scope.paths], + } + + +def grouped_coverage_report( + view: SourceView, items: Sequence[_EvidenceItem], + selected: Sequence[SourceGroup], requested: Sequence[Path], *, + mode: CoverageMode = COVERAGE_BOUNDED, + limits_hit: Sequence[str] = (), +) -> tuple[dict[str, object], tuple[SourceGroupCoverage, ...]]: + """Report selected anchors and actual physical member representation. + + Parameters + ---------- + view: SourceView + Captured grouped operation, including inactive-member diagnostics. + items: Sequence[_EvidenceItem] + Final original evidence items (shared passages occur only once). + selected: Sequence[SourceGroup] + Chosen logical groups, in ranking order. + requested: Sequence[pathlib.Path] + Requested anchors, including unselected groups in exhaustive mode. + mode: CoverageMode, optional + Bounded or exhaustive coverage. Defaults to bounded. + limits_hit: Sequence[str], optional + Resource limits identified during selection and allocation. + + Returns + ------- + tuple[dict[str, object], tuple[SourceGroupCoverage, ...]] + JSON-safe physical and logical coverage and selected group rows. + + Notes + ----- + A shared member can represent several selected groups, but it cannot + make an unselected group selected or its absent anchor represented. + Lookup-only members are reported separately, never required for + scientific evidence completeness. Coverage is not full-file reading. + + """ + anchors = {group.anchor: group for group in view.groups} + chosen = {group.anchor for group in selected} + requested_groups = tuple(anchors[path] for path in dict.fromkeys( + (*requested, *(group.anchor for group in selected)) + )) + rows = tuple(group_coverage(group, items) for group in selected) + represented = {row.group.anchor for row in rows + if row.evidence_represented} + read_anchors = {row.group.anchor for row in rows + if row.anchor_represented} + missing_groups = [group.anchor.as_posix() for group in requested_groups + if group.anchor not in represented] + missing_anchors = [group.anchor.as_posix() for group in requested_groups + if group.anchor not in read_anchors] + unselected = tuple(group for group in requested_groups + if group.anchor not in chosen) + physical = tuple(dict.fromkeys(path for group in requested_groups + for path in group.evidence)) + indexed = {state.path for state in view.operation.inventory.files + if state.indexed} + coverage = coverage_report( + physical, items, mode=mode, + unavailable=tuple(path for path in physical if path not in indexed), + limits_hit=limits_hit, + ) + reasons = set(coverage["limits_hit"]) + if missing_anchors: + reasons.add("group_coverage") + coverage.update({ + "grouped": True, + "physical_complete": coverage["complete"], + "complete": coverage["complete"] and not missing_anchors, + "requested_groups": len(requested_groups), + "selected_groups": len(selected), + "represented_groups": len(represented), + "represented_anchors": len(read_anchors), + "missing_groups": missing_groups, + "missing_anchors": missing_anchors, + "unselected_groups": [group.anchor.as_posix() for group in unselected], + "unselected_group_details": [group_coverage(group, items).data() + for group in unselected], + "groups": [row.data() for row in rows], + "limits_hit": sorted(reasons), + "source_operation": group_operation_data(view), + "meaning": "logical and physical representation, not full review", + }) + return coverage, rows diff --git a/kilin/retrievals/source_descriptions.py b/kilin/retrievals/source_descriptions.py index 5f47ccbc..c26cba73 100644 --- a/kilin/retrievals/source_descriptions.py +++ b/kilin/retrievals/source_descriptions.py @@ -49,6 +49,8 @@ import re from typing import Final +from kilin.source_eligibility import document_candidate + __all__ = ["described_sources"] # Nouns that end a description of one document. @@ -120,6 +122,8 @@ def described_sources( """ + cards = {path: card for path, card in cards.items() + if document_candidate(path)} matches: list[tuple[int, Path]] = [] for match in _DESCRIPTION.finditer(question): path = _resolve(_tokens(match.group("words")), cards) diff --git a/kilin/retrievals/strategies/retrieval_sources.py b/kilin/retrievals/strategies/retrieval_sources.py index 9b6f6e69..965391ee 100644 --- a/kilin/retrievals/strategies/retrieval_sources.py +++ b/kilin/retrievals/strategies/retrieval_sources.py @@ -36,11 +36,11 @@ - ``source_first_search`` - Fuse the four supplied rankings at source level. + Fuse four supplied rankings at physical-file or logical-group level. - ``relevant_sources`` - Keep the ranked sources that the question is about. + Keep the ranked sources or logical groups the question is about. - ``select_source_passages`` @@ -62,7 +62,10 @@ from pathlib import Path from typing import Protocol +from kilin.source_views import SourceGroup + from kilin.defaults import load_defaults_section, require_default_int +from kilin.source_eligibility import document_candidate from kilin.retrievals.strategies.retrieval_hybrid import ( HybridResult, RankedResult, @@ -134,6 +137,8 @@ def source_first_search( cards: Sequence[_CardRankedResult] = (), count: int = 5, rank_constant: int = _RRF_RANK_CONSTANT, + include_bibliographies: bool = False, + groups: Sequence[SourceGroup] | None = None, ) -> list[SourceResult]: """Fuse one rank per distinct source in each available channel. @@ -152,6 +157,12 @@ def source_first_search( Maximum number of sources returned. Defaults to ``5``. rank_constant: int, optional RRF smoothing constant from retrieval defaults. + include_bibliographies: bool, optional + Include bibliography text for explicit lookup, not paper cards. + Defaults to ``False``. + groups: Sequence[SourceGroup] | None, optional + Opt into logical anchors. Only their evidence members contribute; + shared members can vote once for each parent. None ranks files. Returns ------- @@ -168,7 +179,9 @@ def source_first_search( Repeated chunks and cards do not change a source's channel position. Source ranks are consecutive after deduplication, rather than the positions of the original chunks. Raw similarity scores are never - compared between channels. No model or index is queried here. + compared between channels. A shared best member gives its parents the + same group rank; later ranks skip the tied positions. No model or index + is queried here. """ @@ -177,6 +190,12 @@ def source_first_search( if type(rank_constant) is not int or rank_constant < 1: raise ValueError("rank_constant must be a positive whole number.") + if type(include_bibliographies) is not bool: + raise ValueError("include_bibliographies must be boolean.") + + if groups is not None and include_bibliographies: + raise ValueError("Grouped discovery cannot rank bibliography lookup.") + memberships = _group_memberships(groups) if groups is not None else None positions: dict[Path, dict[str, int]] = {} rankings = ( ("semantic", (item.chunk.path for item in semantic)), @@ -187,10 +206,16 @@ def source_first_search( for channel, paths in rankings: seen: set[Path] = set() for path in paths: - if path in seen: + if (not document_candidate(path) + and (channel == "cards" or not include_bibliographies)): continue - seen.add(path) - positions.setdefault(path, {})[channel] = len(seen) + anchors = ((path,) if memberships is None + else memberships.get(path, ())) + rank = len(seen) + 1 + for anchor in anchors: + if anchor not in seen: + seen.add(anchor) + positions.setdefault(anchor, {})[channel] = rank results = [] for path, ranks in positions.items(): @@ -213,6 +238,7 @@ def relevant_sources( depth: int, keep: Collection[Path] = (), minimum: int = 1, + groups: Sequence[SourceGroup] | None = None, ) -> list[SourceResult]: """Keep the ranked sources that the question is about. @@ -235,6 +261,9 @@ def relevant_sources( minimum: int, optional Fewest sources kept when that many are ranked (2 for a comparison). Defaults to ``1``. + groups: Sequence[SourceGroup] | None, optional + In grouped mode, measure relevance depth in distinct anchors, + using their best evidence member. None keeps physical-file depth. Returns ------- @@ -257,8 +286,15 @@ def relevant_sources( raise ValueError("minimum must be a positive whole number.") best: dict[Path, int] = {} - for position, result in enumerate(passages): - best.setdefault(result.chunk.path, position) + if groups is None: + for position, result in enumerate(passages): + best.setdefault(result.chunk.path, position) + else: + memberships = _group_memberships(groups) + for result in passages: + position = len(best) + for anchor in memberships.get(result.chunk.path, ()): + best.setdefault(anchor, position) kept = [ item for item in ranked if item.path in keep @@ -357,3 +393,30 @@ def select_source_passages( selected.append(result) seen.add(result.chunk.identifier) return selected + + +def _group_memberships( + groups: Sequence[SourceGroup], +) -> dict[Path, tuple[Path, ...]]: + """Map scientific evidence members to their independent anchors. + + Parameters + ---------- + groups: Sequence[SourceGroup] + Distinct resolved logical groups, without lookup-only votes. + + Returns + ------- + dict[pathlib.Path, tuple[pathlib.Path, ...]] + Original physical paths mapped to all eligible parent anchors. + + """ + by_path: dict[Path, list[Path]] = {} + anchors: set[Path] = set() + for group in groups: + if group.anchor in anchors: + raise ValueError("Duplicate group anchor.") + anchors.add(group.anchor) + for path in group.evidence: + by_path.setdefault(path, []).append(group.anchor) + return {path: tuple(parents) for path, parents in by_path.items()} diff --git a/kilin/settings_info.json b/kilin/settings_info.json index 31becfcd..cf67ee20 100644 --- a/kilin/settings_info.json +++ b/kilin/settings_info.json @@ -211,6 +211,21 @@ "summary": "Allows evidence from related earlier turns to support this intent.", "description": "Adds eligible previously retrieved context where supported by the conversation and intent policies." }, + "project_behavior.intents.retrieval.related_evidence": { + "title": "Linked source evidence", + "summary": "Declares relation types whose linked sources may support an ordinary intent.", + "description": "Selects declared relation IDs independently of evidence from earlier conversation turns. The accepted project vocabulary validates the policy. Tool-backed intents own their policies." + }, + "project_behavior.intents.retrieval.related_lookup": { + "title": "Linked source lookup", + "summary": "Declares relation types whose linked sources may provide lookup material.", + "description": "Selects declared relation IDs for lookup rather than scientific support. The accepted project vocabulary validates the policy. Tool-backed intents own their policies." + }, + "project_behavior.intents.retrieval.grouped": { + "title": "Logical document groups", + "summary": "Counts independent anchors rather than individual files in source-first retrieval.", + "description": "Opt in to anchor-centered ranking and evidence allocation. Related evidence uses the same passage and estimated-token budgets; lookup-only material does not vote. Defaults to false." + }, "project_behavior.intents.retrieval.prefer_source_code": { "title": "Prefer source code", "summary": "Favors source-code passages where the intent supports this choice.", diff --git a/kilin/settings_info.py b/kilin/settings_info.py index 3a537a21..77eb82eb 100644 --- a/kilin/settings_info.py +++ b/kilin/settings_info.py @@ -57,6 +57,7 @@ from functools import lru_cache from importlib.resources import files import json +from pathlib import Path __all__ = [ "get_setting_info", @@ -97,13 +98,13 @@ def _unique_pairs(pairs: list[tuple[str, object]]) -> dict[str, object]: return parsed -def _load_resource(package: str, filename: str) -> dict[str, object]: +def _load_resource(package: str | Path, filename: str) -> dict[str, object]: """Parse and strictly validate one packaged settings-information file. Parameters ---------- - package: str - Installed Python package owning the metadata. + package: str | pathlib.Path + Installed core package name or observed tool resource directory. filename: str Name of the JSON resource within that package. @@ -119,7 +120,10 @@ def _load_resource(package: str, filename: str) -> dict[str, object]: """ - location = files(package).joinpath(filename) + location = ( + package / filename if isinstance(package, Path) + else files(package).joinpath(filename) + ) raw = location.read_bytes() if len(raw) > _MAX_BYTES: raise ValueError(f"Settings metadata in {package} is too large.") @@ -164,39 +168,37 @@ def _core_info() -> dict[str, object]: @lru_cache(maxsize=None) -def _tool_info(name: str) -> dict[str, object]: - """Load one tool's descriptions and check its declared settings. +def _read_tool_info(name: str, package: Path) -> dict[str, object]: + """Validate optional settings help from a specific package location. Parameters ---------- name: str - Registered tool name. + Candidate tool identifier. + package: pathlib.Path + Observed package directory, independent of registry state. Returns ------- dict[str, object] - Cached metadata keyed by normalized tool setting names. - - Raises - ------ - ValueError - If the tool is unknown or its metadata disagrees with defaults. + Validated descriptions, or an empty mapping when absent. """ - from kilin.tools._registry import TOOL_CHOICES - - if name not in TOOL_CHOICES: - raise ValueError(f"Unknown KíLín tool: {name}.") - package = f"kilin.tools.{name}" + if not (package / "settings_info.json").exists(): + return {} settings = _load_resource(package, "settings_info.json") - raw = files(package).joinpath("defaults.json").read_text( - encoding="utf-8" + path = package / "defaults.json" + if not path.exists(): + return settings + defaults = json.loads( + path.read_text(encoding="utf-8"), object_pairs_hook=_unique_pairs ) - defaults = json.loads(raw, object_pairs_hook=_unique_pairs) - if not isinstance(defaults, dict) or not isinstance( - defaults.get("SETTINGS"), dict - ): + if not isinstance(defaults, dict): + raise ValueError(f"Invalid defaults for tool {name}.") + if "SETTINGS" not in defaults: + return settings + if not isinstance(defaults["SETTINGS"], dict): raise ValueError(f"Invalid defaults for tool {name}.") expected = {key.lower() for key in defaults["SETTINGS"]} if set(settings) != expected: @@ -208,6 +210,35 @@ def _tool_info(name: str) -> dict[str, object]: return settings + +@lru_cache(maxsize=None) +def _tool_info(name: str) -> dict[str, object]: + """Resolve metadata from the registered package. + + Parameters + ---------- + name: str + Registered tool identifier. + + Returns + ------- + dict[str, object] + Descriptions, empty for absent or rejected optional user help. + + """ + + from kilin.tools._registry import registered_tools + + tools = registered_tools() + if name not in tools: + raise ValueError(f"Unknown KíLín tool: {name}.") + tool = tools[name] + info = getattr(tool, "_info", None) + if info is not None and info.origin == "user" and info.warnings: + return {} + return _read_tool_info(name, tool.resource_root) + + def get_tool_settings_info(name: str) -> dict[str, dict[str, str]]: """Return an independent copy of one tool's settings descriptions. @@ -242,10 +273,10 @@ def _combined_info() -> dict[str, object]: """ - from kilin.tools._registry import TOOL_CHOICES + from kilin.tools._registry import tool_choices settings = dict(_core_info()) - for name in TOOL_CHOICES: + for name in tool_choices(): for key, info in _tool_info(name).items(): settings[f"tools.{name}.{key}"] = info return {"format": _FORMAT, "settings": settings} @@ -296,9 +327,9 @@ def get_setting_info(key: str) -> dict[str, str] | None: parts = key.split(".") if len(parts) != 3: return None - from kilin.tools._registry import TOOL_CHOICES + from kilin.tools._registry import tool_choices - if parts[1] not in TOOL_CHOICES: + if parts[1] not in tool_choices(): return None value = _tool_info(parts[1]).get(parts[2]) else: diff --git a/kilin/source_card_policy.py b/kilin/source_card_policy.py index e21a00a4..caac3821 100644 --- a/kilin/source_card_policy.py +++ b/kilin/source_card_policy.py @@ -60,6 +60,7 @@ from typing import Final from kilin.atomic_writes import atomic_write_text +from kilin.source_eligibility import document_candidate from kilin.project_type import ProjectType from kilin.retrievals.source_cards.models import _check_path from kilin.retrievals.source_cards.registry import SOURCE_CARD_KINDS @@ -348,7 +349,7 @@ def select_source_card_kinds( Returns ------- dict[pathlib.Path, str] - One registered kind per selected and enabled source. + One registered kind per selected, enabled, eligible source. """ @@ -363,7 +364,8 @@ def select_source_card_kinds( kind = override.kind if override and override.kind else policy.kind if kind is not None: _check_kind(kind) - selected[path] = kind + if kind != "scientific_paper" or document_candidate(path): + selected[path] = kind return selected diff --git a/kilin/source_eligibility.py b/kilin/source_eligibility.py new file mode 100644 index 00000000..931f67d5 --- /dev/null +++ b/kilin/source_eligibility.py @@ -0,0 +1,176 @@ +"""Distinguish bibliography containers from independent document candidates. + +Bibliographies are selected physical files, not independent publications. +The same path remains eligible for exact lookup, literal scanning, and +file inventory. This module neither classifies papers nor grants file access. + +Key Features +------------ +- Case-insensitive intrinsic bibliography detection. +- Deterministic recognition of explicit bibliography lookup and paper scope. + +Module Structure +---------------- +- ``is_bibliography``: recognize bibliography containers. +- ``document_candidate``: exclude bibliography containers from discovery. +- ``bibliography_lookup``: identify an explicit bibliography operand. +- ``paper_request``: recognize paper-oriented wording, not generic file counts. +- ``without_source_filenames``: distinguish filename tokens from wording. + +Examples +-------- +>>> from pathlib import Path +>>> from kilin.source_eligibility import document_candidate +>>> document_candidate(Path("references.BIB")) +False +>>> document_candidate(Path("report.pdf")) +True + +The latter result does not establish that a report is a scientific paper. + +""" + +from __future__ import annotations + +from collections.abc import Sequence +from pathlib import Path +import re +from typing import Final + +__all__ = [ + "is_bibliography", "document_candidate", "bibliography_lookup", + "paper_request", "without_source_filenames", +] + +_BIBLIOGRAPHY_SUFFIXES: Final[frozenset[str]] = frozenset({".bib", ".bbl"}) +_PAPER_WORDS = re.compile( + r"\b(?:papers?|articles?|stud(?:y|ies)|publications?|preprints?|" + r"manuscripts?)\b", re.IGNORECASE, +) +_BIBLIOGRAPHY_WORDS = re.compile( + r"\b(?:bibliograph(?:y|ies|ic)|bibtex|citation keys?|bib entries)\b", + re.IGNORECASE, +) +_BIBLIOGRAPHY_OPERAND = re.compile( + r"\.(?:bib|bbl)(?![\w]|\.\w)", re.IGNORECASE, +) +_LOOKUP_WORDS = re.compile( + r"\b(?:bibliograph(?:y|ic)|bibtex)\s+(?:keys?|entries|entry|" + r"database|files?|metadata)\b|\bcitation keys?\b|" + r"\b(?:in|from)\s+(?:(?:the|a|my|our)\s+)?" + r"(?:bibliography|bibtex)\b", re.IGNORECASE, +) +_QUOTED_TERMS = re.compile(r'"[^"\n]*"|“[^”\n]*”|`[^`\n]*`') + +# Match a complete filename token, not a word inside a stem or a version. +_SOURCE_FILENAME = re.compile( + r"(? str: + """Remove filename tokens before interpreting natural-language cues. + + Parameters + ---------- + question: str + User request, possibly naming document or code files. + + Returns + ------- + str + Wording with recognized filename tokens replaced by spaces. + This is not a source resolver and grants no source access. + + """ + return _SOURCE_FILENAME.sub(" ", question) + + +def is_bibliography(path: Path) -> bool: + """Return whether a path names a bibliography container. + + Parameters + ---------- + path: pathlib.Path + Selected source-relative file path. + + Returns + ------- + bool + True for BibTeX or compiled LaTeX bibliography suffixes. + + """ + + return path.suffix.casefold() in _BIBLIOGRAPHY_SUFFIXES + + +def document_candidate(path: Path) -> bool: + """Return whether a file can be an independent document candidate. + + Parameters + ---------- + path: pathlib.Path + Selected source-relative file path. + + Returns + ------- + bool + False for bibliography containers. True does not establish a paper. + + """ + + return not is_bibliography(path) + + +def bibliography_lookup( + question: str, scope: Sequence[Path] = (), +) -> bool: + """Recognize a bibliography-specific operand before document discovery. + + Parameters + ---------- + question: str + User's request or explicit retrieval query. + scope: Sequence[pathlib.Path], optional + Explicitly selected paths. Defaults to an empty scope. + + Returns + ------- + bool + True for a scope explicitly including a bibliography, a filename, + or bibliography-specific lookup wording. General paper requests are + not reinterpreted as bibliography lookup merely for mentioning one. + + """ + + return ( + any(is_bibliography(path) for path in scope) + or bool(_BIBLIOGRAPHY_OPERAND.search(question)) + or bool(_BIBLIOGRAPHY_WORDS.search(question)) and ( + not _PAPER_WORDS.search(question) + or bool(_LOOKUP_WORDS.search(question)) + ) + ) + + +def paper_request(question: str) -> bool: + """Recognize requests about papers rather than all physical files. + + Parameters + ---------- + question: str + User's request. + + Returns + ------- + bool + True for paper-oriented wording without explicit bibliography lookup. + + """ + + wording = without_source_filenames(_QUOTED_TERMS.sub("", question)) + return bool(_PAPER_WORDS.search(wording)) and not bibliography_lookup( + question + ) diff --git a/kilin/source_manifest.py b/kilin/source_manifest.py new file mode 100644 index 00000000..dca814e5 --- /dev/null +++ b/kilin/source_manifest.py @@ -0,0 +1,1450 @@ +"""Inspect and edit a project's accepted semantic source organization. + +This module owns root ``source_manifest.json`` independently of managed +imports and derived indexes. New projects establish revision zero inside +creation; existing projects can initialize explicitly. Opening a project +never creates or modifies metadata. Edits are previewed as a batch and +revalidated against the current selected sources under exclusive ownership. +No role or link confers authorization. Accepted discovery rules reconcile +literal bibliography relationships during explicit previews and source +lifecycle operations. + +Key Features +------------ +- Immutable snapshots bound to the canonical project sources directory. +- Transactional role and relation edits, suppressions and orphan resolution. +- Deterministic bibliography discovery under accepted detector identities. +- Revision and exact-content conflict detection with atomic publication. + +Module Structure +---------------- +- Manifest records and snapshots expose saved and active organization. +- ``RoleEdit``, ``RelationEdit`` and ``ResolveSourceEdit`` describe edits. +- ``initialize_source_manifest`` establishes accepted settings. +- ``read_source_manifest`` and ``inspect_source_manifest`` do not write. +- ``preview_source_manifest`` and ``apply_source_manifest`` edit one batch. +- ``refresh_source_manifest`` reconciles an actual source-operation outcome. + +Examples +-------- +>>> import kilin +>>> # project = kilin.open_project("/path/to/project") +>>> # change = kilin.preview_source_manifest(project, ( +>>> # kilin.RoleEdit("paper.pdf", "primary"), +>>> # kilin.RelationEdit("supplement.pdf", "paper.pdf", "attached_to"), +>>> # )) +>>> # result = kilin.apply_source_manifest(project, change) + +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from contextlib import contextmanager +from dataclasses import dataclass, replace +from hashlib import sha256 +import json +import os +from pathlib import Path +import stat +from typing import Iterator, Literal, TypeAlias +import warnings + +from kilin._source_discovery import ( + DiscoveryDiagnostic, SourceDiscovery, detector_versions, + reconcile_discovery, +) +from kilin._source_manifest import ( + SOURCE_MANIFEST_FILE, SOURCE_ORGANIZATION_FORMAT, AcceptedOrganization, + OrganizationIdentity, RelationKey, SourceManifest, SourceRelation, + SourceRole, SourceRoot, UnresolvedSource, _MAX_BYTES, _MAX_FILES, + _MAX_LINKS, active_relations, active_roles, canonical_path, + check_aliases, manifest_data, parse_manifest, relation_key, +) +from kilin.atomic_writes import atomic_create_text, atomic_write_text +from kilin.conversation_ownership import ( + ConversationFileLock, ConversationLockedError, +) +from kilin.project import QAProject, _read_project +from kilin.project_layout import ( + source_scan_exclusions, validate_project_sources, +) +from kilin.project_type import project_type, project_type_catalog +from kilin.repository import scan_repository +from kilin.source_organization import SourceOrganization, _identifier +from kilin.trace_logging import TraceSink + +__all__ = [ + "SOURCE_MANIFEST_FILE", "SOURCE_ORGANIZATION_FORMAT", + "SourceRoot", "OrganizationIdentity", "AcceptedOrganization", + "SourceRole", "RelationKey", "SourceRelation", "UnresolvedSource", + "SourceManifest", "SourceManifestSnapshot", "SourceManifestInspection", + "SourceManifestPreview", "SourceManifestResult", "SourceManifestConflict", + "RoleEdit", "RelationEdit", "ResolveSourceEdit", "SourceManifestEdit", + "DiscoveryDiagnostic", "SourceDiscovery", + "initialize_source_manifest", "read_source_manifest", + "inspect_source_manifest", "preview_source_manifest", + "apply_source_manifest", "refresh_source_manifest", + "SourceLifecycleResult", +] + +_EVENT = "source_organization.committed" +_LIFECYCLE_EVENT = "source_organization.reconciled" + + +class SourceManifestConflict(RuntimeError): + """A stale preview, competing writer, or changed source binding.""" + + +@dataclass(frozen=True, slots=True) +class SourceManifestSnapshot: + """Exact saved semantic state and its on-disk content digest. + + Attributes + ---------- + manifest: SourceManifest + Structurally parsed saved state, including inactive records. + sha256: str + Digest of the original bytes, not a reserialization. + + """ + + manifest: SourceManifest + sha256: str + + +@dataclass(frozen=True, slots=True) +class SourceManifestInspection: + """Read-only view of saved organization and current selected sources. + + Attributes + ---------- + snapshot: SourceManifestSnapshot + Saved state and exact-content identity. + source_root: SourceRoot + Validated canonical source-root binding. + selected: tuple[str, ...] + Authoritative scanner and managed-import selection. + active_files: tuple[SourceRole, ...] + Available accepted assignments, excluding unresolved paths. + active_relations: tuple[SourceRelation, ...] + Available accepted links. + pending: tuple[str, ...] + Selected paths with no active role. + inactive_files: tuple[SourceRole, ...] + Retained records not active in the current selection. + inactive_relations: tuple[SourceRelation, ...] + Links not active in the current selection. + retained_versions: tuple[str, ...] + Selected historical copies, distinct from current source identities. + + """ + + snapshot: SourceManifestSnapshot + source_root: SourceRoot + selected: tuple[str, ...] + active_files: tuple[SourceRole, ...] + active_relations: tuple[SourceRelation, ...] + pending: tuple[str, ...] + inactive_files: tuple[SourceRole, ...] + inactive_relations: tuple[SourceRelation, ...] + retained_versions: tuple[str, ...] = () + + @property + def binding_matches(self) -> bool: + """Return whether the accepted root is still the configured root.""" + return self.source_root == self.snapshot.manifest.source_root + + @property + def current_files(self) -> tuple[SourceRole, ...]: + """Return active current assignments, excluding retained versions.""" + retained = set(self.retained_versions) + return tuple(item for item in self.active_files + if item.path not in retained) + + @property + def pending_roles(self) -> tuple[str, ...]: + """Return current paths needing an explicit role or resolution.""" + paths = set(self.pending) | { + item.path for item in self.current_files + if item.role == "unassigned" + } + return tuple(sorted(paths - set(self.retained_versions))) + + +@dataclass(frozen=True, slots=True) +class RoleEdit: + """Assign a declared role or clear to the accepted default. + + Attributes + ---------- + path: str + Selected source-relative path. + role: str | None + Explicit role, or None to reset to the accepted default. + + """ + + path: str + role: str | None = None + + +@dataclass(frozen=True, slots=True) +class RelationEdit: + """Link, unlink, or explicitly restore automatic eligibility of an edge. + + Attributes + ---------- + source, target: str + Source-relative endpoints, dependent first for a dependency. + relation: str + Relation identifier. + action: str + ``link``, ``unlink`` or ``restore_suppression``. + + """ + + source: str + target: str + relation: str + action: Literal["link", "unlink", "restore_suppression"] = "link" + + +@dataclass(frozen=True, slots=True) +class ResolveSourceEdit: + """Resolve a selected path with a retained inactive assignment. + + Attributes + ---------- + path: str + Selected source-relative path. + restore: bool + True explicitly restores the old role and eligible links. False + resets to the accepted default and removes links incident to the + old assignment, retaining suppressions. + + """ + + path: str + restore: bool = False + + +SourceManifestEdit: TypeAlias = RoleEdit | RelationEdit | ResolveSourceEdit + + +@dataclass(frozen=True, slots=True) +class SourceManifestPreview: + """Proposed state transition bound to one saved revision and inventory. + + Attributes + ---------- + project_root: pathlib.Path + Canonical workspace where the preview was created. + before: SourceManifestInspection + Exact saved state and selected sources used for the preview. + after: SourceManifest + Proposed semantic state; revision advances only for a change. + edits: tuple[SourceManifestEdit, ...] + Ordered batch of explicit operations. + organization: SourceOrganization | None + Optional explicit project-local declaration replacement. + adopt_type_defaults: bool + Explicitly adopt the current installed type's declarations. + role_mapping, relation_mapping: tuple[tuple[str, str], ...] + Explicit resolutions for previously used vocabulary identifiers. + adopt_detector_versions: bool + Explicitly accept installed detector implementations. + discovery: SourceDiscovery + Automatic deltas, proposals and diagnostics of this preview. + + """ + + project_root: Path + before: SourceManifestInspection + after: SourceManifest + edits: tuple[SourceManifestEdit, ...] + organization: SourceOrganization | None + adopt_type_defaults: bool + role_mapping: tuple[tuple[str, str], ...] + relation_mapping: tuple[tuple[str, str], ...] + adopt_detector_versions: bool = False + discovery: SourceDiscovery = SourceDiscovery() + + @property + def changed(self) -> bool: + """Return whether applying this preview would advance revision.""" + return self.after != self.before.snapshot.manifest + + +@dataclass(frozen=True, slots=True) +class SourceManifestResult: + """Durable result, including a post-commit notification failure if any. + + Attributes + ---------- + snapshot: SourceManifestSnapshot + Committed or unchanged semantic state and exact-content identity. + changed: bool + Whether this operation published new semantic metadata. + trace_error: str | None + Diagnostic if supplied tracing could not report the committed state. + None when no trace was requested or the notification succeeded. + discovery: SourceDiscovery + Applied automatic deltas and nonpersistent proposals/diagnostics. + + """ + + snapshot: SourceManifestSnapshot + changed: bool + trace_error: str | None = None + discovery: SourceDiscovery = SourceDiscovery() + + +@dataclass(frozen=True, slots=True) +class SourceLifecycleResult: + """Report the semantic outcome independently of physical source changes. + + Attributes + ---------- + inspection: SourceManifestInspection | None + Current resolved organization, when its canonical source binding can + be validated. Unsupported bindings are rejected without rebinding. + added_files: tuple[SourceRole, ...] + Newly persisted default assignments in this batch. + discovery: SourceDiscovery + Applied automatic changes, proposals and diagnostics. + changed: bool + Whether the semantic manifest was initialized or advanced. + error: str | None + Actionable reconciliation failure, without implying physical rollback. + trace_error: str | None + Post-commit trace failure, if any. + + """ + + inspection: SourceManifestInspection | None = None + added_files: tuple[SourceRole, ...] = () + discovery: SourceDiscovery = SourceDiscovery() + changed: bool = False + error: str | None = None + trace_error: str | None = None + + + +def _unique_keys(pairs: list[tuple[str, object]]) -> dict: + """Reject duplicate JSON keys, including inside nested records. + + Parameters + ---------- + pairs: list[tuple[str, object]] + Ordered object members from the JSON decoder. + + Returns + ------- + dict + Object without duplicate keys. + + """ + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate source-manifest key {key!r}.") + result[key] = value + return result + + +def _regular_entry(path: Path, *, missing: bool = False) -> None: + """Reject linked, nonregular or multiply linked metadata entries. + + Parameters + ---------- + path: pathlib.Path + Root metadata or stable lock sidecar. + missing: bool, optional + Permit an absent entry, but never a dangling link. + + """ + try: + metadata = path.lstat() + except FileNotFoundError: + if missing: + return + raise + if (not stat.S_ISREG(metadata.st_mode) or path.is_junction() + or metadata.st_nlink != 1): + raise ValueError(f"Unsafe source-manifest metadata entry: {path}.") + + +def _read_manifest_file(path: Path) -> SourceManifestSnapshot: + """Read bounded metadata without consulting the current runtime catalog. + + Parameters + ---------- + path: pathlib.Path + Root semantic manifest, not a derived index cache. + + Returns + ------- + SourceManifestSnapshot + Validated saved state and original-byte digest. + + """ + try: + _regular_entry(path) + except FileNotFoundError as error: + raise FileNotFoundError( + f"Missing {SOURCE_MANIFEST_FILE}; initialize explicitly." + ) from error + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) + flags |= getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) + with os.fdopen(os.open(path, flags), "rb") as stream: + metadata = os.fstat(stream.fileno()) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_nlink != 1: + raise ValueError("Unsafe source-manifest metadata file.") + content = stream.read(_MAX_BYTES + 1) + if len(content) > _MAX_BYTES: + raise ValueError("Semantic source manifest exceeds the size limit.") + try: + data = json.loads(content.decode("utf-8"), + object_pairs_hook=_unique_keys) + manifest = parse_manifest(data) + except (ValueError, TypeError, RecursionError) as error: + raise ValueError(f"Invalid source manifest {path}: {error}") from error + return SourceManifestSnapshot(manifest, sha256(content).hexdigest()) + + +def _serialize(manifest: SourceManifest) -> str: + """Validate and serialize canonical semantic state before publication. + + Parameters + ---------- + manifest: SourceManifest + Candidate state. + + Returns + ------- + str + Canonical UTF-8 JSON text ending in a newline. + + """ + data = manifest_data(manifest) + parse_manifest(data) + text = json.dumps(data, ensure_ascii=False, sort_keys=True, indent=2, + allow_nan=False) + "\n" + if len(text.encode("utf-8")) > _MAX_BYTES: + raise ValueError("Semantic source manifest exceeds the size limit.") + return text + + +def _current_project(project: QAProject) -> QAProject: + """Refresh saved profile identity without constructing a model or catalog. + + Parameters + ---------- + project: QAProject + Opened project; its cached source path may be stale. + + Returns + ------- + QAProject + Current saved project profile and resolved directories. + + """ + from kilin.workspace import _source_records + + current = _read_project(project.root, require_registered_type=False) + _source_records(current.root, allow_mirror=True) + return current + + +def _binding(project: QAProject) -> SourceRoot: + """Bind file identities after validating the canonical source directory. + + Parameters + ---------- + project: QAProject + Current or provisionally owned project. + + Returns + ------- + SourceRoot + Project-relative identity that survives moving the whole workspace. + + """ + validate_project_sources(project.root, project.source) + return SourceRoot("project", "sources") + + +def _selected(project: QAProject) -> tuple[str, ...]: + """Resolve the complete selected inventory without reading source bytes. + + Parameters + ---------- + project: QAProject + Current or provisionally owned project. + + Returns + ------- + tuple[str, ...] + Safe selected paths, including recorded explicit imports and versions. + + """ + from kilin.workspace import include_explicit_imports + + report = scan_repository( + project.source, extensions=project.profile.extensions, + max_file_bytes=project.profile.max_file_bytes, + exclude_paths=source_scan_exclusions(project.root, project.source), + ) + if report["complete"] is not True: + raise ValueError("Incomplete source scan; cannot reconcile metadata.") + report = include_explicit_imports(project, report) + names = report["selected_files"] + if len(names) > _MAX_FILES: + raise ValueError( + "Selected source inventory exceeds the manifest limit." + ) + paths = tuple(sorted(canonical_path(name) for name in names)) + check_aliases(paths) + if len(paths) != len(set(paths)): + raise ValueError("Duplicate selected source paths.") + root = project.source.resolve(strict=True) + for name in paths: + current = root + for part in name.split("/"): + current = current / part + if current.is_symlink() or current.is_junction(): + raise ValueError(f"Linked selected source: {name!r}.") + if (not current.is_file() + or not current.resolve(strict=True).is_relative_to(root)): + raise ValueError(f"Unsafe or missing selected source: {name!r}.") + return paths + + +def _retained_versions( + project: QAProject, selected: tuple[str, ...], +) -> tuple[str, ...]: + """Identify selected historical snapshots from managed provenance. + + Parameters + ---------- + project: QAProject + Current or provisional project. + selected: tuple[str, ...] + Complete authorized selection, including historical copies. + + Returns + ------- + tuple[str, ...] + Source-relative paths of selected retained versions. + + """ + from kilin.workspace import list_source_versions + + names = {Path(item["version"]).relative_to("sources").as_posix() + for item in list_source_versions(project)} + return tuple(sorted(names.intersection(selected))) + + + +def _accepted(project: QAProject) -> AcceptedOrganization: + """Capture today's installed type only during explicit acceptance. + + Parameters + ---------- + project: QAProject + Current or provisionally owned project. + + Returns + ------- + AcceptedOrganization + Declarations, exact origin and detector implementation identities. + + """ + type_id = project.profile.type_id + info = project_type_catalog().get(type_id) + if (info is None or not info.available or info.version is None + or info.schema_version is None or info.sha256 is None): + raise ValueError( + f"Missing source-organization identity for {type_id}." + ) + declaration = project_type(type_id).source_organization + identity = OrganizationIdentity( + type_id, info.version, info.schema_version, info.origin, info.sha256, + ) + return AcceptedOrganization( + identity, declaration, detector_versions(declaration), + ) + + +def _initial_manifest( + project: QAProject, *, revision: int, +) -> tuple[SourceManifest, SourceDiscovery, tuple[str, ...]]: + """Materialize accepted defaults for a complete initial inventory. + + Parameters + ---------- + project: QAProject + Current or provisionally owned project. + revision: int + Zero inside new creation; one for explicit existing initialization. + + Returns + ------- + tuple[SourceManifest, SourceDiscovery, tuple[str, ...]] + Initial semantic record, discovery outcome and selected paths. + + """ + accepted = _accepted(project) + selected = _selected(project) + files = tuple(SourceRole(path, accepted.declaration.default_role, + "default") for path in selected) + manifest = SourceManifest(revision, _binding(project), accepted, files) + manifest, discovery = reconcile_discovery( + project.root, project.source, project.profile.max_file_bytes, + manifest, selected, retained_versions=_retained_versions( + project, selected), + ) + return manifest, discovery, selected + + +def _initialize_during_creation( + project: QAProject, +) -> SourceLifecycleResult: + """Publish initial metadata while the exclusive creation claim is held. + + Parameters + ---------- + project: QAProject + Provisional project whose final source copies are already present. + + Returns + ------- + SourceLifecycleResult + Initial assignments and discovery, publishable after creation. + + """ + manifest, discovery, selected = _initial_manifest(project, revision=0) + text = _serialize(manifest) + atomic_create_text(project.root / SOURCE_MANIFEST_FILE, text) + snapshot = SourceManifestSnapshot( + manifest, sha256(text.encode("utf-8")).hexdigest(), + ) + return SourceLifecycleResult( + _inspection(project, snapshot, selected), manifest.files, + discovery, changed=True, + ) + + +@contextmanager +def _write_owner(path: Path) -> Iterator[None]: + """Reuse the stable existing cross-process file ownership protocol. + + Parameters + ---------- + path: pathlib.Path + Canonical root semantic manifest path. + + Yields + ------ + None + Exclusive cooperating writer ownership. + + """ + _regular_entry(path, missing=True) + owner = ConversationFileLock(path) + _regular_entry(owner.lock_path, missing=True) + try: + with owner: + _regular_entry(path, missing=True) + _regular_entry(owner.lock_path) + yield + except ConversationLockedError as error: + raise SourceManifestConflict( + "Another writer owns the semantic source manifest." + ) from error + + +def _notify( + snapshot: SourceManifestSnapshot, before: SourceManifestSnapshot | None, + trace: TraceSink | None, + discovery: SourceDiscovery = SourceDiscovery(), *, + event_type: str = _EVENT, +) -> SourceManifestResult: + """Report committed state without treating a trace failure as rollback. + + Parameters + ---------- + snapshot: SourceManifestSnapshot + Committed semantic state. + before: SourceManifestSnapshot | None + Previous state, or None for explicit initialization. + trace: TraceSink | None + Optional caller-owned trace logger. + discovery: SourceDiscovery, optional + Automatic deltas and proposals for the completed preview. + event_type: str, optional + Distinguish explicit editing from lifecycle reconciliation. + + Returns + ------- + SourceManifestResult + Durable result with a diagnostic for notification failure. + + """ + error = None + if trace is not None: + try: + trace.emit(event_type, component="source_organization", data={ + "previous_revision": (before.manifest.revision + if before is not None else None), + "previous_sha256": before.sha256 if before else None, + "revision": snapshot.manifest.revision, + "sha256": snapshot.sha256, + "source_organization": manifest_data(snapshot.manifest), + }) + if getattr(trace, "_closed", False) is True or getattr( + trace, "_failed", False + ) is True: + error = "Trace logger is closed or incomplete." + except Exception as failure: + error = f"{type(failure).__name__}: {failure}" + return SourceManifestResult(snapshot, True, error, discovery) + + +def initialize_source_manifest( + project: QAProject, *, trace: TraceSink | None = None, +) -> SourceManifestResult: + """Explicitly initialize missing semantic metadata for an open project. + + Parameters + ---------- + project: QAProject + Existing workspace. Its saved profile is refreshed before selection. + trace: TraceSink | None, optional + Caller-owned trace logger for the committed semantic change. + + Returns + ------- + SourceManifestResult + Initialized revision one, or the unchanged valid existing state. + + Raises + ------ + ValueError + Existing metadata is malformed or unsupported; never replace it. + SourceManifestConflict + A competing writer owns the metadata. + + """ + current = _current_project(project) + path = current.root / SOURCE_MANIFEST_FILE + with _write_owner(path): + if path.exists(): + return SourceManifestResult(_read_manifest_file(path), False) + current = _current_project(project) + manifest, discovery, _ = _initial_manifest(current, revision=1) + text = _serialize(manifest) + atomic_create_text(path, text) + snapshot = SourceManifestSnapshot( + parse_manifest(manifest_data(manifest)), + sha256(text.encode("utf-8")).hexdigest(), + ) + return _notify(snapshot, None, trace, discovery) + + +def read_source_manifest(project: QAProject) -> SourceManifestSnapshot: + """Read accepted organization without scanning, adopting or writing. + + Parameters + ---------- + project: QAProject + Project containing the authoritative semantic manifest. + + Returns + ------- + SourceManifestSnapshot + Saved record and original-byte digest. + + """ + return _read_manifest_file(project.root / SOURCE_MANIFEST_FILE) + + +def _inspect(project: QAProject) -> SourceManifestInspection: + """Combine structural state and current inventory without writing. + + Parameters + ---------- + project: QAProject + Current saved profile and resolved directories. + + Returns + ------- + SourceManifestInspection + Read-only resolved organization. + + """ + return _inspection(project, read_source_manifest(project), + _selected(project)) + + +def _inspection( + project: QAProject, snapshot: SourceManifestSnapshot, + selected: tuple[str, ...], *, + retained_versions: tuple[str, ...] | None = None, + source_root: SourceRoot | None = None, +) -> SourceManifestInspection: + """Resolve one snapshot against an already validated selection. + + Parameters + ---------- + project: QAProject + Current or provisional project. + snapshot: SourceManifestSnapshot + Exact saved or newly committed semantic metadata. + selected: tuple[str, ...] + Authoritative selected paths. + retained_versions: tuple[str, ...] | None, optional + Previously inspected historical copies; None reads provenance. + source_root: SourceRoot | None, optional + Previously inspected binding; None resolves the configured source. + + Returns + ------- + SourceManifestInspection + Active, pending, inactive and historical source identities. + + """ + manifest = snapshot.manifest + binding = _binding(project) if source_root is None else source_root + available = set(selected) if binding == manifest.source_root else set() + roles = active_roles(manifest, available) + relations = active_relations(manifest, available) + active_file_set, active_relation_set = set(roles), set(relations) + return SourceManifestInspection( + snapshot, binding, selected, roles, relations, + tuple(sorted(set(selected) - {item.path for item in roles})), + tuple(item for item in manifest.files if item not in active_file_set), + tuple(item for item in manifest.relations + if item not in active_relation_set), + (_retained_versions(project, selected) if retained_versions is None + else retained_versions), + ) + + +def inspect_source_manifest(project: QAProject) -> SourceManifestInspection: + """Inspect live availability under the saved vocabulary and binding. + + Parameters + ---------- + project: QAProject + Opened workspace; refresh its saved profile first. + + Returns + ------- + SourceManifestInspection + Active, pending and inactive records without reconciliation writes. + + """ + return _inspect(_current_project(project)) + + +def _mapping(values: Mapping[str, str] | None) -> tuple[tuple[str, str], ...]: + """Freeze and validate explicit vocabulary mappings. + + Parameters + ---------- + values: Mapping[str, str] | None + Old-to-new role or relation identifiers. + + Returns + ------- + tuple[tuple[str, str], ...] + Immutable sorted mappings. + + """ + if values is None: + return () + if not isinstance(values, Mapping): + raise ValueError("Vocabulary mappings must be mappings.") + return tuple(sorted((_identifier(a, "Old identifier"), + _identifier(b, "New identifier")) + for a, b in values.items())) + + +def _change_settings( + manifest: SourceManifest, accepted: AcceptedOrganization, + role_mapping: tuple[tuple[str, str], ...], + relation_mapping: tuple[tuple[str, str], ...], +) -> SourceManifest: + """Adopt explicit settings without silently reinterpreting used records. + + Parameters + ---------- + manifest: SourceManifest + Existing accepted state, including inactive records. + accepted: AcceptedOrganization + Proposed vocabulary and provenance. + role_mapping: tuple[tuple[str, str], ...] + Explicit mappings for incompatible used roles. + relation_mapping: tuple[tuple[str, str], ...] + Explicit mappings for incompatible used relations or behaviors. + + Returns + ------- + SourceManifest + Proposed settings with all old assignments and links accounted for. + + """ + old = manifest.organization.declaration + new = accepted.declaration + roles, kinds = dict(role_mapping), dict(relation_mapping) + old_kinds = {r.id: r.behavior for r in old.relation_types} + new_kinds = {r.id: r.behavior for r in new.relation_types} + used_roles = {item.role for item in manifest.files} + if not set(roles) <= set(old.roles) | used_roles: + raise ValueError("Role mapping has unknown source roles.") + if not set(roles.values()) <= set(new.roles): + raise ValueError("Role mapping has undeclared destination roles.") + if not set(kinds.values()) <= set(new_kinds): + raise ValueError("Relation mapping has undeclared destinations.") + files = [] + for item in manifest.files: + role = roles.get(item.role, item.role) + if role not in new.roles or ( + item.role not in old.roles and item.role not in roles + ): + raise ValueError(f"Map or resolve used role {item.role!r} first.") + files.append(replace(item, role=role)) + keys = {r.key for r in manifest.relations} | set( + manifest.suppressed_automatic + ) + if not set(kinds) <= set(old_kinds) | {key.type for key in keys}: + raise ValueError("Relation mapping has unknown source relations.") + remapped = {} + for key in keys: + kind = kinds.get(key.type, key.type) + if (kind not in new_kinds or (key.type not in kinds + and old_kinds.get(key.type) != new_kinds.get(kind))): + raise ValueError(f"Map or resolve used relation {key.type!r}.") + remapped[key] = relation_key( + key.source, key.target, kind, new, normalize=True, + ) + # Changing a rule identity or relation still requires explicit + # resolution of its edges. Version-only adoption previews new deltas. + old_rules = {r.id: r for r in old.automatic_rules} + new_rules = {r.id: r for r in new.automatic_rules} + for item in manifest.relations: + if item.origin != "rule": + continue + rule = old_rules.get(item.rule) + if (rule is None or rule != new_rules.get(item.rule) + or remapped[item.key] != item.key): + raise ValueError("Resolve existing automatic edges before " + "changing their detector or rule.") + return replace( + manifest, organization=accepted, files=tuple(files), + relations=tuple(replace(r, key=remapped[r.key]) + for r in manifest.relations), + suppressed_automatic=tuple(remapped[k] + for k in manifest.suppressed_automatic), + ) + + +def _propose( + manifest: SourceManifest, selected: tuple[str, ...], binding: SourceRoot, + edits: tuple[SourceManifestEdit, ...], +) -> SourceManifest: + """Reconcile selection and apply explicit edits as one proposed state. + + Parameters + ---------- + manifest: SourceManifest + Saved state with any explicitly accepted vocabulary changes. + selected: tuple[str, ...] + Complete current source selection. + binding: SourceRoot + Current configured root identity. + edits: tuple[SourceManifestEdit, ...] + Ordered explicit edits; validation of graph cycles occurs at the end. + + Returns + ------- + SourceManifest + Candidate state without an incremented revision. + + """ + declaration = manifest.organization.declaration + files = {r.path: r for r in manifest.files} + links = {r.key: r for r in manifest.relations} + suppressed = set(manifest.suppressed_automatic) + unresolved = {r.path: r for r in manifest.unresolved} + available = set(selected) + if binding != manifest.source_root: + raise SourceManifestConflict( + "Source root does not match the project sources directory." + ) + for path in files.keys() - available: + unresolved.setdefault(path, UnresolvedSource(path, "removed")) + # A structurally inspectable orphan edge must not become active merely + # because its formerly unassigned endpoint appears in a later scan. + orphan_endpoints = { + path for key in (*links, *suppressed) + for path in (key.source, key.target) if path not in files + } + for path in selected: + files.setdefault(path, SourceRole(path, declaration.default_role, + "default")) + if path in orphan_endpoints: + unresolved[path] = UnresolvedSource(path, "missing_assignment") + check_aliases((*files, *available)) + if len(edits) > _MAX_LINKS: + raise ValueError("Too many source-manifest edits in one batch.") + for edit in edits: + if type(edit) in (RoleEdit, ResolveSourceEdit): + path = canonical_path(edit.path) + if path not in available: + raise ValueError(f"Source is not selected: {path!r}.") + if isinstance(edit, ResolveSourceEdit): + if type(edit.restore) is not bool: + raise ValueError("Restore flag must be a boolean.") + if path not in unresolved: + raise ValueError(f"Source is not unresolved: {path!r}.") + if edit.restore: + if files[path].role not in declaration.roles: + raise ValueError("Map or reset the old role first.") + else: + files[path] = SourceRole(path, declaration.default_role, + "default") + links = {k: r for k, r in links.items() + if path not in (k.source, k.target)} + del unresolved[path] + continue + if path in unresolved: + raise ValueError(f"Resolve retained source {path!r} first.") + role = declaration.default_role if edit.role is None else edit.role + if role not in declaration.roles: + raise ValueError(f"Undeclared role {role!r}.") + origin = "default" if edit.role is None else "user" + files[path] = SourceRole(path, role, origin) + elif type(edit) is RelationEdit: + key = relation_key(edit.source, edit.target, edit.relation, + declaration, normalize=True) + if edit.action == "link": + if key.type not in declaration.relation_ids: + raise ValueError(f"Undeclared relation {key.type!r}.") + if any(p not in available or p in unresolved + or files[p].role not in declaration.roles + for p in (key.source, key.target)): + raise ValueError("Link endpoints must be active sources.") + links[key] = SourceRelation(key, "user") + elif edit.action == "unlink": + if key in links: + del links[key] + suppressed.add(key) + elif edit.action == "restore_suppression": + suppressed.discard(key) + else: + raise ValueError(f"Unknown relation edit {edit.action!r}.") + else: + raise ValueError("Unknown source-manifest edit record.") + return replace( + manifest, files=tuple(files.values()), + relations=tuple(links.values()), + suppressed_automatic=tuple(suppressed), + unresolved=tuple(unresolved.values()), + ) + + +def _preview( + current: QAProject, edits: tuple[SourceManifestEdit, ...], *, + organization: SourceOrganization | None, adopt_type_defaults: bool, + role_mapping: tuple[tuple[str, str], ...], + relation_mapping: tuple[tuple[str, str], ...], + adopt_detector_versions: bool = False, + before: SourceManifestInspection | None = None, +) -> SourceManifestPreview: + """Build one deterministic proposal against a freshly resolved project. + + Parameters + ---------- + current: QAProject + Current project profile and resolved directories. + edits: tuple[SourceManifestEdit, ...] + Explicit semantic edits. + organization: SourceOrganization | None + Optional project-local replacement declaration. + adopt_type_defaults: bool + Whether to explicitly accept the current installed type defaults. + role_mapping: tuple[tuple[str, str], ...] + Explicit resolutions for used roles. + relation_mapping: tuple[tuple[str, str], ...] + Explicit resolutions for used relations. + adopt_detector_versions: bool, optional + Explicitly accept installed detector identities. + before: SourceManifestInspection | None, optional + Already inspected inventory under the held writer lease. + + Returns + ------- + SourceManifestPreview + Reproducible proposal, not a write. + + """ + if any(type(flag) is not bool for flag in ( + adopt_type_defaults, adopt_detector_versions, + )): + raise ValueError("Adoption flags must be booleans.") + if organization is not None and ( + adopt_type_defaults or type(organization) is not SourceOrganization + ): + raise ValueError("Specify either local settings or type adoption.") + if (role_mapping or relation_mapping) and not ( + organization is not None or adopt_type_defaults + ): + raise ValueError("Mappings require an explicit settings change.") + if before is None: + before = _inspect(current) + saved = before.snapshot.manifest + manifest = saved + if adopt_type_defaults or organization is not None: + accepted = _accepted(current) if adopt_type_defaults else replace( + saved.organization, declaration=organization, + detector_versions=tuple( + (name, dict(saved.organization.detector_versions).get( + name, version)) + for name, version in detector_versions(organization) + ), + ) + manifest = _change_settings(manifest, accepted, role_mapping, + relation_mapping) + # A mapping that merges edge identities must not silently lose a + # record when the batch constructs its dictionaries. + keys = [r.key for r in manifest.relations] + if (len(keys) != len(set(keys)) + or len(manifest.suppressed_automatic) + != len(set(manifest.suppressed_automatic))): + raise ValueError("Relation mapping merges stored identities.") + if adopt_detector_versions: + accepted = manifest.organization + manifest = replace(manifest, organization=replace( + accepted, detector_versions=detector_versions( + accepted.declaration), + )) + after = _propose(manifest, before.selected, before.source_root, edits) + after, discovery = reconcile_discovery( + current.root, current.source, current.profile.max_file_bytes, + after, before.selected, retained_versions=before.retained_versions, + ) + # An implementation upgrade cannot certify retained active automatic + # links whose referring document could not be inspected. + old_versions = dict(saved.organization.detector_versions) + changed_detectors = { + name for name, version in after.organization.detector_versions + if name in old_versions and old_versions[name] != version + } + changed_rules = {r.id for r in after.organization.declaration + .automatic_rules if r.detector in changed_detectors} + unreadable = {(d.rule, d.target) for d in discovery.diagnostics + if d.reason == "source_unavailable"} + if any(item.origin == "rule" and item.rule in changed_rules + and (item.rule, item.key.target) in unreadable + for item in active_relations(after, set(before.selected))): + raise ValueError("Cannot adopt detector with unreadable active links.") + if after != saved: + after = replace(after, revision=saved.revision + 1) + _serialize(after) + return SourceManifestPreview( + current.root, before, after, edits, organization, adopt_type_defaults, + role_mapping, relation_mapping, adopt_detector_versions, + discovery, + ) + + +def preview_source_manifest( + project: QAProject, edits: Sequence[SourceManifestEdit] = (), *, + organization: SourceOrganization | None = None, + adopt_type_defaults: bool = False, + role_mapping: Mapping[str, str] | None = None, + relation_mapping: Mapping[str, str] | None = None, + adopt_detector_versions: bool = False, +) -> SourceManifestPreview: + """Preview an atomic batch, reconciliation or explicit settings change. + + Parameters + ---------- + project: QAProject + Opened workspace. The saved profile is refreshed before scanning. + edits: Sequence[SourceManifestEdit], optional + Explicit role, link, unlink, suppression or orphan resolution edits. + An empty sequence previews inventory and discovery reconciliation. + organization: SourceOrganization | None, optional + Explicit project-local vocabulary and discovery settings. + adopt_type_defaults: bool, optional + Adopt current installed type defaults, identity and detectors. + role_mapping: Mapping[str, str] | None, optional + Explicit old-to-new roles when changing the accepted vocabulary. + relation_mapping: Mapping[str, str] | None, optional + Explicit old-to-new relation IDs. Include an identity mapping to + explicitly accept a changed behavior. + adopt_detector_versions: bool, optional + Accept installed detector versions without changing the saved type + declarations. Automatic edge changes are included in the preview. + + Returns + ------- + SourceManifestPreview + Candidate state and exact saved-state preconditions. No writes occur. + + """ + return _preview( + _current_project(project), tuple(edits), organization=organization, + adopt_type_defaults=adopt_type_defaults, + adopt_detector_versions=adopt_detector_versions, + role_mapping=_mapping(role_mapping), + relation_mapping=_mapping(relation_mapping), + ) + + +def apply_source_manifest( + project: QAProject, preview: SourceManifestPreview, *, + trace: TraceSink | None = None, +) -> SourceManifestResult: + """Revalidate a preview under writer ownership and atomically publish it. + + Parameters + ---------- + project: QAProject + Same workspace used for preview. + preview: SourceManifestPreview + Previously inspected proposal; exact revision, bytes, root and + selection must still agree with the live workspace. + trace: TraceSink | None, optional + Caller-owned trace logger. Notification happens after publication. + + Returns + ------- + SourceManifestResult + Committed or unchanged state; a trace failure does not roll it back. + + Raises + ------ + SourceManifestConflict + Another writer owns the file or the preview no longer agrees. + ValueError + Invalid or unsupported metadata, preserved without modification. + + """ + if type(preview) is not SourceManifestPreview: + raise ValueError("Expected a source-manifest preview.") + current = _current_project(project) + if current.root != preview.project_root: + raise SourceManifestConflict("Preview belongs to another workspace.") + path = current.root / SOURCE_MANIFEST_FILE + with _write_owner(path): + before = _read_manifest_file(path) + if before != preview.before.snapshot: + raise SourceManifestConflict( + "Source manifest changed; preview again." + ) + current = _current_project(project) + # Check root and inventory before evaluating commands against a + # changed source selection, so stale proposals report a conflict. + inspected = _inspect(current) + if inspected != preview.before: + raise SourceManifestConflict( + "Source selection changed; preview again." + ) + updated = _preview( + current, preview.edits, organization=preview.organization, + adopt_type_defaults=preview.adopt_type_defaults, + role_mapping=preview.role_mapping, + relation_mapping=preview.relation_mapping, + adopt_detector_versions=preview.adopt_detector_versions, + before=inspected, + ) + if updated != preview: + raise SourceManifestConflict( + "Source preview changed; preview again." + ) + return _commit_preview(path, updated, trace) + + +def _commit_preview( + path: Path, preview: SourceManifestPreview, trace: TraceSink | None, + *, event_type: str = _EVENT, +) -> SourceManifestResult: + """Publish a validated preview under the caller's writer lease. + + Parameters + ---------- + path: pathlib.Path + Canonical manifest path. + preview: SourceManifestPreview + Proposal validated under the current writer lease. + trace: TraceSink | None + Caller-owned notification sink. + event_type: str, optional + Semantic edit or lifecycle reconciliation event. + + Returns + ------- + SourceManifestResult + Durable outcome, including any notification failure. + + """ + before = preview.before.snapshot + if not preview.changed: + return SourceManifestResult(before, False, discovery=preview.discovery) + text = _serialize(preview.after) + # Protect against exact-byte changes made by noncooperating writers. + if _read_manifest_file(path) != before: + raise SourceManifestConflict("Source manifest changed; preview again.") + atomic_write_text(path, text) + snapshot = SourceManifestSnapshot( + preview.after, sha256(text.encode("utf-8")).hexdigest(), + ) + return _notify(snapshot, before, trace, preview.discovery, + event_type=event_type) + + +def refresh_source_manifest( + project: QAProject, *, trace: TraceSink | None = None, +) -> SourceLifecycleResult: + """Reconcile selected sources under the saved organization settings. + + Parameters + ---------- + project: QAProject + Workspace after physical changes, or an explicit source refresh. + trace: TraceSink | None, optional + Caller-owned notification sink. + + Returns + ------- + SourceLifecycleResult + One batch outcome, or an actionable error when reconciliation is + unsafe. Missing metadata requires explicit initialization; source + roots outside ``sources`` are rejected. No defaults are adopted. + + Notes + ----- + This operation never embeds sources, loads a model or edits source bytes. + A failed reconciliation never repairs malformed metadata or implies that + an earlier physical operation was rolled back. + + """ + inspected = None + try: + current = _current_project(project) + path = current.root / SOURCE_MANIFEST_FILE + # Do not create even a lock sidecar for missing semantic metadata. + _regular_entry(path) + with _write_owner(path): + current = _current_project(project) + inspected = _inspect(current) + preview = _preview( + current, (), organization=None, adopt_type_defaults=False, + role_mapping=(), relation_mapping=(), + before=inspected, + ) + # Source operations do not share the semantic writer lease. + # A changed selection or profile must be reconciled afresh. + if preview.changed and _inspect(_current_project(current)) != ( + inspected + ): + raise SourceManifestConflict( + "Source selection changed; refresh again." + ) + result = _commit_preview( + path, preview, trace, event_type=_LIFECYCLE_EVENT, + ) + previous = {item.path for item in + inspected.snapshot.manifest.files} + added = tuple(item for item in result.snapshot.manifest.files + if item.path not in previous) + return SourceLifecycleResult( + _inspection(current, result.snapshot, inspected.selected, + retained_versions=inspected.retained_versions, + source_root=inspected.source_root), + added, result.discovery, result.changed, + trace_error=result.trace_error, + ) + except (OSError, ValueError, SourceManifestConflict) as error: + message = f"{type(error).__name__}: {error}" + if isinstance(error, FileNotFoundError): + message += "; initialize missing source metadata explicitly." + return SourceLifecycleResult(inspection=inspected, error=message) + + +def _report_lifecycle( + result: SourceLifecycleResult, + callback: Callable[[SourceLifecycleResult], None] | None, +) -> None: + """Deliver a committed result after releasing writer ownership. + + Parameters + ---------- + result: SourceLifecycleResult + Outcome, including any semantic or notification failure. + callback: Callable[[SourceLifecycleResult], None] | None + Optional adapter observer. Without an observer, report failures as + warnings instead of silently treating physical success as complete. + + """ + if callback is not None: + try: + callback(result) + except Exception as error: + error.add_note("Source operations already completed; " + "notification failure did not roll them back.") + raise + elif result.error or result.trace_error: + warnings.warn( + "Source organization refresh: " + f"{result.error or result.trace_error}", + RuntimeWarning, stacklevel=3, + ) + + +@contextmanager +def _reconcile_source_operation( + project: QAProject, trace: TraceSink | None = None, + callback: Callable[[SourceLifecycleResult], None] | None = None, +) -> Iterator[None]: + """Reconcile actual files after a possibly partial physical operation. + + Parameters + ---------- + project: QAProject + Project whose source inventory may change. + trace: TraceSink | None, optional + Caller-owned notification sink. + callback: Callable[[SourceLifecycleResult], None] | None, optional + Adapter observer, called after reconciliation and outside ownership. + + Yields + ------ + None + Physical operation, including its provenance updates. + + """ + if callback is not None and not callable(callback): + raise TypeError("on_organization must be callable or None.") + try: + yield + except BaseException as error: + # Neither a semantic nor an observer failure may hide the original + # copying/deletion error or claim that completed copies rolled back. + try: + result = refresh_source_manifest(project, trace=trace) + if result.error or result.trace_error: + error.add_note("Source organization refresh: " + f"{result.error or result.trace_error}") + _report_lifecycle(result, callback) + except BaseException as failure: + error.add_note(f"Source organization refresh failed: {failure!r}") + raise + else: + _report_lifecycle(refresh_source_manifest(project, trace=trace), + callback) diff --git a/kilin/source_organization.py b/kilin/source_organization.py new file mode 100644 index 00000000..6e07abff --- /dev/null +++ b/kilin/source_organization.py @@ -0,0 +1,318 @@ +"""Declare source roles, relationship types and deterministic discovery rules. + +Project types describe a vocabulary, not the role of any actual source file. +The declarations are immutable, contain no executable references, and can be +validated without loading models, tools or project workspaces. The semantic +manifest captures accepted declarations separately from installed project-type +defaults. + +Key Features +------------ +- Generic directed dependencies and symmetric associations in every type. +- Explicit default role and a closed set of supported discovery detectors. +- Strict validation of declarations and references between their records. + +Module Structure +---------------- +Classes: +- ``RelationType``: one named relationship and its graph behavior. +- ``DiscoveryRule``: one named deterministic detector declaration. +- ``SourceOrganization``: immutable vocabulary and discovery defaults. + +Functions: +- ``parse_source_organization``: validate a JSON-compatible declaration. + +Examples +-------- +>>> from kilin.source_organization import parse_source_organization +>>> organization = parse_source_organization({ +... "roles": ["document", "supplementary"], +... "default_role": "document", +... }) +>>> organization.default_role +'document' +>>> organization.relation_ids +('attached_to', 'related_to') + +""" + +from __future__ import annotations + +from dataclasses import dataclass +import re +from typing import Final, Literal, TypeAlias + +__all__ = [ + "RelationBehavior", "DiscoveryMode", "RelationType", "DiscoveryRule", + "SourceOrganization", "DEFAULT_SOURCE_ORGANIZATION", + "DISCOVERY_DETECTORS", "parse_source_organization", +] + +RelationBehavior: TypeAlias = Literal["dependency", "association"] +DiscoveryMode: TypeAlias = Literal["apply", "propose"] +_ID_PATTERN: Final[re.Pattern[str]] = re.compile(r"[a-z][a-z0-9_-]{0,31}") +# This registry declares capabilities, not executable import paths. Detection +# itself belongs to the separate source-discovery service. +DISCOVERY_DETECTORS: Final[tuple[str, ...]] = ("latex_bibliography",) + + +def _identifier(value: object, where: str) -> str: + """Validate an unmodified role, relation or rule identifier. + + Parameters + ---------- + value: object + Candidate identifier. + where: str + Diagnostic location. + + Returns + ------- + str + Valid identifier; whitespace and case are never normalized. + + """ + if not isinstance(value, str) or not _ID_PATTERN.fullmatch(value): + raise ValueError( + f"{where} must match [a-z][a-z0-9_-]{{0,31}}." + ) + return value + + +@dataclass(frozen=True, slots=True) +class RelationType: + """One named relation with a fixed graph behavior. + + Attributes + ---------- + id: str + Relation identifier. + behavior: RelationBehavior + ``dependency`` is directed from dependent to parent; + ``association`` is symmetric and preserves independence. + + """ + + id: str + behavior: RelationBehavior + + def __post_init__(self) -> None: + """Reject invalid identifiers and unsupported graph behaviors.""" + _identifier(self.id, "Relation ID") + if self.behavior not in ("dependency", "association"): + raise ValueError( + f"Relation {self.id!r} behavior must be dependency or " + "association." + ) + + +@dataclass(frozen=True, slots=True) +class DiscoveryRule: + """One declarative rule for a supported deterministic detector. + + Attributes + ---------- + id: str + Unique rule identifier within a vocabulary. + detector: str + Name from ``DISCOVERY_DETECTORS``. + relation: str + Declared relation the detector may propose or apply. + mode: DiscoveryMode + ``apply`` or ``propose``. Omit the rule to disable discovery. + + """ + + id: str + detector: str + relation: str + mode: DiscoveryMode + + def __post_init__(self) -> None: + """Reject unknown detectors, modes and malformed identifiers.""" + _identifier(self.id, "Discovery rule ID") + _identifier(self.relation, f"Rule {self.id!r} relation") + if self.detector not in DISCOVERY_DETECTORS: + raise ValueError( + f"Rule {self.id!r} has unknown detector {self.detector!r}." + ) + if self.mode not in ("apply", "propose"): + raise ValueError( + f"Rule {self.id!r} mode must be apply or propose." + ) + + +_GENERIC_RELATIONS: Final[tuple[RelationType, ...]] = ( + RelationType("attached_to", "dependency"), + RelationType("related_to", "association"), +) + + +@dataclass(frozen=True, slots=True) +class SourceOrganization: + """Immutable source-organization defaults of a project type. + + Attributes + ---------- + roles: tuple[str, ...] + Unique role identifiers, in declaration order. + default_role: str + Declared role for sources without a user assignment. + relation_types: tuple[RelationType, ...] + Generic and project-specific relation declarations. + automatic_rules: tuple[DiscoveryRule, ...] + Deterministic discovery declarations, not executed here. + + """ + + roles: tuple[str, ...] + default_role: str + relation_types: tuple[RelationType, ...] = _GENERIC_RELATIONS + automatic_rules: tuple[DiscoveryRule, ...] = () + + def __post_init__(self) -> None: + """Validate vocabulary consistency and detector compatibility.""" + # Require immutable containers even for direct Python construction. + if type(self.roles) is not tuple or not self.roles: + raise ValueError("roles must be a nonempty tuple of identifiers.") + for role in self.roles: + _identifier(role, "Role ID") + if len(set(self.roles)) != len(self.roles): + raise ValueError("Duplicate role IDs in roles.") + if _identifier(self.default_role, "default_role") not in self.roles: + raise ValueError("default_role must be declared in roles.") + if type(self.relation_types) is not tuple or not all( + type(item) is RelationType for item in self.relation_types + ): + raise ValueError("relation_types must be a tuple of RelationType.") + relations = {item.id: item.behavior for item in self.relation_types} + if len(relations) != len(self.relation_types): + raise ValueError("Duplicate IDs in relation_types.") + for generic in _GENERIC_RELATIONS: + if relations.get(generic.id) != generic.behavior: + raise ValueError( + f"Relation {generic.id!r} must have behavior " + f"{generic.behavior!r}." + ) + if type(self.automatic_rules) is not tuple or not all( + type(item) is DiscoveryRule for item in self.automatic_rules + ): + raise ValueError("automatic_rules must be a tuple of rules.") + rule_ids = set() + detectors = set() + for rule in self.automatic_rules: + if rule.id in rule_ids: + raise ValueError(f"Duplicate discovery rule ID {rule.id!r}.") + if rule.detector in detectors: + raise ValueError( + f"Duplicate discovery detector {rule.detector!r}." + ) + rule_ids.add(rule.id) + detectors.add(rule.detector) + if rule.relation not in relations: + raise ValueError( + f"Rule {rule.id!r} has undeclared relation " + f"{rule.relation!r}." + ) + # LaTeX bibliography discovery finds directed dependencies, + # not symmetric associations. Custom relation IDs are allowed. + if relations[rule.relation] != "dependency": + raise ValueError( + f"Detector {rule.detector!r} requires a dependency " + "relation." + ) + + @property + def relation_ids(self) -> tuple[str, ...]: + """Return all available relation identifiers in declaration order.""" + return tuple(item.id for item in self.relation_types) + + +DEFAULT_SOURCE_ORGANIZATION: Final[SourceOrganization] = SourceOrganization( + ("unassigned",), "unassigned", +) + + +def _object(value: object, fields: tuple[str, ...], where: str) -> dict: + """Check a JSON object and reject keys outside its contract. + + Parameters + ---------- + value: object + JSON-compatible candidate object. + fields: tuple[str, ...] + Allowed field names. + where: str + Diagnostic location. + + Returns + ------- + dict + Checked object; required fields are checked by the caller. + + """ + if not isinstance(value, dict): + raise ValueError(f"{where} must be an object.") + for key in value: + if key not in fields: + raise ValueError(f"{where} has unknown field {key!r}.") + return value + + +def parse_source_organization( + data: object, *, where: str = "source_organization", +) -> SourceOrganization: + """Validate a project type's explicit source-organization declaration. + + Parameters + ---------- + data: object + JSON object with required ``roles`` and ``default_role``. Optional + ``relation_types`` maps IDs to behavior objects; generic relations + are supplied when omitted. Optional ``automatic_rules`` is a list. + where: str, optional + Location used in diagnostics. Defaults to ``source_organization``. + + Returns + ------- + SourceOrganization + Fully validated, immutable records independent of the input. + + Raises + ------ + ValueError + For malformed, duplicate or inconsistent declarations. Duplicate + JSON object keys must be rejected by the JSON reader before parsing. + + """ + try: + raw = _object(data, ( + "roles", "default_role", "relation_types", "automatic_rules", + ), where) + roles = raw.get("roles") + if not isinstance(roles, list): + raise ValueError("roles must be a nonempty list of identifiers.") + relation_types = raw.get("relation_types", {}) + if not isinstance(relation_types, dict): + raise ValueError("relation_types must be an object.") + relations = {item.id: item for item in _GENERIC_RELATIONS} + for name, value in relation_types.items(): + value = _object(value, ("behavior",), f"relation_types.{name}") + relations[name] = RelationType(name, value.get("behavior")) + automatic_rules = raw.get("automatic_rules", []) + if not isinstance(automatic_rules, list): + raise ValueError("automatic_rules must be a list.") + rules = [] + for number, value in enumerate(automatic_rules): + rule = _object(value, ("id", "detector", "relation", "mode"), + f"automatic_rules[{number}]") + rules.append(DiscoveryRule( + rule.get("id"), rule.get("detector"), rule.get("relation"), + rule.get("mode"), + )) + return SourceOrganization( + tuple(roles), raw.get("default_role"), tuple(relations.values()), + tuple(rules), + ) + except ValueError as error: + raise ValueError(f"{where}: {error}") from error diff --git a/kilin/source_views.py b/kilin/source_views.py new file mode 100644 index 00000000..ba6b2589 --- /dev/null +++ b/kilin/source_views.py @@ -0,0 +1,873 @@ +"""Resolve immutable operation views of accepted source organization. + +Physical identities remain distinct from logical anchors. The resolver uses +one inspected manifest and one captured physical generation without reading +source bytes, scanning directories or consulting installed project types. + +Key Features +------------ +- Explicit project, preferred and restricted scopes, including empty ones. +- Separate target, candidate, evidence and lookup membership. +- One-hop groups, shared dependencies and unavailable-member diagnostics. +- Captured policy and generation identity, with verified raw-file reads. + +Module Structure +---------------- +- ``SourceScope`` and ``SourcePolicy``: operation selection declarations. +- ``SourceFileState`` and ``SourceInventory``: captured physical identities. +- ``SourceOperation`` and ``SourceView``: immutable operation resolution. +- ``SourceGroup`` and ``UnavailableMember``: anchor-centered membership. +- ``capture_source_inventory`` and ``resolve_source_view``: pure services. +- ``validate_source_view`` and ``read_source_bytes``: consistency checks. +- ``validate_source_policy``: accepted-vocabulary validation. + +Examples +-------- +>>> from pathlib import Path +>>> from kilin.source_views import SourceScope, SourcePolicy +>>> scope = SourceScope("restricted", (Path("paper.pdf"),)) +>>> policy = SourcePolicy(related_evidence=("supplement_to",)) +>>> scope.mode +'restricted' + +""" + +from __future__ import annotations + +from collections.abc import Collection, Mapping +from dataclasses import dataclass +from hashlib import sha256 +import json +from pathlib import Path +import re +from typing import TYPE_CHECKING, Literal, TypeAlias + +from kilin._source_access import selected_source_file +from kilin._source_manifest import ( + SourceRoot, active_relations, active_roles, canonical_path, check_aliases, + root_binding, +) +from kilin.source_eligibility import document_candidate +from kilin.source_organization import SourceOrganization, _identifier + +if TYPE_CHECKING: + from kilin.source_manifest import SourceManifestInspection + +__all__ = [ + "ScopeMode", "SourcePurpose", "SourceScope", "SourcePolicy", + "SourceFileState", "SourceInventory", "SourceOperation", "SourceView", + "SourceGroup", "UnavailableMember", "SourceViewConflict", + "capture_source_inventory", "resolve_source_view", + "validate_source_view", "validate_source_policy", "read_source_bytes", +] + +ScopeMode: TypeAlias = Literal["project", "preferred", "restricted"] +SourcePurpose: TypeAlias = Literal["document", "lookup", "raw"] + + +class SourceViewConflict(RuntimeError): + """An operation's captured organization or physical identity changed.""" + + +def _paths(values: tuple[Path, ...], where: str) -> None: + """Validate an immutable sequence of distinct portable paths. + + Parameters + ---------- + values: tuple[pathlib.Path, ...] + Source-relative operands or members. + where: str + Diagnostic location. + + """ + if type(values) is not tuple or any( + not isinstance(path, Path) for path in values + ): + raise ValueError(f"{where} requires a tuple of relative paths.") + names = tuple(canonical_path(path.as_posix()) for path in values) + if len(set(names)) != len(names): + raise ValueError(f"Duplicate paths in {where}.") + check_aliases(names) + + +def _ids(values: tuple[str, ...], where: str) -> None: + """Check a unique immutable sequence of policy identifiers. + + Parameters + ---------- + values: tuple[str, ...] + Role or relation identifiers. + where: str + Diagnostic location. + + """ + if type(values) is not tuple: + raise ValueError(f"{where} requires a tuple of identifiers.") + for value in values: + _identifier(value, where) + if len(set(values)) != len(values): + raise ValueError(f"Duplicate identifiers in {where}.") + + +def _digest(value: str, where: str) -> None: + """Require an exact lowercase SHA-256 identity. + + Parameters + ---------- + value: str + Candidate hexadecimal digest. + where: str + Diagnostic location. + + """ + if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value): + raise ValueError(f"{where} requires a SHA-256 digest.") + + +@dataclass(frozen=True, slots=True) +class SourceScope: + """Explicit operation scope, separate from comparison and grouping. + + Attributes + ---------- + mode: ScopeMode + Project-wide, preferred anchors, or restricted anchors. + paths: tuple[pathlib.Path, ...] + Ordered explicit operands. Restricted empty means no sources; + preferred requires at least one operand; project has none. + + """ + + mode: ScopeMode = "project" + paths: tuple[Path, ...] = () + + def __post_init__(self) -> None: + """Reject contradictory scope declarations and unsafe operands.""" + if self.mode not in ("project", "preferred", "restricted"): + raise ValueError("Unknown source scope mode.") + _paths(self.paths, "Source scope") + if self.mode == "project" and self.paths: + raise ValueError("Project-wide scope cannot have operands.") + if self.mode == "preferred" and not self.paths: + raise ValueError("Preferred scope requires operands.") + + +@dataclass(frozen=True, slots=True) +class SourcePolicy: + """Declarative operation policy interpreted under accepted vocabulary. + + Attributes + ---------- + purpose: SourcePurpose + Document discovery/support, explicit lookup, or raw-file access. + Lookup and raw purposes permit selected physical bibliography, + dependent and historical paths without classifying them as papers. + target_roles: tuple[str, ...] | None + Eligible anchor roles, unrestricted when None. An empty tuple + permits no roles. Explicit document targets must be independent. + candidate_roles: tuple[str, ...] | None + Role filter for independent document candidates; None inherits the + target role filter. Explicit filters may differ from target roles. + evidence_roles: tuple[str, ...] | None + Role filter for related evidence members, not anchor selection. + lookup_roles: tuple[str, ...] | None + Role filter for related lookup members, not anchor selection. + related_evidence: tuple[str, ...] + Relation types permitted for one-hop supporting evidence. + related_lookup: tuple[str, ...] + Relation types permitted for one-hop lookup. + grouped: bool + Opt into logical-group quotas/ranking when supported by the host. + Relationship expansion is independent of this setting. + + """ + + purpose: SourcePurpose = "document" + target_roles: tuple[str, ...] | None = None + candidate_roles: tuple[str, ...] | None = None + evidence_roles: tuple[str, ...] | None = None + lookup_roles: tuple[str, ...] | None = None + related_evidence: tuple[str, ...] = () + related_lookup: tuple[str, ...] = () + grouped: bool = False + + def __post_init__(self) -> None: + """Validate syntax before checking the accepted project vocabulary.""" + if self.purpose not in ("document", "lookup", "raw"): + raise ValueError("Unknown source purpose.") + for name in ("target_roles", "candidate_roles", "evidence_roles", + "lookup_roles"): + values = getattr(self, name) + if values is not None: + _ids(values, name) + _ids(self.related_evidence, "related_evidence") + _ids(self.related_lookup, "related_lookup") + if type(self.grouped) is not bool: + raise ValueError("grouped must be boolean.") + if self.grouped and self.purpose != "document": + raise ValueError("Grouping requires document purpose.") + + +@dataclass(frozen=True, slots=True) +class SourceFileState: + """One selected physical source's captured index identity. + + Attributes + ---------- + path: pathlib.Path + Selected source-relative path, never a synthetic parent identity. + sha256: str | None + Content digest from the captured physical state; None when no + content identity was recorded for this selected file. + indexed: bool + Whether this generation contains original passages for the file. + + """ + + path: Path + sha256: str | None = None + indexed: bool = False + + def __post_init__(self) -> None: + """Reject unsafe paths and indexed files without content identity.""" + _paths((self.path,), "Source file") + if self.sha256 is not None: + _digest(self.sha256, "Source file") + if type(self.indexed) is not bool or ( + self.indexed and self.sha256 is None + ): + raise ValueError("Indexed files require a content digest.") + + +@dataclass(frozen=True, slots=True) +class SourceInventory: + """Physical selection and index-generation identity captured together. + + Attributes + ---------- + files: tuple[SourceFileState, ...] + Every selected physical file, including those without passages. + index_generation: str + Digest identifying the host's captured index generation, including + applicable indexing configuration. Not a semantic manifest digest. + + """ + + files: tuple[SourceFileState, ...] + index_generation: str + + def __post_init__(self) -> None: + """Require a canonical immutable inventory and generation digest.""" + if type(self.files) is not tuple or any( + type(item) is not SourceFileState for item in self.files + ): + raise ValueError("files requires a tuple of SourceFileState.") + _paths(tuple(item.path for item in self.files), "Source inventory") + _digest(self.index_generation, "Index generation") + object.__setattr__(self, "files", tuple(sorted( + self.files, key=lambda item: item.path.as_posix(), + ))) + + @property + def generation(self) -> str: + """Return a stable digest of selection, contents and index identity.""" + data = [self.index_generation, [ + [item.path.as_posix(), item.sha256, item.indexed] + for item in self.files + ]] + return sha256(json.dumps(data, separators=(",", ":")) + .encode("utf-8")).hexdigest() + + @property + def selected(self) -> tuple[Path, ...]: + """Return all selected physical paths in canonical order.""" + return tuple(item.path for item in self.files) + + +@dataclass(frozen=True, slots=True) +class SourceOperation: + """Frozen semantic and physical generation for one operation. + + Attributes + ---------- + revision: int + Accepted semantic revision. + manifest_sha256: str + Exact saved semantic-manifest digest. + source_root: SourceRoot + Accepted portable or external source binding. + inventory: SourceInventory + Physical identities captured independently of semantic state. + policy: SourcePolicy + Effective task policy checked against the accepted vocabulary. + scope: SourceScope + Explicit target operands and scope mode. + retained_versions: tuple[pathlib.Path, ...] + Captured historical identities, independent of the semantic digest. + + """ + + revision: int + manifest_sha256: str + source_root: SourceRoot + inventory: SourceInventory + policy: SourcePolicy + scope: SourceScope + retained_versions: tuple[Path, ...] = () + + def __post_init__(self) -> None: + """Reject invalid operation identities and mutable declarations.""" + if type(self.revision) is not int or self.revision < 0: + raise ValueError("Invalid semantic revision.") + _digest(self.manifest_sha256, "Semantic manifest") + if (type(self.source_root) is not SourceRoot + or type(self.inventory) is not SourceInventory + or type(self.policy) is not SourcePolicy + or type(self.scope) is not SourceScope): + raise ValueError("Invalid source-operation declaration.") + root_binding({"base": self.source_root.base, + "path": self.source_root.path}) + _paths(self.retained_versions, "Retained versions") + selected = {path.as_posix() for path in self.inventory.selected} + if not {p.as_posix() for p in self.retained_versions} <= selected: + raise ValueError("Retained versions must be selected.") + if not {path.as_posix() for path in self.scope.paths} <= selected: + raise ValueError("Source scope contains unselected operands.") + + @property + def selected_generation(self) -> str: + """Return the physical generation identity for this operation.""" + return self.inventory.generation + + +@dataclass(frozen=True, slots=True) +class UnavailableMember: + """One unavailable physical member, with the reason for omission. + + Attributes + ---------- + path: pathlib.Path + Selected but unreadable, or inactive recorded source-relative path. + reason: str + Unselected, unresolved, unindexed, or raw_unavailable. + + """ + + path: Path + reason: str + + def __post_init__(self) -> None: + """Validate member identity and diagnostic category.""" + _paths((self.path,), "Unavailable member") + if self.reason not in ( + "unselected", "unresolved", "unindexed", "raw_unavailable", + ): + raise ValueError("Unknown unavailable-member reason.") + + +@dataclass(frozen=True, slots=True) +class SourceGroup: + """One anchor's physical membership, not a merged document or index. + + Attributes + ---------- + anchor: pathlib.Path + Independent document or explicit physical lookup target. + evidence: tuple[pathlib.Path, ...] + Selected scientific-support members, including the anchor for + document purpose. May include files without indexed text. + lookup: tuple[pathlib.Path, ...] + Selected lookup members; never scientific support merely by being + linked. The anchor belongs here for lookup/raw purpose. + unavailable: tuple[UnavailableMember, ...] + Missing, unresolved or unreadable members, with explicit reasons. + + """ + + anchor: Path + evidence: tuple[Path, ...] + lookup: tuple[Path, ...] + unavailable: tuple[UnavailableMember, ...] = () + + def __post_init__(self) -> None: + """Require distinct physical identities and immutable diagnostics.""" + _paths((self.anchor,), "Group anchor") + _paths(self.evidence, "Evidence members") + _paths(self.lookup, "Lookup members") + names = {p.as_posix() for p in (*self.evidence, *self.lookup)} + check_aliases((*names, self.anchor.as_posix())) + if self.anchor.as_posix() not in names: + raise ValueError("Group membership must include its anchor.") + if any(not document_candidate(path) for path in self.evidence): + raise ValueError("Bibliographies cannot be scientific evidence.") + if type(self.unavailable) is not tuple or any( + type(item) is not UnavailableMember for item in self.unavailable + ) or len(set(self.unavailable)) != len(self.unavailable): + raise ValueError("Invalid unavailable members.") + + +@dataclass(frozen=True, slots=True) +class SourceView: + """Exact operation membership and immutable generation identity. + + Attributes + ---------- + operation: SourceOperation + Shared snapshot for all services within this operation. + targets: tuple[pathlib.Path, ...] + Explicit operands, or eligible anchors for project-wide selection. + candidates: tuple[pathlib.Path, ...] + Eligible independent document candidates inside the operation scope. + groups: tuple[SourceGroup, ...] + One group for each target/candidate, never transitively merged. + + """ + + operation: SourceOperation + targets: tuple[Path, ...] + candidates: tuple[Path, ...] + groups: tuple[SourceGroup, ...] + + def __post_init__(self) -> None: + """Check that every usable member belongs to the frozen selection.""" + if type(self.operation) is not SourceOperation: + raise ValueError("SourceView requires a SourceOperation.") + _paths(self.targets, "Targets") + _paths(self.candidates, "Candidates") + if type(self.groups) is not tuple or any( + type(group) is not SourceGroup for group in self.groups + ): + raise ValueError("groups requires a tuple of SourceGroup.") + anchors = tuple(dict.fromkeys((*self.targets, *self.candidates))) + if tuple(group.anchor for group in self.groups) != anchors: + raise ValueError("Source groups must match ordered anchors.") + selected = {p.as_posix() for p in self.operation.inventory.selected} + scope = self.operation.scope + if scope.mode == "restricted" and ( + tuple(p.as_posix() for p in self.targets) + != tuple(p.as_posix() for p in scope.paths) + or not {p.as_posix() for p in self.candidates} <= { + p.as_posix() for p in scope.paths + } + ): + raise ValueError("Group anchors exceed the restricted scope.") + if scope.mode == "preferred" and not { + p.as_posix() for p in scope.paths + } <= {p.as_posix() for p in self.targets}: + raise ValueError("Preferred operands must remain targets.") + if any(not {p.as_posix() for p in (*group.evidence, *group.lookup)} + <= selected for group in self.groups): + raise ValueError("Group includes an unselected source.") + + @property + def evidence(self) -> tuple[Path, ...]: + """Return deduplicated selected evidence members in group order.""" + return tuple(dict.fromkeys(path for group in self.groups + for path in group.evidence)) + + @property + def lookup(self) -> tuple[Path, ...]: + """Return deduplicated selected lookup members in group order.""" + return tuple(dict.fromkeys(path for group in self.groups + for path in group.lookup)) + + @property + def unavailable(self) -> tuple[UnavailableMember, ...]: + """Return deduplicated diagnostics without granting membership.""" + return tuple(dict.fromkeys(item for group in self.groups + for item in group.unavailable)) + + +def capture_source_inventory( + inspection: SourceManifestInspection, + index_state: Mapping[str, object], + indexed: Collection[Path], + index_generation: str, +) -> SourceInventory: + """Capture physical identities from the existing index-state inventory. + + Parameters + ---------- + inspection: SourceManifestInspection + Authoritative selected-source inspection, including unindexed files. + index_state: Mapping[str, object] + Captured repository manifest with a ``files`` mapping containing + SHA-256 content identities. No physical cache is written here. + indexed: Collection[pathlib.Path] + Paths with original passages in the captured generation. + index_generation: str + Host-provided index generation digest, including configuration. + + Returns + ------- + SourceInventory + Immutable physical snapshot; new selected files without index + identities remain visible but unavailable for verified reads. + + """ + files = index_state.get("files") + if not isinstance(files, Mapping): + raise ValueError("Index source state requires a files mapping.") + selected = tuple(Path(canonical_path(name)) + for name in inspection.selected) + _paths(selected, "Selected inventory") + selected_names = {path.as_posix() for path in selected} + indexed_paths = tuple(indexed) + _paths(indexed_paths, "Indexed paths") + indexed_names = {path.as_posix() for path in indexed_paths} + if not indexed_names <= selected_names: + raise SourceViewConflict("Index contains unselected sources.") + states = {} + for name, entry in files.items(): + name = canonical_path(name) + if name not in selected_names: + raise SourceViewConflict("Index state contains unselected files.") + if not isinstance(entry, Mapping): + raise ValueError("Invalid index source state entry.") + digest = entry.get("sha256") + _digest(digest, "Index source state") + states[name] = digest + return SourceInventory(tuple(SourceFileState( + path, states.get(path.as_posix()), path.as_posix() in indexed_names, + ) for path in selected), index_generation) + + + +def validate_source_policy( + policy: SourcePolicy, organization: SourceOrganization, +) -> None: + """Check a policy against the supplied accepted vocabulary. + + Parameters + ---------- + policy: SourcePolicy + Syntax-validated operation declaration. + organization: SourceOrganization + Vocabulary accepted by a project or declared by its type. + + Raises + ------ + ValueError + If a role or relation is not declared by the organization. + + """ + declaration = organization + for name in ("target_roles", "candidate_roles", "evidence_roles", + "lookup_roles"): + values = getattr(policy, name) + unknown = set(values or ()) - set(declaration.roles) + if unknown: + raise ValueError(f"Policy {name} has unaccepted roles: " + f"{sorted(unknown)}. Adopt or revise settings.") + unknown = set((*policy.related_evidence, *policy.related_lookup)) - set( + declaration.relation_ids + ) + if unknown: + raise ValueError(f"Policy has unaccepted relations: {sorted(unknown)}." + " Adopt or revise settings.") + +def _operation( + inspection: SourceManifestInspection, inventory: SourceInventory, + policy: SourcePolicy, scope: SourceScope, +) -> SourceOperation: + """Validate one snapshot against selection and accepted declarations. + + Parameters + ---------- + inspection: SourceManifestInspection + Captured saved state and selected inventory. + inventory: SourceInventory + Physical state for exactly that selection. + policy: SourcePolicy + Requested role/relation policy. + scope: SourceScope + Explicit operation operands. + + Returns + ------- + SourceOperation + Consistent frozen generation, or an actionable conflict. + + """ + if not inspection.binding_matches: + raise SourceViewConflict( + "Source root does not match the project sources directory." + ) + if type(inventory) is not SourceInventory or type(policy) is not ( + SourcePolicy + ) or type(scope) is not SourceScope: + raise ValueError("Invalid inventory, policy or source scope.") + selected = tuple(Path(canonical_path(name)) + for name in inspection.selected) + _paths(selected, "Selected inventory") + selected_names = {p.as_posix() for p in selected} + if selected_names != {p.as_posix() for p in inventory.selected}: + raise SourceViewConflict( + "Selected inventory changed; refresh sources." + ) + if not {p.as_posix() for p in scope.paths} <= selected_names: + raise ValueError("Source scope contains unselected operands.") + manifest = inspection.snapshot.manifest + declaration = manifest.organization.declaration + validate_source_policy(policy, declaration) + retained = tuple(Path(canonical_path(name)) + for name in inspection.retained_versions) + return SourceOperation(manifest.revision, inspection.snapshot.sha256, + manifest.source_root, inventory, policy, scope, + retained) + + +def _matches(role: str | None, roles: tuple[str, ...] | None) -> bool: + """Match a role without deriving a default for an unresolved path. + + Parameters + ---------- + role: str | None + Accepted active role, if any. + roles: tuple[str, ...] | None + Explicit filter or None for unrestricted. + + Returns + ------- + bool + Whether the role satisfies the filter. + + """ + return roles is None or role in roles + + +def resolve_source_view( + inspection: SourceManifestInspection, inventory: SourceInventory, + policy: SourcePolicy = SourcePolicy(), scope: SourceScope = SourceScope(), +) -> SourceView: + """Resolve one-hop anchor views without I/O or transitive merging. + + Parameters + ---------- + inspection: SourceManifestInspection + Read-only accepted semantic state and authorized selection. + inventory: SourceInventory + Captured physical generation for the exact selection. + policy: SourcePolicy, optional + Document discovery without related expansion by default. + scope: SourceScope, optional + Project-wide by default; explicit empty restriction stays empty. + + Returns + ------- + SourceView + Immutable targets, independent candidates and physical memberships. + + Notes + ----- + Directed dependencies expand from a parent to its immediate children; + associations expand symmetrically only when explicitly permitted. + Shared children do not combine their parents. Inactive stored links + are diagnostic only, never authority to access an unselected file. + + """ + operation = _operation(inspection, inventory, policy, scope) + manifest = inspection.snapshot.manifest + selected = set(inventory.selected) + names = {path.as_posix() for path in selected} + roles = {Path(item.path): item.role + for item in active_roles(manifest, names)} + relations = active_relations(manifest, names) + behaviors = {item.id: item.behavior for item in + manifest.organization.declaration.relation_types} + dependent = {Path(item.key.source) for item in relations + if behaviors[item.key.type] == "dependency"} + retained = set(operation.retained_versions) + independent = tuple(path for path in inventory.selected + if path in roles and path not in dependent + and path not in retained and document_candidate(path)) + candidate_roles = (policy.target_roles if policy.candidate_roles is None + else policy.candidate_roles) + candidates = tuple(path for path in independent + if _matches(roles[path], candidate_roles)) + eligible = (independent if policy.purpose == "document" + else inventory.selected) + eligible = tuple(path for path in eligible + if _matches(roles.get(path), policy.target_roles)) + if policy.purpose != "document": + # A lookup operation does not discover independent publications. + candidates = () + if scope.mode == "project": + targets = eligible + else: + if not set(scope.paths) <= set(eligible): + raise ValueError("Source operand is ineligible for this policy; " + "use explicit lookup/raw or resolve its role.") + targets = scope.paths + if scope.mode == "restricted": + candidates = tuple(path for path in targets if path in candidates) + elif policy.purpose != "document": + # Preferred physical lookup also permits other eligible targets. + targets = tuple(dict.fromkeys((*targets, *eligible))) + + states = {item.path: item for item in inventory.files} + stored_roles = {Path(item.path): item.role for item in manifest.files} + edges = {item.key for item in relations} + allowed_types = set((*policy.related_evidence, *policy.related_lookup)) + # Build one adjacency map for the operation, not a scan for each anchor. + adjacency = {} + rules = {rule.id: rule.relation for rule in + manifest.organization.declaration.automatic_rules} + suppressed = set(manifest.suppressed_automatic) + for relation in manifest.relations: + key = relation.key + if key.type not in allowed_types or ( + relation.origin != "user" and (key in suppressed + or rules.get(relation.rule) != key.type) + ): + continue + source, target = Path(key.source), Path(key.target) + adjacency.setdefault(target, []).append((source, key, key in edges)) + if behaviors[key.type] == "association": + adjacency.setdefault(source, []).append( + (target, key, key in edges) + ) + + groups = [] + for anchor in dict.fromkeys((*targets, *candidates)): + evidence = [anchor] if policy.purpose == "document" else [] + lookup = [] if policy.purpose == "document" else [anchor] + unavailable = [] + for member, key, active in adjacency.get(anchor, ()): + if anchor not in roles: + continue + # Inactive records can identify a missing member's prior role + # for diagnostics, but never grant active membership. + role = roles.get(member) if active else stored_roles.get(member) + use_evidence = ( + key.type in policy.related_evidence + and document_candidate(member) + and _matches(role, policy.evidence_roles) + ) + use_lookup = ( + key.type in policy.related_lookup + and _matches(role, policy.lookup_roles) + ) + if not (use_evidence or use_lookup): + continue + if not active: + unavailable.append(UnavailableMember( + member, + "unresolved" if member in selected else "unselected", + )) + continue + if use_evidence: + evidence.append(member) + if use_lookup: + lookup.append(member) + for member in dict.fromkeys((*evidence, *lookup)): + state = states[member] + if not state.indexed and policy.purpose != "raw": + unavailable.append(UnavailableMember(member, "unindexed")) + if state.sha256 is None: + unavailable.append(UnavailableMember( + member, "raw_unavailable" + )) + groups.append(SourceGroup( + anchor, tuple(dict.fromkeys(evidence)), + tuple(dict.fromkeys(lookup)), + tuple(dict.fromkeys(unavailable)), + )) + return SourceView(operation, targets, candidates, tuple(groups)) + + +def validate_source_view( + view: SourceView, inspection: SourceManifestInspection, + inventory: SourceInventory, policy: SourcePolicy, scope: SourceScope, +) -> None: + """Check that a service still uses the same captured operation state. + + Parameters + ---------- + view: SourceView + Previously resolved immutable view. + inspection: SourceManifestInspection + Current authoritative semantic inspection. + inventory: SourceInventory + Current physical generation and selection. + policy: SourcePolicy + Current effective operation policy. + scope: SourceScope + Current explicit scope declaration. + + Raises + ------ + SourceViewConflict + If the saved bytes, revision, root, generation or policy changed. + + """ + try: + current = resolve_source_view(inspection, inventory, policy, scope) + except ValueError as error: + raise SourceViewConflict( + f"Source operation is no longer valid; restart it: {error}" + ) from error + if current != view: + raise SourceViewConflict("Source operation changed; restart it.") + + +def read_source_bytes( + project_root: Path, source_root: Path, view: SourceView, path: Path, +) -> bytes: + """Read selected source bytes only if they match the captured identity. + + Parameters + ---------- + project_root: pathlib.Path + Current workspace root. + source_root: pathlib.Path + Current configured source root, contained in the workspace. + view: SourceView + Frozen operation view authorizing this physical member. + path: pathlib.Path + Source-relative path to read. + + Returns + ------- + bytes + Original bytes verified against the captured content digest. + + Raises + ------ + SourceViewConflict + If membership, root, content identity or file availability fails. + + Notes + ----- + The host must use the same operation for all services and check changes + to the saved state with ``validate_source_view`` when needed. This is a + best-effort containment check, not a sandbox or a race-free file opener. + + """ + _paths((path,), "Raw source") + operation = view.operation + members = {p.as_posix() for p in (*view.evidence, *view.lookup)} + if path.as_posix() not in members: + raise SourceViewConflict("Source is outside the operation view.") + binding = operation.source_root + if binding.base != "project": + raise SourceViewConflict("Raw reads require a workspace source root.") + try: + expected = (project_root / binding.path).resolve(strict=True) + if source_root.resolve(strict=True) != expected: + raise SourceViewConflict("Source root changed; restart operation.") + candidate = selected_source_file( + project_root, source_root, path, operation.inventory.selected, + ) + state = next(item for item in operation.inventory.files + if item.path.as_posix() == path.as_posix()) + if candidate is None or state.sha256 is None: + raise SourceViewConflict("Source unavailable for a verified read.") + data = candidate.read_bytes() + except OSError as error: + raise SourceViewConflict( + "Source unavailable for a verified read." + ) from error + if sha256(data).hexdigest() != state.sha256: + raise SourceViewConflict("Source bytes changed; refresh sources.") + return data diff --git a/kilin/sources/_word_metadata.py b/kilin/sources/_word_metadata.py index d1b88ff4..b696192d 100644 --- a/kilin/sources/_word_metadata.py +++ b/kilin/sources/_word_metadata.py @@ -37,6 +37,7 @@ from __future__ import annotations +from io import BytesIO from pathlib import Path from typing import Final @@ -49,7 +50,9 @@ _WORD_SUFFIXES: Final[frozenset[str]] = frozenset({".doc", ".docx"}) -def read_word_metadata(file: Path) -> tuple[str | None, str | None]: +def read_word_metadata( + file: Path, *, original: bytes | None = None, +) -> tuple[str | None, str | None]: """Return a Word file's stored title and author, when readable. Parameters @@ -57,6 +60,8 @@ def read_word_metadata(file: Path) -> tuple[str | None, str | None]: file: pathlib.Path Word file. The suffix must be ``.doc`` or ``.docx``; the content signature determines which metadata reader is used. + original: bytes | None, optional + Verified document content; when supplied, no path is opened. Returns ------- @@ -70,13 +75,17 @@ def read_word_metadata(file: Path) -> tuple[str | None, str | None]: return None, None try: - with file.open("rb") as handle: - signature = handle.read(len(_OLE_SIGNATURE)) + if original is None: + with file.open("rb") as handle: + signature = handle.read(len(_OLE_SIGNATURE)) + else: + signature = original[:len(_OLE_SIGNATURE)] + source = BytesIO(original) if original is not None else str(file) if signature == _OLE_SIGNATURE: import olefile - with olefile.OleFileIO(str(file)) as document: + with olefile.OleFileIO(source) as document: metadata = document.get_metadata() return ( _property(metadata.title), @@ -85,7 +94,7 @@ def read_word_metadata(file: Path) -> tuple[str | None, str | None]: from docx import Document - properties = Document(str(file)).core_properties + properties = Document(source).core_properties return _property(properties.title), _property(properties.author) except Exception: # pylint: disable=broad-exception-caught # Metadata is optional; a reader error cannot abort indexing. diff --git a/kilin/system_testing/__init__.py b/kilin/system_testing/__init__.py new file mode 100644 index 00000000..0e3e8ef5 --- /dev/null +++ b/kilin/system_testing/__init__.py @@ -0,0 +1,56 @@ +"""Expose the KíLín system-testing inspection, replay and comparison API. + +Key Features +------------ +- Reference workspace validation and chronological operation inspection. +- Model-independent, read-only checks of current-format recordings. +- Independent reproduction of validated workspace histories. +- Independent quantitative comparison of original and replayed workspaces. +- Recipe-driven reference generation and reproducible batch reporting. + +Module Structure +---------------- +- ``Experiment``: reference experiment entry point. +- ``TraceEvent``, ``TimelineOperation``: decoded history records. +- ``ValidationIssue``, ``ValidationReport``, ``InvalidRecordingError``: + structured diagnostics and rejection of invalid reference recordings. +- ``ReplayResult``, ``ReplayDifference``, ``ReplayError``: replay outcomes. +- ``Comparison``: structured observations and saved reports. +- ``ManagedReplay``: retained or fresh replay outcome and provenance. +- Reference receipt publication and inspection functions. +- ``generation``, ``batch``, ``analysis``: optional system-testing + workflows, imported explicitly when needed. + +Examples +-------- +>>> from kilin.system_testing import Experiment +>>> # Experiment("workspaces/010_original").validate() + +""" + +from .comparison import Comparison +from .experiment import Experiment +from .replay import ReplayDifference, ReplayError, ReplayResult +from .reference import inspect_receipt, publish_receipt, receipt_path +from .replay_management import ManagedReplay, execution_provenance +from .timeline import TimelineOperation +from .traces import TraceEvent, ValidationIssue +from .validation import InvalidRecordingError, ValidationReport + +__all__ = [ + "Experiment", + "Comparison", + "TraceEvent", + "TimelineOperation", + "ValidationIssue", + "ValidationReport", + "InvalidRecordingError", + "ReplayDifference", + "ReplayError", + "ReplayResult", + "ManagedReplay", + "receipt_path", + "publish_receipt", + "inspect_receipt", + "execution_provenance", +] diff --git a/kilin/system_testing/_comparison_alignment.py b/kilin/system_testing/_comparison_alignment.py new file mode 100644 index 00000000..eed3aa14 --- /dev/null +++ b/kilin/system_testing/_comparison_alignment.py @@ -0,0 +1,435 @@ +"""Align validated workspace histories without using generated identities. + +Key Features +------------ +- Align explicit chronological operations and durable identity transitions. +- Compare source outcomes independently of historical external paths. +- Stop at the first ambiguous or different input; never align by answer. + +Module Structure +---------------- +- ``Alignment`` holds the matched prefix, identity maps, and divergence. +- ``align`` reconstructs correspondences from two validated recordings. + +Examples +-------- +>>> from kilin.system_testing import Experiment +>>> # comparison = Experiment("010_original").compare() + +""" + +from dataclasses import dataclass, field + +from kilin.repository import _manifest_files + +from ._semantic_replay import semantic_request +from .timeline import TimelineOperation, one + +__all__ = [] + + +@dataclass(slots=True) +class Alignment: + """Unambiguous operation prefix and independently reconstructed IDs.""" + + pairs: list[tuple[TimelineOperation, TimelineOperation]] = field( + default_factory=list + ) + conversations: dict[str, str] = field(default_factory=dict) + turns: dict[str, str] = field(default_factory=dict) + reason: str | None = None + + +def _check(condition: bool, message: str) -> None: + """Reject a mismatch before extending the matched prefix. + + Parameters + ---------- + condition: bool + Required correspondence. + message: str + Explanation if the correspondence fails. + + """ + if not condition: + raise ValueError(message) + + +def _mapped(mapping: dict[str, str], value: str | None) -> str | None: + """Map a previously identified object or a genuine absent identity. + + Parameters + ---------- + mapping: dict[str, str] + Established original-to-replay identities. + value: str | None + Recorded original identity. + + Returns + ------- + str | None + Corresponding replay identity. + + """ + return None if value is None else mapping[value] + + +def _register(mapping: dict[str, str], original: str, replayed: str) -> None: + """Extend a one-to-one identity map only for newly allocated objects. + + Parameters + ---------- + mapping: dict[str, str] + Identity map for one object type. + original: str + Newly allocated original identity. + replayed: str + Newly allocated replay identity. + + """ + _check(original not in mapping and replayed not in mapping.values(), + "A newly allocated identity was reused.") + mapping[original] = replayed + + +def _source_effects(op: TimelineOperation) -> dict: + """Describe durable source changes without reopening external inputs. + + Parameters + ---------- + op: TimelineOperation + Validated command interval. + + Returns + ------- + dict + Actual managed copy outcomes, additive sync actions, and manifests. + A direct file's original basename may differ from its managed name. + + """ + copies = [] + for event in op.matching("workspace.source.copied"): + data = event.details + path = data["workspace_path"] + copied = data["copied_files"] + preserved = data["preserved_files"] + if data["kind"] == "file": + copied = [path] if copied else [] + preserved = [path] if preserved else [] + else: + copied = sorted(f"{path}/{name}" for name in copied) + preserved = sorted(f"{path}/{name}" for name in preserved) + copies.append((path, data["kind"], copied, preserved)) + return { + "copies": sorted(copies), + "sync": sorted((e.details["path"], e.details["action"]) + for e in op.matching("workspace.sync.file")), + "manifests": [_manifest_files(e.details["source_manifest"]) + for e in op.matching("index.check.completed", + "index.empty")], + } + + +def interaction_records(op: TimelineOperation) -> list[dict]: + """Pair interaction proposals and outcomes in their original order. + + Parameters + ---------- + op: TimelineOperation + Validated question command. + + Returns + ------- + list[dict] + Proposals and decisions without regenerated interaction identifiers. + + """ + decisions = {e.details["interaction_id"]: e.details for e in op.matching( + "routing.choice.decided", "tool.choice.decided", "tool.plan.decided" + )} + records = [] + for event in op.matching("routing.choice.proposed", "tool.choice.proposed", + "tool.plan.proposed"): + proposal = event.details + decision = decisions[proposal["interaction_id"]] + records.append({ + "kind": event.event_type.removesuffix(".proposed"), + "proposal": {k: v for k, v in proposal.items() + if k != "interaction_id"}, + "decision": {k: v for k, v in decision.items() + if k != "interaction_id"}, + }) + return records + + +def _user_choices(op: TimelineOperation) -> list[dict]: + """Retain semantic responses rather than numerical option positions. + + Parameters + ---------- + op: TimelineOperation + Question with recorded interactive decisions. + + Returns + ------- + list[dict] + Explicit user decisions, excluding automatic choices and estimates. + + """ + responses = [] + for record in interaction_records(op): + kind = record["kind"] + proposal = record["proposal"] + decision = record["decision"] + if not proposal["asked"]: + continue + if kind == "tool.plan": + keys = ["tool", "summary", "scope", "details"] + if decision["choice"] == "quick": + keys.extend(("quick_label", "quick_note")) + if proposal.get("operation") == "network": + keys.extend(("items", "batches", "batches_to_run", + "quick_items")) + value = {k: proposal.get(k) for k in keys} + value.update(operation=proposal.get("operation", "model"), + choice=decision["choice"]) + else: + value = {k: proposal[k] for k in ("question", "allow_cancel")} + value["selected_option"] = decision["selected_option"] + # Replay uses the same semantic choice protocol for router and + # tool prompts. A changed producer stage is a recorded observation. + value["kind"] = kind if kind == "tool.plan" else "choice" + responses.append(value) + return responses + + +def _includes(expected: dict, submitted: dict) -> bool: + """Check explicit overrides against the submitted nested settings form. + + Parameters + ---------- + expected: dict + Recorded sparse overrides; lists are atomic values. + submitted: dict + Settings actually submitted in the corresponding request. + + Returns + ------- + bool + Whether every expected field is present with the same typed value. + + """ + for key, value in expected.items(): + if key not in submitted: + return False + actual = submitted[key] + if isinstance(value, dict): + if not isinstance(actual, dict) or not _includes(value, actual): + return False + elif type(value) is not type(actual) or value != actual: + return False + return True + + +def _overrides(first: dict, second: dict, explicit_key: str, + submitted_key: str) -> bool: + """Allow an explicit value to become equal to a new inherited default. + + Parameters + ---------- + first: dict + Original recorded settings request. + second: dict + Replay recorded settings request. + explicit_key: str + Field holding classified sparse overrides. + submitted_key: str + Field holding the actual submitted settings. + + Returns + ------- + bool + Whether all original overrides were submitted and the replay has + no additional explicit override. A changed default can make a + previously explicit field appear inherited in a GUI full form. + + """ + old, new = first[explicit_key], second[explicit_key] + return (_includes(old, second[submitted_key]) and _includes(new, old)) + + +def _same_request(before: TimelineOperation, after: TimelineOperation, + conversations: dict[str, str], + turns: dict[str, str]) -> None: + """Verify command inputs modulo mapped IDs and inherited settings. + + Parameters + ---------- + before: TimelineOperation + Original command. + after: TimelineOperation + Candidate corresponding replay command. + conversations: dict[str, str] + Established conversation map. + turns: dict[str, str] + Established turn map. + + """ + kind = before.kind + first, second = before.request, after.request + if kind == "create_project": + _check(first["source_batch"]["type_id"] == + second["source_batch"]["type_id"], "Project type changed.") + _check(_overrides(first["settings"], second["settings"], + "explicit_settings", "requested_settings"), + "Explicit creation settings differ.") + return + if kind in ("add_sources", "sync_sources"): + # Source paths and unretained no-effect selections can differ. + # The actual imports and historical manifests are checked separately. + return + if kind == "source_organization": + _check(semantic_request(first) == semantic_request(second), + "Explicit semantic source command differs.") + if first["operation"] == "apply": + old_preview = before.events[0].details["preview_request"] + new_preview = after.events[0].details["preview_request"] + _check(semantic_request(old_preview) == semantic_request( + new_preview), "Applied semantic preview differs.") + return + if kind == "ask": + keys = ("question", "title_question", "retrieval_count", "effort") + _check(all(first.get(k) == second.get(k) for k in keys), + "Question or effort settings differ.") + _check(_overrides(first, second, "explicit_generation_settings", + "generation_settings"), + "Explicit question overrides differ.") + _check(_user_choices(before) == _user_choices(after), + "Semantic user responses differ.") + elif kind == "create_conversation": + _check(all(first.get(k) == second.get(k) for k in ( + "branch", "turn_count")), "Requested branch prefix differs.") + elif kind == "open_project": + _check("relocation" not in second or "relocation" in first, + "Unexpected replay-side project rename.") + elif kind == "rename_conversation": + _check(first["name"] == second["name"], "Explicit title differs.") + elif kind in ("feedback", "memory_exclusion"): + keys = ("role", "saved", "reaction", "excluded") + _check(all(first.get(k) == second.get(k) for k in keys), + "Feedback or exclusion request differs.") + _check(_mapped(turns, first["turn_uuid"]) == second["turn_uuid"], + "Feedback refers to another turn.") + elif kind == "sync_memory": + _check(first["trigger"] == second["trigger"], + "Memory synchronization trigger differs.") + for key in ("conversation_id", "previous_conversation_id", + "requested_conversation_id"): + if key in first or key in second: + _check(_mapped(conversations, first.get(key)) == second.get(key), + f"Different conversation transition: {key}.") + + +def _outcome(before: TimelineOperation, after: TimelineOperation, + conversations: dict[str, str], turns: dict[str, str]) -> None: + """Extend mappings from observed durable outcomes, checking lineage. + + Parameters + ---------- + before: TimelineOperation + Original operation. + after: TimelineOperation + Corresponding replay operation. + conversations: dict[str, str] + Candidate conversation map, updated only within this pair. + turns: dict[str, str] + Candidate turn map, updated only within this pair. + + """ + kind = before.kind + if kind == "create_project": + _register(conversations, before.request["open"]["conversation_id"], + after.request["open"]["conversation_id"]) + elif kind in ("create_conversation", "reset_conversation"): + event_type = ("gui.conversation.create.result" if kind == + "create_conversation" else + "gui.conversation.reset.result") + first = one(before.events, event_type).details + second = one(after.events, event_type).details + _check(first.get("reused") == second.get("reused") and + first.get("origin_turn_count") == + second.get("origin_turn_count") and + _mapped(conversations, first.get("parent_conversation_id")) == + second.get("parent_conversation_id"), + "Conversation creation or branch lineage differs.") + if first.get("reused"): + _check(conversations[first["conversation_id"]] == + second["conversation_id"], "A different chat was reused.") + else: + _register(conversations, first["conversation_id"], + second["conversation_id"]) + elif kind == "delete_conversation": + first = one(before.events, "gui.conversation.deleted").details + second = one(after.events, "gui.conversation.deleted").details + _check(all(first[k] == second[k] for k in ( + "deleted_active", "replacement_created")), + "Archive or replacement policy differs.") + old = first["replacement"]["conversation_id"] + new = second["replacement"]["conversation_id"] + if first["replacement_created"]: + _register(conversations, old, new) + else: + _check(conversations[old] == new, "Replacement chat differs.") + elif kind == "ask": + first = one(before.events, "gui.question.saved").details + second = one(after.events, "gui.question.saved").details + _check(first["turn_count"] == second["turn_count"], + "Committed turn count differs.") + _register(turns, first["conversation_turn_uuid"], + second["conversation_turn_uuid"]) + old = before.matching("conversation.restored") + new = after.matching("conversation.restored") + _check(len(old) == len(new), "Restoration count differs.") + for first, second in zip(old, new): + _check([turns[uid] for uid in first.details["turn_uuids"]] == + second.details["turn_uuids"], "Restored turn prefix differs.") + + +def align(original: tuple[TimelineOperation, ...], + replayed: tuple[TimelineOperation, ...]) -> Alignment: + """Align only the unambiguous common prefix of validated recordings. + + Parameters + ---------- + original: tuple[TimelineOperation, ...] + Validated original timeline. + replayed: tuple[TimelineOperation, ...] + Independently validated replay timeline. + + Returns + ------- + Alignment + Matched prefix, reconstructed IDs, and first mismatch if any. + + """ + result = Alignment() + for before, after in zip(original, replayed): + conversations = dict(result.conversations) + turns = dict(result.turns) + try: + _check(before.kind == after.kind, "Command kind differs.") + _check(before.status == after.status == "completed", + "Command is not completed in both recordings.") + _same_request(before, after, conversations, turns) + _check(_source_effects(before) == _source_effects(after), + "Historical managed source effects differ.") + _outcome(before, after, conversations, turns) + except (ValueError, KeyError, TypeError) as error: + result.reason = str(error) + break + result.conversations = conversations + result.turns = turns + result.pairs.append((before, after)) + if result.reason is None and len(original) != len(replayed): + result.reason = "Recorded command counts differ." + return result diff --git a/kilin/system_testing/_comparison_diagnostics.py b/kilin/system_testing/_comparison_diagnostics.py new file mode 100644 index 00000000..77c03209 --- /dev/null +++ b/kilin/system_testing/_comparison_diagnostics.py @@ -0,0 +1,493 @@ +"""Compare recorded context and tool outcomes without changing execution. + +Key Features +------------ +- Match conversation memory and history by recorded turn identities. +- Distinguish functional tool results from elapsed-time measurements. +- Normalize only corroborated memory headers in structured model inputs. +- Retain independently observable answers when alignment is unavailable. + +Module Structure +---------------- +- ``context_comparison`` measures context selection by mapped identity. +- ``structured_prompt`` prepares a narrowly normalized prompt observation. +- ``tool_comparison`` separates timing, functional results and coverage. +- ``independent_questions`` exposes saved-question candidates and trust. + +Examples +-------- +>>> from kilin.system_testing import Experiment +>>> # report = Experiment("010_original").compare().data + +""" + +from __future__ import annotations + +from collections import Counter +from copy import deepcopy +import json +import re + +from .timeline import TimelineOperation +from .traces import Recording, TraceEvent +from .validation import ValidationReport + +__all__ = [] + +_CONTEXT = ("history.selection.result", "memory.sync.result", + "project.memory.sync.result", "conversation_memory.retrieved") +_HEADER = re.compile( + r"Memory (M[1-9]\d*) \| (user|assistant) \| Turn (T[1-9]\d*)" +) +_MEMORY_HEADING = ( + "CONVERSATION MEMORY (previous discussion, NOT source evidence):" +) +_TIMING = {"seconds", "duration_ms", "elapsed_ms"} +_FAILURES = {"incomplete", "partial", "error", "failed", "cancelled", + "aborted", "interrupted"} + + +def _key(value: object) -> str: + """Serialize one observation for stable, order-independent sorting. + + Parameters + ---------- + value: object + JSON-compatible recorded observation. + + """ + return json.dumps(value, ensure_ascii=False, sort_keys=True) + + +def _mapped(value: str, identities: dict[str, str]) -> str: + """Require a known correspondence instead of erasing an unknown ID. + + Parameters + ---------- + value: str + Recorded identity. + identities: dict[str, str] + Known identities mapped into the reference namespace. + + """ + if value not in identities: + raise ValueError(f"Unmapped recorded identity: {value}") + return identities[value] + + +def _memory_record(record: dict, turns: dict[str, str], + conversations: dict[str, str]) -> dict: + """Normalize one memory identity, keeping role and all branch origins. + + Parameters + ---------- + record: dict + Recorded inventory entry or selected memory hit. + turns: dict[str, str] + Turn identity map into the reference namespace. + conversations: dict[str, str] + Conversation identity map into the reference namespace. + + """ + origins = [{"conversation_id": _mapped(o["conversation_id"], + conversations), + "turn_number": o["turn_number"]} + for o in record["origins"]] + return {"turn_uuid": _mapped(record["turn_uuid"], turns), + "role": record["role"], "origins": sorted(origins, key=_key)} + + +def _context_payload(event: TraceEvent, op: TimelineOperation, + catalog: dict[str, list[str]], turns: dict[str, str], + conversations: dict[str, str]) -> dict: + """Read identity-level context while keeping content metrics separate. + + Parameters + ---------- + event: TraceEvent + Recorded history, memory inventory or memory retrieval event. + op: TimelineOperation + Enclosing validated operation. + catalog: dict[str, list[str]] + Final validated conversation turn prefixes, including archives. + turns: dict[str, str] + Map into the reference turn namespace. + conversations: dict[str, str] + Map into the reference conversation namespace. + + """ + data = event.details + kind = event.event_type + if kind == "history.selection.result": + prefix = catalog[op.request["conversation_id"]] + saved = op.matching("gui.question.saved") + if len(saved) != 1: + raise ValueError("Cannot bound history to a saved question.") + count = saved[0].details["turn_count"] - 1 + result = {} + for field in ("recent_turn_ids", "related_turn_ids", + "final_turn_ids"): + ids = data[field] + if not isinstance(ids, list) or any( + type(i) is not int or not 1 <= i <= count or + i > len(prefix) for i in ids): + raise ValueError(f"Invalid history selection: {field}") + result[field] = [_mapped(prefix[i - 1], turns) for i in ids] + return {"identity": result} + if kind == "conversation_memory.retrieved": + entries = data["selected_memories"] + return {"identity": [_memory_record(r, turns, conversations) + for r in entries], + "historical_lookup": data.get("historical_lookup"), + "scores": [{k: r.get(k) for k in ("relevance", "score")} + for r in entries]} + entries = data.get("records") + if not isinstance(entries, list): + raise ValueError("Memory inventory was not recorded.") + records = [] + for entry in entries: + identity = _memory_record(entry, turns, conversations) + records.append({"identity": identity, + "fingerprint": entry.get("fingerprint"), + "priority": entry.get("priority")}) + records.sort(key=lambda r: _key(r["identity"])) + return {"identity": [r["identity"] for r in records], + "fingerprints": [r["fingerprint"] for r in records], + "priorities": [r["priority"] for r in records], + "enabled": data.get("enabled")} + + +def context_comparison(original: TimelineOperation, + replayed: TimelineOperation, catalogs: tuple, + maps: tuple) -> list[dict]: + """Compare each context observation by event type and occurrence. + + Parameters + ---------- + original: TimelineOperation + Original command. + replayed: TimelineOperation + Aligned replay command. + catalogs: tuple + Original and replayed conversation-to-turn-prefix maps. + maps: tuple + Original-to-replay conversation and turn identity maps. + + Returns + ------- + list[dict] + Mapped observations, explicit missing coverage, ordered selection + agreement and separate content/priority comparisons. Empty recorded + selections are distinct from unavailable observations. + + """ + conversations, turns = maps + namespaces = (({k: k for k in turns}, {k: k for k in conversations}), + ({v: k for k, v in turns.items()}, + {v: k for k, v in conversations.items()})) + rows = [] + for kind in _CONTEXT: + events = (original.matching(kind), replayed.matching(kind)) + for i in range(max(map(len, events))): + row = {"event_type": kind, "occurrence": i + 1, "issues": []} + for side, group, op, catalog, namespace in zip( + ("original", "replayed"), events, (original, replayed), + catalogs, namespaces, strict=True): + row[side] = None + if i < len(group): + try: + row[side] = _context_payload( + group[i], op, catalog, *namespace) + except (KeyError, TypeError, ValueError, + AttributeError) as error: + row["issues"].append(f"{side}: {error}") + a, b = row["original"], row["replayed"] + row["identity_equal"] = (a["identity"] == b["identity"] + if a is not None and b is not None + else None) + if (kind == "history.selection.result" and + a is not None and b is not None): + row["selection_equal"] = { + key: a["identity"][key] == b["identity"][key] + for key in a["identity"] + } + for field in ("fingerprints", "priorities", "historical_lookup", + "enabled", "scores"): + if (a is not None and b is not None and + field in a and field in b): + row[field + "_equal"] = (a[field] == b[field] + if row["identity_equal"] + else None) + rows.append(row) + return rows + + +def _header(record: dict, line: str, turns: dict[str, str], + conversations: dict[str, str], local_turn: str) -> str: + """Normalize a memory header only if its recorded identity agrees. + + Parameters + ---------- + record: dict + Selected memory observation corroborating this header. + line: str + Exact structured-message line. + turns: dict[str, str] + Turn map into the reference namespace. + conversations: dict[str, str] + Conversation map into the reference namespace. + local_turn: str + Expected prompt-local label for the selected turn UUID. + + """ + match = _HEADER.fullmatch(line) + if not match: + raise ValueError("Memory header does not match recorded format.") + label, role, turn = match.groups() + if (label, role, turn) != ( + record["label"], record["role"], local_turn + ): + raise ValueError("Memory header does not match selected memory.") + identity = _memory_record(record, turns, conversations) + return f"Memory {label} | {_key(identity)}" + + +def structured_prompt(event: TraceEvent | None, op: TimelineOperation, + turns: dict[str, str], + conversations: dict[str, str]) -> dict | None: + """Measure exact structured messages and corroborated header metadata. + + Parameters + ---------- + event: TraceEvent or None + LLM input event, or unavailable. + op: TimelineOperation + Enclosing operation with selected memory observations. + turns: dict[str, str] + Turn map into the reference namespace. + conversations: dict[str, str] + Conversation map into the reference namespace. + + Returns + ------- + dict or None + Exact and normalized JSON strings, plus changed header count. Only + the final user message's explicitly recorded memory block is eligible. + Unknown or ambiguous blocks yield unavailable normalization. + + """ + if event is None: + return None + artifact = event.exact_content.get("01_structured_messages", {}) + messages = artifact.get("value") + if not isinstance(messages, list) or not all( + isinstance(m, dict) and isinstance(m.get("content"), str) + for m in messages): + return None + result = {"raw": _key(messages), "normalized": _key(messages), + "headers": 0, "issue": None} + # Only the final user message is supplied by the memory formatter. + if not messages or messages[-1].get("role") != "user": + return result + text = messages[-1]["content"] + if _MEMORY_HEADING not in text: + return result + try: + if text.count(_MEMORY_HEADING) != 1: + raise ValueError("Ambiguous conversation memory block.") + prior = [e for e in op.matching("conversation_memory.retrieved") + if e.sequence < event.sequence] + if not prior: + raise ValueError("Missing preceding selected-memory record.") + hits = prior[-1].details["selected_memories"] + prefix, block = text.split(_MEMORY_HEADING, 1) + lines = block.split("\n") + indices = [i for i, line in enumerate(lines) + if line.startswith("Memory M")] + if not hits or len(indices) != len(hits): + raise ValueError("Memory header coverage differs from selection.") + local_turns: dict[str, str] = {} + for i, record in zip(indices, hits, strict=True): + local_turn = local_turns.setdefault( + record["turn_uuid"], f"T{len(local_turns) + 1}" + ) + lines[i] = _header( + record, lines[i], turns, conversations, local_turn + ) + normalized = deepcopy(messages) + normalized[-1]["content"] = (prefix + _MEMORY_HEADING + + "\n".join(lines)) + result.update(normalized=_key(normalized), headers=len(indices)) + except (KeyError, ValueError, TypeError, AttributeError) as error: + result.update(normalized=None, issue=str(error)) + return result + + +def _functional_tool(value: object) -> tuple[object, dict]: + """Separate known tool timing fields, not arbitrary numeric results. + + Parameters + ---------- + value: object + Raw saved tool summary or absent value. + + """ + if not isinstance(value, dict): + return value, {} + functional = deepcopy(value) + timing = {key: functional.pop(key) for key in sorted(_TIMING) + if key in functional} + plan = functional.get("plan") + if isinstance(plan, dict): + for key in ("estimated_seconds", "quick_seconds"): + if key in plan: + timing["plan." + key] = plan.pop(key) + return functional, timing + + +def _completion(tool: object, completion: object, *, + execution_count: int | None = None, + finish_reason: object = None) -> dict: + """Describe explicit incomplete outcomes without judging answer quality. + + Parameters + ---------- + tool: object + Saved tool summary, if recorded. + completion: object + Saved completion metadata, if recorded. + execution_count: int | None, optional + Number of recorded tool starts. None means execution is unknown. + finish_reason: object, optional + Saved final model termination reason, if recorded. + + """ + a = tool if isinstance(tool, dict) else {} + b = completion if isinstance(completion, dict) else {} + failures = [v for v in (a.get("status"), b.get("status")) + if isinstance(v, str) and v in _FAILURES] + if tool is None and execution_count == 0: + status = "not_applicable" + elif tool is None and execution_count is None: + status = "unknown" + elif (a.get("valid") is False or failures or + a.get("incomplete_items") or b.get("incomplete_items") or + finish_reason == "length"): + status = "incomplete" + elif a.get("valid") is True or a.get("status") in ( + "completed", "complete", "success", "ok") or b.get("status") in ( + "completed", "complete", "success", "ok"): + status = "complete" + else: + # A returned tool.run span or saved filename alone does not prove + # that every requested task was successfully completed. + status = "unknown" + return {"status": status, "tool": a.get("name"), + "tool_status": a.get("status"), "valid": a.get("valid"), + "completion": b, "problems": a.get("problems"), + "execution_count": execution_count, "finish_reason": finish_reason, + "incomplete_items": a.get("incomplete_items"), + "saved": {k: a[k] for k in ("report", "saved", "saved_pdf") + if k in a}} + + +def tool_comparison(tool: dict, completion: dict, *, + executions: dict | None = None, + finish_reasons: dict | None = None) -> dict: + """Keep raw tool summaries in the report and compare functional fields. + + Parameters + ---------- + tool: dict + Original and replayed saved tool summaries. + completion: dict + Original and replayed saved completion metadata. + executions: dict | None, optional + Recorded tool-start counts by side. + finish_reasons: dict | None, optional + Saved termination reasons by side. + + """ + functional, timings, outcomes = {}, {}, {} + for side in ("original", "replayed"): + functional[side], timings[side] = _functional_tool(tool[side]) + outcomes[side] = _completion( + tool[side], completion[side], + execution_count=(executions or {}).get(side), + finish_reason=(finish_reasons or {}).get(side)) + a, b = (outcomes[s]["status"] for s in ("original", "replayed")) + transition = { + ("complete", "complete"): "complete_reproduced", + ("incomplete", "incomplete"): "incomplete_reproduced", + ("complete", "incomplete"): "potential_regression", + ("incomplete", "complete"): "possible_improvement", + ("not_applicable", "not_applicable"): "not_applicable", + }.get((a, b), "unknown" if "unknown" in (a, b) else "changed") + return {"functional": functional, "timing": timings, + "functional_equal": functional["original"] == + functional["replayed"], "outcomes": outcomes, + "transition": transition} + + +def independent_questions(recording: Recording, + report: ValidationReport) -> list[dict]: + """Expose unique decodable saved questions independently of alignment. + + Parameters + ---------- + recording: Recording + Independently read workspace snapshot. + report: ValidationReport + Validation of that snapshot. + + Returns + ------- + list[dict] + Saved questions corroborated by a save event and a unique matching + canonical turn. Invalid-recording rows are explicitly unverified. + Ambiguous or unavailable saved text is not reconstructed. + + """ + turns = {} + ambiguous = set() + for state in recording.states.values(): + for turn in state.get("turns", []): + uid = turn.get("conversation_turn_uuid") + if not isinstance(uid, str): + continue + if uid in turns and turns[uid] != turn: + ambiguous.add(uid) + turns[uid] = turn + events = [e for e in report.events if e.event_type == "gui.question.saved"] + counts = Counter(e.details.get("conversation_turn_uuid") for e in events + if isinstance(e.details.get("conversation_turn_uuid"), + str)) + operations = {event.sequence: op for op in report.operations + if op.kind == "ask" for event in op.matching( + "gui.question.saved")} + rows = [] + for event in events: + uid = event.details.get("conversation_turn_uuid") + if not isinstance(uid, str) or counts[uid] != 1 or uid in ambiguous: + continue + turn = turns.get(uid, {}) + if not all(isinstance(turn.get(k), str) + for k in ("question", "answer")): + continue + parameters = turn.get("parameters") or {} + if not isinstance(parameters, dict): + parameters = {} + op = operations.get(event.sequence) + count = (len(op.matching("tool.run.started")) + if op is not None else None) + rows.append({"sequence": event.sequence, "trace": event.path, + "turn_uuid": uid, "validated": report.valid, + "question": turn["question"], "answer": turn["answer"], + "intent": parameters.get("intent"), + "completion": parameters.get("completion"), + "finish_reason": parameters.get("finish_reason"), + "tool_outcome": _completion( + parameters.get("tool"), parameters.get("completion"), + execution_count=count, + finish_reason=parameters.get("finish_reason"))}) + return rows diff --git a/kilin/system_testing/_comparison_metrics.py b/kilin/system_testing/_comparison_metrics.py new file mode 100644 index 00000000..4a6aa58f --- /dev/null +++ b/kilin/system_testing/_comparison_metrics.py @@ -0,0 +1,1128 @@ +"""Measure recorded text, retrieval, model calls, and file inventories. + +Key Features +------------ +- Deterministic lexical and exact-passage metrics, without a model judge. +- Optional cosine similarity from one explicitly selected local evaluator. +- Recorded durations and token counts, with missing values left unavailable. + +Module Structure +---------------- +- Text, ranking, evidence, and trace-stage measurements. +- ``EmbeddingEvaluator`` owns one optional embedding session per comparison. +- ``inventory`` and ``file_changes`` compare retained file bytes. + +Examples +-------- +>>> from kilin.system_testing import Experiment +>>> # Experiment("010_original").compare().display() + +""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Collection +from datetime import datetime +from hashlib import sha256 +import math +import json +import os +from pathlib import Path +import re +import unicodedata + +from kilin._model_completion import strip_thinking + +from ._filesystem import is_incidental_metadata +from .timeline import TimelineOperation +from .traces import TraceEvent, safe_path + +__all__ = [] + +_CITATION = re.compile(r"\[(\d+(?:\s*,\s*\d+)*)\]") +_TOKENS = re.compile(r"\w+|[^\w\s]", re.UNICODE) +_RANKINGS = ( + "retrieval.semantic.ranked", "retrieval.lexical.ranked", + "retrieval.code.ranked", "retrieval.hybrid.ranked", + "retrieval.sources.ranked", +) + + +def normalized_text(text: str) -> str: + """Normalize display text without changing its case or punctuation. + + Parameters + ---------- + text: str + Recorded text, potentially including model thinking tags. + + Returns + ------- + str + Visible text in NFC with whitespace runs collapsed. Numbered + citations remain in the text; thinking is excluded. + + """ + return " ".join(unicodedata.normalize("NFC", strip_thinking(text)).split()) + + +def text_metrics(original: str, replayed: str) -> dict: + """Measure lexical agreement without claiming semantic correctness. + + Parameters + ---------- + original: str + Original saved or traced text. + replayed: str + Reproduced text. + + Returns + ------- + dict + Raw and normalized equality, visible character counts and multiset + token Dice/F1. Two empty token sets have no measured similarity. + + """ + first, second = normalized_text(original), normalized_text(replayed) + a, b = Counter(_TOKENS.findall(first)), Counter(_TOKENS.findall(second)) + count = sum(a.values()) + sum(b.values()) + return { + "exact_equal": original == replayed, + "normalized_equal": first == second, + "original_characters": len(first), "replayed_characters": len(second), + "token_f1": (2 * sum((a & b).values()) / count if count else None), + } + + +def _number(value: object) -> int | float | None: + """Return a finite nonnegative measurement, not a guessed zero. + + Parameters + ---------- + value: object + Recorded duration, count, or absent value. + + Returns + ------- + int | float | None + Valid measurement or None. + + """ + if type(value) in (int, float) and value >= 0: + if type(value) is int or math.isfinite(value): + return value + return None + + +def _count(value: object) -> int | None: + """Return a recorded integer count, including a genuine zero. + + Parameters + ---------- + value: object + Recorded count. + + Returns + ------- + int | None + Nonnegative integer or None. + + """ + return value if type(value) is int and value >= 0 else None + + +def _duration(event: TraceEvent) -> int | float | None: + """Use the explicit event duration, falling back to its result field. + + Parameters + ---------- + event: TraceEvent + One decoded diagnostic event. + + Returns + ------- + int | float | None + Recorded duration in milliseconds, if available. + + """ + return _number(event.metadata.get("duration_ms", + event.details.get("duration_ms"))) + + +def operation_duration(op: TimelineOperation) -> dict: + """Measure a command at its own recorded boundaries. + + Parameters + ---------- + op: TimelineOperation + Original or replayed command interval. + + Returns + ------- + dict + Duration and measurement basis; point events have no duration. + Cross-logger intervals use recorded UTC wall-clock timestamps. + + """ + first, last = op.events[0], op.events[-1] + if first.sequence == last.sequence: + return {"ms": None, "basis": None} + if (first.span_id is not None and first.span_id == last.span_id and + first.metadata["trace_id"] == last.metadata["trace_id"] and + _duration(last) is not None): + return {"ms": _duration(last), "basis": "span"} + start = datetime.fromisoformat(first.metadata["timestamp_utc"]) + end = datetime.fromisoformat(last.metadata["timestamp_utc"]) + return {"ms": _number((end - start).total_seconds() * 1000), + "basis": "utc_boundary"} + + +def _stage_summary(events: list[TraceEvent]) -> dict: + """Summarize one event type without adding nested stage times together. + + Parameters + ---------- + events: list[TraceEvent] + Events of one component and type in chronological order. + + Returns + ------- + dict + Occurrence count, available timing samples and total only when all + occurrences contain durations. + + """ + durations = [_duration(event) for event in events] + complete = bool(durations) and all(ms is not None for ms in durations) + return {"count": len(events), "duration_ms": durations, + "total_duration_ms": sum(durations) if complete else None, + "statuses": dict(sorted(Counter(e.metadata["status"] + for e in events).items()))} + + +def stage_metrics(original: TimelineOperation, + replayed: TimelineOperation) -> list[dict]: + """Compare diagnostic event counts and explicit timing by stage type. + + Parameters + ---------- + original: TimelineOperation + Aligned original operation. + replayed: TimelineOperation + Aligned replay operation. + + Returns + ------- + list[dict] + Per-component, per-event-type observations. Inclusive nested span + durations are not a decomposition of total wall time. + + """ + groups = [] + for op in (original, replayed): + values = {} + for event in op.events: + key = event.metadata["component"], event.event_type + values.setdefault(key, []).append(event) + groups.append(values) + first, second = groups + return [{"component": key[0], "event_type": key[1], + "original": _stage_summary(first.get(key, [])), + "replayed": _stage_summary(second.get(key, []))} + for key in sorted(first.keys() | second.keys())] + + +def passage_identity(record: dict) -> dict: + """Describe an exact passage by source coordinates and text digest. + + Parameters + ---------- + record: dict + Saved evidence or traced chunk metadata, using managed relative + source paths rather than absolute workspace or external paths. + + Returns + ------- + dict + Source coordinates, symbol, optional section/cell, and SHA-256 of + the exact text. Generated chunk identifiers and scores are excluded. + + """ + path = record["path"] + if not isinstance(path, str) or not path: + raise ValueError("Invalid passage source path.") + start, end = record["start_line"], record["end_line"] + if (type(start) is not int or type(end) is not int or + start < 1 or end < start): + raise ValueError("Invalid passage line coordinates.") + digest = record.get("text_sha256") + if "text" in record: + digest = sha256(record["text"].encode("utf-8")).hexdigest() + if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", + digest): + raise ValueError("Missing exact passage content hash.") + return {"path": path, "start_line": start, "end_line": end, + "symbol": record.get("symbol"), "cell": record.get("cell"), + "section": record.get("section"), "text_sha256": digest} + + +def _key(item: dict) -> tuple: + """Build a hashable passage identity without comparing ranking scores. + + Parameters + ---------- + item: dict + Exact passage identity. + + Returns + ------- + tuple + Stable ordered identity fields. + + """ + return tuple(item.get(key) for key in ("path", "start_line", "end_line", + "symbol", "cell", "section", + "text_sha256")) + + +def overlap(original: list[dict], replayed: list[dict]) -> dict: + """Measure exact and source-level overlap, including rank displacement. + + Parameters + ---------- + original: list[dict] + Original passage identities in recorded order. + replayed: list[dict] + Replay passage identities in recorded order. + + Returns + ------- + dict + Unique set overlap and mean absolute displacement of common exact + passages, based on first occurrence positions. Empty unions and no + common ranks have no measured similarity or displacement. + + """ + ranks = [] + for items in (original, replayed): + positions = {} + for i, item in enumerate(items, 1): + positions.setdefault(_key(item), i) + ranks.append(positions) + first, second = ranks + common = first.keys() & second.keys() + union = first.keys() | second.keys() + paths_a = {item["path"] for item in original} + paths_b = {item["path"] for item in replayed} + paths = paths_a | paths_b + depth = min(len(original), len(replayed)) + # Compare the same available prefix depth, without arbitrary top-k cuts. + prefix_a = {_key(item) for item in original[:depth]} + prefix_b = {_key(item) for item in replayed[:depth]} + return { + "original_count": len(original), "replayed_count": len(replayed), + "original_unique": len(first), "replayed_unique": len(second), + "common": len(common), "union": len(union), + "jaccard": len(common) / len(union) if union else None, + "source_jaccard": (len(paths_a & paths_b) / len(paths) + if paths else None), + "prefix_depth": depth, + "prefix_overlap": (len(prefix_a & prefix_b) / depth if depth + else None), + "mean_absolute_rank_shift": ( + sum(abs(first[key] - second[key]) for key in common) / len(common) + if common else None + ), + } + + +def _evidence(turn: dict) -> tuple[list[dict], list[dict], list[str]]: + """Resolve visible numeric citations against the saved evidence list. + + Parameters + ---------- + turn: dict + Authoritative saved question, answer and evidence record. + + Returns + ------- + tuple + Evidence identities, cited identities in first-use order, and + unmatched citation numbers. This is syntactic, not a support check. + + """ + passages = [] + citations = {} + for item in turn["evidence"]: + identity = passage_identity(item) + number = item["citation"] + if type(number) is not int or number < 1 or str(number) in citations: + raise ValueError("Invalid or duplicate saved citation number.") + passages.append(identity) + citations[str(number)] = identity + cited = [] + missing = [] + seen = set() + for group in _CITATION.findall(strip_thinking(turn["answer"])): + for number in group.split(","): + number = number.strip().lstrip("0") or "0" + if number in seen: + continue + seen.add(number) + if number in citations: + cited.append(citations[number]) + else: + missing.append(number) + return passages, cited, missing + + +def evidence_metrics(original: dict, replayed: dict) -> dict: + """Compare saved evidence and actual syntactically cited passages. + + Parameters + ---------- + original: dict + Original saved turn. + replayed: dict + Corresponding replayed saved turn. + + Returns + ------- + dict + Both passage inventories, overlap metrics, and unresolved citations. + + """ + a, cited_a, missing_a = _evidence(original) + b, cited_b, missing_b = _evidence(replayed) + return {"original": a, "replayed": b, "overlap": overlap(a, b), + "citations": {"original": cited_a, "replayed": cited_b, + "overlap": overlap(cited_a, cited_b), + "original_unresolved": missing_a, + "replayed_unresolved": missing_b}} + + +def _ranked(event: TraceEvent) -> list[dict]: + """Read one complete recorded ranking in its recorded rank order. + + Parameters + ---------- + event: TraceEvent + Ranked retrieval diagnostic. + + Returns + ------- + list[dict] + Exact passage identities in rank order. + + """ + if event.event_type == "retrieval.sources.ranked": + rows = event.details["sources"] + if (not isinstance(rows, list) or not all( + isinstance(row.get("path"), str) and row["path"] + for row in rows)): + raise ValueError("Invalid source ranking diagnostic.") + return [{"path": row["path"]} for row in rows] + rows = event.details["results"] + if (not isinstance(rows, list) or event.details["count"] != len(rows) + or any(row["rank"] != i for i, row in enumerate(rows, 1))): + raise ValueError("Invalid ranked retrieval diagnostic.") + return [passage_identity(row["chunk"]) for row in rows] + + +def ranking_metrics(original: TimelineOperation, + replayed: TimelineOperation) -> list[dict]: + """Compare ranked events by channel and occurrence, not generated IDs. + + Parameters + ---------- + original: TimelineOperation + Aligned original operation. + replayed: TimelineOperation + Aligned replay operation. + + Returns + ------- + list[dict] + One row per channel occurrence, with absent sides left unavailable. + Occurrence pairing is descriptive; a changed pipeline may have + changed the query or purpose of a particular search. + + """ + comparisons = [] + for kind in _RANKINGS: + old, new = original.matching(kind), replayed.matching(kind) + for i in range(max(len(old), len(new))): + row = {"event_type": kind, "occurrence": i + 1, + "identity": ("source_path" if kind == + "retrieval.sources.ranked" else "passage")} + errors = [] + for side, events in (("original", old), ("replayed", new)): + row[side] = None + if i < len(events): + try: + row[side] = _ranked(events[i]) + except (ValueError, TypeError, KeyError, + AttributeError) as error: + errors.append(f"{side}: {error}") + a, b = row["original"], row["replayed"] + row["overlap"] = None + if a is not None and b is not None: + try: + row["overlap"] = overlap(a, b) + except (ValueError, TypeError, KeyError, + AttributeError) as error: + errors.append(str(error)) + row["issues"] = errors + comparisons.append(row) + return comparisons + + +def _artifact_text(event: TraceEvent | None, name: str) -> str | None: + """Read an inline exact-text artifact without following external paths. + + Parameters + ---------- + event: TraceEvent | None + Diagnostic containing the artifact, if any. + name: str + Exact-content section key from the trace writer. + + Returns + ------- + str | None + Exact text or None when absent. + + """ + if event is not None: + section = event.exact_content.get(name) + if isinstance(section, dict) and isinstance(section.get("value"), str): + return section["value"] + return None + + +def _snapshot_revision(data: dict) -> str | None: + """Recognize a recorded Hugging Face snapshot without reading its path. + + Parameters + ---------- + data: dict + Recorded model-call input metadata. + + Returns + ------- + str | None + Recorded commit hash, only for a matching repository snapshot. + Local model files without a recorded revision remain unverified. + + """ + model, source = data.get("model_id"), data.get("model_source") + if not isinstance(model, str) or not isinstance(source, str): + return None + parts = source.replace("\\", "/").rstrip("/").split("/") + if (len(parts) >= 3 and parts[-3] == "models--" + model.replace("/", "--") + and parts[-2] == "snapshots" and + re.fullmatch(r"[0-9a-f]{40}", parts[-1])): + return parts[-1] + return None + + +def model_calls(op: TimelineOperation) -> list[dict]: + """Correlate LLM inputs and outputs by call identity within a command. + + Parameters + ---------- + op: TimelineOperation + One recorded operation, including router and tool calls. + + Returns + ------- + list[dict] + Chronological call metadata, token counts, timing, finish reason, + and optional exact-text artifacts. Missing output is not zero tokens. + Repeated or unpaired call identities remain explicitly ambiguous. + + """ + inputs = op.matching("llm.call.input") + outputs = op.matching("llm.call.output") + matches = {} + for event in outputs: + matches.setdefault((event.metadata["trace_id"], + event.details.get("call_id")), []).append(event) + counts = Counter((e.metadata["trace_id"], e.details.get("call_id")) + for e in inputs) + rows = [] + for event in inputs: + data = event.details + key = event.metadata["trace_id"], data.get("call_id") + ends = matches.get(key, []) + valid = (isinstance(key[1], str) and counts[key] == 1 and + len(ends) == 1 and ends[0].sequence > event.sequence) + end = ends[0] if valid else None + result = end.details if end is not None else {} + rows.append({ + "input_sequence": event.sequence, + "output_sequence": end.sequence if end is not None else None, + "model_id": data.get("model_id"), "backend": data.get("backend"), + "model_source": data.get("model_source"), + "device": data.get("device"), + "resolved_revision": _snapshot_revision(data), + "thinking": data.get("thinking"), + "generation": data.get("generation"), + "chat_template": data.get("chat_template"), + "input_tokens": _count(data.get("input_token_count")), + "output_tokens": _count(result.get("output_token_count")), + "output_token_count_source": result.get( + "output_token_count_source"), + "finish_reason": result.get("finish_reason"), + "generation_duration_ms": _number(result.get( + "generation_duration_ms", end.metadata.get("duration_ms") + if end is not None else None)), + "reply_duration_ms": _number(result.get("reply_duration_ms")), + "output_available": valid, + "prompt": _artifact_text(event, "02_rendered_prompt"), + "answer": _artifact_text(end, "01_generated_answer"), + }) + used = {row["output_sequence"] for row in rows} + for event in outputs: + if event.sequence not in used: + rows.append({"input_sequence": None, + "output_sequence": event.sequence, + "output_available": False, + "issue": "Unpaired or ambiguous model output."}) + return rows + + +def _inference_settings(row: dict) -> dict | None: + """Require the producer's effective settings, not requested defaults. + + Parameters + ---------- + row: dict + One correlated model-call observation. + + Returns + ------- + dict | None + Complete recorded generation and template settings, or unavailable. + + """ + generation, template = row.get("generation"), row.get("chat_template") + if not isinstance(generation, dict) or not isinstance(template, dict): + return None + temperature = _number(generation.get("temperature")) + limit = generation.get("max_new_tokens") + thinking = row.get("thinking") + if (temperature is None or type(limit) is not int or limit <= 0 or + type(thinking) is not bool or + any(type(generation.get(k)) is not bool for k in ( + "sampling", "cjk_blocking_requested", "cjk_tokens_blocked")) + or _count(generation.get("cjk_suppressed_token_count")) is None + or type(template.get("add_generation_prompt")) is not bool + or type(template.get("enable_thinking")) is not bool): + return None + # Retain every recorded field, including future additional settings. + settings = {"generation": generation, "chat_template": template, + "thinking": thinking} + try: + json.dumps(settings, allow_nan=False, sort_keys=True) + except (TypeError, ValueError): + return None + return settings + + +def inference_comparison(original: dict | None, replayed: dict | None, + text: dict) -> dict: + """Compare effective inference inputs and observed output reproducibility. + + Parameters + ---------- + original: dict | None + Original model-call row, if present. + replayed: dict | None + Corresponding model-call row, if present. + text: dict + Existing exact-text and structured-prompt comparison flags. + + Returns + ------- + dict + Independent tri-state equality observations and conditional category. + Equal recorded settings are not proof of equal model binaries or + complete backend state. Normalized prompts are never used as exact + inputs for conditional reproducibility. + + """ + left, right = original or {}, replayed or {} + fields = ("model_id", "resolved_revision", "backend", "device") + model = None + if all(isinstance(row.get(k), str) and row[k] for row in (left, right) + for k in fields): + model = all(left[k] == right[k] for k in fields) + else: + # Known differences remain observable even if revision is unknown. + if any(isinstance(left.get(k), str) and isinstance(right.get(k), str) + and left[k] != right[k] for k in fields): + model = False + a, b = _inference_settings(left), _inference_settings(right) + settings = a == b if a is not None and b is not None else None + prompt = (text.get("prompt") or {}).get("exact_equal") + answer = (text.get("answer") or {}).get("exact_equal") + finish = None + if all(isinstance(row.get("finish_reason"), str) + for row in (left, right)): + finish = left["finish_reason"] == right["finish_reason"] + tokens = None + if all(_count(row.get("input_tokens")) is not None + for row in (left, right)): + tokens = left["input_tokens"] == right["input_tokens"] + category = None + if (model is True and settings is True and prompt is True and + tokens is True): + generation = a["generation"] + if (generation["temperature"] == 0 and not generation["sampling"]): + category = "zero_temperature" + elif generation["temperature"] > 0 and generation["sampling"]: + category = "nonzero_temperature" + return {"model_equal": model, "settings_equal": settings, + "rendered_prompt_equal": prompt, "input_token_count_equal": tokens, + "normalized_structured_prompt_equal": text.get( + "structured_normalized_equal"), + "output_equal": answer, "finish_reason_equal": finish, + "conditional_category": category} + + +_INFERENCE_FLAGS = ( + "model_equal", "settings_equal", "rendered_prompt_equal", + "input_token_count_equal", "normalized_structured_prompt_equal", + "output_equal", + "finish_reason_equal", +) +_CONDITIONAL = ("zero_temperature", "nonzero_temperature") + + +def inference_summary(operations: list[dict]) -> dict: + """Aggregate model-call comparison coverage over matched commands. + + Parameters + ---------- + operations: list[dict] + Aligned operation comparisons. + + Returns + ------- + dict + Paired/unpaired counts, flag denominators and conditional output + agreement. Unknown output text never contributes an equality value. + Model calls outside matched commands are not included. + + """ + rows = [row for op in operations for row in op.get("model_calls") or []] + sides = {side: sum(isinstance(row.get(side), dict) and + row[side].get("input_sequence") is not None + for row in rows) for side in ("original", "replayed")} + paired = [row for row in rows if all( + isinstance(row.get(side), dict) and + row[side].get("input_sequence") is not None + for side in ("original", "replayed"))] + result = {"input_calls": sides, "paired_calls": len(paired), + "unpaired_inputs": {s: n - len(paired) + for s, n in sides.items()}, + "unavailable_operations": sum( + op.get("model_calls") is None for op in operations), + "agreement": {}, "conditional": {}} + diagnostics = [row.get("inference", {}) for row in paired] + for key in _INFERENCE_FLAGS: + values = [d[key] for d in diagnostics if type(d.get(key)) is bool] + result["agreement"][key] = {"equal": sum(values), + "available": len(values), + "total": len(paired)} + for key in _CONDITIONAL: + eligible = [d for d in diagnostics + if d.get("conditional_category") == key] + outputs = [d["output_equal"] for d in eligible + if type(d.get("output_equal")) is bool] + result["conditional"][key] = { + "identical_inputs": len(eligible), + "available_outputs": len(outputs), + "equal_outputs": sum(outputs), + } + return result + + +_TIMING_SPANS = { + "initialization": ("gui.project.open",), + "indexing": ("indexing",), + "model_loading": ("model.chat.load", "model.embedding.load"), + "retrieval_and_embeddings": ( + "retrieval.semantic", "retrieval.lexical", "retrieval.code", + "embedding.calculate"), + "model_inference": ("llm.call",), + "question_duration": ("gui.question.request",), +} + + +def _union_duration(intervals: list[tuple[float, float]]) -> float: + """Measure the union of intervals in one logger's monotonic clock. + + Parameters + ---------- + intervals: list[tuple[float, float]] + Known start/end times in milliseconds. + + Returns + ------- + float + Nonduplicated inclusive duration within this clock domain. + + """ + total, end = 0., None + for start, stop in sorted(intervals): + if end is None or start >= end: + total += stop - start + end = stop + elif stop > end: + total += stop - end + end = stop + return total + + +def _span_timing(events: tuple[TraceEvent, ...], kinds: tuple[str, ...] + ) -> dict: + """Measure corroborated spans once, merging nested clock intervals. + + Parameters + ---------- + events: tuple[TraceEvent, ...] + Independently decoded recording events. + kinds: tuple[str, ...] + Selected span event-type stems. + + Returns + ------- + dict + Span coverage and measured union duration. Different categories can + overlap; even complete category times are not an additive breakdown. + + """ + starts, ends = {}, {} + for event in events: + stem, _, phase = event.event_type.rpartition(".") + if stem not in kinds or phase not in ("started", "completed", + "failed", "cancelled"): + continue + key = (event.metadata.get("trace_id"), event.span_id, stem) + group = starts if phase == "started" else ends + group.setdefault(key, []).append(event) + intervals = {} + available = 0 + for key in starts.keys() | ends.keys(): + a, b = starts.get(key, []), ends.get(key, []) + if len(a) != 1 or len(b) != 1 or not key[0] or not key[1]: + continue + start = _number(a[0].metadata.get("started_elapsed_ms")) + duration = _duration(b[0]) + if (start is None or duration is None or + a[0].sequence >= b[0].sequence or + b[0].metadata.get("started_elapsed_ms") != start): + continue + intervals.setdefault(key[0], []).append((start, start + duration)) + available += 1 + count = len(starts.keys() | ends.keys()) + return {"duration_ms": math.fsum(_union_duration(group) for group in + intervals.values()) if available else None, + "available": available, "total": count} + + +def performance_summary(events: tuple[TraceEvent, ...]) -> dict: + """Measure independent recorded timing categories and reply throughput. + + Parameters + ---------- + events: tuple[TraceEvent, ...] + All events of a closed recording, including outside-command calls. + + Returns + ------- + dict + Coverage-aware span timings and output-token throughput. Generation + duration is taken from the output event (the producer records that + same duration in its metadata). Throughput includes only measured + generated-token counts from MLX or PyTorch, with positive durations. + Reply time includes prompt work; neither rate is guaranteed to be + pure decoding throughput. + + """ + timing = {key: _span_timing(events, kinds) + for key, kinds in _TIMING_SPANS.items()} + # Use the same input/output identity correlation as the call comparison. + op = TimelineOperation("performance", 0, 0, "completed", {}, events) + calls = model_calls(op) + result = {"spans": timing, "throughput": {}} + recorded = [row["output_tokens"] for row in calls + if row.get("output_available") and + row.get("output_tokens") is not None] + result["output_tokens"] = { + "recorded_total": sum(recorded) if recorded else None, + "available": len(recorded), "total": len(calls), + } + for kind in ("generation", "reply"): + samples = [(row["output_tokens"], row[kind + "_duration_ms"]) + for row in calls if row.get("output_available") and + row.get("output_token_count_source") in ( + "generated_tokens", "generated_token_ids") and + row.get("output_tokens") is not None and + row.get(kind + "_duration_ms") is not None and + row[kind + "_duration_ms"] > 0] + tokens = sum(n for n, _ in samples) + duration = math.fsum(ms for _, ms in samples) + result["throughput"][kind] = { + "tokens": tokens if samples else None, + "duration_ms": duration if samples else None, + "tokens_per_second": 1000 * tokens / duration if samples else None, + "available": len(samples), "total": len(calls), + } + return result + + +def usage(turn: dict) -> dict: + """Read saved total chat-model usage without double-counting calls. + + Parameters + ---------- + turn: dict + Saved turn with historical parameter snapshot. + + Returns + ------- + dict + Original saved input and output token counts, or None if absent. + These cover the chat and router counters, not embedding token use. + + """ + values = turn["parameters"].get("usage", {}) + if not isinstance(values, dict): + values = {} + return {key: _count(values.get(key)) for key in ( + "input_tokens", "output_tokens")} + + +def cosine(first: list[float], second: list[float]) -> float: + """Compute cosine similarity with finite nonzero equal-size vectors. + + Parameters + ---------- + first: list[float] + Evaluation embedding of the original text. + second: list[float] + Evaluation embedding of the replayed text. + + Returns + ------- + float + Cosine in [-1, 1], with only floating-point rounding clamped. + + """ + if (not first or len(first) != len(second) or + not all(type(value) in (int, float) and math.isfinite(value) + for values in (first, second) for value in values)): + raise ValueError("Invalid or incompatible evaluation embeddings.") + a, b = math.hypot(*first), math.hypot(*second) + if not a or not b or not math.isfinite(a) or not math.isfinite(b): + raise ValueError("Invalid evaluation embedding norm.") + return max(-1.0, min(1.0, math.fsum((x / a) * (y / b) + for x, y in zip(first, second)))) + + +class EmbeddingEvaluator: + """Own one local model instance for optional symmetric answer metrics.""" + + def __init__(self, model: str | None, backend: str, + revision: str | None) -> None: + """Store evaluation provenance without loading a model yet. + + Parameters + ---------- + model: str | None + Explicit local model ID/path, or None to disable embeddings. + backend: str + Selected backend preference. + revision: str | None + Optional explicit model revision. + + """ + self.session = None + self.provenance = {"model_id": model, "backend_preference": backend, + "requested_revision": revision, + "status": "disabled" if model is None else + "not_used", "error": None} + + def measure(self, original: str, replayed: str) -> dict: + """Use the same loaded model for both normalized visible answers. + + Parameters + ---------- + original: str + Original saved answer. + replayed: str + Replayed saved answer. + + Returns + ------- + dict + Cosine or None and a precise unavailable reason. No retries, + truncation, substitute models, or downloads are requested. + + """ + provenance = self.provenance + if provenance["status"] == "disabled": + return {"cosine": None, "reason": "disabled"} + first = normalized_text(original) + second = normalized_text(replayed) + if not first or not second: + return {"cosine": None, "reason": "empty visible answer"} + if provenance["status"] == "failed": + return {"cosine": None, "reason": provenance["error"]} + if self.session is None: + try: + from kilin.embeddings import EmbeddingSession + + self.session = EmbeddingSession( + provenance["model_id"], + backend=provenance["backend_preference"], + revision=provenance["requested_revision"], + allow_download=False, + ) + provenance.update(status="loaded", + backend=self.session.backend, + device=self.session.device, + model_source=self.session.model_source) + except Exception as error: + provenance.update(status="failed", error=str(error)) + return {"cosine": None, "reason": str(error)} + try: + vectors = self.session.embed_documents([first, second]) + if len(vectors) != 2: + raise ValueError("Expected two evaluation embeddings.") + return {"cosine": cosine(*vectors), "reason": None} + except Exception as error: + return {"cosine": None, "reason": str(error)} + + def close(self) -> None: + """Release the evaluator; retain any cleanup problem in provenance.""" + if self.session is not None: + try: + self.session.close() + except Exception as error: + self.provenance["cleanup_error"] = str(error) + finally: + self.session = None + + +def inventory(root: Path, directory: str, *, + recorded: Collection[str] = ()) -> dict: + """Hash retained regular files without opening linked or external paths. + + Parameters + ---------- + root: pathlib.Path + Resolved stable workspace root. + directory: str + Workspace-relative inventory folder. + recorded: collection of str, optional + Expected workspace-relative source paths, if available. + + Returns + ------- + dict + File records and explicit inspection errors. A missing folder is + distinguished from an empty folder. No files are created or repaired. + + """ + files = {} + issues = [] + exists = False + + def on_error(error: OSError) -> None: + """Collect traversal errors rather than hiding missing content. + + Parameters + ---------- + error: OSError + Error reported by the directory walk. + + """ + issues.append(str(error)) + + try: + path = safe_path(root, directory) + exists = path.exists() + if exists and not path.is_dir(): + raise ValueError(f"Not a directory: {directory}") + if exists: + for parent, dirs, names in os.walk(path, onerror=on_error): + dirs.sort() + for name in list(dirs): + child = Path(parent) / name + if child.is_symlink(): + dirs.remove(name) + issues.append(f"Linked directory: {child}") + for name in sorted(names): + child = Path(parent) / name + relative = child.relative_to(root).as_posix() + try: + safe_path(root, relative) + if not child.is_file(): + raise ValueError(f"Nonregular file: {relative}") + if is_incidental_metadata(child, relative, recorded): + continue + with child.open("rb") as stream: + before = os.fstat(stream.fileno()) + digest = sha256() + for block in iter(lambda: stream.read(1024 * 1024), + b""): + digest.update(block) + after = os.fstat(stream.fileno()) + fields = ("st_dev", "st_ino", "st_size", "st_mtime_ns", + "st_ctime_ns") + if any(getattr(before, key) != getattr(after, key) + for key in fields): + raise ValueError(f"File changed: {relative}") + files[relative] = {"size_bytes": after.st_size, + "sha256": digest.hexdigest()} + except (ValueError, OSError) as error: + issues.append(str(error)) + except (ValueError, OSError) as error: + issues.append(str(error)) + return {"exists": exists, "files": files, "issues": issues} + + +def file_changes(original: dict, replayed: dict) -> dict: + """Compare inventories by relative name and bytes, not modification time. + + Parameters + ---------- + original: dict + Original folder inventory. + replayed: dict + Replay folder inventory. + + Returns + ------- + dict + Missing, added, changed, and unchanged names. Incomplete inventories + have no asserted comparison; their individual errors are retained. + + """ + result = {"original": original, "replayed": replayed, "changes": None} + if (original["exists"] and replayed["exists"] and + not original["issues"] and not replayed["issues"]): + a, b = original["files"], replayed["files"] + result["changes"] = { + "removed": sorted(a.keys() - b.keys()), + "added": sorted(b.keys() - a.keys()), + "changed": sorted(k for k in a.keys() & b.keys() if a[k] != b[k]), + "unchanged": sorted(k for k in a.keys() & b.keys() + if a[k] == b[k]), + } + return result diff --git a/kilin/system_testing/_comparison_report.py b/kilin/system_testing/_comparison_report.py new file mode 100644 index 00000000..e46c5d0c --- /dev/null +++ b/kilin/system_testing/_comparison_report.py @@ -0,0 +1,548 @@ +"""Present and persist comparison results without modifying workspaces. + +Key Features +------------ +- Summarize measurements, coverage, divergence and file differences. +- Escape recorded strings when rendering Markdown. +- Save deterministic JSON and Markdown beside the two workspaces. + +Module Structure +---------------- +- ``markdown_report`` renders a compact human-readable report. +- ``save_reports`` writes the corresponding sibling report files. + +Examples +-------- +>>> from kilin.system_testing import Experiment +>>> # Experiment("010_original").compare().save() + +""" + +from html import escape +import json +import os +from pathlib import Path +from tempfile import NamedTemporaryFile + +__all__ = [] + + +def _cell(value: object) -> str: + """Escape arbitrary recorded text for a Markdown table cell. + + Parameters + ---------- + value: object + Recorded value or unavailable measurement. + + Returns + ------- + str + Safe single-line table cell text; None is represented as n/a. + + """ + if value is None: + return "n/a" + if type(value) is float: + return f"{value:.4g}" + if isinstance(value, (dict, list)): + value = json.dumps(value, ensure_ascii=False, sort_keys=True) + text = escape(" ".join(str(value).split()), quote=False) + for char in ("\\", "|", "`", "*", "_", "[", "]", "~"): + text = text.replace(char, "\\" + char) + return text + + +def _row(*values: object) -> str: + """Render one table row without interpreting recorded content. + + Parameters + ---------- + *values: object + Ordered cell values. + + Returns + ------- + str + Markdown table row. + + """ + return "| " + " | ".join(_cell(value) for value in values) + " |" + + +def markdown_report(data: dict) -> str: + """Render the comparison snapshot, keeping details in the JSON report. + + Parameters + ---------- + data: dict + Structured comparison snapshot. + + Returns + ------- + str + Markdown report with validation, coverage, operation and question + metrics, settings and final file differences. + + """ + a, b = data["original"], data["replayed"] + alignment = data["alignment"] + summary = data["summary"] + lines = ["# KíLín workspace comparison", "", + "This is a measurement report, not a correctness verdict.", "", + f"Alignment: **{_cell(alignment['status'])}**", ""] + if alignment["reason"] is not None: + lines.extend((f"Reason: {_cell(alignment['reason'])}", "")) + lines.extend(("| Workspace | Path | Valid recording | Events | Commands |", + "|---|---|---|---:|---:|", + _row("Original", a["path"], a["valid"], a["event_count"], + len(a["operations"])), + _row("Replayed", b["path"], b["valid"], b["event_count"], + len(b["operations"])), "", + f"Matched commands: {alignment['matched_operations']}. " + f"Matched committed questions: {summary['questions']}.", + "", "## Validation", "")) + for label, workspace in (("Original", a), ("Replayed", b)): + lines.append(f"### {label}") + lines.append("") + issues = workspace["validation_issues"] + if not issues: + lines.append("No blocking validation issues.") + for issue in issues: + lines.append(f"- {_cell(issue['code'])}: " + f"{_cell(issue['message'])} " + f"(sequence {_cell(issue['sequence'])}, " + f"{_cell(issue['path'])})") + for warning in workspace["validation_warnings"]: + lines.append(f"- Warning: {_cell(warning['message'])}") + lines.append("") + if "first_divergence" in data: + lines.extend(("## First observed divergence", "", + "Ordered by original trace sequence; not a causal " + "diagnosis. Later changes may be downstream.", "", + _cell(data["first_divergence"]), "")) + for key, label in (("reference_publication", "Reference publication"), + ("replay_execution", "Replay execution provenance")): + if key in data: + lines.extend((f"## {label}", "", _cell(data[key]), "")) + if any("plugin_provenance" in side for side in (a, b)): + lines.extend(("## Recorded plugin provenance", "", + "Unknown identities are not inferred from installed " + "plugins. Changed identities describe an environment " + "difference, not answer quality.", "", + "| Workspace | Recorded | Unknown | Invalid |", + "|---|---:|---:|---:|")) + for label, workspace in (("Original", a), ("Replayed", b)): + observations = workspace.get("plugin_provenance", []) + lines.append(_row(label, *(sum(item["status"] == status + for item in observations) + for status in ("recorded", "unknown", + "invalid")))) + lines.extend(("", "| Original seq. | Scope | Plugin | Status | " + "Original identity | Replayed identity |", + "|---:|---|---|---|---|---|")) + for op in data["operations"]: + for pair in op.get("plugin_provenance", []): + if pair["status"] != "equal": + lines.append(_row(op["original_sequence"], pair["scope"], + pair["name"], pair["status"], + (pair["original"] or {}).get("identity"), + (pair["replayed"] or {}).get( + "identity"))) + lines.append("") + if any(side.get("source_organization") for side in (a, b)): + lines.extend(("## Semantic source organization", "", + "Compared recorded semantic states and bound views, " + "not live preview tokens or project paths.", "", + "| Original seq. | Event | Occurrence | Equal |", + "|---:|---|---:|---|")) + for op in data["operations"]: + for pair in op.get("source_organization", []): + if pair["equal"] is not True: + lines.append(_row(op["original_sequence"], + pair["event_type"], pair["occurrence"], + pair["equal"])) + lines.append("") + inspection = data.get("inspection") + if inspection is not None: + lines.extend(("## Additional reference inspection", "", + _cell(inspection["message"]), "")) + lines.extend(("## Independently observed saved questions", "", + "Unverified text is not evidence of a valid recording.", + "", "| Workspace | Saved questions | Validated |", + "|---|---:|---:|")) + for side in ("original", "replayed"): + questions = data[side].get("saved_questions", []) + lines.append(_row(side, len(questions), sum( + q["validated"] for q in questions))) + lines.extend(("", "## Context, prompt and tool diagnostics", "", + "| Measurement | Equal | Available | Total |", + "|---|---:|---:|---:|")) + context = [item for op in data["operations"] + for item in op.get("context", [])] + calls = [call["text"] for op in data["operations"] + for call in op.get("model_calls") or []] + tools = [op["question"]["tool_comparison"] for op in data["operations"] + if "tool_comparison" in op.get("question", {})] + for label, values in ( + ("Mapped context identity", [c["identity_equal"] for c in context]), + ("Structured model input", [c.get("structured_raw_equal") + for c in calls]), + ("Metadata-normalized model input", [c.get( + "structured_normalized_equal") for c in calls]), + ("Functional tool summary", [t["functional_equal"] for t in tools]), + ): + lines.append(_row(label, sum(v is True for v in values), + sum(type(v) is bool for v in values), len(values))) + for side in ("original", "replayed"): + incomplete = [q["sequence"] for q in data[side].get( + "saved_questions", []) if q["tool_outcome"]["status"] == + "incomplete"] + if incomplete: + lines.extend(("", f"{side.capitalize()} explicitly incomplete " + f"saved outcomes: {_cell(incomplete)}.")) + lines.append("") + model = summary.get("model_reproducibility") + if model is not None: + lines.extend(("## Model-call reproducibility", "", + f"Paired input calls: {model['paired_calls']}; " + f"unpaired inputs: {_cell(model['unpaired_inputs'])}.", + "Matched operations only; stage and occurrence pairing " + "does not establish causal equivalence.", "", + "| Observation | Equal | Available | Paired calls |", + "|---|---:|---:|---:|")) + for name, metric in model["agreement"].items(): + lines.append(_row(name, metric["equal"], metric["available"], + metric["total"])) + lines.extend(("", "| Conditional category | Equal outputs | " + "Available outputs | Identical recorded inputs |", + "|---|---:|---:|---:|")) + for name, metric in model["conditional"].items(): + lines.append(_row(name, metric["equal_outputs"], + metric["available_outputs"], + metric["identical_inputs"])) + lines.extend(("", "Conditional agreement requires a recorded model " + "snapshot, backend, device, complete equal effective " + "settings, exact rendered prompt and input-token count. " + "Normalized prompts never qualify as identical input. " + "This is evidence about recorded inputs, not a " + "guarantee " + "of identical runtime state.", "")) + if "tool_transitions" in summary: + lines.extend(("## Recorded tool outcomes", "", + "| Original / replay outcome | Questions |", + "|---|---:|")) + for label, count in summary["tool_transitions"].items(): + lines.append(_row(label, count)) + lines.extend(("", "Unknown completion is not a failure or a success. " + "Historical generator coverage observations are not " + "current replay outcomes.", "")) + performance = data.get("performance") + if performance is not None: + lines.extend(("## Recorded performance categories", "", + "Complete workspace recordings, including calls outside " + "matched commands. Timings are inclusive across " + "categories; do not sum them. Within a category nested " + "intervals in the same logger are counted once.", "", + "| Category | Original ms | Coverage | Replay ms | " + "Coverage |", "|---|---:|---:|---:|---:|")) + kinds = dict.fromkeys(k for side in ("original", "replayed") + for k in (performance.get(side) or {}).get( + "spans", {})) + for kind in kinds: + values = [(performance.get(side) or {}).get("spans", {}).get( + kind, {}) for side in ("original", "replayed")] + lines.append(_row(kind, *(value for metric in values for value in ( + metric.get("duration_ms"), + f"{metric['available']}/{metric['total']}" if metric + else None)))) + lines.extend(("", "| Throughput | Original tokens/s | Coverage | " + "Replay tokens/s | Coverage |", + "|---|---:|---:|---:|---:|")) + for kind in ("generation", "reply"): + values = [(performance.get(side) or {}).get("throughput", {}).get( + kind, {}) for side in ("original", "replayed")] + lines.append(_row(kind, *(value for metric in values for value in ( + metric.get("tokens_per_second"), + f"{metric['available']}/{metric['total']}" if metric + else None)))) + lines.extend(("", "Only recorded generated-token counts with positive " + "timing enter throughput. Generation includes backend " + "prompt processing; reply includes additional overhead. " + "Uncontrolled execution conditions preclude performance " + "verdicts.", "")) + lines.extend(("## Question metrics", "", + "Each mean includes only available measurements. " + "An empty evidence union is not a similarity of zero.", + "", "| Metric | Mean | Available | Questions |", + "|---|---:|---:|---:|")) + for key in ("token_f1", "embedding_cosine", "evidence_jaccard", + "citation_jaccard"): + metric = summary[key] + lines.append(_row(key, metric["mean"], metric["available"], + metric["total"])) + lines.extend(("", f"Exact saved answers: {summary['exact_answers']}; " + f"normalized visible answers equal: " + f"{summary['normalized_equal_answers']}.", "", + "| Original seq. | Question | Token F1 | Cosine | " + "Evidence Jaccard | Citation Jaccard |", + "|---:|---|---:|---:|---:|---:|")) + for op in data["operations"]: + q = op.get("question") + if q is None: + continue + evidence = q["evidence"] + lines.append(_row(op["original_sequence"], q["question"], + q["answer"]["token_f1"], + q["answer"]["embedding"]["cosine"], + evidence["overlap"]["jaccard"] if evidence else None, + evidence["citations"]["overlap"]["jaccard"] + if evidence else None)) + evaluator = data["embedding_evaluation"] + lines.extend(("", "Embedding evaluation: " + _cell(evaluator), "", + "## Operations and recorded duration", "", + "Durations are milliseconds at the recorded boundaries; " + "point events have no measured duration. Nested stage " + "times are not summed into wall time.", "", + "| Original seq. | Replay seq. | Operation | Original ms | " + "Replay ms | Settings differences |", + "|---:|---:|---|---:|---:|---:|")) + for op in data["operations"]: + lines.append(_row(op["original_sequence"], op["replayed_sequence"], + op["kind"], op["duration"]["original"]["ms"], + op["duration"]["replayed"]["ms"], + len(op["settings_differences"]))) + for op in data["operations"]: + relocation = op.get("relocation") + if relocation is not None: + recorded = relocation["original"] + outcome = ("physical rename recorded" if relocation[ + "physical_rename_replayed"] else "replay directory retained") + lines.extend(("", "Project relocation at original sequence " + f"{op['original_sequence']}: " + f"{_cell(recorded['source_directory'])} to " + f"{_cell(recorded['destination_directory'])} " + f"({recorded['provenance']}); {outcome}.")) + for side in ("original", "replayed"): + unmatched = alignment[side + "_unmatched"] + if unmatched: + lines.extend(("", f"{side.capitalize()} unmatched commands: " + + str(len(unmatched)))) + duration = summary["paired_command_duration_ms"] + lines.extend(("", "Paired command duration (ms): " + f"{_cell(duration['original'])} / " + f"{_cell(duration['replayed'])}; " + f"{duration['available']}/{duration['total']} commands.", + "", "## Workspace token usage", "", + "Saved-turn usage and traced call usage have different " + "boundaries and must not be added together.", "", + "| Measurement | Original total | Original coverage | " + "Replay total | Replay coverage |", + "|---|---:|---|---:|---|")) + for key, unit in (("usage", "turns"), + ("traced_chat_usage", "records")): + for token in ("input_tokens", "output_tokens"): + values = [] + for side in (a, b): + metric = (side[key] or {}).get(token, {}) + available = metric.get("available_" + unit) + total = metric.get("total_" + unit) + values.extend((metric.get("recorded_total"), + f"{available}/{total}" if total is not None + else None)) + lines.append(_row(f"{key}.{token}", *values)) + state = data["final_state"] + lines.extend(("", "## Final mapped state", "", + "Final snapshots can include unmatched suffixes.", "", + "| Observation | Equal | Mapped |", "|---|---:|---:|")) + for key in ("name_equal", "archival_equal", "lineage_equal", + "turn_prefix_equal"): + records = state["conversations"] + lines.append(_row(key, sum(r[key] for r in records), len(records))) + records = state["feedback"] + lines.append(_row("feedback_equal", sum(r["equal"] for r in records), + len(records))) + lines.extend(("", "## Recorded settings differences", "", + "| Original seq. | Field | Original | Replayed |", + "|---:|---|---|---|")) + for op in data["operations"]: + for diff in op["settings_differences"]: + lines.append(_row(op["original_sequence"], diff["field"], + diff["original"], diff["replayed"])) + lines.extend(("", "## Per-question execution details", "")) + for op in data["operations"]: + q = op.get("question") + if q is None: + continue + lines.extend((f"### Original sequence {op['original_sequence']}", "", + "| Observation | Original | Replayed |", + "|---|---|---|", + _row("Intent", q["intent"]["original"], + q["intent"]["replayed"]), + _row("Retrieval mode", q["retrieval_mode"]["original"], + q["retrieval_mode"]["replayed"]), + _row("Tool summary", q["tool"]["original"], + q["tool"]["replayed"]), + _row("Input tokens", q["usage"]["original"][ + "input_tokens"], q["usage"]["replayed"][ + "input_tokens"]), + _row("Output tokens", q["usage"]["original"][ + "output_tokens"], q["usage"]["replayed"][ + "output_tokens"]), + _row("Saved trace", q["original_trace"], + q["replayed_trace"]), "")) + if "tool_comparison" in q: + tools = q["tool_comparison"] + if "transition" in tools: + lines.extend(("Recorded tool transition: " + + _cell(tools["transition"]), "", + "| Tool observation | Original | Replay |", + "|---|---|---|", + _row("Tool outcome", *( + tools["outcomes"][side] for side in + ("original", "replayed"))), "")) + calls = op.get("model_calls") or [] + if any("inference" in call for call in calls): + lines.extend(("| Stage | Occurrence | Model | Settings | " + "Exact prompt | Output | Finish reason |", + "|---|---:|---|---|---|---|---|")) + for call in calls: + flags = call.get("inference", {}) + lines.append(_row(call["stage"], call["occurrence"], *( + flags.get(k) for k in ("model_equal", "settings_equal", + "rendered_prompt_equal", + "output_equal", + "finish_reason_equal")))) + lines.append("") + if op["rankings"]: + lines.extend(("| Ranking channel | Occurrence | Exact Jaccard | " + "File Jaccard | Mean absolute rank shift |", + "|---|---:|---:|---:|---:|")) + for row in op["rankings"]: + metrics = row["overlap"] or {} + lines.append(_row(row["event_type"], row["occurrence"], + metrics.get("jaccard"), + metrics.get("source_jaccard"), + metrics.get("mean_absolute_rank_shift"))) + lines.append("") + for ranking in op["rankings"]: + for message in ranking["issues"]: + lines.append(f"- {_cell(ranking['event_type'])}: " + f"{_cell(message)}") + timed = [stage for stage in op["stages"] if any( + stage[side]["total_duration_ms"] is not None + for side in ("original", "replayed"))] + if timed: + lines.extend(("", "| Timed diagnostic stage | Original count | " + "Original ms | Replay count | Replay ms |", + "|---|---:|---:|---:|---:|")) + for stage in timed: + lines.append(_row(stage["event_type"], + stage["original"]["count"], + stage["original"]["total_duration_ms"], + stage["replayed"]["count"], + stage["replayed"]["total_duration_ms"])) + lines.append("") + for message in op["issues"] + q["issues"]: + lines.append(f"- {_cell(message)}") + error = q["answer"]["embedding"]["reason"] + if error not in (None, "disabled"): + lines.append(f"- Embedding unavailable: {_cell(error)}") + lines.append("") + lines.extend(("## Final file inventories", "", + "Compared by workspace-relative name, SHA-256, and size. " + "Byte differences do not establish semantic differences.", + "", "| Directory | Added | Removed | Changed | Unchanged |", + "|---|---:|---:|---:|---:|")) + for directory, result in data["files"].items(): + changes = result["changes"] + counts = ([len(changes[key]) for key in ( + "added", "removed", "changed", "unchanged")] + if changes is not None else [None] * 4) + lines.append(_row(directory, *counts)) + for directory, result in data["files"].items(): + changes = result["changes"] + lines.extend(("", f"### {_cell(directory)}", "")) + for side in ("original", "replayed"): + for issue in result[side]["issues"]: + lines.append(f"- {_cell(side)}: {_cell(issue)}") + if changes is not None: + for kind in ("added", "removed", "changed"): + for path in changes[kind]: + lines.append(f"- {kind}: {_cell(path)}") + if data.get("report_issues"): + lines.extend(("", "## Unavailable diagnostic values", "")) + for issue in data["report_issues"]: + lines.append(f"- {_cell(issue)}") + lines.extend(("", "The JSON report contains the full paired answer text, " + "mapped conversation and turn IDs, file hashes, all stage " + "measurements, model-call metadata and recorded outcomes. " + "It may contain sensitive project information.", "")) + return "\n".join(lines) + + +def save_reports(reference: Path, data: dict, markdown: str, *, + overwrite: bool) -> tuple[Path, Path]: + """Write two sibling report files, never a file inside either workspace. + + Parameters + ---------- + reference: pathlib.Path + Resolved original workspace path. + data: dict + JSON-compatible report snapshot. + markdown: str + Human-readable report text. + overwrite: bool + Explicit permission to replace existing regular report files. + + Returns + ------- + tuple[pathlib.Path, pathlib.Path] + Saved JSON and Markdown paths. + + Notes + ----- + Each file is published atomically. Both files are staged before either is + published, but the two-file publication is not a filesystem transaction. + Existing files or links are refused by default. No path is followed for + report writes, and no existing directory is removed. + + """ + if type(overwrite) is not bool: + raise ValueError("overwrite must be a Boolean.") + base = reference.name.removesuffix("_original") + "_comparison" + paths = (reference.with_name(base + ".json"), + reference.with_name(base + ".md")) + contents = (json.dumps(data, indent=2, ensure_ascii=False, + sort_keys=True, allow_nan=False) + "\n", markdown) + for path in paths: + if path.is_symlink() or (path.exists() and not path.is_file()): + raise ValueError(f"Not a regular report destination: {path}") + if not overwrite and path.exists(): + raise FileExistsError(f"Comparison report already exists: {path}") + temporary = [] + try: + for path, content in zip(paths, contents): + with NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", + prefix="." + path.name + ".", + dir=path.parent, delete=False) as stream: + temporary.append(Path(stream.name)) + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + for source, path in zip(temporary, paths): + if overwrite: + # Replace the directory entry rather than following a link. + # A concurrent change to a directory still fails normally. + if path.is_symlink(): + raise ValueError(f"Linked report destination: {path}") + os.replace(source, path) + else: + # Publish exclusively, so even a concurrent creator cannot + # be overwritten between the preflight and publication. + os.link(source, path) + finally: + for source in temporary: + source.unlink(missing_ok=True) + return paths diff --git a/kilin/system_testing/_filesystem.py b/kilin/system_testing/_filesystem.py new file mode 100644 index 00000000..a1032c40 --- /dev/null +++ b/kilin/system_testing/_filesystem.py @@ -0,0 +1,61 @@ +"""Recognize incidental filesystem metadata in managed test inventories. + +Key Features +------------ +- Exclude only narrowly identified, unrecorded regular metadata files. +- Keep source ownership and file safety checks independent of exclusion. + +Module Structure +---------------- +- ``is_incidental_metadata`` implements the shared inventory policy. + +Examples +-------- +>>> from pathlib import Path +>>> from tempfile import TemporaryDirectory +>>> from kilin.system_testing._filesystem import is_incidental_metadata +>>> with TemporaryDirectory() as directory: +... relative = ".DS_Store" +... path = Path(directory) / relative +... path.touch() +... print(is_incidental_metadata(path, relative)) +... print(is_incidental_metadata(path, relative, {relative})) +True +False + +""" + +from collections.abc import Collection +from pathlib import Path + +__all__ = [] + + +def is_incidental_metadata( + path: Path, relative: str, recorded: Collection[str] = (), +) -> bool: + """Identify a regular metadata file outside the recorded inventory. + + Parameters + ---------- + path: pathlib.Path + Physical file encountered during a managed inventory scan. + relative: str + Relative path in the same namespace as the recorded paths. + recorded: collection of str, optional + Authoritative expected paths. Recorded files are never excluded. + Defaults to an empty collection. + + Returns + ------- + bool + True only for an unrecorded regular Finder metadata file. + + Notes + ----- + Callers still reject links and nonregular entries before checking + this policy. No other protected or hidden filenames are excluded. + + """ + return (path.name == ".DS_Store" and relative not in recorded + and not path.is_symlink() and path.is_file()) diff --git a/kilin/system_testing/_first_divergence.py b/kilin/system_testing/_first_divergence.py new file mode 100644 index 00000000..7e4c4fdb --- /dev/null +++ b/kilin/system_testing/_first_divergence.py @@ -0,0 +1,295 @@ +"""Locate the first observed difference in an aligned system-test replay. + +The diagnostic reuses the recorded comparison observations, including +plugin provenance. It neither infers causality nor treats unavailable +observations as equal. + +Key Features +------------ +- Locate observed differences in the original recording's sequence order. +- Identify changed recorded plugin identities at their observed boundaries. +- Keep unavailable observations and unlocalized differences explicit. +- Identify later changed questions without asserting causal relationships. + +Module Structure +---------------- +- ``_sequence`` locates one event occurrence in a recorded operation. +- ``operation_divergence`` compares observations within aligned operations. +- ``first_divergence`` summarizes the earliest located difference and + subsequent changed questions across the comparison. + +Examples +-------- +>>> from kilin.system_testing._first_divergence import first_divergence +>>> first_divergence([], "partial")["status"] +'unavailable' +>>> first_divergence([], "complete")["first"] is None +True + +""" + +__all__ = [] + + +def _sequence(operation, event_type, occurrence=1): + """Return the sequence of a recorded event occurrence, if available. + + Parameters + ---------- + operation: TimelineOperation + Recorded operation containing the candidate events. + event_type: str + Type of event to locate. + occurrence: int, optional + One-based occurrence among matching events. Defaults to one. + + Returns + ------- + int or None + Recorded event sequence, or None when the occurrence is absent. + + """ + events = operation.matching(event_type) + if 0 < occurrence <= len(events): + return events[occurrence - 1].sequence + return None + + +def operation_divergence(row, original, replayed): + """Locate comparable differences within one aligned operation. + + Parameters + ---------- + row : dict + Existing operation comparison, including plugin identities, model calls + and context. + original: TimelineOperation + Aligned operation from the original recording. + replayed: TimelineOperation + Corresponding replayed operation, in its own sequence namespace. + + Returns + ------- + dict + Earliest observed difference in original event order, unlocalized + differences, and the number of unavailable observations. A sequence + in one recording is never compared numerically with the other. + + """ + differences = [] + unavailable = 0 + + def observe(equal, category, stage, a, b, detail=None): + """Retain differences and count unavailable observations. + + Parameters + ---------- + equal: bool or None + Comparison result; None indicates an unavailable observation. + category: str + Diagnostic classification of an observed difference. + stage: str + Recorded event or model-call stage associated with the result. + a: int or None + Sequence in the original recording, if known. + b: int or None + Corresponding sequence in the replayed recording, if known. + detail: str or int or None, optional + Comparison field, occurrence number, or explanatory detail. + + """ + nonlocal unavailable + if equal is None: + unavailable += 1 + elif equal is False: + differences.append({ + "category": category, "stage": stage, + "original_sequence": a, "replayed_sequence": b, + "detail": detail, + }) + + def event(equal, category, stage, occurrence=1, detail=None): + """Locate a difference at its recorded event occurrence. + + Parameters + ---------- + equal: bool or None + Comparison result; None indicates an unavailable observation. + category: str + Diagnostic classification of an observed difference. + stage: str + Event type used to locate the observation in both recordings. + occurrence: int, optional + One-based occurrence among matching events. Defaults to one. + detail: str or int or None, optional + Comparison field, occurrence number, or explanatory detail. + + """ + observe(equal, category, stage, + _sequence(original, stage, occurrence), + _sequence(replayed, stage, occurrence), detail) + + for difference in row.get("settings_differences", []): + field = difference.get("field", "") + for prefix, stage in ( + ("configuration", "gui.project.configuration.effective"), + ("question.resolved", "gui.question.settings.resolved"), + ("question.effective", "turn.settings.snapshot"), + ): + if field == prefix or field.startswith(prefix + "."): + event(False, "effective_settings", stage, detail=field) + break + + # Plugin observations are paired by scope, kind and name, not merely + # by the ordinal of their event type. Use their captured sequences. + # A missing or invalid identity cannot establish an implementation + # change; a one-sided observation may instead reflect changed routing. + plugin_stages = { + "open": "gui.project.configuration.effective", + "turn": "turn.settings.snapshot", + "execution": "tool.run.started", + } + for item in row.get("plugin_provenance", []): + equal = {"equal": True, "changed": False}.get(item["status"]) + observe(equal, "plugin_identity", plugin_stages[item["scope"]], + (item["original"] or {}).get("sequence"), + (item["replayed"] or {}).get("sequence"), + f"{item['kind']}: {item['name']}") + + for item in row.get("source_organization", []): + observe(item["equal"], "source_organization", item["event_type"], + (item["original"] or {}).get("sequence"), + (item["replayed"] or {}).get("sequence"), item["occurrence"]) + + for item in row.get("context", []): + stage = item["event_type"] + fields = ["identity_equal", "fingerprints_equal", + "priorities_equal", "historical_lookup_equal", + "enabled_equal"] + # Floating-point scores alone are not changes in selected context. + for field in fields: + if field in item: + event(item[field], "context", stage, item["occurrence"], + field) + for item in row.get("rankings", []): + a, b = item.get("original"), item.get("replayed") + equal = a == b if a is not None and b is not None else None + event(equal, "retrieval_ranking", item["event_type"], + item["occurrence"]) + + calls = row.get("model_calls") + if calls is None: + unavailable += 1 + for call in calls or []: + a, b = call.get("original"), call.get("replayed") + stage = call["stage"] + if a is None or b is None: + observe(False, "unmatched_model_call", stage, + (a or {}).get("input_sequence"), + (b or {}).get("input_sequence"), call["occurrence"]) + unavailable += 1 + continue + flags = call.get("inference", {}) + for field, category in (("model_equal", "model_identity"), + ("settings_equal", "model_settings"), + ("rendered_prompt_equal", "model_prompt"), + ("input_token_count_equal", "input_tokens")): + detail = field + if (field == "rendered_prompt_equal" and + flags.get("normalized_structured_prompt_equal") is True): + detail = "normalized structured prompts equal" + observe(flags.get(field), category, stage, + a.get("input_sequence"), b.get("input_sequence"), detail) + category = flags.get("conditional_category") + output = { + "zero_temperature": "zero_temperature_output", + "nonzero_temperature": "nonzero_temperature_output", + }.get(category, "output_with_unverified_or_changed_inputs") + observe(flags.get("output_equal"), output, stage, + a.get("output_sequence"), b.get("output_sequence")) + observe(flags.get("finish_reason_equal"), "finish_reason", stage, + a.get("output_sequence"), b.get("output_sequence")) + + question = row.get("question") + if question is not None: + for field, stage in (("intent", "intent.classification.decided"), + ("retrieval_mode", "retrieval.plan")): + pair = question.get(field, {}) + a, b = pair.get("original"), pair.get("replayed") + equal = a == b if a is not None and b is not None else None + event(equal, field, stage) + evidence = question.get("evidence") or {} + a, b = evidence.get("original"), evidence.get("replayed") + equal = a == b if a is not None and b is not None else None + event(equal, "evidence", "evidence.finalized") + tool = question.get("tool_comparison") or {} + if tool: + event(tool.get("functional_equal"), "tool_result", + "gui.question.saved") + event((question.get("answer") or {}).get("normalized_equal"), + "saved_answer", "gui.question.saved") + + located = [item for item in differences + if item["original_sequence"] is not None] + unlocalized = [item for item in differences + if item["original_sequence"] is None] + first = min(located, key=lambda item: item["original_sequence"], + default=None) + return {"first": first, "unlocalized": unlocalized, + "unavailable_observations": unavailable} + + +def first_divergence(operations, alignment): + """Summarize the earliest observed difference across aligned operations. + + Parameters + ---------- + operations : list of dict + Aligned operation comparisons in original command order. + alignment : str + Workspace alignment status. + + Returns + ------- + dict + Earliest located observation and later changed question numbers. + Unlocalized differences and missing coverage remain explicit. + + Notes + ----- + Later changes may be downstream effects, but the diagnostic does not + establish that relationship. It does not inspect unmatched commands, + generated titles outside commands, timing, or final file inventories. + + """ + first = None + later = [] + question_number = 0 + unlocalized = 0 + unavailable = 0 + for row in operations: + is_question = isinstance(row.get("question"), dict) + question_number += int(is_question) + diagnostic = row.get("divergence") + if diagnostic is None: + unavailable += 1 + continue + unlocalized += len(diagnostic["unlocalized"]) + unavailable += diagnostic["unavailable_observations"] + item = diagnostic["first"] + if item is not None and first is None: + first = {**item, "operation_sequence": row["original_sequence"], + "question_number": question_number if is_question + else None} + elif is_question and (item is not None or diagnostic["unlocalized"]): + later.append(question_number) + if first is not None or unlocalized: + status = "observed" + elif unavailable or alignment != "complete": + status = "unavailable" + else: + status = "not_observed" + return {"status": status, "alignment": alignment, "first": first, + "later_changed_questions": later, + "unlocalized_differences": unlocalized, + "unavailable_observations": unavailable} diff --git a/kilin/system_testing/_inspection.py b/kilin/system_testing/_inspection.py new file mode 100644 index 00000000..c6082fa0 --- /dev/null +++ b/kilin/system_testing/_inspection.py @@ -0,0 +1,174 @@ +"""Identify additional closed reference inspection sessions. + +Key Features +------------ +- Recognize only validated open, select and close operation suffixes. +- Retain strict alignment and distinguish subsequent substantive changes. + +Module Structure +---------------- +- ``inspection_suffix`` validates a closed tail of view-only commands. +- ``note_inspection`` annotates a strictly divergent comparison. + +Examples +-------- +>>> from kilin.system_testing import Experiment +>>> # Experiment("010_original").compare().data.get("inspection") + +""" + +from .validation import ValidationReport + +__all__ = [] + + +def inspection_suffix(report: ValidationReport, + count: int) -> list[dict] | None: + """Recognize a nonempty closed tail of ordinary inspection commands. + + Parameters + ---------- + report: ValidationReport + Closed recording to inspect. + count: int + Number of commands in the matched or published prefix. + + Notes + ----- + Callers must validate the entire recording first. No substantive command + or incomplete session qualifies. Selection may change the viewed chat + but not its saved turns. The original operation history is not trimmed. + + """ + operations = report.operations + if not report.valid or not 0 < count < len(operations): + return None + if operations[count - 1].kind != "close_project": + return None + # Source-change notices can be outside the open-command span. + for event in report.events: + if (event.sequence > operations[count - 1].end_sequence and + event.event_type == "gui.sources.changes.found" and + any(event.details.get(key) != [] for key in + ("added", "changed", "deleted", "edited"))): + return None + opened = False + tail = [] + for op in operations[count:]: + if op.status != "completed": + return None + if op.kind == "open_project": + if (opened or op.request.get("reason") != "resume" or + "relocation" in op.request): + return None + opened = True + elif op.kind == "select_conversation": + if not opened: + return None + elif op.kind == "close_project": + if not opened: + return None + opened = False + else: + return None + tail.append({"kind": op.kind, "sequence": op.start_sequence, + "end_sequence": op.end_sequence}) + return None if opened else tail + + +def note_inspection(data: dict, report: ValidationReport) -> dict | None: + """Describe an inspection-only tail absent from an existing replay. + + Parameters + ---------- + data: dict + Independently aligned comparison data. + report: ValidationReport + Validation of the same closed original snapshot. + + Notes + ----- + Require independently valid recordings and exact prefix alignment. Keep + the strict comparison status and unmatched operations unchanged. A + substantive extension, failed command or replay-side mismatch is never + downgraded to inspection-only. + + """ + alignment = data["alignment"] + if (not report.valid or not data["original"]["valid"] or + not data["replayed"]["valid"] or + alignment["status"] != "diverged" or + alignment["reason"] != "Recorded command counts differ." or + alignment["replayed_unmatched"]): + return None + count = alignment["matched_operations"] + if (report.event_count != data["original"]["event_count"] or + len(report.operations) != len(data["original"]["operations"]) or + count != len(data["replayed"]["operations"])): + return None + tail = inspection_suffix(report, count) + if not tail: + return None + if [op["sequence"] for op in tail] != [ + op["sequence"] for op in alignment["original_unmatched"]]: + return None + return {"status": "inspection_only", "operations": tail, + "message": "The existing replay matches the recorded prefix. " + "The original has additional closed inspection " + "sessions. A fresh replay includes these sessions. " + "Strict alignment remains divergent."} + + +def relocation_event_differences(data: dict, before: ValidationReport, + after: ValidationReport) -> list[str]: + """Identify fully explained event-count deltas for normalized renames. + + Parameters + ---------- + data: dict + Complete independently aligned comparison. + before: ValidationReport + Validated original recording. + after: ValidationReport + Validated replay recording. + + Notes + ----- + Only classify deltas when all counted extra events are accounted for + by recorded rename markers or empty checks immediately after a mapped + reopening. Other source checks or unmatched commands are not ignored. + + """ + if (not before.valid or not after.valid or + data["alignment"]["status"] != "complete"): + return [] + expected = {"gui.project.rename.requested": 0, + "gui.project.rename.completed": 0, + "gui.sources.changes.found": 0} + for i, row in enumerate(data["operations"]): + move = row.get("relocation") + if not move or move["physical_rename_replayed"]: + continue + expected["gui.project.rename.requested"] -= 1 + expected["gui.project.rename.completed"] -= 1 + a, b = before.operations[i], after.operations[i] + # A successful opening may be followed by a source check outside + # its command span. Only an explicitly empty diagnostic qualifies. + counts = [] + for report, op in ((before, a), (after, b)): + end = (report.operations[i + 1].start_sequence + if i + 1 < len(report.operations) else + report.event_count + 1) + notices = [e for e in report.events if + op.start_sequence <= e.sequence < end and + e.event_type == "gui.sources.changes.found"] + if any(any(e.details.get(k) != [] for k in + ("added", "changed", "deleted", "edited")) + for e in notices): + return [] + counts.append(len(notices)) + expected["gui.sources.changes.found"] += counts[1] - counts[0] + old = data["original"]["event_counts"] + new = data["replayed"]["event_counts"] + return [kind for kind, delta in expected.items() if delta and + new.get(kind, 0) - old.get(kind, 0) == delta] diff --git a/kilin/system_testing/_notebooks/experiment_template.ipynb b/kilin/system_testing/_notebooks/experiment_template.ipynb new file mode 100644 index 00000000..0e05df44 --- /dev/null +++ b/kilin/system_testing/_notebooks/experiment_template.ipynb @@ -0,0 +1,144 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "fad219e2", + "metadata": {}, + "source": [ + "# KíLín · Experiment comparison\n", + "\n", + "**Recording validity · alignment · reproducibility · performance**\n", + "\n", + "Generated and pre-executed by `../run_all.ipynb`. This notebook presents\n", + "one comparison snapshot and does not run models or change workspaces.\n", + "Re-executing it manually reads the saved native comparison JSON. For a\n", + "fresh comparison or replay, use `run_all.ipynb` (optionally select only\n", + "this experiment). For complete answers, open the sibling `_answers.ipynb`.\n", + "\n", + "See [README.md](../README.md) for metric definitions and the workflow." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3084815c", + "metadata": {}, + "outputs": [], + "source": [ + "from pathlib import Path\n", + "from IPython.display import HTML, display\n", + "\n", + "from kilin.system_testing.batch import load_snapshot\n", + "from kilin.system_testing.analysis import (\n", + " overview, event_inventory_html, question_explorer, operation_explorer,\n", + ")\n", + "\n", + "REFERENCE = Path(\"__ORIGINAL_WORKSPACE__\")\n", + "DESTINATION = REFERENCE.with_name(\n", + " REFERENCE.name.removesuffix(\"_original\") + \"_replay\"\n", + ")\n", + "data, source, digest = load_snapshot(REFERENCE)\n", + "print(\"Experiment:\", REFERENCE.name)\n", + "print(\"Snapshot:\", source)\n", + "print(\"Snapshot SHA-256:\", digest)" + ] + }, + { + "cell_type": "markdown", + "id": "b74ff717", + "metadata": {}, + "source": [ + "## 1. Visual overview\n", + "\n", + "Check validation and alignment before interpreting similarities. Measures\n", + "of text overlap do not establish scientific correctness. Recorded durations\n", + "and token totals have separate coverage and boundaries. Tool transitions\n", + "and conditional model-output agreement are reported separately from\n", + "execution integrity." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e36e1880", + "metadata": {}, + "outputs": [], + "source": [ + "display(HTML(overview(data)))" + ] + }, + { + "cell_type": "markdown", + "id": "65865b02", + "metadata": {}, + "source": [ + "## 2. Event inventory\n", + "\n", + "The report counts include compacted span terminal events and events outside\n", + "command boundaries. Full inventories use independently recorded counts when available.\n", + "Legacy comparisons require complete alignment and reconciled event totals. Enable\n", + "`INCLUDE_EVENT_DETAILS` to inspect the local events of changed types; local\n", + "trace details are not independently hash-verified and may contain private\n", + "text." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "41f6d6a8", + "metadata": {}, + "outputs": [], + "source": [ + "INCLUDE_EVENT_DETAILS = False\n", + "\n", + "display(HTML(event_inventory_html(\n", + " data, original=REFERENCE, replayed=DESTINATION,\n", + " include_details=INCLUDE_EVENT_DETAILS,\n", + ")))" + ] + }, + { + "cell_type": "markdown", + "id": "39cd22c4", + "metadata": {}, + "source": [ + "## 3. Inspect all aligned operations\n", + "\n", + "Expand source operations, configuration, opening/closing, interactions,\n", + "model calls and stage diagnostics. The matched prefix is not a complete\n", + "history for divergent recordings." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5581f31e", + "metadata": {}, + "outputs": [], + "source": [ + "display(HTML(operation_explorer(data)))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "kilin (3.12.x)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.-1" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/kilin/system_testing/_notebooks/explore_answers.ipynb b/kilin/system_testing/_notebooks/explore_answers.ipynb new file mode 100644 index 00000000..995673a9 --- /dev/null +++ b/kilin/system_testing/_notebooks/explore_answers.ipynb @@ -0,0 +1,155 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "0784cd0c", + "metadata": {}, + "source": [ + "# KíLín · Explore and compare answers\n", + "\n", + "**Read-only · No replay · No model loading**\n", + "\n", + "KíLín generates this `_answers.ipynb` for one reference workspace. The\n", + "batch pre-executes it from the same comparison snapshot as the sibling\n", + "comparison notebook. Open the generated notebook in `workspaces/` to\n", + "explore the saved outputs without running cells. Manually re-executing the\n", + "notebook reads the saved comparison JSON, not the historical questions.\n", + "\n", + "See [README.md](../README.md) for details." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1821734a", + "metadata": {}, + "outputs": [], + "source": [ + "from pathlib import Path\n", + "from IPython.display import HTML, display\n", + "\n", + "from kilin.system_testing.batch import load_snapshot\n", + "from kilin.system_testing.analysis import (\n", + " overview, event_inventory_html, question_explorer, operation_explorer,\n", + ")\n", + "\n", + "REFERENCE = Path(\"__ORIGINAL_WORKSPACE__\")\n", + "DESTINATION = REFERENCE.with_name(\n", + " REFERENCE.name.removesuffix(\"_original\") + \"_replay\"\n", + ")\n", + "data, source, digest = load_snapshot(REFERENCE)\n", + "print(\"Experiment:\", REFERENCE.name)\n", + "print(\"Snapshot:\", source)\n", + "print(\"Snapshot SHA-256:\", digest)" + ] + }, + { + "cell_type": "markdown", + "id": "f243d763", + "metadata": {}, + "source": [ + "## 1. Question-level overview\n", + "\n", + "Check the recording validity and aligned question coverage before reading\n", + "individual pairs. If alignment is unavailable, independently saved answers are shown\n", + "when available, with invalid recordings explicitly marked as unverified." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "05ebbfc4", + "metadata": {}, + "outputs": [], + "source": [ + "display(HTML(overview(data)))" + ] + }, + { + "cell_type": "markdown", + "id": "42bc9f4b", + "metadata": {}, + "source": [ + "## 2. Side-by-side answers and execution details\n", + "\n", + "Expand a question to see the complete saved original and replay responses,\n", + "exact text, literal line diff, routing, retrieval, evidence, citations,\n", + "rankings, settings, timings and model calls.\n", + "\n", + "Set `QUESTION` to a one-based matched-question index to focus on a case,\n", + "or `None` to display all. `DIFFERENCES_ONLY` includes recorded execution differences, incomplete\n", + "outcomes and citation problems even when the saved answers are identical.\n", + "Timing differences alone do not select a question.\n", + "`INCLUDE_MODEL_TEXT=True` reads exact local prompt/response text only when\n", + "its event type, sequence and SHA-256 match the report. Enable it selectively:\n", + "full prompts and answers may contain private information." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "99d9936b", + "metadata": {}, + "outputs": [], + "source": [ + "QUESTION = None\n", + "DIFFERENCES_ONLY = False\n", + "INCLUDE_MODEL_TEXT = False\n", + "\n", + "display(HTML(question_explorer(\n", + " data, question=QUESTION, differences_only=DIFFERENCES_ONLY,\n", + " original=REFERENCE, replayed=DESTINATION,\n", + " include_model_text=INCLUDE_MODEL_TEXT,\n", + ")))" + ] + }, + { + "cell_type": "markdown", + "id": "a4b2ccd0", + "metadata": {}, + "source": [ + "## 3. Event inventory and diagnostic differences\n", + "\n", + "Open the full inventory or enable local trace details for event types\n", + "whose counts differ. The counts describe recorded diagnostics, not\n", + "necessarily different user operations. Local details are not hash-verified." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "73710de7", + "metadata": {}, + "outputs": [], + "source": [ + "INCLUDE_EVENT_DETAILS = False\n", + "\n", + "display(HTML(event_inventory_html(\n", + " data, original=REFERENCE, replayed=DESTINATION,\n", + " include_details=INCLUDE_EVENT_DETAILS,\n", + ")))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "kilin (3.12.x)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.-1" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/kilin/system_testing/_plugin_provenance.py b/kilin/system_testing/_plugin_provenance.py new file mode 100644 index 00000000..3ded534d --- /dev/null +++ b/kilin/system_testing/_plugin_provenance.py @@ -0,0 +1,260 @@ +"""Inspect historical plugin identities and preflight fresh replay inputs. + +Historical inspection uses only recorded data, never the inspecting runtime's +catalog. Fresh replay explicitly resolves trusted installed plugins before +creating or archiving a destination. + +Key Features +------------ +- Validate required metadata and retain genuinely unknown identities. +- Compare captured identities at matching command boundaries. +- Resolve historical and current plugin requirements before replay. + +Module Structure +---------------- +- ``plugin_observations`` decodes recorded plugin identities. +- ``compare_plugins`` compares observations without loading plugins. +- ``preflight_plugins`` checks the executing runtime and captures identities. + +Examples +-------- +>>> from kilin.system_testing._plugin_provenance import plugin_observations +>>> plugin_observations(()) +[] + +""" + +from __future__ import annotations + +from collections import defaultdict +from copy import deepcopy +import re + +from kilin.plugins._versioning import _is_semver + +from .timeline import TimelineOperation +from .traces import TraceEvent + +__all__ = [] + +_MISSING = object() + + +def _observation( + event: TraceEvent, scope: str, kind: str, name: object, identity: object, +) -> dict: + """Decode an optional portable identity without consulting a catalog. + + Parameters + ---------- + event: TraceEvent + Historical event supplying the observation. + scope: str + Opening, turn, or tool execution boundary. + kind: str + Project type or tool identity category. + name: object + Identifier recorded independently of the identity payload. + identity: object + Identity payload; None is unknown and _MISSING is a missing field. + + Returns + ------- + dict + Observation with recorded, unknown or invalid status. + + """ + + result = {"sequence": event.sequence, "scope": scope, "kind": kind, + "name": name if isinstance(name, str) else None, + "status": "unknown", "identity": None} + if not isinstance(name, str) or not name: + result.update(status="invalid", error="Missing plugin identifier.") + return result + if identity is _MISSING: + result.update(status="invalid", error="Missing plugin identity field.") + return result + if identity is None: + return result + key = "type_id" if kind == "project_type" else "name" + version = "schema_version" if kind == "project_type" else "api_version" + required = {key, "origin", version, "sha256", "version"} + if (not isinstance(identity, dict) or set(identity) != required + or identity[key] != name + or identity["origin"] not in ("distribution", "user") + or type(identity[version]) is not int or identity[version] < 1 + or not isinstance(identity["sha256"], str) + or re.fullmatch(r"[0-9a-f]{64}", identity["sha256"]) is None + or not _is_semver(identity["version"])): + result.update(status="invalid", error="Invalid plugin identity.") + else: + result.update(status="recorded", identity=deepcopy(identity)) + return result + + +def plugin_observations(events: tuple[TraceEvent, ...]) -> list[dict]: + """Read the opening and execution identities from historical events. + + Parameters + ---------- + events: tuple[TraceEvent, ...] + Decoded events, including expanded configuration observations. + + Returns + ------- + list[dict] + Chronological observations. Required metadata must be present. + Explicitly unknown identities and unavailable turn identities are + retained without inferring them from an installed catalog. + + """ + + result = [] + for event in events: + data = event.details + if event.event_type == "gui.project.configuration.effective": + profile = data.get("profile") + name = (profile.get("type_id") + if isinstance(profile, dict) else None) + tools = data.get("tools") + snapshot = data.get("plugins") + if (not isinstance(name, str) or not name + or not isinstance(tools, list) + or not all(isinstance(entry, dict) + and isinstance(entry.get("name"), str) + and entry["name"] for entry in tools) + or not isinstance(snapshot, dict) + or set(snapshot) != {"project_type", "tools"} + or not isinstance(snapshot["tools"], dict) + or set(snapshot["tools"]) != { + entry["name"] for entry in tools}): + result.append({"sequence": event.sequence, "scope": "open", + "kind": "project_type", + "name": (name if isinstance(name, str) + else None), + "status": "invalid", "identity": None, + "error": "Invalid or missing plugin snapshot."}) + continue + result.append(_observation(event, "open", "project_type", + name, snapshot["project_type"])) + for tool in sorted(snapshot["tools"]): + result.append(_observation(event, "open", "tool", tool, + snapshot["tools"][tool])) + elif event.event_type == "turn.settings.snapshot": + # The producer omits an unavailable project-type identity. + result.append(_observation( + event, "turn", "project_type", data.get("project_type_id"), + data.get("project_type_plugin"), + )) + elif event.event_type == "tool.run.started": + # Unlike turn settings, tool execution always records the key. + result.append(_observation( + event, "execution", "tool", data.get("name"), + data.get("plugin", _MISSING), + )) + return result + + +def compare_plugins( + original: TimelineOperation, replayed: TimelineOperation, +) -> list[dict]: + """Compare matching historical plugin observations, never live code. + + Parameters + ---------- + original: TimelineOperation + Reference command with recorded observations. + replayed: TimelineOperation + Aligned replay command with its own observations. + + Returns + ------- + list[dict] + Pairs with equal, changed, unknown, invalid or one-sided status. + An unobserved tool may reflect different routing, not changed code. + + """ + + groups = [] + for op in (original, replayed): + grouped = defaultdict(list) + for item in plugin_observations(op.events): + key = (item["scope"], item["kind"], item["name"] or "") + grouped[key].append(item) + groups.append(grouped) + left, right = groups + result = [] + for scope, kind, name in sorted(left.keys() | right.keys()): + key = scope, kind, name + before, after = left[key], right[key] + for index in range(max(len(before), len(after))): + a = before[index] if index < len(before) else None + b = after[index] if index < len(after) else None + if a is None or b is None: + status = "one_sided" + elif "invalid" in (a["status"], b["status"]): + status = "invalid" + elif "unknown" in (a["status"], b["status"]): + status = "unknown" + else: + status = ("equal" if a["identity"] == b["identity"] + else "changed") + result.append({"scope": scope, "kind": kind, "name": name, + "status": status, "original": a, "replayed": b}) + return result + + +def preflight_plugins(operations: tuple[TimelineOperation, ...]) -> dict: + """Require usable historical and current plugins before fresh execution. + + Parameters + ---------- + operations: tuple[TimelineOperation, ...] + Validated reference operations, starting with project creation. + + Returns + ------- + dict + Portable identities of the current type and all required tools, + including any tools required by the historical configuration or + observed historical tool execution. + + Raises + ------ + ValueError + If a required plugin is missing or unavailable. A changed identity + alone is not an error: replay intentionally uses current code. + + Notes + ----- + Only fresh execution calls this function. Registry access imports + trusted installed plugins; historical names never authorize imports. + + """ + + from kilin.plugins import list_tools + from kilin.project_type import project_type_catalog + from kilin.tools._registry import _tool_identity, registered_tools + + type_id = operations[0].request["source_batch"]["type_id"] + info = project_type_catalog().get(type_id) + if info is None or not info.available: + reason = info.error if info is not None else "Not installed." + raise ValueError(f"Required project type {type_id!r} is unavailable: " + f"{reason}") + required = set(info.required_tools) + for op in operations: + for item in plugin_observations(op.events): + if item["kind"] == "tool": + required.add(item["name"]) + missing = required - registered_tools().keys() + if missing: + diagnostics = {entry.name: entry.error for entry in list_tools() + if not entry.available} + details = "; ".join( + f"{name}: {diagnostics.get(name) or 'Not installed.'}" + for name in sorted(missing) + ) + raise ValueError(f"Required tool plugins unavailable: {details}") + return {"project_type": info.identity(), + "tools": {name: _tool_identity(name) for name in sorted(required)}} diff --git a/kilin/system_testing/_replay_interactions.py b/kilin/system_testing/_replay_interactions.py new file mode 100644 index 00000000..c0ad0bea --- /dev/null +++ b/kilin/system_testing/_replay_interactions.py @@ -0,0 +1,158 @@ +"""Replay only recorded user responses to live interactive prompts. + +Key Features +------------ +- Match a selected option by its unique label rather than its old index. +- Require compatible confirmation plans and consume responses in order. +- Refuse new, changed, missing, cancelled or ambiguous interactions. + +Module Structure +---------------- +- ``InteractionReplay`` implements the synchronous engine command callback. + +Examples +-------- +>>> from kilin.system_testing import Experiment +>>> # Experiment("workspaces/010_original").replay() + +""" + +from __future__ import annotations + +from collections import deque +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .timeline import TimelineOperation + +__all__ = [] + + +class InteractionReplay: + """Consume recorded user responses in the scope of one question.""" + + def __init__(self) -> None: + """Initialize an empty interaction queue.""" + self._expected = deque() + self._prompt = None + self.failure: str | None = None + self.differences: list[tuple[str, object, object]] = [] + + def begin(self, op: TimelineOperation) -> None: + """Extract only actual user responses, correlated by interaction ID. + + Parameters + ---------- + op: TimelineOperation + Validated reference question and its diagnostics. + + """ + self._expected.clear() + self._prompt = None + self.failure = None + self.differences.clear() + decisions = { + e.details["interaction_id"]: e.details + for e in op.matching("tool.plan.decided", "tool.choice.decided", + "routing.choice.decided") + } + for event in op.matching("tool.plan.proposed", "tool.choice.proposed", + "routing.choice.proposed"): + if event.details["asked"]: + self._expected.append(( + event.event_type, event.details, + decisions[event.details["interaction_id"]], + )) + + def observe(self, event: dict) -> None: + """Capture the actual prompt sent before a synchronous callback. + + Parameters + ---------- + event: dict + Ordinary headless engine event. + + """ + if event.get("event") != "answer_phase": + return + for kind in ("plan", "choice"): + if kind in event: + if self._prompt is not None: + self._fail("Overlapping interactive prompts.") + self._prompt = (kind, event[kind]) + + def _fail(self, message: str) -> None: + """Record a divergence even if the engine catches the exception. + + Parameters + ---------- + message: str + Precise mismatch explanation. + + """ + self.failure = message + raise RuntimeError(message) + + def read_command(self) -> dict: + """Return the recorded semantic response to the current prompt. + + Returns + ------- + dict + Ordinary GUI protocol choice command with the live index. + + """ + if self.failure: + self._fail(self.failure) + if not self._expected or self._prompt is None: + self._fail("Unexpected interaction; no matching user response.") + kind, live = self._prompt + self._prompt = None + prefix, original, decision = self._expected[0] + if prefix == "tool.plan.proposed": + if kind != "plan": + self._fail("Expected a tool plan, not an option question.") + # Counts and timing estimates can vary. Scope and action meaning + # must agree, especially for a recorded network approval. + fields = ("tool", "summary", "scope", "details") + if (any(original.get(key) != live.get(key) for key in fields) + or original.get("operation", "model") != + live.get("operation", "model")): + self._fail("Tool plan scope or meaning changed.") + choice = decision["choice"] + if choice not in ("continue", "quick"): + self._fail("No recorded affirmative plan response.") + if choice == "quick" and any( + original.get(key) != live.get(key) + for key in ("quick_label", "quick_note") + ): + self._fail("Quick-plan meaning changed.") + for key in ("items", "batches", "batches_to_run", "quick_items"): + if original.get(key) != live.get(key): + if live.get("operation") == "network": + self._fail("Network approval scope changed.") + self.differences.append(( + f"plan.{key}", original.get(key), live.get(key) + )) + else: + if (kind != "choice" or original["question"] != + live.get("question") or original["allow_cancel"] != + live.get("allow_cancel", True)): + self._fail("Interactive question or choice scope changed.") + label = decision["selected_option"] + options = live.get("options", []) + if not isinstance(options, list) or options.count(label) != 1: + self._fail(f"Recorded choice is missing or ambiguous: {label}") + choice = f"option:{options.index(label)}" + if original["options"] != options: + self.differences.append(("choice.options", original["options"], + options)) + self._expected.popleft() + return {"action": "plan_choice", "choice": choice} + + def finish(self) -> None: + """Reject a question that did not consume its exact user responses.""" + if self.failure: + self._fail(self.failure) + if self._expected or self._prompt is not None: + self._fail("Recorded interaction was not reproduced.") diff --git a/kilin/system_testing/_replay_sources.py b/kilin/system_testing/_replay_sources.py new file mode 100644 index 00000000..4062cc6a --- /dev/null +++ b/kilin/system_testing/_replay_sources.py @@ -0,0 +1,266 @@ +"""Plan additive replay inputs from retained managed source snapshots. + +Key Features +------------ +- Map historical external identities to actual retained source destinations. +- Reproduce historical selections without copying later files prematurely. +- Check source inventories and content hashes after replayed operations. + +Module Structure +---------------- +- ``SourceReplay`` prepares creation/import/sync arguments and checks copies. + +Examples +-------- +>>> from kilin.system_testing import Experiment +>>> # Experiment("workspaces/010_original").replay() + +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +import os +from pathlib import Path + +from kilin.repository import _manifest_files +from kilin.workspace import _hash_file + +from ._filesystem import is_incidental_metadata +from .timeline import TimelineOperation, one +from .traces import safe_path + +__all__ = [] + + +@dataclass(slots=True) +class SourceCommand: + """Prepared arguments for an ordinary creation, addition or sync.""" + + sources: list[str] = field(default_factory=list) + selections: dict[str, list[str]] = field(default_factory=dict) + decisions: dict[str, str] | None = None + manifest: dict[str, dict] = field(default_factory=dict) + omitted: tuple[str, ...] = () + + +def _scan_error(error: OSError) -> None: + """Propagate an inaccessible source directory. + + Parameters + ---------- + error: OSError + Directory traversal failure. + + """ + raise error + + +class SourceReplay: + """Preflight source commands without using historical external paths. + + Parameters + ---------- + root: pathlib.Path + Closed, validated original workspace. + operations: tuple[TimelineOperation, ...] + Complete chronological reference operations. + + Attributes + ---------- + commands: dict[int, SourceCommand] + Source arguments and expected inventories by original sequence. + + Notes + ----- + The normal importer allocates the destination from the basename of the + input. Use the already collision-adjusted managed basename, not the + original external basename. All imported files are explicitly selected. + Original folder snapshots can contain later additions, but those files + must not enter the replay's managed sources until their recorded batch. + + """ + + def __init__(self, root: Path, + operations: tuple[TimelineOperation, ...]) -> None: + """Prepare every source command before opening a model. + + Parameters + ---------- + root: pathlib.Path + Validated reference root. + operations: tuple[TimelineOperation, ...] + Chronologically ordered reference operations. + + """ + self.root = root + self.commands: dict[int, SourceCommand] = {} + self._origins: dict[str, str] = {} + self._manifest: dict[str, dict] = {} + for op in operations: + if op.kind in ("create_project", "add_sources", "sync_sources", + "open_project"): + self.commands[op.start_sequence] = self._plan(op) + + def _plan(self, op: TimelineOperation) -> SourceCommand: + """Reconstruct a source command using actual copy outcomes. + + Parameters + ---------- + op: TimelineOperation + Validated original operation. + + Returns + ------- + SourceCommand + Arguments and expected post-operation source inventory. + + """ + command = SourceCommand() + copies = op.matching("workspace.source.copied") + batch = op.matching("workspace.prepare.started") + if len(batch) != bool(copies) and not ( + len(batch) == 1 and op.kind == "create_project" and not copies + and not batch[0].details["source_paths"] + ): + raise ValueError("Missing or ambiguous source preparation batch.") + actual = [] + for event in copies: + data = event.details + original = data["source"] + managed = data["workspace_path"] + path = safe_path(self.root, managed) + if (not managed.startswith("sources/") + or len(Path(managed).parts) != 2 + or original in self._origins + or data["preserved_files"]): + raise ValueError("Expected a new, additive source copy.") + selected = data["copied_files"] + if data["kind"] == "file" and path.is_file(): + if len(selected) != 1: + raise ValueError("Ambiguous direct file copy.") + selected = [path.name] + elif data["kind"] == "folder" and path.is_dir(): + selected = list(selected) + for name in selected: + if not safe_path(self.root, f"{managed}/{name}").is_file(): + raise ValueError(f"Missing retained file: {name}") + else: + raise ValueError(f"Missing retained source: {managed}") + if not selected or str(path) in command.selections: + raise ValueError("Ambiguous retained source selection.") + actual.append(str(path)) + self._origins[original] = str(path) + command.selections[str(path)] = selected + # A source batch preserves the order of unique resolved inputs. For + # one-to-one batches this also establishes their submitted aliases. + if batch: + submitted = batch[0].details["source_paths"] + if len(submitted) == len(actual): + for raw, path in zip(submitted, actual): + if self._origins.get(raw, path) != path: + raise ValueError("Conflicting source identity.") + self._origins[raw] = path + if op.kind == "create_project": + command.sources = actual + elif op.kind == "add_sources": + completed = one(op.events, "gui.sources.add.completed").details + new = completed["new_sources"] + if len(new) != len(actual) or any( + self._origins.get(raw) != path + for raw, path in zip(new, actual) + ): + raise ValueError("Cannot map the recorded new source batch.") + # The canonical new-input order is recorded separately from + # the raw request. Aliases no longer on disk need not be guessed + # to reproduce the actual new copies. + command.sources = list(actual) + omitted = [] + for raw in op.request["sources"]: + path = self._origins.get(raw) + if path is None: + # Skipped originals are not retained in the workspace. + # They cannot supply replay inputs or alter its sources. + omitted.append(raw) + elif path not in command.sources: + command.sources.append(path) + if not command.sources: + raise ValueError("No unambiguous retained source request.") + command.omitted = tuple(omitted) + sync = op.matching("workspace.sync.started") + if sync: + request = one(op.events, "workspace.sync.started").details + imports = {e.details["path"]: "import" for e in op.matching( + "workspace.sync.file" + ) if e.details["action"] == "import"} + if len(imports) != len(op.matching("workspace.sync.file")): + raise ValueError("Nonadditive synchronization is unsupported.") + decisions = request["decisions"] + # A default sync can act on newly visible external files. Use + # explicit additive actions only, never the automatic policy. + command.decisions = dict(imports) + for path, action in (decisions or {}).items(): + if action == "import" and path in imports: + continue + if action != "keep": + raise ValueError("Unsupported synchronization decision.") + # Preserve a keep only when that unimported source is still + # represented in the final snapshot. Never invent a file. + retained = safe_path(self.root, path) + relative = path.removeprefix("sources/") + if (path.startswith("sources/") and retained.is_file() + and relative not in self._manifest + and path not in imports): + command.decisions[path] = "keep" + else: + command.omitted += (f"keep: {path}",) + elif op.kind == "add_sources": + command.decisions = op.request["decisions"] + if command.decisions: + raise ValueError("Source decisions lack a recorded sync.") + manifests = op.matching("index.check.completed", "index.empty") + if manifests: + self._manifest = _manifest_files( + manifests[-1].details["source_manifest"] + ) + command.manifest = dict(self._manifest) + return command + + def verify(self, destination: Path, op: TimelineOperation) -> None: + """Check actual source inventory and bytes after a source command. + + Parameters + ---------- + destination: pathlib.Path + Newly created replay workspace. + op: TimelineOperation + Original command that has just been executed. + + """ + if op.start_sequence not in self.commands: + return + expected = self.commands[op.start_sequence].manifest + root = safe_path(destination, "sources") + if not root.is_dir(): + raise ValueError("Replay has no managed source directory.") + found = set() + for parent, directories, files in os.walk(root, onerror=_scan_error): + for name in directories + files: + path = Path(parent) / name + if path.is_symlink(): + raise ValueError(f"Linked replay source: {path}") + if name in files: + if not path.is_file(): + raise ValueError(f"Nonregular replay source: {path}") + relative = path.relative_to(root).as_posix() + if not is_incidental_metadata(path, relative, expected): + found.add(relative) + if found != set(expected): + raise ValueError("Replay source inventory differs from history: " + f"missing={sorted(set(expected) - found)}, " + f"extra={sorted(found - set(expected))}.") + for relative, record in expected.items(): + path = safe_path(root, relative) + if (path.stat().st_size != record["size_bytes"] + or _hash_file(path) != record["sha256"]): + raise ValueError(f"Replay source content differs: {relative}") diff --git a/kilin/system_testing/_semantic_replay.py b/kilin/system_testing/_semantic_replay.py new file mode 100644 index 00000000..fa777690 --- /dev/null +++ b/kilin/system_testing/_semantic_replay.py @@ -0,0 +1,668 @@ +"""Validate and compare chronological semantic source organization. + +Key Features +------------ +- Require correlated command outcomes and a complete revision/digest chain. +- Validate accepted state separately from physical source provenance. +- Compare recorded semantic snapshots without reusing live preview tokens. + +Module Structure +---------------- +- ``validate_semantic_history`` checks the current recording protocol. +- ``semantic_observations`` and ``compare_semantics`` describe differences. +- ``semantic_request`` isolates portable explicit command inputs. + +Examples +-------- +>>> from kilin.system_testing import Experiment +>>> # Experiment(workspace).validate() checks recorded semantic decisions. + +""" + +from __future__ import annotations + +from dataclasses import asdict, replace +from hashlib import sha256 +from typing import TYPE_CHECKING + +from kilin._source_manifest import ( + SourceManifest, canonical_path, parse_manifest, +) +from kilin.repository import _manifest_files +from kilin.source_manifest import ( + SOURCE_MANIFEST_FILE, SourceManifestSnapshot, _read_manifest_file, + _serialize, _change_settings, _mapping, _propose, +) + +from .timeline import _historical_directory, _opening_directory +from .traces import safe_path + +if TYPE_CHECKING: + from .timeline import TimelineOperation + from .traces import Recording + +__all__ = [] + +PREFIX = "gui.source_organization." +OBSERVED = PREFIX + "observed" +COMMITTED = "source_organization.committed" +RECONCILED = "source_organization.reconciled" +PROJECT_TRACE = "logs/traces/project.json" +_OPERATIONS = { + "inspect": set(), "initialize": set(), "reconcile": set(), + "apply": {"preview_id"}, + "preview": {"revision", "sha256", "edits", "organization", + "adopt_type_defaults", "role_mapping", "relation_mapping", + "adopt_detector_versions"}, +} + + +def _require(condition: bool, message: str) -> None: + """Reject an incomplete or inconsistent semantic observation. + + Parameters + ---------- + condition: bool + Required invariant. + message: str + Diagnostic for a violated invariant. + + """ + if not condition: + raise ValueError(message) + + +def _snapshot(data: dict) -> SourceManifestSnapshot: + """Decode a canonical, byte-identified semantic state. + + Parameters + ---------- + data: dict + Recorded identity and complete manifest. + + Returns + ------- + SourceManifestSnapshot + Validated managed state and canonical SHA-256 digest. + + """ + state = parse_manifest(data["source_organization"]) + digest = sha256(_serialize(state).encode("utf-8")).hexdigest() + _require(type(data.get("revision")) is int and + data["revision"] == state.revision and + data.get("sha256") == digest, + "Semantic source identity does not match canonical state.") + _require(state.source_root.base == "project" and + state.source_root.path == "sources", + "Semantic source root is not the managed directory.") + return SourceManifestSnapshot(state, digest) + + +def _inspection(data: dict, state: SourceManifestSnapshot, + indexed: set[str] | None = None) -> set[str]: + """Check accepted identity and the separately observed inventory. + + Parameters + ---------- + data: dict + Recorded inspection or flattened lifecycle observation. + state: SourceManifestSnapshot + Accepted state at this chronological boundary. + indexed: set of str or None, optional + Physical inventory, when an index checkpoint already exists. + + Returns + ------- + set of str + Selected physical relative paths. + + """ + _require(_snapshot(data) == state and data.get("binding_matches") is True + and data.get("source_root") == { + "base": "project", "path": "sources"}, + "Semantic observation differs from accepted state.") + selected = data["selected"] + _require(isinstance(selected, list) and + all(isinstance(path, str) for path in selected) and + len(selected) == len(set(selected)), + "Invalid semantic selection.") + selected = {canonical_path(path) for path in selected} + if indexed is not None: + _require(selected == indexed, + "Semantic selection differs from physical index checkpoint.") + return selected + + +def _command(op: TimelineOperation, project: object) -> tuple[dict, dict]: + """Validate the recorded command envelope and terminal correlation. + + Parameters + ---------- + op: TimelineOperation + Reconstructed semantic command interval. + project: pathlib.PurePath + Historical open project identity, not a local filesystem path. + + Returns + ------- + tuple of dict + Request marker and completed outcome. + + """ + start, end = op.events[0], op.events[-1] + request = op.request + operation = request.get("operation") + _require(isinstance(operation, str) and operation in _OPERATIONS and + start.event_type == PREFIX + operation + ".requested" and + end.event_type == PREFIX + operation + ".completed" and + end.details.get("request") == request and + end.details.get("command_id") == start.details["command_id"] + and type(request.get("request_id")) is int and + request["request_id"] > 0 and + _historical_directory(request.get("project")) == project and + not set(request) - {"project", "request_id", "operation"} - + _OPERATIONS[operation], "Invalid semantic command envelope.") + _require(all(start.details.get(key) == end.details.get(key) for key in ( + "preview_request", "preview_command_id")), + "Semantic preview linkage changed at completion.") + _require(not any(end.details.get(key) for key in ( + "error", "trace_error", "refresh_error")), + "Semantic command failed or has incomplete post-commit recording.") + return start.details, end.details + + +def _validate_preview(request: dict, result: dict, + state: SourceManifestSnapshot) -> None: + """Check a preview's accepted identity and proposed revision. + + Parameters + ---------- + request: dict + Explicit editor inputs. + result: dict + Recorded preview outcome. + state: SourceManifestSnapshot + State before the read-only preview. + + """ + _require(type(request.get("revision")) is int and + request["revision"] == state.manifest.revision and + request.get("sha256") == state.sha256, + "Semantic preview was not bound to accepted identity.") + proposed = parse_manifest(result["proposed_source_organization"]) + changed = proposed != state.manifest + _require(type(result.get("changed")) is bool and + result["changed"] == changed and proposed.revision == + state.manifest.revision + int(changed) and + isinstance(result.get("preview_id"), str) and + bool(result["preview_id"]), "Invalid semantic preview outcome.") + _validate_transition(state.manifest, proposed, + result["inspection"]["selected"], request, + result["discovery"]) + + +def _validate_transition(before: SourceManifest, after: SourceManifest, + selected: list[str], request: dict, + discovery: dict) -> None: + """Prove explicit changes independently of historical detector code. + + Parameters + ---------- + before: SourceManifest + Previously accepted state. + after: SourceManifest + Candidate recorded result. + selected: list of str + Historically selected physical paths, not current disk discovery. + request: dict + Explicit preview inputs, or an empty reconciliation request. + discovery: dict + Recorded automatic additions and removals after explicit edits. + + Notes + ----- + Reuse the core's pure edit and vocabulary transformations. Historical + automatic discovery cannot be inferred from today's detector version; + check its recorded graph deltas without running a detector or reading + external files. Actual replay re-executes discovery normally. + + """ + from kilin.gui._source_organization import _edits + from kilin.source_organization import parse_source_organization + + for flag in ("adopt_type_defaults", "adopt_detector_versions"): + _require(flag not in request or type(request[flag]) is bool, + "Invalid semantic preview flag.") + adoption = request.get("adopt_type_defaults", False) + local = "organization" in request + detectors = request.get("adopt_detector_versions", False) + _require(not (adoption and local), "Conflicting organization adoption.") + roles = _mapping(request.get("role_mapping")) + relations = _mapping(request.get("relation_mapping")) + _require(not (roles or relations) or adoption or local, + "Semantic mappings lack an explicit settings change.") + old, new = before.organization, after.organization + if adoption: + _require(new.derived_from.project_type == + old.derived_from.project_type, + "Semantic adoption refers to a different project type.") + elif local: + _require(new.derived_from == old.derived_from and + new.declaration == parse_source_organization( + request["organization"]), + "Recorded organization differs from explicit declaration.") + else: + _require(new.derived_from == old.derived_from and + new.declaration == old.declaration, + "Unrecorded source organization change.") + if not adoption and not detectors: + versions = dict(new.detector_versions) + _require(all(versions[name] == version for name, version in + old.detector_versions if name in versions), + "Unrecorded detector version adoption.") + if not (adoption or local or detectors): + _require(new == old, "Unrecorded accepted organization change.") + candidate = before + if adoption or local: + candidate = _change_settings(candidate, new, roles, relations) + elif detectors: + candidate = replace(candidate, organization=new) + candidate = _propose(candidate, tuple(sorted(selected)), + before.source_root, _edits(request.get("edits", []))) + _require(candidate.source_root == after.source_root and + set(candidate.files) == set(after.files) and + set(candidate.unresolved) == set(after.unresolved) and + set(candidate.suppressed_automatic) == + set(after.suppressed_automatic) and + {r for r in candidate.relations if r.origin == "user"} == + {r for r in after.relations if r.origin == "user"}, + "Semantic result does not implement recorded explicit edits.") + original = {r.key: r for r in candidate.relations} + actual = {r.key: r for r in after.relations} + additions = [actual[k] for k in sorted(actual.keys() - original.keys())] + removals = [original[k] for k in sorted(original.keys() - actual.keys())] + rules = {r.id: r for r in new.declaration.automatic_rules} + for edge in actual.values(): + if edge != original.get(edge.key) and edge.origin == "rule": + rule = rules.get(edge.rule) + _require(rule is not None and rule.mode == "apply" and + rule.relation == edge.key.type, + "Unrecognized automatic semantic relationship.") + _require(discovery.get("added") == [asdict(r) for r in additions] and + discovery.get("removed") == [asdict(r) for r in removals], + "Recorded discovery deltas differ from semantic graph changes.") + + +def validate_semantic_history(recording: Recording, + operations: tuple[TimelineOperation, ...] + ) -> None: + """Verify semantic commands, lifecycle and question checkpoints. + + Parameters + ---------- + recording: Recording + Offline, closed reference workspace. + operations: tuple of TimelineOperation + Reconstructed chronological command intervals. + + Notes + ----- + The complete semantic history is required for every recording. + Physical source history is validated separately. Missing, externally + replaced or unrecorded semantic states are not reconstructed from the + final file. The supported physical history remains additive. + + """ + state = None + indexed = None + selected = None + pending = None + project = None + consumed = set() + try: + for op in operations: + if op.kind in ("create_project", "open_project"): + project = _opening_directory(op) + pending = None + if op.kind == "close_project": + project = None + pending = None + command = None + if op.kind == "source_organization": + _require(project is not None, + "Semantic command without an open project.") + command = _command(op, project) + core = op.matching(COMMITTED, RECONCILED) + if command is None: + _require(not core or op.kind in ( + "create_project", "open_project", "add_sources", + "sync_sources") and all(e.event_type == RECONCILED + for e in core), + "Unrecorded semantic mutation.") + else: + operation = op.request["operation"] + _require(len(core) == int(command[1].get("changed") is True + and operation in ("apply", "initialize", "reconcile")) + and all(e.event_type == (RECONCILED if operation == + "reconcile" else COMMITTED) for e in core), + "Semantic mutation lacks a correlated core commit.") + if operation == "apply": + _require(pending is not None and + op.request.get("preview_id") == pending[1][ + "preview_id"] and + command[0].get("preview_command_id") == + pending[0]["command_id"] and + command[0].get("preview_request") == + pending[0]["request"], + "Missing, stale or unrelated semantic preview.") + before = state + lifecycle_before = None + observations = op.matching(OBSERVED) + for event in op.events: + kind, data = event.event_type, event.details + if kind in (COMMITTED, RECONCILED, OBSERVED) or ( + kind.startswith(PREFIX)): + consumed.add(event.sequence) + _require(event.path == PROJECT_TRACE, + "Semantic event in wrong trace.") + if kind in (COMMITTED, RECONCILED): + new = _snapshot(data) + _require(state is not None and + type(data.get("previous_revision")) is int and + data.get("previous_revision") == + state.manifest.revision and + data.get("previous_sha256") == state.sha256 and + new.manifest.revision == + state.manifest.revision + 1, + "Broken semantic revision/digest chain.") + if kind == RECONCILED and command is None: + _require(lifecycle_before is None, + "Missing lifecycle commit observation.") + lifecycle_before = state + state = new + elif kind == OBSERVED: + _require(project is not None and + _historical_directory(data.get("project")) == + project and not data.get("error") and + not data.get("trace_error"), + "Invalid semantic lifecycle observation.") + if state is None: + state = _snapshot(data) + _require(op.kind == "create_project" and + data.get("reason") == "create" and + state.manifest.revision == 0 and + not state.manifest.suppressed_automatic and + not state.manifest.unresolved and all( + item.origin == "default" for item in + state.manifest.files) and all( + r.origin == "rule" for r in + state.manifest.relations), + "Missing initial semantic creation state.") + selected = _inspection(data, state) + reason = data.get("reason") + allowed = { + "create": ("create_project",), + "opened": ("create_project", "open_project", + "add_sources", "sync_sources"), + "add": ("add_sources",), + "sync": ("add_sources", "sync_sources"), + "refresh": ("add_sources", "sync_sources"), + } + _require(op.kind in allowed.get(reason, ()), + "Unsupported semantic lifecycle reason.") + if reason == "create": + _require(op.kind == "create_project" and + state.manifest.revision == 0 and + {r.path for r in state.manifest.files} == + selected and state.manifest.organization. + derived_from.project_type == op.request[ + "source_batch"]["type_id"], + "Invalid initial semantic assignments.") + initial = replace(state.manifest, files=(), + relations=()) + _validate_transition(initial, state.manifest, + data["selected"], {}, + data["discovery"]) + elif reason != "opened": + _require(type(data.get("changed")) is bool and + data["changed"] == + (lifecycle_before is not None), + "Lifecycle change lacks correlated commit.") + _validate_transition( + (lifecycle_before or state).manifest, + state.manifest, data["selected"], {}, + data["discovery"], + ) + lifecycle_before = None + if reason != "opened": + pending = None + elif kind in ("index.check.completed", "index.empty"): + indexed = set(_manifest_files(data["source_manifest"])) + _require(state is not None, + "Missing initial semantic creation state.") + _require(selected == indexed, + "Semantic state has no matching physical index " + "checkpoint.") + _require(lifecycle_before is None, + "Missing semantic lifecycle commit observation.") + if op.kind in ("create_project", "open_project"): + _require(observations and observations[-1].details.get( + "reason") == "opened" and indexed == selected, + "Missing semantic opening observation.") + if op.kind in ("add_sources", "sync_sources"): + _require(observations and observations[-1].details.get( + "reason") == "opened" and indexed == selected, + "Missing semantic source lifecycle observation.") + if command is not None: + operation = op.request["operation"] + result = command[1] + _require(state is not None and before is not None, + "Semantic command without accepted state.") + _inspection(result["inspection"], state, indexed) + if operation == "preview": + _validate_preview(op.request, result, state) + pending = command + elif operation != "inspect": + _require(_snapshot(result) == state and + type(result.get("changed")) is bool and + result["changed"] == (before != state), + "Semantic outcome differs from committed state.") + if operation == "reconcile": + _validate_transition(before.manifest, state.manifest, + result["inspection"]["selected"], + {}, result["discovery"]) + elif operation == "initialize": + _require(before == state, + "Unrecorded missing semantic state.") + if operation == "apply": + _require(parse_manifest(pending[1][ + "proposed_source_organization"]) == + state.manifest and result.get("discovery") == + pending[1].get("discovery"), + "Apply differs from preview.") + pending = None + if op.kind == "ask": + _require(state is not None and not op.request.get( + "source_organization_error") and + type(op.request.get("source_organization_revision")) + is int and op.request["source_organization_revision"] == + state.manifest.revision and op.request.get( + "source_organization_sha256") == state.sha256, + "Question semantic identity differs from accepted state.") + for event in op.events: + view = event.details.get("source_operation") + if event.event_type == "tool.source_view.resolved": + view = dict(event.details, semantic_revision= + event.details.get("revision")) + if isinstance(view, dict): + _require(type(view.get("semantic_revision")) is int and + view.get("semantic_revision") == + state.manifest.revision and + view.get("manifest_sha256") == state.sha256, + "Tool view has stale semantic identity.") + for event in recording.events: + if (event.event_type in (COMMITTED, RECONCILED, OBSERVED) or + event.event_type.startswith(PREFIX)): + _require(event.sequence in consumed, + "Unrecorded semantic mutation; no final physical " + "index checkpoint or command boundary.") + _require(state is not None and selected == indexed, + "Semantic history has no final physical index checkpoint.") + saved = _read_manifest_file(safe_path(recording.root, + SOURCE_MANIFEST_FILE)) + _require(saved == state, + "Saved source organization differs from recorded history.") + except (ValueError, OSError, KeyError, TypeError, AttributeError) as error: + recording.issue("source.organization.unsupported", str(error), + SOURCE_MANIFEST_FILE) + + +def semantic_request(request: dict) -> dict: + """Return explicit portable inputs, excluding live command identities. + + Parameters + ---------- + request: dict + Recorded semantic command request. + + Returns + ------- + dict + User's original edit choices and operation, without replay-local + project, request, revision, digest and preview identifiers. + + """ + return {key: value for key, value in request.items() if key not in ( + "project", "request_id", "revision", "sha256", "preview_id")} + + +def _portable_view(data: dict) -> dict: + """Normalize only source-relative native Path fields in view records. + + Parameters + ---------- + data: dict + Bound tool view or one group serialized from native Path objects. + + Returns + ------- + dict + Portable observation. Semantic identifiers, policy and order are + unchanged; historical absolute project paths are never interpreted. + + """ + result = dict(data) + for field in ("targets", "candidates", "evidence", "lookup", + "scope_operands"): + if isinstance(result.get(field), list): + result[field] = [p.replace("\\", "/") if isinstance(p, str) + else p for p in result[field]] + for field in ("anchor", "path"): + if isinstance(result.get(field), str): + result[field] = result[field].replace("\\", "/") + for field in ("groups", "unavailable"): + if isinstance(result.get(field), list): + result[field] = [_portable_view(row) if isinstance(row, dict) + else row for row in result[field]] + return result + + +def semantic_observations(op: TimelineOperation) -> list[dict]: + """Collect semantic state and bound source-view observations. + + Parameters + ---------- + op: TimelineOperation + Recorded command including its own diagnostics. + + Returns + ------- + list of dict + Ordered observations with event identity and portable state. + + """ + rows = [] + for event in op.events: + kind, data = event.event_type, event.details + value = None + if kind == OBSERVED or kind in (COMMITTED, RECONCILED): + value = {k: data[k] for k in ( + "reason", "revision", "sha256", "source_organization", + "selected", "pending", "pending_roles", "retained_versions", + "discovery", "changed", "error") if k in data} + elif kind.startswith(PREFIX) and kind.endswith(".completed"): + value = {k: data[k] for k in ( + "inspection", "proposed_source_organization", "revision", + "sha256", "source_organization", "changed", "discovery") + if k in data} + elif kind == "gui.question.request.started": + if "source_organization_revision" in data: + value = {k: data[k] for k in ( + "source_organization_revision", + "source_organization_sha256") if k in data} + elif kind == "tool.source_view.resolved": + value = _portable_view(data) + elif isinstance(data.get("source_operation"), dict): + value = {k: data[k] for k in ( + "source_operation", "groups", "requested_groups", + "selected_groups", "represented_groups", "represented_anchors", + "missing_groups", "missing_anchors", "unselected_groups", + "unselected_group_details", "physical_complete", "complete", + "requested_sources", "represented_sources", "missing_sources", + "unindexed_sources", "passage_count", "limits_hit") + if k in data} + if value is not None: + if kind == "retrieval.sources.ranked" and "groups" in value: + value = _portable_view(value) + rows.append({"event_type": kind, "sequence": event.sequence, + "value": value}) + return rows + + +def compare_semantics(original: TimelineOperation, + replayed: TimelineOperation) -> list[dict]: + """Compare semantic observations by event type and occurrence. + + Parameters + ---------- + original: TimelineOperation + Reference operation. + replayed: TimelineOperation + Corresponding replay operation. + + Returns + ------- + list of dict + Paired observations, explicitly unknown if one is unavailable. + + """ + def group(op): + """Assign occurrence numbers within each semantic event type. + + Parameters + ---------- + op: TimelineOperation + Recorded command containing semantic observations. + + Returns + ------- + dict + Observations keyed by event type and occurrence. + + """ + counts, rows = {}, {} + for row in semantic_observations(op): + kind = row["event_type"] + counts[kind] = counts.get(kind, 0) + 1 + rows[kind, counts[kind]] = row + return rows + + left, right = group(original), group(replayed) + pairs = [] + for key in sorted(left.keys() | right.keys()): + a, b = left.get(key), right.get(key) + equal = (a["value"] == b["value"] if a is not None and b is not None + else None) + pairs.append({"event_type": key[0], "occurrence": key[1], + "original": a, "replayed": b, "equal": equal}) + return pairs diff --git a/kilin/system_testing/analysis.py b/kilin/system_testing/analysis.py new file mode 100644 index 00000000..f089c0a1 --- /dev/null +++ b/kilin/system_testing/analysis.py @@ -0,0 +1,2491 @@ +"""Present KíLín comparison snapshots without rerunning an experiment. + +Key Features +------------ +- Read-only report discovery and visual, coverage-aware summaries. +- Side-by-side saved answers and expandable execution diagnostics. +- Optional exact model texts verified against recorded SHA-256 digests. +- Shared reference decoding for local diagnostics, with explicit read issues. +- Independent visual Markdown exports alongside native reports. + +Module Structure +---------------- +- Report loading and presentation helpers. +- Overview, operation and question renderers. +- Restricted local trace lookup and Markdown export. + +Examples +-------- +>>> from pathlib import Path +>>> from kilin.system_testing import analysis +>>> report = Path('workspaces/020_hello_world_comparison.json') +>>> data = analysis.load_report(report) # doctest: +SKIP +>>> analysis.overview(data) # doctest: +SKIP + +No model calls or network access are required. HTML is +escaped, and optional Markdown rendering disables active links and images. +The JSON snapshot is authoritative for the displayed metrics; inspecting +it does not revalidate the workspaces. + +""" + +from __future__ import annotations + +from collections import Counter +from difflib import unified_diff +from hashlib import sha256 +from html import escape +import json +import math +from pathlib import Path +from tempfile import NamedTemporaryFile + +from .comparison import COMPARISON_FORMAT_VERSION +from .traces import read_recording + +__all__ = [ + "load_report", "discover_reports", "overview", "batch_overview", + "question_explorer", "operation_explorer", "analysis_markdown", + "save_analysis", "event_inventory", "event_inventory_html", +] + +SIDES = ("original", "replayed") +METRICS = ( + ("token_f1", "Token F1"), ("embedding_cosine", "Embedding cosine"), + ("evidence_jaccard", "Evidence Jaccard"), + ("citation_jaccard", "Citation Jaccard"), +) +SUFFIX = "_comparison.json" + +# Scope every selector to the report. Jupyter's theme variables allow the +# same HTML output to be legible in light and dark themes. +STYLE = """""" + + +def _dict(value): + """Return a mapping or an empty mapping for unavailable sections. + + Parameters + ---------- + value: object + Recorded value to inspect or format. + + Returns + ------- + dict + Original mapping or an empty dictionary. + + """ + return value if isinstance(value, dict) else {} + + +def _list(value): + """Return a list or an empty list for unavailable inventories. + + Parameters + ---------- + value: object + Recorded value to inspect or format. + + Returns + ------- + list + Original list or an empty list. + + """ + return value if isinstance(value, list) else [] + + +def _at(value, *keys): + """Retrieve nested report fields without substituting missing values. + + Parameters + ---------- + value: object + Recorded value to inspect or format. + *keys: str + Nested dictionary keys, in traversal order. + + Returns + ------- + object + Nested value, or None when unavailable. + + """ + for key in keys: + value = _dict(value).get(key) + return value + + +def _number(value): + """Retain finite numeric measurements, excluding Boolean flags. + + Parameters + ---------- + value: object + Recorded value to inspect or format. + + Returns + ------- + int or float or None + Finite number, or None. + + """ + return (value if type(value) in (int, float) and math.isfinite(value) + else None) + + +def _format(value): + """Format measurements while distinguishing null, zero and false. + + Parameters + ---------- + value: object + Recorded value to inspect or format. + + Returns + ------- + str + Rendered or formatted text. + + """ + if value is None: + return "n/a" + if isinstance(value, bool): + return "Yes" if value else "No" + if isinstance(value, float): + return f"{value:.4g}" if math.isfinite(value) else "n/a" + if isinstance(value, (list, dict)): + return json.dumps(value, ensure_ascii=False, sort_keys=True) + return str(value) + + +def _seconds(value): + """Convert a recorded millisecond value to a labeled duration. + + Parameters + ---------- + value: object + Recorded value to inspect or format. + + Returns + ------- + str + Rendered or formatted text. + + """ + value = _number(value) + return "n/a" if value is None else f"{value / 1000:.3f} s" + + +def _e(value): + """Escape every data-derived value before insertion into HTML. + + Parameters + ---------- + value: object + Recorded value to inspect or format. + + Returns + ------- + str + Rendered or formatted text. + + """ + return escape(_format(value), quote=True) + + +def _table(headers, rows): + """Create a scrollable HTML table with escaped cells. + + Parameters + ---------- + headers: sequence[str] + Column headings in display order. + rows: iterable + Rows of values, one sequence per table row. + + Returns + ------- + str + Rendered or formatted text. + + """ + head = "".join(f"{_e(x)}" for x in headers) + body = "".join("" + "".join(f"{_e(x)}" for x in row) + + "" for row in rows) + return (f'
{head}' + f"{body}
") + + +def _section(title, body, *, expanded=False): + """Create a native collapsible panel, without JavaScript. + + Parameters + ---------- + title: str + Panel heading, escaped before insertion. + body: str + Trusted, already rendered HTML fragment. + expanded: bool + Whether the collapsible panel starts open. + + Returns + ------- + str + Rendered or formatted text. + + """ + state = " open" if expanded else "" + return (f'{_e(title)}' + f"
{body}
") + + +def _wrap(body): + """Wrap an HTML fragment in scoped Jupyter-compatible styling. + + Parameters + ---------- + body: str + Trusted, already rendered HTML fragment. + + Returns + ------- + str + Rendered or formatted text. + + """ + return STYLE + f'
{body}
' + + +def _raw(value): + """Present complete escaped JSON for detailed diagnostic inspection. + + Parameters + ---------- + value: object + Recorded value to inspect or format. + + Returns + ------- + str + Rendered or formatted text. + + """ + return "
" + _e(json.dumps(value, indent=2, ensure_ascii=False)) + (
+        "
" + ) + + +def _pair(left, right): + """Place trusted rendered fragments in labeled side-by-side panes. + + Parameters + ---------- + left: str + Original-side text or rendered content. + right: str + Replay-side text or rendered content. + + Returns + ------- + str + Rendered or formatted text. + + """ + return ('
' + '

Original

' + f'{left}
' + f'

Replay

{right}
') + + +def _card(label, value, detail="", tone="muted"): + """Create a compact metric tile with an optional status tone. + + Parameters + ---------- + label: str + Human-readable label. + value: object + Recorded value to inspect or format. + detail: str + Optional supplementary text. + tone: str + Trusted CSS status class suffix. + + Returns + ------- + str + Rendered or formatted text. + + """ + return (f'
{_e(label)}' + f'
{_e(value)}
' + f'
{_e(detail)}
') + + +def _bar(value, maximum=1, *, original=False): + """Scale a nonnegative finite number; missing has no bar. + + Parameters + ---------- + value: object + Recorded value to inspect or format. + maximum: float + Positive reference scale for the bar. + original: bool + Use the original-side bar style. + + Returns + ------- + str + Rendered or formatted text. + + """ + value = _number(value) + if value is None or maximum <= 0 or value < 0: + return "" + width = min(value / maximum, 1) * 100 + cls = "ks-fill ks-fill-original" if original else "ks-fill" + return (f'
') + + +def _metric_value(value): + """Format a similarity on its native scale, including negatives. + + Parameters + ---------- + value: object + Recorded value to inspect or format. + + Returns + ------- + str + Rendered or formatted text. + + """ + value = _number(value) + return "n/a" if value is None else f"{value:.4f}" + + +def _questions(data): + """Return aligned committed questions in report order. + + Parameters + ---------- + data: dict + Saved comparison snapshot; never modified. + + Returns + ------- + list[dict] + Aligned question operations in chronological order. + + """ + return [op for op in data["operations"] + if isinstance(op.get("question"), dict)] + + +def _question_metrics(op): + """Extract the four similarity measurements from one question pair. + + Parameters + ---------- + op: dict + One aligned operation from the comparison. + + Returns + ------- + tuple + Token F1, embedding cosine, evidence and citation overlap. + + """ + q = op["question"] + return ( + _at(q, "answer", "token_f1"), + _at(q, "answer", "embedding", "cosine"), + _at(q, "evidence", "overlap", "jaccard"), + _at(q, "evidence", "citations", "overlap", "jaccard"), + ) + + +def _agreement(data): + """Count observed equality separately from measurement coverage. + + Parameters + ---------- + data: dict + Saved comparison snapshot; never modified. + + Returns + ------- + list[tuple] + Agreement counts with measured and total coverage. + + """ + questions = _questions(data) + rows = [] + for field, label in (("intent", "Intent"), + ("retrieval_mode", "Retrieval mode"), + ("tool", "Functional tool result")): + if field == "tool": + values = [] + for op in questions: + q = op["question"] + if "tool_comparison" in q: + values.append(_at(q, "tool_comparison", + "functional_equal")) + else: + pair = _dict(q.get("tool")) + if all(side in pair for side in SIDES): + values.append(pair["original"] == pair["replayed"]) + measured = [v for v in values if type(v) is bool] + rows.append((label, sum(measured), len(measured), + len(questions))) + continue + pairs = [_dict(op["question"].get(field)) for op in questions] + available = [pair for pair in pairs if all( + side in pair and (field == "tool" or pair[side] is not None) + for side in SIDES)] + rows.append((label, sum(pair["original"] == pair["replayed"] + for pair in available), + len(available), len(questions))) + return rows + + +def _mapped_state(data): + """Count recorded final-state equality only for available flags. + + Parameters + ---------- + data: dict + Saved comparison snapshot; never modified. + + Returns + ------- + list[tuple] + Mapped-state agreement counts and coverage. + + """ + state = data["final_state"] + rows = [] + for key, label in (("name_equal", "Conversation name"), + ("archival_equal", "Archival state"), + ("lineage_equal", "Lineage"), + ("turn_prefix_equal", "Mapped turn prefix"), + ("feedback_equal", "Feedback")): + items = (_list(state.get("feedback")) if key == "feedback_equal" + else _list(state.get("conversations"))) + flag = "equal" if key == "feedback_equal" else key + observed = [item[flag] for item in items + if type(item.get(flag)) is bool] + rows.append((label, sum(observed), len(observed), len(items))) + return rows + + +def _alignment_label(data): + """Describe strict alignment with an optional inspection note. + + Parameters + ---------- + data: dict + Saved comparison snapshot; never modified. + + Returns + ------- + str + Alignment label, including inspection-only annotation. + + """ + if data.get("inspection", data.get("batch_inspection")): + return "diverged (inspection only)" + return data["alignment"].get("status") + + +def _status(data): + """Translate only structural alignment status into a display tone. + + Parameters + ---------- + data: dict + Saved comparison snapshot; never modified. + + Returns + ------- + str + CSS status tone. + + """ + status = data["alignment"].get("status") + return {"complete": "ok", "invalid_recording": "bad", + "diverged": "warn"}.get(status, "muted") + + +def load_report(path: str | Path) -> dict: + """Read one native comparison snapshot of the supported format. + + Parameters + ---------- + path : str or pathlib.Path + Local regular JSON comparison report. Symlinks are rejected. + + Returns + ------- + dict + Saved report, with its original measurements unchanged. + + Raises + ------ + ValueError + Unsupported schema, malformed sections or invalid event inventory. + OSError + Report cannot be read. + + """ + path = Path(path) + if path.is_symlink() or not path.is_file(): + raise ValueError(f"Expected a regular comparison report: {path}") + data = json.loads(path.read_text(encoding="utf-8")) + if type(_at(data, "format_version")) is not int or ( + data["format_version"] != COMPARISON_FORMAT_VERSION): + raise ValueError("Unsupported comparison report format version; " + "regenerate the comparison report.") + for key in ("alignment", "summary", "original", "replayed", "files", + "final_state", "embedding_evaluation"): + if not isinstance(data.get(key), dict): + raise ValueError(f"Invalid report section: {key}") + for key in ("operations", "report_issues"): + if not isinstance(data.get(key), list): + raise ValueError(f"Invalid report section: {key}") + if any(not isinstance(op, dict) for op in data["operations"]): + raise ValueError("Invalid operation record.") + if data["alignment"].get("status") not in ( + "complete", "diverged", "invalid_recording"): + raise ValueError("Unknown alignment status.") + if not event_inventory(data)["complete"]: + raise ValueError("Missing or invalid independent event counts; " + "regenerate the comparison report.") + return data + + +def discover_reports(directory: str | Path) -> tuple[dict, dict]: + """Discover direct native report files, isolating unreadable reports. + + Parameters + ---------- + directory : str or pathlib.Path + Real workspace parent directory. + + Returns + ------- + tuple[dict, dict] + Snapshots and error messages keyed by experiment stem. Discovery + does not use absolute paths embedded in the recorded reports. + + """ + directory = Path(directory) + if directory.is_symlink() or not directory.is_dir(): + raise ValueError(f"Expected a real directory: {directory}") + reports, errors = {}, {} + for path in sorted(directory.glob(f"*{SUFFIX}")): + stem = path.name.removesuffix(SUFFIX) + try: + reports[stem] = load_report(path) + except (OSError, ValueError, TypeError) as error: + errors[stem] = str(error) + return reports, errors + + +def _diagnostics(data): + """Show validation, unmatched operations, and report-level issues. + + Parameters + ---------- + data: dict + Saved comparison snapshot; never modified. + + Returns + ------- + str + Rendered or formatted text. + + """ + blocks = [] + for side in SIDES: + value = data[side] + rows = [] + for key, label in (("validation_issues", "Issue"), + ("validation_warnings", "Warning")): + for issue in _list(value.get(key)): + rows.append((label, issue.get("code"), issue.get("sequence"), + issue.get("path"), issue.get("message"))) + body = _table(("Level", "Code", "Sequence", "Path", "Message"), rows) + blocks.append(body if rows else "

No recorded diagnostics.

") + alignment = data["alignment"] + body = _pair(*blocks) + if alignment.get("reason") is not None: + body += f'

{_e(alignment["reason"])}

' + if data.get("inspection", data.get("batch_inspection")): + note = data.get("inspection", data.get("batch_inspection")) + body += "

" + _e(note["message"]) + "

" + if data.get("reference_publication"): + body += _section("Reference publication", _raw( + data["reference_publication"])) + if data.get("replay_execution"): + body += _section("Replay execution provenance", _raw( + data["replay_execution"])) + for key in ("original_unmatched", "replayed_unmatched"): + rows = _list(alignment.get(key)) + if rows: + body += _section(key.replace("_", " ").title(), _raw(rows)) + if data["report_issues"]: + body += _section("Report issues", _raw(data["report_issues"]), + expanded=True) + return body + + +def _timings(data): + """Plot paired outer command durations on one shared scale. + + Parameters + ---------- + data: dict + Saved comparison snapshot; never modified. + + Returns + ------- + str + Rendered or formatted text. + + """ + ops = data["operations"] + times = [_number(_at(op, "duration", side, "ms")) + for op in ops for side in SIDES] + maximum = max([x for x in times if x is not None] + [1]) + body = ('

Original: slate · Replay: blue. ' + 'One common scale; missing durations have no bar.

') + for op in ops: + title = f'{op.get("original_sequence")} · {op.get("kind")}' + q = _at(op, "question", "question") + if q is not None: + title += " · " + str(q) + body += f'

{_e(title)}

' + for side in SIDES: + value = _at(op, "duration", side, "ms") + body += (f'
{_e(side.title())}: {_e(_seconds(value))}' + + _bar(value, maximum, original=side == "original") + + "
") + body += "
" + return body if ops else "

No paired operations.

" + + +def _state(data): + """Summarize workspace-level settings, tokens and final inventories. + + Parameters + ---------- + data: dict + Saved comparison snapshot; never modified. + + Returns + ------- + str + Rendered or formatted text. + + """ + rows = [] + for key, label in (("usage", "Saved turn"), + ("traced_chat_usage", "Traced call")): + for kind in ("input_tokens", "output_tokens"): + cells = [f"{label} · {kind}"] + for side in SIDES: + entry = _dict(_at(data, side, key, kind)) + coverage = ("available_turns", "total_turns") if key == ( + "usage") else ("available_records", "total_records") + cells.extend((_format(entry.get("recorded_total")), + f'{_format(entry.get(coverage[0]))}/' + f'{_format(entry.get(coverage[1]))}')) + rows.append(cells) + body = ("

Token usage and coverage

" + '

Saved-turn and traced-call counters ' + 'overlap; do not add them.

' + _table( + ("Boundary", "Original", "Coverage", "Replay", "Coverage"), + rows)) + diffs = [(op.get("original_sequence"), item) + for op in data["operations"] + for item in _list(op.get("settings_differences"))] + body += "

Recorded settings differences

" + body += (_table(("Sequence", "Difference"), diffs) if diffs else + "

No differences reported for the matched operations.

") + rows = [] + for kind, inventory in data["files"].items(): + changes = _dict(_at(inventory, "changes")) + rows.append([kind] + [len(changes[k]) if isinstance( + changes.get(k), list) else None for k in + ("added", "removed", "changed", "unchanged")]) + body += "

Final file inventories

" + _table( + ("Directory", "Added", "Removed", "Changed", "Unchanged"), rows) + body += _section("Complete file identities and inventory issues", + _raw(data["files"])) + body += "

Final mapped state

" + _table( + ("Observation", "Equal", "Available", "Mapped"), _mapped_state(data)) + body += _section("Final mapped conversation and feedback state", + _raw(data["final_state"])) + body += _section("Recorded environments and model identities", _pair( + *[_raw({k: data[s].get(k) for k in ("environments", "models")}) + for s in SIDES])) + if any("plugin_provenance" in data[s] for s in SIDES): + body += _section("Recorded plugin identities", _pair( + *[_raw(data[s].get("plugin_provenance")) for s in SIDES])) + changes = [(op.get("original_sequence"), pair) + for op in data["operations"] + for pair in _list(op.get("plugin_provenance")) + if pair.get("status") != "equal"] + body += _section("Plugin identity differences and unknowns", + _table(("Sequence", "Observation"), changes)) + if any(data[s].get("source_organization") for s in SIDES): + body += _section("Recorded semantic source organization", _pair( + *[_raw(data[s].get("source_organization")) for s in SIDES])) + changes = [(op.get("original_sequence"), pair) + for op in data["operations"] + for pair in _list(op.get("source_organization")) + if pair.get("equal") is not True] + body += _section("Semantic source differences and unknowns", + _table(("Sequence", "Observation"), changes)) + return body + + +def overview(data: dict) -> str: + """Render a visual overview of a comparison snapshot. + + Parameters + ---------- + data : dict + Native version-1 comparison report. + + Returns + ------- + str + HTML containing alignment, coverage, per-question similarities, + paired timings, validation and workspace-state diagnostics. + + """ + a, s = data["alignment"], data["summary"] + ops, questions = data["operations"], _questions(data) + diffs = sum(len(_list(op.get("settings_differences"))) for op in ops) + matched = a.get("matched_operations") + body = ("

Workspace comparison

" + '

Saved measurement snapshot. ' + 'Similarity is not a correctness or quality verdict.

') + body += '
' + _card( + "Alignment", _alignment_label(data), a.get("reason") or "", + _status(data)) + body += _card("Matched operations", matched, + "Original / replay: " + " / ".join(_format(len( + _list(data[k].get("operations")))) for k in SIDES)) + body += _card("Matched questions", s.get("questions"), + f'{_format(s.get("exact_answers"))} exact saved answers') + body += _card("Settings differences", diffs, "Matched operations") + for key, label in METRICS: + metric = _dict(s.get(key)) + body += _card(label, _metric_value(metric.get("mean")), + f'{_format(metric.get("available"))}/' + f'{_format(metric.get("total"))} available') + body += "
" + body += _table(("Workspace", "Valid", "Events", "Commands"), [ + (side.title(), data[side].get("valid"), data[side].get("event_count"), + len(_list(data[side].get("operations")))) for side in SIDES]) + body += _section("Validation and alignment diagnostics", _diagnostics( + data), expanded=a.get("status") != "complete") + if "first_divergence" in data: + body += _section("First observed divergence (not causal)", + _raw(data["first_divergence"]), expanded=True) + body += "

Question agreement

" + if not questions: + body += "

No aligned committed question pairs.

" + else: + body += _table(("Question", "Exact", "Normalized", "Token F1", + "Cosine", "Evidence", "Citation", + "Intent O / R"), [ + (f'Q{i} · {op["question"].get("question")}', + _at(op, "question", "answer", "exact_equal"), + _at(op, "question", "answer", "normalized_equal"), + *(_metric_value(x) for x in _question_metrics(op)), + " / ".join(_format(_at(op, "question", "intent", side)) + for side in SIDES)) + for i, op in enumerate(questions, 1)]) + for i, op in enumerate(questions, 1): + value = _question_metrics(op)[0] + body += (f'
Q{i} · Token F1: {_e(_metric_value(value))}
' + + _bar(value)) + body += "

Recorded behavior agreement

" + _table( + ("Observation", "Equal", "Available", "Question pairs"), + _agreement(data)) + body += ('

Two null tool summaries are equal ' + 'recorded absences, not proof that no tool ran.

') + body += "

Effective model-call reproducibility

" + ( + _model_reproducibility_html(data)) + body += "

Recorded tool outcomes

" + _tool_outcomes_html(data) + body += _section("Stage-specific performance", _performance_html(data), + expanded=True) + body += "

Recorded operation durations

" + _timings(data) + duration = _dict(s.get("paired_command_duration_ms")) + body += ('

Paired measured total: ' + f'{_e(_seconds(duration.get("original")))} / ' + f'{_e(_seconds(duration.get("replayed")))} · ' + f'{_e(duration.get("available"))}/{_e(duration.get("total"))} ' + 'operations. Nested diagnostics are not summed.

') + body += _state(data) + body += _section("Embedding evaluation", _raw( + data["embedding_evaluation"])) + return _wrap(body) + + +def event_inventory(data: dict) -> dict: + """Check the independent event inventories recorded for both sides. + + Counts must reconcile with each recording's total independently of + alignment. Missing or malformed inventories cannot establish event + differences and are never reconstructed from aligned operations. + + Parameters + ---------- + data: dict + Saved comparison snapshot; never modified. + + Returns + ------- + dict + Count coverage, per-side inventories and event-type differences. + + """ + counts = {side: Counter() for side in SIDES} + expected = {side: _at(data, side, "event_count") for side in SIDES} + complete = True + for side in SIDES: + raw = _at(data, side, "event_counts") + if not isinstance(raw, dict) or not all( + isinstance(k, str) and type(v) is int and v >= 0 + for k, v in raw.items()): + complete = False + continue + counts[side].update(raw) + if (type(expected[side]) is not int or + sum(counts[side].values()) != expected[side]): + complete = False + differences = [] + if complete: + for name in sorted(counts["original"].keys() | + counts["replayed"].keys()): + old, new = (counts[side][name] for side in SIDES) + if old != new: + differences.append({"event_type": name, "original": old, + "replayed": new, "delta": new - old}) + return {"complete": complete, "expected": expected, + "counts": {side: dict(counts[side]) for side in SIDES}, + "differences": differences} + + +def _local_trace_data(root): + """Decode local diagnostics through the authoritative recording reader. + + Parameters + ---------- + root: pathlib.Path or None + Explicit local workspace directory. + + Returns + ------- + dict + Decoded events, readable issues and event-specific decoding failures. + Partial recordings remain inspectable, with all issues retained. + + """ + empty = {"events": [], "errors": [], "invalid": set()} + if root is None: + empty["errors"].append("Local workspace unavailable.") + return empty + try: + root = Path(root) + trace_dir = root / "logs" / "traces" + if (root.is_symlink() or (root / "logs").is_symlink() + or trace_dir.is_symlink() or not trace_dir.is_dir()): + raise ValueError("Local trace directory unavailable.") + recording = read_recording(root) + except (OSError, ValueError, TypeError, RecursionError) as error: + empty["errors"].append(str(error)) + return empty + errors = [] + invalid = set() + for issue in recording.issues: + location = issue.path or "workspace" + if issue.sequence is not None: + location += f" (sequence {issue.sequence})" + invalid.add((issue.path, issue.sequence)) + errors.append(f"{location}: {issue.code}: {issue.message}") + return {"events": recording.events, "errors": errors, + "invalid": invalid} + + +def _local_events(root, kinds): + """Read resolved local events of selected types, including merged ends. + + Parameters + ---------- + root: pathlib.Path + Explicit local repository or workspace directory. + kinds: set[str] + Recorded event types to include. + + Returns + ------- + dict or None + Local events and decoding issues, or None for an omitted root. + Failed payloads remain labelled as unverified details. Other decoder + passes may have expanded independent fields, so these are not + claimed to be the raw stored payload or a verified observation. + + """ + if root is None: + return None + local = _local_trace_data(root) + records = [] + for event in local["events"]: + if event.event_type not in kinds: + continue + record = {"path": event.path, "location": event.location, + "metadata": event.metadata, + "exact_content": event.exact_content} + if (event.path, event.sequence) in local["invalid"]: + record.update(details=None, unverified_details=event.details) + else: + record["details"] = event.details + records.append(record) + return {"events": records, "errors": local["errors"]} + + +def event_inventory_html(data: dict, *, original=None, replayed=None, + include_details: bool = False) -> str: + """Render reconciled event counts and optional local trace details. + + Local references are verified and expanded by the recording reader. + Event text is not verified against the saved report and never changes + its metrics. Events of a changed type are listed on both sides without + claiming individual event pairing. Decoding issues remain visible. + + Parameters + ---------- + data: dict + Saved comparison snapshot; never modified. + original: str or pathlib.Path or None + Explicit local reference directory, if available. + replayed: str or pathlib.Path or None + Explicit local replay directory, if available. + include_details: bool + Include locally read event details, not verified against the + report. + + Returns + ------- + str + Rendered or formatted text. + + """ + result = event_inventory(data) + body = "

Event inventory

" + body += _table(("Side", "Reported total", "Counted in report"), [ + (side, result["expected"][side], + sum(result["counts"][side].values())) for side in SIDES]) + if not result["complete"]: + return _wrap(body + "

Complete event inventory unavailable; " + "do not interpret partial counts as differences. " + "Regenerate the comparison report.

") + differences = result["differences"] + if differences: + body += _table(("Event type", "Original", "Replay", "Delta"), [ + (r["event_type"], r["original"], r["replayed"], r["delta"]) + for r in differences]) + if include_details: + kinds = {item["event_type"] for item in differences} + body += _section("Local events of changed types", _pair( + *[_raw(_local_events(root, kinds)) + for root in (original, replayed)])) + body += ("

Local trace details may differ from the saved " + "snapshot if the workspace was changed.

") + else: + body += "

Every recorded event-type count agrees.

" + names = sorted(set(result["counts"]["original"]) | + set(result["counts"]["replayed"])) + body += _section("Full event inventory", _table( + ("Event type", "Original", "Replay"), [ + (name, *(result["counts"][side].get(name, 0) for side in SIDES)) + for name in names])) + body += ("

Count differences are descriptive; they are not alone " + "evidence of a replay defect.

") + return _wrap(body) + + +def _flag_counts(values): + """Count measured Boolean observations without imputing missing values. + + Parameters + ---------- + values: iterable + Boolean flags or unavailable observations. + + Returns + ------- + dict + Equal, available and total counts. + + """ + values = list(values) + observed = [v for v in values if type(v) is bool] + return {"equal": sum(observed), "available": len(observed), + "total": len(values)} + + +def _release_measurements(data: dict) -> dict: + """Collect a compact set of measurements for one point comparison. + + Parameters + ---------- + data: dict + Native comparison snapshot, possibly from an incomplete recording. + + Returns + ------- + dict + Independent recording coverage and paired behavioral observations. + + """ + questions = _questions(data) + summary = data["summary"] + agreement = {label: dict(equal=equal, available=available, total=total) + for label, equal, available, total in _agreement(data)} + agreement["Exact saved answers"] = _flag_counts( + _at(op, "question", "answer", "exact_equal") for op in questions) + context = [row for op in data["operations"] + for row in _list(op.get("context"))] + for label, kinds, field in ( + ("Final history selection", ("history.selection.result",), + "final_turn_ids"), + ("Memory inventory identities", ("memory.sync.result", + "project.memory.sync.result"), None), + ("Retrieved memory identities", ("conversation_memory.retrieved",), + None), + ): + if not all("context" in op for op in data["operations"]): + continue + agreement[label] = _flag_counts( + _at(row, "selection_equal", field) if field else + row.get("identity_equal") for row in context + if row.get("event_type") in kinds) + for name, label in (("evidence_jaccard", "Exact evidence agreement"), + ("citation_jaccard", "Resolved citation agreement")): + index = 2 if name == "evidence_jaccard" else 3 + values = [_question_metrics(op)[index] for op in questions] + agreement[label] = _flag_counts( + v == 1 if _number(v) is not None else None for v in values) + model = _dict(summary.get("model_reproducibility")) + for label, category in (("Comparable T=0 model outputs", + "zero_temperature"), + ("Comparable T>0 model outputs", + "nonzero_temperature")): + metric = _at(model, "conditional", category) + if isinstance(metric, dict): + agreement[label] = { + "equal": metric.get("equal_outputs"), + "available": metric.get("available_outputs"), + "total": metric.get("identical_inputs"), + } + coverage = {} + for name, field, matched in ( + ("operations", "operations", data["alignment"].get( + "matched_operations")), + ("questions", "saved_questions", summary.get("questions")), + ): + coverage[name] = {"matched": matched, **{ + side: len(data[side][field]) if isinstance(data[side].get(field), + list) else None + for side in SIDES}} + return {"coverage": coverage, "agreement": agreement, + "token_f1": summary.get("token_f1"), + "tool_transitions": summary.get("tool_transitions"), + "model_reproducibility": model or None} + + +def _coverage_text(numerator, denominator): + """Format explicit counts; missing coverage is not a successful zero. + + Parameters + ---------- + numerator: int or None + Measured or equal count. + denominator: int or None + Relevant recorded population. + + """ + if type(numerator) is not int or type(denominator) is not int: + return "n/a" + return f"{numerator}/{denominator}" + + +def _release_rows(rows): + """Build the compact experiment table shared by HTML and Markdown. + + Parameters + ---------- + rows: list[dict] + Batch action rows containing the current or explicitly saved metrics. + + Returns + ------- + list[tuple] + Execution status and paired coverage, without a composite score. + + """ + result = [] + for row in rows: + metrics = _dict(row.get("release_measurements")) + cover = _dict(metrics.get("coverage")) + exact = _at(metrics, "agreement", "Exact saved answers") or {} + counts = [] + for name in ("operations", "questions"): + record = _dict(cover.get(name)) + counts.append(_coverage_text(record.get("matched"), + record.get("original"))) + result.append((row.get("experiment"), row.get("execution_status"), + row.get("replay_status"), *counts, + _coverage_text(exact.get("equal"), + exact.get("available")), + _metric_value(_at(metrics, "token_f1", "mean")), + _at(row, "issue_counts", "review"))) + return result + + +def _release_totals(rows, *, include_saved=False): + """Summarize one invocation, keeping saved snapshots separate. + + Parameters + ---------- + rows: list[dict] + Batch action rows with compact measurement snapshots. + include_saved: bool, optional + Include saved snapshots for explicitly report-only displays. + + Returns + ------- + dict + Execution counters, measured coverage and tool outcome counts. + + """ + execution = Counter(row.get("execution_status") for row in rows) + eligible = [row["release_measurements"] for row in rows + if isinstance(row.get("release_measurements"), dict) and + (include_saved or row.get("snapshot") == "current")] + transitions = Counter() + coverage = {name: Counter() for name in ("operations", "questions")} + for item in eligible: + transitions.update(_dict(item.get("tool_transitions"))) + for name in coverage: + record = _dict(_at(item, "coverage", name)) + for key, value in record.items(): + if type(value) is int: + coverage[name][key] += value + coverage[name][key + "_snapshots"] += 1 + return {"complete": execution["complete"], + "blocked": execution["blocked"], + "inspection": execution["inspection only"], + "saved": execution["saved snapshot"], + "fresh": sum(r.get("replay_status") == "completed" for r in rows), + "review_experiments": sum(bool(_at(r, "issue_counts", "review")) + for r in rows), + "snapshots": len(eligible), "coverage": coverage, + "tool_transitions": dict(transitions)} + + +def _release_agreement_rows(rows, *, include_saved=False): + """Aggregate counts, not averages of per-experiment percentages. + + Parameters + ---------- + rows: list[dict] + Batch action rows with compact measurement snapshots. + include_saved: bool, optional + Include saved reports for an explicitly historical display. + + Returns + ------- + list[tuple] + Metric label, equal count, available count, population and snapshot + coverage. + A metric absent from an old snapshot is not imputed. + + """ + sums = {} + snapshots = 0 + for row in rows: + if not include_saved and row.get("snapshot") != "current": + continue + metrics = row.get("release_measurements") + if not isinstance(metrics, dict): + continue + snapshots += 1 + for label, value in _dict(metrics.get("agreement")).items(): + if all(type(value.get(k)) is int + for k in ("equal", "available", "total")): + sums.setdefault(label, Counter()).update(value) + sums[label]["snapshots"] += 1 + return [(label, value["equal"], value["available"], value["total"], + f'{value["snapshots"]}/{snapshots}') + for label, value in sums.items()] + + +def _model_reproducibility_html(data): + """Show actual-input comparisons and conditional output coverage. + + Parameters + ---------- + data: dict + Saved comparison snapshot. + + Returns + ------- + str + Escaped HTML tables with explicit measurement boundaries. + + """ + model = _at(data, "summary", "model_reproducibility") + if not isinstance(model, dict): + return "

Effective model-call measurements unavailable.

" + body = (f'

Paired calls: {_e(model.get("paired_calls"))}; ' + f'unpaired inputs: {_e(model.get("unpaired_inputs"))}.

') + body += _table(("Observation", "Equal", "Available", "Paired calls"), [ + (key, value.get("equal"), value.get("available"), value.get("total")) + for key, value in _dict(model.get("agreement")).items()]) + body += _table(("Conditional category", "Equal outputs", + "Available outputs", "Identical recorded inputs"), [ + (key, value.get("equal_outputs"), value.get("available_outputs"), + value.get("identical_inputs")) for key, value in + _dict(model.get("conditional")).items()]) + body += ("

Conditional agreement uses equal recorded model revision, " + "backend, device, effective settings, rendered prompt and token " + "count. Normalized prompts are diagnostic only. This does not " + "establish identical unrecorded runtime state.

") + return body + + +def _performance_html(data): + """Show category timing and throughput without summing nested spans. + + Parameters + ---------- + data: dict + Comparison snapshot with independent full-workspace performance. + + Returns + ------- + str + Escaped timing observations and coverage, or unavailable note. + + """ + performance = data.get("performance") + if not isinstance(performance, dict): + return "

Stage-specific performance unavailable.

" + names = dict.fromkeys(name for side in SIDES for name in + _dict(_at(performance, side, "spans"))) + rows = [] + for name in names: + metrics = [_dict(_at(performance, side, "spans", name)) + for side in SIDES] + rows.append((name, *[value for metric in metrics for value in ( + _seconds(metric.get("duration_ms")), + _coverage_text(metric.get("available"), metric.get("total")))])) + body = _table(("Category", "Original", "Coverage", "Replay", "Coverage"), + rows) + body += _table(("Rate", "Original tokens/s", "Coverage", + "Replay tokens/s", "Coverage"), [ + (name, *[value for side in SIDES for value in ( + _at(performance, side, "throughput", name, "tokens_per_second"), + _coverage_text(_at(performance, side, "throughput", name, + "available"), _at(performance, side, + "throughput", name, + "total")))]) + for name in ("generation", "reply")]) + body += ("

Whole valid recordings, not only matched operations. " + "Nested intervals within a category and clock domain are merged; " + "categories overlap and are not additive. Rates use recorded " + "generated-token counts and include prompt processing; reply " + "timing includes additional overhead. Conditions are not " + "controlled, so no performance-regression verdict is " + "implied.

") + return body + + +def _tool_outcomes_html(data): + """Display paired tool transitions and their saved reasons and outputs. + + Parameters + ---------- + data: dict + Saved comparison snapshot. + + Returns + ------- + str + Concise transition table with expandable full outcome records. + + """ + rows, detail = [], "" + for i, op in enumerate(_questions(data), 1): + tools = _dict(_at(op, "question", "tool_comparison")) + transition = tools.get("transition") + if transition in (None, "not_applicable"): + continue + outcomes = _dict(tools.get("outcomes")) + rows.append((f"Q{i}", *(_at(outcomes, side, "status") + for side in SIDES), transition, + *(_at(outcomes, side, "tool") for side in SIDES))) + detail += _section(f"Q{i} · {transition}", _raw(outcomes)) + if not rows: + return "

No paired applicable tool outcomes measured.

" + return (_table(("Question", "Original", "Replay", "Transition", + "Original tool", "Replay tool"), rows) + + "

Unknown completion is not proof of success. Historical " + "generator coverage is separate.

" + detail) + + +def batch_overview(reports: dict, errors: dict | None = None, + *, runs: list | None = None) -> str: + """Render cross-experiment measurements without a composite score. + + Parameters + ---------- + reports : dict + Comparison snapshots keyed by experiment stem. + errors : dict, optional + Report discovery errors keyed by stem. + runs : list, optional + Current batch execution rows. These remain separate from saved + report measurements so an old report cannot imply a new run passed. + + Returns + ------- + str + Visual dashboard and isolated run or report errors. + + """ + # Associate only the current invocation's rows with their snapshots. + # A report-only display is explicitly saved data, never a new test pass. + if runs is None: + rows = [{"experiment": name, "execution_status": "saved snapshot", + "snapshot": "saved", "release_measurements": + _release_measurements(data)} + for name, data in reports.items()] + else: + rows = [dict(row) for row in runs] + for row in rows: + name = str(row.get("experiment", "")).removesuffix("_original") + if "release_measurements" not in row and name in reports: + row["release_measurements"] = _release_measurements( + reports[name]) + ordered = sorted(rows, key=lambda row: row.get("experiment", "")) + totals = _release_totals(rows, include_saved=runs is None) + body = "

Release verification

" + if runs is not None: + body += '
' + "".join(( + _card("Current complete comparisons", + f'{totals["complete"]}/{len(rows)}', tone="ok" if + totals["complete"] == len(rows) and rows else "muted"), + _card("Blocking experiments", totals["blocked"], tone="bad" if + totals["blocked"] else "muted"), + _card("Fresh completed replays", totals["fresh"]), + _card("Experiments with review findings", + totals["review_experiments"], tone="warn" if + totals["review_experiments"] else "muted"))) + "
" + body += (f'

Inspection-only comparisons: ' + f'{_e(totals["inspection"])}; ' + f'saved snapshots: {_e(totals["saved"])}. A comparison-only ' + 'run does not count as a fresh replay.

') + else: + body += "

Saved reports only; no current execution verified.

" + body += ("

Critical: blocking recording, replay or report failures. " + "Review: differences or explicit incomplete outcomes requiring " + "inspection. Information: descriptive observations. Neither " + "complete execution nor exact text proves answer " + "correctness.

") + body += _table(("Experiment", "Execution", "Replay", "Operations M/O", + "Questions M/O", "Exact answers", "Token F1", + "Review groups"), _release_rows(ordered)) + body += '

M/O = matched / recorded original; ' + body += 'invalid recordings may contain unverified observations. ' + body += ('Replay counts and unmatched operations are in detailed ' + 'reports.

') + if totals["snapshots"]: + body += "

Measurement coverage

" + body += _table(("Boundary", "Matched", "Original", "Replay"), [ + (name, *(value.get(key) if value.get(key + "_snapshots") == + totals["snapshots"] else None for key in + ("matched", "original", "replayed"))) + for name, value in totals["coverage"].items()]) + body += "

Behavioral agreement

" + _table( + ("Observation", "Equal", "Available", "Total", "Snapshots"), + _release_agreement_rows(rows, include_saved=runs is None)) + body += ('

Counts use available observations ' + 'from current comparisons (or explicitly saved reports in ' + 'report-only view). Unavailable metrics are not failures or ' + 'successes. Context metrics count occurrences, not ' + 'questions. Snapshots counts reports containing each ' + 'metric. No similarity threshold or composite score.

') + body += "

Recorded tool outcomes

" + _table( + ("Transition", "Questions"), sorted(totals[ + "tool_transitions"].items())) + body += "

Unknown tool completion is not proof of success.

" + else: + body += "

No current comparison measurements available.

" + if runs is not None: + body += "

Findings requiring attention

" + findings = [(row, group) for row in ordered + for group in _list(row.get("issue_groups")) + if group.get("severity") != "info"] + for row, group in sorted(findings, key=lambda pair: ( + pair[1].get("severity") != "critical", + pair[0].get("experiment", ""))): + number = group.get("question_number") + where = f" · Q{number}" if number is not None else "" + title = (f'{row.get("experiment")}{where} · ' + f'{group.get("severity")} · {group.get("code")} ' + f'({len(group.get("issues", []))} observations)') + body += _section(title, _table( + ("Code", "Sequence", "Observation"), [ + (i.get("code"), i.get("sequence"), i.get("message")) + for i in _list(group.get("issues"))]), + expanded=group.get("severity") == "critical") + if not findings: + body += "

No critical or review groups recorded.

" + body += _section("Artifact and snapshot status", _table( + ("Experiment", "Snapshot", "Comparison notebook", + "Answer notebook"), + [(r.get("experiment"), r.get("snapshot"), + _at(r, "notebooks", "comparison", "status"), + _at(r, "notebooks", "answers", "status")) for r in ordered])) + for row in ordered: + info = [i for i in _list(row.get("issues")) + if i.get("severity") == "info"] + if info: + body += _section(f'{row.get("experiment")} · information', + _table(("Code", "Sequence", "Observation"), [ + (i.get("code"), i.get("sequence"), + i.get("message")) for i in info])) + if reports: + body += "

Detailed experiment measurements

" + for name, data in sorted(reports.items()): + summary = data["summary"] + table = _table(("Metric", "Mean", "Available", "Total"), [ + (label, _metric_value(_at(summary, key, "mean")), + _at(summary, key, "available"), _at(summary, key, "total")) + for key, label in METRICS]) + duration = _dict(summary.get("paired_command_duration_ms")) + table += (f'

Paired command duration: ' + f'{_e(_seconds(duration.get("original")))} / ' + f'{_e(_seconds(duration.get("replayed")))}.

') + table += _section("Effective model-call measurements", + _model_reproducibility_html(data)) + table += _section("Tool outcome transitions", + _tool_outcomes_html(data)) + table += _section("Recorded performance", _performance_html(data)) + body += _section(name + " · " + str(_alignment_label(data)), + table) + if errors: + body += "

Report discovery errors

" + _table( + ("Experiment", "Error"), sorted(errors.items())) + if runs is not None: + body += _section("Full batch action log", _raw(runs)) + return _wrap(body) + + +def _answer_html(value): + """Render saved Markdown as inert text and formatting, not active HTML. + + Parameters + ---------- + value: object + Recorded value to inspect or format. + + Returns + ------- + str + Rendered or formatted text. + + """ + if not isinstance(value, str): + return "

Unavailable.

" + try: + import mistune + except ImportError: + return f'
{_e(value)}
' + + class SafeRenderer(mistune.HTMLRenderer): + """Suppress navigable links and externally loaded images.""" + + def link(self, text, url, title=None): + """Keep the formatted label and display the escaped URL. + + Parameters + ---------- + text: str + Already rendered link label. + url: str + Recorded URL; displayed as text, never fetched. + title: str or None + Optional link title. + + Returns + ------- + str + Rendered or formatted text. + + """ + return f"{text} {escape(url)}" + + def image(self, text, url, title=None): + """Represent images as inert descriptions without loading. + + Parameters + ---------- + text: str + Image description to display as text. + url: str + Recorded URL; displayed as text, never fetched. + title: str or None + Optional image title. + + Returns + ------- + str + Rendered or formatted text. + + """ + return f"[Image: {escape(text)} — {escape(url)}]" + + markdown = mistune.create_markdown(renderer=SafeRenderer(escape=True), + plugins=["table", "strikethrough"]) + return markdown(value) + + +def _diff(left, right): + """Render a literal line diff of saved answers, not a semantic verdict. + + Parameters + ---------- + left: str + Original-side text or rendered content. + right: str + Replay-side text or rendered content. + + Returns + ------- + str + Rendered or formatted text. + + """ + if not isinstance(left, str) or not isinstance(right, str): + return "

Both texts are required.

" + if left == right: + return "

Saved answer strings are identical.

" + lines = [] + for line in unified_diff(left.splitlines(keepends=True), + right.splitlines(keepends=True), + fromfile="Original", tofile="Replay"): + tone = ("add" if line.startswith("+") else "remove" if + line.startswith("-") else None) + text = _e(line.rstrip("\n")) + "\n" + lines.append(f'{text}' + if tone else text) + if not lines: + return "

Only line-ending or whitespace representation differs.

" + return "
" + "".join(lines) + "
" + + +def _paired_fields(q): + """Show user-facing routing, completion, and saved-turn token fields. + + Parameters + ---------- + q: dict + Question-pair observations from an aligned operation. + + Returns + ------- + str + Rendered or formatted text. + + """ + rows = [] + for field, label in (("intent", "Intent"), + ("retrieval_mode", "Retrieval mode"), + ("tool", "Tool summary"), + ("completion", "Completion"), + ("finish_reason", "Finish reason")): + rows.append((label, *(_at(q, field, side) for side in SIDES))) + for key in ("input_tokens", "output_tokens"): + rows.append((key, *(_at(q, "usage", side, key) for side in SIDES))) + rows.append(("Saved turn UUID", q.get("original_turn_uuid"), + q.get("replayed_turn_uuid"))) + rows.append(("Trace", q.get("original_trace"), q.get("replayed_trace"))) + return _table(("Observation", "Original", "Replay"), rows) + + +def _passages(items): + """Render ranked passage identities without pretending hashes are text. + + Parameters + ---------- + items: list + Recorded items in display order. + + Returns + ------- + str + Rendered or formatted text. + + """ + if items is None: + return "

Unavailable.

" + if not items: + return "

No recorded passages.

" + return _table(("Rank", "Source", "Start", "End", "Section / symbol / cell", + "Text SHA-256"), [ + (i, x.get("path"), x.get("start_line"), x.get("end_line"), + " / ".join(_format(x[k]) for k in ("section", "symbol", "cell") + if x.get(k) is not None), x.get("text_sha256")) + for i, x in enumerate(items, 1)]) + + +def _evidence(q): + """Display evidence, citation overlap, and unresolved citation numbers. + + Parameters + ---------- + q: dict + Question-pair observations from an aligned operation. + + Returns + ------- + str + Rendered or formatted text. + + """ + evidence = q.get("evidence") + if not isinstance(evidence, dict): + return "

Evidence comparison unavailable.

" + citations = _dict(evidence.get("citations")) + body = "

Retrieved evidence identities

" + _pair( + *[_passages(evidence.get(side)) for side in SIDES]) + body += "

Cited passage identities

" + _pair( + *[_passages(citations.get(side)) for side in SIDES]) + body += _table(("Observation", "Original", "Replay"), [ + ("Unresolved citation numbers", citations.get("original_unresolved"), + citations.get("replayed_unresolved"))]) + body += ('

Citation resolution is syntactic, not ' + 'verification of scientific support. Empty evidence unions ' + 'have unavailable overlap.

') + body += _section("Evidence and citation overlap details", _raw({ + "evidence": evidence.get("overlap"), + "citations": citations.get("overlap")})) + return body + + +def _rankings(op): + """Display ranked identities, overlap and per-channel coverage. + + Parameters + ---------- + op: dict + One aligned operation from the comparison. + + Returns + ------- + str + Rendered or formatted text. + + """ + body = "" + for row in _list(op.get("rankings")): + title = (f'{row.get("event_type")} · ' + f'occurrence {row.get("occurrence")}') + panels = [] + for side in SIDES: + items = row.get(side) + if items is None: + panels.append("

Unavailable.

") + elif not items: + panels.append("

No ranked entries.

") + else: + panels.append(_table(("Rank", "Identity"), + enumerate(items, 1))) + body += _section(title, _pair(*panels) + _section( + "Overlap and issues", _raw({"overlap": row.get("overlap"), + "issues": row.get("issues")}))) + return body or "

No aligned ranking records.

" + + +def _stages(op): + """Show all stage counts, statuses and recorded durations. + + Parameters + ---------- + op: dict + One aligned operation from the comparison. + + Returns + ------- + str + Rendered or formatted text. + + """ + return _table(("Component", "Event", "Original count", "Original time", + "Replay count", "Replay time", "Original statuses", + "Replay statuses"), [ + (x.get("component"), x.get("event_type"), + _at(x, "original", "count"), + _seconds(_at(x, "original", "total_duration_ms")), + _at(x, "replayed", "count"), + _seconds(_at(x, "replayed", "total_duration_ms")), + _at(x, "original", "statuses"), _at(x, "replayed", "statuses")) + for x in _list(op.get("stages"))]) + + +def _trace_index(root, relative, cache): + """Index verified events from the requested and shared project traces. + + Parameters + ---------- + root: pathlib.Path + Explicit local repository or workspace directory. + relative: str + Workspace-relative recorded trace or artifact path. + cache: dict + Per-render local recording and trace index cache. + + Returns + ------- + dict + Event nodes indexed by sequence and all local decoding issues. + A render reads each workspace once, across conversation lookups. + + """ + relative = relative if isinstance(relative, str) else None + key = ("index", str(root), relative) + if key in cache: + return cache[key] + recording_key = ("recording", str(root)) + if recording_key not in cache: + cache[recording_key] = _local_trace_data(root) + local = cache[recording_key] + index = {} + paths = {relative, "logs/traces/project.json"} + sequences = {event.sequence for event in local["events"] + if event.path in paths} + # Keep competing allocations even in another conversation: a project + # sequence must identify one event, not merely one event in this pane. + for event in local["events"]: + if event.sequence not in sequences: + continue + node = {"event": event.metadata, "details": event.details, + "exact_content": event.exact_content} + if (event.path, event.sequence) in local["invalid"]: + node["invalid"] = True + index.setdefault(event.sequence, []).append(node) + result = {"events": index, "errors": local["errors"]} + cache[key] = result + return result + + +def _exact_model_text(row, field, index): + """Recover only a unique model artifact matching the report digest. + + Parameters + ---------- + row: dict + Current record or batch action row. + field: str + Recorded field to inspect. + index: dict + Trace nodes keyed by project event sequence and local read issues. + + Returns + ------- + tuple + Verified text or None, and an explanatory observation. + + """ + key = "input" if field == "prompt" else "output" + artifact = "02_rendered_prompt" if key == "input" else ( + "01_generated_answer") + sequence = _at(row, key + "_sequence") + digest = _at(row, field + "_sha256") + if type(sequence) is not int or not isinstance(digest, str): + return None, "No exact artifact recorded in the report." + events = index["events"].get(sequence, []) + if len(events) != 1: + return None, "Local trace event missing or ambiguous." + node = events[0] + if node.get("invalid"): + return None, "Local trace event failed decoding or verification." + if _at(node, "event", "event_type") != "llm.call." + key: + return None, "Local event type does not match the report." + value = _at(node, "exact_content", artifact, "value") + if not isinstance(value, str): + return None, "Inline exact text unavailable." + if sha256(value.encode("utf-8")).hexdigest() != digest: + return None, "Local trace content differs from the report hash." + return value, "Verified against report SHA-256." + + +def _model_calls(op, roots, cache, include_text): + """Display aligned call metadata and optional verified local texts. + + Parameters + ---------- + op: dict + One aligned operation from the comparison. + roots: dict + Explicit workspace paths keyed by comparison side. + cache: dict + Per-render local trace index cache. + include_text: bool + Include verified exact local model texts. + + Returns + ------- + str + Rendered or formatted text. + + """ + q = _dict(op.get("question")) + body = "" + for row in _list(op.get("model_calls")): + title = f'{row.get("stage")} · occurrence {row.get("occurrence")}' + pairs = [] + for field in ("model_id", "resolved_revision", "backend", "device", + "thinking", "generation", "chat_template", + "input_sequence", + "output_sequence", "input_tokens", "output_tokens", + "finish_reason", "reply_duration_ms", + "generation_duration_ms", "output_available"): + pairs.append((field, *(_at(row, side, field) for side in SIDES))) + panel = _table(("Call field", "Original", "Replay"), pairs) + panel += _section("Prompt and response similarity / hashes", _raw({ + "similarities": row.get("text"), + "effective_inference": row.get("inference"), + **{side: {key: _at(row, side, key) for key in + ("prompt_sha256", "answer_sha256", "model_source")} + for side in SIDES}})) + if include_text: + for field in ("prompt", "answer"): + panes = [] + for side in SIDES: + index = _trace_index(roots.get(side), + q.get(side + "_trace"), cache) + value, note = _exact_model_text(row.get(side), field, + index) + pane = f'

{_e(note)}

' + if index["errors"]: + pane += _section("Local trace decoding issues", + _raw(index["errors"])) + pane += (f'
{_e(value)}
' + if value is not None else "") + panes.append(pane) + panel += _section("Exact " + field, _pair(*panes)) + body += _section(title, panel) + return body or "

No aligned model-call records.

" + + +def _question_panel(op, ordinal, roots, cache, include_text, expanded): + """Build one expandable case with answers and diagnostic layers. + + Parameters + ---------- + op: dict + One aligned operation from the comparison. + ordinal: int + One-based aligned question index. + roots: dict + Explicit workspace paths keyed by comparison side. + cache: dict + Per-render local trace index cache. + include_text: bool + Include verified exact local model texts. + expanded: bool + Whether the collapsible panel starts open. + + Returns + ------- + str + Rendered or formatted text. + + """ + q = op["question"] + a = _dict(q.get("answer")) + metrics = _question_metrics(op) + title = (f'Q{ordinal} · {q.get("question")} · ' + f'F1 {_metric_value(metrics[0])} · ' + + ("exact" if a.get("exact_equal") is True else + "different" if a.get("exact_equal") is False else + "equality unavailable")) + body = '
' + "".join( + _card(label, _metric_value(value)) for (_, label), value in + zip(METRICS, metrics, strict=True)) + "
" + body += _table(("Sequence", "Original", "Replay"), [ + ("Command start", op.get("original_sequence"), + op.get("replayed_sequence")), + ("Duration", *(_seconds(_at(op, "duration", side, "ms")) + for side in SIDES)), + ("Answer characters", a.get("original_characters"), + a.get("replayed_characters")), + ("Exact saved answer equality", a.get("exact_equal"), ""), + ("Normalized visible equality", a.get("normalized_equal"), "")]) + body += "

Complete saved answers

" + _pair( + *[_answer_html(a.get(side)) for side in SIDES]) + body += _section( + "Exact saved text (including any recorded reasoning)", + _pair(*[f'
{_e(a.get(side))}
' for side in SIDES])) + body += _section("Literal line-by-line difference", _diff( + a.get("original"), a.get("replayed"))) + body += _section("Routing, tool, token use and saved turn identity", + _paired_fields(q), expanded=True) + if "tool_comparison" in q: + body += _section("Functional tool result and completion", _raw( + q["tool_comparison"]), expanded=True) + if "context" in op: + body += _section("Mapped history and memory selections", _raw( + op["context"])) + body += _section("Evidence and citations", _evidence(q)) + body += _section("Ranked retrieval comparisons", _rankings(op)) + body += _section("Execution stages (nested; not additive)", _stages(op)) + body += _section("Individual model calls", _model_calls( + op, roots, cache, include_text)) + for key, label in (("observations", "History, routing and retrieval"), + ("settings_provenance", "Settings provenance")): + body += _section(label, _pair(*[_raw(_at(op, key, s)) for s in SIDES])) + body += _section("Recorded interactions", _pair(*[_raw( + _at(q, "interactions", s)) for s in SIDES])) + body += _section("Settings differences and diagnostic issues", _raw({ + "settings_differences": op.get("settings_differences"), + "operation_issues": op.get("issues"), + "question_issues": q.get("issues")})) + return _section(title, body, expanded=expanded) + + +def question_explorer(data: dict, *, question: int | None = None, + differences_only: bool = False, + original: str | Path | None = None, + replayed: str | Path | None = None, + include_model_text: bool = False) -> str: + """Explore matched saved answers and expandable execution diagnostics. + + Parameters + ---------- + data : dict + Native version-1 comparison report. + question : int or None, optional + One-based aligned question index; None shows all pairs. + differences_only : bool, optional + Include pairs with differing answers, routing, retrieval, tools, + recorded settings, or reported issues. Not a quality filter. + original: str, pathlib.Path or None, optional + Explicit local original path, never a path taken from the report. + replayed: str, pathlib.Path or None, optional + Explicit local replay path, never a path taken from the report. + include_model_text : bool, optional + Inspect inline local prompt/response artifacts only when their + sequences, event types and SHA-256 digests match the report. + + Returns + ------- + str + Standalone HTML with collapsible cases; no widgets or model calls. + + """ + questions = _questions(data) + if question is not None and (type(question) is not int or + not 1 <= question <= len(questions)): + raise ValueError( + "Question must be a one-based matched question index.") + roots = {"original": original, "replayed": replayed} + cache = {} + body = ('

Answer explorer

Expand any ' + 'question to compare complete saved answers and diagnostics. ' + 'Different answers are not automatically regressions. ' + 'These are aligned pairs, not all historical turns.

') + shown = 0 + for i, op in enumerate(questions, 1): + if question is not None and question != i: + continue + q = op["question"] + changed = (_at(q, "answer", "exact_equal") is not True or + any(_at(q, key, "original") != _at(q, key, "replayed") + for key in ("intent", "retrieval_mode")) or + (_at(q, "tool_comparison", "functional_equal") is False + if "tool_comparison" in q else + _at(q, "tool", "original") != _at(q, "tool", "replayed")) + or any(outcome.get("status") == "incomplete" for outcome + in _dict(_at(q, "tool_comparison", "outcomes") + ).values()) or + bool(op.get("settings_differences") or op.get("issues") + or q.get("issues")) or + any(row.get("identity_equal") is False or row.get("issues") + for row in _list(op.get("context"))) or + any(_at(call, "inference", key) is False for call in + _list(op.get("model_calls")) for key in ( + "model_equal", "settings_equal", "output_equal", + "finish_reason_equal")) or + any((call.get("original") is None) != + (call.get("replayed") is None) for call in + _list(op.get("model_calls"))) or + any(_at(q, "evidence", "citations", side + "_unresolved") + for side in SIDES) or + any(_at(q, field, "original") != _at(q, field, "replayed") + for field in ("completion", "finish_reason", + "interactions")) or + any(_at(q, "completion", side, "status") in ( + "partial", "incomplete", "failed", "error") or + _at(q, "finish_reason", side) == "length" + for side in SIDES) or + any(row.get("issues") or ( + _number(_at(row, "overlap", "jaccard")) is not None + and _at(row, "overlap", "jaccard") < 1) + for row in _list(op.get("rankings"))) or + any(row.get("event_type") != "runtime.output" and + _at(row, "original", "count") != + _at(row, "replayed", "count") + for row in _list(op.get("stages"))) or + any(_number(value) is not None and value < 1 + for value in _question_metrics(op)[2:])) + if differences_only and not changed: + continue + body += _question_panel(op, i, roots, cache, include_model_text, + expanded=question is not None) + shown += 1 + body += f"

Showing {shown} of {len(questions)} matched questions.

" + if question is None: + for side in SIDES: + paired = {op["question"].get(side + "_turn_uuid") + for op in questions} + unmatched = [q for q in _list(_at(data, side, "saved_questions")) + if q.get("turn_uuid") not in paired] + if unmatched: + panel = "" + for q in unmatched: + trust = ("validated" if q.get("validated") else + "unverified recording") + title = (f'{q.get("sequence")} · {q.get("question")}' + f" · {trust}") + panel += _section( + title, + _answer_html(q.get("answer")) + _raw({ + "intent": q.get("intent"), + "tool_outcome": q.get("tool_outcome"), + "completion": q.get("completion"), + "finish_reason": q.get("finish_reason"), + "validated": q.get("validated")}), expanded=True) + body += _section(f"{side.title()} — independently saved " + "questions (not paired)", panel, + expanded=True) + if not questions: + body += _diagnostics(data) + return _wrap(body) + + +def operation_explorer(data: dict) -> str: + """Render all aligned operation records, including non-question commands. + + Parameters + ---------- + data : dict + Native version-1 comparison snapshot. + + Returns + ------- + str + Collapsible operations with durations, settings, manifests, stage + diagnostics and observations. Question answers are reviewed in the + separate answer explorer. + + """ + body = "

Operation explorer

" + for op in data["operations"]: + label = (f'{op.get("kind")} · ' + f'original #{op.get("original_sequence")} ' + f'→ replay #{op.get("replayed_sequence")}') + fields = {key: value for key, value in op.items() + if key not in ("question", "stages")} + body += _section(label, _stages(op) + _section( + "Complete operation metadata", _raw(fields))) + if not data["operations"]: + body += "

No aligned operations.

" + return _wrap(body) + + +def _md(value): + """Escape data used in Markdown cells, including raw HTML and pipes. + + Parameters + ---------- + value: object + Recorded value to inspect or format. + + Returns + ------- + str + Rendered or formatted text. + + """ + value = _format(value).replace("\n", " ").replace("\r", " ") + value = escape(value, quote=False).replace("\\", "\\\\") + for char in "|`*_[]!~": + value = value.replace(char, "\\" + char) + return value + + +def _md_table(headers, rows): + """Build a Markdown table with escaped report values. + + Parameters + ---------- + headers: sequence[str] + Column headings in display order. + rows: iterable + Rows of values, one sequence per table row. + + Returns + ------- + list[str] + Markdown table lines. + + """ + line = lambda row: "| " + " | ".join(_md(x) for x in row) + " |" + return [line(headers), line(["---"] * len(headers)), + *(line(row) for row in rows), ""] + + +def _md_bar(value, maximum=1, width=12): + """Produce a portable text bar with a labeled scale or missing value. + + Parameters + ---------- + value: object + Recorded value to inspect or format. + maximum: float + Positive reference scale for the bar. + width: int + Number of characters in the portable bar. + + Returns + ------- + str + Rendered or formatted text. + + """ + value = _number(value) + if value is None or maximum <= 0 or value < 0: + return "n/a" if value is None else _format(value) + filled = round(min(value / maximum, 1) * width) + if value > 0: + filled = max(1, filled) + return "█" * filled + "░" * (width - filled) + + +def analysis_markdown(data: dict, name: str = "Workspace") -> str: + """Create a portable visual summary of a saved comparison snapshot. + + Parameters + ---------- + data : dict + Native version-1 comparison snapshot. + name : str, optional + Experiment stem used in the heading. + + Returns + ------- + str + Markdown with portable text bars, coverage, per-question routing, + paired durations and diagnostic summaries. The native reports + remain the authoritative detailed exports. + + """ + summary, align = data["summary"], data["alignment"] + questions = _questions(data) + lines = [f"# {_md(name)} — visual analysis", "", + "Saved comparison snapshot; not a correctness verdict.", "", + f'**Alignment:** {_md(align.get("status"))} ', + f'**Matched operations:** {_md(align.get("matched_operations"))}' + f' · **Questions:** {_md(summary.get("questions"))} ', + f'**Exact answers:** {_md(summary.get("exact_answers"))}', ""] + if align.get("reason") is not None: + lines.extend([_md(align["reason"]), ""]) + if data.get("inspection", data.get("batch_inspection")): + note = data.get("inspection", data.get("batch_inspection")) + lines += [_md(note["message"]), ""] + receipt = data.get("reference_publication", {}) + if receipt: + lines += ["**Reference publication:** " + + _md(receipt.get("status")), ""] + if receipt.get("message"): + lines += [_md(receipt["message"]), ""] + lines += [f"- {_md(hint)}" for hint in receipt.get("coverage", [])] + lines += [""] + lines += ["## Validity and coverage", ""] + _md_table( + ("Workspace", "Valid", "Events", "Commands", "Issues"), [ + (side.title(), data[side].get("valid"), + data[side].get("event_count"), + len(_list(data[side].get("operations"))), + len(_list(data[side].get("validation_issues")))) + for side in SIDES]) + lines += ["## Agreement", ""] + _md_table( + ("Metric", "Mean", "Coverage", "0–1 scale"), [ + (label, _metric_value(_at(summary, key, "mean")), + f'{_format(_at(summary, key, "available"))}/' + f'{_format(_at(summary, key, "total"))}', + _md_bar(_at(summary, key, "mean"))) for key, label in METRICS]) + lines += ["Missing values are not zeros. Negative cosine values are " + "shown numerically without a nonnegative bar.", "", + "## Questions", ""] + if not questions: + lines += ["No aligned committed question pairs.", ""] + else: + lines += _md_table(("Question", "Exact", "Token F1", "Overlap bar", + "Cosine", "Evidence", "Citation", + "Intent O / R"), [ + (f'Q{i} · {op["question"].get("question")}', + _at(op, "question", "answer", "exact_equal"), + _metric_value(_question_metrics(op)[0]), + _md_bar(_question_metrics(op)[0]), + *(_metric_value(x) for x in _question_metrics(op)[1:]), + " / ".join(_format(_at(op, "question", "intent", side)) + for side in SIDES)) + for i, op in enumerate(questions, 1)]) + lines += ["## Recorded behavior agreement", ""] + _md_table( + ("Observation", "Equal", "Available", "Question pairs"), + _agreement(data)) + lines += ["Equal null tool summaries mean equal recorded absences, " + "not proof that no tool ran.", ""] + model = _at(data, "summary", "model_reproducibility") + if isinstance(model, dict): + lines += ["## Effective model-call reproducibility", ""] + _md_table( + ("Observation", "Equal", "Available", "Paired calls"), [ + (key, value.get("equal"), value.get("available"), + value.get("total")) for key, value in + _dict(model.get("agreement")).items()]) + lines += _md_table(("Conditional category", "Equal outputs", + "Available outputs", "Identical inputs"), [ + (key, value.get("equal_outputs"), value.get("available_outputs"), + value.get("identical_inputs")) for key, value in + _dict(model.get("conditional")).items()]) + lines += ["Conditional equality uses exact recorded inputs, not " + "metadata-normalized prompts.", ""] + lines += ["## Recorded tool outcomes", ""] + _md_table( + ("Question", "Original", "Replay", "Transition"), [ + (f"Q{i}", *(_at(op, "question", "tool_comparison", "outcomes", + side, "status") for side in SIDES), + _at(op, "question", "tool_comparison", "transition")) + for i, op in enumerate(questions, 1) if _at( + op, "question", "tool_comparison", "transition") not in ( + None, "not_applicable")]) + lines += ["Unknown tool completion is not proof of success.", ""] + performance = data.get("performance") + if isinstance(performance, dict): + names = dict.fromkeys(name for side in SIDES for name in + _dict(_at(performance, side, "spans"))) + lines += ["## Recorded performance categories", ""] + _md_table( + ("Category", "Original", "Coverage", "Replay", "Coverage"), [ + (name, *[value for side in SIDES for value in ( + _seconds(_at(performance, side, "spans", name, + "duration_ms")), + _coverage_text(_at(performance, side, "spans", name, + "available"), _at(performance, side, + "spans", name, + "total")))]) + for name in names]) + lines += _md_table(("Rate", "Original tokens/s", "Coverage", + "Replay tokens/s", "Coverage"), [ + (name, *[value for side in SIDES for value in ( + _at(performance, side, "throughput", name, + "tokens_per_second"), + _coverage_text(_at(performance, side, "throughput", name, + "available"), _at(performance, side, + "throughput", name, + "total")))]) + for name in ("generation", "reply")]) + lines += ["Categories overlap and are not additive. Rates are not " + "necessarily decoding-only throughput.", ""] + lines += ["## Performance", "", + "All operation bars share the same duration scale (rounded; " + "positive values get at least one block). Nested " + "stage times must not be added to these totals.", ""] + maximum = max([_number(_at(op, "duration", side, "ms")) or 0 + for op in data["operations"] for side in SIDES] + [1]) + lines += _md_table(("Operation", "Original", "Replay", "Original bar", + "Replay bar"), [ + (f'{op.get("original_sequence")} · {op.get("kind")}', + *(_seconds(_at(op, "duration", side, "ms")) for side in SIDES), + *(_md_bar(_at(op, "duration", side, "ms"), maximum) + for side in SIDES)) for op in data["operations"]]) + duration = _dict(summary.get("paired_command_duration_ms")) + lines += [f'**Paired measured total:** ' + f'{_seconds(duration.get("original"))} / ' + f'{_seconds(duration.get("replayed"))} · ' + f'{_format(duration.get("available"))}/' + f'{_format(duration.get("total"))} operations.', ""] + lines += _md_table(("Token boundary", "Original", "Replay"), [ + (f"{key}.{field}", *(_at(data, side, key, field, "recorded_total") + for side in SIDES)) for key in + ("usage", "traced_chat_usage") for field in + ("input_tokens", "output_tokens")]) + lines += ["Saved-turn and traced-call tokens overlap; do not sum them. " + "See the native report for token coverage.", "", + "## Configuration and final state", ""] + diffs = [(op.get("original_sequence"), difference) + for op in data["operations"] for difference in + _list(op.get("settings_differences"))] + lines += [f"Recorded settings differences: **{len(diffs)}** " + "across matched operations.", ""] + if diffs: + lines += _md_table(("Sequence", "Difference"), diffs) + lines += _md_table(("Directory", "Added", "Removed", "Changed", + "Unchanged"), [ + (directory, *(len(_at(entry, "changes", key)) if isinstance( + _at(entry, "changes", key), list) else None for key in + ("added", "removed", "changed", "unchanged"))) + for directory, entry in data["files"].items()]) + lines += _md_table(("Final state", "Equal", "Available", "Mapped"), + _mapped_state(data)) + events = event_inventory(data) + lines += ["## Event inventory", ""] + lines += _md_table(("Side", "Reported events", "Counted events"), [ + (side, events["expected"][side], + sum(events["counts"][side].values())) for side in SIDES]) + if not events["complete"]: + lines += ["Complete inventory unavailable; partial counts are not " + "interpreted as differences. Regenerate the comparison " + "report.", ""] + elif events["differences"]: + lines += _md_table(("Event type", "Original", "Replay", "Delta"), [ + (r["event_type"], r["original"], r["replayed"], r["delta"]) + for r in events["differences"]]) + else: + lines += ["Every recorded event-type count agrees.", ""] + lines += ["## Diagnostics", ""] + for side in SIDES: + lines += [f"### {side.title()}", ""] + for key in ("validation_issues", "validation_warnings"): + for issue in _list(data[side].get(key)): + lines.append(f'- {_md(key)} · {_md(issue.get("code"))} · ' + f'{_md(issue.get("sequence"))}: ' + f'{_md(issue.get("message"))}') + lines.append("") + for issue in data["report_issues"]: + lines.append(f'- Report: {_md(issue)}') + lines += ["", "## Detailed inspection", "", + f"Open `{_md(name)}_answers.ipynb` in `workspaces/` " + "to compare full answers, " + "evidence identities, citations, model calls and stages.", "", + "The native `_comparison.json` and `_comparison.md` files " + "contain the complete underlying comparison measurements. " + "All reports may contain private information.", ""] + return "\n".join(lines) + + +def save_analysis(report_path: str | Path, *, overwrite: bool = False + ) -> Path: + """Write a visual Markdown companion to an existing native JSON report. + + Parameters + ---------- + report_path : str or pathlib.Path + Saved native ``*_comparison.json`` report, not an in-memory result. + overwrite : bool, optional + Replace an existing regular companion only when explicitly enabled. + The native Markdown and JSON files are never modified. + + Returns + ------- + pathlib.Path + Path of the ``*_analysis.md`` companion. + + """ + report_path = Path(report_path) + if not report_path.name.endswith(SUFFIX): + raise ValueError("Expected a *_comparison.json report.") + if report_path.parent.is_symlink(): + raise ValueError("Linked report directory rejected.") + data = load_report(report_path) + stem = report_path.name.removesuffix(SUFFIX) + path = report_path.with_name(stem + "_analysis.md") + if path.is_symlink() or (path.exists() and not path.is_file()): + raise ValueError(f"Nonregular analysis destination: {path}") + text = analysis_markdown(data, stem) + if not overwrite: + with path.open("x", encoding="utf-8") as stream: + stream.write(text) + else: + temp_path = None + try: + with NamedTemporaryFile(mode="w", encoding="utf-8", + dir=path.parent, delete=False) as stream: + temp_path = Path(stream.name) + stream.write(text) + temp_path.replace(path) + finally: + if temp_path is not None: + temp_path.unlink(missing_ok=True) + return path diff --git a/kilin/system_testing/batch.py b/kilin/system_testing/batch.py new file mode 100644 index 00000000..828f08ee --- /dev/null +++ b/kilin/system_testing/batch.py @@ -0,0 +1,1198 @@ +"""Orchestrate reference experiments and pre-render their analysis notebooks. + +Key Features +------------ +- One validation/replay/comparison path per discovered reference. +- Independent notebook generation and execution from current templates. +- Explicit issue classification and complete per-experiment action logs. +- Explicit retain, archive, or error policy for existing replays. +- Reference publication and inspection-only extension diagnostics. + +Module Structure +---------------- +- Snapshot and notebook generation helpers. +- Batch orchestration and issue collection. + +Examples +-------- +>>> from pathlib import Path +>>> from kilin.system_testing.batch import discover_originals +>>> originals = discover_originals(Path('workspaces')) # doctest: +SKIP + +Only packaged KíLín templates are executed, in separate local kernels +using the interpreter running the batch. Saved report text is data only. + +""" + +from __future__ import annotations + +from collections import Counter +from hashlib import sha256 +from importlib.resources import files +import json +import os +from pathlib import Path +import sys +from tempfile import TemporaryDirectory, NamedTemporaryFile +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from nbformat import NotebookNode + +from .analysis import ( + load_report, save_analysis, event_inventory, _release_measurements, + _release_rows, _release_totals, _release_agreement_rows, +) + +__all__ = [ + "discover_originals", "run_batch", "collect_issues", "load_snapshot", + "save_batch_summary", "group_issues", +] + +NOTEBOOKS = ( + ("comparison", "experiment_template.ipynb", ".ipynb"), + ("answers", "explore_answers.ipynb", "_answers.ipynb"), +) +MARKER = 'REFERENCE = Path("__ORIGINAL_WORKSPACE__")' +SNAPSHOT_ENV = "KILIN_SYSTEM_TESTS_BATCH_REPORT" +SOURCE_ENV = "KILIN_SYSTEM_TESTS_BATCH_SOURCE" + + +def discover_originals(directory: Path) -> list[Path]: + """Discover direct real original workspaces in deterministic order. + + Parameters + ---------- + directory: pathlib.Path + Explicit directory to inspect or write artifacts in. + + Returns + ------- + list[pathlib.Path] + Direct original workspaces, sorted by path. + + """ + directory = Path(directory) + if directory.is_symlink() or not directory.is_dir(): + raise ValueError(f"Expected a real workspace directory: {directory}") + return sorted(p for p in directory.glob("*_original") + if p.is_dir() and not p.is_symlink()) + + +def _write_text(path: Path, text: str, *, overwrite: bool) -> None: + """Publish a complete artifact without following linked destinations. + + Parameters + ---------- + path: pathlib.Path + Local artifact destination. + text: str + Text to publish or render. + overwrite: bool + Explicitly permit replacing an existing regular artifact. + + """ + if path.is_symlink() or (path.exists() and not path.is_file()): + raise ValueError(f"Nonregular artifact destination: {path}") + temp = None + try: + with NamedTemporaryFile(mode="w", encoding="utf-8", delete=False, + dir=path.parent) as stream: + temp = Path(stream.name) + stream.write(text) + if overwrite: + temp.replace(path) + else: + # Exclusive publication avoids truncation or partial notebooks. + os.link(temp, path) + finally: + if temp is not None: + temp.unlink(missing_ok=True) + + +def _notebook(template: str, original: Path) -> "NotebookNode": + """Instantiate a canonical template, removing all historical outputs. + + Parameters + ---------- + template: str + Name of a trusted notebook resource packaged with KíLín. + original: pathlib.Path + Reference whose name replaces the template marker. + + Returns + ------- + NotebookNode + Fresh validated notebook with its reference marker replaced. + + """ + import nbformat + + resource = files(__package__).joinpath("_notebooks", template) + if not resource.is_file(): + raise FileNotFoundError(f"Missing packaged notebook: {template}") + nb = nbformat.reads(resource.read_text(encoding="utf-8"), + as_version=4) + nbformat.validate(nb) + matches = 0 + for cell in nb.cells: + if cell.cell_type != "code": + continue + lines = cell.source.splitlines(keepends=True) + for i, line in enumerate(lines): + if line.rstrip("\r\n") == MARKER: + lines[i] = f"REFERENCE = Path({original.name!r})\n" + matches += 1 + cell.source = "".join(lines) + cell.outputs = [] + cell.execution_count = None + if matches != 1: + raise ValueError("Expected exactly one template reference marker.") + nb.metadata["kilin_system_tests"] = { + "generated": True, "reference": original.name, + "template": template, + } + nbformat.validate(nb) + return nb + + +def _canonical_json(data: dict) -> str: + """Use a stable representation for snapshot identity across views. + + Parameters + ---------- + data: dict + Saved comparison snapshot; never modified. + + """ + return json.dumps(data, ensure_ascii=False, sort_keys=True, + separators=(",", ":"), allow_nan=False) + + +def load_snapshot(reference: Path) -> tuple[dict, str, str]: + """Load the batch's exact snapshot or the ordinary saved local report. + + Parameters + ---------- + reference: pathlib.Path + Reference workspace associated with the snapshot. + + Returns + ------- + tuple[dict, str, str] + Comparison data, provenance, and SHA-256 of canonical JSON. + A temporary batch snapshot is never stored as a notebook parameter. + + """ + reference = Path(reference) + if (reference.name == "__ORIGINAL_WORKSPACE__" or + not reference.name.endswith("_original")): + raise ValueError("Open a generated workspace notebook instead.") + override = os.environ.get(SNAPSHOT_ENV) + if override: + path = Path(override) + source = os.environ.get(SOURCE_ENV, "Current batch snapshot") + else: + stem = reference.name.removesuffix("_original") + path = reference.with_name(stem + "_comparison.json") + source = "Saved report snapshot (not independently revalidated)" + data = load_report(path) + digest = sha256(_canonical_json(data).encode("utf-8")).hexdigest() + return data, source, digest + + +def _execute(nb, directory: Path, snapshot: Path, source: str, + timeout: int) -> None: + """Execute a fresh template in the batch interpreter's local kernel. + + Parameters + ---------- + nb: NotebookNode + Fresh notebook instance to execute in place. + directory: pathlib.Path + Explicit directory to inspect or write artifacts in. + snapshot: pathlib.Path + Temporary file containing the exact comparison snapshot. + source: str + Human-readable snapshot provenance. + timeout: int + Per-cell execution timeout in seconds. + + """ + from jupyter_client import AsyncKernelManager + from jupyter_client.kernelspec import KernelSpecManager + from nbclient import NotebookClient + + # Do not silently use a different installed python3 kernelspec. + with TemporaryDirectory(prefix="kilin-kernel-") as temporary: + kernel = Path(temporary) / "kilin-local" + kernel.mkdir() + spec = {"argv": [sys.executable, "-m", "ipykernel_launcher", + "-f", "{connection_file}"], + "display_name": "KíLín batch interpreter", + "language": "python"} + (kernel / "kernel.json").write_text(json.dumps(spec), + encoding="utf-8") + km = AsyncKernelManager( + kernel_name="kilin-local", + kernel_spec_manager=KernelSpecManager(kernel_dirs=[temporary]), + ) + env = os.environ.copy() + env[SNAPSHOT_ENV] = str(snapshot.resolve()) + env[SOURCE_ENV] = source + client = NotebookClient(nb, km=km, timeout=timeout, + allow_errors=False) + client.execute(cwd=str(directory.resolve()), env=env, + cleanup_kc=True) + + +def _prepare_notebooks(original, row, overwrite): + """Create fresh templates or explicitly retain existing artifacts. + + Parameters + ---------- + original: pathlib.Path + Reference for the generated report notebooks. + row: dict + Current record or batch action row. + overwrite: bool + Explicitly permit replacing an existing regular artifact. + + Returns + ------- + dict + Fresh notebook instances ready for execution. + + """ + stem = original.name.removesuffix("_original") + if not stem: + raise ValueError("Original workspace requires a nonempty stem.") + prepared = {} + for kind, template, suffix in NOTEBOOKS: + destination = original.with_name(stem + suffix) + entry = {"path": str(destination), "status": "pending", + "error": None} + row["notebooks"][kind] = entry + try: + import nbformat + + if destination.is_symlink() or (destination.exists() and + not destination.is_file()): + raise ValueError(f"Nonregular notebook: {destination}") + existed = destination.exists() + if existed and not overwrite: + entry["status"] = "retained" + continue + nb = _notebook(template, original) + _write_text(destination, nbformat.writes(nb) + "\n", + overwrite=overwrite) + entry["status"] = "refreshed" if existed else "created" + prepared[kind] = (nb, destination) + except Exception as error: + entry.update(status="error", error=str(error)) + return prepared + + +def _render_notebooks(prepared, row, snapshot, source, timeout): + """Persist executed notebooks, retaining diagnostic outputs on failure. + + Parameters + ---------- + prepared: dict + Prepared notebook instances and their destination paths. + row: dict + Current record or batch action row. + snapshot: pathlib.Path + Temporary file containing the exact comparison snapshot. + source: str + Human-readable snapshot provenance. + timeout: int + Per-cell execution timeout in seconds. + + """ + for kind, (nb, path) in prepared.items(): + entry = row["notebooks"][kind] + try: + print(f"Executing {path.name}...", flush=True) + _execute(nb, path.parent, snapshot, source, timeout) + entry["status"] = "executed" + except Exception as error: + entry.update(status="error", error=str(error)) + # A failing cell's traceback is valuable, but not a success. + try: + import nbformat + + nbformat.validate(nb) + _write_text(path, nbformat.writes(nb) + "\n", overwrite=True) + except Exception as error: + previous = entry.get("error") + entry.update(status="error", error=( + f"{previous}; notebook save: {error}" if previous else + f"Notebook save: {error}")) + + +def _event_differences(data: dict, inventory: dict) -> list[dict]: + """Attribute event-count changes to aligned commands when corroborated. + + Parameters + ---------- + data: dict + Comparison with per-operation recorded stage counts. + inventory: dict + Reconciled independent workspace event inventories. + + Returns + ------- + list[dict] + Per-command changes and residual outside-matched-command changes. + Every side's counts must reconcile; no causal relationships are + inferred, and opposite changes in different commands are retained. + + """ + sides = ("original", "replayed") + counted = {side: Counter() for side in sides} + result = [] + fallback = [{**item, "attribution": "unavailable"} + for item in inventory["differences"]] + for op in data["operations"]: + local = {side: Counter() for side in sides} + if not isinstance(op.get("stages"), list): + return fallback + for stage in op["stages"]: + name = stage.get("event_type") + for side in sides: + count = (stage.get(side) or {}).get("count") + if (not isinstance(name, str) or type(count) is not int + or count < 0): + # No reliable operation-level attribution is possible. + return fallback + local[side][name] += count + for side in sides: + counted[side].update(local[side]) + for name in sorted(local["original"].keys() | + local["replayed"].keys()): + a, b = (local[side][name] for side in sides) + if a != b: + result.append({"event_type": name, "original": a, + "replayed": b, + "sequence": op.get("original_sequence")}) + remainder = {} + for side in sides: + remainder[side] = Counter(inventory["counts"][side]) + remainder[side].subtract(counted[side]) + if any(count < 0 for count in remainder[side].values()): + return fallback + for name in sorted(remainder["original"].keys() | + remainder["replayed"].keys()): + a, b = (remainder[side][name] for side in sides) + if a != b: + result.append({"event_type": name, "original": a, + "replayed": b, "sequence": None}) + return result + + +def _incomplete_answer(completion: object, finish: object) -> bool: + """Identify explicit ordinary-answer incompletion without a tool. + + Parameters + ---------- + completion: object + Saved answer completion metadata. + finish: object + Saved model termination reason. + + Returns + ------- + bool + Whether recorded metadata explicitly indicates incompletion. + + """ + status = completion.get("status") if isinstance(completion, dict) else None + return finish == "length" or status in ( + "incomplete", "partial", "failed", "error", "cancelled", "aborted", + "interrupted") + + +def _tool_finding(tools: dict) -> tuple[str, str] | None: + """Describe a paired tool outcome without treating unknown as success. + + Parameters + ---------- + tools: dict + Functional tool comparison with side-specific outcome observations. + + Returns + ------- + tuple[str, str] | None + Diagnostic code and concise comparison, when attention is warranted. + + """ + outcomes = tools.get("outcomes", {}) + transition = tools.get("transition") + states = [outcomes.get(side, {}).get("status") + for side in ("original", "replayed")] + failed = [side for side, state in zip(("original", "replayed"), states) + if state == "incomplete"] + labels = { + "incomplete_reproduced": "Incomplete outcome reproduced", + "potential_regression": "Potential regression: complete to incomplete", + "possible_improvement": "Changed outcome: incomplete to complete", + "changed": "Recorded tool applicability or outcome changed", + } + if transition in labels or failed: + label = labels.get(transition, "Incomplete recorded result") + reasons = [] + for side, outcome in outcomes.items(): + completion = outcome.get("completion") or {} + reason = completion.get("reason") or outcome.get("finish_reason") + items = outcome.get("incomplete_items") or completion.get( + "incomplete_items") or [] + item_reasons = sorted({item["reason"] for item in items + if isinstance(item, dict) and isinstance( + item.get("reason"), str)}) + if reason or item_reasons: + reasons.append(f"{side}: {reason or 'incomplete items'}" + + (f" ({', '.join(item_reasons)})" + if item_reasons else "")) + code = ("capability.changed" if transition in ( + "possible_improvement", "changed") else "capability.incomplete") + return code, (f"{label}; original: {states[0]}, replay: {states[1]}" + + ("; " + "; ".join(reasons) if reasons else "")) + return None + + +def collect_issues(data: dict | None, row: dict) -> list[dict]: + """Classify execution failures separately from descriptive differences. + + Critical means a failed requested step, invalid/divergent recording, + or an explicit diagnostic error. Review means a measured difference or + a warning requiring inspection. Text similarity never defines failure. + Recording-limit warnings are informational, not per-run defects. + + Parameters + ---------- + data: dict or None + Current comparison snapshot, if available. + row: dict + Current record or batch action row. + + Returns + ------- + list[dict] + Classified individual observations. + + """ + issues = [] + + def add(level, code, message, sequence=None, *, side=None): + """Append an individual diagnostic finding. + + Parameters + ---------- + level: str + Severity of the diagnostic finding. + code: str + Diagnostic category identifier. + message: object + Finding detail, converted to text. + sequence: int or None + Recorded sequence associated with the finding. + side: str or None, optional + Recording side for an independently observed sequence. + + """ + issue = {"severity": level, "code": code, + "message": str(message), "sequence": sequence} + if side is not None: + issue["side"] = side + issues.append(issue) + + for field in ("replay_error", "comparison_error", "save_error", + "analysis_error", "snapshot_error"): + if row.get(field): + add("critical", field, row[field]) + for kind, entry in row.get("notebooks", {}).items(): + if entry.get("error"): + add("critical", f"notebook.{kind}", entry["error"]) + elif entry.get("status") == "retained" and row.get("render_requested"): + add("review", f"notebook.{kind}.retained", + "Existing notebook retained; not pre-executed.") + if data is None: + return issues + alignment = data["alignment"] + inspection = data.get("inspection", data.get("batch_inspection")) + if (isinstance(inspection, dict) and + inspection.get("status") == "inspection_only" and + alignment.get("status") == "diverged"): + add("info", "alignment.inspection", inspection["message"]) + elif alignment.get("status") != "complete": + add("critical", "alignment", alignment.get("reason") or + alignment.get("status")) + receipt = data.get("reference_publication", {}) + if receipt.get("status") == "inspection_only": + add("info", "reference.inspection", + "Published reference retained; inspection sessions appended.") + elif receipt.get("status") in ("changed", "extended", "error"): + add("review", "reference." + receipt["status"], + receipt.get("message")) + execution = data.get("replay_execution", {}) + for observation in (row.get("replay_execution", {}), execution): + status = observation.get("status") + match = observation.get("reference_match") + if status in ("changed", "error") or match in ("changed", "error"): + add("review", "replay.provenance", observation.get("message") or + "Execution receipt or recorded reference prefix differs.") + break + for hint in receipt.get("coverage", []): + if isinstance(hint, str) and hint.startswith("REVIEW:"): + add("info", "generator.coverage", + "Reference at publication: " + hint) + for side in ("original", "replayed"): + workspace = data[side] + if workspace.get("valid") is not True: + add("critical", f"{side}.invalid", "Recording is not valid.") + for field, level in (("validation_issues", "critical"), + ("validation_warnings", "review")): + for issue in workspace.get(field, []): + severity = ("info" if issue.get("code") in ( + "recording.limit", "environment.difference") else level) + add(severity, f'{side}.{issue.get("code")}', + issue.get("message"), issue.get("sequence"), side=side) + for issue in data.get("report_issues", []): + add("critical", "report.issue", issue) + evaluation = data.get("embedding_evaluation", {}) + if evaluation.get("error"): + add("review", "embedding.error", evaluation["error"]) + if alignment.get("status") != "complete": + # The matched prefix is not evidence of a complete execution. + add("info", "alignment.coverage", "Only reliable pairs are shown.") + for op in data["operations"]: + seq = op.get("original_sequence") + for issue in op.get("issues", []): + add("critical", "operation.issue", issue, seq) + for diff in op.get("settings_differences", []): + add("review", "settings.difference", diff, seq) + for pair in op.get("plugin_provenance", []): + if pair["status"] == "changed": + add("review", "plugin.environment.difference", pair, seq) + for stage in op.get("stages", []): + for side in ("original", "replayed"): + statuses = (stage.get(side) or {}).get("statuses", {}) + for status, count in statuses.items(): + if count and status in {"error", "failed", "cancelled", + "aborted", "interrupted"}: + # These are intermediate events in a matched valid + # command. Blocking command failures are handled by + # recording validation/alignment above. + add("review", "stage.failure", + f'{side}: {stage.get("event_type")} ' + f'{status} ({count})', seq) + question = op.get("question") + for context in op.get("context", []): + kind = context.get("event_type") + for issue in context.get("issues", []): + add("review", "context.unavailable", issue, seq) + if context.get("identity_equal") is False: + if kind == "history.selection.result": + flags = context.get("selection_equal", {}) + different = [key for key, equal in flags.items() + if equal is False] + add("review", "context.history", ", ".join(different), + seq) + else: + add("review", "context.identity", kind, seq) + elif context.get("identity_equal") is None and not context.get( + "issues"): + add("review", "context.unavailable", kind, seq) + for ranking in op.get("rankings", []): + for issue in ranking.get("issues", []): + add("review", "ranking.issue", issue, seq) + overlap = ranking.get("overlap") or {} + jaccard = overlap.get("jaccard") + if type(jaccard) in (int, float) and jaccard < 1: + add("review", "ranking.difference", + f'{ranking.get("event_type")}: {jaccard:.4f}', seq) + for call in op.get("model_calls") or []: + old, new = call.get("original"), call.get("replayed") + if (old is None) != (new is None): + add("review", "model_call.difference", + f'{call.get("stage")}: unmatched call', seq) + for side, entry in (("original", old), ("replayed", new)): + if isinstance(entry, dict) and entry.get("issue"): + add("review", "model_call.issue", + f'{side}: {entry["issue"]}', seq) + flags = call.get("inference", {}) + label = f'{call.get("stage")} #{call.get("occurrence")}' + changed = [key for key in ("model_equal", "settings_equal", + "finish_reason_equal") + if flags.get(key) is False] + if (flags.get("rendered_prompt_equal") is True and + flags.get("input_token_count_equal") is False): + changed.append("input_token_count_equal") + if changed: + add("review", "model_call.configuration", + f'{label}: {", ".join(changed)}', seq) + category = flags.get("conditional_category") + if flags.get("output_equal") is False: + if category == "zero_temperature": + add("review", "model_call.conditional_output", + f"{label}: different output with identical recorded " + "zero-temperature inputs.", seq) + elif category == "nonzero_temperature": + add("info", "model_call.stochastic_output", + f"{label}: output differs at nonzero temperature.", + seq) + if not isinstance(question, dict): + continue + for issue in question.get("issues", []): + add("critical", "question.issue", issue, seq) + tools = question.get("tool_comparison") + if isinstance(tools, dict): + if tools.get("functional_equal") is False: + add("review", "question.tool", "Functional results differ.", + seq) + finding = _tool_finding(tools) + if finding is not None: + add("review", *finding, seq) + ordinary = [side for side in ("original", "replayed") + if tools.get("outcomes", {}).get(side, {}).get( + "status") in ("not_applicable", "unknown") and + _incomplete_answer( + (question.get("completion") or {}).get(side), + (question.get("finish_reason") or {}).get(side))] + if ordinary: + add("review", "answer.incomplete", + "Incomplete saved answer: " + ", ".join(ordinary), seq) + fields = ("intent", "retrieval_mode", "completion", + "finish_reason", "interactions") + if not isinstance(tools, dict): + fields += ("tool",) + for field in fields: + pair = question.get(field) or {} + if ("original" in pair and "replayed" in pair and + pair["original"] != pair["replayed"]): + add("review", f"question.{field}", + "Recorded observations differ.", seq) + evidence = question.get("evidence") or {} + citations = evidence.get("citations") or {} + for side in ("original", "replayed"): + if citations.get(f"{side}_unresolved"): + add("review", "citation.unresolved", + f"{side}: {citations[f'{side}_unresolved']}", seq) + for name, item in (("evidence", evidence), ("citation", citations)): + jaccard = (item.get("overlap") or {}).get("jaccard") + if type(jaccard) in (int, float) and jaccard < 1: + add("review", f"{name}.difference", + f"Exact passage overlap: {jaccard:.4f}", seq) + if (question.get("answer") or {}).get("normalized_equal") is False: + add("info", "answer.difference", "Visible answers differ.", seq) + for directory, inventory in data.get("files", {}).items(): + for side in ("original", "replayed"): + for issue in (inventory.get(side) or {}).get("issues", []): + add("critical", "files.inventory", + f"{side}: {directory}: {issue}") + changes = inventory.get("changes") or {} + if any(changes.get(key) for key in ("added", "removed", "changed")): + add("review", "files.difference", f"{directory}: files differ.") + for item in data.get("final_state", {}).get("conversations", []): + for field in ("name_equal", "lineage_equal", "archival_equal", + "turn_prefix_equal"): + if item.get(field) is False: + origins = item.get("name_origin", {}) + generated = (field == "name_equal" and + origins.get("original") == "generated" and + origins.get("replayed") == "generated") + add("info" if generated else "review", "state.difference", + field) + for item in data.get("final_state", {}).get("feedback", []): + if item.get("equal") is False: + add("review", "state.feedback", "Mapped feedback differs.") + events = event_inventory(data) + if events["complete"]: + for item in _event_differences(data, events): + # A runtime message is a diagnostic, not a failed command. + level = ("info" if (item["event_type"] == "runtime.output" or + item["event_type"] in data.get( + "expected_event_differences", []) or + alignment.get("status") != "complete") else "review") + location = ( + "Workspace total (operation attribution unavailable): " + if item.get("attribution") == "unavailable" else + "Outside matched commands: " if item.get("sequence") is None + else "") + add(level, "events.difference", location + + f'{item["event_type"]}: {item["original"]} -> ' + f'{item["replayed"]}', item.get("sequence")) + elif alignment.get("status") == "complete": + add("review", "events.coverage", "Full event counts unavailable.") + # A missing or invalid replay does not suppress independently saved + # tool outcomes. Do not duplicate already aligned questions. + for side in ("original", "replayed"): + paired = {op["question"].get(side + "_turn_uuid") + for op in data["operations"] if op.get("question")} + for question in data[side].get("saved_questions", []): + if question.get("turn_uuid") in paired: + continue + status = question.get("tool_outcome", {}).get("status") + if status == "incomplete": + add("review", "capability.incomplete", f"{side}: " + "independently observed incomplete result.", + question.get("sequence"), side=side) + elif status in ("not_applicable", "unknown", None) and ( + _incomplete_answer( + question.get("completion"), + question.get("finish_reason"))): + add("review", "answer.incomplete", f"{side}: " + "independently observed incomplete answer.", + question.get("sequence"), side=side) + return issues + + +def group_issues(issues, data): + """Group related observations without discarding individual findings. + + Groups are diagnostic categories, not proof of a causal relationship. + + Parameters + ---------- + issues: list[dict] + Individual classified diagnostic findings. + data: dict or None + Comparison providing alignment and workspace context. + + Returns + ------- + list[dict] + Groups retaining their complete underlying findings. + + """ + groups = {} + missing = bool(data and not data["replayed"].get("valid") and + data["replayed"].get("event_count") == 0) + original_invalid = bool(data and not data["original"].get("valid")) + operations = {op["original_sequence"]: op for op in + (data or {}).get("operations", [])} + questions = {op["original_sequence"]: i for i, op in enumerate( + (op for op in operations.values() if op.get("question")), 1)} + for i, issue in enumerate(issues): + code, seq = issue["code"], issue["sequence"] + key = (issue["severity"], code, i) + paired = issue.get("side") is None and seq in operations + if missing and issue["severity"] == "critical" and ( + code in ("alignment", "replay_error") or + code.startswith("replayed.") or + (original_invalid and code.startswith("original.")) or + (code == "files.inventory" and + issue["message"].startswith("replayed:"))): + key = ("critical", "recording.original" if original_invalid else + "recording.replayed", None) + elif code == "plugin.environment.difference": + key = (issue["severity"], "environment.plugins", seq) + elif code.endswith(".environment.difference"): + key = (issue["severity"], "environment.inspection", None) + elif paired and code in ( + "citation.unresolved", "citation.difference"): + key = (issue["severity"], "question.citations", seq) + elif paired and (code.startswith(("context.", + "ranking.", "model_call.")) or code in ( + "question.intent", "question.retrieval_mode", + "question.interactions", "question.tool", + "question.completion", "question.finish_reason", + "events.difference", "settings.difference", + "stage.failure", "evidence.difference")): + key = (issue["severity"], "question.execution" if seq in questions + else "operation.execution", seq) + group = groups.setdefault(key, {"severity": key[0], "code": key[1], + "sequence": seq, "issues": []}) + if paired and seq in questions: + group["question_number"] = questions[seq] + group["issues"].append(issue) + return list(groups.values()) + + +def _compare(original, row, replay, compare, save, overwrite, analysis, + evaluation, existing_replay, root): + """Run the KíLín API once per requested stage; isolate failures. + + Parameters + ---------- + original: pathlib.Path + Closed reference workspace. + row: dict + Current record or batch action row. + replay: bool + Whether to execute or retain a replay. + compare: bool + Whether to calculate a new comparison. + save: bool + Whether to save native comparison reports. + overwrite: bool + Explicitly permit replacing an existing regular artifact. + analysis: bool + Whether to write the visual Markdown companion. + evaluation: dict or None + Optional comparison embedding-evaluation settings. + existing_replay: str + Existing-replay policy: retain, archive, or error. + root: pathlib.Path + Explicit local repository or workspace directory. + + Returns + ------- + dict or None + Current comparison data, if requested and available. + + """ + data = None + destination = original.with_name( + original.name.removesuffix("_original") + "_replay") + if replay or compare: + try: + from kilin.system_testing import Experiment + experiment = Experiment(original) + except Exception as error: + row["comparison_error" if compare else "replay_error"] = str(error) + return None + if replay: + try: + action = experiment.run_replay( + destination=destination, + existing_replay=existing_replay, + archive_directory=root / "_replay_archive", + progress=lambda i, n, op: print(i, n, op.kind), + ) + row.update(replay_status=action.status, + replay_error=action.error, + replay_execution=action.provenance, + completed_operations=action.completed_operations, + failure_sequence=action.sequence) + if action.archived_workspace is not None: + row["archived_replay"] = str(action.archived_workspace) + print("Previous replay archived: " + f"{action.archived_workspace}", flush=True) + if action.status == "retained": + print("Existing replay retained.", flush=True) + except Exception as error: + row.update(replay_status="error", replay_error=str(error)) + if compare: + try: + print("Comparing recordings...", flush=True) + result = experiment.compare(destination=destination, + **evaluation) + data = result.data + row["reference_publication"] = data.get( + "reference_publication", {"status": "unavailable"}) + row["inspection"] = data.get("inspection") + row["snapshot"] = "current" + row["alignment"] = data["alignment"]["status"] + except Exception as error: + row["comparison_error"] = str(error) + return None + if save: + try: + paths = result.save(overwrite=overwrite) + row["reports"] = [str(path) for path in paths] + except Exception as error: + row["save_error"] = str(error) + else: + if analysis: + try: + row["analysis"] = str(save_analysis( + paths[0], overwrite=overwrite)) + except Exception as error: + row["analysis_error"] = str(error) + return data + + +def run_batch(originals: list[Path], root: Path, *, run_replay: bool, + run_comparison: bool, save_reports: bool, + overwrite_reports: bool, save_visual_analysis: bool, + run_notebooks: bool = True, refresh_notebooks: bool = True, + notebook_timeout: int = 180, evaluation: dict | None = None, + existing_replay: str = "retain" + ) -> tuple[dict, list[dict]]: + """Run all requested stages and compile current data and action rows. + + Existing replays are retained by default. ``"archive"`` moves an + existing replay outside discovery before a new execution; ``"error"`` + refuses reuse. The policy applies only when replay is requested. + Both projects must be closed; no concurrent GUI use is supported. + + Each comparison is evaluated once. Its exact JSON data are provided to + both report-only notebooks via a temporary file, even when native + saving is disabled or fails. An old saved report never substitutes for + a failed requested comparison. With comparison disabled, rendering an + explicitly historical snapshot is allowed. The temporary copy is + removed on exit and never becomes a notebook source parameter. + + Parameters + ---------- + originals: list[pathlib.Path] + Reference workspaces in the intended batch order. + root: pathlib.Path + Local experiment repository for replay archives, not templates. + run_replay: bool + Request managed replay of each reference. + run_comparison: bool + Compute a fresh comparison of each pair. + save_reports: bool + Save native JSON and Markdown comparison reports. + overwrite_reports: bool + Permit replacement of existing report files. + save_visual_analysis: bool + Write visual Markdown companions when native reports are + saved. + run_notebooks: bool + Generate and execute report-only notebooks. + refresh_notebooks: bool + Refresh existing generated notebooks from packaged templates. + notebook_timeout: int + Maximum seconds allowed for one notebook cell. + evaluation: dict or None + Optional comparison embedding-evaluation settings. + existing_replay: str + Existing-replay policy: retain, archive, or error. + + Returns + ------- + tuple[dict, list[dict]] + Comparison snapshots keyed by stem and per-experiment action + rows. + + """ + if existing_replay not in ("retain", "archive", "error"): + raise ValueError( + "Choose retain, archive, or error for existing replay.") + reports, results = {}, [] + root = Path(root).resolve() + claimed = {} + all_originals = set(originals) + for parent in {Path(p).parent for p in originals}: + all_originals.update(discover_originals(parent)) + for candidate in all_originals: + stem = candidate.name.removesuffix("_original") + for _, _, suffix in NOTEBOOKS: + path = candidate.parent.resolve() / (stem + suffix) + claimed.setdefault(path, set()).add(candidate.name) + for original in originals: + original = Path(original) + stem = original.name.removesuffix("_original") + print(f"\n=== {stem} ===", flush=True) + row = {"experiment": original.name, "snapshot": None, + "replay_status": "not requested", "notebooks": {}, + "existing_replay": existing_replay, "archived_replay": None, + "render_requested": run_notebooks, "replay_error": None, + "comparison_error": None, "save_error": None, + "analysis_error": None, "snapshot_error": None} + try: + conflicts = [original.with_name(stem + suffix) for _, _, suffix + in NOTEBOOKS if len(claimed.get( + original.parent.resolve() / (stem + suffix), + set())) > 1] + if conflicts: + raise ValueError(f"Notebook name collision: {conflicts}") + prepared = _prepare_notebooks(original, row, refresh_notebooks) + except Exception as error: + row["snapshot_error"] = str(error) + prepared = {} + data = None + try: + data = _compare(original, row, run_replay, run_comparison, + save_reports, overwrite_reports, + save_visual_analysis, evaluation or {}, + existing_replay, root) + except Exception as error: + row["comparison_error"] = str(error) + if not run_comparison and run_notebooks: + try: + path = original.with_name(stem + "_comparison.json") + data = load_report(path) + row["snapshot"] = "saved" + row["alignment"] = data["alignment"]["status"] + except Exception as error: + row["snapshot_error"] = str(error) + if data is not None: + try: + row["inspection"] = data.get( + "inspection", data.get("batch_inspection")) + row["reference_publication"] = data.get( + "reference_publication", {"status": "unavailable"}) + row["comparison_replay_execution"] = data.get( + "replay_execution", {"status": "unavailable"}) + matched = data["alignment"]["matched_operations"] + questions = data["summary"]["questions"] + if any(type(n) is not int or n < 0 + for n in (matched, questions)): + raise ValueError("Invalid comparison coverage counts.") + row["matched_operations"] = matched + row["questions"] = questions + row["release_measurements"] = _release_measurements(data) + for metric in ("token_f1", "embedding_cosine", + "evidence_jaccard", "citation_jaccard"): + row[metric] = data["summary"].get(metric) + # Ensure the snapshot is serializable before exposing it + # to either notebook or the compiled dashboard. + _canonical_json(data) + except Exception as error: + row["snapshot_error"] = str(error) + data = None + row["snapshot"] = None + row.pop("release_measurements", None) + else: + reports[stem] = data + if run_notebooks and prepared and data is not None: + try: + with TemporaryDirectory(prefix="kilin-report-") as temp: + snapshot = Path(temp) / (stem + "_comparison.json") + # All views are compiled from exactly the same data. + snapshot.write_text(_canonical_json(data), + encoding="utf-8") + source = ("Current batch comparison" if + row["snapshot"] == "current" else + "Saved historical comparison snapshot") + row["snapshot_sha256"] = sha256( + snapshot.read_bytes()).hexdigest() + _render_notebooks(prepared, row, snapshot, source, + notebook_timeout) + except Exception as error: + row["snapshot_error"] = str(error) + elif run_notebooks and data is None: + for kind in prepared: + row["notebooks"][kind]["status"] = "no report" + try: + row["issues"] = collect_issues(data, row) + except Exception as error: + # Preserve stage failures even if the report is malformed. + row["issues"] = collect_issues(None, row) + row["issues"].append({"severity": "critical", + "code": "issue_collection.error", + "message": str(error), "sequence": None}) + row["issue_groups"] = group_issues(row["issues"], data) + row["coverage_findings"] = [i for i in row["issues"] + if i["code"] in ("capability.incomplete", + "capability.changed", + "generator.coverage")] + row["tool_findings"] = [i for i in row["coverage_findings"] + if i["code"] != "generator.coverage"] + counts = {level: sum(issue["severity"] == level + for issue in row["issue_groups"]) + for level in ("critical", "review", "info")} + row["issue_counts"] = counts + # An old snapshot must never certify a newly requested replay. + row["execution_status"] = ( + "blocked" if counts["critical"] else + "not analyzed" if data is None else + "saved snapshot" if row["snapshot"] != "current" else + "inspection only" if row.get("inspection") else "complete") + if counts["critical"]: + row["status"] = "CRITICAL" + elif data is None: + row["status"] = "NOT ANALYZED" + elif counts["review"]: + row["status"] = "REVIEW" + else: + row["status"] = "COMPLETE" + results.append(row) + print(f'{row["status"]}: {counts}', flush=True) + return reports, results + + +def save_batch_summary(directory: Path, rows: list[dict], *, + overwrite: bool) -> tuple[Path, Path]: + """Persist the current batch action log and readable issue summary. + + Parameters + ---------- + directory: pathlib.Path + Explicit directory to inspect or write artifacts in. + rows: list[dict] + Complete action and diagnostic rows from the current batch. + overwrite: bool + Explicitly permit replacing an existing regular artifact. + + Returns + ------- + tuple[pathlib.Path, pathlib.Path] + JSON and Markdown summary paths. + + """ + from .analysis import _md, _md_table + + directory = Path(directory) + if directory.is_symlink() or not directory.is_dir(): + raise ValueError("Expected a real summary directory.") + path = directory / "_batch_summary.json" + markdown = directory / "_batch_summary.md" + for target in (path, markdown): + if target.is_symlink() or (target.exists() and not target.is_file()): + raise ValueError(f"Nonregular summary destination: {target}") + if target.exists() and not overwrite: + raise FileExistsError(str(target)) + ordered = sorted(rows, key=lambda row: row["experiment"]) + totals = _release_totals(rows) + lines = ["# KíLín · Release verification", "", + "Current invocation only. Execution, behavioral agreement and " + "capability observations are separate; no quality verdict.", "", + f"Current complete comparisons: **{totals['complete']} / " + f"{len(rows)}**; blocking experiments: **{totals['blocked']}**; " + f"fresh completed replays: **{totals['fresh']}**; " + f"inspection-only comparisons: **{totals['inspection']}**.", ""] + lines += _md_table(("Experiment", "Execution", "Replay", "Operations M/O", + "Questions M/O", "Exact answers", "Token F1", + "Review groups"), _release_rows(ordered)) + lines += ["M/O = matched / recorded original.", "", + "## Measurement coverage", ""] + lines += _md_table(("Boundary", "Matched", "Original", "Replay"), [ + (name, *(value.get(key) if value.get(key + "_snapshots") == + totals["snapshots"] and totals["snapshots"] else None + for key in ("matched", "original", "replayed"))) + for name, value in totals["coverage"].items()]) + lines += ["## Behavioral agreement (current comparisons)", ""] + lines += _md_table(("Observation", "Equal", "Available", "Total", + "Snapshots"), _release_agreement_rows(rows)) + lines += ["Missing values are unavailable, not zero. Snapshots shows " + "the number of reports containing each metric. Saved snapshots " + "are excluded from current aggregate measurements.", "", + "## Recorded tool outcomes", ""] + lines += _md_table(("Transition", "Questions"), sorted( + totals["tool_transitions"].items())) + lines += ["Historical generator hints describe only the reference at " + "publication. Unknown tool completion is not proof of success.", + "", "## Findings by experiment", ""] + for row in ordered: + lines += [f'## {_md(row["experiment"])}', ""] + if row.get("archived_replay"): + lines += [f'Previous replay archived: ' + f'{_md(row["archived_replay"])}', ""] + if row.get("inspection"): + lines += [_md(row["inspection"]["message"]), ""] + receipt = row.get("reference_publication", {}) + if receipt.get("status") == "inspection_only": + lines += ["Published reference preserved; inspection sessions " + "appended.", ""] + if row.get("coverage_findings"): + lines += [f'Capability coverage observations: ' + f'{len(row["coverage_findings"])}.', ""] + if row.get("replay_execution"): + lines += ["Replay execution provenance: " + _md( + row["replay_execution"].get("status")), ""] + groups = [group for group in row.get("issue_groups", []) + if group["severity"] != "info"] + if groups: + for group in groups: + where = (f"Q{group['question_number']} · " if + group.get("question_number") is not None else "") + lines += [f"### {where}{_md(group['code'])} " + f"({_md(group['severity'])})", ""] + lines += _md_table(("Code", "Sequence", "Observation"), [ + (issue["code"], issue["sequence"], issue["message"]) + for issue in group["issues"]]) + else: + lines += ["No critical or review issues recorded.", ""] + lines += ["The JSON includes informational observations, metrics, and " + "complete action logs. Inspect the executed per-workspace " + "notebooks for details.", ""] + _write_text(path, json.dumps(rows, indent=2, ensure_ascii=False, + allow_nan=False) + "\n", overwrite=overwrite) + _write_text(markdown, "\n".join(lines), overwrite=overwrite) + return path, markdown diff --git a/kilin/system_testing/comparison.py b/kilin/system_testing/comparison.py new file mode 100644 index 00000000..a58871a3 --- /dev/null +++ b/kilin/system_testing/comparison.py @@ -0,0 +1,883 @@ +"""Compare independent recorded workspaces without replaying either one. + +Key Features +------------ +- Validate both recordings and reconstruct their operation correspondences. +- Compare configuration, sources, saved answers, tools, and trace stages. +- Return a portable structured report with optional local answer embeddings. + +Module Structure +---------------- +- ``Comparison`` provides the report and presentation methods. +- ``compare`` performs fresh, read-only inspection of two workspace trees. + +Examples +-------- +>>> from kilin.system_testing import Experiment +>>> # comparison = Experiment("010_original").compare() +>>> # comparison.display() +>>> # comparison.save() + +""" + +from __future__ import annotations + +from collections import Counter +from dataclasses import asdict, dataclass +from hashlib import sha256 +import json +import math +from pathlib import Path +from typing import Final, TYPE_CHECKING + +from kilin.conversation_memory.feedback import FeedbackStore + +from ._comparison_alignment import align, interaction_records +from ._comparison_diagnostics import ( + context_comparison, independent_questions, structured_prompt, + tool_comparison, +) +from ._comparison_metrics import ( + EmbeddingEvaluator, evidence_metrics, file_changes, inventory, + inference_comparison, inference_summary, model_calls, operation_duration, + performance_summary, ranking_metrics, stage_metrics, text_metrics, usage, +) +from ._comparison_report import markdown_report, save_reports +from ._first_divergence import first_divergence, operation_divergence +from ._inspection import note_inspection, relocation_event_differences +from ._plugin_provenance import compare_plugins, plugin_observations +from .replay import _configuration_differences +from ._semantic_replay import compare_semantics, semantic_observations +from .reference import inspect_receipt +from .replay_management import ( + execution_provenance, reference_execution_match, +) +from .timeline import TimelineOperation, one +from .traces import Recording, read_recording +from .validation import ValidationReport, validate_recording + +if TYPE_CHECKING: + from .experiment import Experiment + +__all__ = ["Comparison", "compare", "COMPARISON_FORMAT_VERSION"] + +COMPARISON_FORMAT_VERSION: Final[int] = 2 + + +@dataclass(frozen=True, slots=True) +class Comparison: + """One independently computed comparison, not a quality verdict. + + Attributes + ---------- + reference: pathlib.Path + Original workspace, unchanged by comparison. + workspace: pathlib.Path + Replayed workspace, unchanged by comparison. + data: dict + JSON-compatible report snapshot, including validation, alignment, + identity maps, file inventories, and individual observations. + + """ + + reference: Path + workspace: Path + data: dict + + @property + def complete(self) -> bool: + """Return whether the entire validated histories could be aligned.""" + return self.data["alignment"]["status"] == "complete" + + def markdown(self) -> str: + """Return a human-readable report; JSON retains the detailed data.""" + return markdown_report(self.data) + + def display(self) -> None: + """Display the Markdown report in a notebook, or print it in a CLI.""" + content = self.markdown() + try: + from IPython import get_ipython + from IPython.display import Markdown, display + except ImportError: + print(content) + else: + if get_ipython() is None: + print(content) + else: + display(Markdown(content)) + + def save(self, *, overwrite: bool = False) -> tuple[Path, Path]: + """Save JSON and Markdown reports beside the workspace directories. + + Parameters + ---------- + overwrite: bool, optional + Permit replacement of existing regular report files only. + Defaults to False. No workspace contents are replaced. + + Returns + ------- + tuple[pathlib.Path, pathlib.Path] + JSON and Markdown report paths, in that order. + + """ + return save_reports(self.reference, self.data, self.markdown(), + overwrite=overwrite) + + +def _replay_path(root: Path, destination: str | Path | None) -> Path: + """Resolve a separate sibling, allowing a missing replay for diagnosis. + + Parameters + ---------- + root: pathlib.Path + Resolved original workspace. + destination: str | pathlib.Path | None + Explicit replay directory or the default sibling. + + Returns + ------- + pathlib.Path + Replay directory; no directories are created. + + """ + if destination is None: + path = root.with_name(root.name.removesuffix("_original") + "_replay") + else: + if not str(destination).strip(): + raise ValueError("Choose a replay workspace.") + path = Path(destination).expanduser() + if path.is_symlink(): + raise ValueError("Replay comparison does not follow workspace links.") + path = path.resolve() + if path == root or path.parent != root.parent: + raise ValueError("Compare a separate sibling replay workspace.") + if (path.exists() and not path.is_dir()) or ( + root.exists() and not root.is_dir()): + raise ValueError("Workspace paths must be directories.") + if path.exists() and root.exists() and path.samefile(root): + raise ValueError("Cannot compare the original workspace to itself.") + return path + + +def _saved_turns(recording: Recording) -> dict[str, dict]: + """Index validated saved turns once, including inherited and archived. + + Parameters + ---------- + recording: Recording + Validated snapshot with canonical conversation states. + + Returns + ------- + dict[str, dict] + Unique committed turn UUIDs, not branch-local turn numbers. + + """ + return {turn["conversation_turn_uuid"]: turn + for state in recording.states.values() + for turn in state.get("turns", [])} + + +def _catalog(recording: Recording) -> list[dict]: + """Describe the final active/archive catalog without changing names. + + Parameters + ---------- + recording: Recording + Validated recording with authoritative states. + + Returns + ------- + list[dict] + Trace locations, final names, lineage and inherited turn identities. + + """ + return [{"path": path, "id": state["conversation_id"], + "name": state["name"], + "archived": Path(path).parent.name == ".deleted", + "parent_id": state.get("parent_conversation_id"), + "origin_turn_count": state.get("origin_turn_count"), + "origin_checkpoint_id": state.get("origin_checkpoint_id"), + "turn_uuids": [t["conversation_turn_uuid"] + for t in state.get("turns", [])]} + for path, state in sorted(recording.states.items())] + + +def _workspace(recording: Recording, report: ValidationReport) -> dict: + """Collect independent workspace observations and validation diagnostics. + + Parameters + ---------- + recording: Recording + Fresh trace snapshot. + report: ValidationReport + Validation of that same snapshot. + + Returns + ------- + dict + Candidate command inventory, validation, recorded environment/model + provenance, and authoritative conversation data only when validated. + + """ + environments = {} + models = [] + for event in report.events: + if event.event_type == "trace.started": + environment = event.details.get("environment") + if isinstance(environment, dict): + environments[json.dumps(environment, sort_keys=True)] = ( + environment + ) + if event.event_type.startswith("model.") and ( + event.event_type.endswith(".resolved")): + models.append({"sequence": event.sequence, + "type": event.event_type, + "details": event.details}) + assigned = {event.sequence for op in report.operations + for event in op.events} + unassigned = [event for event in report.events + if event.sequence not in assigned] + result = { + "path": str(recording.root), "valid": report.valid, + "event_count": report.event_count, + "validation_issues": [asdict(issue) for issue in report.issues], + "validation_warnings": [asdict(w) for w in report.warnings], + "operations": [{"kind": op.kind, "sequence": op.start_sequence, + "end_sequence": op.end_sequence, "status": op.status} + for op in report.operations], + "operation_counts": dict(sorted(Counter( + op.kind for op in report.operations).items())), + "environments": list(environments.values()), "models": models, + "plugin_provenance": plugin_observations(report.events), + "source_organization": [item for op in report.operations + for item in semantic_observations(op)], + # A title generation occurs outside the outer question span. Retain + # this diagnostic overhead without inventing a user operation. + "outside_commands": { + "event_counts": dict(sorted(Counter(e.event_type for e in + unassigned).items())), + "generated_titles": [{"sequence": e.sequence, + "details": e.details} for e in unassigned + if e.event_type == + "conversation.title.generated"], + }, + "traced_chat_usage": _traced_usage(report), + "event_counts": dict(sorted(Counter(e.event_type for e in + report.events).items())), + "saved_questions": independent_questions(recording, report), + "conversations": None, "turn_count": None, "usage": None, + "feedback": None, "configuration": None, + } + if report.valid: + turns = _saved_turns(recording) + names = {} + for event in report.events: + if event.event_type in ("gui.conversation.renamed", + "conversation.title.generated"): + uid = event.details.get("conversation_id") + if isinstance(uid, str): + names[uid] = ("explicit" if event.event_type == + "gui.conversation.renamed" else "generated") + catalog = _catalog(recording) + for item in catalog: + item["name_origin"] = names.get(item["id"], "unclassified") + feedback = FeedbackStore(recording.root).load() + counts = [usage(turn) for turn in turns.values()] + result.update(conversations=catalog, turn_count=len(turns), + usage={key: { + "recorded_total": (sum(v[key] for v in counts + if v[key] is not None) + if any(v[key] is not None + for v in counts) + else None), + "available_turns": sum(v[key] is not None + for v in counts), + "total_turns": len(turns), + } for key in ("input_tokens", "output_tokens")}, + feedback={uid: {role: asdict(rating) for role, rating + in values.items()} for uid, values + in feedback.entries.items()}, + configuration=[{"sequence": e.sequence, + "details": e.details} + for e in report.events + if e.event_type == + "gui.project.configuration.effective"]) + return result + + +def _traced_usage(report: ValidationReport) -> dict: + """Count recorded chat call tokens, separately from saved turn usage. + + Parameters + ---------- + report: ValidationReport + Decoded workspace diagnostics, including events outside commands. + + Returns + ------- + dict + Available token totals and coverage by call-input/output record. + This is not a second sum to add to the saved chat counters. + + """ + result = {} + for key, event_type, field in ( + ("input_tokens", "llm.call.input", "input_token_count"), + ("output_tokens", "llm.call.output", "output_token_count"), + ): + records = [e.details.get(field) for e in report.events + if e.event_type == event_type] + samples = [value for value in records + if type(value) is int and value >= 0] + result[key] = {"recorded_total": sum(samples) if samples else None, + "available_records": len(samples), + "total_records": len(records)} + return result + + +def _call_rows(op: TimelineOperation) -> list[dict]: + """Annotate call rows by enclosing stage before occurrence comparison. + + Parameters + ---------- + op: TimelineOperation + One aligned recorded command. + + Returns + ------- + list[dict] + Call observations grouped by enclosing span type and occurrence. + + """ + events = {e.sequence: e for e in op.events} + starts = {(e.metadata["trace_id"], e.span_id): e.event_type + for e in op.events if e.span_id and + e.event_type.endswith(".started") and + "started_elapsed_ms" in e.metadata} + rows = model_calls(op) + for row in rows: + event = events[row["input_sequence"] or row["output_sequence"]] + row["stage"] = starts.get((event.metadata["trace_id"], event.span_id), + "unscoped") + return rows + + +def _call_comparison(original: TimelineOperation, + replayed: TimelineOperation, maps: tuple) -> list[dict]: + """Compare available exact model texts by stage and occurrence. + + Parameters + ---------- + original: TimelineOperation + Original operation. + replayed: TimelineOperation + Corresponding replay operation. + maps: tuple + Original-to-replay conversation and turn identity maps. + + Returns + ------- + list[dict] + Paired observations or unavailable sides, text metrics where both + artifacts exist, and text hashes instead of duplicated prompts. + + """ + conversations, turns = maps + namespaces = (({k: k for k in turns}, {k: k for k in conversations}), + ({v: k for k, v in turns.items()}, + {v: k for k, v in conversations.items()})) + groups = [] + for op, namespace in zip((original, replayed), namespaces, strict=True): + values = {} + inputs = {e.sequence: e for e in op.matching("llm.call.input")} + for row in _call_rows(op): + row["structured_prompt"] = structured_prompt( + inputs.get(row["input_sequence"]), op, *namespace) + values.setdefault(row["stage"], []).append(row) + groups.append(values) + first, second = groups + rows = [] + for stage in sorted(first.keys() | second.keys()): + a, b = first.get(stage, []), second.get(stage, []) + for i in range(max(len(a), len(b))): + old = a[i] if i < len(a) else None + new = b[i] if i < len(b) else None + metrics = {} + structures = [row.pop("structured_prompt", None) if row else None + for row in (old, new)] + for key in ("raw", "normalized"): + a_text, b_text = [entry.get(key) if entry else None + for entry in structures] + metrics["structured_" + key + "_equal"] = ( + a_text == b_text if a_text is not None and + b_text is not None else None) + for row, structure in zip((old, new), structures, strict=True): + if row is not None: + row["prompt_metadata"] = ( + {k: structure[k] for k in ("headers", "issue")} + if structure is not None else None) + for key in ("prompt", "answer"): + left = old.pop(key, None) if old else None + right = new.pop(key, None) if new else None + metrics[key] = (text_metrics(left, right) + if left is not None and right is not None + else None) + for row, text in ((old, left), (new, right)): + if row is not None: + row[key + "_sha256"] = (sha256(text.encode("utf-8") + ).hexdigest() + if text is not None else None) + rows.append({"stage": stage, "occurrence": i + 1, + "original": old, "replayed": new, + "text": metrics, + "inference": inference_comparison(old, new, metrics)}) + return rows + + +def _observations(op: TimelineOperation) -> dict: + """Extract semantic stage observations without comparing generated IDs. + + Parameters + ---------- + op: TimelineOperation + A validated command. + + Returns + ------- + dict + Selected original diagnostic payloads for manual interpretation. + + """ + types = ( + "intent.classification.decided", "history.selection.result", + "retrieval.plan", "retrieval.result", "evidence.finalized", + "retrieval.document.selected", "retrieval.sources.ranked", + "retrieval.context_expansion.planned", "memory.sync.result", + "generation.input.prepared", "generation.incomplete", + "conversation_memory.retrieved", "project.memory.sync.result", + "index.rebuilt", "index.reused", "index.empty", "tool.run.started", + "source_cards.prepared", "project.source_cards.regenerate.completed", + "workspace.source.copied", "workspace.sync.file", + "workspace.sync.started", "workspace.sync.completed", + "gui.sources.add.requested", "gui.sources.add.completed", + ) + rows = {} + for event in op.events: + kind = event.event_type + if kind in types or (kind.startswith("tool.") and + kind.endswith(".result")): + rows.setdefault(kind, []).append(event.details) + return rows + + +def _source_manifest(op: TimelineOperation) -> list[dict]: + """Expose the retained historical file manifests at a command boundary. + + Parameters + ---------- + op: TimelineOperation + One recorded command. + + Returns + ------- + list[dict] + Historical source manifests, not regenerated final indexes. + + """ + return [e.details["source_manifest"] for e in op.matching( + "index.check.completed", "index.empty")] + + +def _question(original: TimelineOperation, replayed: TimelineOperation, + old_turns: dict[str, dict], new_turns: dict[str, dict], + evaluator: EmbeddingEvaluator) -> dict: + """Compare the committed question once, even if inherited by branches. + + Parameters + ---------- + original: TimelineOperation + Original ask command. + replayed: TimelineOperation + Matched replay ask command. + old_turns: dict[str, dict] + Validated original committed turns. + new_turns: dict[str, dict] + Validated replay committed turns. + evaluator: EmbeddingEvaluator + Shared optional evaluator, reused across questions. + + Returns + ------- + dict + Text, citation, usage, tool, intent, and semantic similarity metrics. + + """ + first = one(original.events, "gui.question.saved") + second = one(replayed.events, "gui.question.saved") + old_id = first.details["conversation_turn_uuid"] + new_id = second.details["conversation_turn_uuid"] + a, b = old_turns[old_id], new_turns[new_id] + left, right = a["parameters"], b["parameters"] + issues = [] + try: + evidence = evidence_metrics(a, b) + except (ValueError, KeyError, TypeError, AttributeError) as error: + evidence = None + issues.append(f"Evidence metric unavailable: {error}") + return { + "question": a["question"], + "original_turn_uuid": old_id, "replayed_turn_uuid": new_id, + "original_trace": first.path, "replayed_trace": second.path, + "answer": {"original": a["answer"], "replayed": b["answer"], + **text_metrics(a["answer"], b["answer"]), + "embedding": evaluator.measure(a["answer"], b["answer"])}, + "evidence": evidence, "issues": issues, + "intent": {"original": left.get("intent"), + "replayed": right.get("intent")}, + "retrieval_mode": {"original": left.get("retrieval_mode"), + "replayed": right.get("retrieval_mode")}, + "tool": {"original": left.get("tool"), "replayed": right.get("tool")}, + "completion": {"original": left.get("completion"), + "replayed": right.get("completion")}, + "finish_reason": {"original": left.get("finish_reason"), + "replayed": right.get("finish_reason")}, + "usage": {"original": usage(a), "replayed": usage(b)}, + "interactions": {"original": interaction_records(original), + "replayed": interaction_records(replayed)}, + } + + +def _operation(original: TimelineOperation, replayed: TimelineOperation, + old_turns: dict[str, dict], new_turns: dict[str, dict], + evaluator: EmbeddingEvaluator, catalogs: tuple, + maps: tuple) -> dict: + """Measure a matched command and its observed intermediate stages. + + Parameters + ---------- + original: TimelineOperation + Original operation. + replayed: TimelineOperation + Replayed operation. + old_turns: dict[str, dict] + Unique original committed turns. + new_turns: dict[str, dict] + Unique replay committed turns. + evaluator: EmbeddingEvaluator + Shared optional evaluation model. + catalogs: tuple + Original and replayed conversation turn-prefix maps. + maps: tuple + Original-to-replay conversation and turn maps. + + Returns + ------- + dict + One structured comparison row, with explicit metric errors. + + """ + row = {"kind": original.kind, "original_sequence": original.start_sequence, + "replayed_sequence": replayed.start_sequence, + "duration": {"original": operation_duration(original), + "replayed": operation_duration(replayed)}, + "settings_differences": [asdict(d) for d in + _configuration_differences( + (original,), (replayed,))], + "plugin_provenance": compare_plugins(original, replayed), + "source_organization": compare_semantics(original, replayed), + "source_manifests": {"original": _source_manifest(original), + "replayed": _source_manifest(replayed)}, + "stages": stage_metrics(original, replayed), + "observations": {"original": _observations(original), + "replayed": _observations(replayed)}, + "rankings": ranking_metrics(original, replayed), "issues": []} + row["context"] = context_comparison(original, replayed, catalogs, maps) + try: + row["model_calls"] = _call_comparison(original, replayed, maps) + except (ValueError, TypeError, KeyError, AttributeError) as error: + row["model_calls"] = None + row["issues"].append(f"Model call metrics unavailable: {error}") + if original.kind in ("create_project", "add_sources", "sync_sources"): + row["source_requests"] = { + side: (op.request["source_batch"] if op.kind == "create_project" + else op.request) for side, op in ( + ("original", original), ("replayed", replayed)) + } + if original.kind == "open_project" and "relocation" in original.request: + row["relocation"] = { + "original": original.request["relocation"], + "replayed": replayed.request.get("relocation"), + "physical_rename_replayed": "relocation" in replayed.request, + } + if original.kind == "create_project": + row["settings_provenance"] = { + side: op.request["settings"] for side, op in ( + ("original", original), ("replayed", replayed)) + } + if original.kind == "ask": + row["settings_provenance"] = { + side: {k: op.request[k] for k in ( + "generation_settings", "generation_provenance", + "profile_generation_settings", "explicit_generation_settings", + "effort", "retrieval_count")} + for side, op in (("original", original), ("replayed", replayed)) + } + row["question"] = _question(original, replayed, old_turns, new_turns, + evaluator) + question = row["question"] + question["tool_comparison"] = tool_comparison( + question["tool"], question["completion"], + executions={side: len(op.matching("tool.run.started")) + for side, op in (("original", original), + ("replayed", replayed))}, + finish_reasons=question["finish_reason"]) + row["divergence"] = operation_divergence(row, original, replayed) + return row + + +def _state_pairs(left: dict, right: dict, conversations: dict[str, str], + turns: dict[str, str]) -> dict: + """Compare mapped final conversation structure and authoritative ratings. + + Parameters + ---------- + left: dict + Original validated workspace summary. + right: dict + Replay validated workspace summary. + conversations: dict[str, str] + Reconstructed original-to-replay conversation map. + turns: dict[str, str] + Reconstructed original-to-replay unique turn map. + + Returns + ------- + dict + Paired final metadata, mapped turn prefixes and feedback. For a + divergent prefix the final snapshots may include unmatched suffixes. + + """ + result = {"conversations": [], "feedback": []} + if not left["valid"] or not right["valid"]: + return result + a = {c["id"]: c for c in left["conversations"]} + b = {c["id"]: c for c in right["conversations"]} + for old, new in conversations.items(): + first, second = a[old], b[new] + mapped = [turns.get(uid) for uid in first["turn_uuids"]] + result["conversations"].append({ + "original_id": old, "replayed_id": new, + "name_equal": first["name"] == second["name"], + "name_origin": {"original": first["name_origin"], + "replayed": second["name_origin"]}, + "archival_equal": first["archived"] == second["archived"], + "lineage_equal": (first["origin_turn_count"] == + second["origin_turn_count"] and + (first["parent_id"] is None or + first["parent_id"] in conversations) and + conversations.get(first["parent_id"]) == + second["parent_id"]), + "turn_prefix_equal": mapped == second["turn_uuids"], + }) + for old, new in turns.items(): + first = left["feedback"].get(old, {}) + second = right["feedback"].get(new, {}) + result["feedback"].append({"original_turn_uuid": old, + "replayed_turn_uuid": new, + "original": first, "replayed": second, + "equal": first == second}) + return result + + +def _aggregate(operations: list[dict]) -> dict: + """Summarize only available question metrics with coverage counts. + + Parameters + ---------- + operations: list[dict] + Matched operation observations. + + Returns + ------- + dict + Per-metric means and denominators, without thresholds or composites. + + """ + questions = [row["question"] for row in operations if "question" in row] + values = { + "token_f1": [q["answer"]["token_f1"] for q in questions], + "embedding_cosine": [q["answer"]["embedding"]["cosine"] + for q in questions], + "evidence_jaccard": [q["evidence"]["overlap"]["jaccard"] + if q["evidence"] else None for q in questions], + "citation_jaccard": [q["evidence"]["citations"]["overlap"]["jaccard"] + if q["evidence"] else None for q in questions], + } + result = {"questions": len(questions), "exact_answers": sum( + q["answer"]["exact_equal"] for q in questions), + "normalized_equal_answers": sum(q["answer"]["normalized_equal"] + for q in questions)} + for name, samples in values.items(): + available = [value for value in samples if value is not None] + result[name] = {"mean": math.fsum(available) / len(available) + if available else None, + "available": len(available), "total": len(samples)} + durations = [(op["duration"]["original"]["ms"], + op["duration"]["replayed"]["ms"]) for op in operations] + paired = [(a, b) for a, b in durations if a is not None and b is not None] + result["paired_command_duration_ms"] = { + "original": math.fsum(a for a, _ in paired) if paired else None, + "replayed": math.fsum(b for _, b in paired) if paired else None, + "available": len(paired), "total": len(durations), + } + result["model_reproducibility"] = inference_summary(operations) + result["tool_transitions"] = dict(sorted(Counter( + q["tool_comparison"]["transition"] for q in questions).items())) + return result + + +def _portable(value: object, path: str, issues: list[str]) -> object: + """Copy JSON values and identify invalid optional diagnostic numbers. + + Parameters + ---------- + value: object + Diagnostic value or report container. + path: str + Location within the report, for unavailable observations. + issues: list[str] + Collector for explicit nonfinite-value diagnostics. + + Returns + ------- + object + Independent JSON-compatible value; nonfinite numbers become None, + never zero. The unavailable location is retained in the report. + + """ + if type(value) is float and not math.isfinite(value): + issues.append(f"Nonfinite diagnostic value unavailable at {path}.") + return None + if isinstance(value, dict): + return {k: _portable(v, f"{path}/{k}", issues) + for k, v in value.items()} + if isinstance(value, (list, tuple)): + return [_portable(v, f"{path}/{i}", issues) + for i, v in enumerate(value)] + return value + + +def compare(experiment: Experiment, destination: str | Path | None = None, + *, embedding_model: str | None = None, + embedding_backend: str = "auto", + embedding_revision: str | None = None) -> Comparison: + """Inspect and compare the original and an existing replay independently. + + Parameters + ---------- + experiment: Experiment + Closed original reference workspace. + destination: str | pathlib.Path | None, optional + Existing sibling replay, defaulting to the usual replay path. A missing + or invalid replay is reported without inventing correspondences. + embedding_model: str | None, optional + Explicit local/cached evaluation model. Defaults to None, disabling + embeddings; deterministic metrics remain available without models. + embedding_backend: str, optional + Evaluation backend preference, defaulting to ``"auto"``. + embedding_revision: str | None, optional + Requested evaluation model revision, defaulting to None. + + Returns + ------- + Comparison + Portable report snapshot. Both workspaces remain unchanged. + + Notes + ----- + Both complete recordings must validate before any matching. For valid + but divergent histories, only their unambiguous prefix is compared. + Recorded metrics are observations, not correctness or quality verdicts. + The evaluator is optional, uses one model for both sides, and does not + request downloads, retries, or fallback models. + + """ + if embedding_model is not None and ( + not isinstance(embedding_model, str) or not embedding_model.strip() + ): + raise ValueError("Choose an explicit embedding model or None.") + if embedding_backend not in ("auto", "mlx", "torch"): + raise ValueError("Invalid evaluation embedding backend.") + if embedding_revision is not None and ( + not isinstance(embedding_revision, str) or + not embedding_revision.strip()): + raise ValueError("Invalid evaluation model revision.") + if embedding_model is None and embedding_revision is not None: + raise ValueError("An embedding revision requires an evaluation model.") + root = experiment.workspace + target = _replay_path(root, destination) + old, new = read_recording(root), read_recording(target) + before, after = validate_recording(old), validate_recording(new) + evaluator = EmbeddingEvaluator(embedding_model, embedding_backend, + embedding_revision) + rows = [] + if before.valid and after.valid: + matched = align(before.operations, after.operations) + old_turns, new_turns = _saved_turns(old), _saved_turns(new) + catalogs = tuple({c["id"]: c["turn_uuids"] for c in _catalog(r)} + for r in (old, new)) + maps = matched.conversations, matched.turns + try: + for a, b in matched.pairs: + rows.append(_operation(a, b, old_turns, new_turns, evaluator, + catalogs, maps)) + finally: + evaluator.close() + status = "complete" if matched.reason is None else "diverged" + reason = matched.reason + conversations, turns = matched.conversations, matched.turns + else: + status = "invalid_recording" + reason = "Both closed workspace recordings must validate." + conversations, turns = {}, {} + left, right = _workspace(old, before), _workspace(new, after) + data = { + "format_version": COMPARISON_FORMAT_VERSION, + "original": left, "replayed": right, + "alignment": {"status": status, "reason": reason, + "matched_operations": len(rows), + "original_unmatched": left["operations"][len(rows):], + "replayed_unmatched": right["operations"][len(rows):], + "conversation_ids": conversations, "turn_uuids": turns}, + "summary": _aggregate(rows), "operations": rows, + "first_divergence": first_divergence(rows, status), + "final_state": _state_pairs(left, right, conversations, turns), + "embedding_evaluation": evaluator.provenance, + "files": { + directory: file_changes( + inventory(root, directory, recorded=before.source_paths), + inventory(target, directory, recorded=after.source_paths), + ) + for directory in ("sources", "templates", "outputs") + }, + } + data["performance"] = { + side: performance_summary(report.events) if report.valid else None + for side, report in (("original", before), ("replayed", after))} + data["inspection"] = note_inspection(data, before) + data["reference_publication"] = inspect_receipt(root, before) + data["replay_execution"] = execution_provenance(target, after) + if data["replay_execution"]["status"] == "recorded": + data["replay_execution"]["reference_match"] = ( + reference_execution_match(data["replay_execution"], before)) + data["expected_event_differences"] = relocation_event_differences( + data, before, after) + issues: list[str] = [] + snapshot = _portable(data, "", issues) + snapshot["report_issues"] = issues + # Fail before publishing if the report is not a valid JSON object. + json.dumps(snapshot, ensure_ascii=False, allow_nan=False) + return Comparison(root, target, snapshot) diff --git a/kilin/system_testing/experiment.py b/kilin/system_testing/experiment.py new file mode 100644 index 00000000..424755d9 --- /dev/null +++ b/kilin/system_testing/experiment.py @@ -0,0 +1,195 @@ +"""Inspect, reproduce and compare a recorded system-testing workspace. + +Key Features +------------ +- Inspect reference recordings without loading a model or starting the GUI. +- Validate on demand and reconstruct supported chronological commands. +- Never modify, repair, or migrate the reference workspace. +- Reproduce its validated operations in a separate new workspace. +- Independently compare the original and reproduced recordings. + +Module Structure +---------------- +- ``Experiment`` provides the public entry point for reference inspection. + +Examples +-------- +>>> from pathlib import Path +>>> from kilin.system_testing import Experiment +>>> experiment = Experiment(Path("workspaces/010_original")) +>>> # report = experiment.validate() +>>> # if report.valid: +>>> # operations = experiment.timeline() + +""" + +from pathlib import Path + +from .comparison import Comparison, compare +from .replay import ProgressCallback, ReplayResult, replay +from .replay_management import ManagedReplay, run_replay +from .timeline import TimelineOperation +from .traces import read_recording +from .validation import ValidationReport, validate_recording + +__all__ = ["Experiment"] + + +class Experiment: + """Read-only reference inspection and independent workspace replay. + + Parameters + ---------- + workspace: str | pathlib.Path + Reference project directory. The path is resolved without creating + missing files. Validation is explicit, not performed on construction. + + Attributes + ---------- + workspace: pathlib.Path + Resolved reference workspace path. + + Notes + ----- + Each inspection reads a fresh snapshot. Close the original project and + keep its files unchanged during inspection. No writer lock is acquired; + acquiring one could modify the reference. Replay creates an independent + sibling workspace; comparison of answers is separate. + + """ + + def __init__(self, workspace: str | Path) -> None: + """Store the original workspace location without opening it. + + Parameters + ---------- + workspace: str | pathlib.Path + Reference project directory. + + """ + self.workspace = Path(workspace).expanduser().resolve() + + def validate(self) -> ValidationReport: + """Inspect the current reference and collect detectable issues. + + Returns + ------- + ValidationReport + Complete inspection result with blocking issues and limitations. + + """ + return validate_recording(read_recording(self.workspace)) + + def timeline(self) -> tuple[TimelineOperation, ...]: + """Return chronological operations only for a valid reference. + + Returns + ------- + tuple[TimelineOperation, ...] + Chronologically ordered supported commands with diagnostics. + + Raises + ------ + InvalidRecordingError + If validation detects a missing or inconsistent recording. + + """ + report = self.validate() + report.raise_for_errors() + return report.operations + + def replay( + self, destination: str | Path | None = None, *, + progress: ProgressCallback | None = None, + ) -> ReplayResult: + """Execute the validated reference in a new sibling workspace. + + Parameters + ---------- + destination: str | pathlib.Path | None, optional + New sibling directory, which must not exist. Defaults to a + sibling with the suffix ``_replay``. + progress: ProgressCallback | None, optional + Called before each operation with index, total, and the + original TimelineOperation. Defaults to None. + + Returns + ------- + ReplayResult + Reproduced workspace, identity mappings and observed differences. + + Notes + ----- + Runs ordinary KíLín operations and models. Current inherited + defaults are not replaced with historical values. Divergence raises + ReplayError and leaves the partial workspace available for inspection. + + """ + return replay(self, destination, progress=progress) + + def run_replay( + self, destination: str | Path | None = None, *, + existing_replay: str = "retain", + archive_directory: str | Path | None = None, + progress: ProgressCallback | None = None, + ) -> ManagedReplay: + """Manage a fresh or retained replay with explicit provenance. + + Parameters + ---------- + destination: str or pathlib.Path or None, optional + Separate sibling replay workspace; defaults to the usual name. + existing_replay: str, optional + Retain (default), archive, or reject an existing replay using + the corresponding lowercase policy string. + archive_directory: str or pathlib.Path or None, optional + Separate archive root outside workspace discovery. Defaults to + ``_replay_archive`` beside the discovery directory. + progress: ProgressCallback or None, optional + Progress callback for a new replay. + + Returns + ------- + ManagedReplay + Actual action outcome including archived workspace and receipt. + + """ + return run_replay(self, destination, existing_replay=existing_replay, + archive_directory=archive_directory, + progress=progress) + + def compare( + self, destination: str | Path | None = None, *, + embedding_model: str | None = None, + embedding_backend: str = "auto", + embedding_revision: str | None = None, + ) -> Comparison: + """Compare an existing replay without re-executing either workspace. + + Parameters + ---------- + destination: str | pathlib.Path | None, optional + Existing sibling replay workspace, defaulting to the usual name. + embedding_model: str | None, optional + Explicit local or cached evaluation embedding model. Defaults to + None, so deterministic metrics do not require model inference. + embedding_backend: str, optional + Evaluation backend preference. Defaults to ``"auto"``. + embedding_revision: str | None, optional + Evaluation model revision. Defaults to None. + + Returns + ------- + Comparison + Fresh validation, alignment and quantitative comparison snapshot. + + Notes + ----- + Both closed recordings are read independently. No in-memory replay + result or previous report is required. Optional embedding evaluation + uses the same model instance on both sides without downloads. + + """ + return compare(self, destination, embedding_model=embedding_model, + embedding_backend=embedding_backend, + embedding_revision=embedding_revision) diff --git a/kilin/system_testing/generation.py b/kilin/system_testing/generation.py new file mode 100644 index 00000000..3975faac --- /dev/null +++ b/kilin/system_testing/generation.py @@ -0,0 +1,531 @@ +"""Generate closed system-testing references from trusted experiment recipes. + +Key Features +------------ +- Drive ordinary recorded engine commands and explicit local interactions. +- Validate command history, protect destinations and publish references. +- Report question-specific coverage hints and saved output observations. + +Module Structure +---------------- +- ``Recorder``: synchronous command and interaction adapter. +- ``generate_reference``: staging, validation and publication lifecycle. +- ``check_output``, ``reference_overview``: descriptive recipe diagnostics. + +Examples +-------- +>>> from kilin.system_testing.generation import generate_reference +>>> # Pass a trusted recipe and explicit creation settings. + +""" + +from __future__ import annotations + +from html import escape +from pathlib import Path + +from .experiment import Experiment +from .reference import publish_receipt, receipt_path + +__all__ = ["Recorder", "generate_reference", "check_output", + "reference_overview"] + + +class Recorder: + """Drive the real synchronous engine and verify command outcomes.""" + + def __init__(self, recording, relocated, project_type, settings): + """Configure a traced engine without loading a model. + + Parameters + ---------- + recording: pathlib.Path + Fresh staging workspace path. + relocated: pathlib.Path + Staging sibling used by an explicit rename recipe. + project_type: str + Registered project type identifier. + settings: dict + Explicit project creation settings. + + """ + from ..gui.engine import ChatEngine + + self.project_type = project_type + self.settings = dict(settings) + self.relocated = relocated + self.events = [] + self.results = [] + self.coverage = [] + self.prompt = None + self.plans = {} + self.options = {} + self.responses = [] + self.failure = None + self.request_id = 0 + self.directory = recording + self.engine = ChatEngine( + recording.parent, self.observe, trace_enabled=True, + read_command=self.read_command, + ) + + def observe(self, event): + """Collect acknowledgements and live interaction payloads. + + Parameters + ---------- + event: dict + Synchronous engine notification. + + """ + kind = event["event"] + if kind == "answer_delta": + return + self.events.append(event) + if kind == "status": + print(event.get("message", "")) + if kind == "answer_phase": + for name in ("plan", "choice"): + if name in event: + if self.prompt is not None: + self.failure = "Overlapping interaction prompts." + raise RuntimeError(self.failure) + self.prompt = (name, event[name]) + + def read_command(self): + """Answer only a predeclared local plan or unique option label. + + Returns + ------- + dict + Explicit approved engine response. + + """ + try: + if self.prompt is None: + raise RuntimeError("Unexpected interaction without a prompt.") + kind, prompt = self.prompt + self.prompt = None + if kind == "plan": + if prompt.get("operation", "model") != "model": + raise RuntimeError( + "Non-model plan requires manual review." + ) + tool = prompt.get("tool") + choice = self.plans.get(tool) + if choice not in ("quick", "continue"): + raise RuntimeError(f"Unapproved plan: {prompt}") + self.responses.append(("plan", tool, choice)) + else: + question = prompt.get("question") + prefix = self.options.get(question) + labels = prompt.get("options", []) + matches = [i for i, label in enumerate(labels) + if prefix and label.startswith(prefix)] + if len(matches) != 1: + raise RuntimeError(f"Unapproved choice: {prompt}") + index = matches[0] + choice = f"option:{index}" + self.responses.append(("choice", question, labels[index])) + print("Scripted response:", self.responses[-1]) + return {"action": "plan_choice", "choice": choice} + except Exception as error: + self.failure = str(error) + raise + + def call(self, method, *args, expected=None, **kwargs): + """Reject failures emitted by engine methods, not just exceptions. + + Parameters + ---------- + method: callable + Ordinary synchronous engine command. + *args: object + Positional arguments forwarded to the command. + expected: str or None + Required acknowledgement event type, if any. + **kwargs: object + Keyword arguments forwarded to the command. + + """ + self.events.clear() + self.prompt = None + self.failure = None + method(*args, **kwargs) + bad = [event for event in self.events if ( + event["event"] in ("error", "workspace_conflict", + "backend_failed", "answer_cancelled", + "memory_sync_failed") + or event.get("error") + )] + if self.failure or bad or self.prompt is not None: + raise RuntimeError(self.failure or str(bad or self.prompt)) + if expected and not any(e["event"] == expected for e in self.events): + raise RuntimeError(f"Missing acknowledgement: {expected}") + + def active_id(self): + """Return the current live conversation identity. + + Returns + ------- + str + Current conversation identity. + + """ + return self.engine.active_conversation.conversation_id + + def open(self, sources=(), *, selected_files=None): + """Create a traced project, without GUI widgets. + + Parameters + ---------- + sources: sequence[pathlib.Path] + Local sources to copy into the new workspace. + selected_files: list[str] or None + Explicit file selection within imported source paths. + + """ + paths = [str(path.resolve(strict=True)) for path in sources] + self.call(self.engine.open_project, paths, self.project_type, + str(self.directory), selected_files=selected_files, + settings=self.settings, expected="opened") + if self.engine.session.project.root != self.directory: + raise RuntimeError("Opened an unexpected workspace.") + profile = self.engine.session.project.profile + if (profile.temperature != self.settings["temperature"] + or profile.thinking != self.settings["thinking"] + or profile.max_new_tokens != + self.settings["max_new_tokens"]): + raise RuntimeError("Creation generation settings differ.") + + def ask(self, label, question, *, terms=(), source_names=(), + intent=None, plans=None, options=None, require=(), **kwargs): + """Save a question and collect nonjudgmental review hints. + + Parameters + ---------- + label: str + Human-readable label. + question: str + Exact user question to record. + terms: sequence[str] + Case-insensitive answer-content hints. + source_names: sequence[str] + Expected evidence basenames, used only as review hints. + intent: str or None + Optional expected intent, recorded as a review hint. + plans: dict or None + Approved local tool-plan choices keyed by tool name. + options: dict or None + Approved option-label prefixes keyed by prompt question. + require: sequence[str] + Interaction kinds expected as coverage observations. + **kwargs: object + Question-specific settings forwarded to the engine. + + Returns + ------- + object + Newly committed conversation turn. + + """ + self.plans = dict(plans or {}) + self.options = dict(options or {}) + self.responses.clear() + before = len(self.engine.session.turns) + generation = kwargs.get("generation_settings") or {} + profile = self.engine.session.project.profile + expected_temperature = generation.get( + "temperature", profile.temperature + ) + print(f"\n{label}: {question}") + try: + self.call(self.engine.ask, question, expected="answered", **kwargs) + finally: + self.plans.clear() + self.options.clear() + turns = self.engine.session.turns + if len(turns) != before + 1 or turns[-1].question != question: + raise RuntimeError("Expected one newly committed question.") + turn = turns[-1] + if turn.parameters.get("temperature") != expected_temperature: + raise RuntimeError("Recorded temperature differs from request.") + paths = sorted({Path(e.path).name for e in turn.evidence}) + visible = turn.answer.rsplit("", 1)[-1].strip() + hints = [f"Expected text: {term}" for term in terms + if term.casefold() not in visible.casefold()] + hints += [f"Expected evidence file: {name}" for name in source_names + if name not in paths] + actual = turn.parameters.get("intent") + if intent is not None and actual != intent: + hints.append(f"Expected intent {intent}; observed {actual}") + for kind in require: + if not any(response[0] == kind for response in self.responses): + hints.append(f"Planned {kind} interaction not exercised") + self.results.append({ + "id": label, "question": question, "answer": visible, + "intent": actual, "evidence": paths, "hints": hints, + "temperature": turn.parameters["temperature"], + "thinking": turn.parameters.get("thinking"), + "responses": list(self.responses), + }) + return turn + + def rename(self): + """Exercise the recorded project-folder relocation command.""" + active = self.active_id() + before = [turn.conversation_turn_uuid + for turn in self.engine.session.turns] + self.call(self.engine.rename_project, self.relocated.name, + expected="opened") + self.directory = self.relocated + if (self.engine.session.project.root != self.directory + or self.active_id() != active + or [turn.conversation_turn_uuid + for turn in self.engine.session.turns] != before): + raise RuntimeError("Project relocation did not restore the chat.") + + def resume(self, conversation_id): + """Reopen a closed workspace at an explicitly selected chat. + + Parameters + ---------- + conversation_id: str + Existing conversation to restore. + + """ + self.call(self.engine.resume_project, str(self.directory), + conversation_id, expected="opened") + if self.active_id() != conversation_id: + raise RuntimeError("Incorrect conversation restored.") + + +def generate_reference(root: Path, experiment: str, project_type: str, + settings: dict, expected_operations, record, + check_coverage): + """Record and publish one closed reference using a trusted recipe. + + Preserve incomplete staging directories and refuse existing references, + replays or publication receipts. Only the recipe may authorize local + interactions. Coverage observations are not answer-quality verdicts. + + Parameters + ---------- + root: pathlib.Path + Experiment repository containing the workspaces directory. + experiment: str + Unique single-component stem, without the original suffix. + project_type: str + Registered project type for the creation command. + settings: dict + Explicit creation settings, including temperature, thinking and + maximum new tokens. + expected_operations: sequence[str] + Complete chronological command kinds expected from the recipe. + record: callable + Trusted function accepting a Recorder and issuing engine commands. + check_coverage: callable + Trusted function accepting the recorder and validated report, + appending descriptive coverage observations before publication. + + Returns + ------- + tuple[Recorder, ValidationReport] + Recorder and validated published reference report. + + """ + root = Path(root).resolve() + if (not isinstance(experiment, str) or not experiment or + experiment in (".", "..") or any(c in experiment for c in + ("/", "\\", ":", "\x00")) or + experiment.endswith(("_original", "_replay"))): + raise ValueError("Expected a single experiment stem.") + workspaces = root / "workspaces" + original = workspaces / f"{experiment}_original" + replay = workspaces / f"{experiment}_replay" + staging = root / "_recordings" + recording = staging / f"{experiment}_recording" + relocated = staging / f"{experiment}_relocated_recording" + # Run the complete script once. Preserve failed or unfinished attempts. + protected = (original, replay, recording, relocated, + receipt_path(original)) + if staging.is_symlink() or (staging.exists() and not staging.is_dir()): + raise ValueError(f"Expected a real staging directory: {staging}") + if workspaces.is_symlink() or not workspaces.is_dir(): + raise ValueError(f"Expected a real workspace folder: {workspaces}") + for path in protected: + if path.exists() or path.is_symlink(): + raise FileExistsError(f"Move the existing workspace first: {path}") + + staging.mkdir(exist_ok=True) + recorder = Recorder(recording, relocated, project_type, settings) + try: + record(recorder) + finally: + recorder.engine.close() + + report = Experiment(recorder.directory).validate() + for issue in report.issues: + print(issue.code, issue.sequence, issue.message) + report.raise_for_errors() + actual_operations = [op.kind for op in report.operations] + if actual_operations != list(expected_operations): + raise RuntimeError( + f"Unexpected command history:\n{actual_operations}\n" + f"Expected:\n{expected_operations}" + ) + asks = [op for op in report.operations if op.kind == "ask"] + if [op.request["question"] for op in asks] != [ + row["question"] for row in recorder.results]: + raise RuntimeError( + "Saved question history differs from scripted inputs.") + check_coverage(recorder, report) + for row in recorder.results: + recorder.coverage.extend( + f'REVIEW: {row["id"]}: {hint}' for hint in row["hints"] + ) + + # Publication is an ordinary move of an already closed recording, not a + # simulated GUI rename. Never move a live workspace or overwrite a target. + if original.exists() or original.is_symlink(): + raise FileExistsError(original) + recorder.directory.rename(original) + recorder.directory = original + report = Experiment(original).validate() + report.raise_for_errors() + receipt = publish_receipt(original, report, recorder.coverage) + print("\nPublished reference:", original) + print("Publication receipt:", receipt) + print("Events:", report.event_count, "Operations:", len(report.operations)) + print("Questions:", len(asks)) + for warning in report.warnings: + print("Validation warning:", warning.code, warning.message) + return recorder, report + + +def check_output(directory: Path, summary, *, label: str, tool: str, + field: str, expected: str, template: str | None = None, + require_valid: bool = False) -> list[str]: + """Check the output attributed to one particular recorded question. + + A file from another question cannot fulfill the check. A failed or + partial tool result is retained as a coverage observation; it does not + invalidate an otherwise valid operation recording. + + Parameters + ---------- + directory: pathlib.Path + Explicit directory to inspect or write artifacts in. + summary: dict or None + Tool summary from the particular committed question. + label: str + Human-readable label. + tool: str + Expected tool name. + field: str + Tool-summary field containing the saved filename. + expected: str + Expected workspace-relative saved output filename. + template: str or None + Expected report template identifier, if specified. + require_valid: bool + Require an explicit successful validation result. + + Returns + ------- + list[str] + Coverage observations, with REVIEW prefixes for missing + coverage. + + """ + if not isinstance(summary, dict) or summary.get("name") != tool: + return [f"REVIEW: {label}: expected tool {tool} did not complete."] + if summary.get("status") in ("incomplete", "partial", "error", "failed"): + return [f"REVIEW: {label}: {tool} did not produce a complete result."] + if template is not None and summary.get("template") != template: + return [f"REVIEW: {label}: expected template {template} not used."] + if require_valid and summary.get("valid") is not True: + return [f"REVIEW: {label}: {template} report was not validated."] + if summary.get(field) != expected: + return [f"REVIEW: {label}: expected saved file {expected} absent."] + + def present(relative: str) -> bool: + """Check a safe, nonempty regular file under the outputs folder. + + Parameters + ---------- + relative: str + Workspace-relative recorded trace or artifact path. + + Returns + ------- + bool + Whether the reported output is a nonempty regular file. + + """ + if not isinstance(relative, str): + return False + path = Path(relative) + if (path.is_absolute() or len(path.parts) < 2 or + path.parts[0] != "outputs" or ".." in path.parts or + "\\" in relative): + return False + location = directory + for part in path.parts: + location = location / part + if location.is_symlink(): + return False + return location.is_file() and location.stat().st_size > 0 + + if not present(expected): + return [f"REVIEW: {label}: missing or empty file {expected}."] + messages = [f"{label}: verified {tool} output {expected}."] + pdf = summary.get("saved_pdf") + if pdf is not None: + if present(pdf): + messages.append(f"{label}: verified reported PDF file {pdf}.") + else: + messages.append(f"REVIEW: {label}: reported PDF is missing.") + elif require_valid: + messages.append(f"{label}: no PDF output reported (Markdown checked).") + return messages + + +def reference_overview(recorder: Recorder, report) -> str: + """Render saved reference answers and coverage without calling a model. + + Parameters + ---------- + recorder: Recorder + Completed reference recording adapter. + report: ValidationReport + Validation result for the published reference. + + """ + # Read the actual recorded answers; these are review hints, not pass/fail + # criteria. No model, judge, or replay is called by this presentation cell. + rows = [] + for result in recorder.results: + hints = result["hints"] + state = "REVIEW" if hints else "No scripted hints missing" + title = f'{result["id"]} — {result["question"]} — {state}' + meta = (f'Intent: {result["intent"]}; ' + f'Temperature: {result["temperature"]}; ' + f'Configured thinking: {result["thinking"]}; ' + f'Evidence: {", ".join(result["evidence"]) or "none"}; ' + f'Choices: {result["responses"] or "none"}') + items = "".join(f"
  • {escape(hint)}
  • " for hint in hints) + rows.append( + f'
    {escape(title)}' + f'

    {escape(meta)}

      {items}
    ' + '
    ' + f'{escape(result["answer"])}
    ' + ) + summary = [f"{len(report.operations)} recorded operations; " + f"{report.event_count} events; " + f"{len(recorder.results)} questions."] + summary.extend(recorder.coverage) + return "

    Recorded reference — valid

    " + "".join( + f"

    {escape(line)}

    " for line in summary + ) + "".join(rows) diff --git a/kilin/system_testing/reference.py b/kilin/system_testing/reference.py new file mode 100644 index 00000000..5abe0826 --- /dev/null +++ b/kilin/system_testing/reference.py @@ -0,0 +1,258 @@ +"""Record and inspect reference publication without freezing GUI history. + +Key Features +------------ +- An optional receipt fingerprints the published trace prefix and artifacts. +- Closed inspection sessions may extend a reference without rewriting it. +- Strict KíLín comparison remains authoritative; benign tails are annotated. + +Module Structure +---------------- +- Publication receipt creation and verification. +- Publication receipt integrity and trace-prefix fingerprints. + +Examples +-------- +>>> receipt_path(Path('workspaces/010_hello_world_original')).name +'010_hello_world_reference.json' + +""" + +from __future__ import annotations + +from hashlib import sha256 +import json +import os +from pathlib import Path +from tempfile import NamedTemporaryFile +from typing import Final + +from ._filesystem import is_incidental_metadata +from ._inspection import inspection_suffix +from .traces import TraceEvent, read_json +from .validation import ValidationReport + +__all__ = [ + "receipt_path", "publish_receipt", "inspect_receipt", + "REFERENCE_RECEIPT_FORMAT_VERSION", +] + +REFERENCE_RECEIPT_FORMAT_VERSION: Final[int] = 1 + + +def receipt_path(original: Path) -> Path: + """Return the optional publication receipt beside a reference. + + Parameters + ---------- + original: pathlib.Path + Reference directory named with the ``_original`` suffix. + + """ + original = Path(original) + if not original.name.endswith("_original"): + raise ValueError("Expected a reference workspace name.") + return original.with_name( + original.name.removesuffix("_original") + "_reference.json") + + +def _prefix_digest(events: tuple[TraceEvent, ...], count: int) -> str: + """Hash exact decoded event payloads, not mutable trace containers. + + Parameters + ---------- + events: tuple[TraceEvent, ...] + Decoded chronological trace events. + count: int + Number of initial events to fingerprint. + + """ + prefix = [e for e in events if e.sequence <= count] + if [e.sequence for e in prefix] != list(range(1, count + 1)): + raise ValueError("Published trace prefix is not contiguous.") + digest = sha256() + for event in prefix: + payload = {"path": event.path, "metadata": event.metadata, + "details": event.details, + "exact_content": event.exact_content} + digest.update(json.dumps(payload, ensure_ascii=False, + sort_keys=True, allow_nan=False, + separators=(",", ":")).encode("utf-8")) + digest.update(b"\n") + return digest.hexdigest() + + +def _artifacts(original: Path) -> dict[str, str]: + """Fingerprint managed source, template and output files only. + + Parameters + ---------- + original: pathlib.Path + Closed reference workspace, with regular managed directories. + + """ + files = {} + for folder in ("sources", "templates", "outputs"): + root = original / folder + if root.is_symlink() or not root.is_dir(): + raise ValueError(f"Expected a real artifact directory: {root}") + for path in sorted(root.rglob("*")): + if path.is_symlink(): + raise ValueError(f"Linked artifact: {path}") + if path.is_dir(): + continue + if not path.is_file(): + raise ValueError(f"Nonregular artifact: {path}") + # Preserve the format-1 receipt's existing metadata exclusion. + if is_incidental_metadata( + path, path.relative_to(original).as_posix() + ): + continue + digest = sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + files[path.relative_to(original).as_posix()] = digest.hexdigest() + return files + + +def publish_receipt(original: Path, report: ValidationReport, + coverage: list[str]) -> Path: + """Publish a new receipt only after successful reference validation. + + Parameters + ---------- + original: pathlib.Path + Published, closed reference workspace. + report: ValidationReport + Fresh validation of the same reference. The caller must ensure no + intervening writes or concurrent GUI access. + coverage: list[str] + Generator observations, including explicit missing coverage. + + Notes + ----- + The receipt describes the reference at publication. It is never updated + by a replay or ordinary GUI inspection. A preexisting receipt is not + overwritten, and a failed publication leaves the closed reference intact. + + """ + report.raise_for_errors() + original = Path(original) + if original.is_symlink(): + raise ValueError("Reference must not be a symbolic link.") + if (not isinstance(coverage, list) or + any(not isinstance(item, str) for item in coverage)): + raise ValueError("Coverage must be a list of strings.") + if report.workspace != original.resolve(): + raise ValueError("Receipt must describe this validated reference.") + target = receipt_path(original) + if target.exists() or target.is_symlink(): + raise FileExistsError(target) + data = {"format_version": REFERENCE_RECEIPT_FORMAT_VERSION, + "reference": original.name, + "event_count": report.event_count, + "operation_count": len(report.operations), + "prefix_sha256": _prefix_digest(report.events, + report.event_count), + "artifacts": _artifacts(original), "coverage": list(coverage)} + temporary = None + try: + with NamedTemporaryFile(mode="w", encoding="utf-8", delete=False, + dir=target.parent) as stream: + temporary = Path(stream.name) + json.dump(data, stream, ensure_ascii=False, indent=2, + allow_nan=False) + stream.write("\n") + os.link(temporary, target) + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + return target + + +def inspect_receipt(original: Path, report: ValidationReport) -> dict: + """Describe preservation or extension of an optional published baseline. + + Parameters + ---------- + original: pathlib.Path + Closed original workspace. + report: ValidationReport + Fresh validation of this same workspace. + + Notes + ----- + Missing receipts are normal for manual and older references. A changed + prefix or artifact is a review finding, not a replacement for validation. + The original can intentionally be extended through recorded commands. + + """ + original = Path(original) + if not original.name.endswith("_original"): + return {"status": "unavailable"} + path = receipt_path(original) + if not path.exists() and not path.is_symlink(): + return {"status": "unavailable"} + try: + if original.is_symlink() or path.is_symlink() or not path.is_file(): + raise ValueError(f"Nonregular receipt: {path}") + data = read_json(path.parent, path.name) + if (type(data["format_version"]) is not int or + data["format_version"] != REFERENCE_RECEIPT_FORMAT_VERSION or + data["reference"] != original.name): + raise ValueError("Receipt does not identify this reference.") + count, operations = data["event_count"], data["operation_count"] + if (type(count) is not int or type(operations) is not int or + count < 1 or operations < 1): + raise ValueError("Invalid publication counts.") + if (not isinstance(data["coverage"], list) or + any(not isinstance(item, str) for item in data["coverage"])): + raise ValueError("Invalid publication coverage.") + if not report.valid: + return {"status": "not_validated"} + if report.workspace != original.resolve(): + raise ValueError("Validation report describes another reference.") + result = {"status": "unchanged", "published_events": count, + "published_operations": operations, + "additional_events": report.event_count - count, + "coverage": data["coverage"]} + if count > report.event_count or ( + _prefix_digest(report.events, count) != data["prefix_sha256"] + ): + return {**result, "status": "changed", + "message": "Published trace prefix differs."} + if not isinstance(data["artifacts"], dict): + raise ValueError("Invalid published artifact inventory.") + current = _artifacts(original) + changed = sorted(k for k in current.keys() | data["artifacts"].keys() + if current.get(k) != data["artifacts"].get(k)) + if changed: + return {**result, "status": "changed", "artifacts": changed, + "message": "Published managed artifacts differ."} + # A receipt must describe a closed command prefix, not a count + # chosen from inside a later inspection session. + if (operations > len(report.operations) or + report.operations[operations - 1].kind != "close_project" or + report.operations[operations - 1].end_sequence > count or + (operations < len(report.operations) and + report.operations[operations].start_sequence <= count)): + return {**result, "status": "changed", + "message": "Published command boundary differs."} + if len(report.operations) == operations: + if report.event_count != count: + result.update(status="extended", + message="Additional diagnostic events.") + elif len(report.operations) > operations: + tail = inspection_suffix(report, operations) + if tail: + result.update(status="inspection_only", operations=tail) + else: + result.update(status="extended", + message="Additional recorded commands.") + else: + result.update(status="changed", + message="Published operation count decreased.") + return result + except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: + return {"status": "error", "message": str(error)} diff --git a/kilin/system_testing/replay.py b/kilin/system_testing/replay.py new file mode 100644 index 00000000..259b6101 --- /dev/null +++ b/kilin/system_testing/replay.py @@ -0,0 +1,995 @@ +"""Execute a validated reference history in a separate managed workspace. + +Key Features +------------ +- Reuse the synchronous engine commands, without launching the frontend. +- Reproduce source batches, question inputs, and actual user decisions. +- Map newly allocated conversation and message identities across branches. +- Report effective settings differences and preserve failed replay attempts. + +Module Structure +---------------- +- ``ReplayResult`` and ``ReplayDifference`` describe the replay outcome. +- ``ReplayError`` identifies the first operation that could not be reproduced. +- ``replay`` runs a validated experiment using ordinary KíLín operations. + +Examples +-------- +>>> from kilin.system_testing import Experiment +>>> # result = Experiment("workspaces/010_original").replay() +>>> # result.workspace + +""" + +from __future__ import annotations + +from collections.abc import Callable +from copy import deepcopy +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import TYPE_CHECKING + +from kilin.conversation_memory.feedback import FeedbackStore + +from ._plugin_provenance import compare_plugins, preflight_plugins +from ._replay_interactions import InteractionReplay +from ._replay_sources import SourceReplay +from ._semantic_replay import compare_semantics +from .timeline import TimelineOperation, build_timeline, one +from .traces import read_recording +from .validation import ValidationReport + +if TYPE_CHECKING: + from .experiment import Experiment + +__all__ = ["ReplayResult", "ReplayDifference", "ReplayError", "replay"] + +ProgressCallback = Callable[[int, int, TimelineOperation], None] + + +@dataclass(frozen=True, slots=True) +class ReplayDifference: + """An observed change in settings or a replay input representation. + + Attributes + ---------- + sequence: int + Start of the original operation, not the replay event number. + field: str + Dotted configuration or interaction field. + original: object + Original recorded value. + replayed: object + Actual value or None when the retained input is unavailable. + + """ + + sequence: int + field: str + original: object + replayed: object + + +@dataclass(frozen=True, slots=True) +class ReplayResult: + """Outcome of a complete chronological replay. + + Attributes + ---------- + reference: pathlib.Path + Unmodified reference workspace. + workspace: pathlib.Path + Independently created replay workspace. + operation_count: int + Number of successfully reproduced reference commands. + conversation_ids: dict[str, str] + Original-to-replay conversation IDs, including archived records. + turn_uuids: dict[str, str] + Original-to-replay committed turn UUIDs, shared across branches. + differences: tuple[ReplayDifference, ...] + Configuration, interaction, and source-request differences. These + are observations, not answer-quality evaluations. + validation: ValidationReport + Independent validation of the closed replay workspace. + + """ + + reference: Path + workspace: Path + operation_count: int + conversation_ids: dict[str, str] + turn_uuids: dict[str, str] + differences: tuple[ReplayDifference, ...] + validation: ValidationReport + + +class ReplayError(RuntimeError): + """A reference command or resulting recording could not be reproduced. + + Attributes + ---------- + workspace: pathlib.Path + Requested destination; it may contain a partial replay. + sequence: int | None + Original operation start, if the failure occurred in a command. + completed_operations: int + Number of commands that completed their immediate checks. + differences: tuple[ReplayDifference, ...] + Differences detected up to the failure. + validation: ValidationReport | None + Final replay validation if it was reached. + + """ + + def __init__(self, workspace: Path, sequence: int | None, + completed_operations: int, message: str, + differences: tuple[ReplayDifference, ...] = (), + validation: ValidationReport | None = None) -> None: + """Retain failure context without hiding a partial workspace. + + Parameters + ---------- + workspace: pathlib.Path + Replay destination. + sequence: int | None + Original command sequence, if known. + completed_operations: int + Number of successfully checked commands. + message: str + Specific reason reproduction stopped. + differences: tuple[ReplayDifference, ...], optional + Recorded differences. Defaults to an empty tuple. + validation: ValidationReport | None, optional + Final replay validation, if available. Defaults to None. + + """ + self.workspace = workspace + self.sequence = sequence + self.completed_operations = completed_operations + self.differences = differences + self.validation = validation + where = f" at original sequence {sequence}" if sequence else "" + super().__init__(f"Replay failed{where}: {message}") + + +def _require(condition: bool, message: str) -> None: + """Enforce a replay outcome instead of silently changing its history. + + Parameters + ---------- + condition: bool + Required replay invariant. + message: str + Explanation on divergence. + + """ + if not condition: + raise ValueError(message) + + +def _destination(reference: Path, destination: str | Path | None) -> Path: + """Choose an absent sibling workspace without overwriting any path. + + Parameters + ---------- + reference: pathlib.Path + Resolved original workspace. + destination: str | pathlib.Path | None + Explicit sibling destination or the default replay name. + + Returns + ------- + pathlib.Path + New sibling path. The ordinary importer reserves it exclusively. + + """ + if destination is None: + name = reference.name.removesuffix("_original") + "_replay" + path = reference.with_name(name) + else: + if not str(destination).strip(): + raise ValueError("Choose a replay destination.") + path = Path(destination).expanduser() + if path.is_symlink(): + raise ValueError("Replay destination must not be a symbolic link.") + path = path.resolve() + if path == reference or path.parent != reference.parent: + raise ValueError("Replay must be a separate sibling workspace.") + if path.exists() or path.is_symlink(): + raise FileExistsError(f"Replay destination already exists: {path}") + if not path.parent.is_dir(): + raise ValueError("Replay destination parent does not exist.") + return path + + +def _current_request(defaults: dict, requested: dict, + overrides: dict) -> dict: + """Reproduce the submitted form's shape with current inherited values. + + Parameters + ---------- + defaults: dict + Current full settings form. + requested: dict + Historical submitted form, including its partial backend mappings. + overrides: dict + Historical explicit fields; lists are atomic settings. + + Returns + ------- + dict + Current values for the submitted fields and recorded overrides. + + Notes + ----- + Displayed defaults contain fields never submitted by the frontend. + Do not write those fields, or inactive backend settings, merely because + they appeared in the defaults snapshot. + + """ + result = {} + for key, value in requested.items(): + if isinstance(value, dict) and isinstance(defaults.get(key), dict): + result[key] = _current_request( + defaults[key], value, overrides.get(key, {}) + ) + elif key in overrides: + result[key] = deepcopy(overrides[key]) + else: + _require(key in defaults, f"Inherited setting unavailable: {key}") + result[key] = deepcopy(defaults[key]) + return result + + +def _differences(sequence: int, field: str, original: object, + replayed: object) -> list[ReplayDifference]: + """Compare JSON-compatible configuration without model judgment. + + Parameters + ---------- + sequence: int + Original operation start. + field: str + Current dotted setting name. + original: object + Recorded original value. + replayed: object + Observed replay value. + + Returns + ------- + list[ReplayDifference] + Changed fields; lists remain atomic, as in settings provenance. + + """ + if isinstance(original, dict) and isinstance(replayed, dict): + changes = [] + for key in sorted(original.keys() | replayed.keys()): + name = f"{field}.{key}" + if key not in original or key not in replayed: + changes.append(ReplayDifference( + sequence, name, original.get(key), replayed.get(key) + )) + else: + changes.extend(_differences( + sequence, name, original[key], replayed[key] + )) + return changes + if original != replayed or type(original) is not type(replayed): + return [ReplayDifference(sequence, field, original, replayed)] + return [] + + +def _configuration_differences( + original: tuple[TimelineOperation, ...], + reproduced: tuple[TimelineOperation, ...], +) -> list[ReplayDifference]: + """Compare actual effective settings at matching command boundaries. + + Parameters + ---------- + original: tuple[TimelineOperation, ...] + Reference operations. + reproduced: tuple[TimelineOperation, ...] + Complete or partial replay operations in command order. + + Returns + ------- + list[ReplayDifference] + Observed setting changes for the unambiguous common prefix. + + """ + changes = [] + for before, after in zip(original, reproduced): + if before.kind != after.kind: + break + for event_type, field in ( + ("gui.project.configuration.effective", "configuration"), + ("gui.question.settings.resolved", "question.resolved"), + ("turn.settings.snapshot", "question.effective"), + ): + old, new = before.matching(event_type), after.matching(event_type) + if len(old) != 1 or len(new) != 1: + continue + first, second = deepcopy(old[0].details), deepcopy(new[0].details) + # The workspace is intentionally relocated. Its absolute source + # path and the behavior editor's project ID are not settings. + if event_type == "gui.project.configuration.effective": + for values in (first, second): + values.pop("plugins", None) + if isinstance(values.get("behavior"), dict): + values["behavior"].pop("project", None) + elif event_type == "turn.settings.snapshot": + for values in (first, second): + values.pop("source", None) + values.pop("project_type_plugin", None) + changes.extend(_differences(before.start_sequence, field, + first, second)) + return changes + + +def _plugin_differences( + original: tuple[TimelineOperation, ...], + reproduced: tuple[TimelineOperation, ...], +) -> list[ReplayDifference]: + """Report observed identity changes separately from setting changes. + + Parameters + ---------- + original: tuple[TimelineOperation, ...] + Reference operations. + reproduced: tuple[TimelineOperation, ...] + Complete or partial replay operations in command order. + + Returns + ------- + list[ReplayDifference] + Known differences in the common command prefix. Unavailable + identities are not inferred differences; comparison reports retain + their explicit unknown status. + + """ + + changes = [] + for before, after in zip(original, reproduced): + if before.kind != after.kind: + break + for pair in compare_plugins(before, after): + if pair["status"] == "changed": + field = ".".join(("plugins", pair["scope"], pair["kind"], + pair["name"])) + changes.extend(_differences( + before.start_sequence, field, + pair["original"]["identity"], + pair["replayed"]["identity"], + )) + return changes + + +def _semantic_differences( + original: tuple[TimelineOperation, ...], + reproduced: tuple[TimelineOperation, ...], +) -> list[ReplayDifference]: + """Report independently recorded source-organization observations. + + Parameters + ---------- + original: tuple of TimelineOperation + Reference operations. + reproduced: tuple of TimelineOperation + Complete or partial replay history. + + Returns + ------- + list of ReplayDifference + Comparable differences in the common chronological prefix. + + """ + changes = [] + for before, after in zip(original, reproduced): + if before.kind != after.kind: + break + for pair in compare_semantics(before, after): + if pair["equal"] is False: + field = (f"source_organization.{pair['event_type']}." + f"{pair['occurrence']}") + changes.extend(_differences( + before.start_sequence, field, + pair["original"]["value"], pair["replayed"]["value"], + )) + return changes + + +class _Runner: + """Coordinate one replay, using the same synchronous engine as the GUI.""" + + def __init__(self, workspace: Path, + operations: tuple[TimelineOperation, ...], + sources: SourceReplay) -> None: + """Create an idle headless command coordinator. + + Parameters + ---------- + workspace: pathlib.Path + New sibling replay destination. + operations: tuple[TimelineOperation, ...] + Validated operation history. + sources: SourceReplay + Preflighted additive source input plans. + + """ + # Import the engine only for execution, not reference inspection. + from kilin.gui.engine import ChatEngine + + self.workspace = workspace + self.operations = operations + self.sources = sources + self.interactions = InteractionReplay() + self.conversations: dict[str, str] = {} + self.turns: dict[str, str] = {} + self.differences: list[ReplayDifference] = [] + self.completed = 0 + self.sequence: int | None = None + self.events: set[str] = set() + self.error: str | None = None + self.semantic_reply: dict | None = None + self.semantic_previews: dict[str, str] = {} + self.engine = ChatEngine(workspace.parent, self._observe, + trace_enabled=True, + read_command=self.interactions.read_command) + + def _observe(self, event: dict) -> None: + """Consume acknowledgements without retaining token streams. + + Parameters + ---------- + event: dict + Synchronous engine event, including its prompt or error payload. + + """ + self.interactions.observe(event) + kind = event["event"] + self.events.add(kind) + if kind == "source_organization": + self.semantic_reply = event + if self.error is None and ( + kind in ("error", "workspace_conflict", "backend_failed", + "answer_cancelled", "memory_sync_failed") + or kind in ("message_feedback", "memory_exclusion", + "memory_status") and event.get("error") + or kind in ("source_organization", + "source_organization_lifecycle") and any( + event.get(key) for key in ( + "error", "trace_error", "refresh_error")) + ): + self.error = str(event.get("error") or event.get("message") + or kind) + + def _call(self, method: Callable, *args: object, + expected: str | None = None, **kwargs: object) -> None: + """Invoke a command and check errors caught by the engine itself. + + Parameters + ---------- + method: Callable + Ordinary synchronous engine command. + *args: object + Positional command arguments. + expected: str | None, optional + Required successful acknowledgement. None if no such event is + defined. Defaults to None. + **kwargs: object + Keyword command arguments. + + """ + self.events.clear() + self.error = None + self.semantic_reply = None + method(*args, **kwargs) + _require(self.error is None, self.error or "Engine command failed.") + _require(expected is None or expected in self.events, + f"Missing success acknowledgement: {expected}") + + def _active(self) -> str: + """Return the live replay conversation identity.""" + item = self.engine.active_conversation + _require(item is not None and self.engine.session is not None, + "Replay has no active conversation.") + return item.conversation_id + + def _catalog(self) -> dict: + """Read the active replay store, including unused empty chats.""" + _require(self.engine.conversation_store is not None, + "Replay has no conversation store.") + return {item.conversation_id: item for item in + self.engine.conversation_store.conversations()} + + def _ids(self) -> list[str]: + """Return the currently loaded committed turn identities.""" + self._active() + return [turn.conversation_turn_uuid for turn in + self.engine.session.turns] + + def _register(self, original: str, actual: str) -> None: + """Register a newly allocated conversation without reusing identity. + + Parameters + ---------- + original: str + Reference conversation ID. + actual: str + Independently allocated replay conversation ID. + + """ + _require(original not in self.conversations and + actual not in self.conversations.values(), + "Conversation identity reused unexpectedly.") + self.conversations[original] = actual + + def _check_active(self, original: str) -> None: + """Require the recorded conversation to be active via its new ID. + + Parameters + ---------- + original: str + Original active conversation ID. + + """ + _require(self._active() == self.conversations[original], + "Active conversation differs from recorded transition.") + + def _create(self, op: TimelineOperation) -> None: + """Open a new workspace with current defaults and explicit overrides. + + Parameters + ---------- + op: TimelineOperation + Original creation with source outcomes and settings provenance. + + """ + request = op.request + type_id = request["source_batch"]["type_id"] + provenance = request["settings"] + explicit = provenance["explicit_settings"] + if provenance["provenance"] == "displayed_defaults": + # The existing blank-workspace settings command can borrow + # saved preferences from a profile in the working directory. + # Do not let that silently change the inherited replay inputs. + _require(not (Path.cwd() / "profile.ini").is_file(), + "Run replay from a directory without profile.ini.") + # Reuse the same default form that the current frontend uses. + self._call(self.engine.settings, type_id, "", expected="settings") + defaults = self.engine._creation_defaults + _require(defaults is not None and defaults[0] == type_id, + "Current creation defaults are unavailable.") + settings = _current_request( + defaults[1], provenance["requested_settings"], explicit + ) + settings["_gui_full_snapshot"] = True + else: + settings = deepcopy(explicit) + source = self.sources.commands[op.start_sequence] + self._call(self.engine.open_project, source.sources, type_id, + str(self.workspace), selected_files=source.selections, + settings=settings, expected="opened") + _require(self.engine.session.project.root == self.workspace, + "Engine opened an unexpected workspace.") + active = self._active() + _require(set(self._catalog()) == {active} and not self._ids(), + "New replay did not start with one empty conversation.") + self._register(request["open"]["conversation_id"], active) + + def _open(self, op: TimelineOperation) -> None: + """Reopen using the original explicit or inherited selection policy. + + A validated relocation is reproduced as a normal resume with the + mapped active conversation, not as a physical filesystem rename. + + Parameters + ---------- + op: TimelineOperation + Recorded resume operation. + + """ + selected = op.request["requested_conversation_id"] + self._call(self.engine.resume_project, str(self.workspace), + self.conversations[selected] if selected else None, + expected="opened") + self._check_active(op.request["conversation_id"]) + if "relocation" in op.request: + self.differences.append(ReplayDifference( + op.start_sequence, "project.relocation", + op.request["relocation"], + {"directory": str(self.workspace), + "policy": "retain_destination_directory"}, + )) + + def _ask(self, op: TimelineOperation) -> None: + """Reissue a question and map its newly committed turn. + + Parameters + ---------- + op: TimelineOperation + Original question, settings provenance and interaction history. + + """ + request = op.request + self._check_active(request["conversation_id"]) + before = self._ids() + explicit = request["explicit_generation_settings"] + if request["generation_provenance"] == "profile_difference": + profile = self.engine.session.project.profile + settings = {key: getattr(profile, key) for key in + request["generation_settings"]} + settings.update(explicit) + settings["_title_question"] = request["title_question"] + else: + settings = deepcopy(explicit) + self.interactions.begin(op) + try: + self._call(self.engine.ask, request["question"], + retrieval_count=request["retrieval_count"], + generation_settings=settings, + effort=deepcopy(request["effort"]), expected="answered") + self.interactions.finish() + finally: + self.differences.extend(ReplayDifference( + op.start_sequence, field, old, new + ) for field, old, new in self.interactions.differences) + self._check_active(request["conversation_id"]) + after = self._ids() + _require(len(after) == len(before) + 1 and after[:-1] == before, + "Question did not commit exactly one new turn.") + expected = one(op.events, "gui.question.saved").details + original = expected["conversation_turn_uuid"] + _require(len(after) == expected["turn_count"] and + original not in self.turns and + after[-1] not in self.turns.values() and + self.engine.session.turns[-1].question == + request["question"].strip(), + "Committed question or turn identity differs from history.") + self.turns[original] = after[-1] + + def _create_conversation(self, op: TimelineOperation) -> None: + """Reproduce a new chat, empty-chat reuse, branch or reset. + + Parameters + ---------- + op: TimelineOperation + Recorded conversation creation or reset operation. + + """ + request = op.request + self._check_active(request["previous_conversation_id"]) + previous = self._active() + before = set(self._catalog()) + inherited = [] + if op.kind == "reset_conversation": + result = one(op.events, "gui.conversation.reset.result").details + self._call(self.engine.reset, expected="reset") + else: + result = one(op.events, "gui.conversation.create.result").details + if request["branch"]: + inherited = self._ids()[:request["turn_count"]] + self._call(self.engine.create_conversation, + branch=request["branch"], + turn_count=request["turn_count"], + expected="conversation_opened") + active = self._active() + after = self._catalog() + original = result["conversation_id"] + if result.get("reused"): + self._check_active(original) + _require(set(after) == before, "Empty-chat reuse created a chat.") + else: + _require(set(after) == before | {active} and active not in before, + "Conversation creation did not allocate one new chat.") + self._register(original, active) + parent = previous if request.get("branch") else None + _require(after[active].parent_conversation_id == parent and + self._ids() == inherited, + "Conversation did not inherit the recorded turn prefix.") + + def _delete(self, op: TimelineOperation) -> None: + """Archive a mapped chat and check the actual replacement policy. + + Parameters + ---------- + op: TimelineOperation + Recorded deletion, archive, and replacement metadata. + + """ + target = self.conversations[op.request["conversation_id"]] + before = set(self._catalog()) + result = one(op.events, "gui.conversation.deleted").details + _require((target == self._active()) == result["deleted_active"], + "Deletion targets a different active conversation.") + self._call(self.engine.delete_conversation, target) + active = self._active() + expected = before - {target} + original = result["replacement"]["conversation_id"] + if result["replacement_created"]: + _require(active not in before, "No new deletion replacement.") + self._register(original, active) + expected.add(active) + self._check_active(original) + _require(set(self._catalog()) == expected, + "Deletion changed the conversation catalog unexpectedly.") + + def _feedback(self, op: TimelineOperation) -> None: + """Replay message feedback using the new UUID and current revision. + + Parameters + ---------- + op: TimelineOperation + Feedback or exclusion mutation with its committed result. + + """ + request = op.request + store = FeedbackStore(self.workspace) + data = {"project": str(self.workspace), + "conversation_id": self.conversations[ + request["conversation_id"]], + "turn_uuid": self.turns[request["turn_uuid"]], + "role": request["role"], "revision": store.load().revision, + "request_id": op.start_sequence} + if op.kind == "feedback": + data.update(saved=request["saved"], reaction=request["reaction"]) + self._call(self.engine.save_message_feedback, data, + expected="message_feedback") + event_type = "gui.conversation.feedback.saved" + else: + data["excluded"] = request["excluded"] + self._call(self.engine.set_memory_exclusion, data, + expected="memory_exclusion") + event_type = "gui.conversation.memory_exclusion.saved" + rating = store.load().get(data["turn_uuid"], data["role"]) + recorded = one(op.events, event_type).details["rating"] + _require(asdict(rating) == recorded, + "Feedback mutation differs from the recorded result.") + + def _semantic_command(self, op: TimelineOperation) -> None: + """Reissue explicit semantic decisions using live engine identities. + + Parameters + ---------- + op: TimelineOperation + Validated reference command, including its original outcome. + + Notes + ----- + A preview binds to the independently reconstructed live state. The + historical digest and token are evidence, never reusable authority. + Current inherited defaults can differ; no historical result is + copied or forced into the replay manifest. + + """ + from kilin.source_manifest import read_source_manifest + + self._active() + request = deepcopy(op.request) + operation = request["operation"] + request["project"] = str(self.workspace) + if operation == "preview": + snapshot = read_source_manifest(self.engine.session.project) + request.update(revision=snapshot.manifest.revision, + sha256=snapshot.sha256) + self.semantic_previews.clear() + elif operation == "apply": + request["preview_id"] = self.semantic_previews.pop( + request["preview_id"]) + self.semantic_previews.clear() + elif operation != "inspect": + self.semantic_previews.clear() + self._call(self.engine.source_organization, request, + expected="source_organization") + result = self.semantic_reply + _require(result is not None and result.get("operation") == operation + and result.get("project") == str(self.workspace) and + result.get("request_id") == request["request_id"], + "Missing or unrelated semantic command acknowledgement.") + if operation == "preview": + token = result.get("preview_id") + _require(isinstance(token, str) and bool(token), + "Replay did not produce a semantic preview.") + original = op.events[-1].details["preview_id"] + self.semantic_previews[original] = token + + def _execute(self, op: TimelineOperation) -> None: + """Dispatch one validated operation without executing recorded code. + + Parameters + ---------- + op: TimelineOperation + Next chronological reference command. + + """ + kind, request = op.kind, op.request + if kind in ("create_project", "open_project", "close_project", + "sync_sources") or (kind == "add_sources" and + op.matching("workspace.prepare.started", + "workspace.sync.started")): + self.semantic_previews.clear() + if kind == "create_project": + self._create(op) + elif kind == "open_project": + self._open(op) + elif kind == "close_project": + self._check_active(request["conversation_id"]) + self._call(self.engine.close) + _require(self.engine.session is None, "Project did not close.") + elif kind == "ask": + self._ask(op) + elif kind in ("add_sources", "sync_sources"): + command = self.sources.commands[op.start_sequence] + if kind == "add_sources": + self._call(self.engine.add_project_sources, command.sources, + decisions=command.decisions, + selected_files=command.selections or None, + expected="opened") + else: + self._call(self.engine.sync_sources, command.decisions, + expected="opened") + elif kind in ("create_conversation", "reset_conversation"): + self._create_conversation(op) + elif kind == "select_conversation": + self._call(self.engine.select_conversation, + self.conversations[request["conversation_id"]]) + self._check_active(request["conversation_id"]) + elif kind == "rename_conversation": + target = self.conversations[request["conversation_id"]] + self._call(self.engine.rename_conversation, target, + request["name"], + expected="conversations") + name = one(op.events, "gui.conversation.renamed").details["name"] + _require(self._catalog()[target].name == name, + "Explicit conversation name differs from recording.") + elif kind == "delete_conversation": + self._delete(op) + elif kind in ("feedback", "memory_exclusion"): + self._feedback(op) + elif kind == "sync_memory": + self._call(self.engine.sync_memory_index, str(self.workspace), + expected="memory_synced") + elif kind == "source_organization": + self._semantic_command(op) + elif kind == "regenerate_source_cards": + self._call(self.engine.regenerate_source_cards, + expected="source_cards_regenerated") + else: + raise ValueError(f"Unsupported replay operation: {kind}") + self.sources.verify(self.workspace, op) + command = self.sources.commands.get(op.start_sequence) + if command is not None: + self.differences.extend(ReplayDifference( + op.start_sequence, "source.unretained_request", item, None + ) for item in command.omitted) + for restored in op.matching("conversation.restored"): + expected = [self.turns[uid] for uid in + restored.details["turn_uuids"]] + _require(self._ids() == expected, + "Restored replay history differs from mapped turns.") + + def run(self, progress: ProgressCallback | None) -> None: + """Execute the chronological operations, stopping at first failure. + + Parameters + ---------- + progress: ProgressCallback | None + Optional callback before each command (one-based index, total, + original operation). No callback when None. + + """ + total = len(self.operations) + try: + for i, op in enumerate(self.operations, 1): + self.sequence = op.start_sequence + if progress is not None: + progress(i, total, op) + self._execute(op) + self.completed += 1 + except BaseException as error: + # Never delete a partial replay or let a secondary close failure + # obscure the operation that first diverged. + try: + self.engine.close() + except BaseException as cleanup: + error.add_note(f"Replay cleanup also failed: {cleanup!r}") + raise + else: + self.engine.close() + + +def replay(experiment: Experiment, destination: str | Path | None = None, + *, progress: ProgressCallback | None = None) -> ReplayResult: + """Replay a closed reference into one independently created workspace. + + Parameters + ---------- + experiment: Experiment + Original reference, validated before any model or destination opens. + destination: str | pathlib.Path | None, optional + Absent sibling directory. Defaults to replacing a trailing + ``_original`` with ``_replay``, or appending ``_replay`` otherwise. + progress: ProgressCallback | None, optional + Called before each operation with its one-based index, total count, + and original TimelineOperation. Defaults to None. + + Returns + ------- + ReplayResult + Closed, independently validated replay and identity mappings. + + Raises + ------ + InvalidRecordingError + If the original cannot be validated. + FileExistsError + If the requested replay destination already exists. + ValueError + If the destination is not a separate sibling. + ReplayError + If replay inputs, command outcomes, or final validation diverge. + + Notes + ----- + Uses current defaults for inherited settings and recorded explicit + overrides for user settings. Only live matching user decisions are + supplied. Models and explicitly approved network actions run normally; + the original answers, outputs, templates and indexes are not copied. + The original must remain closed and unchanged throughout replay. + + """ + root = experiment.workspace + target = _destination(root, destination) + report = experiment.validate() + report.raise_for_errors() + operations = report.operations + try: + preflight_plugins(operations) + sources = SourceReplay(root, operations) + runner = _Runner(target, operations, sources) + except Exception as error: + raise ReplayError(target, None, 0, str(error)) from error + try: + runner.run(progress) + except Exception as error: + # Read partial diagnostics only when the replay actually exists. + # They are evidence, not permission to resume or overwrite it. + if target.is_dir(): + try: + partial = build_timeline(read_recording(target)) + runner.differences.extend(_configuration_differences( + operations, partial + )) + runner.differences.extend(_plugin_differences( + operations, partial + )) + runner.differences.extend(_semantic_differences( + operations, partial + )) + except Exception as inspection: + error.add_note(f"Partial inspection failed: {inspection!r}") + raise ReplayError(target, runner.sequence, runner.completed, + str(error), tuple(runner.differences)) from error + from .experiment import Experiment + + validation = Experiment(target).validate() + runner.differences.extend(_configuration_differences( + operations, validation.operations + )) + runner.differences.extend(_plugin_differences( + operations, validation.operations + )) + runner.differences.extend(_semantic_differences( + operations, validation.operations + )) + if (not validation.valid or [op.kind for op in validation.operations] != + [op.kind for op in operations]): + message = (validation.issues[0].message if validation.issues else + "Replay command sequence differs from reference.") + raise ReplayError(target, None, runner.completed, message, + tuple(runner.differences), validation) + return ReplayResult(root, target, runner.completed, + dict(runner.conversations), dict(runner.turns), + tuple(runner.differences), validation) diff --git a/kilin/system_testing/replay_management.py b/kilin/system_testing/replay_management.py new file mode 100644 index 00000000..baaeddf4 --- /dev/null +++ b/kilin/system_testing/replay_management.py @@ -0,0 +1,383 @@ +"""Manage complete fresh replays without replacing reference recordings. + +Key Features +------------ +- Keep, archive or reject an existing replay through an explicit policy. +- Preserve old replays and partial failures without copy-and-delete fallback. +- Record actual replay execution provenance separately from project traces. + +Module Structure +---------------- +- ``ManagedReplay`` reports the requested action and any resulting error. +- ``run_replay`` applies the lifecycle policy around ordinary replay. +- ``execution_provenance`` reads the optional historical execution receipt. + +Examples +-------- +>>> from kilin.system_testing import Experiment +>>> # Experiment("workspaces/010_original").run_replay( +>>> # existing_replay="archive") + +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime, timezone +from hashlib import sha256 +import json +import os +from pathlib import Path +import platform +import subprocess +from tempfile import NamedTemporaryFile, mkdtemp +from typing import Final, TYPE_CHECKING + +import kilin + +from ._plugin_provenance import preflight_plugins +from .reference import _prefix_digest +from .replay import ProgressCallback, ReplayError, ReplayResult +from .traces import read_json, safe_path +from .validation import ValidationReport + +if TYPE_CHECKING: + from .experiment import Experiment + +__all__ = [ + "ManagedReplay", "run_replay", "execution_provenance", + "REPLAY_RECEIPT_FORMAT_VERSION", +] + +REPLAY_RECEIPT_FORMAT_VERSION: Final[int] = 1 + +_RECEIPT = "logs/system_testing_execution.json" + + +@dataclass(frozen=True, slots=True) +class ManagedReplay: + """One managed replay action, with preservation and provenance details. + + Attributes + ---------- + workspace: pathlib.Path + Designated sibling replay workspace. + status: str + ``completed``, ``retained`` or ``error``. + archived_workspace: pathlib.Path or None + Preserved previous replay, if moved. + result: ReplayResult or None + Successful new replay, never fabricated for a retained recording. + error: str or None + Actual failed action, if any. + provenance: dict + Execution receipt or explicit unavailable/error information. + completed_operations: int or None + Reproduced commands, if established by the actual execution. + sequence: int or None + Original command at a replay failure, if known. + + """ + + workspace: Path + status: str + archived_workspace: Path | None + result: ReplayResult | None + error: str | None + provenance: dict + completed_operations: int | None = None + sequence: int | None = None + + +def _environment() -> dict: + """Identify the executing code and runtime, without guessing a revision.""" + source = Path(kilin.__file__).resolve().parent + digest = sha256() + # Include package resources as well as Python modules. A checkout hash + # alone cannot identify uncommitted code or modified packaged defaults. + for path in sorted(source.rglob("*")): + if (not path.is_file() or "__pycache__" in path.parts or + path.suffix in (".pyc", ".pyo") or path.name == ".DS_Store"): + continue + digest.update(path.relative_to(source).as_posix().encode("utf-8")) + digest.update(b"\0") + digest.update(sha256(path.read_bytes()).digest()) + result = {"kilin_version": kilin.__version__, + "package_sha256": digest.hexdigest(), + "python": platform.python_version(), + "platform": platform.platform(), "machine": platform.machine(), + "git_revision": None, "git_dirty": None} + # A wheel installed inside some unrelated Git project is not its source. + parent = source.parent + if (parent / ".git").exists() and (parent / "pyproject.toml").is_file(): + try: + command = ["git", "-C", str(parent)] + result["git_revision"] = subprocess.check_output( + command + ["rev-parse", "HEAD"], text=True, + stderr=subprocess.DEVNULL, timeout=5).strip() + result["git_dirty"] = bool(subprocess.check_output( + command + ["status", "--porcelain", "--", "kilin"], + text=True, stderr=subprocess.DEVNULL, timeout=5).strip()) + except (OSError, subprocess.SubprocessError): + pass + return result + + +def _fingerprint(report: ValidationReport) -> dict: + """Identify the exact validated command/event prefix of a recording. + + Parameters + ---------- + report: ValidationReport + Closed recording snapshot. + + """ + report.raise_for_errors() + return {"event_count": report.event_count, + "operation_count": len(report.operations), + "prefix_sha256": _prefix_digest(report.events, + report.event_count)} + + +def _archive(destination: Path, directory: Path) -> Path: + """Move a previous replay into a reserved, separate archive directory. + + Parameters + ---------- + destination: pathlib.Path + Existing regular workspace with a ``_replay`` suffix. + directory: pathlib.Path + Archive root outside the workspace discovery directory. + + """ + if (not destination.name.endswith("_replay") or + destination.is_symlink() or not destination.is_dir()): + raise ValueError(f"Expected a real replay directory: {destination}") + if (directory.is_symlink() or + (directory.exists() and not directory.is_dir())): + raise ValueError(f"Nonregular replay archive: {directory}") + directory = directory.resolve() + if (directory.is_relative_to(destination.parent) or + destination.parent.is_relative_to(directory)): + raise ValueError("Replay archive must be separate from workspaces.") + directory.mkdir(parents=True, exist_ok=True) + folder = Path(mkdtemp(prefix=destination.name + "-", dir=directory)) + target = folder / destination.name + try: + destination.rename(target) + except OSError: + folder.rmdir() + raise + return target + + +def _write_receipt(workspace: Path, data: dict) -> None: + """Publish provenance exclusively after a successfully closed replay. + + Parameters + ---------- + workspace: pathlib.Path + Newly generated replay workspace. + data: dict + Execution provenance bound to its validated event prefix. + + """ + target = safe_path(workspace, _RECEIPT) + temporary = None + try: + with NamedTemporaryFile(mode="w", encoding="utf-8", delete=False, + dir=target.parent) as stream: + temporary = Path(stream.name) + json.dump(data, stream, ensure_ascii=False, allow_nan=False, + indent=2) + stream.write("\n") + os.link(temporary, target) + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + + +def execution_provenance(workspace: Path, report: ValidationReport) -> dict: + """Read an optional historical replay receipt and verify its trace prefix. + + Parameters + ---------- + workspace: pathlib.Path + Closed replay workspace. + report: ValidationReport + Fresh validation of this workspace. + + Returns + ------- + dict + Recorded execution with verified prefix, or explicit unavailable, + unverified, changed or error status. Missing older receipts are + never replaced with information about the inspection environment. + + """ + workspace = Path(workspace) + try: + path = safe_path(workspace, _RECEIPT) + if not path.exists(): + return {"status": "unavailable"} + data = read_json(workspace, _RECEIPT) + if (type(data["format_version"]) is not int or + data["format_version"] != REPLAY_RECEIPT_FORMAT_VERSION or + data["status"] != "completed"): + raise ValueError("Invalid execution receipt format.") + if report.workspace != workspace.resolve(): + raise ValueError("Validation describes another workspace.") + prefix = data["replayed"] + count = prefix["event_count"] + operations = prefix["operation_count"] + if (type(count) is not int or count < 1 or + type(operations) is not int or operations < 1): + raise ValueError("Invalid replay prefix counts.") + if not report.valid: + return {"status": "not_validated", "recorded": data} + if (count > report.event_count or + _prefix_digest(report.events, count) != prefix["prefix_sha256"] + or operations > len(report.operations) or + report.operations[operations - 1].kind != "close_project" or + report.operations[operations - 1].end_sequence > count or + (operations < len(report.operations) and + report.operations[operations].start_sequence <= count)): + return {"status": "changed", "recorded": data} + return {"status": "recorded", "recorded": data, + "additional_events": report.event_count - count} + except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: + return {"status": "error", "message": str(error)} + + +def reference_execution_match(provenance: dict, + report: ValidationReport) -> str: + """Compare a recorded replay input to the current reference prefix. + + Parameters + ---------- + provenance: dict + Independently verified execution receipt observation. + report: ValidationReport + Current reference recording, which may have been extended. + + """ + if provenance.get("status") != "recorded" or not report.valid: + return "unavailable" + try: + prefix = provenance["recorded"]["reference"] + count, operations = prefix["event_count"], prefix["operation_count"] + if (type(count) is not int or count < 1 or + type(operations) is not int or operations < 1): + return "error" + if (count > report.event_count or operations > len(report.operations) + or report.operations[operations - 1].kind != "close_project" + or report.operations[operations - 1].end_sequence > count or + (operations < len(report.operations) and + report.operations[operations].start_sequence <= count) or + _prefix_digest(report.events, count) != + prefix["prefix_sha256"]): + return "changed" + if (count == report.event_count and + operations == len(report.operations)): + return "exact" + return "prefix" + except (ValueError, KeyError, TypeError, AttributeError): + return "error" + + +def run_replay(experiment: Experiment, destination: str | Path | None = None, + *, existing_replay: str = "retain", + archive_directory: str | Path | None = None, + progress: ProgressCallback | None = None) -> ManagedReplay: + """Apply an explicit existing-replay policy and record actual execution. + + Parameters + ---------- + experiment: Experiment + Closed original workspace; validated before any archive or replay. + destination: str or pathlib.Path or None, optional + Separate sibling replay directory. Defaults to the usual suffix. + existing_replay: str, optional + ``retain`` (default), ``archive`` or ``error``. Archiving preserves + the old workspace even if execution of the new replay fails. + archive_directory: str or pathlib.Path or None, optional + Archive root separate from workspace discovery. Defaults to + ``_replay_archive`` beside the workspace discovery directory. + progress: ProgressCallback or None, optional + Forwarded to ordinary replay when a fresh execution is requested. + + Returns + ------- + ManagedReplay + Action outcome, optional archived path, replay result and provenance. + Operational failures are represented explicitly; invalid policy or + destination arguments raise ValueError. + + Notes + ----- + The original and replay must be closed and have no concurrent writers. + The low-level ``Experiment.replay`` still requires an absent destination. + A failed replay remains available. Only a successful fresh replay is + given a persistent execution receipt; failed attempts retain their + actual execution context in the returned action record. + + """ + from .comparison import _replay_path + + if existing_replay not in ("retain", "archive", "error"): + raise ValueError( + "Choose retain, archive, or error for existing replay.") + target = _replay_path(experiment.workspace, destination) + archived = None + provenance = {"status": "not_executed"} + completed = sequence = None + try: + report = experiment.validate() + report.raise_for_errors() + if target.exists(): + if existing_replay == "error": + raise FileExistsError(f"Replay already exists: {target}") + if existing_replay == "retain": + from .experiment import Experiment + + retained = Experiment(target).validate() + return ManagedReplay(target, "retained", None, None, None, + execution_provenance(target, retained)) + # Do not move an existing replay until plugin eligibility has + # been established. Retaining a recording needs no live catalog. + try: + plugins = preflight_plugins(report.operations) + except Exception as error: + raise ReplayError(target, None, 0, str(error)) from error + provenance = {"format_version": REPLAY_RECEIPT_FORMAT_VERSION, + "status": "running", + "reference": _fingerprint(report), + "environment": {**_environment(), "plugins": plugins}, + "started_at_utc": datetime.now(timezone.utc).isoformat()} + if target.exists(): + directory = (Path(archive_directory).expanduser() if + archive_directory is not None else + target.parent.parent / "_replay_archive") + archived = _archive(target, directory) + result = experiment.replay(target, progress=progress) + completed = result.operation_count + provenance.update(status="completed", replayed=_fingerprint( + result.validation), finished_at_utc=datetime.now( + timezone.utc).isoformat()) + try: + _write_receipt(target, provenance) + except (OSError, ValueError, TypeError) as error: + return ManagedReplay(target, "completed", archived, result, None, + {"status": "error", "message": str(error), + "recorded": provenance}, completed) + return ManagedReplay(target, "completed", archived, result, None, + {"status": "recorded", "recorded": provenance, + "additional_events": 0}, completed) + except Exception as error: + if isinstance(error, ReplayError): + completed, sequence = error.completed_operations, error.sequence + if provenance["status"] == "running": + provenance.update(status="error", finished_at_utc=datetime.now( + timezone.utc).isoformat()) + return ManagedReplay(target, "error", archived, None, str(error), + provenance, completed, sequence) diff --git a/kilin/system_testing/timeline.py b/kilin/system_testing/timeline.py new file mode 100644 index 00000000..cad2ec6d --- /dev/null +++ b/kilin/system_testing/timeline.py @@ -0,0 +1,557 @@ +"""Reconstruct explicit user operations from project-wide event order. + +Key Features +------------ +- Group creation, source batches, and question spans without guessing inputs. +- Keep intermediate diagnostics with the operation that caused them. +- Detect ambiguous or overlapping command boundaries. + +Module Structure +---------------- +- ``TimelineOperation`` describes one command and its recorded diagnostics. +- ``build_timeline`` groups supported command boundaries in allocation order. + +Examples +-------- +>>> from kilin.system_testing import Experiment +>>> # Experiment(workspace).timeline() returns ordered command records. + +""" + +from __future__ import annotations + +from bisect import bisect_left, bisect_right +from dataclasses import dataclass, replace +from pathlib import PurePath, PurePosixPath, PureWindowsPath + +from .traces import Recording, TraceEvent + +__all__ = ["TimelineOperation", "build_timeline"] + +_SPANS = { + "gui.project.open": "open_project", + "gui.question.request": "ask", + "gui.conversation.create": "create_conversation", + "gui.conversation.select": "select_conversation", + "gui.conversation.rename": "rename_conversation", + "gui.conversation.delete": "delete_conversation", + "gui.conversation.reset": "reset_conversation", + "gui.conversation.feedback": "feedback", + "gui.conversation.memory_exclusion": "memory_exclusion", + "gui.conversation.memory.sync": "sync_memory", + "project.source_cards.regenerate": "regenerate_source_cards", +} +_PROJECT = "logs/traces/project.json" + + +@dataclass(frozen=True, slots=True) +class TimelineOperation: + """A recorded command with its request, outcome, and diagnostic context. + + Attributes + ---------- + kind: str + Stable operation name, independent of GUI event display labels. + start_sequence: int + First event allocated for this operation. + end_sequence: int + Last event at the operation's recorded boundary. + status: str + Completed, failed, incomplete, or committed_with_error. The last + status preserves a saved core turn despite a failed outer request. + request: dict + Recorded input, including provenance for creation and questions. + events: tuple[TraceEvent, ...] + All diagnostic events within the operation's sequence interval. + Intermediate model and indexing events are not separate commands. + + """ + + kind: str + start_sequence: int + end_sequence: int + status: str + request: dict + events: tuple[TraceEvent, ...] + + def matching(self, *event_types: str) -> tuple[TraceEvent, ...]: + """Return recorded events of the requested types in original order. + + Parameters + ---------- + *event_types: str + Exact original event types to select. + + Returns + ------- + tuple[TraceEvent, ...] + Matching diagnostics, including results and interaction records. + + """ + return tuple(e for e in self.events if e.event_type in event_types) + + +def one(events: tuple[TraceEvent, ...] | list[TraceEvent], + *types: str) -> TraceEvent: + """Require exactly one matching event rather than selecting arbitrarily. + + Parameters + ---------- + events: sequence of TraceEvent + Candidate events in an operation or recording. + *types: str + Alternative exact event types. + + Returns + ------- + TraceEvent + The sole matching event. + + """ + found = [event for event in events if event.event_type in types] + if len(found) != 1: + raise ValueError(f"Expected one of {types}, found {len(found)}.") + return found[0] + + +def _batch_end(recording: Recording, start: TraceEvent, + ends: dict[str, list[TraceEvent]]) -> TraceEvent | None: + """Find a terminal source event by its recorded batch ID. + + Parameters + ---------- + recording: Recording + Issue collector. + start: TraceEvent + Batch start. + ends: dict + Candidate terminal events by event type. + + Returns + ------- + TraceEvent | None + Unambiguous matching terminal, if recorded. + + """ + batch = start.details.get("batch_id") + found = [e for e in ends.get(start.event_type[:-8] + ".completed", []) + if e.details.get("batch_id") == batch] + if (not isinstance(batch, str) or not batch or len(found) != 1 + or found[0].sequence <= start.sequence): + recording.issue("batch.incomplete", "Missing or ambiguous batch end.", + start.path, start.sequence) + return None + return found[0] + + +def _historical_directory(value: object) -> PurePath: + """Interpret a recorded absolute directory without touching the disk. + + Parameters + ---------- + value: object + Recorded directory on the original operating system. + + Returns + ------- + pathlib.PurePath + Absolute, lexical path in its recorded platform's path syntax. + + """ + if not isinstance(value, str) or not value or "\x00" in value: + raise ValueError("Missing historical project directory.") + windows = PureWindowsPath(value) + path = windows if windows.drive else PurePosixPath(value) + if not path.is_absolute() or ".." in path.parts or not path.name: + raise ValueError("Invalid historical project directory.") + return path + + +def _opening_directory(op: TimelineOperation) -> PurePath: + """Read the absolute project identity from an opening's configuration. + + Parameters + ---------- + op: TimelineOperation + Project creation or reopening command. + + Returns + ------- + pathlib.PurePath + Historical directory, independent of the inspection machine. + + """ + config = one(op.events, "gui.project.configuration.effective").details + return _historical_directory(config["behavior"]["project"]) + + +def _relocations(recording: Recording, + operations: list[TimelineOperation]) -> None: + """Normalize proven folder moves into explicit close/open operations. + + Parameters + ---------- + recording: Recording + Snapshot receiving any ambiguous relocation issues. + operations: list[TimelineOperation] + Sorted candidate operations, updated in place with replay inputs. + + Notes + ----- + Require a matching request and completion for every internal reopen. + Corroborate their paths and conversation identity with independent + opening configurations, trace paths and close/open boundaries. + Persistent settings and source manifests are checked separately by + validation. Historical paths are never opened. + + """ + events = recording.events + markers = [e for e in events if e.event_type in ( + "gui.project.rename.requested", "gui.project.rename.completed")] + trace_starts = [e for e in events if e.event_type == + "conversation.trace.started"] + consumed = set() + identities = set() + previous_open = None + for i, op in enumerate(operations): + if op.kind not in ("create_project", "open_project"): + continue + if op.request.get("reason") != "internal_reopen": + previous_open = op + continue + try: + if (previous_open is None or i < 2 or op.status != "completed" + or operations[i - 1].kind != "close_project"): + raise ValueError("Internal reopen lacks a completed close.") + close = operations[i - 1] + active = op.request["conversation_id"] + if not active or close.request.get("conversation_id") != active: + raise ValueError("Relocation changed active conversation.") + source = _opening_directory(previous_open) + destination = _opening_directory(op) + if (type(source) is not type(destination) or source == destination + or source.parent != destination.parent): + raise ValueError("Internal reopen is not a sibling rename.") + gap = [e for e in events if close.end_sequence < e.sequence < + op.start_sequence] + if any(e.event_type not in ("trace.closed", "trace.started", + "conversation.trace.started", + "runtime.output") for e in gap): + raise ValueError("Unexpected operation during relocation.") + old_trace = next((e for e in reversed(trace_starts) + if e.sequence < close.start_sequence), None) + new_trace = one(gap, "conversation.trace.started") + for trace, directory in ((old_trace, source), + (new_trace, destination)): + if (trace is None or _historical_directory(trace.details.get( + "project_directory")) != directory or + trace.details["conversation"]["conversation_id"] != + active): + raise ValueError("Relocation trace identity differs.") + starts = [e for e in gap if e.event_type == "trace.started" + and e.details.get("scope") == "project"] + if (len(starts) != 1 or _historical_directory( + starts[0].details.get("output_path")) != + destination / "logs" / "traces" / "project.json"): + raise ValueError("Relocation project trace path differs.") + lower = operations[i - 2].end_sequence + upper = (operations[i + 1].start_sequence + if i + 1 < len(operations) else float("inf")) + # A following consecutive rename may already have requested + # its move before its close event. Match each marker by both + # type and its own boundary, not the entire intervening window. + relevant = [e for e in markers if e.sequence not in consumed + and ((e.event_type == "gui.project.rename.requested" + and lower < e.sequence < close.start_sequence) + or (e.event_type == + "gui.project.rename.completed" + and op.end_sequence < e.sequence < upper))] + request = one(relevant, "gui.project.rename.requested") + result = one(relevant, "gui.project.rename.completed") + identity = request.details.get("rename_id") + if (not isinstance(identity, str) or not identity or + identity in identities or + request.path != _PROJECT or result.path != _PROJECT or + not lower < request.sequence < close.start_sequence < + op.start_sequence <= op.end_sequence < + result.sequence < upper or + request.details != result.details or + request.details.get("conversation_id") != active or + _historical_directory(request.details.get( + "source_directory")) != source or + _historical_directory(request.details.get( + "destination_directory")) != destination): + raise ValueError("Uncorrelated project rename markers.") + consumed.update((request.sequence, result.sequence)) + identities.add(identity) + relocation = {"source_directory": str(source), + "destination_directory": str(destination), + "provenance": "recorded", "rename_id": identity} + operations[i] = replace(op, request={ + **op.request, "requested_conversation_id": active, + "relocation": relocation, + }) + except (ValueError, KeyError, TypeError, AttributeError) as error: + recording.issue("relocation.history", str(error), + sequence=op.start_sequence) + previous_open = op + for marker in markers: + if marker.sequence not in consumed: + recording.issue("relocation.history", "Unmatched rename marker.", + marker.path, marker.sequence) + + +def build_timeline(recording: Recording) -> tuple[TimelineOperation, ...]: + """Build supported command intervals from explicit recorded boundaries. + + Parameters + ---------- + recording: Recording + Ordered decoded events; receives grouping issues. + + Returns + ------- + tuple[TimelineOperation, ...] + Candidate chronological commands. A validator must check the recording + and these intervals before exposing them for replay. + + Notes + ----- + Initial import and first open constitute one creation command. Additional + source imports and sync batches inside an add command belong to that add. + A standalone synchronization ends after the GUI index refresh. Only + explicit recorded command boundaries establish replay operations; + arbitrary diagnostic events or direct core calls do not. + + """ + events = recording.events + sequences = [event.sequence for event in events] + by_type: dict[str, list[TraceEvent]] = {} + terminals: dict[tuple[str, str], list[TraceEvent]] = {} + for event in events: + by_type.setdefault(event.event_type, []).append(event) + if event.span_id: + terminals.setdefault((event.span_id, event.event_type), []).append( + event + ) + operations = [] + + def add(kind: str, start: TraceEvent, end: TraceEvent | None, + request: dict, status: str = "completed") -> None: + """Retain the sequence interval and all its recorded diagnostics. + + Parameters + ---------- + kind: str + Command kind. + start: TraceEvent + Opening boundary. + end: TraceEvent | None + Closing boundary, if present. + request: dict + Original command data. + status: str, optional + Recorded outcome. + + """ + last = end.sequence if end is not None else start.sequence + subset = tuple(events[bisect_left(sequences, start.sequence): + bisect_right(sequences, last)]) + if end is None: + status = "incomplete" + elif end.event_type.endswith(".failed"): + status = "failed" + if kind == "ask" and any( + e.event_type == "state.checkpoint.committed" for e in subset + ): + status = "committed_with_error" + operations.append(TimelineOperation( + kind, start.sequence, last, status, request, subset + )) + if status != "completed": + recording.issue("command." + status, + f"{kind}: {status.replace('_', ' ')}.", + start.path, start.sequence) + + create_batches = [e for e in by_type.get("workspace.prepare.started", []) + if e.details.get("operation") == "create"] + markers = by_type.get("gui.project.creation.settings", []) + for prefix, kind in _SPANS.items(): + for start in by_type.get(prefix + ".started", []): + ends = [e for suffix in (".completed", ".failed") + for e in terminals.get( + (start.span_id, prefix + suffix), []) + if e.path == start.path and e.sequence > start.sequence] + end = ends[0] if len(ends) == 1 else None + if ((kind == "ask" and start.path == _PROJECT) + or (kind != "ask" and start.path != _PROJECT)): + recording.issue("command.scope", "Command in wrong trace.", + start.path, start.sequence) + if kind == "open_project": + reason = start.details.get("reason") + if reason == "create": + if len(create_batches) != 1 or len(markers) != 1: + recording.issue("creation.missing", + "Ambiguous project creation.", + start.path, start.sequence) + add("create_project", start, end, start.details) + continue + batch, marker = create_batches[0], markers[0] + completed = _batch_end(recording, batch, by_type) + if (completed is None or not batch.sequence < + completed.sequence < marker.sequence < + start.sequence): + recording.issue("creation.order", + "Invalid creation event order.", + start.path, start.sequence) + add("create_project", batch, end, { + "source_batch": batch.details, + "settings": marker.details, + "open": start.details, + }) + continue + if reason not in ("resume", "internal_reopen"): + recording.issue("command.unsupported", + "Unknown project opening reason.", + start.path, start.sequence) + add(kind, start, end, start.details) + + # The add command has explicit request/completion diagnostics but no span. + pending = None + add_events = [e for e in events if e.event_type in ( + "gui.sources.add.requested", "gui.sources.add.completed", + "gui.sources.add.failed")] + for event in add_events: + if event.event_type.endswith(".requested"): + if pending is not None: + add("add_sources", pending, None, pending.details) + pending = event + elif pending is None: + recording.issue("command.orphan", "Source addition has no " + "request.", + event.path, event.sequence) + else: + add("add_sources", pending, event, pending.details) + pending = None + if pending is not None: + add("add_sources", pending, None, pending.details) + + # Semantic requests and outcomes are correlated by command identity, + # not by client request IDs (which can be reused by another editor). + prefix = "gui.source_organization." + semantic = {} + for event in events: + if not event.event_type.startswith(prefix): + continue + if event.event_type == prefix + "observed": + continue + suffix = event.event_type.removeprefix(prefix).split(".") + identifier = event.details.get("command_id") + if (len(suffix) != 2 or suffix[0] not in ( + "inspect", "preview", "apply", "initialize", "reconcile") + or suffix[1] not in ("requested", "completed", "failed") + or event.path != _PROJECT or not isinstance(identifier, str) + or not identifier): + recording.issue("command.scope", "Invalid semantic command.", + event.path, event.sequence) + continue + semantic.setdefault(identifier, []).append(event) + for group in semantic.values(): + start = group[0] + if (len(group) != 2 or not start.event_type.endswith(".requested") + or group[1].event_type.rsplit(".", 1)[0] != + start.event_type.rsplit(".", 1)[0] + or not group[1].event_type.endswith((".completed", ".failed")) + or start.metadata["trace_id"] != group[1].metadata["trace_id"] + or not isinstance(start.details.get("request"), dict)): + recording.issue("command.coverage", "Unpaired semantic command.", + start.path, start.sequence) + continue + add("source_organization", start, group[1], start.details["request"]) + + for start in by_type.get("workspace.sync.started", []): + end = _batch_end(recording, start, by_type) + if any(op.kind == "add_sources" and op.start_sequence < start.sequence + <= op.end_sequence for op in operations): + continue + # A subsequent refresh must follow this batch without crossing any + # other explicit command or source batch. Never borrow a later refresh. + next_bound = min((op.start_sequence for op in operations + if op.start_sequence > start.sequence), + default=float("inf")) + next_bound = min(next_bound, min((e.sequence for e in events + if e.sequence > start.sequence and e.event_type in ( + "workspace.prepare.started", + "workspace.sync.started", "gui.project.closed")), + default=float("inf"))) + refreshes = [e for e in by_type.get("gui.sources.refreshed", []) + if end is not None and end.sequence < e.sequence + < next_bound] + terminal = refreshes[0] if len(refreshes) == 1 else None + if terminal is not None: + opened = [e for e in by_type.get(prefix + "observed", []) + if terminal.sequence < e.sequence < next_bound + and e.details.get("reason") == "opened"] + if len(opened) == 1: + terminal = opened[0] + add("sync_sources", start, terminal, start.details) + for event in by_type.get("gui.project.closed", []): + add("close_project", event, event, event.details) + + operations.sort(key=lambda op: op.start_sequence) + _relocations(recording, operations) + previous = None + for op in operations: + if previous is not None and op.start_sequence <= previous.end_sequence: + recording.issue("command.overlap", "Overlapping user commands.", + sequence=op.start_sequence) + if previous is None or op.end_sequence > previous.end_sequence: + previous = op + # Known producer events must belong to reconstructed commands. + boundaries = { + "workspace.prepare.started": ("create_project", "add_sources"), + "workspace.prepare.completed": ("create_project", "add_sources"), + "workspace.source.copied": ("create_project", "add_sources"), + "workspace.sync.started": ("add_sources", "sync_sources"), + "workspace.sync.completed": ("add_sources", "sync_sources"), + "workspace.sync.file": ("add_sources", "sync_sources"), + "workspace.sync.detached": ("add_sources", "sync_sources"), + "gui.sources.refreshed": ("add_sources", "sync_sources"), + "gui.project.creation.settings": ("create_project",), + "gui.project.open.started": ("create_project", "open_project"), + "gui.conversation.catalog.opened": ("create_project", "open_project"), + "turn.started": ("ask",), + "state.checkpoint.committed": ("ask",), + "gui.question.saved": ("ask",), + } + # Some GUI failures precede the core span, or occur during notification + # after it. They still make the reference unsuitable for exact replay. + failures = { + "gui.question.failed", "gui.answer.cancelled", + "gui.project.prepare.failed", "gui.project.resume.failed", + "gui.project.rename.failed", "gui.indexing.change.failed", + "gui.sources.sync.failed", "gui.source_cards.regenerate.failed", + "gui.conversation_create.failed", "gui.conversation_select.failed", + "gui.conversation_rename.failed", "gui.conversation_delete.failed", + "gui.conversation_reset.failed", "gui.command.failed", + } + cursor = 0 + for event in events: + while (cursor < len(operations) and operations[cursor].end_sequence + < event.sequence): + cursor += 1 + op = (operations[cursor] if cursor < len(operations) and + operations[cursor].start_sequence <= event.sequence else None) + allowed = boundaries.get(event.event_type) + if allowed is not None and (op is None or op.kind not in allowed): + recording.issue("command.orphan", f"Orphan {event.event_type}.", + event.path, event.sequence) + if event.event_type.startswith(("tool.choice.", "tool.plan.", + "routing.choice.")) and ( + op is None or op.kind != "ask"): + recording.issue("command.orphan", "Interaction outside question.", + event.path, event.sequence) + if event.event_type in failures: + recording.issue("command.failed", f"{event.event_type}.", + event.path, event.sequence) + return tuple(operations) diff --git a/kilin/system_testing/traces.py b/kilin/system_testing/traces.py new file mode 100644 index 00000000..4ba47e7b --- /dev/null +++ b/kilin/system_testing/traces.py @@ -0,0 +1,722 @@ +"""Read recorded project events without opening a live project session. + +Key Features +------------ +- Decode only the diagnostic hierarchy, including compact span completions. +- Inspect active and archived conversations without silent discovery skips. +- Preserve raw event identity and report malformed records without repair. +- Expand verified configuration and source references for downstream readers. + +Module Structure +---------------- +- ``TraceEvent`` and ``Recording`` describe the decoded recording. +- ``ValidationIssue`` describes a problem at a file or event location. +- ``read_recording`` loads the supported recording format. + +Examples +-------- +>>> from kilin.system_testing.traces import TraceEvent +>>> TraceEvent.__name__ +'TraceEvent' + +""" + +from __future__ import annotations + +from dataclasses import dataclass, field, replace +from datetime import datetime, timedelta +import json +import math +import os +from pathlib import Path, PureWindowsPath + +from kilin._trace_configuration import ( + CONFIGURATION_CONTENT_REFERENCE, + CONFIGURATION_EVENT, + configuration_content_bytes, + resolve_configuration_reference, +) +from kilin._trace_project import TRACE_FORMAT_VERSION +from kilin._trace_snapshots import ( + SEMANTIC_SNAPSHOT_EVENTS, SEMANTIC_SNAPSHOT_REFERENCE, + SOURCE_SNAPSHOT_FIELDS, SOURCE_SNAPSHOT_REFERENCE, + resolve_semantic_reference, resolve_source_reference, + semantic_snapshot, source_snapshot, +) +from kilin.conversation_format import ( + validate_conversation_metadata, + validate_conversation_payload, +) + +__all__ = ["TraceEvent", "ValidationIssue", "Recording", "read_recording"] + + +@dataclass(frozen=True, slots=True) +class ValidationIssue: + """One independently identifiable recording problem or limitation. + + Attributes + ---------- + code: str + Stable machine-readable issue category. + message: str + Explanation intended for the researcher. + path: str | None + Workspace-relative file location when available. + sequence: int | None + Original event number when available. + + """ + + code: str + message: str + path: str | None = None + sequence: int | None = None + + +@dataclass(frozen=True, slots=True) +class TraceEvent: + """One original event, including an expanded span terminal event. + + Attributes + ---------- + path: str + Workspace-relative trace file, including archival placement. + location: str + Location within the diagnostic JSON hierarchy. + metadata: dict + Original event metadata, not the readable span summary. + details: dict + Input, result, or sampled progress payload. Valid compact project + configuration and source observations expose their resolved payload. + exact_content: dict + Separately retained artifact contents, if present. + + """ + + path: str + location: str + metadata: dict + details: dict + exact_content: dict = field(default_factory=dict) + + @property + def sequence(self) -> int: + """Return the original workspace-wide allocation number.""" + return self.metadata["sequence"] + + @property + def event_type(self) -> str: + """Return the original event type, not a display name.""" + return self.metadata["event_type"] + + @property + def span_id(self) -> str | None: + """Return the event's span correlation identifier, if available.""" + return self.metadata.get("span_id") + + +@dataclass(slots=True) +class Recording: + """Internal read-only snapshot of trace payloads and decoding issues. + + Attributes + ---------- + root: pathlib.Path + Original workspace root. + events: list[TraceEvent] + Decodable events in allocation order. + states: dict[str, dict] + Canonical conversation resume states by relative trace path. + issues: list[ValidationIssue] + Problems encountered during decoding. + last_sequence: int | None + Recorded counter high-water mark, if valid. + + """ + + root: Path + events: list[TraceEvent] = field(default_factory=list) + states: dict[str, dict] = field(default_factory=dict) + issues: list[ValidationIssue] = field(default_factory=list) + last_sequence: int | None = None + + def issue(self, code: str, message: str, path: str | None = None, + sequence: int | None = None) -> None: + """Collect an issue without concealing other decodable records. + + Parameters + ---------- + code: str + Stable problem category. + message: str + Human-readable explanation. + path: str | None, optional + Workspace-relative file location. + sequence: int | None, optional + Event number if known. + + """ + self.issues.append(ValidationIssue(code, message, path, sequence)) + + +def safe_path(root: Path, relative: str) -> Path: + """Resolve a normalized relative path without following child links. + + Parameters + ---------- + root: pathlib.Path + Resolved workspace root. + relative: str + Untrusted workspace-relative POSIX path. + + Returns + ------- + pathlib.Path + Safe child path, which need not exist. + + """ + if (not isinstance(relative, str) or not relative + or "\\" in relative or "\x00" in relative + or PureWindowsPath(relative).drive + or any(p in ("", ".", "..") for p in relative.split("/"))): + raise ValueError("Expected a normalized workspace-relative path.") + path = root + for part in relative.split("/"): + path = path / part + if path.is_symlink(): + raise ValueError(f"Linked workspace path: {relative}") + return path + + +def _unique_object(pairs: list[tuple[str, object]]) -> dict: + """Reject ambiguous JSON objects instead of using the last value. + + Parameters + ---------- + pairs: list of tuple + Ordered decoded JSON object members. + + Returns + ------- + dict + Unambiguous object. + + """ + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate JSON member: {key}") + result[key] = value + return result + + +def _invalid_constant(value: str) -> None: + """Reject non-JSON numeric constants. + + Parameters + ---------- + value: str + Invalid numeric constant. + + """ + raise ValueError(f"Nonfinite JSON constant: {value}") + + +def read_json(root: Path, relative: str) -> dict: + """Read one regular JSON object without modifying its file. + + Parameters + ---------- + root: pathlib.Path + Workspace root. + relative: str + Normalized relative file location. + + Returns + ------- + dict + Decoded object. + + """ + path = safe_path(root, relative) + if not path.is_file(): + raise ValueError(f"Missing or nonregular file: {relative}") + with path.open(encoding="utf-8") as stream: + result = json.load(stream, object_pairs_hook=_unique_object, + parse_constant=_invalid_constant) + if not isinstance(result, dict): + raise ValueError("Expected a JSON object.") + return result + + +def _object(value: object) -> dict: + """Require an object at a known structural position. + + Parameters + ---------- + value: object + Decoded JSON value. + + Returns + ------- + dict + Checked object. + + """ + if not isinstance(value, dict): + raise ValueError("Expected a JSON object.") + return value + + +def _event(recording: Recording, path: str, location: str, + metadata: object, details: object, exact: object) -> None: + """Decode one event and retain its source location. + + Parameters + ---------- + recording: Recording + Snapshot receiving events and issues. + path: str + Trace file location. + location: str + Diagnostic hierarchy location. + metadata: object + Raw compact event metadata. + details: object + Raw event data. + exact: object + Raw separately retained content. + + """ + try: + meta = dict(_object(metadata)) + seq = meta.get("sequence") + if type(seq) is not int or seq < 1: + raise ValueError("Invalid event sequence.") + for key in ("event_type", "trace_id", "event_id", "component", + "status", "timestamp_utc"): + if not isinstance(meta.get(key), str) or not meta[key]: + raise ValueError(f"Missing event metadata: {key}") + stamp = datetime.fromisoformat(meta["timestamp_utc"]) + if stamp.utcoffset() != timedelta(0): + raise ValueError("Expected a UTC event timestamp.") + elapsed = meta.get("elapsed_ms") + if (type(elapsed) not in (int, float) or elapsed < 0 + or not math.isfinite(elapsed)): + raise ValueError("Invalid event elapsed time.") + for key in ("turn_id", "span_id", "parent_span_id"): + if key in meta and (not isinstance(meta[key], str) + or not meta[key]): + raise ValueError(f"Invalid event correlation: {key}") + # The writer substitutes running/completed/failed for the original + # start status. Preserve the original rather than the summary. + if "started_status" in meta: + status = meta.pop("started_status") + if not isinstance(status, str) or not status: + raise ValueError("Invalid original start status.") + meta["status"] = status + meta.pop("finished_at_utc", None) + recording.events.append(TraceEvent( + path, location, meta, _object(details), _object(exact) + )) + except (ValueError, TypeError, OverflowError) as error: + recording.issue("event.invalid", f"{location}: {error}", path) + + +def _operations(recording: Recording, path: str, location: str, + operations: object, turn_id: str | None = None) -> None: + """Decode an operation mapping and its compact lifecycle terminals. + + Parameters + ---------- + recording: Recording + Snapshot receiving events and issues. + path: str + Trace file location. + location: str + Parent diagnostic hierarchy location. + operations: object + Operation mapping. + turn_id: str | None, optional + Enclosing turn identity, when in a turn stage. + + """ + for key, value in _object(operations).items(): + here = f"{location}/{key}" + try: + node = _object(value) + meta = _object(node.get("event")) + if meta.get("turn_id") != turn_id: + raise ValueError("Event is in the wrong turn group.") + _event(recording, path, here + "/event", meta, + node.get("details", {}), node.get("exact_content", {})) + if "completion" in node: + end = _object(node["completion"]) + start_type = meta.get("event_type") + if (not isinstance(start_type, str) + or not start_type.endswith(".started") + or end.get("event_type") not in ( + start_type[:-8] + ".completed", + start_type[:-8] + ".failed") + or any(end.get(k) != meta.get(k) for k in ( + "span_id", "trace_id", "turn_id", "component", + "parent_span_id")) + or not meta.get("span_id") + or type(end.get("sequence")) is not int + or type(meta.get("sequence")) is not int + or end["sequence"] <= meta["sequence"]): + raise ValueError("Mismatched span completion.") + _event(recording, path, here + "/completion", end, + node.get("result", {}), {}) + elif "started_status" in meta: + recording.issue("span.incomplete", "Unfinished span.", path, + meta.get("sequence")) + except (ValueError, TypeError) as error: + recording.issue("hierarchy.invalid", f"{here}: {error}", path) + + +def _document(recording: Recording, path: str, payload: dict) -> None: + """Read only documented diagnostic locations and canonical state. + + Parameters + ---------- + recording: Recording + Snapshot receiving events, states, and issues. + path: str + Trace file location. + payload: dict + Decoded trace document. + + """ + project = path == "logs/traces/project.json" + if (type(payload.get("trace_format_version")) is not int + or payload["trace_format_version"] != TRACE_FORMAT_VERSION + or payload.get("sequence_scope") != "project" + or payload.get("trace_scope") != ( + "project" if project else "conversation")): + recording.issue("trace.format", "Unsupported trace format or scope.", + path) + return + if payload.get("trace_incomplete") is not False: + recording.issue("trace.incomplete", "Trace health is not complete.", + path) + if not project: + try: + state = validate_conversation_payload(payload) + validate_conversation_metadata(state) + recording.states[path] = state + except (ValueError, TypeError) as error: + recording.issue("conversation.invalid", str(error), path) + for key, value in _object(payload.get("sessions")).items(): + here = f"sessions/{key}" + try: + session = _object(value) + if project and "resume_state" in session: + raise ValueError("Project trace contains conversation state.") + _operations(recording, path, here + "/operations", + session.get("operations", {})) + for name, raw in _object(session.get("turns", {})).items(): + turn = _object(raw) + tid = turn.get("turn_id") + if not isinstance(tid, str) or not tid: + raise ValueError("Missing diagnostic turn identity.") + for stage, group in _object(turn.get("stages")).items(): + _operations( + recording, path, + f"{here}/turns/{name}/stages/{stage}/operations", + _object(group).get("operations"), tid, + ) + checkpoints = _object(session.get("progress_checkpoints", {})) + for name, raw in checkpoints.items(): + progress = _object(raw) + keys = ("sequence", "timestamp_utc", "elapsed_ms", + "trace_id", "event_id", "event_type", "component", + "status", "turn_id", "span_id", "parent_span_id", + "started_elapsed_ms", "duration_ms") + meta = {k: progress[k] for k in keys if k in progress} + details = {k: v for k, v in progress.items() if k not in keys} + _event(recording, path, + f"{here}/progress_checkpoints/{name}", + meta, details, {}) + except (ValueError, TypeError) as error: + recording.issue("hierarchy.invalid", f"{here}: {error}", path) + + +def _trace_paths(recording: Recording) -> list[str]: + """Discover every JSON candidate without silently skipping archives. + + Parameters + ---------- + recording: Recording + Workspace and issue collector. + + Returns + ------- + list[str] + Sorted relative trace paths, excluding the sequence counter. + + """ + root = recording.root + directory = safe_path(root, "logs/traces") + if not directory.is_dir(): + raise ValueError("Missing trace directory.") + paths = [] + + def on_error(error: OSError) -> None: + """Report an inaccessible history directory. + + Parameters + ---------- + error: OSError + Directory traversal error. + + """ + recording.issue("trace.discovery", str(error), "logs/traces") + + for parent, dirs, files in os.walk(directory, onerror=on_error): + dirs.sort() + for name in sorted(dirs): + child = Path(parent) / name + if child.is_symlink(): + recording.issue("trace.discovery", "Linked trace directory.", + child.relative_to(root).as_posix()) + dirs.remove(name) + for name in sorted(files): + relative = (Path(parent) / name).relative_to(root).as_posix() + if name.lower().endswith(".json") and relative != ( + "logs/traces/.sequence.json" + ): + paths.append(relative) + return sorted(paths) + + +def _resolve_configurations(recording: Recording) -> None: + """Expand compact configuration observations in chronological order. + + Parameters + ---------- + recording: Recording + Decoded recording sorted by project-wide sequence number. Invalid + references contribute blocking issues; original files stay untouched. + + Notes + ----- + Track the most recent full project configuration, not the most recent + reference. Complete full observations pass through unchanged. A reference + must belong to the same project trace and cannot target a later event, + a different event type, an earlier superseded snapshot, or another + reference. + + """ + + latest = None + for index, event in enumerate(recording.events): + compact = CONFIGURATION_CONTENT_REFERENCE in event.details + if event.event_type != CONFIGURATION_EVENT: + if compact: + recording.issue( + "configuration.reference", + "Reference is not a configuration observation.", + event.path, event.sequence, + ) + continue + # A duplicate allocation cannot identify a unique reference target. + duplicate = ( + (index > 0 + and recording.events[index - 1].sequence == event.sequence) + or (index + 1 < len(recording.events) + and recording.events[index + 1].sequence == event.sequence) + ) + try: + if not compact: + if event.path == "logs/traces/project.json": + if (not duplicate + and event.metadata.get("status") == "completed" + and "turn_id" not in event.metadata): + # An invalid full observation (including obsolete + # compact payloads) cannot supply historical state. + latest = None + configuration_content_bytes(event.details) + latest = (event.sequence, event.details) + else: + latest = None + continue + if duplicate: + raise ValueError("Ambiguous configuration event sequence.") + if (event.path != "logs/traces/project.json" + or event.metadata.get("status") != "completed" + or "turn_id" in event.metadata): + raise ValueError( + "Reference is not a completed project observation." + ) + details = resolve_configuration_reference( + event.details, event.sequence, latest + ) + recording.events[index] = replace(event, details=details) + except (ValueError, TypeError, RecursionError) as error: + recording.issue("configuration.reference", str(error), + event.path, event.sequence) + + +def _resolve_semantic_snapshots(recording: Recording) -> None: + """Resolve shared manifests using only raw full project observations. + + Parameters + ---------- + recording: Recording + Globally ordered events. Invalid references add blocking issues; + no source file, semantic manifest or trace is modified. + + Notes + ----- + Resolve before same-type source groups so a previously compact opening + can never become an implicit reference target. Only the exact manifest + is shared; revision, provenance and command outcome stay inline. + + """ + + latest = None + for index, event in enumerate(recording.events): + kind = event.event_type + compact = SEMANTIC_SNAPSHOT_REFERENCE in event.details + if kind not in SEMANTIC_SNAPSHOT_EVENTS and not compact: + continue + duplicate = ( + (index > 0 + and recording.events[index - 1].sequence == event.sequence) + or (index + 1 < len(recording.events) + and recording.events[index + 1].sequence == event.sequence) + ) + project = (event.path == "logs/traces/project.json" + and "turn_id" not in event.metadata + and event.location.endswith("/event")) + eligible = (project and not duplicate + and event.metadata.get("status") == "completed") + if not compact: + if project and SOURCE_SNAPSHOT_REFERENCE not in event.details: + latest = None + if eligible: + try: + semantic_snapshot(kind, event.details) + except ValueError: + pass + else: + latest = (event.sequence, kind, event.details) + continue + try: + if not eligible: + raise ValueError("Reference is not a unique project event.") + details = resolve_semantic_reference( + kind, event.details, event.sequence, latest, + ) + recording.events[index] = replace(event, details=details) + except (ValueError, TypeError, RecursionError) as error: + recording.issue("semantic_snapshot.reference", str(error), + event.path, event.sequence) + + +def _resolve_source_snapshots(recording: Recording) -> None: + """Expand source observations before validation and replay. + + Parameters + ---------- + recording: Recording + Events in global sequence order. Invalid references are blocking + issues; the original files are never changed. + + Notes + ----- + Candidates are independent for each supported event type. A full failed + or incomplete observation resets its candidate. References never become + candidates, and invalid references cannot use current workspace data. + + """ + + latest = {} + for index, event in enumerate(recording.events): + kind = event.event_type + compact = SOURCE_SNAPSHOT_REFERENCE in event.details + if kind not in SOURCE_SNAPSHOT_FIELDS and not compact: + continue + duplicate = ( + (index > 0 + and recording.events[index - 1].sequence == event.sequence) + or (index + 1 < len(recording.events) + and recording.events[index + 1].sequence == event.sequence) + ) + project = (event.path == "logs/traces/project.json" + and "turn_id" not in event.metadata + and event.location.endswith("/event")) + eligible = (project and not duplicate + and event.metadata.get("status") == "completed") + if not compact: + if project: + latest.pop(kind, None) + if eligible: + try: + source_snapshot(kind, event.details) + except ValueError: + pass + else: + latest[kind] = (event.sequence, event.details) + continue + try: + if not eligible: + raise ValueError("Reference is not a unique project event.") + details = resolve_source_reference( + kind, event.details, event.sequence, latest.get(kind), + ) + recording.events[index] = replace(event, details=details) + except (ValueError, TypeError, RecursionError) as error: + recording.issue("source_snapshot.reference", str(error), + event.path, event.sequence) + + +def read_recording(root: Path) -> Recording: + """Read the project counter and all trace documents independently. + + Parameters + ---------- + root: pathlib.Path + Reference workspace, already resolved by the caller. + + Returns + ------- + Recording + Decoded events, canonical states, and structural issues. No project + files or lock companions are created, updated, or repaired. + + """ + recording = Recording(root) + counter = "logs/traces/.sequence.json" + try: + data = read_json(root, counter) + last = data.get("last_sequence") + if (type(data.get("format_version")) is not int + or data["format_version"] != TRACE_FORMAT_VERSION + or type(last) is not int or last < 1): + raise ValueError("Invalid shared sequence counter.") + recording.last_sequence = last + if data.get("incomplete") is not False: + recording.issue("counter.incomplete", "Recording is incomplete.", + counter) + except (OSError, ValueError, RecursionError) as error: + recording.issue("counter.invalid", str(error), counter) + try: + paths = _trace_paths(recording) + except (OSError, ValueError) as error: + recording.issue("trace.discovery", str(error), "logs/traces") + return recording + if "logs/traces/project.json" not in paths: + recording.issue("trace.missing", "Missing shared project trace.") + for path in paths: + try: + _document(recording, path, read_json(root, path)) + except (OSError, ValueError, TypeError, RecursionError) as error: + recording.issue("trace.invalid", str(error), path) + recording.events.sort(key=lambda event: event.sequence) + _resolve_configurations(recording) + _resolve_semantic_snapshots(recording) + _resolve_source_snapshots(recording) + return recording diff --git a/kilin/system_testing/validation.py b/kilin/system_testing/validation.py new file mode 100644 index 00000000..a4f8f1a6 --- /dev/null +++ b/kilin/system_testing/validation.py @@ -0,0 +1,1560 @@ +"""Validate a closed reference workspace without inference or mutation. + +Key Features +------------ +- Check sequence continuity, span identity, and recorded command boundaries. +- Verify retained sources against historical import and indexing records. +- Reconstruct conversation identities, checkpoints, and feedback state. +- Report detectable inconsistencies without repairing the reference. + +Module Structure +---------------- +- ``ValidationReport`` and ``InvalidRecordingError`` expose validation results. +- ``validate_recording`` checks the decoded history and retained workspace. + +Examples +-------- +>>> from kilin.system_testing import Experiment +>>> # report = Experiment(workspace).validate() +>>> # report.valid + +""" + +from __future__ import annotations + +from configparser import ConfigParser, Error as ConfigError +from dataclasses import asdict, dataclass, field +from hashlib import sha256 +import json +import os +import platform +import sys +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path + +import kilin +from kilin._trace_project import OPERATION_RECORDING_VERSION +from kilin.conversation_format import validate_conversation_state +from kilin.conversation_memory.feedback import FeedbackStore +from kilin.conversation_memory.models import ( + MessageFeedback, + require_turn_uuid, +) +from kilin.project import _read_project +from kilin.repository import _manifest_files +from kilin.workspace import SOURCE_MANIFEST_VERSION, _read_records + +from ._filesystem import is_incidental_metadata +from ._plugin_provenance import plugin_observations +from ._semantic_replay import validate_semantic_history +from .timeline import TimelineOperation, build_timeline, one +from .traces import ( + Recording, TraceEvent, ValidationIssue, read_json, safe_path, +) + +__all__ = ["ValidationReport", "InvalidRecordingError", "validate_recording"] + +_PROJECT = "logs/traces/project.json" + + +@dataclass(frozen=True, slots=True) +class ValidationReport: + """Result of inspecting a reference recording. + + Attributes + ---------- + workspace: pathlib.Path + Resolved reference workspace. + issues: tuple[ValidationIssue, ...] + Blocking recording errors, in deterministic discovery order. + warnings: tuple[ValidationIssue, ...] + Nonblocking limitations or environmental differences. + event_count: int + Number of successfully decoded original events. + events: tuple[TraceEvent, ...] + All decodable original events, including non-command diagnostics. + operations: tuple[TimelineOperation, ...] + Candidate command intervals, including unsuccessful commands. These + are for inspection only when validation fails. + source_paths: tuple of str + Workspace-relative paths owned by recorded source imports. + + """ + + workspace: Path + issues: tuple[ValidationIssue, ...] + warnings: tuple[ValidationIssue, ...] + event_count: int + events: tuple[TraceEvent, ...] + operations: tuple[TimelineOperation, ...] + source_paths: tuple[str, ...] = () + + @property + def valid(self) -> bool: + """Return whether no blocking issue was detected.""" + return not self.issues + + def raise_for_errors(self) -> None: + """Reject invalid recordings before further processing.""" + if not self.valid: + raise InvalidRecordingError(self) + + +class InvalidRecordingError(ValueError): + """A reference cannot be used as a validated operation timeline. + + Attributes + ---------- + report: ValidationReport + Complete inspection result for diagnosing the rejection. + + """ + + def __init__(self, report: ValidationReport) -> None: + """Retain the validation report with a concise exception message. + + Parameters + ---------- + report: ValidationReport + Invalid reference inspection result. + + """ + self.report = report + first = report.issues[0] + super().__init__(f"Invalid recording ({len(report.issues)} issues): " + f"{first.code}: {first.message}") + + +def _require(condition: bool, message: str) -> None: + """Require a recorded invariant without relying on Python assertions. + + Parameters + ---------- + condition: bool + Checked recording invariant. + message: str + Explanation if the check fails. + + """ + if not condition: + raise ValueError(message) + + +def _text(value: object) -> str: + """Require a nonempty recorded string identity. + + Parameters + ---------- + value: object + Untrusted recorded value. + + Returns + ------- + str + Nonempty identity. + + """ + if not isinstance(value, str) or not value: + raise ValueError("Missing or invalid recorded string.") + return value + + +def _strings(value: object) -> list[str]: + """Require a list of distinct nonempty recorded strings. + + Parameters + ---------- + value: object + Untrusted recorded inventory. + + Returns + ------- + list[str] + Checked inventory in its original order. + + """ + if not isinstance(value, list): + raise ValueError("Missing or invalid recorded list.") + items = [_text(item) for item in value] + _require(len(items) == len(set(items)), "Duplicate inventory entries.") + return items + + +def _sequence_checks(recording: Recording) -> None: + """Verify event numbers, identities, span links and logger lifetimes. + + Parameters + ---------- + recording: Recording + Snapshot receiving detected issues. + + """ + previous = 0 + identifiers = set() + runs: dict[str, list[TraceEvent]] = {} + spans: dict[str, TraceEvent] = {} + finished: dict[str, TraceEvent] = {} + for event in recording.events: + seq = event.sequence + meta = event.metadata + if seq == previous: + recording.issue("sequence.duplicate", "Repeated event sequence.", + event.path, seq) + elif seq > previous + 1: + recording.issue("sequence.gap", + f"Missing sequences {previous + 1}-{seq - 1}.", + event.path, seq) + previous = seq + if meta["event_id"] in identifiers: + recording.issue("event.duplicate", "Repeated event identity.", + event.path, seq) + identifiers.add(meta["event_id"]) + runs.setdefault(meta["trace_id"], []).append(event) + if "started_elapsed_ms" in meta: + span = event.span_id + if event.event_type.endswith(".started"): + if span is None or span in spans: + recording.issue("span.identity", "Invalid span identity.", + event.path, seq) + else: + spans[span] = event + elif event.event_type.endswith((".completed", ".failed")): + if span is None or span in finished: + recording.issue("span.identity", "Invalid span terminal.", + event.path, seq) + else: + finished[span] = event + high = recording.last_sequence + if high is not None and previous != high: + recording.issue("sequence.counter", f"Last event {previous} differs " + f"from allocation counter {high}.") + for span in sorted(set(spans) | set(finished)): + start, end = spans.get(span), finished.get(span) + if (start is None or end is None or start.sequence >= end.sequence + or start.event_type[:-8] != end.event_type.rsplit(".", 1)[0] + or start.path != end.path + or start.metadata["trace_id"] != end.metadata["trace_id"]): + event = start or end + recording.issue("span.incomplete", "Missing or mismatched span.", + event.path, event.sequence) + for event in recording.events: + parent = event.metadata.get("parent_span_id") + if parent is None: + continue + start, end = spans.get(parent), finished.get(parent) + if (start is None or end is None or start.path != event.path + or start.metadata["trace_id"] != event.metadata["trace_id"] + or not start.sequence < event.sequence < end.sequence): + recording.issue("span.parent", "Invalid parent span link.", + event.path, event.sequence) + archived = {} + for event in recording.events: + if event.event_type == "gui.conversation.deleted" and ( + event.details.get("deleted_active") is True): + path = event.details.get("archived_path") + if isinstance(path, str): + archived[path] = event.sequence + latest = {} + for run in runs.values(): + latest[run[-1].path] = max(latest.get(run[-1].path, 0), + run[-1].sequence) + for run in runs.values(): + first, last = run[0], run[-1] + # Active deletion detaches the writer without appending a close to + # the archived bytes. This is the only supported missing-close case. + detached = (archived.get(last.path, -1) > last.sequence + and latest[last.path] == last.sequence) + if (len({e.path for e in run}) != 1 + or first.event_type != "trace.started" + or sum(e.event_type == "trace.started" for e in run) != 1 + or (last.event_type != "trace.closed" and not detached) + or sum(e.event_type == "trace.closed" for e in run) != ( + 1 if last.event_type == "trace.closed" else 0)): + recording.issue("trace.lifetime", "Unclosed or ambiguous logger " + "run.", first.path, first.sequence) + + +@dataclass(slots=True) +class _SourceHistory: + """Accumulate actual imported copies and historical content identities.""" + + root: Path + files: dict[str, tuple[str, str, str]] = field(default_factory=dict) + origins: dict[str, tuple[str, str]] = field(default_factory=dict) + hashes: dict[str, dict] = field(default_factory=dict) + batches: dict[str, TraceEvent] = field(default_factory=dict) + completed: set[str] = field(default_factory=set) + copied: dict[str, set[str]] = field(default_factory=dict) + + def consume(self, event: TraceEvent) -> None: + """Validate one source batch or historical manifest in order. + + Parameters + ---------- + event: TraceEvent + Original event whose payload may describe a source change. + + """ + kind, data = event.event_type, event.details + if kind in ("workspace.prepare.started", "workspace.sync.started"): + batch = _text(data.get("batch_id")) + _require(batch not in self.batches, "Repeated source batch ID.") + _require(not set(self.batches) - self.completed, + "Overlapping source batches.") + self.batches[batch] = event + self.copied[batch] = set() + if kind == "workspace.prepare.started": + _require(data.get("operation") in ("create", "import"), + "Unknown source preparation operation.") + _require(data.get("replace_existing") is False, + "Reference imports must not replace sources.") + _strings(data.get("source_paths")) + elif kind in ("workspace.source.copied", "workspace.sync.file", + "workspace.prepare.completed", + "workspace.sync.completed", "workspace.sync.detached"): + batch = _text(data.get("batch_id")) + start = self.batches.get(batch) + _require(start is not None and batch not in self.completed, + "Source event without an active batch.") + if kind.endswith(".completed"): + _require(kind[:-10] == start.event_type[:-8], + "Mismatched source batch completion.") + if kind == "workspace.prepare.completed": + _require(data.get("operation") == start.details.get( + "operation"), "Mismatched preparation operation.") + # Copy records use resolved external identities, while + # the submitted paths may contain aliases. Never resolve + # original external paths during reference inspection. + _require(len(self.copied[batch]) <= + len(start.details["source_paths"]), + "More source copies than submitted paths.") + _require(type(data.get("source_count")) is int + and data["source_count"] == len(self.origins), + "Source count differs from recorded origins.") + else: + changes = data.get("changes") + _require(isinstance(changes, dict), "Missing sync result.") + _require(set(_strings(changes.get("added"))) == + self.copied[batch], "Sync result differs from " + "recorded imports.") + _require(not changes.get("changed") and not + changes.get("deleted") and not + changes.get("edited"), "Nonadditive source sync.") + self.completed.add(batch) + elif kind == "workspace.source.copied": + _require(start.event_type == "workspace.prepare.started", + "Copy belongs to the wrong batch.") + self._copy(data, batch) + elif kind == "workspace.sync.file": + _require(start.event_type == "workspace.sync.started", + "Sync copy belongs to the wrong batch.") + self._sync(data, batch) + else: + raise ValueError("Source detachment is not additive.") + elif kind in ("index.check.completed", "index.empty"): + manifest = _manifest_files(data.get("source_manifest")) + managed = {f"sources/{name}": record + for name, record in manifest.items()} + _require(set(managed) == set(self.files), + "Index inventory differs from imported source files.") + for path, record in managed.items(): + _require(path not in self.hashes or + self.hashes[path] == record, + f"Historical source content changed: {path}") + self.hashes[path] = record + + def _copy(self, data: dict, batch: str) -> None: + """Record actual file destinations, including renamed direct files. + + Parameters + ---------- + data: dict + Source copy payload. + batch: str + Active preparation batch identity. + + """ + source = _text(data.get("source")) + destination = _text(data.get("workspace_path")) + kind = data.get("kind") + _require(kind in ("file", "folder"), "Invalid source kind.") + _require(destination.startswith("sources/") and + len(destination.split("/")) == 2, + "Invalid managed source destination.") + safe_path(self.root, destination) + _require(source not in self.copied[batch], "Duplicate source copy.") + self.copied[batch].add(source) + previous = self.origins.get(source) + _require(previous is None or previous == (destination, kind), + "Source destination or kind changed.") + _require(not any(value[0] == destination and key != source + for key, value in self.origins.items()), + "Conflicting source ownership.") + self.origins[source] = (destination, kind) + copied = _strings(data.get("copied_files")) + preserved = _strings(data.get("preserved_files")) + _require(not set(copied) & set(preserved), + "File both copied and preserved.") + selection = data.get("requested_files") + requested = self.batches[batch].details.get("selected_files") + if requested is not None: + _require(isinstance(requested, dict) and + requested.get(source) == selection, + "Copy selection differs from batch request.") + if selection is not None: + _require(set(_strings(selection)) == set(copied + preserved), + "Copy result differs from exact selection.") + if kind == "file": + _require(len(copied + preserved) == 1 and + "/" not in (copied + preserved)[0], + "Direct import must identify exactly one file.") + for relative in copied + preserved: + safe_path(self.root, f"sources/{relative}") + path = (destination if kind == "file" else + f"{destination}/{relative}") + identity = (source, kind, relative) + if relative in copied: + _require(path not in self.files, + f"Historical source was overwritten: {path}") + self.files[path] = identity + else: + _require(self.files.get(path) == identity, + f"Preserved source was never imported: {path}") + + def _sync(self, data: dict, batch: str) -> None: + """Record an additive synchronization into an existing source. + + Parameters + ---------- + data: dict + Actual synchronization event payload. + batch: str + Active synchronization batch identity. + + """ + _require(data.get("action") == "import", "Nonadditive source sync.") + path = _text(data.get("path")) + original = _text(data.get("original")) + relative = _text(data.get("relative")) + origin = self.origins.get(original) + _require(origin is not None, "Sync source has no recorded origin.") + destination, kind = origin + _require(kind == "folder" and data.get("kind") == kind + and path == f"{destination}/{relative}", + "Sync destination differs from original source ownership.") + safe_path(self.root, path) + _require(path not in self.files, "Sync overwrites a recorded source.") + self.files[path] = (original, kind, relative) + self.copied[batch].add(path) + + def finish(self, recording: Recording) -> None: + """Compare final managed inventory and bytes with historical records. + + Parameters + ---------- + recording: Recording + Issue collector for mismatching final state. + + """ + if set(self.batches) != self.completed: + recording.issue("batch.incomplete", "Unfinished source batch.") + try: + path = safe_path(self.root, "sources.json") + if path.exists() or self.origins: + raw = read_json(self.root, "sources.json") + _require(type(raw.get("version")) is int and + raw["version"] == SOURCE_MANIFEST_VERSION, + "Invalid source manifest version.") + records = _read_records(path) + observed = {} + origins = {} + for record in records: + source, name = record["original"], record["name"] + kind = record["kind"] + destination = f"sources/{name}" + origins[source] = (destination, kind) + _require(not record.get("versions"), + "Reference contains replaced source versions.") + for relative in record["files"]: + path = destination if kind == "file" else ( + f"{destination}/{relative}") + observed[path] = (source, kind, relative) + _require(origins == self.origins and observed == self.files, + "Source ownership manifest differs from recorded " + "imports.") + except (OSError, ValueError, TypeError, KeyError) as error: + recording.issue("source.inventory", str(error), "sources.json") + found = set() + try: + directory = safe_path(self.root, "sources") + _require(directory.is_dir(), "Missing managed source directory.") + for parent, dirs, files in os.walk(directory, onerror=_raise_os): + dirs.sort() + for name in sorted(dirs + files): + path = Path(parent) / name + relative = path.relative_to(self.root).as_posix() + if path.is_symlink(): + recording.issue("source.link", "Linked source path.", + relative) + if name in dirs: + dirs.remove(name) + elif name in files: + if not path.is_file(): + recording.issue("source.invalid", "Nonregular " + "source file.", relative) + found.add(relative) + elif not is_incidental_metadata( + path, relative, self.files + ): + found.add(relative) + for path in sorted(found - self.files.keys()): + recording.issue("source.unrecorded", "Unrecorded source.", + path) + except (OSError, ValueError) as error: + recording.issue("source.discovery", str(error), "sources") + for relative in sorted(self.files): + try: + path = safe_path(self.root, relative) + _require(path.is_file(), "Missing retained source file.") + expected = self.hashes.get(relative) + _require(expected is not None, + "Source lacks a historical content manifest.") + with path.open("rb") as stream: + before = os.fstat(stream.fileno()) + digest = sha256() + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + after = os.fstat(stream.fileno()) + fields = ("st_dev", "st_ino", "st_size", "st_mtime_ns", + "st_ctime_ns") + _require(all(getattr(before, field) == getattr(after, field) + for field in fields), + "Source changed during inspection.") + _require(expected == {"sha256": digest.hexdigest(), + "size_bytes": after.st_size}, + "Retained source differs from recorded content.") + except (OSError, ValueError) as error: + recording.issue("source.content", str(error), relative) + + +def _raise_os(error: OSError) -> None: + """Propagate a failed directory traversal. + + Parameters + ---------- + error: OSError + Directory scan error. + + """ + raise error + + +@dataclass(slots=True) +class _Conversation: + """Reconstructed conversation identity and committed history.""" + + path: str + name: str + parent: str | None = None + origin_count: int | None = None + origin_checkpoint: str | None = None + turns: list[str] = field(default_factory=list) + checkpoint: str | None = None + deleted: bool = False + + +@dataclass(slots=True) +class _ConversationHistory: + """Check conversation and feedback history against durable final state.""" + + recording: Recording + conversations: dict[str, _Conversation] = field(default_factory=dict) + questions: dict[str, str] = field(default_factory=dict) + checkpoints: set[str] = field(default_factory=set) + ratings: dict[tuple[str, str], MessageFeedback] = field( + default_factory=dict + ) + feedback_revision: str = field( + default_factory=lambda: sha256(b"").hexdigest() + ) + active: str | None = None + created: bool = False + + def _new(self, data: dict, *, parent: str | None = None) -> str: + """Register a recorded new conversation and its inherited prefix. + + Parameters + ---------- + data: dict + Recorded conversation identity and lineage. + parent: str | None, optional + Expected parent of a branch. + + Returns + ------- + str + Newly registered conversation identifier. + + """ + identifier = _text(data.get("conversation_id")) + _require(identifier not in self.conversations, + "Conversation identity reused for a new record.") + path = _text(data.get("path")) + safe_path(self.recording.root, path) + _require(Path(path).parent.as_posix() == "logs/traces" and + Path(path).name.startswith("conversation_") and + path.endswith(".json"), "Invalid conversation path.") + _require(not any(item.path == path for item in + self.conversations.values()), + "Conflicting conversation paths.") + _require(data.get("parent_conversation_id") == parent, + "Unexpected conversation parent.") + count = data.get("origin_turn_count") + origin = data.get("origin_checkpoint_id") + item = _Conversation(path, _text(data.get("name")), parent, + count, origin) + if parent is not None: + ancestor = self._known(parent) + _require(type(count) is int and 0 <= count <= len(ancestor.turns) + and origin == ancestor.checkpoint, + "Branch origin does not match parent history.") + item.turns = ancestor.turns[:count] + if count == len(ancestor.turns): + item.checkpoint = ancestor.checkpoint + else: + _require(count is None and origin is None, + "Root conversation has branch metadata.") + self.conversations[identifier] = item + return identifier + + def _known(self, identifier: object) -> _Conversation: + """Resolve a live conversation identity at the current sequence. + + Parameters + ---------- + identifier: object + Recorded conversation ID. + + Returns + ------- + _Conversation + Live reconstructed conversation. + + """ + item = self.conversations.get(_text(identifier)) + _require(item is not None and not item.deleted, + "Command refers to an unknown or archived conversation.") + return item + + def _check_record(self, data: dict) -> None: + """Check recorded catalog metadata against reconstructed lineage. + + Parameters + ---------- + data: dict + One catalog, selection, or mutation result. + + """ + item = self._known(data.get("conversation_id")) + _require(data.get("path") == item.path and data.get("name") == + item.name and data.get("parent_conversation_id") == + item.parent and data.get("origin_turn_count") == + item.origin_count and data.get("origin_checkpoint_id") == + item.origin_checkpoint, "Conversation metadata disagrees " + "with recorded history.") + + def consume(self, op: TimelineOperation) -> None: + """Apply one command's recorded durable outcome to the history. + + Parameters + ---------- + op: TimelineOperation + Candidate recorded command, never executed by this validator. + + """ + kind, request = op.kind, op.request + if kind in ("create_project", "open_project"): + self._open(op) + else: + _require(self.active is not None, "Command without open project.") + previous = self.active + if kind == "close_project": + _require(request.get("conversation_id") == self.active, + "Close refers to the wrong conversation.") + self.active = None + elif kind == "ask": + self._question(op) + elif kind in ("create_conversation", "reset_conversation"): + _require(request.get("previous_conversation_id") == previous, + "Creation refers to the wrong active conversation.") + result = one(op.events, "gui.conversation.create.result" if + kind == "create_conversation" else + "gui.conversation.reset.result").details + if kind == "create_conversation": + _require(type(request.get("branch")) is bool and + type(result.get("reused")) is bool, + "Missing creation or reuse policy.") + if result.get("reused") is True: + _require(request.get("branch") is False and + not self._known(result.get("conversation_id") + ).turns, + "Only an empty nonbranch chat may be reused.") + self._check_record(result) + self.active = result["conversation_id"] + _require(self.active != previous, "Reused active chat.") + else: + parent = previous if request.get("branch") else None + self.active = self._new(result, parent=parent) + if parent is not None: + count = request.get("turn_count") + expected = (len(self._known(parent).turns) + if count is None else count) + _require(type(expected) is int and + result.get("origin_turn_count") == expected, + "Branch result differs from requested " + "prefix.") + self._selection(op, previous) + elif kind == "select_conversation": + target = _text(request.get("conversation_id")) + self._known(target) + self.active = target + if previous == target: + unchanged = one(op.events, + "gui.conversation.select.unchanged") + _require(unchanged.details.get("conversation_id") == + target, "Invalid unchanged selection.") + _require(not op.matching("gui.conversation.selected"), + "No-op selection also switched conversations.") + else: + self._selection(op, previous) + elif kind == "rename_conversation": + item = self._known(request.get("conversation_id")) + result = one(op.events, "gui.conversation.renamed").details + _require(result.get("conversation_id") == + request.get("conversation_id") and + result.get("name") == " ".join( + _text(request.get("name")).split()), + "Rename result differs from requested name.") + item.name = result["name"] + self._check_record(result) + elif kind == "delete_conversation": + self._delete(op) + elif kind in ("feedback", "memory_exclusion"): + self._feedback(op) + elif kind == "sync_memory": + _require(request.get("trigger") == "manual", + "Expected manual memory synchronization.") + one(op.events, "gui.conversation.memory.sync.result") + one(op.events, "project.memory.sync.result") + # Restoration is expected when an actual switch/open occurs, but + # additional model-restoration diagnostics do not create new turns. + for event in op.matching("conversation.restored"): + _require(self.active is not None, "Restore without active chat.") + self._restored(event) + + def _open(self, op: TimelineOperation) -> None: + """Verify opening and the active catalog without creating state. + + Parameters + ---------- + op: TimelineOperation + Creation or resume command. + + """ + _require(self.active is None, "Project opened without closing first.") + catalog = one(op.events, "gui.conversation.catalog.opened").details + rows = catalog.get("conversations") + _require(isinstance(rows, list), "Missing conversation catalog.") + if op.kind == "create_project": + _require(not self.created and len(rows) == 1, + "Reference must begin with one new conversation.") + self.created = True + self._new(rows[0]) + request = op.request["open"] + else: + _require(self.created, "Resume precedes creation.") + request = op.request + identifiers = [_text(row.get("conversation_id")) for row in rows] + _require(len(set(identifiers)) == len(identifiers) and + set(identifiers) == {key for key, item in + self.conversations.items() + if not item.deleted}, + "Catalog differs from reconstructed conversations.") + for row in rows: + self._check_record(row) + self.active = _text(catalog.get("active_conversation_id")) + self._known(self.active) + _require(request.get("conversation_id") == self.active, + "Open request and catalog disagree.") + if request.get("requested_conversation_id") is not None: + _require(request["requested_conversation_id"] == self.active, + "Resume selected a different conversation.") + one(op.events, "conversation.restored") + + def _selection(self, op: TimelineOperation, previous: str) -> None: + """Check the selected identity and its restoration event. + + Parameters + ---------- + op: TimelineOperation + Command that switches the active conversation. + previous: str + Previously active conversation. + + """ + result = one(op.events, "gui.conversation.selected").details + _require(result.get("previous_conversation_id") == previous and + result.get("conversation_id") == self.active, + "Selection result differs from requested transition.") + self._check_record(result) + one(op.events, "conversation.restored") + + def _restored(self, event: TraceEvent) -> None: + """Check restored turns and checkpoint against reconstructed state. + + Parameters + ---------- + event: TraceEvent + Core conversation restoration diagnostic. + + """ + item = self._known(self.active) + data = event.details + _require(data.get("turn_uuids") == item.turns and + type(data.get("turn_count")) is int and + data["turn_count"] == len(item.turns) and + data.get("checkpoint_id") == item.checkpoint, + "Restored history differs from committed history.") + # Archived files have their final location even for older events. + state = self.recording.states.get(event.path, {}) + _require(state.get("conversation_id") == self.active, + "Restoration was written to a different conversation.") + + def _delete(self, op: TimelineOperation) -> None: + """Verify archive identity and any replacement conversation. + + Parameters + ---------- + op: TimelineOperation + Recorded deletion command. + + """ + previous = self.active + identifier = _text(op.request.get("conversation_id")) + item = self._known(identifier) + result = one(op.events, "gui.conversation.deleted").details + _require(result.get("conversation_id") == identifier and + result.get("deleted_active") is (identifier == previous), + "Invalid deletion result.") + archive = _text(result.get("archived_path")) + safe_path(self.recording.root, archive) + _require(Path(archive).parent.as_posix() == "logs/traces/.deleted", + "Invalid archive location.") + item.path, item.deleted = archive, True + replacement = result.get("replacement") + _require(isinstance(replacement, dict) and + type(result.get("replacement_created")) is bool, + "Missing deletion replacement result.") + if result["replacement_created"]: + _require(all(c.deleted for c in self.conversations.values()), + "Unexpected replacement creation.") + self.active = self._new(replacement) + else: + self._check_record(replacement) + self.active = replacement["conversation_id"] + if identifier != previous: + _require(self.active == previous, + "Deleting an inactive chat changed selection.") + else: + self._selection(op, previous) + + def _question(self, op: TimelineOperation) -> None: + """Validate the request, exact question, and its durable checkpoint. + + Parameters + ---------- + op: TimelineOperation + Question command and correlated core turn events. + + """ + request = op.request + _require(request.get("conversation_id") == self.active, + "Question targets the wrong active conversation.") + item = self._known(self.active) + question = _text(request.get("question")).strip() + _require(bool(question) and isinstance(request.get("title_question"), + str), "Invalid question text.") + _require(isinstance(request.get("generation_settings"), dict) and + isinstance(request.get("explicit_generation_settings"), dict) + and isinstance(request.get("profile_generation_settings"), + dict), "Missing question settings provenance.") + start = one(op.events, "gui.question.request.started") + resolved = one(op.events, "gui.question.settings.resolved") + core = one(op.events, "turn.started") + effective = one(op.events, "turn.settings.snapshot") + _require(core.sequence < effective.sequence and + effective.metadata.get("turn_id") == + core.metadata.get("turn_id") and + resolved.details.get("chat_model") == + effective.details.get("chat_model") and + (resolved.details.get("retrieval_count") is None or + resolved.details["retrieval_count"] == + effective.details.get("retrieval_count")), + "Resolved question settings disagree with core turn.") + end = one(op.events, "turn.completed") + committed = one(op.events, "state.checkpoint.committed") + saved = one(op.events, "gui.question.saved") + _require(start.sequence < resolved.sequence < core.sequence < + committed.sequence < end.sequence < saved.sequence and + core.metadata.get("parent_span_id") == start.span_id and + core.path == start.path == committed.path == saved.path and + core.metadata.get("turn_id") == + committed.metadata.get("turn_id") and + saved.span_id == start.span_id, + "Uncorrelated question, turn, or checkpoint.") + _require(self.recording.states.get(start.path, {}).get( + "conversation_id") == self.active, + "Question stored in another conversation trace.") + _require(core.details.get("question") == question and + core.details.get("question_sha256") == sha256( + question.encode("utf-8")).hexdigest(), + "Core question differs from recorded request.") + data = committed.details + uid = require_turn_uuid(data.get("conversation_turn_uuid")) + checkpoint = _text(data.get("checkpoint_id")) + _require(uid not in self.questions and checkpoint not in + self.checkpoints and data.get("parent_checkpoint_id") == + item.checkpoint and data.get("immutable_state_saved") is True + and type(data.get("turn_count")) is int and + data["turn_count"] == len(item.turns) + 1, + "Invalid checkpoint identity or lineage.") + _require(all(saved.details.get(k) == data.get(k) for k in ( + "conversation_turn_uuid", "turn_count", "checkpoint_id")), + "GUI save result disagrees with core checkpoint.") + self.questions[uid] = question + self.checkpoints.add(checkpoint) + item.turns.append(uid) + item.checkpoint = checkpoint + _interactions(op, core) + + def _feedback(self, op: TimelineOperation) -> None: + """Check feedback mutations against the referenced committed turn. + + Parameters + ---------- + op: TimelineOperation + Feedback or memory-exclusion command. + + """ + request = op.request + item = self._known(request.get("conversation_id")) + uid = require_turn_uuid(request.get("turn_uuid")) + role = request.get("role") + _require(uid in item.turns and role in ("user", "assistant"), + "Feedback references an unavailable turn or role.") + result = one(op.events, "gui.conversation.feedback.saved" if + op.kind == "feedback" else + "gui.conversation.memory_exclusion.saved").details + _require(all(result.get(k) == request.get(k) for k in ( + "conversation_id", "turn_uuid", "role")), + "Feedback result targets another message.") + revision = request.get("expected_revision") + _require(revision is None or revision == self.feedback_revision, + "Feedback revision does not follow previous mutation.") + key = uid, role + before = self.ratings.get(key, MessageFeedback()) + values = asdict(before) + fields = ("saved", "reaction") if op.kind == "feedback" else ( + "excluded",) + for name in fields: + if request.get(name) is not None: + values[name] = request[name] + rating = MessageFeedback(**values) + _require(result.get("rating") == asdict(rating), + "Committed feedback differs from requested mutation.") + self.ratings[key] = rating + self.feedback_revision = _text(result.get("revision")) + + def generated_title(self, event: TraceEvent) -> None: + """Apply a generated name as observed state, never as a command. + + Parameters + ---------- + event: TraceEvent + Generated title diagnostic. + + """ + identifier = event.details.get("conversation_id") + item = self._known(identifier) + _require(identifier == self.active and item.turns, + "Generated title without a committed active conversation.") + item.name = _text(event.details.get("name")) + + def finish(self) -> None: + """Compare archived and active states and final feedback to history.""" + recording = self.recording + if self.active is not None: + recording.issue("project.unclosed", "Close the reference project.") + actual = {} + copies = {} + for path, state in recording.states.items(): + try: + validate_conversation_state(state) + identifier = _text(state.get("conversation_id")) + _require(identifier not in actual, + "Duplicate conversation ID.") + actual[identifier] = path + item = self.conversations.get(identifier) + _require(item is not None, "Unrecorded conversation.") + _require(item.path == path and item.name == state.get("name") + and item.parent == state.get("parent_conversation_id") + and item.origin_count == state.get( + "origin_turn_count") + and item.origin_checkpoint == + state.get("origin_checkpoint_id"), + "Final conversation metadata differs from history.") + turns = state.get("turns", []) + _require([t["conversation_turn_uuid"] for t in turns] == + item.turns and state.get("checkpoint_id") == + item.checkpoint, "Final turn/checkpoint mismatch.") + for turn in turns: + uid = turn["conversation_turn_uuid"] + _require(turn.get("question") == self.questions.get(uid) + and isinstance(turn.get("answer"), str) + and isinstance(turn.get("parameters"), dict) + and isinstance(turn.get("evidence"), list), + "Saved turn does not match recorded input.") + _require(uid not in copies or copies[uid] == turn, + "Inherited turn content differs across branches.") + copies[uid] = turn + if item.checkpoint is not None: + checkpoint = state.get("checkpoint") + _require(isinstance(checkpoint, dict) and + checkpoint.get("checkpoint_id") == item.checkpoint + and type(checkpoint.get("turn_count")) is int + and checkpoint["turn_count"] == len(turns), + "Invalid saved checkpoint metadata.") + else: + _require(state.get("checkpoint") is None, + "Checkpoint exists without recorded identity.") + except (ValueError, KeyError, TypeError, AttributeError) as error: + recording.issue("conversation.state", str(error), path) + for identifier in sorted(set(self.conversations) - set(actual)): + recording.issue("conversation.missing", f"Missing {identifier}.", + self.conversations[identifier].path) + try: + feedback = safe_path(recording.root, "memory/feedback.json") + if feedback.exists(): + read_json(recording.root, "memory/feedback.json") + snapshot = FeedbackStore(recording.root).load() + observed = {(uid, role): rating for uid, values in + snapshot.entries.items() for role, rating in + values.items()} + expected = {key: rating for key, rating in self.ratings.items() + if rating != MessageFeedback()} + _require(observed == expected and snapshot.revision == + self.feedback_revision, + "Final feedback differs from recorded mutations.") + except (ValueError, OSError, TypeError) as error: + recording.issue("feedback.state", str(error), + "memory/feedback.json") + + +def _interactions(op: TimelineOperation, core: TraceEvent) -> None: + """Verify proposal/decision pairs and semantic user responses. + + Parameters + ---------- + op: TimelineOperation + Question with all recorded interaction events. + core: TraceEvent + Owning core turn start. + + """ + pending = {} + seen = set() + for event in op.events: + prefix, _, suffix = event.event_type.rpartition(".") + if prefix not in ("routing.choice", "tool.choice", "tool.plan"): + continue + if suffix not in ("proposed", "decided", "failed"): + continue + data = event.details + identifier = _text(data.get("interaction_id")) + _require(event.path == core.path and event.metadata.get("turn_id") + == core.metadata.get("turn_id"), + "Interaction is not correlated to the core turn.") + if suffix == "proposed": + _require(identifier not in seen and not pending, + "Repeated or overlapping interaction.") + _require(type(data.get("asked")) is bool, + "Missing interaction callback policy.") + seen.add(identifier) + pending[identifier] = event + continue + proposal = pending.pop(identifier, None) + _require(proposal is not None and proposal.event_type == + prefix + ".proposed", "Interaction lacks matching proposal.") + _require(suffix == "decided", "Interactive callback failed.") + request = proposal.details + asked = request["asked"] + _require(data.get("asked") is asked, "Interaction policy changed.") + if prefix == "tool.plan": + choices = _strings(request.get("choices")) + choice = data.get("choice") + _require(choice in choices and choice in ("continue", "quick") + and data.get("policy") == request.get("policy") and + (data.get("response") == choice if asked else + choice == "continue" and data.get("response") is None), + "Invalid or cancelled plan choice.") + else: + _require(isinstance(request.get("question"), str) and + type(request.get("allow_cancel")) is bool and + isinstance(request.get("options"), list), + "Invalid recorded option proposal.") + options = [_text(value) for value in request["options"]] + index = data.get("index") + if asked: + _require(type(index) is int and 0 <= index < len(options) + and data.get("response") == index and + data.get("selected_option") == options[index] and + options.count(options[index]) == 1, + "Invalid, ambiguous or cancelled option choice.") + else: + _require(index is None and data.get("selected_option") is None + and data.get("response") is None, + "Automatic choice has a user response.") + _require(not pending, "Interaction proposal has no terminal decision.") + + +def _differences(defaults: dict, requested: dict) -> dict: + """Check the historical sparse-override classification. + + Parameters + ---------- + defaults: dict + Defaults actually displayed in the original environment. + requested: dict + Full submitted settings, not present-day defaults. + + Returns + ------- + dict + Recursively differing fields, treating lists as atomic. + + """ + changes = {} + for key, value in requested.items(): + if isinstance(value, dict) and isinstance(defaults.get(key), dict): + nested = _differences(defaults[key], value) + if nested: + changes[key] = nested + elif key not in defaults or defaults[key] != value: + changes[key] = value + return changes + + +def _creation_checks(op: TimelineOperation) -> None: + """Require the current complete-recording marker and settings provenance. + + Parameters + ---------- + op: TimelineOperation + Recorded creation command. + + """ + settings = one(op.events, "gui.project.creation.settings").details + _require(type(settings.get("operation_recording_version")) is int and + settings["operation_recording_version"] == + OPERATION_RECORDING_VERSION, "Unsupported recording version.") + requested = settings.get("requested_settings") + explicit = settings.get("explicit_settings") + _require(isinstance(requested, dict) and isinstance(explicit, dict), + "Creation settings provenance is unavailable.") + if settings.get("provenance") == "explicit_request": + _require(explicit == requested, "Explicit creation settings differ.") + else: + defaults = settings.get("displayed_defaults") + _require(settings.get("provenance") == "displayed_defaults" and + isinstance(defaults, dict) and explicit == + _differences(defaults, requested), + "Creation defaults and explicit overrides disagree.") + + +def _operation_checks(op: TimelineOperation) -> None: + """Require indexing, settings and source outcome coverage per command. + + Parameters + ---------- + op: TimelineOperation + Supported command with its correlated diagnostics. + + """ + kind = op.kind + needs_index = kind in ("create_project", "open_project", "sync_sources") + if kind == "create_project": + _creation_checks(op) + if kind in ("create_project", "open_project"): + config = one(op.events, "gui.project.configuration.effective").details + _require(all(key in config for key in ( + "profile", "effort_levels", "router_models", "search_depth", + "source_cards", "behavior", "tools")), + "Missing effective project configuration.") + if kind == "add_sources": + result = one(op.events, "gui.sources.add.completed").details + _strings(op.request.get("sources")) + new = _strings(result.get("new_sources")) + batches = op.matching("workspace.prepare.started") + _require(len(batches) == bool(new) and + (not new or batches[0].details.get("operation") == "import" + and batches[0].details.get("source_paths") == new), + "Source addition lacks matching import batch.") + decisions = op.request.get("decisions") + _require(result.get("decisions") == decisions and + len(op.matching("workspace.sync.started")) == bool(decisions), + "Source addition lacks matching synchronization batch.") + needs_index = bool(new or decisions) + if kind in ("add_sources", "sync_sources") and needs_index: + one(op.events, "gui.sources.refreshed") + if needs_index: + first = one(op.events, "indexing.started") + last = one(op.events, "indexing.completed") + scan = one(op.events, "source.scan.completed") + result = one(op.events, "index.rebuilt", "index.reused", + "index.empty") + _require(first.sequence < scan.sequence < result.sequence < + last.sequence and first.span_id == last.span_id and + scan.details.get("complete") is True, + "Incomplete or uncorrelated index preparation.") + manifest = (result if result.event_type == "index.empty" else + one(op.events, "index.check.completed")) + _require(scan.sequence < manifest.sequence <= result.sequence and + set(_strings(scan.details.get("selected_files"))) == + set(_manifest_files(manifest.details.get("source_manifest"))), + "Source scan differs from historical content manifest.") + for event in op.matching("workspace.prepare.completed", + "workspace.sync.completed"): + _require(event.sequence < first.sequence, + "Indexing precedes completion of source import.") + if kind == "ask": + request = op.request + explicit = request.get("explicit_generation_settings") + settings = request.get("generation_settings") + profile = request.get("profile_generation_settings") + _require(isinstance(settings, dict) and isinstance(explicit, dict) + and isinstance(profile, dict), "Invalid question settings.") + provenance = request.get("generation_provenance") + _require((provenance == "explicit_request" and explicit == settings) + or (provenance == "profile_difference" and explicit == + _differences(profile, settings)), + "Question settings provenance does not match the request.") + # Generation values can be persisted inside an answer request. Other + # persistent setting mutations are not permitted in reference runs. + for event in op.matching("project.configuration.requested"): + changes = event.details.get("requested_settings") + _require(isinstance(changes, dict) and set(changes) <= { + "temperature", "thinking", "max_new_tokens"}, + "Unsupported configuration change inside question.") + + +def _configuration_checks(recording: Recording, + operations: tuple[TimelineOperation, ...]) -> None: + """Check fixed recorded configuration and its saved profile. + + Parameters + ---------- + recording: Recording + Recording and issue collector. + operations: tuple[TimelineOperation, ...] + Candidate command boundaries. + + """ + profile = None + configuration = None + for event in recording.events: + data = event.details + kind = event.event_type + try: + if kind == "gui.project.configuration.effective": + current = data.get("profile") + _require(isinstance(current, dict), + "Missing effective profile.") + if profile is not None: + _require(profile == current, + "Effective profile changed between openings.") + profile = current + # Plugin implementation identity may change between + # closed runtimes without changing persistent settings. + fixed = {k: v for k, v in data.items() + if k not in ("profile", "plugins")} + if isinstance(fixed.get("behavior"), dict): + fixed["behavior"] = {k: v for k, v in + fixed["behavior"].items() + if k != "project"} + _require(configuration is None or configuration == fixed, + "Persistent settings changed between openings.") + configuration = fixed + elif kind == "project.configuration.saved": + _require(profile is not None and data.get("before") == profile + and isinstance(data.get("effective"), dict), + "Saved configuration does not follow prior profile.") + profile = data["effective"] + elif kind in ("project.configuration.requested", + "project.settings.changed"): + _require(any(op.kind == "ask" and op.start_sequence < + event.sequence < op.end_sequence + for op in operations), + "Persistent setting change outside a question.") + elif kind == "gui.models.effort_levels.saved": + _require(any(op.kind == "create_project" and + op.start_sequence < event.sequence < + op.end_sequence for op in operations), + "Effort settings changed after creation.") + elif (kind in ("project.behavior.saved", + "project.tool_settings.saved", + "gui.models.change.requested", + "gui.models.change.applied", + "gui.source_cards.settings.saved") or + kind.startswith(("gui.folder.", "gui.sources.remove."))): + raise ValueError("Unsupported persistent or resource change.") + elif kind == "gui.project.configuration.snapshot.failed": + raise ValueError("Project configuration snapshot failed.") + except (ValueError, TypeError, KeyError) as error: + recording.issue("configuration.history", str(error), + event.path, event.sequence) + try: + profile_path = safe_path(recording.root, "profile.ini") + safe_path(recording.root, "sources") + parser = ConfigParser(interpolation=None) + with profile_path.open(encoding="utf-8") as stream: + parser.read_file(stream) + _require(parser.get("project", "source") == "sources", + "Reference must use its managed source directory.") + project = _read_project( + recording.root, require_registered_type=False, + ) + _require(project.profile.source == "sources" and + project.source == recording.root / "sources", + "Reference must use its managed source directory.") + observed = json.loads(json.dumps(asdict(project.profile))) + _require(profile is not None and observed == profile, + "Saved profile differs from the last recorded profile.") + # Explicit behavior changes are not supported during reference + # preparation. Its revision identifies the saved overrides, not + # current package defaults, which are allowed to evolve. + behavior = safe_path(recording.root, "project_behavior.json") + _require(not behavior.exists() or behavior.is_file(), + "Invalid saved behavior file.") + revision = sha256(behavior.read_bytes() if behavior.is_file() + else b"").hexdigest() + _require(configuration is not None and + isinstance(configuration.get("behavior"), dict) and + configuration["behavior"].get("revision") == revision, + "Saved behavior overrides differ from recorded revision.") + _saved_settings_match(parser, configuration) + overrides = safe_path(recording.root, "source_card_sources.json") + _require(not overrides.exists(), + "Per-source card overrides are not recorded replay inputs.") + except (OSError, ValueError, TypeError, KeyError, AttributeError, + ConfigError) as error: + recording.issue("configuration.state", str(error), "profile.ini") + + +def _saved_settings_match(parser: ConfigParser, configuration: dict) -> None: + """Compare persisted overrides to historical, not current, defaults. + + Parameters + ---------- + parser: configparser.ConfigParser + Saved project profile, read without interpolation. + configuration: dict + Last recorded effective settings apart from the core profile. + + """ + for backend in ("mlx", "torch"): + levels = [] + for index in range(1, 6): + value = parser.get(f"effort.{backend}", f"level{index}") + name, separator, model = value.partition("|") + _require(bool(separator), "Invalid saved effort level.") + levels.append({"name": name.strip(), "model": model.strip()}) + _require(levels == configuration["effort_levels"][backend] and + parser.get("router", backend) == + configuration["router_models"][backend], + "Saved effort or router settings differ from recording.") + depths = [int(value) for value in parser.get("search", "depth").split(",")] + _require(depths == configuration["search_depth"], + "Saved search depth differs from recording.") + tools = {entry["name"]: entry for entry in configuration["tools"]} + saved = {section[5:]: dict(parser.items(section)) + for section in parser.sections() if section.startswith("tool.")} + for name, entries in saved.items(): + _require(name in tools and all( + key in tools[name]["settings"] and + json.loads(value) == tools[name]["settings"][key] + for key, value in entries.items()), + "Saved tool overrides differ from recording.") + for name, entry in tools.items(): + changed = _differences(entry["type_settings"], entry["settings"]) + _require(all(key in saved.get(name, {}) for key in changed), + "Recorded tool overrides are missing from the profile.") + cards = configuration["source_cards"] + policy = "source_cards" + if parser.has_section(policy): + for key in ("enabled", "kind", "automatic"): + if parser.has_option(policy, key): + value = (parser.get(policy, key) or None if key == "kind" + else parser.getboolean(policy, key)) + _require(value == cards["policy"][key], + "Saved source-card policy differs from recording.") + section = "source_card_generation" + for backend, settings in cards["models"].items(): + if parser.has_option(section, backend): + _require(parser.get(section, backend) == settings["model_id"], + "Saved source-card model differs from recording.") + for name, getter in (("thinking", parser.getboolean), + ("temperature", parser.getfloat), + ("max_input_tokens", parser.getint), + ("max_new_tokens", parser.getint)): + if parser.has_option(section, name): + _require(getter(section, name) == settings[name], + "Saved source-card settings differ from recording.") + + +def _environment_warnings(recording: Recording) -> list[ValidationIssue]: + """Report runtime differences without importing model backends. + + Parameters + ---------- + recording: Recording + Original logger environments. + + Returns + ------- + list[ValidationIssue] + Distinct differences from the inspection environment. + + """ + differences = set() + # The executing checkout may differ from installed distribution metadata. + versions: dict[str, str | None] = {"kilin": kilin.__version__} + for event in recording.events: + if event.event_type != "trace.started": + continue + environment = event.details.get("environment") + if not isinstance(environment, dict): + recording.issue("trace.environment", "Missing logger environment.", + event.path, event.sequence) + continue + for key, current in (("python", sys.version), + ("platform", platform.platform())): + recorded = environment.get(key) + if not isinstance(recorded, str): + recording.issue("trace.environment", f"Invalid {key}.", + event.path, event.sequence) + elif recorded != current: + differences.add(f"{key}: recorded {recorded}; local {current}") + packages = environment.get("packages") + if not isinstance(packages, dict): + recording.issue("trace.environment", "Missing package versions.", + event.path, event.sequence) + continue + for name, recorded in packages.items(): + if recorded is not None and not isinstance(recorded, str): + recording.issue("trace.environment", + "Invalid package version.", + event.path, event.sequence) + continue + if name not in versions: + try: + versions[name] = version(name) + except (PackageNotFoundError, ValueError): + versions[name] = None + if recorded != versions[name]: + differences.add(f"{name}: recorded {recorded}; " + f"local {versions[name]}") + return [ValidationIssue("environment.difference", message) + for message in sorted(differences)] + + +def validate_recording(recording: Recording) -> ValidationReport: + """Collect structural, chronological and durable-state inconsistencies. + + Parameters + ---------- + recording: Recording + Decoded snapshot of an offline reference workspace. + + Returns + ------- + ValidationReport + Blocking issues, warnings and the candidate timeline. No models, + GUI components, external source paths or generated indexes are opened. + + """ + _sequence_checks(recording) + operations = build_timeline(recording) + validate_semantic_history(recording, operations) + creations = [op for op in operations if op.kind == "create_project"] + if (len(creations) != 1 or not operations + or operations[0].kind != "create_project"): + recording.issue("creation.missing", "Expected one initial creation.") + sources = _SourceHistory(recording.root) + for event in recording.events: + try: + sources.consume(event) + except (ValueError, OSError, KeyError, TypeError, AttributeError) as e: + recording.issue("source.history", str(e), event.path, + event.sequence) + sources.finish(recording) + history = _ConversationHistory(recording) + titles = iter(e for e in recording.events + if e.event_type == "conversation.title.generated") + title = next(titles, None) + for i, op in enumerate(operations): + try: + _operation_checks(op) + except (ValueError, KeyError, TypeError, AttributeError) as error: + recording.issue("command.coverage", str(error), + sequence=op.start_sequence) + try: + if op.status in ("completed", "committed_with_error"): + history.consume(op) + except (ValueError, KeyError, TypeError, AttributeError) as error: + recording.issue("conversation.history", str(error), + sequence=op.start_sequence) + # Automatic naming is emitted just after the question span closes. + # Do not borrow a later question's title for an earlier operation. + next_start = (operations[i + 1].start_sequence + if i + 1 < len(operations) else float("inf")) + generated = 0 + while title is not None and title.sequence < next_start: + try: + _require(op.kind == "ask" and + op.start_sequence < title.sequence and generated == 0, + "Unmatched generated title.") + history.generated_title(title) + generated += 1 + except (ValueError, KeyError, TypeError, AttributeError) as error: + recording.issue("conversation.title", str(error), title.path, + title.sequence) + title = next(titles, None) + if title is not None: + recording.issue("conversation.title", "Unmatched generated title.", + title.path, title.sequence) + history.finish() + _configuration_checks(recording, operations) + for observation in plugin_observations(tuple(recording.events)): + if observation["status"] == "invalid": + recording.issue("plugin.provenance", observation["error"], + sequence=observation["sequence"]) + warnings = [ValidationIssue( + "recording.limit", "Validation requires a closed, unchanged reference " + "workspace. Unrecorded actions and edits restored before observation " + "cannot always be detected. Model availability is not checked." + )] + warnings.extend(_environment_warnings(recording)) + return ValidationReport(recording.root, tuple(recording.issues), + tuple(warnings), len(recording.events), + tuple(recording.events), operations, + tuple(sorted(sources.files))) diff --git a/kilin/tool_settings.py b/kilin/tool_settings.py index 7cb927b5..f7f9be4b 100644 --- a/kilin/tool_settings.py +++ b/kilin/tool_settings.py @@ -58,10 +58,11 @@ from typing import Final from kilin.atomic_writes import atomic_write_text -from kilin.project import open_project +from kilin.project import QAProject, open_project from kilin.project_type import ProjectTypeId, project_type from kilin.tools import ToolUse -from kilin.tools._registry import TOOL_REGISTRY +from kilin.tools._contract import _validate_tool_policies +from kilin.tools._registry import _parse_settings, registered_tools from kilin.trace_logging import NullTraceLogger, TraceSink __all__ = [ @@ -106,9 +107,10 @@ def project_tool_settings( tools = [] for name, uses in _tool_uses(project.profile.type_id).items(): _, type_settings, per_intent = _split_settings(uses) + _validate_effective(project, name, uses, saved.get(name, {})) tools.append({ "name": name, - "summary": TOOL_REGISTRY[name].summary, + "summary": registered_tools()[name].summary, "intents": list(uses), "settings": {**type_settings, **saved.get(name, {})}, "type_settings": type_settings, @@ -166,10 +168,6 @@ def save_tool_settings( f"{name}: {', '.join(fixed)} cannot be changed for the project." ) values = _json_values(settings) - for use in uses.values(): - TOOL_REGISTRY[name].parse_settings( - {**_json_values(asdict(use.settings)), **values}, name - ) changed = { key: value for key, value in values.items() @@ -180,11 +178,13 @@ def save_tool_settings( parser = ConfigParser(interpolation=None) parser.read(path, encoding="utf-8") section = f"{TOOL_SECTION_PREFIX}{name}" + before = _saved_settings(project.root).get(name, {}) kept = { key: value - for key, value in _saved_settings(project.root).get(name, {}).items() + for key, value in before.items() if key not in values } + _validate_effective(project, name, uses, {**kept, **changed}) parser.remove_section(section) if kept or changed: parser.add_section(section) @@ -196,7 +196,11 @@ def save_tool_settings( active_trace.emit( "project.tool_settings.saved", component="project", - data={"tool": name, "changed": {**kept, **changed}}, + data={ + "tool": name, "changed": {**kept, **changed}, + "requested": values, "before": before, + "effective": {**type_settings, **kept, **changed}, + }, ) return project_tool_settings(project.root) @@ -227,13 +231,63 @@ def with_project_settings(root: Path, use: ToolUse) -> ToolUse: saved = _saved_settings(root).get(use.name) if not saved: return use - return ToolUse( - use.name, - TOOL_REGISTRY[use.name].parse_settings( - {**_json_values(asdict(use.settings)), **saved}, - f"profile.ini [{TOOL_SECTION_PREFIX}{use.name}]", - ), + tool = registered_tools()[use.name] + parsed = _parse_settings( + tool, {**_json_values(asdict(use.settings)), **saved}, + f"profile.ini [{TOOL_SECTION_PREFIX}{use.name}]", ) + if tool.source_policies is not None: + _validate_accepted_policies(open_project(root), use.name, parsed) + return ToolUse(use.name, parsed) + + +def _validate_accepted_policies( + project: QAProject, name: str, settings: object, +) -> None: + """Validate tool policies without adopting newer installed settings. + + Parameters + ---------- + project: QAProject + Workspace owning the accepted vocabulary. + name: str + Registered tool identifier. + settings: object + Parsed effective settings for one use of the tool. + + """ + tool = registered_tools()[name] + if tool.source_policies is not None: + from kilin.source_manifest import read_source_manifest + + declaration = read_source_manifest(project).manifest.organization + _validate_tool_policies(tool, settings, declaration.declaration) + + +def _validate_effective( + project: QAProject, name: str, uses: dict[str, ToolUse], + overrides: dict[str, object], +) -> None: + """Validate every intent against the merged persisted overrides. + + Parameters + ---------- + project: QAProject + Workspace owning accepted organization settings. + name: str + Registered tool identifier. + uses: dict[str, ToolUse] + Per-intent base settings. + overrides: dict[str, object] + Complete proposed project overrides, including retained values. + + """ + tool = registered_tools()[name] + for use in uses.values(): + parsed = _parse_settings( + tool, {**_json_values(asdict(use.settings)), **overrides}, name, + ) + _validate_accepted_policies(project, name, parsed) def _tool_uses(type_id: ProjectTypeId) -> dict[str, dict[str, ToolUse]]: diff --git a/kilin/tools/__init__.py b/kilin/tools/__init__.py index 1ed716ef..3764dd68 100644 --- a/kilin/tools/__init__.py +++ b/kilin/tools/__init__.py @@ -12,10 +12,9 @@ ``_shared/``. Tool packages can own their ``defaults.json``, helper modules, and templates. Every registered executable tool is a package. -This package re-exports the contract, the planning vocabulary, the -registry, and the names other modules use from ``batch_classify`` and -``scan_and_list``. Other tools and helpers are reached through their own -submodules. +This package exposes the public tool API and planning vocabulary without +constructing the registry. Catalog queries load definitions on demand. +The plugin API version is independent of the application version. Key Features ------------ @@ -86,7 +85,47 @@ Module Structure ---------------- -- ``EarlierTurn``, ``ToolRequest``, ``ToolContext``, and ``ToolResult`` +- ``PLUGIN_API_VERSION`` + + Independent generation of the authoring contract. + +- ``registered_tools`` and ``tool_choices`` + + Explicit queries for the process-local catalog. + +- ``Tool``, ``ToolRouting``, and ``WorkspaceResource`` + + Registration, routing, and resource declarations. + +- ``ask_choice`` and ``confirm_plan`` + + Recorded user interactions. + +- ``selected_paths``, ``selected_source_file``, and ``save_output_file`` + + Source inventory, contained file lookup, and non-overwriting output. + +- ``partial_result``, ``IncompleteModelResponse``, ``GenerationCancelled`` + + Explicit model failures and partial results, separate from cancellation. + +- ``Chunk``, ``CodeEntity``, ``CodeGraph``, ``CodeRelation``, + ``HybridResult``, ``EvidenceLimits``, ``RetrievalRequest``, + ``RetrievalResult``, and ``Suggestion`` + + Data records exchanged through the tool context. + +- ``SourceScope``, ``SourcePolicy``, ``SourceView``, ``SourceGroup``, + ``SourceOperation``, and physical inventory/coverage records + + Immutable source-view declarations and operation membership services. + +- ``check_bool``, ``check_choice``, ``check_int``, and ``reject_unknown`` + + Settings-validation helpers. + +- ``EarlierTurn``, ``ToolRequest``, ``ToolContext``, ``ToolTrace``, + and ``ToolResult`` What a tool receives and returns (from ``_contract``). @@ -111,14 +150,10 @@ - ``TOOL_BATCH_CLASSIFY``, ``TOOL_BATCH_REVIEW``, ``TOOL_GENERATE_PAPER_SUMMARY``, ``TOOL_PROJECT_INVENTORY``, - ``TOOL_SCAN_AND_LIST``, ``TOOL_CHOICES``, and ``ToolName`` + ``TOOL_SCAN_AND_LIST`` and ``ToolName`` Registered tool names (from ``_registry``). -- ``TOOL_REGISTRY`` - - Map from each tool name to its registered tool. - - ``Tool`` and ``ToolUse`` One registered tool, and an intent's tool with validated settings. @@ -127,55 +162,72 @@ Validate an intent's ``tool`` object, and run it. -- ``CANDIDATES_MENTIONS``, ``CANDIDATE_CHOICES``, and ``CandidateSource`` - - How ``batch_classify`` collects the items it labels. - -- ``ClassifySettings`` - - Settings of ``batch_classify`` in a project type. - -- ``UNCLEAR`` and ``Label`` - - The always-offered category, and the category given to one mention. - -- ``MAX_TERMS`` - - Most terms ``scan_and_list`` scans for in one question. - -- ``ScanSettings`` - - Settings of ``scan_and_list`` in a project type. - -- ``Mention`` and ``MentionScan`` - - One occurrence of a term, and all mentions found. - -- ``scan_mentions`` - - Find every occurrence of the terms in the indexed text. - Examples -------- ->>> from kilin.tools import TOOL_REGISTRY, TOOL_SCAN_AND_LIST ->>> print(TOOL_REGISTRY[TOOL_SCAN_AND_LIST].summary) +>>> from kilin.tools import registered_tools, TOOL_SCAN_AND_LIST +>>> print(registered_tools()[TOOL_SCAN_AND_LIST].summary) List and count every exact mention of the question's terms. """ -from kilin.tools.batch_classify import ( - CANDIDATE_CHOICES, - CANDIDATES_MENTIONS, - UNCLEAR, - CandidateSource, - ClassifySettings, - Label, +from importlib import import_module + +from kilin._model_completion import ( + GenerationCancelled, + IncompleteModelResponse, +) +from kilin.chunking import Chunk +from kilin.retrievals import CodeEntity, CodeGraph, CodeRelation, HybridResult +from kilin.retrievals.evidence_budget import EvidenceLimits +from kilin.retrievals.requests import ( + RetrievalRequest, RetrievalResult, SourceGroupCoverage, group_coverage, +) +from kilin.source_views import ( + ScopeMode, + SourcePurpose, + SourceScope, + SourcePolicy, + SourceFileState, + SourceInventory, + SourceOperation, + SourceView, + SourceGroup, + UnavailableMember, + SourceViewConflict, + capture_source_inventory, + resolve_source_view, + validate_source_view, + validate_source_policy, + read_source_bytes, +) +from kilin.workspace_resources import ( + WorkspaceResource, + template_resource, + templates_folder, ) from kilin.tools._contract import ( + PLUGIN_API_VERSION, EarlierTurn, + Tool, ToolContext, + ToolSourceServices, + require_source_services, + check_source_ids, + ToolName, ToolRequest, + ToolTrace, ToolResult, + ToolRouting, + ToolUse, + check_bool, + check_choice, + check_int, + reject_unknown, +) +from kilin.tools._shared.model_results import partial_result +from kilin.tools._shared.source_access import ( + selected_paths, + selected_source_file, ) from kilin.tools._shared.planning import ( CONFIRMATION_ALWAYS, @@ -189,68 +241,126 @@ ConfirmationPolicy, PlanChoice, ToolPlan, + ask_choice, + confirm_plan, needs_confirmation, ) from kilin.tools._registry import ( TOOL_BATCH_CLASSIFY, TOOL_BATCH_REVIEW, - TOOL_CHOICES, TOOL_GENERATE_PAPER_SUMMARY, TOOL_PROJECT_INVENTORY, - TOOL_REGISTRY, TOOL_SCAN_AND_LIST, - Tool, - ToolName, - ToolUse, parse_tool, + registered_tools, run_tool, -) -from kilin.tools.scan_and_list import ( - MAX_TERMS, - Mention, - MentionScan, - ScanSettings, - scan_mentions, + tool_choices, ) __all__ = [ - "CANDIDATES_MENTIONS", - "CANDIDATE_CHOICES", + "PLUGIN_API_VERSION", + "Chunk", + "CodeEntity", + "CodeGraph", + "CodeRelation", + "EvidenceLimits", + "GenerationCancelled", + "HybridResult", + "IncompleteModelResponse", + "RetrievalRequest", + "RetrievalResult", + "ScopeMode", + "SourcePurpose", + "SourceScope", + "SourcePolicy", + "SourceFileState", + "SourceInventory", + "SourceOperation", + "SourceView", + "SourceGroup", + "UnavailableMember", + "SourceViewConflict", + "capture_source_inventory", + "resolve_source_view", + "validate_source_view", + "validate_source_policy", + "read_source_bytes", + "SourceGroupCoverage", + "group_coverage", + "Suggestion", + "ToolRouting", + "WorkspaceResource", + "template_resource", + "templates_folder", + "ask_choice", + "check_bool", + "check_choice", + "check_int", + "confirm_plan", + "registered_tools", + "partial_result", + "selected_paths", + "selected_source_file", + "save_output_file", + "reject_unknown", + "tool_choices", "CONFIRMATION_ALWAYS", "CONFIRMATION_CHOICES", "CONFIRMATION_NEVER", "CONFIRMATION_WHEN_LARGE", - "MAX_TERMS", "PLAN_CHOICE_CANCEL", "PLAN_CHOICE_CHOICES", "PLAN_CHOICE_CONTINUE", "PLAN_CHOICE_QUICK", "TOOL_BATCH_CLASSIFY", "TOOL_BATCH_REVIEW", - "TOOL_CHOICES", "TOOL_GENERATE_PAPER_SUMMARY", "TOOL_PROJECT_INVENTORY", - "TOOL_REGISTRY", "TOOL_SCAN_AND_LIST", - "UNCLEAR", - "CandidateSource", - "ClassifySettings", "ConfirmationPolicy", "EarlierTurn", - "Label", - "Mention", - "MentionScan", "PlanChoice", - "ScanSettings", "Tool", "ToolContext", + "ToolSourceServices", + "require_source_services", + "check_source_ids", "ToolName", "ToolPlan", "ToolRequest", + "ToolTrace", "ToolResult", "ToolUse", "needs_confirmation", "parse_tool", "run_tool", - "scan_mentions", ] + + +def __getattr__(name: str) -> object: + """Resolve shared public helpers only on demand. + + Parameters + ---------- + name: str + Requested module attribute. + + Returns + ------- + object + The requested deferred export. + + Raises + ------ + AttributeError + If the module does not provide the requested attribute. + + """ + + if name == "Suggestion": + return getattr(import_module("kilin.question_suggestions"), name) + if name == "save_output_file": + return getattr( + import_module("kilin.tools._shared.outputs"), name + ) + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/kilin/tools/_contract.py b/kilin/tools/_contract.py index 62c94f28..03e4ce99 100644 --- a/kilin/tools/_contract.py +++ b/kilin/tools/_contract.py @@ -33,6 +33,11 @@ KíLín's services, including optional bounded retrieval, as plain callables; complete hybrid ranking remains unchanged. +- **Scoped sources** + + Bind an immutable source view to original passages, ranking, cards, + verified raw bytes, and bounded retrieval services. + - **Result** Answer, evidence fields, and a JSON-compatible summary. @@ -45,6 +50,14 @@ Module Structure ---------------- +- ``PLUGIN_API_VERSION`` and ``ToolName`` + + Independent API generation and extensible tool identifier type. + +- ``Tool`` and ``ToolUse`` + + A registration descriptor and an intent's validated settings. + - ``EarlierTurn`` An earlier turn the question points back to. @@ -53,9 +66,17 @@ What the user asked. -- ``ToolContext`` +- ``ToolContext`` and ``ToolTrace`` - KíLín's services, as a tool may use them. + KíLín's services and the tool-facing trace interface. + +- ``ToolSourceServices`` and ``require_source_services`` + + View-bound source access without unscoped fallback. + +- ``check_source_ids`` + + Validate a list of distinct role or relation identifiers. - ``ToolResult`` @@ -83,7 +104,7 @@ Examples -------- ->>> from kilin.tools._contract import ToolRequest, check_int +>>> from kilin.tools import ToolRequest, check_int >>> question = "list every mention of MRI" >>> request = ToolRequest(question, question) >>> check_int("code.intents.x.tool", {"max_calls": 5}, "max_calls", 10, 1, 50) @@ -94,21 +115,42 @@ from __future__ import annotations from collections.abc import Callable, Collection, Mapping, Sequence -from dataclasses import dataclass +from contextlib import AbstractContextManager +from dataclasses import dataclass, field from pathlib import Path -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Final, Protocol, TypeAlias + +from kilin.tools._defaults import load_tool_defaults +from kilin.tools._model_calls import ( + ModelCallSettings, + load_optional_model_call_settings, +) +from kilin.workspace_resources import WorkspaceResource +from kilin.source_organization import SourceOrganization, _identifier +from kilin.source_views import ( + SourceFileState, SourcePolicy, SourceScope, SourceView, + validate_source_policy, +) if TYPE_CHECKING: from kilin.chunking import Chunk from kilin.retrievals import CodeGraph, HybridResult from kilin.retrievals.requests import RetrievalRequest, RetrievalResult from kilin.tools._shared.planning import ToolPlan - from kilin.trace_logging import TraceSink + from kilin.question_suggestions import Suggestion __all__ = [ + "PLUGIN_API_VERSION", + "Tool", + "ToolName", + "ToolUse", "EarlierTurn", "ToolContext", + "ToolSourceServices", + "require_source_services", + "check_source_ids", "ToolRequest", + "ToolTrace", "ToolResult", "ToolRouting", "check_bool", @@ -118,6 +160,11 @@ ] +# The API generation does not track the KíLín distribution version. +PLUGIN_API_VERSION: Final[int] = 1 +ToolName: TypeAlias = str + + @dataclass(frozen=True, slots=True) class EarlierTurn: """An earlier turn the question points back to. @@ -184,6 +231,133 @@ class ToolRequest: earlier: tuple[EarlierTurn, ...] = () +class ToolTrace(Protocol): + """The subset of the conversation trace supported for tool authors. + + The host owns the trace lifetime, persistence, and turn correlation. + A disabled trace supports the same operations without writing events. + + """ + + @property + def include_content(self) -> bool: + """Whether the user's trace policy permits content in diagnostics. + + Returns + ------- + bool + True when tool diagnostics may include source or prompt text. + + """ + + ... + + def emit( + self, + event_type: str, + *, + component: str, + data: Mapping[str, object] | None = None, + status: str = "completed", + turn_id: str | None = None, + ) -> None: + """Record an event through the host's trace sink. + + Parameters + ---------- + event_type: str + Nonempty, conventionally dot-separated event name. + component: str + Nonempty subsystem identifier, normally ``"tool"``. + data: Mapping[str, object] | None, optional + JSON-compatible diagnostic fields. Defaults to ``None``. + status: str, optional + Event status. Defaults to ``"completed"``. + turn_id: str | None, optional + Active turn identifier, normally ``context.trace_turn_id``. + + """ + + ... + + def span( + self, + event_type: str, + *, + component: str, + data: Mapping[str, object] | None = None, + turn_id: str | None = None, + ) -> AbstractContextManager[str]: + """Record the lifetime of an operation and propagate its failures. + + Parameters + ---------- + event_type: str + Nonempty operation name, conventionally dot-separated. + component: str + Nonempty subsystem identifier, normally ``"tool"``. + data: Mapping[str, object] | None, optional + JSON-compatible diagnostic fields. Defaults to ``None``. + turn_id: str | None, optional + Active turn identifier, normally ``context.trace_turn_id``. + + Returns + ------- + contextlib.AbstractContextManager[str] + Context manager yielding the span identifier. + + """ + + ... + + +@dataclass(frozen=True, slots=True) +class ToolSourceServices: + """Bind source operations to one immutable, host-resolved view. + + Attributes + ---------- + view: SourceView + Accepted semantic and physical generation and allowed members. + chunks: tuple[Chunk, ...] + Original indexed passages for the view's ranking purpose, in + physical index order. Raw-only views expose no indexed passages. + rank: Callable[[str], list[HybridResult]] + Rank only authorized original passages before rank fusion. + retrieve: Callable[[RetrievalRequest], RetrievalResult] + Bounded retrieval; requests must use this view and its scope. + card: Callable[[pathlib.Path], Mapping[str, str] | None] + Read indexed metadata for an eligible independent anchor. + read_bytes: Callable[[pathlib.Path], bytes] + Return content-verified bytes of an evidence or lookup member. + validate: Callable[[], None] + Reject an operation whose semantic or physical state has changed. + Call before publishing any derived output. + + Notes + ----- + The host provides the callbacks. This is a provenance contract for + trusted tools, not a sandbox for arbitrary Python plugins. + + """ + + view: SourceView + chunks: tuple[Chunk, ...] + rank: Callable[[str], list[HybridResult]] + retrieve: Callable[[RetrievalRequest], RetrievalResult] + card: Callable[[Path], Mapping[str, str] | None] + read_bytes: Callable[[Path], bytes] + validate: Callable[[], None] + + @property + def files(self) -> tuple[SourceFileState, ...]: + """Return physical member identities, including unindexed files.""" + names = {path.as_posix() for path in + (*self.view.evidence, *self.view.lookup)} + return tuple(item for item in self.view.operation.inventory.files + if item.path.as_posix() in names) + + @dataclass(frozen=True, slots=True) class ToolContext: """KíLín's services, as a tool may use them. @@ -194,11 +368,13 @@ class ToolContext: The project folder (``outputs/`` and ``templates/`` live here; see ``kilin.tools._shared.outputs`` and the report-summary tool). chunks: Sequence[Chunk] - Every indexed chunk, in index order. + Every indexed chunk, in index order, for physical inventory tools. + Scoped consumers use ``source_view`` instead. graph: CodeGraph The project's code graph (empty without code). rank: Callable[[str], list[HybridResult]] Ranks every chunk for a text with the fused search channels. + This physical service is not appropriate for a scoped operation. retrieval_count: int The project's retrieval count, for "top results" decisions. unsearchable: Callable[[list[pathlib.Path]], list[pathlib.Path]] @@ -206,7 +382,8 @@ class ToolContext: no indexed text (for coverage reports). source_files: Callable[[], dict[pathlib.Path, int]] Every selected source file (as in the source manifest) with its - size in bytes. + size in bytes. This is intentionally the full physical inventory. + Required callback; returns an empty mapping without selected files. ask_router: Callable[[str, str, int], str] Asks the router model ``(system, prompt, max_new_tokens)`` with thinking off and greedy decoding; the conversation is untouched. @@ -239,7 +416,7 @@ class ToolContext: confirm: Callable[[ToolPlan], str] | None Asks the user to confirm a plan and returns ``continue``, ``quick``, or ``cancel``; None runs every plan. - trace: TraceSink + trace: ToolTrace The conversation's trace; emit events with ``trace_turn_id``. trace_turn_id: str | None The turn the tool runs for. @@ -259,7 +436,7 @@ class ToolContext: source_root: pathlib.Path | None, optional Saved project source directory. The selected-source reader rejects this path when it is outside the project workspace. Defaults to - ``None`` for legacy test contexts. + ``None`` when no source directory is supplied. model_attempt_count: Callable[[], int] | None, optional Cumulative number of internal answering-model generation attempts, including incomplete attempts and bounded recovery, for this tool @@ -278,7 +455,7 @@ class ToolContext: decoding, such as whether the passages found answer the question; the conversation is untouched. None for contexts without it, where tools fall back to ``ask_router``. Defaults to ``None``. - suggestions: Callable[[], Sequence[object]] | None, optional + suggestions: Callable[[], Sequence[Suggestion]] | None, optional Returns the project's suggested questions, each with ``intent`` and ``question`` (``kilin.question_suggestions.Suggestion``), possibly several per intent, without those of the intent being answered; @@ -287,6 +464,11 @@ class ToolContext: fixed_suggestions: tuple[str, ...], optional The project type's fixed example requests, for a project without sources. Defaults to ``()``. + source_view: Callable | None, optional + Bind scoped operations to one captured generation for this tool + run. None when the host cannot provide these services. A tool + requiring them must fail explicitly, not fall back to ``rank`` or + ``chunks``. """ @@ -304,7 +486,7 @@ class ToolContext: progress: Callable[..., None] done: Callable[..., None] confirm: Callable[[ToolPlan], str] | None - trace: TraceSink + trace: ToolTrace trace_turn_id: str | None write_pdf: Callable[..., int] | None = None choose: Callable[[str, tuple[str, ...]], int | None] | None = None @@ -313,8 +495,51 @@ class ToolContext: source_root: Path | None = None card: Callable[[Path], Mapping[str, str] | None] | None = None ask_check: Callable[[str, str, int], str] | None = None - suggestions: Callable[[], Sequence[object]] | None = None + suggestions: Callable[[], Sequence[Suggestion]] | None = None fixed_suggestions: tuple[str, ...] = () + source_view: ( + Callable[[SourcePolicy, SourceScope], ToolSourceServices] | None + ) = None + + +def require_source_services( + context: ToolContext, policy: SourcePolicy = SourcePolicy(), + scope: SourceScope = SourceScope(), +) -> ToolSourceServices: + """Request a scoped service, never an implicit physical fallback. + + Parameters + ---------- + context: ToolContext + Active tool host services. + policy: SourcePolicy, optional + Effective source policy, document discovery by default. + scope: SourceScope, optional + Explicit scope, project-wide by default. + + Returns + ------- + ToolSourceServices + Bound source services for this operation. + + Raises + ------ + RuntimeError + If the host does not supply the requested policy and scope. + + """ + bind = getattr(context, "source_view", None) + if not callable(bind): + raise RuntimeError("Scoped access requires ToolContext.source_view.") + result = bind(policy, scope) + if not isinstance(result, ToolSourceServices): + raise RuntimeError("Host did not return scoped source services.") + operation = result.view.operation + if (operation.policy != policy or operation.scope.mode != scope.mode + or tuple(p.as_posix() for p in operation.scope.paths) + != tuple(p.as_posix() for p in scope.paths)): + raise RuntimeError("Host returned a different policy or scope.") + return result @dataclass(frozen=True, slots=True) @@ -351,7 +576,8 @@ class ToolRouting: """Routing a tool adds to its intent for one project. A tool whose use depends on the project's own files (the report - templates in ``templates/``) describes them for routing, so a new file + templates under ``templates//``) describes them for routing, + so a new file is routed to without editing the project type. Attributes @@ -368,6 +594,147 @@ class ToolRouting: description: str = "" +@dataclass(frozen=True, slots=True) +class Tool: + """Describe one tool for registration. + + Attributes + ---------- + name: ToolName + Name used in project types. + summary: str + What the tool does, for documentation and listings. + parse_settings: Callable[[dict, str], object] + Validates the tool's settings from a project type and returns a + dataclass with JSON-compatible fields. + run: Callable[[object, ToolRequest, ToolContext], ToolResult] + Runs the tool with validated settings. + follows_up: bool + True when the tool works on an earlier answer, so a question + routed to it always relates to an earlier turn. Automatic routing + omits the tool's intents when no eligible earlier turn exists. + follows_up_when: Callable[[str], bool] | None + For a tool that works on an earlier answer only for some + questions: True for those questions, which then relate to an + earlier turn like ``follows_up`` when one exists. Conditional + follow-ups remain available without earlier turns and are not + ruled out for naming a file. + routing: Callable[[object, Path, tuple[object, ...]], ToolRouting | None] + Optional ``routing(settings, project_root, others)``: cues and a + router description from the project's own files, added to the + intent before routing (``with_project_routing``); ``others`` are + the settings of the project type's other intents using the same + tool, whose cases the routing can leave to them. + model_calls: ModelCallSettings + Tool-owned policy for internal answering-model calls, available + after registration. Absent policies inherit the session. + resource_root: pathlib.Path + Package directory assigned by the registry, not by the author. + workspace_resources: Callable | None + Optional declaration of packaged resources for a new project. + source_policies: Callable[[object], tuple[SourcePolicy, ...]] | None + Optional pure declaration of policies used by validated settings. + The core validates their identifiers against the project type and + the project's accepted vocabulary before running the tool. + version: str + Required independent implementation version (SemVer 2.0.0). + api_version: int + Required integer API generation implemented by the tool, + validated against the supported generation during registration. + + """ + + name: ToolName + summary: str + parse_settings: Callable[[dict, str], object] + run: Callable[[object, ToolRequest, ToolContext], ToolResult] + follows_up: bool = False + follows_up_when: Callable[[str], bool] | None = None + routing: ( + Callable[[object, Path, tuple[object, ...]], ToolRouting | None] + | None + ) = None + workspace_resources: ( + Callable[[object], tuple[WorkspaceResource, ...]] | None + ) = None + source_policies: ( + Callable[[object], tuple[SourcePolicy, ...]] | None + ) = None + version: str = field(kw_only=True) + api_version: int = field(kw_only=True) + + @property + def resource_root(self) -> Path: + """Return the package root assigned by the registry. + + Returns + ------- + pathlib.Path + Absolute directory containing this registered tool's resources. + + Raises + ------ + RuntimeError + If the descriptor has not been bound to an installed package. + + """ + + raise RuntimeError(f"Tool {self.name!r} is not registered.") + + @property + def model_calls(self) -> ModelCallSettings: + """Return the registered tool's validated internal thinking policy. + + Returns + ------- + ModelCallSettings + Cached policy from this tool's own packaged defaults. + + """ + + return load_optional_model_call_settings( + self.resource_root / "defaults.json" + ) + + @property + def internal_defaults(self) -> dict[str, object]: + """Return the tool's packaged defaults other than ``SETTINGS``. + + These sections, such as ``MODEL_CALLS`` or ``ESTIMATES``, belong to + the tool: project types and users cannot change them. + + Returns + ------- + dict[str, object] + The sections by name, empty when the tool has no defaults file. + + """ + + path = self.resource_root / "defaults.json" + if not path.is_file(): + return {} + defaults = load_tool_defaults(path) + defaults.pop("SETTINGS", None) + return defaults + + +@dataclass(frozen=True, slots=True) +class ToolUse: + """An intent's tool with its validated settings. + + Attributes + ---------- + name: ToolName + The tool. + settings: object + The tool's settings dataclass, such as ``ScanSettings``. + + """ + + name: ToolName + settings: object + + def reject_unknown(where: str, data: dict, known: Collection[str]) -> None: """Reject settings a tool does not have. @@ -506,3 +873,60 @@ def check_choice( ) return value + + +def check_source_ids( + where: str, data: Mapping[str, object], key: str, + default: tuple[str, ...] = (), +) -> tuple[str, ...]: + """Read distinct role or relation identifiers without normalization. + + Parameters + ---------- + where: str + Diagnostic location of the settings. + data: Mapping[str, object] + Raw JSON-compatible tool settings. + key: str + Setting containing a list of identifiers. + default: tuple[str, ...], optional + Immutable value used when the key is absent. Defaults to empty. + + Returns + ------- + tuple[str, ...] + Ordered identifiers. Vocabulary validation occurs separately. + + """ + values = data.get(key, default) + if not isinstance(values, (list, tuple)): + raise ValueError(f"{where}.{key} requires a list of identifiers.") + result = tuple(_identifier(value, f"{where}.{key}") for value in values) + if len(set(result)) != len(result): + raise ValueError(f"{where}.{key} contains duplicate identifiers.") + return result + + +def _validate_tool_policies( + tool: Tool, settings: object, organization: SourceOrganization, +) -> None: + """Validate the policies declared by a tool's effective settings. + + Parameters + ---------- + tool: Tool + Registered descriptor, with optional policy declaration. + settings: object + Validated settings from the type or project overrides. + organization: SourceOrganization + Vocabulary for the configuration boundary being checked. + + """ + if tool.source_policies is not None: + policies = tool.source_policies(settings) + if not isinstance(policies, tuple) or any( + not isinstance(policy, SourcePolicy) for policy in policies + ): + raise ValueError(f"{tool.name}: invalid source policies.") + for policy in policies: + validate_source_policy(policy, organization) diff --git a/kilin/tools/_model_calls.py b/kilin/tools/_model_calls.py index c9582b28..29b0735d 100644 --- a/kilin/tools/_model_calls.py +++ b/kilin/tools/_model_calls.py @@ -59,6 +59,7 @@ "ModelCallSettings", "ThinkingPolicy", "load_model_call_settings", + "load_optional_model_call_settings", ] ThinkingPolicy: TypeAlias = Literal["inherit", "on", "off"] @@ -135,3 +136,33 @@ def load_model_call_settings(path: Path) -> ModelCallSettings: data = require_section(load_tool_defaults(path), "MODEL_CALLS", where) require_keys(data, {"THINKING"}, where) return ModelCallSettings(thinking=require_string(data, "THINKING", where)) + + +@lru_cache(maxsize=None) +def load_optional_model_call_settings(path: Path) -> ModelCallSettings: + """Resolve a tool policy, inheriting when no policy is declared. + + Parameters + ---------- + path: pathlib.Path + Path to the tool-owned ``defaults.json``. + + Returns + ------- + ModelCallSettings + Validated declared policy, or the session-inheritance policy. + + Raises + ------ + ValueError + If a supplied defaults document or policy is invalid. + OSError + If a supplied defaults file cannot be read. + + """ + + if not path.exists(): + return ModelCallSettings() + if "MODEL_CALLS" not in load_tool_defaults(path): + return ModelCallSettings() + return load_model_call_settings(path) diff --git a/kilin/tools/_registry.py b/kilin/tools/_registry.py index b36f1deb..83babcbf 100644 --- a/kilin/tools/_registry.py +++ b/kilin/tools/_registry.py @@ -2,30 +2,35 @@ The registry is the controlled boundary between configuration and code. A project type names a tool (``"tool": {"name": "scan_and_list", ...}``); the -name must be in ``TOOL_REGISTRY``, and the tool's own ``parse_settings`` -checks the rest. Configuration never imports arbitrary Python paths, so a -project type file can choose among these tools but cannot add code. +name must be in ``registered_tools()``, and the tool's own +``parse_settings`` checks the rest. Configuration never imports arbitrary +Python paths, so a project type file can choose among these tools but +cannot add code. +The registry is constructed on first access, not during module import. A tool may also declare resources to install in newly created projects; the core resolves and copies them, not the GUI. -Adding a tool means providing a package with a settings -dataclass, ``parse_settings(data, where)``, and ``run(settings, request, -context)`` (see ``kilin.tools._contract``), then adding it here. A tool -marked ``follows_up`` works on an earlier answer, so routing relates a -question sent to it to an earlier turn even when the router named none; -one with ``follows_up_when`` does so only for the questions it accepts. +Each distributed or user tool exposes a ``PLUGIN`` descriptor with +its own settings parser and runner (see ``kilin.tools._contract``). +Discovery binds the descriptor to the package actually loaded. A tool +marked ``follows_up`` works on an earlier answer, so routing excludes its +intents when no eligible turn exists, and otherwise relates the question +to an earlier turn even when the router named none. A tool with only +``follows_up_when`` remains available for first questions and relates to +an earlier turn, if available, for the questions its predicate accepts. Key Features ------------ - **Names** - The tools that exist, as a ``Literal`` type and ``Final`` constants. + Bundled identifiers and an open string type for tool names. - **Registry** - One entry per tool with its summary, parser, runner, and optional - packaged workspace resources. + Discover each public package, validate its descriptor and bind its + observed package root before publishing the registry. User failures + remain individually inspectable; bundled failures are fatal. - **Configuration** @@ -44,10 +49,6 @@ Canonical string values of the registered tool names. -- ``TOOL_CHOICES`` - - Ordered collection of the registered tool names. - - ``ToolName`` Type alias for the registered tool names. @@ -60,9 +61,9 @@ An intent's tool with its validated settings. -- ``TOOL_REGISTRY`` +- ``registered_tools`` and ``tool_choices`` - Map from each tool name to its registered tool. + Explicit accessors for the lazily constructed runtime registry. - ``parse_tool`` @@ -83,46 +84,39 @@ from __future__ import annotations -from collections.abc import Callable -from dataclasses import dataclass +from collections.abc import Mapping +from dataclasses import asdict, dataclass, field, fields, is_dataclass +from importlib import import_module +import json from pathlib import Path -from typing import Final, Literal, TypeAlias - -from kilin.tools import ( - assistant_guide, - batch_classify, - batch_review, - filter_results, - find_fact, - find_passages, - generate_paper_summary, - paper_overview, - project_inventory, - project_summary, - reference_check, - scan_and_list, - show_source, - suggest_reference, - writing_check, +import re +from threading import RLock +from types import MappingProxyType, ModuleType +from typing import Final + +from kilin.plugins._discovery import ( + ToolPluginInfo, _check_defaults, _check_package, _discard_user_package, + _load_user_package, _package_digest, ) +from kilin.plugins._versioning import _require_semver +from kilin.plugins._lifecycle import _ensure_runtime +from kilin.tools._defaults import load_tool_defaults, require_section from kilin.tools._contract import ( + PLUGIN_API_VERSION, + Tool, ToolContext, + ToolName, ToolRequest, ToolResult, - ToolRouting, -) -from kilin.tools._defaults import load_tool_defaults -from kilin.tools._model_calls import ( - ModelCallSettings, - load_model_call_settings, + ToolUse, ) -from kilin.workspace_resources import WorkspaceResource __all__ = [ + "registered_tools", + "tool_choices", "TOOL_ASSISTANT_GUIDE", "TOOL_BATCH_CLASSIFY", "TOOL_BATCH_REVIEW", - "TOOL_CHOICES", "TOOL_FILTER_RESULTS", "TOOL_FIND_FACT", "TOOL_FIND_PASSAGES", @@ -131,7 +125,6 @@ "TOOL_PROJECT_INVENTORY", "TOOL_PROJECT_SUMMARY", "TOOL_REFERENCE_CHECK", - "TOOL_REGISTRY", "TOOL_SCAN_AND_LIST", "TOOL_SHOW_SOURCE", "TOOL_SUGGEST_REFERENCE", @@ -143,24 +136,7 @@ "run_tool", ] -# The tools that exist. Project type files name tools by these values. -ToolName: TypeAlias = Literal[ - "project_inventory", - "scan_and_list", - "batch_classify", - "batch_review", - "filter_results", - "find_fact", - "find_passages", - "generate_paper_summary", - "paper_overview", - "reference_check", - "show_source", - "suggest_reference", - "writing_check", - "project_summary", - "assistant_guide", -] +# Canonical identifiers of bundled tools. TOOL_PROJECT_INVENTORY: Final[ToolName] = "project_inventory" TOOL_SCAN_AND_LIST: Final[ToolName] = "scan_and_list" TOOL_BATCH_CLASSIFY: Final[ToolName] = "batch_classify" @@ -176,7 +152,7 @@ TOOL_WRITING_CHECK: Final[ToolName] = "writing_check" TOOL_PROJECT_SUMMARY: Final[ToolName] = "project_summary" TOOL_ASSISTANT_GUIDE: Final[ToolName] = "assistant_guide" -TOOL_CHOICES: Final[tuple[ToolName, ...]] = ( +_BUILTIN_TOOL_ORDER: Final[tuple[ToolName, ...]] = ( TOOL_PROJECT_INVENTORY, TOOL_SCAN_AND_LIST, TOOL_BATCH_CLASSIFY, @@ -195,225 +171,452 @@ ) +# Define registry iteration order separately from chooser order. Neither +# preference list controls which packages are discovered. +_BUILTIN_REGISTRY_ORDER: Final[tuple[ToolName, ...]] = ( + TOOL_PROJECT_INVENTORY, + TOOL_SCAN_AND_LIST, + TOOL_BATCH_CLASSIFY, + TOOL_BATCH_REVIEW, + TOOL_FILTER_RESULTS, + TOOL_FIND_FACT, + TOOL_FIND_PASSAGES, + TOOL_PAPER_OVERVIEW, + TOOL_REFERENCE_CHECK, + TOOL_SUGGEST_REFERENCE, + TOOL_WRITING_CHECK, + TOOL_ASSISTANT_GUIDE, + TOOL_SHOW_SOURCE, + TOOL_GENERATE_PAPER_SUMMARY, + TOOL_PROJECT_SUMMARY, +) + + +# Construct the registry only when a consumer explicitly needs it. The lock +# prevents concurrent first accesses from publishing different registries. +_REGISTRY_LOCK = RLock() +_registry: dict[ToolName, Tool] | None = None +_initializing = False +_rejected_tools: tuple[ToolPluginInfo, ...] = () + + @dataclass(frozen=True, slots=True) -class Tool: - """One registered tool. +class _RegisteredTool(Tool): + """Bind an authoring descriptor to a loader-observed package. Attributes ---------- - name: ToolName - Name used in project types. - summary: str - What the tool does, for documentation and listings. - parse_settings: Callable[[dict, str], object] - Validates the tool's settings from a project type. - run: Callable[[object, ToolRequest, ToolContext], ToolResult] - Runs the tool with validated settings. - follows_up: bool - True when the tool works on an earlier answer, so a question - routed to it always relates to an earlier turn. - follows_up_when: Callable[[str], bool] | None - For a tool that works on an earlier answer only for some - questions: True for those questions, which then relate to an - earlier turn like ``follows_up``. They are not ruled out for - naming a file. - routing: Callable[[object, Path, tuple[object, ...]], ToolRouting | None] - Optional ``routing(settings, project_root, others)``: cues and a - router description from the project's own files, added to the - intent before routing (``with_project_routing``); ``others`` are - the settings of the project type's other intents using the same - tool, whose cases the routing can leave to them. - model_calls: ModelCallSettings - Tool-owned policy for internal answering-model calls. - workspace_resources: Callable | None - Optional declaration of packaged resources for a new project. + _package_root: pathlib.Path + Resolved directory of the imported package. It is not supplied + by the descriptor and is retained when replacing test callbacks. + _info: ToolPluginInfo | None + Captured identity and nonfatal diagnostics of the loaded package. """ - name: ToolName - summary: str - parse_settings: Callable[[dict, str], object] - run: Callable[[object, ToolRequest, ToolContext], ToolResult] - follows_up: bool = False - follows_up_when: Callable[[str], bool] | None = None - routing: ( - Callable[[object, Path, tuple[object, ...]], ToolRouting | None] - | None - ) = None - workspace_resources: ( - Callable[[object], tuple[WorkspaceResource, ...]] | None - ) = None + _package_root: Path = field(kw_only=True, repr=False) + _info: ToolPluginInfo | None = field(default=None, kw_only=True, + repr=False) @property - def model_calls(self) -> ModelCallSettings: - """Return the registered tool's validated internal thinking policy. + def resource_root(self) -> Path: + """Return the observed root of the registered package. Returns ------- - ModelCallSettings - Cached policy from this tool's own packaged defaults. + pathlib.Path + Absolute directory for owned configuration and assets. """ - return load_model_call_settings( - Path(__file__).parent / self.name / "defaults.json" + return self._package_root + + +def _validate_descriptor(name: str, tool: object) -> None: + """Validate the identity and declared contract of a plugin. + + Parameters + ---------- + name: str + Expected tool identifier, from the package directory. + tool: object + Candidate descriptor exported by the package. + + Raises + ------ + ValueError + If its type, identity, version or callable declarations are invalid. + + """ + + if not isinstance(tool, Tool): + raise ValueError(f"Tool {name!r} must export a Tool as PLUGIN.") + if not re.fullmatch(r"[a-z][a-z0-9_]*", name) or tool.name != name: + raise ValueError(f"Tool {name!r} has invalid descriptor identity.") + if ( + type(tool.api_version) is not int + or tool.api_version != PLUGIN_API_VERSION + ): + raise ValueError( + f"Tool {name!r} declares plugin API version " + f"{tool.api_version!r}; supported version is " + f"{PLUGIN_API_VERSION}." ) + if ( + not isinstance(tool.summary, str) or not tool.summary.strip() + or tool.summary != tool.summary.strip() + ): + raise ValueError(f"Tool {name!r} has invalid summary.") + _require_semver(tool.version, f"Tool {name!r} version") + if type(tool.follows_up) is not bool: + raise ValueError(f"Tool {name!r} has invalid follows_up.") + for key in ("parse_settings", "run"): + if not callable(getattr(tool, key)): + raise ValueError(f"Tool {name!r} requires callable {key}.") + for key in ("follows_up_when", "routing", "workspace_resources", + "source_policies"): + value = getattr(tool, key) + if value is not None and not callable(value): + raise ValueError(f"Tool {name!r} has invalid {key}.") + + +def _parse_settings(tool: Tool, data: dict, where: str) -> object: + """Validate settings returned by the tool at every configuration boundary. - @property - def internal_defaults(self) -> dict[str, object]: - """Return the tool's packaged defaults other than ``SETTINGS``. + Parameters + ---------- + tool: Tool + Descriptor providing the settings parser. + data: dict + Raw settings supplied to the parser. + where: str + Diagnostic location of the settings. - These sections, such as ``MODEL_CALLS`` or ``ESTIMATES``, belong to - the tool: project types and users cannot change them. + Returns + ------- + object + Settings dataclass with JSON-compatible fields. - Returns - ------- - dict[str, object] - The sections by name, empty when the tool has no defaults file. + """ - """ + try: + settings = tool.parse_settings(data, where) + except SystemExit as error: + raise ValueError( + f"Tool {tool.name!r} settings parser attempted to exit: {error}" + ) from error + if not is_dataclass(settings) or isinstance(settings, type): + raise ValueError(f"Tool {tool.name!r} settings must be a dataclass.") + try: + _check_json(asdict(settings)) + except (TypeError, ValueError, RecursionError) as error: + raise ValueError( + f"Tool {tool.name!r} settings must be JSON-compatible." + ) from error + return settings + + +def _check_json(value: object) -> None: + """Require strict JSON data, permitting tuples as array representations. + + Parameters + ---------- + value: object + Settings or result payload to validate. + + """ + + if isinstance(value, dict): + for key, item in value.items(): + if not isinstance(key, str): + raise ValueError("JSON object keys must be strings.") + _check_json(item) + elif isinstance(value, (tuple, list)): + for item in value: + _check_json(item) + elif value is not None and not isinstance(value, (str, int, float)): + raise TypeError("Unsupported JSON value.") + # Reject NaN and infinity without serializing every nested object again. + if isinstance(value, float): + json.dumps(value, allow_nan=False) + + +def _register_tool( + module: ModuleType, directory: Path, *, origin: str = "distribution", + digest: str | None = None, +) -> Tool: + """Bind and validate a descriptor from an already imported package. + + Parameters + ---------- + module: types.ModuleType + Imported trusted Python package exposing ``PLUGIN``. + directory: pathlib.Path + Candidate package directory selected by the loader, not the plugin. + origin: str, optional + Distribution or user-level source of the package. + digest: str | None, optional + Digest captured before importing user code. + + Returns + ------- + Tool + A descriptor bound to its actual resource directory. + + Raises + ------ + ValueError + If the package origin, descriptor or declared defaults are invalid. + + """ - path = Path(__file__).parent / self.name / "defaults.json" - if not path.is_file(): - return {} + directory = directory.resolve() + location = getattr(module, "__file__", None) + if ( + not location or Path(location).resolve() != directory / "__init__.py" + ): + raise ValueError(f"Tool {directory.name!r} has unexpected origin.") + name = directory.name + descriptor = getattr(module, "PLUGIN", None) + _validate_descriptor(name, descriptor) + # Copy only authoring fields, never ownership supplied by a descriptor. + values = { + item.name: getattr(descriptor, item.name) for item in fields(Tool) + } + tool = _RegisteredTool(**values, _package_root=directory) + path = directory / "defaults.json" + if path.exists(): defaults = load_tool_defaults(path) - defaults.pop("SETTINGS", None) - return defaults + if "SETTINGS" in defaults: + data = require_section(defaults, "SETTINGS", name) + normalized = {key.lower(): value for key, value in data.items()} + if len(normalized) != len(data): + raise ValueError(f"Tool {name!r} has duplicate settings.") + _parse_settings(tool, normalized, f"{name}.defaults") + # An absent policy inherits the session. A supplied policy must be valid. + _ = tool.model_calls + warnings = () + if origin == "user": + from kilin.settings_info import _read_tool_info + + try: + _read_tool_info(name, directory) + except (OSError, ValueError, TypeError) as error: + warnings = (f"Settings help: {error}",) + current_digest = _package_digest(directory) + if digest is not None and current_digest != digest: + raise ValueError(f"Tool {name!r} changed during registration.") + info = ToolPluginInfo( + name, directory, origin, tool.version, tool.api_version, + current_digest, warnings=warnings, + ) + return _RegisteredTool(**values, _package_root=directory, _info=info) -@dataclass(frozen=True, slots=True) -class ToolUse: - """An intent's tool with its validated settings. +def _register_user_tool(directory: Path) -> Tool: + """Import and bind a trusted user plugin, cleaning failures from cache. - Attributes + Parameters + ---------- + directory: pathlib.Path + Candidate source package folder. + + Returns + ------- + Tool + Registered descriptor with captured user identity. + + """ + + directory = _check_package(directory) + digest = _package_digest(directory) + _check_defaults(directory) + module = _load_user_package(directory) + try: + return _register_tool(module, directory, origin="user", digest=digest) + except BaseException: + _discard_user_package(directory.name) + raise + + +def _discover_user_tools( + entries: dict[ToolName, Tool], directory: Path, +) -> tuple[ToolPluginInfo, ...]: + """Extend the bundled registry and retain rejected user candidates. + + Parameters + ---------- + entries: dict[ToolName, Tool] + Registry under construction; distribution names have precedence. + directory: pathlib.Path + User tools directory, which may be absent. + + Returns + ------- + tuple[ToolPluginInfo, ...] + Unavailable candidates with individual diagnostic messages. + + """ + + rejected = [] + try: + if directory.is_symlink() or directory.is_junction(): + raise ValueError("Linked tools directory.") + candidates = sorted(directory.iterdir()) + except FileNotFoundError: + return () + except (OSError, ValueError) as error: + return (ToolPluginInfo( + "", directory, "user", error=str(error), + runtime_checked=False, + ),) + for path in candidates: + name = path.name + if name.startswith(("_", ".")): + continue + try: + if not (path.is_dir() or path.is_symlink()): + continue + if name in entries: + rejected.append(ToolPluginInfo( + name, path.absolute(), "user", + error=f"Tool ID {name!r} is already registered.", + runtime_checked=False, + )) + continue + entries[name] = _register_user_tool(path) + except (Exception, SystemExit) as error: + rejected.append(ToolPluginInfo( + name, path.absolute(), "user", + error=f"{type(error).__name__}: {error}", + )) + return tuple(rejected) + + +def _tool_plugin_infos() -> tuple[ToolPluginInfo, ...]: + """Inspect registered and rejected tool candidates without reimporting.""" + + entries = _tool_registry() + return tuple( + tool._info for tool in entries.values() + if isinstance(tool, _RegisteredTool) and tool._info is not None + ) + _rejected_tools + + +def _tool_identity(name: str) -> dict[str, object] | None: + """Return captured tool provenance, if available for this entry. + + Parameters ---------- - name: ToolName - The tool. - settings: object - The tool's settings dataclass, such as ``ScanSettings``. + name: str + Registered tool identifier. + + Returns + ------- + dict[str, object] | None + Portable identity, or None for a synthetic test descriptor. + + """ + + info = getattr(_tool_registry().get(name), "_info", None) + return info.identity() if info is not None else None + + +def _build_tool_registry() -> dict[ToolName, Tool]: + """Discover bundled and trusted user packages and register descriptors. + + Returns + ------- + dict[ToolName, Tool] + Tool definitions in their established registration order, followed + by newly distributed and then user packages in alphabetical order. + + Raises + ------ + ValueError + If a public bundled package cannot be registered. + + """ + + global _rejected_tools + root = _ensure_runtime() + entries = {} + for directory in sorted(Path(__file__).parent.iterdir()): + name = directory.name + if name.startswith("_") or not (directory / "__init__.py").is_file(): + continue + if not re.fullmatch(r"[a-z][a-z0-9_]*", name): + raise ValueError(f"Invalid bundled tool package: {name!r}.") + module = import_module(f"kilin.tools.{name}") + entries[name] = _register_tool(module, directory) + order = (*_BUILTIN_REGISTRY_ORDER, *entries) + entries = {name: entries[name] for name in order if name in entries} + _rejected_tools = _discover_user_tools( + entries, root / "tools", + ) + return entries + + +def _tool_registry() -> dict[ToolName, Tool]: + """Resolve the single process-local registry on first use. + + Returns + ------- + dict[ToolName, Tool] + The registry, constructed once on successful access. + + Raises + ------ + RuntimeError + If construction recursively requests the registry. + ValueError + If a bundled tool declares an unsupported plugin API version. """ - name: ToolName - settings: object - - -TOOL_REGISTRY: Final[dict[ToolName, Tool]] = { - TOOL_PROJECT_INVENTORY: Tool( - TOOL_PROJECT_INVENTORY, - "Count and list the project's files by type and folder, with " - "which have searchable text.", - project_inventory.parse_settings, - project_inventory.run, - ), - TOOL_SCAN_AND_LIST: Tool( - TOOL_SCAN_AND_LIST, - "List and count every exact mention of the question's terms.", - scan_and_list.parse_settings, - scan_and_list.run, - ), - TOOL_BATCH_CLASSIFY: Tool( - TOOL_BATCH_CLASSIFY, - "Sort every exact mention into categories with the answering " - "model, and count each category.", - batch_classify.parse_settings, - batch_classify.run, - ), - TOOL_BATCH_REVIEW: Tool( - TOOL_BATCH_REVIEW, - "Read one whole document in parts, taking notes with passage " - "numbers, then answer from the notes.", - batch_review.parse_settings, - batch_review.run, - ), - TOOL_FILTER_RESULTS: Tool( - TOOL_FILTER_RESULTS, - "Judge each item an earlier answer listed and keep those that match " - "a follow-up.", - filter_results.parse_settings, - filter_results.run, - follows_up=True, - ), - TOOL_FIND_FACT: Tool( - TOOL_FIND_FACT, - "Find a specific fact in one paper or every paper by reading every " - "passage; the user can choose a quick answer instead.", - find_fact.parse_settings, - find_fact.run, - ), - TOOL_FIND_PASSAGES: Tool( - TOOL_FIND_PASSAGES, - "Read every sentence in scope and list the ones about a topic, " - "copied word for word.", - find_passages.parse_settings, - find_passages.run, - ), - TOOL_PAPER_OVERVIEW: Tool( - TOOL_PAPER_OVERVIEW, - "Summarize one paper in the chat; ask which paper when it is " - "unclear.", - paper_overview.parse_settings, - paper_overview.run, - ), - TOOL_REFERENCE_CHECK: Tool( - TOOL_REFERENCE_CHECK, - "Check one paper's reference list against the project's files, " - "find where each reference is cited, optionally check claims, " - "and give offline or explicitly authorized online links for " - "missing works; save the report to outputs/.", - reference_check.parse_settings, - reference_check.run, - ), - TOOL_SUGGEST_REFERENCE: Tool( - TOOL_SUGGEST_REFERENCE, - "Find the papers in the project that could be cited for a " - "statement, judging each with a quote from its own passages.", - suggest_reference.parse_settings, - suggest_reference.run, - ), - TOOL_WRITING_CHECK: Tool( - TOOL_WRITING_CHECK, - "Check the grammar and style of one document or part of it, " - "paragraph by paragraph, and suggest changes without making them; " - "save the report to outputs/.", - writing_check.parse_settings, - writing_check.run, - follows_up_when=writing_check.asks_rewrite, - ), - TOOL_ASSISTANT_GUIDE: Tool( - TOOL_ASSISTANT_GUIDE, - "Answer what KíLín can do with one ready-to-send example question " - "per kind of request, about the project's own files.", - assistant_guide.parse_settings, - assistant_guide.run, - ), - TOOL_SHOW_SOURCE: Tool( - TOOL_SHOW_SOURCE, - "Show the sentence an earlier answer cited, with the sentences " - "around it, and explain it without searching again.", - show_source.parse_settings, - show_source.run, - follows_up=True, - ), - TOOL_GENERATE_PAPER_SUMMARY: Tool( - TOOL_GENERATE_PAPER_SUMMARY, - "Summarize one paper with a report template, check the structure, " - "and save the Markdown to outputs/.", - generate_paper_summary.parse_settings, - generate_paper_summary.run, - routing=generate_paper_summary.routing, - workspace_resources=generate_paper_summary.workspace_resources, - ), - TOOL_PROJECT_SUMMARY: Tool( - TOOL_PROJECT_SUMMARY, - "Write one report on all the documents of a project with a project " - "template, reading every document, and save it to outputs/.", - project_summary.parse_settings, - project_summary.run, - routing=project_summary.routing, - workspace_resources=project_summary.workspace_resources, - ), -} + global _registry, _initializing + with _REGISTRY_LOCK: + if _registry is None: + if _initializing: + raise RuntimeError("Recursive tool registry initialization.") + _initializing = True + try: + entries = _build_tool_registry() + for name, tool in entries.items(): + _validate_descriptor(name, tool) + _registry = entries + finally: + _initializing = False + return _registry + + +def registered_tools() -> Mapping[ToolName, Tool]: + """Return a read-only view of the process-local tool registry. + + Returns + ------- + Mapping[ToolName, Tool] + Registered tools in their established registration order. + + """ + + return MappingProxyType(_tool_registry()) + + +def tool_choices() -> tuple[ToolName, ...]: + """Return the available tool identifiers in their established order. + + Returns + ------- + tuple[ToolName, ...] + Registered identifiers, with the original bundled ordering. + + """ + + entries = _tool_registry() + return tuple(name for name in _BUILTIN_TOOL_ORDER if name in entries) + ( + tuple(name for name in entries if name not in _BUILTIN_TOOL_ORDER) + ) def parse_tool(where: str, data: object) -> ToolUse: @@ -443,15 +646,16 @@ def parse_tool(where: str, data: object) -> ToolUse: raise ValueError(f"Intent {where!r} tool must be an object.") name = data.get("name") - if name not in TOOL_REGISTRY: + entries = _tool_registry() + if not isinstance(name, str) or name not in entries: raise ValueError( f"Intent {where!r} tool name must be one of: " - f"{', '.join(TOOL_CHOICES)}." + f"{', '.join(tool_choices())}." ) settings = {key: value for key, value in data.items() if key != "name"} return ToolUse( - name, TOOL_REGISTRY[name].parse_settings(settings, f"{where}.tool") + name, _parse_settings(entries[name], settings, f"{where}.tool") ) @@ -476,4 +680,34 @@ def run_tool( """ - return TOOL_REGISTRY[use.name].run(use.settings, request, context) + tool = _tool_registry()[use.name] + try: + result = tool.run(use.settings, request, context) + except SystemExit as error: + raise RuntimeError( + f"Tool {tool.name!r} attempted to exit: {error}" + ) from error + if not isinstance(result, ToolResult): + raise ValueError(f"Tool {use.name!r} must return ToolResult.") + if ( + not isinstance(result.answer, str) + or not isinstance(result.evidence, tuple) + or any(not isinstance(item, dict) for item in result.evidence) + or not isinstance(result.summary, dict) + or type(result.streamed) is not bool + ): + raise ValueError(f"Tool {use.name!r} returned an invalid ToolResult.") + try: + # Evidence uses real pathlib paths until conversation persistence. + # Only the summary and the serialized evidence representation are + # JSON data; do not reject existing tools for returning Path values. + for item in result.evidence: + if not isinstance(item.get("path"), Path): + raise ValueError("Tool evidence requires a pathlib path.") + _check_json({**item, "path": item["path"].as_posix()}) + _check_json(result.summary) + except (TypeError, ValueError, RecursionError) as error: + raise ValueError( + f"Tool {use.name!r} result must be JSON-compatible." + ) from error + return result diff --git a/kilin/tools/_shared/choose_document.py b/kilin/tools/_shared/choose_document.py index c9650a82..ce45aa71 100644 --- a/kilin/tools/_shared/choose_document.py +++ b/kilin/tools/_shared/choose_document.py @@ -95,9 +95,12 @@ import re from typing import Final +from kilin.source_eligibility import ( + bibliography_lookup, document_candidate, paper_request, +) from kilin.retrievals.document_reading import dominant_path, named_paths from kilin.retrievals.source_descriptions import described_sources -from kilin.tools._contract import ToolContext, ToolRequest +from kilin.tools._contract import ToolContext, ToolRequest, ToolSourceServices from kilin.tools._shared.planning import ask_choice __all__ = [ @@ -165,6 +168,9 @@ def choose_document( example: str, prefer: tuple[str, ...] = (), avoid: frozenset[Path] = frozenset(), + paper_only: bool = False, + services: ToolSourceServices | None = None, + allow_unindexed: bool = False, ) -> tuple[Path, str, bool] | str: """Choose one indexed source file for a request. @@ -187,6 +193,14 @@ def choose_document( Files not to choose or offer unless the question names them, such as the papers already discussed when the user asks for "another paper". Defaults to an empty set. + paper_only: bool, optional + Require independent documents even for an explicit bibliography + operand. Defaults to False (explicit file lookup is permitted). + services: ToolSourceServices | None, optional + Bound target view and ranking service. Defaults to None for + existing physical-document consumers. + allow_unindexed: bool, optional + Include eligible anchors without indexed passages for group reading. Returns ------- @@ -197,7 +211,32 @@ def choose_document( """ - sources = list(dict.fromkeys(chunk.path for chunk in context.chunks)) + chunks = context.chunks if services is None else services.chunks + sources = list(dict.fromkeys(chunk.path for chunk in chunks)) + if services is not None: + names = {path.as_posix() for path in services.view.targets} + sources = (list(services.view.targets) if allow_unindexed else + [path for path in sources if path.as_posix() in names]) + selected = services.view.operation.inventory.selected + named = named_paths(request.question, list(selected)) + allowed = {path.as_posix() for path in sources} + if named and any(path.as_posix() not in allowed for path in named): + return "The named file is not an eligible indexed paper." + + explicit_lookup = bibliography_lookup(request.question) + if paper_only and explicit_lookup: + named = named_paths(request.question, sources) + else: + named = [] + if named and not any(document_candidate(path) for path in named): + return ( + "A bibliography is not an independent paper. Name the paper " + "instead, or ask to inspect the bibliography entries." + ) + if paper_only or not explicit_lookup: + sources = [path for path in sources if document_candidate(path)] + if (chunks or services is not None) and not sources: + return "The project has no eligible indexed document to select." known = set(sources) hits = named_paths(request.question, sources, authors=True) if len(hits) == 1: @@ -223,8 +262,12 @@ def choose_document( for path, _ in counts.most_common(2) ] - ranked = context.rank(request.text) if context.chunks else [] - top = ranked[: context.retrieval_count] + ranked = [] + if sources: + rank = context.rank if services is None else services.rank + ranked = rank(request.text) + top = [result for result in ranked if result.chunk.path in known] + top = top[: context.retrieval_count] preferred = [ path for path in sources if path.suffix.lower() in prefer ] @@ -249,25 +292,39 @@ def choose_document( options += [ (path, "in this project") for path in sorted( - sources, key=lambda source: source.name.casefold() + sources, key=lambda source: ( + source.suffix.lower() not in prefer if allow_unindexed + else False, source.as_posix().casefold() + if allow_unindexed else source.name.casefold(), + ) ) if path not in listed and path not in avoid - and (not prefer or path.suffix.lower() in prefer) + and (allow_unindexed or not prefer + or path.suffix.lower() in prefer) ] options = options[:_MAX_CHOICES] - names = ", ".join(path.name for path, _ in options) + names = ", ".join( + path.as_posix() if allow_unindexed else path.name + for path, _ in options + ) if not options: return ( f"I couldn't tell which file you mean. Name it, for example: " f"{example}." ) + if allow_unindexed and len(hits) > 1 and context.choose is None: + return f"Name one document to read. Matching files: {names}." + if context.choose is not None: index = ask_choice( question, - tuple(f"{path.name} ({why})" for path, why in options), + tuple( + f"{path.as_posix() if allow_unindexed else path.name} ({why})" + for path, why in options + ), context, ) if index is None: @@ -406,6 +463,8 @@ def document_scope( """ + if paper_request(request.question): + sources = [path for path in sources if document_candidate(path)] named = named_paths(request.question, sources, authors=True) indexed = set(sources) described = described_sources( diff --git a/kilin/tools/_shared/claims.py b/kilin/tools/_shared/claims.py index a7a27fed..9d06c22c 100644 --- a/kilin/tools/_shared/claims.py +++ b/kilin/tools/_shared/claims.py @@ -566,7 +566,10 @@ def verification_prompt( "of the sentence is context." ) listed_passages = "\n\n".join( - f"Passage {index}:\n{chunk.text.strip()}" + f"Passage {index}:\n" + + (f"Related source: {chunk.path.as_posix()}\n" + if chunk.path != claim.cited else "") + + chunk.text.strip() for index, chunk in enumerate(passages, start=1) ) preceding = ( @@ -653,7 +656,10 @@ def support_prompt( "what you know. Be strict and fair, and copy quotes exactly." ) listed_passages = "\n\n".join( - f"Passage {index}:\n{chunk.text.strip()}" + f"Passage {index}:\n" + + (f"Related source: {chunk.path.as_posix()}\n" + if chunk.path != cited else "") + + chunk.text.strip() for index, chunk in enumerate(passages, start=1) ) user = f"""A writer needs a reference for this sentence: diff --git a/kilin/tools/_shared/document_notes.py b/kilin/tools/_shared/document_notes.py index 18ef147b..a19ebe6f 100644 --- a/kilin/tools/_shared/document_notes.py +++ b/kilin/tools/_shared/document_notes.py @@ -53,6 +53,8 @@ from __future__ import annotations +from pathlib import Path + from collections.abc import Mapping, Sequence import re from time import perf_counter @@ -333,6 +335,7 @@ def take_notes( what: str = "document", whole: bool = True, failures: list[dict[str, object]] | None = None, + paths: Sequence[Path] | None = None, ) -> list[tuple[int, list[str]]]: """Take checked notes on each part of a document with the model. @@ -359,6 +362,9 @@ def take_notes( Collect independent failed parts and continue when supplied. Failed parts are omitted from notes, never represented as NOTHING. None retains strict failure propagation. + paths: Sequence[Path] | None, optional + Physical identity for each passage. Group-reading callers plan + parts within a single member and retain global citation numbers. Returns ------- @@ -378,20 +384,22 @@ def take_notes( notes: list[tuple[int, list[str]]] = [] for number, part in enumerate(parts, start=1): + member = paths[part[0]].as_posix() if paths is not None else name if not whole: - message = f"Reading the most relevant passages: {name}" + label = "selected" if paths is not None else "most relevant" + message = f"Reading {label} passages: {member}" elif len(parts) == 1: - message = f"Reading the whole {what}: {name}" + message = f"Reading the whole {what}: {member}" else: message = ( f"Reading the whole {what} (part {number} of " - f"{len(parts)}): {name}" + f"{len(parts)}): {member}" ) context.progress(message, current=number, total=len(parts)) started = perf_counter() system, prompt = notes_prompt( task, - name, + member, number, len(parts), [(index + 1, texts[index]) for index in part], @@ -408,7 +416,7 @@ def take_notes( if failures is None: raise failure = { - "item": f"{name}, reading part {number}", + "item": f"{member}, reading part {number}", "part": number, "passages": len(part), "passage_numbers": [index + 1 for index in part], **error.to_dict(), @@ -436,6 +444,8 @@ def take_notes( "notes": len(lines), "seconds": round(perf_counter() - started, 2), } + if paths is not None: + data["path"] = member if context.trace.include_content: data["raw"] = reply context.trace.emit( diff --git a/kilin/tools/_shared/group_reading.py b/kilin/tools/_shared/group_reading.py new file mode 100644 index 00000000..66c71415 --- /dev/null +++ b/kilin/tools/_shared/group_reading.py @@ -0,0 +1,296 @@ +"""Plan source-ordered reading of one authorized logical document. + +The host resolves relationships. This module only chooses an anchor and +orders its physical members, preserving original chunks and citation numbers. + +Key Features +------------ + +- One aggregate reading plan and explicit per-member coverage. +- Separate physical-file lookup for an explicitly named dependent file. +- No directory scans, graph traversal or independent index construction. + +Module Structure +---------------- + +- ``GroupReading``: chosen anchor, physical passages and member coverage. +- ``choose_group``: choose and bind one target through the tool host. +- ``reading_policy``: construct the effective document policy. + +Examples +-------- +>>> from kilin.tools._shared.group_reading import reading_policy +>>> reading_policy((), (), ()).related_evidence +() + +""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from dataclasses import dataclass +from pathlib import Path + +from kilin.chunking import Chunk +from kilin.retrievals.document_reading import named_paths +from kilin.source_eligibility import document_candidate +from kilin.source_views import SourcePolicy, SourceScope, UnavailableMember +from kilin.tools import ( + ToolContext, ToolRequest, ToolSourceServices, require_source_services, +) +from .choose_document import choose_document +from .document_notes import plan_parts + +__all__ = ["GroupReading", "choose_group", "reading_policy", "bind_group"] + + +def reading_policy( + target_roles: tuple[str, ...], evidence_roles: tuple[str, ...], + related_evidence: tuple[str, ...], +) -> SourcePolicy: + """Construct the effective policy without enabling lookup expansion. + + Parameters + ---------- + target_roles: tuple[str, ...] + Accepted roles eligible as document anchors. + evidence_roles: tuple[str, ...] + Accepted roles eligible as supporting evidence. + related_evidence: tuple[str, ...] + Permitted direct evidence relationships. + + """ + return SourcePolicy( + target_roles=target_roles or None, + evidence_roles=evidence_roles or None, + related_evidence=related_evidence, + ) + + +@dataclass(frozen=True, slots=True) +class GroupReading: + """One selected anchor, with original passages ordered by member. + + Attributes + ---------- + anchor: Path + The chosen source or explicit output operand. + chunks: tuple[Chunk, ...] + Original passages, anchor first and other members in path order. + members: tuple[Path, ...] + Selected reading members, including those without indexed text. + unavailable: tuple[UnavailableMember, ...] + Missing or unresolved members reported by the host. + reason: str + How the anchor was selected. + guessed: bool + Whether the selection needs user confirmation where available. + services: ToolSourceServices | None + Bound generation; None only for the separate output operand. + functions: tuple[str, ...] + Explicit code-function selection within a physical file. + + """ + + anchor: Path + chunks: tuple[Chunk, ...] + members: tuple[Path, ...] + unavailable: tuple[UnavailableMember, ...] + reason: str + guessed: bool + services: ToolSourceServices | None = None + functions: tuple[str, ...] = () + + def parts(self, limit: int, indices: Sequence[int] | None = None + ) -> list[list[int]]: + """Pack consecutive passages of each member without mixing files. + + Parameters + ---------- + limit: int + Estimated token target for each physical reading part. + indices: Sequence[int] | None + Optional global passage indices to include. + + """ + selected = list(range(len(self.chunks))) if indices is None else ( + sorted(set(indices)) + ) + parts = [] + for path in self.members: + local = [i for i in selected if self.chunks[i].path == path] + parts.extend([[local[i] for i in part] for part in plan_parts( + [self.chunks[i] for i in local], limit + )]) + return parts + + def coverage(self, read: Iterable[int]) -> list[dict[str, object]]: + """Describe actual processed passages, not planned or ranked ones. + + Parameters + ---------- + read: Iterable[int] + Global indices of successfully processed passages. + + """ + indices = set(read) + paths = tuple(dict.fromkeys((*self.members, *( + item.path for item in self.unavailable + if item.reason != "raw_unavailable" + )))) + result = [] + for path in paths: + available = {i for i, c in enumerate(self.chunks) + if c.path == path} + count = len(indices & available) + reasons = [item.reason for item in self.unavailable + if item.path == path + and item.reason != "raw_unavailable"] + result.append({ + "path": path.as_posix(), "anchor": path == self.anchor, + "passages": len(available), "read": count, + "unavailable": reasons, + "complete": bool(available) and count == len(available) + and not reasons, + }) + return result + + def notice(self, read: Iterable[int]) -> str: + """Describe incomplete or multi-file coverage without attribution. + + Parameters + ---------- + read: Iterable[int] + Global indices of successfully processed passages. + + """ + rows = self.coverage(read) + if len(rows) == 1 and rows[0]["complete"]: + return "" + details = [] + for row in rows: + label = "anchor" if row["anchor"] else "related source" + reasons = ", ".join(row["unavailable"]) + suffix = f"; {reasons}" if reasons else "" + details.append( + f"{row['path']} ({label}): {row['read']}/" + f"{row['passages']} indexed passages read{suffix}" + ) + return ("Reading coverage: " + "; ".join(details) + ". " + "Unread or unavailable material is not negative evidence.") + + def part_sources( + self, parts: Sequence[Sequence[int]], + notes: Sequence[tuple[int, list[str]]], + ) -> str: + """Label completed note blocks by their original physical source. + + Parameters + ---------- + parts: Sequence[Sequence[int]] + Planned passage indices in each reading part. + notes: Sequence[tuple[int, list[str]]] + Successfully processed part numbers and their notes. + + """ + if len(self.members) == 1: + return "" + lines = [f"Part {n}: {self.chunks[parts[n - 1][0]].path.as_posix()}" + for n, _ in notes] + return "\n\nPhysical sources of notes:\n" + "\n".join(lines) + + def validate(self) -> None: + """Reject stale source operations before publishing their results.""" + if self.services is not None: + self.services.validate() + + +def bind_group( + context: ToolContext, policy: SourcePolicy, anchor: Path, + reason: str, guessed: bool, +) -> GroupReading: + """Bind a single target and order its original indexed members. + + Parameters + ---------- + context: ToolContext + Host services for the current tool operation. + policy: SourcePolicy + Effective source membership policy. + anchor: Path + Selected physical document identity. + reason: str + Description of how the document was selected. + guessed: bool + Whether selection is a guess requiring confirmation. + + """ + service = require_source_services( + context, policy, SourceScope("restricted", (anchor,)), + ) + group = service.view.groups[0] + paths = group.evidence if policy.purpose == "document" else group.lookup + members = (anchor, *sorted((p for p in paths if p != anchor), + key=Path.as_posix)) + chunks = tuple(chunk for path in members for chunk in service.chunks + if chunk.path.as_posix() == path.as_posix()) + return GroupReading(anchor, chunks, members, group.unavailable, + reason, guessed, service) + + +def choose_group( + request: ToolRequest, context: ToolContext, policy: SourcePolicy, + *, question: str, example: str, prefer: tuple[str, ...] = (), + paper_only: bool = False, + targets: ToolSourceServices | None = None, +) -> GroupReading | str: + """Choose an eligible anchor or an explicitly named physical file. + + An explicit dependent or retained file is a single-file operation, + not an independent publication candidate. Role restrictions remain + binding. Bibliography files are permitted only for non-paper reading. + Unindexed anchors may be chosen when their permitted members have text. + + Parameters + ---------- + request: ToolRequest + Question and earlier-turn context. + context: ToolContext + Host services for the current tool operation. + policy: SourcePolicy + Effective source membership policy. + question: str + Prompt for choosing an ambiguous document. + example: str + Example of an explicitly named request. + prefer: tuple[str, ...] + Preferred filename suffixes for selection. + paper_only: bool + Whether bibliography containers must be excluded. + targets: ToolSourceServices | None + Optional prebound anchor-only selection services. + + """ + discovery = SourcePolicy(target_roles=policy.target_roles) + if targets is None: + targets = require_source_services(context, discovery) + selected = targets.view.operation.inventory.selected + named = named_paths(request.question, selected) + if len(named) == 1: + path = named[0] + eligible = {p.as_posix() for p in targets.view.targets} + if path.as_posix() not in eligible: + if paper_only and not document_candidate(path): + return "A bibliography is not an independent paper." + if policy.target_roles is not None: + return "The named file is not an eligible document." + return bind_group(context, SourcePolicy(purpose="lookup"), + path, "named physical file", False) + chosen = choose_document( + request, context, question=question, example=example, + prefer=prefer, paper_only=paper_only, services=targets, + allow_unindexed=True, + ) + if isinstance(chosen, str): + return chosen + return bind_group(context, policy, *chosen) diff --git a/kilin/tools/_shared/long_lists.py b/kilin/tools/_shared/long_lists.py index b4f4cc93..59b6b98c 100644 --- a/kilin/tools/_shared/long_lists.py +++ b/kilin/tools/_shared/long_lists.py @@ -62,6 +62,7 @@ from __future__ import annotations +from collections.abc import Callable from pathlib import Path import re from typing import Final @@ -87,6 +88,7 @@ def offer_export( what: str, name: str, markdown: str, + validate: Callable[[], None] | None = None, ) -> Path | None: """Ask whether to save a long list as a Markdown file, and save it. @@ -103,6 +105,8 @@ def offer_export( taken name gets ``-2``, ``-3``, ... markdown: str The full list as Markdown. + validate: Callable[[], None] | None, optional + Verify the source operation after confirmation and before saving. Returns ------- @@ -127,6 +131,8 @@ def offer_export( if index != 0: return None + if validate is not None: + validate() text = _CITATION.sub("", markdown).strip() + "\n" return save_output_file(context.project_root, name, text) diff --git a/kilin/tools/_shared/mentions.py b/kilin/tools/_shared/mentions.py index 98f76cad..18c11c13 100644 --- a/kilin/tools/_shared/mentions.py +++ b/kilin/tools/_shared/mentions.py @@ -35,8 +35,13 @@ from typing import Protocol from kilin.chunking import Chunk +from kilin.tools._shared.search_sources import ( + restrict_sources, search_sources, unindexed_sources, +) from kilin.retrievals.document_reading import dominant_path -from kilin.tools._contract import ToolContext, ToolRequest, ToolResult +from kilin.tools._contract import ( + ToolContext, ToolRequest, ToolResult, ToolSourceServices, +) from kilin.tools._shared.choose_document import document_scope from kilin.tools._shared.terms import ( CATEGORIES_REPLY_TOKENS, @@ -236,12 +241,14 @@ class MentionCollection: scope_note: str | None How the scanned files were chosen, when not all were scanned. unsearchable: tuple[pathlib.Path, ...] - Source files without indexed text (only for a full scan). + Selected files in scope without indexed text. summary: dict[str, object] Terms, scope, and counts, saved with the turn. reply: str The router model's extraction reply (it may also carry categories). + services: ToolSourceServices | None + Bound source view for validation before publishing results. """ @@ -250,6 +257,7 @@ class MentionCollection: unsearchable: tuple[Path, ...] summary: dict[str, object] reply: str + services: ToolSourceServices | None = None def collect_mentions( @@ -293,6 +301,14 @@ def collect_mentions( """ trace = context.trace + sources = search_sources(request, context) + if not sources.view.targets: + sources.validate() + context.done("No eligible sources", evidence_count=0) + return ToolResult( + "The requested scope has no eligible sources to scan.", + (), {"name": tool, "unsearchable_files": []}, + ) context.progress("Finding the terms to scan") # Terms come from the question itself; earlier questions are used only @@ -338,8 +354,11 @@ def collect_mentions( summary, ) - indexed = list(dict.fromkeys(chunk.path for chunk in context.chunks)) - named, scoped_by = document_scope(request, context.ask_router, indexed) + indexed = list(dict.fromkeys(chunk.path for chunk in sources.chunks)) + eligible = set(indexed) + named, scoped_by = document_scope( + request, context.ask_router, list(sources.view.targets) + ) file_terms = [ term for term in terms @@ -365,11 +384,12 @@ def collect_mentions( ) if scoped_by != "named in the question": scope_note += " Name the file to scan a different one." - elif document: + elif document and eligible: # A described document ("the Smith paper") is the file that # dominates a search for the description. path = dominant_path( - context.rank(document)[: context.retrieval_count] + [result for result in sources.rank(document) + if result.chunk.path in eligible][: context.retrieval_count] ) if path is not None: scope = [path] @@ -378,6 +398,19 @@ def collect_mentions( f"“{document}”. Name the file to scan a different one." ) + if scope: + sources = restrict_sources(context, sources, scope) + if not sources.chunks: + sources.validate() + summary["unsearchable_files"] = [ + path.as_posix() for path in unindexed_sources(sources) + ] + context.done("No searchable text", evidence_count=0) + return ToolResult( + "The requested scope has no searchable indexed text; " + "the presence or absence of the terms cannot be established.", + (), summary, + ) listed = " or ".join(f"“{term}”" for term in terms) context.progress( f"Scanning {scope[0].name} for {listed}" @@ -391,7 +424,7 @@ def collect_mentions( turn_id=context.trace_turn_id, ): scan = scan_mentions( - context.chunks, + sources.chunks, terms, case_sensitive=settings.case_sensitive, whole_words=settings.whole_words, @@ -399,7 +432,8 @@ def collect_mentions( paths=scope or None, ) - unsearchable = () if scope else tuple(context.unsearchable(indexed)) + sources.validate() + unsearchable = unindexed_sources(sources) summary.update( { "total_mentions": len(scan.mentions), @@ -413,7 +447,9 @@ def collect_mentions( "whole_words": scan.whole_words, } ) - return MentionCollection(scan, scope_note, unsearchable, summary, reply) + return MentionCollection( + scan, scope_note, unsearchable, summary, reply, sources + ) def scan_mentions( diff --git a/kilin/tools/_shared/planning.py b/kilin/tools/_shared/planning.py index 9bd32ffa..e81beb0e 100644 --- a/kilin/tools/_shared/planning.py +++ b/kilin/tools/_shared/planning.py @@ -102,11 +102,14 @@ from __future__ import annotations +from collections.abc import Callable from dataclasses import asdict, dataclass from typing import TYPE_CHECKING, Final, Literal, TypeAlias +from uuid import uuid4 if TYPE_CHECKING: from kilin.tools._contract import ToolContext + from kilin.trace_logging import TraceSink __all__ = [ "CONFIRMATION_ALWAYS", @@ -283,28 +286,47 @@ def confirm_plan( """ trace = context.trace + interaction_id = uuid4().hex + asked = context.confirm is not None and needs_confirmation( + policy, plan, large_batches + ) trace.emit( "tool.plan.proposed", component="tool", - data=plan.to_dict(), + data={ + **plan.to_dict(), "interaction_id": interaction_id, + "choices": list(PLAN_CHOICE_CHOICES), "asked": asked, + "policy": policy, + }, turn_id=context.trace_turn_id, ) - - asked = context.confirm is not None and needs_confirmation( - policy, plan, large_batches - ) choice: PlanChoice = PLAN_CHOICE_CONTINUE + answer = None if asked: - context.progress(_WAITING_FOR_CHOICE, plan=plan.to_dict()) - answer = context.confirm(plan) - choice = ( - answer if answer in PLAN_CHOICE_CHOICES else PLAN_CHOICE_CANCEL - ) + try: + context.progress(_WAITING_FOR_CHOICE, plan=plan.to_dict()) + answer = context.confirm(plan) + choice = ( + answer if answer in PLAN_CHOICE_CHOICES else PLAN_CHOICE_CANCEL + ) + except BaseException as error: + trace.emit( + "tool.plan.failed", component="tool", status="failed", + data={"interaction_id": interaction_id, + "error_type": type(error).__name__, + "message": str(error)}, + turn_id=context.trace_turn_id, + ) + raise trace.emit( "tool.plan.decided", component="tool", - data={"choice": choice, "asked": asked, "policy": policy}, + data={ + "interaction_id": interaction_id, + "choice": choice, "asked": asked, "policy": policy, + "response": answer, + }, turn_id=context.trace_turn_id, ) @@ -335,29 +357,103 @@ def ask_choice( """ - trace = context.trace - trace.emit( - "tool.choice.proposed", - component="tool", - data={"question": question, "options": list(options)}, - turn_id=context.trace_turn_id, - ) - - index = None - if context.choose is not None and options: + def notify() -> None: + """Display the question and options before waiting for the choice.""" context.progress( _WAITING_FOR_CHOICE, choice={"question": question, "options": list(options)}, ) - answer = context.choose(question, options) - if type(answer) is int and 0 <= answer < len(options): - index = answer - trace.emit( - "tool.choice.decided", - component="tool", - data={"index": index, "asked": context.choose is not None}, - turn_id=context.trace_turn_id, + return _record_choice( + question, options, context.choose, notify, + trace=context.trace, turn_id=context.trace_turn_id, + prefix="tool.choice", component="tool", allow_cancel=True, ) + +def _record_choice( + question: str, + options: tuple[str, ...], + choose: Callable[[str, tuple[str, ...]], int | None] | None, + notify: Callable[[], None], + *, + trace: TraceSink, + turn_id: str | None, + prefix: str, + component: str, + allow_cancel: bool, +) -> int | None: + """Record one routing or tool choice at the actual callback boundary. + + Parameters + ---------- + question: str + Prompt shown to the caller. + options: tuple[str, ...] + Ordered option labels shown to the caller. + choose: Callable | None + Existing user-choice callback, or None for automatic behavior. + notify: Callable[[], None] + Existing presentation callback invoked before the choice. + trace: TraceSink + Owning conversation trace. + turn_id: str | None + Correlation identifier of the active turn. + prefix: str + Event namespace for routing or tool choices. + component: str + Emitting subsystem. + allow_cancel: bool + Whether the displayed prompt offers an explicit cancellation option. + + Returns + ------- + int | None + Valid selected index, or None when no option was selected. + + Notes + ----- + Store the label as well as the position; replay must match the meaning, + not reuse the original position. A proposal without a terminal record + is incomplete. Automatic fallbacks are not user responses. + + """ + + interaction_id = uuid4().hex + asked = choose is not None and bool(options) + trace.emit( + f"{prefix}.proposed", component=component, + data={ + "interaction_id": interaction_id, "question": question, + "options": list(options), "asked": asked, + "allow_cancel": allow_cancel, + }, + turn_id=turn_id, + ) + index = None + answer = None + if asked: + try: + notify() + answer = choose(question, options) + if type(answer) is int and 0 <= answer < len(options): + index = answer + except BaseException as error: + trace.emit( + f"{prefix}.failed", component=component, status="failed", + data={"interaction_id": interaction_id, + "error_type": type(error).__name__, + "message": str(error)}, + turn_id=turn_id, + ) + raise + trace.emit( + f"{prefix}.decided", component=component, + data={ + "interaction_id": interaction_id, "index": index, + "asked": asked, "response": answer, + "selected_option": options[index] if index is not None else None, + }, + turn_id=turn_id, + ) return index diff --git a/kilin/tools/_shared/references.py b/kilin/tools/_shared/references.py index 2f2a960e..af058061 100644 --- a/kilin/tools/_shared/references.py +++ b/kilin/tools/_shared/references.py @@ -99,6 +99,7 @@ from dataclasses import dataclass, replace from functools import lru_cache from pathlib import Path +from io import BytesIO import re from typing import Final import unicodedata @@ -498,7 +499,7 @@ def _ends_list(line: str) -> bool: def reference_list( passages: Sequence[Chunk], layout: ReferenceLayout, - file: Path | None = None, + file: Path | bytes | None = None, which: int = -1, ) -> str: """Return one of the paper's reference lists, found by its heading. @@ -509,7 +510,7 @@ def reference_list( The paper's passages, in order. layout: ReferenceLayout The caller's thresholds; ``max_characters`` limits the list. - file: pathlib.Path | None, optional + file: pathlib.Path | bytes | None, optional The paper on disk. For a PDF, the list is read again from the page layout in column order (``pdf_text``), because extracted text can interleave the columns of a two-column list. Defaults to @@ -552,7 +553,7 @@ def reference_list( def reference_lists( passages: Sequence[Chunk], layout: ReferenceLayout, - file: Path | None = None, + file: Path | bytes | None = None, *, accept_short: Callable[[str], bool] | None = None, ) -> list[ReferenceList]: @@ -568,7 +569,7 @@ def reference_lists( The paper's passages, in order. layout: ReferenceLayout The caller's thresholds. - file: pathlib.Path | None, optional + file: pathlib.Path | bytes | None, optional The paper on disk, for a PDF's column order. Defaults to ``None``. accept_short: Callable[[str], bool] | None, optional As for ``numbered_reference_entries``. @@ -601,7 +602,7 @@ def reference_lists( def reference_entries( passages: Sequence[Chunk], layout: ReferenceLayout, - file: Path | None = None, + file: Path | bytes | None = None, ) -> list[str]: """Split the paper's reference list into entries, as printed. @@ -611,7 +612,7 @@ def reference_entries( The paper's passages, in order. layout: ReferenceLayout The caller's thresholds for splitting and filtering entries. - file: pathlib.Path | None, optional + file: pathlib.Path | bytes | None, optional The paper on disk, for a PDF's column order (``reference_list``). Defaults to ``None``. @@ -631,7 +632,7 @@ def reference_entries( def numbered_reference_entries( passages: Sequence[Chunk], layout: ReferenceLayout, - file: Path | None = None, + file: Path | bytes | None = None, *, accept_short: Callable[[str], bool] | None = None, which: int = -1, @@ -644,7 +645,7 @@ def numbered_reference_entries( The paper's passages, in order. layout: ReferenceLayout The caller's thresholds for splitting and filtering entries. - file: pathlib.Path | None, optional + file: pathlib.Path | bytes | None, optional The paper on disk, for a PDF's column order (``reference_list``). Defaults to ``None``. accept_short: Callable[[str], bool] | None, optional @@ -921,14 +922,14 @@ def _joined_numbers(lines: list[str]) -> list[str]: return joined -def _source_text(passages: Sequence[Chunk], file: Path | None) -> str: +def _source_text(passages: Sequence[Chunk], file: Path | bytes | None) -> str: """Return the text a reference list is read from. Parameters ---------- passages: Sequence[Chunk] The paper's passages, in order. - file: pathlib.Path | None + file: pathlib.Path | bytes | None The paper on disk, or None. Returns @@ -990,7 +991,7 @@ def joined_text(passages: Sequence[Chunk]) -> str: return "\n".join(parts) -def pdf_text(file: Path) -> str: +def pdf_text(file: Path | bytes) -> str: """Return a PDF's text with each page read in column order. ``pdfminer.six`` orders text boxes in a way that can interleave the @@ -1003,8 +1004,8 @@ def pdf_text(file: Path) -> str: Parameters ---------- - file: pathlib.Path - A file on disk. + file: pathlib.Path | bytes + A file on disk or verified PDF bytes. Returns ------- @@ -1014,6 +1015,8 @@ def pdf_text(file: Path) -> str: """ + if isinstance(file, bytes): + return _pdf_text(file, 0, len(file)) if file.suffix.lower() != ".pdf" or not file.is_file(): return "" @@ -1022,13 +1025,13 @@ def pdf_text(file: Path) -> str: @lru_cache(maxsize=8) -def _pdf_text(file: str, modified: int, size: int) -> str: +def _pdf_text(file: str | bytes, modified: int, size: int) -> str: """Return a PDF's column-ordered text, cached per file version. Parameters ---------- - file: str - The PDF on disk. + file: str | bytes + The PDF on disk or its verified content. modified: int Its modification time in nanoseconds, so an edited file is read again. @@ -1047,7 +1050,10 @@ def _pdf_text(file: str, modified: int, size: int) -> str: from pdfminer.high_level import extract_pages from pdfminer.layout import LAParams, LTTextContainer, LTTextLine - pages = list(extract_pages(file, laparams=LAParams())) + pages = list(extract_pages( + BytesIO(file) if isinstance(file, bytes) else file, + laparams=LAParams(), + )) except Exception: # Unreadable PDF: the caller uses the passages. return "" diff --git a/kilin/tools/_shared/report_selection.py b/kilin/tools/_shared/report_selection.py new file mode 100644 index 00000000..34133d7a --- /dev/null +++ b/kilin/tools/_shared/report_selection.py @@ -0,0 +1,574 @@ +"""Discover report templates without sharing a workspace namespace. + +The two bundled report tools share a syntax, but not resources or limits. +Inspect each namespace using its owner's rules. Resolve named requests +across the report namespaces so an ambiguous title cannot silently select +a report with a different scope. + +Key Features +------------ + +- Read only the two known report namespaces, never arbitrary plugin files. +- Recognize exact qualified paths and explicit document or project scope. +- Keep existing report-name matching and deterministic diagnostics. + +Module Structure +---------------- + +- ``report_entries`` and ``sibling_report_entries``: inspect namespaces. +- ``report_matches`` and ``select_report_matches``: resolve named requests. +- ``report_intent_override``: resolve explicit report routing cues. + +Examples +-------- +>>> from kilin.tools._shared.report_selection import qualified_references +>>> qualified_references('use templates/project_summary/report.md') +(('project_summary', 'report'),) + +""" + +from __future__ import annotations + +from pathlib import Path +import re +from typing import TYPE_CHECKING, Final, TypeAlias +from unicodedata import normalize + +from kilin.source_eligibility import without_source_filenames +from kilin.tools._registry import ( + TOOL_GENERATE_PAPER_SUMMARY, + TOOL_PROJECT_SUMMARY, + registered_tools, +) +from kilin.tools._shared.report_templates import ( + ReportTemplate, + SCOPE_DOCUMENT, + SCOPE_PROJECT, + TemplateRules, + TemplateScope, + load_template, + template_names, +) +from kilin.workspace_resources import templates_folder + +if TYPE_CHECKING: + from kilin.project_type import ProjectType + +__all__ = [ + "CHECK_TEMPLATE", + "LIST_TEMPLATES", + "ReportEntry", + "OwnedReportEntry", + "report_entries", + "sibling_report_entries", + "qualified_references", + "without_report_references", + "report_matches", + "select_report_matches", + "report_intent_override", +] + +ReportEntry: TypeAlias = tuple[str, ReportTemplate | None, str] +OwnedReportEntry: TypeAlias = tuple[str, ReportEntry] +_OWNERS: Final[tuple[str, str]] = ( + TOOL_GENERATE_PAPER_SUMMARY, TOOL_PROJECT_SUMMARY, +) +_QUALIFIED_START: Final[re.Pattern[str]] = re.compile( + r"(?:(?P[`'\"])|(?" + r"[a-z][a-z0-9_]*)/", + re.I, +) +_PATH_END: Final[str] = r"(?=$|[\s,;:!?)\]}]|\.(?![\w./-]))" +_BARE_MARKDOWN: Final[re.Pattern[str]] = re.compile( + r"[^/\\\r\n`\"]*?\.md" + _PATH_END, + re.I, +) +_PROJECT_SCOPE: Final[re.Pattern[str]] = re.compile( + r"\b(?:(?:whole|entire)\s+(?:project|collection)|" + r"(?:all|every)\s+(?:of\s+)?(?:the\s+)?" + r"(?:papers|documents|articles)|" + r"(?:project|collection)\s+(?:report(?:\s+templates?)?|templates?)|" + r"summari[sz]e\s+(?:this|the|my|our)\s+(?:project|collection))\b", + re.I, +) +_DOCUMENT_SCOPE: Final[re.Pattern[str]] = re.compile( + r"\b(?:(?:one|single|individual)\s+(?:paper|document|article)|" + r"(?:paper|document)\s+report)\b", re.I, +) +LIST_TEMPLATES: Final[re.Pattern[str]] = re.compile( + r"\b(?:list|which|what|show|available)\b[^\n]{0,40}\btemplates\b" + r"|\btemplates\b[^\n]{0,40}\b(?:do\s+(?:i|we)\s+have|available)\b", + re.I, +) +CHECK_TEMPLATE: Final[re.Pattern[str]] = re.compile( + r"\b(?:check|validate|test|verify)\b[^\n]{0,40}\btemplate\b", re.I, +) + + +def report_entries( + folder: Path, rules: TemplateRules, scope: TemplateScope, +) -> list[ReportEntry]: + """Read one namespace with its owning report tool's validation rules. + + Parameters + ---------- + folder: pathlib.Path + Explicit template namespace. + rules: TemplateRules + Limits of the tool that consumes these templates. + scope: TemplateScope + Scope required by the namespace. + + Returns + ------- + list[ReportEntry] + Sorted IDs, parsed templates, and validation problems. Invalid + files, including misplaced report templates, are not selectable. + + """ + + found = [] + for name in template_names(folder): + try: + template = load_template(name, folder, rules) + if template.scope != scope: + if scope == SCOPE_PROJECT: + raise ValueError( + f"{name}: individual-document template belongs to " + "individual documents, not project reports." + ) + raise ValueError( + f"{name}: template is for project reports, " + "not individual papers." + ) + except (ValueError, UnicodeError, OSError) as error: + found.append((name, None, str(error))) + else: + found.append((name, template, "")) + return found + + +def sibling_report_entries( + project_root: Path, owner: str, +) -> list[ReportEntry]: + """Inspect the other report namespace for cross-report diagnostics. + + Parameters + ---------- + project_root: pathlib.Path + Project workspace. + owner: str + Identifier of the executing report tool. + + Returns + ------- + list[ReportEntry] + Sibling report entries, validated with its own packaged limits; + empty if the sibling folder is absent or cannot be safely read. + + Notes + ----- + Only these two report tools participate. An unrelated plugin need not + use the report syntax. Never import the sibling's executable module + from the caller, or traverse a linked sibling directory. + + """ + + other = next(name for name in _OWNERS if name != owner) + try: + folder = templates_folder(project_root, other) + except (ValueError, OSError): + return [] + if not folder.is_dir(): + return [] + data = registered_tools()[other].internal_defaults["TEMPLATE_VALIDATION"] + rules = TemplateRules( + limit_tolerance=data["LIMIT_TOLERANCE"], + min_total_words=data["MIN_TOTAL_WORDS"], + ) + scope = SCOPE_PROJECT if other == TOOL_PROJECT_SUMMARY else SCOPE_DOCUMENT + return report_entries(folder, rules, scope) + + +def _fold_name(name: str) -> str: + """Normalize case and equivalent Unicode spellings for name matching. + + Parameters + ---------- + name: str + Filename stem, title or text containing a template reference. + + Returns + ------- + str + Case-folded NFC text, independent of filesystem normalization. + + """ + + return normalize("NFC", name.casefold()) + + +def _qualified_mentions( + question: str, +) -> list[tuple[str, str, tuple[int, int]]]: + """Find complete qualified template paths and their text spans. + + Parameters + ---------- + question: str + User request containing workspace-relative report paths. + + Returns + ------- + list of tuple + Owner, case-folded stem, and span of each reference, including + delimiters. An unclosed delimiter produces an empty stem. + + Notes + ----- + Quoted paths take their entire filename literally. A bare Markdown + path ends at the first complete .md suffix; an extensionless path + consumes the remaining text up to the next reference or line break. + Never truncate a possible filename at its first space or period. + + """ + + starts = list(_QUALIFIED_START.finditer(question)) + mentions = [] + for index, match in enumerate(starts): + stop = (starts[index + 1].start() if index + 1 < len(starts) + else len(question)) + tail = question[match.end():stop].split("\n", 1)[0] + quote = match["quote"] + if quote: + closing = tail.find(quote) + filename = tail[:closing] if closing >= 0 else "" + length = closing + 1 if closing >= 0 else len(tail) + else: + markdown = _BARE_MARKDOWN.match(tail) + filename = (markdown[0] if markdown else + tail.rstrip(" \t\r.,;:!?)]}")) + length = len(filename) + stem = _fold_name(filename) + if stem.endswith(".md"): + stem = stem[:-3] + mentions.append((match["owner"].casefold(), stem, + (match.start(), match.end() + length))) + return mentions + + +def qualified_references(question: str) -> tuple[tuple[str, str], ...]: + """Return distinct explicitly qualified report references. + + Parameters + ---------- + question: str + User request, optionally naming a workspace-relative template path. + + Returns + ------- + tuple[tuple[str, str], ...] + Tool IDs and normalized, case-folded stems in mention order. A + malformed quoted path retains its owner with an empty stem so + routing can return a diagnostic instead of selecting a default. + + """ + + return tuple(dict.fromkeys( + (owner, stem) for owner, stem, _ in _qualified_mentions(question) + if owner in _OWNERS + )) + + +def without_report_references(question: str) -> str: + """Remove qualified template paths before selecting a source document. + + Parameters + ---------- + question: str + Original request, possibly naming a template and a source. + + Returns + ------- + str + Question without the qualified template paths. + + """ + + # Remove exactly the same spans used to resolve the requested format. + for _, _, (start, end) in reversed(_qualified_mentions(question)): + question = question[:start] + " " + question[end:] + return question + + +def _scope_owner(question: str) -> str | None: + """Recognize an unambiguous explicit report-scope phrase. + + Parameters + ---------- + question: str + User request. + + Returns + ------- + str or None + Report owner if exactly one scope is requested. + + """ + + project = bool(_PROJECT_SCOPE.search(question)) + document = bool(_DOCUMENT_SCOPE.search(question)) + if project == document: + return None + return TOOL_PROJECT_SUMMARY if project else TOOL_GENERATE_PAPER_SUMMARY + + +def _alias_spans(alias: str, text: str) -> list[tuple[int, int]]: + """Find complete mentions of a report alias in normalized text. + + Parameters + ---------- + alias: str + Template name, filename or title. + text: str + Case-folded, NFC-normalized request with collapsed whitespace. + + Returns + ------- + list of tuple + Matching character spans, allowing natural separator variants. + + """ + + words = [word for word in re.split(r"[\s_-]+", _fold_name(alias)) + if word] + if not words: + return [] + pattern = r"(? list[OwnedReportEntry]: + """Find named entries across the two report namespaces. + + Parameters + ---------- + question: str + User request. + inventories: dict[str, list[ReportEntry]] + Entries grouped by report owner. + + Returns + ------- + list[OwnedReportEntry] + Matched entries, retaining namespace identity. Exact qualified + paths take precedence; a scope phrase resolves cross-tool ties. + + Raises + ------ + ValueError + If a qualified path is malformed, ambiguous, belongs to another + tool, or does not identify an existing report template. + + """ + + entries = [(owner, entry) for owner, values in inventories.items() + for entry in values] + mentions = _qualified_mentions(question) + qualified = tuple(dict.fromkeys( + (owner, name) for owner, name, _ in mentions + )) + if qualified: + for owner, _ in qualified: + if owner not in _OWNERS: + raise ValueError( + f"Template namespace {owner!r} belongs to another " + "tool, not a built-in report tool." + ) + # A bare .md terminator can also occur inside a longer filename. + # If the longer reading is present in the inventory, require a + # quote instead of silently choosing a shorter format. + for owner, _, (start, end) in mentions: + if question[start] in "`'\"": + continue + tail = _fold_name(question[start:]) + path = _fold_name(question[start:end]) + for key, entry in entries: + if key != owner: + continue + candidate = f"templates/{owner}/{_fold_name(entry[0])}.md" + if (candidate.startswith(path) and len(candidate) > len(path) + and re.match(re.escape(candidate) + _PATH_END, tail)): + raise ValueError( + "Ambiguous unquoted report path. Name exactly one " + "template by its complete path in backticks or quotes." + ) + matches = [] + for owner, name in qualified: + if not name: + raise ValueError( + f"Invalid qualified report reference for {owner!r}. " + "Name a complete template path." + ) + named = [(key, entry) for key, entry in entries + if key == owner and _fold_name(entry[0]) == name] + if not named: + raise ValueError( + f"Unknown report template `templates/{owner}/{name}.md`. " + "Add it to that tool's template folder or name another." + ) + matches.extend(named) + return matches + + # Discard shorter aliases embedded in longer matches, across namespaces. + # Separate mentions and identical titles remain distinct candidates. + text = " ".join(_fold_name(question).split()) + hits: list[tuple[int, tuple[int, int]]] = [] + for index, (_, (name, template, _)) in enumerate(entries): + aliases = {name, f"{name}.md"} + if template is not None: + aliases.add(template.title) + for alias in aliases: + hits.extend((index, span) for span in _alias_spans(alias, text)) + surviving = [(index, (start, end)) for index, (start, end) in hits + if not any( + left <= start and end <= right + and (left, right) != (start, end) + for _, (left, right) in hits + )] + matched = {index for index, _ in surviving} + result = [item for index, item in enumerate(entries) if index in matched] + scope = _scope_owner(question) + # A scope resolves a shared alias, not two separately named reports. + spans = {owner: {span for index, span in surviving + if entries[index][0] == owner} for owner in _OWNERS} + if scope and spans[_OWNERS[0]] == spans[_OWNERS[1]]: + result = [item for item in result if item[0] == scope] + return result + + +def select_report_matches( + question: str, owner: str, found: list[ReportEntry], + other: list[ReportEntry], +) -> list[ReportEntry]: + """Resolve named entries for one report tool without cross-scope use. + + Parameters + ---------- + question: str + User request. + owner: str + Executing report tool's identifier. + found: list[ReportEntry] + Entries in its own namespace. + other: list[ReportEntry] + Entries in the sibling namespace. + + Returns + ------- + list[ReportEntry] + Named entries from the executing namespace only. + + Raises + ------ + ValueError + If the request names another namespace or is ambiguous across them. + + """ + + sibling = next(name for name in _OWNERS if name != owner) + matches = report_matches(question, {owner: found, sibling: other}) + if any(key != owner for key, _ in matches): + paths = ", ".join(f"`templates/{key}/{entry[0]}.md`" + for key, entry in matches) + if len(matches) > 1: + raise ValueError( + f"Several report templates match: {paths}. " + "Name exactly one by its qualified path." + ) + raise ValueError( + f"{paths} belongs to " + + ("individual-document reports, not whole-project reports." + if owner == TOOL_PROJECT_SUMMARY else + "whole-project reports, not individual papers.") + ) + return [entry for _, entry in matches] + + +def report_intent_override( + project: ProjectType, question: str, matched: tuple[str, ...], +) -> str | None: + """Prefer explicit report namespace or scope over cue ordering. + + Parameters + ---------- + project: ProjectType + Effective project type with dynamic tool cues. + question: str + User request. + matched: tuple[str, ...] + Intent IDs whose regular expressions matched the question. + + Returns + ------- + str or None + Explicitly selected report intent, otherwise None (keep existing + cue ordering). No model or filesystem operation is performed. + + """ + + qualified = qualified_references(question) + by_owner = { + owner: [(key, intent) for key, intent in project.intents.items() + if intent.tool is not None and intent.tool.name == owner] + for owner in _OWNERS + } + action = without_source_filenames(without_report_references(question)) + if LIST_TEMPLATES.search(action) or CHECK_TEMPLATE.search(action): + # The existing inventory/check operation belongs to the document + # tool but may describe both namespaces without running a report. + if qualified or any(key in matched for key, _ in + by_owner[TOOL_GENERATE_PAPER_SUMMARY]): + candidates = by_owner[TOOL_GENERATE_PAPER_SUMMARY] + generic = [key for key, intent in candidates + if intent.tool.settings.template == "choose"] + if generic: + return generic[0] + if qualified: + owner, name = qualified[0] + candidates = by_owner[owner] + if not candidates: + # A different report tool can provide a wrong-scope diagnostic. + return next((key for other in _OWNERS + for key, _ in by_owner[other]), None) + fixed = [key for key, intent in candidates + if _fold_name(intent.tool.settings.template) == name] + generic = [key for key, intent in candidates + if intent.tool.settings.template == "choose"] + return (fixed or generic or [key for key, _ in candidates])[0] + scope = _scope_owner(action) + if scope and by_owner[scope] and any( + key in matched for owner in _OWNERS if owner != scope + for key, _ in by_owner[owner] + ): + candidates = by_owner[scope] + cued = [key for key, _ in candidates if key in matched] + if cued: + return cued[0] + # A fixed report intent need not contribute a dynamic cue. A + # sibling's cue must not override an explicit report scope. + text = " ".join(_fold_name(action).split()) + fixed = [key for key, intent in candidates + if intent.tool.settings.template != "choose" + and _alias_spans(intent.tool.settings.template, text)] + if len(fixed) == 1: + return fixed[0] + generic = [key for key, intent in candidates + if intent.tool.settings.template == "choose"] + if generic: + return generic[0] + return None diff --git a/kilin/tools/_shared/report_templates.py b/kilin/tools/_shared/report_templates.py index 5f309cbb..ca139ed8 100644 --- a/kilin/tools/_shared/report_templates.py +++ b/kilin/tools/_shared/report_templates.py @@ -11,8 +11,8 @@ (``generate_paper_summary`` for one document, ``project_summary`` for a whole project). Each tool ships its own templates in its package and passes its own limits as ``TemplateRules``. Each project has its own -``templates/`` folder, next to ``sources/`` and ``outputs/`` and never -indexed; adding a ``.md`` file there adds a format, deleting it removes the +``templates//`` directory for each report tool, never indexed; +adding a ``.md`` file there adds a format, and deleting it removes that format only from that project. Templates are read fresh on every load, so edits apply at once. A template diff --git a/kilin/tools/_shared/search_sources.py b/kilin/tools/_shared/search_sources.py new file mode 100644 index 00000000..ac50a28e --- /dev/null +++ b/kilin/tools/_shared/search_sources.py @@ -0,0 +1,119 @@ +"""Resolve physical or documentary scope for exhaustive search tools. + +Use the accepted source generation before any passage ranking or scan. +Physical requests retain file-level counts; paper requests enumerate only +independent current document targets. Explicit restrictions never widen. + +Key Features +------------ +- Bound source selection and pre-fusion ranking. +- Physical membership for literal file searches and bibliography lookup. +- Explicit coverage of selected members without indexed text. + +Module Structure +---------------- +- ``search_sources``: choose a project-wide or named source view. +- ``restrict_sources``: bind a narrower view without changing its policy. +- ``unindexed_sources``: list selected members lacking original passages. + +Examples +-------- +>>> from kilin.tools._shared.search_sources import restrict_sources +>>> callable(restrict_sources) +True + +""" + +from __future__ import annotations + +from pathlib import Path +from collections.abc import Sequence + +from kilin.retrievals.document_reading import named_paths +from kilin.source_eligibility import paper_request +from kilin.source_views import SourcePolicy, SourceScope +from kilin.tools._contract import ( + ToolContext, ToolRequest, ToolSourceServices, require_source_services, +) + +__all__ = ["search_sources", "restrict_sources", "unindexed_sources"] + + +def search_sources( + request: ToolRequest, context: ToolContext, +) -> ToolSourceServices: + """Bind the project scope for a paper or physical-file search. + + Parameters + ---------- + request: ToolRequest + User wording determines documentary versus literal physical scope. + context: ToolContext + Host that owns the accepted semantic and indexed generation. + + Returns + ------- + ToolSourceServices + Bound project selection. Named ineligible documentary files produce + an empty restriction rather than silently searching other files. + + """ + policy = SourcePolicy( + purpose="document" if paper_request(request.question) else "lookup", + ) + services = require_source_services(context, policy) + # A named physical file must not disappear from the document operands + # just because it cannot be treated as an independent publication. + selected = services.view.operation.inventory.selected + named = named_paths(request.question, selected, authors=True) + eligible = {path.as_posix() for path in services.view.targets} + if any(path.as_posix() not in eligible for path in named): + return restrict_sources(context, services, ()) + return services + + +def restrict_sources( + context: ToolContext, services: ToolSourceServices, + paths: Sequence[Path], +) -> ToolSourceServices: + """Bind exact physical operands under the already accepted policy. + + Parameters + ---------- + context: ToolContext + Host for the same operation. + services: ToolSourceServices + Existing project or restricted selection. + paths: Sequence[pathlib.Path] + Selected operands, including an intentional empty restriction. + + Returns + ------- + ToolSourceServices + A restricted view, without ranking excluded members. + + """ + allowed = {path.as_posix() for path in services.view.targets} + if any(path.as_posix() not in allowed for path in paths): + raise ValueError("Source scope contains an ineligible operand.") + return require_source_services( + context, services.view.operation.policy, + SourceScope("restricted", tuple(paths)), + ) + + +def unindexed_sources(services: ToolSourceServices) -> tuple[Path, ...]: + """List selected physical files without searchable passages. + + Parameters + ---------- + services: ToolSourceServices + Final view; excluded files are not coverage omissions. + + Returns + ------- + tuple[pathlib.Path, ...] + Selected members lacking indexed text. + + """ + return tuple(item.path for item in services.files if not item.indexed) diff --git a/kilin/tools/_shared/source_access.py b/kilin/tools/_shared/source_access.py index 49097f1f..253f637f 100644 --- a/kilin/tools/_shared/source_access.py +++ b/kilin/tools/_shared/source_access.py @@ -42,13 +42,14 @@ from __future__ import annotations -from collections.abc import Collection from pathlib import Path -from kilin.tools._contract import ToolContext +from kilin._source_access import selected_source_file +from kilin.tools._contract import ToolContext, ToolSourceServices __all__ = [ "selected_paths", + "optional_source_bytes", "selected_source_file", ] @@ -59,8 +60,8 @@ def selected_paths(context: ToolContext) -> frozenset[Path]: Parameters ---------- context: ToolContext - Tool services and selected source inventory. Legacy mock contexts - without ``source_files`` use their indexed paths. + Tool services with the required ``source_files`` inventory callback. + Scoped consumers use bound source services instead. Returns ------- @@ -68,71 +69,42 @@ def selected_paths(context: ToolContext) -> frozenset[Path]: Names authorized for the current project. An available but empty inventory remains empty and is not replaced by stale index data. + Raises + ------ + RuntimeError + If the host does not provide a callable source inventory. + """ inventory = getattr(context, "source_files", None) - if callable(inventory): - return frozenset(inventory()) - return frozenset(chunk.path for chunk in context.chunks) + if not callable(inventory): + raise RuntimeError( + "Source inventory requires ToolContext.source_files." + ) + return frozenset(inventory()) -def selected_source_file( - project_root: Path, - source_root: Path, - path: Path, - selected: Collection[Path], -) -> Path | None: - """Locate one selected regular file under the project source root. +def optional_source_bytes( + services: ToolSourceServices, path: Path, +) -> bytes | None: + """Read a verified member unless raw access was unavailable at capture. Parameters ---------- - 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. + services: ToolSourceServices + Bound physical access service. path: pathlib.Path - Source-relative file path, as recorded by the source inventory. - selected: Collection[pathlib.Path] - Explicitly selected source-relative file paths. + Exact member to read. Returns ------- - pathlib.Path | None - Validated source file path, or ``None`` if the selection, file, - source root, containment or symlink conditions fail. - - 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. + bytes | None + Verified content, or None for recorded raw unavailability. A stale + identity or unauthorized member is an error, not a fallback. """ - - if not isinstance(path, Path) or path.is_absolute(): - return None - if not path.parts or any(part in ("", ".", "..") for part in path.parts): - return None - if path not in selected: + if any(item.path.as_posix() == path.as_posix() + and item.reason == "raw_unavailable" + for item in services.view.unavailable): return None - try: - root = project_root.resolve(strict=True) - source = source_root.resolve(strict=True) - if ( - source_root.is_symlink() - or not source.is_relative_to(root) - or not source.is_dir() - ): - return None - candidate = source - for part in path.parts: - candidate = candidate / part - if candidate.is_symlink(): - return None - target = candidate.resolve(strict=True) - if target.is_relative_to(source) and target.is_file(): - return candidate - except (OSError, ValueError): - pass - return None + return services.read_bytes(path) diff --git a/kilin/tools/assistant_guide/CHANGELOG.md b/kilin/tools/assistant_guide/CHANGELOG.md new file mode 100644 index 00000000..f9a92daa --- /dev/null +++ b/kilin/tools/assistant_guide/CHANGELOG.md @@ -0,0 +1,5 @@ +# assistant_guide changelog + +This changelog records changes to the `assistant_guide` tool. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/kilin/tools/assistant_guide/README.md b/kilin/tools/assistant_guide/README.md index 15a447f4..2aca088f 100644 --- a/kilin/tools/assistant_guide/README.md +++ b/kilin/tools/assistant_guide/README.md @@ -1,6 +1,6 @@ # assistant_guide -This package owns the `assistant_guide` registered tool. It answers "What can you do for me?" with one ready-to-send example question for each kind of request the project type supports, written about the project's own files and topics by `kilin.question_suggestions`. Every answer 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, and a question about files, such as "how to drag files" or "What do you mean by adding files?", gets only what sources are and these steps, without the examples. A project without sources is told how to add its files first, followed by the project type's fixed suggestions. No model writes the answer; when the source-specific pool is not saved yet, the tool can call the router once to pick phrases for the examples. Projects with indexed sources but no fillable examples keep the fixed suggestions without being described as empty. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type tool settings override the keys in `SETTINGS`. Other sections are internal execution parameters. All values are read and validated on import. +This package owns the `assistant_guide` registered tool. It answers "What can you do for me?" with one ready-to-send example question for each kind of request the project type supports, written about the project's own files and topics by `kilin.question_suggestions`. Every answer 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, and a question about files, such as "how to drag files" or "What do you mean by adding files?", gets only what sources are and these steps, without the examples. A project without sources is told how to add its files first, followed by the project type's fixed suggestions. The answer is composed deterministically; when the source-specific suggestion pool is missing or invalid, the suggestion service can call the router to pick phrases for the examples. Projects with indexed sources but no fillable examples keep the fixed suggestions without being described as empty. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type intent settings override packaged `SETTINGS` values; saved project-specific overrides take precedence for exposed settings. See the [configuration policy](../../../docs/configuration.md#tool-configuration-and-resources). Other sections are internal execution parameters. Packaged values are validated on import. ## Defaults @@ -11,8 +11,9 @@ This package owns the `assistant_guide` registered tool. It answers "What can yo ## Generation settings -The answer is written without a model call, so output allowances do not -apply. +The answer is composed deterministically, so answering-model output +allowances do not apply. On-demand suggestion-pool generation can use the +router with its own bounded settings. `MODEL_CALLS` contains one key: `THINKING` (packaged value `"inherit"`). It accepts `inherit`, `on`, or `off` for internal `context.ask_model` calls, diff --git a/kilin/tools/assistant_guide/__init__.py b/kilin/tools/assistant_guide/__init__.py index 25d08d65..f0ac0ad3 100644 --- a/kilin/tools/assistant_guide/__init__.py +++ b/kilin/tools/assistant_guide/__init__.py @@ -18,6 +18,10 @@ Module Structure ---------------- +- ``PLUGIN`` + + Versioned descriptor discovered by the tool registry. + - ``parse_settings`` and ``run`` The registry entry points for this tool. @@ -30,14 +34,28 @@ """ -from kilin.tools.assistant_guide.tool import ( +from kilin.tools import Tool + +from .tool import ( GuideSettings, parse_settings, run, ) __all__ = [ + "PLUGIN", "GuideSettings", "parse_settings", "run", ] + + +PLUGIN = Tool( + name="assistant_guide", + summary="Answer what KíLín can do with one ready-to-send example question " + "per kind of request, about the project's own files.", + parse_settings=parse_settings, + run=run, + version="0.1.0", + api_version=1, +) diff --git a/kilin/tools/assistant_guide/tool.py b/kilin/tools/assistant_guide/tool.py index feaeed19..2113bf6f 100644 --- a/kilin/tools/assistant_guide/tool.py +++ b/kilin/tools/assistant_guide/tool.py @@ -67,14 +67,14 @@ import re from typing import Final -from kilin.tools._contract import ( +from kilin.tools import ( ToolContext, ToolRequest, ToolResult, check_int, reject_unknown, ) -from kilin.tools.assistant_guide import _configuration as _config +from . import _configuration as _config __all__ = [ "GuideSettings", diff --git a/kilin/tools/batch_classify/CHANGELOG.md b/kilin/tools/batch_classify/CHANGELOG.md new file mode 100644 index 00000000..06e83600 --- /dev/null +++ b/kilin/tools/batch_classify/CHANGELOG.md @@ -0,0 +1,5 @@ +# batch_classify changelog + +This changelog records changes to the `batch_classify` tool. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/kilin/tools/batch_classify/README.md b/kilin/tools/batch_classify/README.md index 1d509097..af0644ef 100644 --- a/kilin/tools/batch_classify/README.md +++ b/kilin/tools/batch_classify/README.md @@ -1,6 +1,12 @@ # batch_classify -This package owns the `batch_classify` registered tool. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type tool settings override the keys in `SETTINGS`. Other sections are internal execution parameters. All values are read and validated on import. +This package owns the `batch_classify` registered tool. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type intent settings override packaged `SETTINGS` values; saved project-specific overrides take precedence for exposed settings. See the [configuration policy](../../../docs/configuration.md#tool-configuration-and-resources). Other sections are internal execution parameters. Packaged values are validated on import. + +The scan uses the same accepted source view as `scan_and_list`. Literal +physical scans include selected dependents, retained versions and +bibliographies; paper-oriented wording selects independent current document +anchors without automatic relationship expansion. Unsearchable members are +reported separately and never classified as negative matches. ## Defaults @@ -43,7 +49,7 @@ may use an explicit smaller cap, never exceeding the user's maximum. Changing `THINKING` to `inherit` resets this tool to the main setting; `on` forces thinking and bypasses local short-response caps. Restart after editing cached defaults. See the [shared policy](../../../docs/configuration.md#internal-tool-thinking) -for precedence, the retained exceptions, and migration of obsolete keys. +for precedence, output-limit exceptions, and configuration validation. ## Partial completion diff --git a/kilin/tools/batch_classify/__init__.py b/kilin/tools/batch_classify/__init__.py index b954321e..5e436b70 100644 --- a/kilin/tools/batch_classify/__init__.py +++ b/kilin/tools/batch_classify/__init__.py @@ -18,6 +18,10 @@ Module Structure ---------------- +- ``PLUGIN`` + + Versioned descriptor discovered by the tool registry. + - ``parse_settings`` and ``run`` The registry entry points for this tool. @@ -30,7 +34,9 @@ """ -from kilin.tools.batch_classify.tool import ( +from kilin.tools import Tool + +from .tool import ( CANDIDATES_MENTIONS, CANDIDATE_CHOICES, UNCLEAR, @@ -51,6 +57,7 @@ ) __all__ = [ + "PLUGIN", "CANDIDATES_MENTIONS", "CANDIDATE_CHOICES", "UNCLEAR", @@ -69,3 +76,14 @@ "quick_sample", "validated_categories", ] + + +PLUGIN = Tool( + name="batch_classify", + summary="Sort every exact mention into categories with the answering " + "model, and count each category.", + parse_settings=parse_settings, + run=run, + version="0.1.0", + api_version=1, +) diff --git a/kilin/tools/batch_classify/tool.py b/kilin/tools/batch_classify/tool.py index 7643c64b..12146f52 100644 --- a/kilin/tools/batch_classify/tool.py +++ b/kilin/tools/batch_classify/tool.py @@ -64,11 +64,11 @@ from time import perf_counter from typing import Final, Literal, TypeAlias -from kilin.tools._shared.model_results import partial_result +from kilin.tools import partial_result from kilin._model_completion import IncompleteModelResponse from kilin.retrievals.document_reading import estimate_tokens -from kilin.tools.batch_classify import _configuration as _config -from kilin.tools._contract import ( +from . import _configuration as _config +from kilin.tools import ( ToolContext, ToolRequest, ToolResult, @@ -76,7 +76,7 @@ check_int, reject_unknown, ) -from kilin.tools._shared.planning import ( +from kilin.tools import ( CONFIRMATION_CHOICES, PLAN_CHOICE_CANCEL, PLAN_CHOICE_QUICK, @@ -428,6 +428,8 @@ def run( }, turn_id=context.trace_turn_id, ) + if found.services is not None: + found.services.validate() classified = sorted(index for batch in runs for index in batch) evidence = classification_evidence( scan, labels, categories, settings.max_listed @@ -442,6 +444,13 @@ def run( quick=choice == PLAN_CHOICE_QUICK, scope_note=found.scope_note, ) + if found.unsearchable: + answer += ( + "\n\nSelected files without searchable text were not " + "classified: " + ", ".join( + path.as_posix() for path in found.unsearchable + ) + "." + ) counts = {category: 0 for category in [*categories, UNCLEAR]} for label in labels.values(): counts[label.category] += 1 diff --git a/kilin/tools/batch_review/CHANGELOG.md b/kilin/tools/batch_review/CHANGELOG.md new file mode 100644 index 00000000..f68fa195 --- /dev/null +++ b/kilin/tools/batch_review/CHANGELOG.md @@ -0,0 +1,5 @@ +# batch_review changelog + +This changelog records changes to the `batch_review` tool. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/kilin/tools/batch_review/README.md b/kilin/tools/batch_review/README.md index 8b92d1d7..dc629db5 100644 --- a/kilin/tools/batch_review/README.md +++ b/kilin/tools/batch_review/README.md @@ -1,6 +1,9 @@ # batch_review -This package owns the `batch_review` registered tool. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type tool settings override the keys in `SETTINGS`. Other sections are internal execution parameters. All values are read and validated on import. +This package owns the `batch_review` registered tool. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type intent settings override packaged `SETTINGS` values; saved project-specific overrides take precedence for exposed settings. See the [configuration policy](../../../docs/configuration.md#tool-configuration-and-resources). Other sections are internal execution parameters. Packaged values are validated on import. + +Independent document discovery excludes bibliography containers. Explicit +lookup of a named bibliography remains possible as a physical-file operation. ## Defaults @@ -49,7 +52,7 @@ may use an explicit smaller cap, never exceeding the user's maximum. Changing `THINKING` to `inherit` resets this tool to the main setting; `on` forces thinking and bypasses local short-response caps. Restart after editing cached defaults. See the [shared policy](../../../docs/configuration.md#internal-tool-thinking) -for precedence, the retained exceptions, and migration of obsolete keys. +for precedence, output-limit exceptions, and configuration validation. ## Partial completion @@ -59,3 +62,25 @@ synthesis receives a coverage warning. Useful completed work is returned with `status: partial` and `incomplete_items`. No usable notes means an incomplete result without synthesis. The shared internal adapter may retry unfinished, length-limited thinking once without thinking; final `write` is not retried. + +### Source organization settings + +- `TARGET_ROLES` (`target_roles`, default `[]`): eligible anchor roles. +- `EVIDENCE_ROLES` (`evidence_roles`, default `[]`): eligible related roles. +- `RELATED_EVIDENCE` (`related_evidence`, default `[]`): accepted relation + identifiers to expand. Empty disables expansion. Empty role lists impose + no extra role restriction. Project overrides retain their precedence. + +Only original indexed passages of the chosen target and explicitly permitted +related evidence are used. Bibliography links are not scientific evidence. +Coverage identifies each physical member; unindexed or omitted material is +not negative evidence. + +Reading parts never mix physical members. The anchor is read first, then +related members in relative-path order, each in indexed passage order. +`max_model_calls` limits planned reading-part calls across the group; final +synthesis/section calls and existing bounded recovery are separate. + +Quick reads return only completed original passage citations, with their +original numbering. The coverage report distinguishes capped, unindexed, +missing and completed members. diff --git a/kilin/tools/batch_review/__init__.py b/kilin/tools/batch_review/__init__.py index 9ac4ec2c..c832536d 100644 --- a/kilin/tools/batch_review/__init__.py +++ b/kilin/tools/batch_review/__init__.py @@ -18,6 +18,10 @@ Module Structure ---------------- +- ``PLUGIN`` + + Versioned descriptor discovered by the tool registry. + - ``parse_settings`` and ``run`` The registry entry points for this tool. @@ -30,16 +34,33 @@ """ -from kilin.tools.batch_review.tool import ( +from kilin.tools import Tool + +from .tool import ( ReviewSettings, answer_prompt, parse_settings, + source_policies, run, ) __all__ = [ + "source_policies", + "PLUGIN", "ReviewSettings", "answer_prompt", "parse_settings", "run", ] + + +PLUGIN = Tool( + name="batch_review", + summary="Read one whole document in parts, taking notes with passage " + "numbers, then answer from the notes.", + parse_settings=parse_settings, + source_policies=source_policies, + run=run, + version="0.1.0", + api_version=1, +) diff --git a/kilin/tools/batch_review/_configuration.py b/kilin/tools/batch_review/_configuration.py index 2c3f1080..3d9d8374 100644 --- a/kilin/tools/batch_review/_configuration.py +++ b/kilin/tools/batch_review/_configuration.py @@ -32,6 +32,8 @@ from __future__ import annotations +from kilin.tools import check_source_ids + from pathlib import Path from typing import Final @@ -50,6 +52,10 @@ ) __all__ = [ + "DEFAULT_TARGET_ROLES", + "DEFAULT_EVIDENCE_ROLES", + "DEFAULT_RELATED_EVIDENCE", + "ANSWER_REPLY_TOKENS", "NOTE_REPLY_TOKENS", "MODEL_CALLS", @@ -79,6 +85,7 @@ "MAX_MODEL_CALLS", "CONFIRMATION", "LARGE_BATCHES", + "TARGET_ROLES", "EVIDENCE_ROLES", "RELATED_EVIDENCE", }, "batch_review.SETTINGS" ) DEFAULT_PART_TOKENS: Final[int] = ( @@ -144,3 +151,13 @@ MODEL_CALLS: Final[ModelCallSettings] = load_model_call_settings( Path(__file__).with_name("defaults.json") ) + +DEFAULT_TARGET_ROLES: Final[tuple[str, ...]] = check_source_ids( + "batch_review.SETTINGS", _SETTINGS, "TARGET_ROLES" +) +DEFAULT_EVIDENCE_ROLES: Final[tuple[str, ...]] = check_source_ids( + "batch_review.SETTINGS", _SETTINGS, "EVIDENCE_ROLES" +) +DEFAULT_RELATED_EVIDENCE: Final[tuple[str, ...]] = check_source_ids( + "batch_review.SETTINGS", _SETTINGS, "RELATED_EVIDENCE" +) diff --git a/kilin/tools/batch_review/defaults.json b/kilin/tools/batch_review/defaults.json index 4b580f69..23d12e6f 100644 --- a/kilin/tools/batch_review/defaults.json +++ b/kilin/tools/batch_review/defaults.json @@ -3,7 +3,10 @@ "PART_TOKENS": 6000, "MAX_MODEL_CALLS": 20, "CONFIRMATION": "when_large", - "LARGE_BATCHES": 3 + "LARGE_BATCHES": 3, + "TARGET_ROLES": [], + "EVIDENCE_ROLES": [], + "RELATED_EVIDENCE": [] }, "ESTIMATES": { "PROMPT_TOKENS_PER_SECOND": 700.0, diff --git a/kilin/tools/batch_review/settings_info.json b/kilin/tools/batch_review/settings_info.json index 4e0765f3..240828b6 100644 --- a/kilin/tools/batch_review/settings_info.json +++ b/kilin/tools/batch_review/settings_info.json @@ -4,12 +4,12 @@ "part_tokens": { "title": "Part token budget", "summary": "Sets the token budget for one part of a multi-part operation.", - "description": "Constrains the context provided for each model call when work is split into parts." + "description": "Estimated tokens per physical reading part. An oversized indivisible passage remains a single part; parts never mix different physical files." }, "max_model_calls": { "title": "Maximum model calls", - "summary": "Caps model calls permitted for one tool operation.", - "description": "Limits computational cost and processing time. Work may stop early before every candidate is examined." + "summary": "Caps planned reading-part calls across all members.", + "description": "One shared limit for the chosen anchor and its evidence members, in physical source order. Synthesis, section writing and existing bounded model recovery are separate." }, "confirmation": { "title": "Confirmation policy", @@ -20,6 +20,21 @@ "title": "Large workload threshold", "summary": "Sets the batch threshold used by the confirmation policy.", "description": "Used to decide whether a planned multi-batch operation is large enough to request confirmation." + }, + "target_roles": { + "title": "Target roles", + "summary": "Restricts eligible document anchors.", + "description": "Accepted role identifiers. Empty permits all eligible anchors." + }, + "evidence_roles": { + "title": "Related evidence roles", + "summary": "Restricts supporting member roles.", + "description": "Accepted role identifiers. Empty permits any eligible related evidence role." + }, + "related_evidence": { + "title": "Related evidence", + "summary": "Selects relationships for group reading.", + "description": "Accepted relation identifiers. Empty reads only the selected physical document." } } } diff --git a/kilin/tools/batch_review/tool.py b/kilin/tools/batch_review/tool.py index 5cce04b0..742083fb 100644 --- a/kilin/tools/batch_review/tool.py +++ b/kilin/tools/batch_review/tool.py @@ -56,28 +56,34 @@ from __future__ import annotations -from kilin.tools._shared.model_results import partial_result +from kilin.tools import partial_result from kilin.tools._shared.citations import inspect_citations from kilin.tools._shared.document_notes import ( NOTHING, - plan_parts, take_notes, ) from collections.abc import Sequence -from dataclasses import dataclass +from dataclasses import dataclass, replace from time import perf_counter from typing import Final from kilin.retrievals.document_reading import ( - DOCUMENT_REASON_SEARCH, + DOCUMENT_REASON_NAMED_FUNCTION, + named_paths, estimate_tokens, read_document, ) -from kilin.tools._shared.choose_document import choose_document +from kilin.retrievals._scope import scoped_graph +from kilin.tools._shared.group_reading import ( + choose_group, reading_policy, bind_group, +) +from kilin.tools import ( + SourcePolicy, check_source_ids, require_source_services, +) from kilin.tools._shared.term_filter import term_hits, term_label -from kilin.tools.batch_review import _configuration as _config -from kilin.tools._contract import ( +from . import _configuration as _config +from kilin.tools import ( ToolContext, ToolRequest, ToolResult, @@ -85,7 +91,7 @@ check_int, reject_unknown, ) -from kilin.tools._shared.planning import ( +from kilin.tools import ( CONFIRMATION_CHOICES, PLAN_CHOICE_CANCEL, PLAN_CHOICE_QUICK, @@ -95,6 +101,7 @@ ) __all__ = [ + "source_policies", "ReviewSettings", "answer_prompt", "parse_settings", @@ -125,12 +132,22 @@ class ReviewSettings: With ``when_large``, plans with more parts than this ask first (0-100). + target_roles: tuple[str, ...] + Eligible anchor roles; empty means unrestricted. + evidence_roles: tuple[str, ...] + Eligible related evidence roles; empty means unrestricted. + related_evidence: tuple[str, ...] + Accepted relation identifiers to expand; empty reads only the anchor. + """ part_tokens: int = _config.DEFAULT_PART_TOKENS max_model_calls: int = _config.DEFAULT_MAX_MODEL_CALLS confirmation: ConfirmationPolicy = _config.DEFAULT_CONFIRMATION large_batches: int = _config.DEFAULT_LARGE_BATCHES + target_roles: tuple[str, ...] = _config.DEFAULT_TARGET_ROLES + evidence_roles: tuple[str, ...] = _config.DEFAULT_EVIDENCE_ROLES + related_evidence: tuple[str, ...] = _config.DEFAULT_RELATED_EVIDENCE def parse_settings(data: dict, where: str) -> ReviewSettings: @@ -163,6 +180,7 @@ def parse_settings(data: dict, where: str) -> ReviewSettings: "max_model_calls", "confirmation", "large_batches", + "target_roles", "evidence_roles", "related_evidence", ), ) defaults = ReviewSettings() @@ -183,9 +201,31 @@ def parse_settings(data: dict, where: str) -> ReviewSettings: large_batches=check_int( where, data, "large_batches", defaults.large_batches, 0, 100 ), + target_roles=check_source_ids( + where, data, "target_roles", defaults.target_roles + ), + evidence_roles=check_source_ids( + where, data, "evidence_roles", defaults.evidence_roles + ), + related_evidence=check_source_ids( + where, data, "related_evidence", defaults.related_evidence + ), ) +def source_policies(settings: ReviewSettings) -> tuple[SourcePolicy, ...]: + """Declare the reading policy for accepted vocabulary validation. + + Parameters + ---------- + settings: ReviewSettings + Validated settings for this tool. + + """ + return (reading_policy(settings.target_roles, settings.evidence_roles, + settings.related_evidence),) + + def answer_prompt( question: str, name: str, @@ -217,7 +257,8 @@ def answer_prompt( system = ( "You answer questions for KíLín from notes taken while reading a " - "document in full. Use only the notes, and cite passage numbers " + "selected document and permitted related sources. Distinguish their " + "physical origins. Use only the notes, and cite passage numbers " "exactly as the notes give them, like [12]." ) blocks = "\n\n".join( @@ -254,7 +295,7 @@ def run( Returns ------- ToolResult - The streamed answer, every passage of the document as evidence, + The streamed answer, successfully processed passages as evidence, and a summary with parts read, notes, and citation checks. Notes @@ -267,50 +308,52 @@ def run( trace = context.trace context.progress("Finding the document to read") - ranked = context.rank(request.text) - selection = read_document( - request.text, - context.chunks, - context.graph, - ranked, - max_tokens=10**9, - top=context.retrieval_count, + policy = source_policies(settings)[0] + targets = require_source_services( + context, SourcePolicy(target_roles=policy.target_roles), ) summary: dict[str, object] = {"name": "batch_review"} - if selection is not None and selection.reason == DOCUMENT_REASON_SEARCH: - # Only a search guessed the file: use the earlier turns, or ask. - chosen = choose_document( - request, - context, - question="Which document should I read in full?", - example="read smith2020.pdf and say which software it uses", - ) - if isinstance(chosen, str): - context.done("No document chosen", evidence_count=0) - return ToolResult(chosen, (), summary) - summary["chosen"] = chosen[1] + # Exact functions remain a physical operation. Do not let an excluded + # file or graph endpoint influence the initial document choice. + selection = None + if targets.chunks and not named_paths( + request.question, targets.view.operation.inventory.selected + ): + ranked = targets.rank(request.text) selection = read_document( - request.text, - context.chunks, - context.graph, - ranked, - max_tokens=10**9, - top=context.retrieval_count, - path=chosen[0], + request.text, targets.chunks, + scoped_graph(context.graph, frozenset(targets.view.targets)), + ranked, max_tokens=10**9, top=context.retrieval_count, ) - if selection is None: - context.done("No document found to read", evidence_count=0) - return ToolResult( - "I couldn't find a document to read. Name the file, for " - "example: read smith2020.pdf and say which software it uses.", - (), - summary, + if selection is not None and selection.reason == ( + DOCUMENT_REASON_NAMED_FUNCTION + ): + reading = bind_group( + context, SourcePolicy(target_roles=policy.target_roles), + selection.path, selection.reason, False, + ) + reading = replace(reading, chunks=tuple(selection.chunks), + functions=selection.functions) + else: + reading = choose_group( + request, context, policy, targets=targets, + question="Which document should I read in full?", + example="read smith2020.pdf and say which software it uses", ) - passages = list(selection.chunks) - name = selection.path.name - if selection.functions: - name = f"{', '.join(selection.functions)} in {name}" - parts = plan_parts(passages, settings.part_tokens) + if isinstance(reading, str): + context.done("No document chosen", evidence_count=0) + return ToolResult(reading, (), summary) + if not reading.chunks: + context.done("No indexed passages", evidence_count=0) + summary["member_coverage"] = reading.coverage(()) + return ToolResult("No indexed passages to read. " + reading.notice(()), + (), summary) + passages = list(reading.chunks) + ranked = reading.services.rank(request.text) + name = reading.anchor.name + if reading.functions: + name = f"{', '.join(reading.functions)} in {name}" + parts = reading.parts(settings.part_tokens) to_read = parts[: settings.max_model_calls] texts = [chunk.text for chunk in passages] order = {chunk.identifier: index for index, chunk in enumerate(passages)} @@ -319,25 +362,26 @@ def run( for result in ranked if result.chunk.identifier in order ] + if not relevant: + relevant = list(range(len(passages))) # Quick: the passages that mention the question's exact terms, when it # names any; otherwise the most relevant passages that fit one part. terms, hits = term_hits(request.question, context, passages) - quick_parts = ( - [[hits[i] for i in part] for part in plan_parts( - [passages[i] for i in hits], settings.part_tokens - )] - if terms - else [sorted(_fit(relevant, texts, settings.part_tokens))] - ) + quick_parts = reading.parts( + settings.part_tokens, + hits if terms else _fit(relevant, texts, settings.part_tokens), + )[:settings.max_model_calls] quick = [index for part in quick_parts for index in part] label, note = term_label(terms, hits) if terms else ("", "") + if terms and len(quick) < len(hits): + note += f"; the reading cap permits only {len(quick)}." plan = ToolPlan( tool="batch_review", summary=( - f"Read all {len(passages)} passages of {name} in " + f"Read all {len(passages)} passages for {name} in " f"{len(parts)} parts, then answer from the notes." ), - scope=f"{selection.path.as_posix()} ({selection.reason})", + scope=f"{reading.anchor.as_posix()} ({reading.reason})", items=len(passages), batches=len(parts), batches_to_run=len(to_read), @@ -356,7 +400,8 @@ def run( 1, ), details=( - f"About {selection.estimated_tokens:,} tokens", + f"About {sum(estimate_tokens(t) for t in texts):,} tokens", + reading.notice(()), f"Model: {context.model_id}", ), quick_label=label, @@ -367,15 +412,16 @@ def run( ) summary.update( { - "document": selection.path.as_posix(), - "functions": list(selection.functions), - "reason": selection.reason, + "document": reading.anchor.as_posix(), + "functions": list(reading.functions), + "reason": reading.reason, "passages": len(passages), "plan": plan.to_dict(), "choice": choice, "asked": asked, } ) + summary["member_coverage"] = reading.coverage(()) if choice == PLAN_CHOICE_CANCEL: context.done("Cancelled before reading", evidence_count=0) return ToolResult( @@ -390,13 +436,22 @@ def run( context.done(f"No passage mentions {quoted}", evidence_count=0) summary.update({"terms": list(terms), "term_hits": 0}) return ToolResult( - f"No passage of {name} mentions {quoted}; all {len(passages)} " + f"No indexed passage selected for {name} mentions {quoted}; " + f"all {len(passages)} available " "passages were checked for these words. Ask again and choose " - "Continue to read it in full for related wording.", + "Continue to read available passages for related wording. " + + reading.notice(()), (), summary, ) runs = quick_parts if choice == PLAN_CHOICE_QUICK else to_read + if not runs: + context.done("No fitting indexed passages", evidence_count=0) + return ToolResult( + "No fitting indexed passages to read. " + reading.notice(()), + (), summary, + ) + reading.validate() started = perf_counter() failures: list[dict[str, object]] = [] notes = take_notes( @@ -407,15 +462,22 @@ def run( context, what=( "function" - if selection.functions + if reading.functions else "paper" - if selection.path.suffix.lower() == ".pdf" + if reading.anchor.suffix.lower() == ".pdf" else "file" ), - whole=choice != PLAN_CHOICE_QUICK, + whole=choice != PLAN_CHOICE_QUICK and all( + row["complete"] for row in reading.coverage( + i for part in runs for i in part + ) + ), failures=failures, + paths=[c.path for c in passages], ) read = sorted(index for number, _ in notes for index in runs[number - 1]) + summary["member_coverage"] = reading.coverage(read) + notice = reading.notice(read) if failures and not any(lines for _, lines in notes): return partial_result( ToolResult( @@ -424,20 +486,27 @@ def run( failures, completed=False, ) context.done( - f"Read {len(read)} of {len(passages)} passages of {name}", + f"Read {len(read)} of {len(passages)} passages for {name}", evidence_count=len(read), ) system, prompt = answer_prompt( request.question, name, notes, len(runs), request.guidance ) + if notice: + prompt += "\n\n" + notice + prompt += reading.part_sources(runs, notes) if failures: prompt += ( "\n\nSome reading parts failed. Answer only from the supplied " "notes; do not infer absence from missing notes." ) + reading.validate() answer = context.write(system, prompt, None) + reading.validate() citation_report = inspect_citations(answer, len(passages)) - invalid = list(citation_report.invalid_numbers) + invalid = sorted(set(citation_report.invalid_numbers) | ( + citation_report.valid - {i + 1 for i in read} + )) if choice == PLAN_CHOICE_QUICK or len(read) < len(passages): answer += ( f"\n\n*Read {len(read)} of {len(passages)} passages of {name}" @@ -452,10 +521,15 @@ def run( ) + "*" ) + if notice: + answer += "\n\n*" + notice + "*" summary.update( { "parts_read": len(notes), "passages_read": len(read), + "reading_complete": all( + row["complete"] for row in summary["member_coverage"] + ), "notes": sum(len(lines) for _, lines in notes), "parts_without_notes": [ part for part, lines in notes if not lines @@ -490,7 +564,7 @@ def run( "cell": chunk.cell, } for index, chunk in enumerate(passages) - if not failures or index in read + if index in read ) return partial_result( ToolResult(answer, evidence, summary, streamed=True), failures, @@ -522,8 +596,8 @@ def _fit( used = 0 for index in order: size = estimate_tokens(texts[index]) - if chosen and used + size > part_tokens: - break + if used + size > part_tokens: + continue chosen.append(index) used += size return chosen diff --git a/kilin/tools/filter_results/CHANGELOG.md b/kilin/tools/filter_results/CHANGELOG.md new file mode 100644 index 00000000..382b99e2 --- /dev/null +++ b/kilin/tools/filter_results/CHANGELOG.md @@ -0,0 +1,5 @@ +# filter_results changelog + +This changelog records changes to the `filter_results` tool. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/kilin/tools/filter_results/README.md b/kilin/tools/filter_results/README.md index c3e5017b..821ad6fc 100644 --- a/kilin/tools/filter_results/README.md +++ b/kilin/tools/filter_results/README.md @@ -1,6 +1,10 @@ # filter_results -This package owns the `filter_results` registered tool. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type tool settings override the keys in `SETTINGS`. Other sections are internal execution parameters. All values are read and validated on import. +This package owns the `filter_results` registered tool. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type intent settings override packaged `SETTINGS` values; saved project-specific overrides take precedence for exposed settings. See the [configuration policy](../../../docs/configuration.md#tool-configuration-and-resources). Other sections are internal execution parameters. Packaged values are validated on import. + +Filtering operates exclusively on saved items from the earlier turn. It does +not perform a new source search or assert that the cited text is current. The +result records the earlier-turn origin. ## Defaults @@ -42,7 +46,7 @@ may use an explicit smaller cap, never exceeding the user's maximum. Changing `THINKING` to `inherit` resets this tool to the main setting; `on` forces thinking and bypasses local short-response caps. Restart after editing cached defaults. See the [shared policy](../../../docs/configuration.md#internal-tool-thinking) -for precedence, the retained exceptions, and migration of obsolete keys. +for precedence, output-limit exceptions, and configuration validation. ## Partial completion diff --git a/kilin/tools/filter_results/__init__.py b/kilin/tools/filter_results/__init__.py index f0c4a62c..f2dd721e 100644 --- a/kilin/tools/filter_results/__init__.py +++ b/kilin/tools/filter_results/__init__.py @@ -18,6 +18,10 @@ Module Structure ---------------- +- ``PLUGIN`` + + Versioned descriptor discovered by the tool registry. + - ``parse_settings`` and ``run`` The registry entry points for this tool. @@ -30,7 +34,9 @@ """ -from kilin.tools.filter_results.tool import ( +from kilin.tools import Tool + +from .tool import ( FilterSettings, filter_prompt, parse_settings, @@ -38,8 +44,21 @@ ) __all__ = [ + "PLUGIN", "FilterSettings", "filter_prompt", "parse_settings", "run", ] + + +PLUGIN = Tool( + name="filter_results", + summary="Judge each item an earlier answer listed and keep those that " + "match a follow-up.", + parse_settings=parse_settings, + run=run, + follows_up=True, + version="0.1.0", + api_version=1, +) diff --git a/kilin/tools/filter_results/tool.py b/kilin/tools/filter_results/tool.py index 4394b6c1..619aaaa7 100644 --- a/kilin/tools/filter_results/tool.py +++ b/kilin/tools/filter_results/tool.py @@ -69,11 +69,11 @@ from dataclasses import dataclass from typing import Final -from kilin.tools._shared.model_results import partial_result +from kilin.tools import partial_result from kilin._model_completion import IncompleteModelResponse from kilin.retrievals.document_reading import estimate_tokens -from kilin.tools.filter_results import _configuration as _config -from kilin.tools._contract import ( +from . import _configuration as _config +from kilin.tools import ( ToolContext, ToolRequest, ToolResult, @@ -241,9 +241,10 @@ def run( "item": f"Filter batch {index}", "items": [number for number, _ in batch], **error.to_dict(), }) - summary.update( - {"turn": turn.number, "items": len(items), "matched": len(picked)} - ) + summary.update({ + "turn": turn.number, "items": len(items), "matched": len(picked), + "source_origin": "earlier_turn", + }) context.done( f"{len(picked)} of {len(items)} items match", evidence_count=len(picked), @@ -251,7 +252,7 @@ def run( lines = [ f"**{len(picked)} of {len(items)}** items from turn {turn.number} " - "match." + "match (using the saved items, not a new source search)." ] evidence = [] for citation, number in enumerate(picked, start=1): diff --git a/kilin/tools/find_fact/CHANGELOG.md b/kilin/tools/find_fact/CHANGELOG.md new file mode 100644 index 00000000..4585d55b --- /dev/null +++ b/kilin/tools/find_fact/CHANGELOG.md @@ -0,0 +1,5 @@ +# find_fact changelog + +This changelog records changes to the `find_fact` tool. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/kilin/tools/find_fact/README.md b/kilin/tools/find_fact/README.md index 3f7c9769..a25efb1a 100644 --- a/kilin/tools/find_fact/README.md +++ b/kilin/tools/find_fact/README.md @@ -1,6 +1,13 @@ # find_fact -This package owns the `find_fact` registered tool. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type tool settings override the keys in `SETTINGS`. Other sections are internal execution parameters. All values are read and validated on import. +This package owns the `find_fact` registered tool. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type intent settings override packaged `SETTINGS` values; saved project-specific overrides take precedence for exposed settings. See the [configuration policy](../../../docs/configuration.md#tool-configuration-and-resources). Other sections are internal execution parameters. Packaged values are validated on import. + +Fact searches bind the accepted source generation before ranking or +reading. Paper-oriented wording selects independent current document anchors; +physical lookup includes selected dependents, retained versions and +bibliographies. No related-file expansion is implicit. Named ineligible +operands do not widen the search, and selected files without indexed text +are reported as coverage omissions. ## Defaults @@ -53,7 +60,7 @@ may use an explicit smaller cap, never exceeding the user's maximum. Changing `THINKING` to `inherit` resets this tool to the main setting; `on` forces thinking and bypasses local short-response caps. Restart after editing cached defaults. See the [shared policy](../../../docs/configuration.md#internal-tool-thinking) -for precedence, the retained exceptions, and migration of obsolete keys. +for precedence, output-limit exceptions, and configuration validation. ## Partial completion diff --git a/kilin/tools/find_fact/__init__.py b/kilin/tools/find_fact/__init__.py index b7398921..74b42f98 100644 --- a/kilin/tools/find_fact/__init__.py +++ b/kilin/tools/find_fact/__init__.py @@ -18,6 +18,10 @@ Module Structure ---------------- +- ``PLUGIN`` + + Versioned descriptor discovered by the tool registry. + - ``parse_settings`` and ``run`` The registry entry points for this tool. @@ -30,7 +34,9 @@ """ -from kilin.tools.find_fact.tool import ( +from kilin.tools import Tool + +from .tool import ( FactSettings, fact_prompt, parse_settings, @@ -38,8 +44,20 @@ ) __all__ = [ + "PLUGIN", "FactSettings", "fact_prompt", "parse_settings", "run", ] + + +PLUGIN = Tool( + name="find_fact", + summary="Find a specific fact in one paper or every paper by reading " + "every passage; the user can choose a quick answer instead.", + parse_settings=parse_settings, + run=run, + version="0.1.0", + api_version=1, +) diff --git a/kilin/tools/find_fact/tool.py b/kilin/tools/find_fact/tool.py index 968b7fa1..8bc212f4 100644 --- a/kilin/tools/find_fact/tool.py +++ b/kilin/tools/find_fact/tool.py @@ -95,7 +95,7 @@ from time import perf_counter from typing import Final -from kilin.tools._shared.model_results import partial_result +from kilin.tools import partial_result from kilin.chunking import Chunk from kilin.retrievals.document_reading import estimate_tokens from kilin.tools._shared.citations import inspect_citations @@ -106,8 +106,11 @@ take_notes, ) from kilin.tools._shared.choose_document import document_scope -from kilin.tools.find_fact import _configuration as _config -from kilin.tools._contract import ( +from kilin.tools._shared.search_sources import ( + restrict_sources, search_sources, unindexed_sources, +) +from . import _configuration as _config +from kilin.tools import ( ToolContext, ToolRequest, ToolResult, @@ -115,7 +118,7 @@ check_int, reject_unknown, ) -from kilin.tools._shared.planning import ( +from kilin.tools import ( CONFIRMATION_CHOICES, PLAN_CHOICE_CANCEL, PLAN_CHOICE_QUICK, @@ -316,14 +319,35 @@ def run( started = perf_counter() summary: dict[str, object] = {"name": "find_fact"} context.progress("Finding the documents to read") - indexed = list(dict.fromkeys(chunk.path for chunk in context.chunks)) - scope, why = document_scope(request, context.ask_router, indexed) - files = scope or indexed + sources = search_sources(request, context) + summary["unsearchable_files"] = [ + p.as_posix() for p in unindexed_sources(sources) + ] + if not sources.chunks: + context.done("No eligible documents", evidence_count=0) + return ToolResult( + "The requested scope has no eligible indexed documents.", + (), summary, + ) + scope, why = document_scope( + request, context.ask_router, list(sources.view.targets) + ) + if scope: + sources = restrict_sources(context, sources, scope) + files = list(dict.fromkeys(chunk.path for chunk in sources.chunks)) + unavailable = unindexed_sources(sources) + summary["unsearchable_files"] = [p.as_posix() for p in unavailable] + if not files: + context.done("No eligible documents", evidence_count=0) + return ToolResult( + "The requested scope has no eligible indexed documents.", + (), summary, + ) # One passage numbering across all files: each file's parts hold # indices into ``passages``. per_file = [ - (path, [chunk for chunk in context.chunks if chunk.path == path]) + (path, [chunk for chunk in sources.chunks if chunk.path == path]) for path in files ] passages: list[Chunk] = [ @@ -344,7 +368,7 @@ def run( order = {chunk.identifier: index for index, chunk in enumerate(passages)} ranking = list(dict.fromkeys( order[result.chunk.identifier] - for result in context.rank(request.text) + for result in sources.rank(request.text) if result.chunk.identifier in order )) ranked = ranking[: context.retrieval_count] @@ -448,7 +472,6 @@ def run( request.question, quick_by_file, texts, - settings, context, whole=False, failures=failures, @@ -494,7 +517,6 @@ def run( request.question, in_budget, texts, - settings, context, whole=True, failures=failures, @@ -509,6 +531,7 @@ def run( ), failures, completed=False, ) + sources.validate() context.done( f"Read {read} of {len(passages)} passages", evidence_count=read, @@ -525,7 +548,11 @@ def run( "\n\nSome reading parts failed. Answer only from the supplied " "notes; do not infer absence from missing notes." ) + if unavailable: + prompt += ("\n\nSome selected files have no indexed text. " + "Do not infer facts or absence from those files.") answer = context.write(system, prompt, None) + sources.validate() number_of = {index: number for number, index in numbering.items()} answer, quotes = quote_citations( answer, {number_of[index]: texts[index] for index in given} @@ -551,6 +578,10 @@ def run( f"\n\n*Read {read} of {len(passages)} passages; " "reading coverage is incomplete.*" ) + if unavailable: + answer += "\n\n*No searchable text: " + ", ".join( + path.as_posix() for path in unavailable + ) + ".*" summary.update( { "files": len(files), @@ -583,7 +614,7 @@ def run( "cell": passages[index].cell, } for number, index in numbering.items() - if number in cited + if number in cited and index in given ) return partial_result( ToolResult(answer, evidence, summary, streamed=True), failures, @@ -594,7 +625,6 @@ def _notes( question: str, parts_by_file: Sequence[tuple[Path, list[list[int]]]], texts: Sequence[str], - settings: FactSettings, context: ToolContext, *, whole: bool, @@ -613,8 +643,6 @@ def _notes( Selected text parts grouped by source file. texts: Sequence[str] Text passages or fields to inspect. - settings: FactSettings - Settings used to configure the operation. context: ToolContext Tool context for the current request. whole: bool diff --git a/kilin/tools/find_passages/CHANGELOG.md b/kilin/tools/find_passages/CHANGELOG.md new file mode 100644 index 00000000..a538527b --- /dev/null +++ b/kilin/tools/find_passages/CHANGELOG.md @@ -0,0 +1,5 @@ +# find_passages changelog + +This changelog records changes to the `find_passages` tool. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/kilin/tools/find_passages/README.md b/kilin/tools/find_passages/README.md index 07be9d8f..92b7e719 100644 --- a/kilin/tools/find_passages/README.md +++ b/kilin/tools/find_passages/README.md @@ -1,6 +1,13 @@ # find_passages -This package owns the `find_passages` registered tool. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type tool settings override the keys in `SETTINGS`. Other sections are internal execution parameters. All values are read and validated on import. +This package owns the `find_passages` registered tool. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type intent settings override packaged `SETTINGS` values; saved project-specific overrides take precedence for exposed settings. See the [configuration policy](../../../docs/configuration.md#tool-configuration-and-resources). Other sections are internal execution parameters. Packaged values are validated on import. + +Passage searches use the same accepted source view for exact matches, +ranking and exhaustive reading. Paper-oriented wording selects independent +current document anchors; physical lookup includes selected dependents, +retained versions and bibliographies. No related-file expansion is implicit. +Selected files without indexed text are reported, and long-list exports +validate the view after confirmation before writing. ## Defaults @@ -56,7 +63,7 @@ may use an explicit smaller cap, never exceeding the user's maximum. Changing `THINKING` to `inherit` resets this tool to the main setting; `on` forces thinking and bypasses local short-response caps. Restart after editing cached defaults. See the [shared policy](../../../docs/configuration.md#internal-tool-thinking) -for precedence, the retained exceptions, and migration of obsolete keys. +for precedence, output-limit exceptions, and configuration validation. ## Partial completion diff --git a/kilin/tools/find_passages/__init__.py b/kilin/tools/find_passages/__init__.py index c224e1ca..62a5298b 100644 --- a/kilin/tools/find_passages/__init__.py +++ b/kilin/tools/find_passages/__init__.py @@ -18,6 +18,10 @@ Module Structure ---------------- +- ``PLUGIN`` + + Versioned descriptor discovered by the tool registry. + - ``parse_settings`` and ``run`` The registry entry points for this tool. @@ -30,8 +34,10 @@ """ +from kilin.tools import Tool + from kilin.tools._shared.sentences import Sentence, split_sentences -from kilin.tools.find_passages.tool import ( +from .tool import ( PassageSettings, judge_prompt, parse_settings, @@ -40,6 +46,7 @@ ) __all__ = [ + "PLUGIN", "PassageSettings", "Sentence", "judge_prompt", @@ -48,3 +55,14 @@ "split_sentences", "topic_prompt", ] + + +PLUGIN = Tool( + name="find_passages", + summary="Read every sentence in scope and list the ones about a topic, " + "copied word for word.", + parse_settings=parse_settings, + run=run, + version="0.1.0", + api_version=1, +) diff --git a/kilin/tools/find_passages/tool.py b/kilin/tools/find_passages/tool.py index 5ad92bc6..2bd7d19f 100644 --- a/kilin/tools/find_passages/tool.py +++ b/kilin/tools/find_passages/tool.py @@ -110,14 +110,17 @@ import re from typing import Final -from kilin.tools._shared.model_results import partial_result +from kilin.tools import partial_result from kilin._model_completion import IncompleteModelResponse from kilin.retrievals.document_reading import estimate_tokens, named_paths from kilin.tools._shared.choose_document import document_scope -from kilin.tools.find_passages import _configuration as _config +from kilin.tools._shared.search_sources import ( + restrict_sources, search_sources, unindexed_sources, +) +from . import _configuration as _config from kilin.tools._shared.model_results import selected_numbers from kilin.tools._shared.sentences import Sentence, split_sentences -from kilin.tools._contract import ( +from kilin.tools import ( ToolContext, ToolRequest, ToolResult, @@ -130,7 +133,7 @@ file_name, offer_export, ) -from kilin.tools._shared.planning import ( +from kilin.tools import ( CONFIRMATION_CHOICES, PLAN_CHOICE_CANCEL, PLAN_CHOICE_QUICK, @@ -382,6 +385,16 @@ def run( """ summary: dict[str, object] = {"name": "find_passages"} + sources = search_sources(request, context) + summary["unsearchable_files"] = [ + p.as_posix() for p in unindexed_sources(sources) + ] + if not sources.chunks: + context.done("No eligible documents", evidence_count=0) + return ToolResult( + "The requested scope has no eligible indexed documents.", + (), summary, + ) context.progress("Finding the topic") topic, document, by_file = _topic(request.question, context) summary.update({"topic": topic, "document": document}) @@ -396,16 +409,23 @@ def run( # The router's document phrase is a fallback for a document that # ``document_scope`` does not find in the question itself. - indexed = list(dict.fromkeys(chunk.path for chunk in context.chunks)) - scope, _ = document_scope(request, context.ask_router, indexed) + targets = list(sources.view.targets) + scope, _ = document_scope(request, context.ask_router, targets) if not scope and document: - scope = named_paths(document, indexed, authors=True) + scope = named_paths(document, targets, authors=True) + if scope: + sources = restrict_sources(context, sources, scope) + unavailable = unindexed_sources(sources) + summary["unsearchable_files"] = [p.as_posix() for p in unavailable] + eligible = {chunk.path for chunk in sources.chunks} + if not eligible: + context.done("No eligible documents", evidence_count=0) + return ToolResult( + "The requested scope has no eligible indexed documents.", + (), summary, + ) chunks = sorted( - ( - chunk - for chunk in context.chunks - if not scope or chunk.path in scope - ), + sources.chunks, key=lambda chunk: (str(chunk.path), chunk.start_line), ) sentences = split_sentences(chunks, min_words=_config.MIN_WORDS) @@ -416,7 +436,10 @@ def run( # one, found by Python without the model; otherwise the sentences of # the best-ranked passages, judged by the model. terms, hits = term_hits(request.question, context, chunks) - ranked = context.rank(topic) if context.chunks else [] + ranked = [ + result for result in sources.rank(topic) + if result.chunk.path in eligible + ] if eligible else [] if terms: quick_chunks = [chunks[index] for index in hits] else: @@ -497,6 +520,7 @@ def run( ) if exact_only: summary["exact_terms"] = list(terms) + sources.validate() context.done( f"Found {len(found)} sentences", evidence_count=len(found) ) @@ -526,7 +550,9 @@ def run( + f" about “{topic}”", name=file_name("passages", topic), markdown=full.answer, + validate=sources.validate, ) + sources.validate() if saved: summary["saved"] = saved.as_posix() counts = full.answer.split("\n", 1)[0] @@ -834,6 +860,9 @@ def _result( "coverage is incomplete." ) + unavailable = summary.get("unsearchable_files", []) + if unavailable: + lines.append("No searchable text: " + ", ".join(unavailable) + ".") names = short_names(sorted({sentence.path for sentence in found}, key=str)) if by_file: # One line per file: how many sentences match, and the first one. @@ -855,7 +884,7 @@ def _result( if not found: lines.append( "No match established; some files remain unassessed." - if summary.get("incomplete_items") + if summary.get("incomplete_items") or unavailable else "No file in scope matches." ) return partial_result( @@ -881,7 +910,7 @@ def _result( if not found: lines.append( "No match established; some sentences remain unassessed." - if summary.get("incomplete_items") + if summary.get("incomplete_items") or unavailable else "No sentence in scope is about this topic." ) return partial_result( diff --git a/kilin/tools/generate_paper_summary/CHANGELOG.md b/kilin/tools/generate_paper_summary/CHANGELOG.md new file mode 100644 index 00000000..3dcf01a5 --- /dev/null +++ b/kilin/tools/generate_paper_summary/CHANGELOG.md @@ -0,0 +1,5 @@ +# generate_paper_summary changelog + +This changelog records changes to the `generate_paper_summary` tool. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/kilin/tools/generate_paper_summary/README.md b/kilin/tools/generate_paper_summary/README.md index 4c8705db..948486ab 100644 --- a/kilin/tools/generate_paper_summary/README.md +++ b/kilin/tools/generate_paper_summary/README.md @@ -6,6 +6,9 @@ sections, checks their structure and length, and saves the report to the project's `outputs/` directory. The model can still make factual errors: validation checks structure, not scientific correctness. +Bibliography containers (`.bib` and `.bbl`) are excluded from paper +selection. Explicit saved-output operands retain their existing behavior. + ## Selecting the source paper or a saved output An explicitly named file in `outputs/` can be used as input to a new report. @@ -58,13 +61,13 @@ The tool is a self-contained package: ## Configuration and precedence The `SETTINGS` section supplies defaults for the tool's -`SummarySettings`. Each intent's `tool` entry in -`kilin/project_types/.json` may override these six settings. -Missing keys use this tool's packaged defaults, **not** values from -`kilin_defaults.json`. The remaining sections are tool-internal -heuristics and estimation parameters; they are not project-type settings. -Project-type overrides of unrelated core KíLín defaults are not yet -supported and belong to a separate configuration-precedence change. +`SummarySettings`. The selected project-type intent's `tool` entry can +override the documented settings, and saved project-specific overrides take +precedence for exposed settings. Omitted keys retain the preceding layer's +value. See the [configuration policy](../../../docs/configuration.md#tool-configuration-and-resources). +Tool defaults are independent of `kilin_defaults.json`. The remaining +sections are tool-internal configuration, not per-intent or saved project +overrides. All packaged values are validated before the tool is usable. Values are read once per Python process; edits require restarting KíLín. No tool @@ -74,7 +77,7 @@ uses the global README to define its settings. | Key | Default | Meaning and validation | | --- | --- | --- | -| `TEMPLATE` | `research_briefing` | Default template ID when no format is named; a safe filename stem, without `.md` or directory separators. | +| `TEMPLATE` | `research_briefing` | Default template ID when no format is named; a safe filename stem, without `.md` or directory separators, or `choose` for automatic selection of the only valid template or an explicit choice. | | `PART_TOKENS` | 6000 | Approximate paper tokens read per model call; integer, 1000–16000. | | `REPAIR_ATTEMPTS` | 1 | Allowed targeted revisions of a nonconforming section; integer, 0–4. | | `MAX_MODEL_CALLS` | 20 | Limit on paper-reading parts; integer, 1–200. | @@ -175,7 +178,8 @@ controls whether a PDF renderer is available through `ToolContext`. An intent whose `template` setting is `"choose"` (`templated_report`, in the Literature and Writing Assistant project types) uses any template in the -project's `templates/` folder, so anyone can add a report format by adding +project's `templates/generate_paper_summary/` folder, so anyone can add a +report format by adding a Markdown file there, without editing a project type: - **Routing.** Before each question is routed, `routing(settings, @@ -188,21 +192,32 @@ a Markdown file there, without editing a project type: for smith20"). Templates that another intent of the project type names (the four fixed Literature intents) are left to that intent. - **Choosing.** A complete template ID, filename (with or without `.md`), - or title names the format. Spaces, underscores, and hyphens in names are - interchangeable; a shorter name within a longer one is not a second + or title names the format. Use the qualified workspace path to resolve + ambiguous names across report tools. For example, use the complete path + in backticks: `templates/generate_paper_summary/lab notes.md`. + Single or double quotes also delimit a path. Unquoted qualified paths + end at the first complete `.md` suffix; quote paths with punctuation or + an embedded `.md` that could be mistaken for the end of the filename. + Include `.md` in an unquoted path followed by other words. In unqualified + names, spaces, underscores, and hyphens are interchangeable; a shorter + name within a longer one is not a second match. If two distinct templates are named, KíLín asks for exactly one - filename instead of silently picking the first. When none is named, - the project's only valid template is used, or the user chooses one - (`ToolContext.choose`). The desktop GUI receives the choices through - the shared, traced `ask_choice` protocol before waiting for a selection; - cancellation or an invalid response stops the report. Without an - interactive callback, the answer lists the templates and how to name one. + filename instead of silently picking the first. A uniquely named template + takes precedence over the configured default; an invalid named template + is rejected. When none is named, a fixed configured template is loaded + and validated. With `choose`, the project's only valid template is used, + or the user chooses among several (`ToolContext.choose`). No valid + template produces a diagnostic. The desktop GUI receives the choices + through the shared, traced `ask_choice` protocol before waiting for a + selection; cancellation or an invalid response stops the report. Without + an interactive callback, the answer lists the templates and how to name + one. - **Listing and checking.** "Which templates do I have?" lists each template with its description, and those that break a rule with the problem (`templates_answer`). "Check my journal_club template" says whether it can be used, with its sections and limits, or what to fix. Neither reads a document. -- **The format guide.** `templates/README.md` (shipped in +- **The format guide.** `templates/generate_paper_summary/README.md` (shipped in `templates/` here and installed with the templates) explains the format for people writing a template by hand, with a complete example that the tests check is valid. `template_names` skips it. @@ -216,7 +231,8 @@ for an intent using any template (`"choose"`) every bundled template and `README.md`. The core deduplicates repeated declarations and copies only required files. An unbundled custom template name results in no packaged resource: -users can create the Markdown file manually in `templates/`. +users can create the Markdown file manually in +`templates/generate_paper_summary/`. Opening an existing project never replaces, recreates, or deletes its project-owned templates. Edited and custom files take precedence over the @@ -267,7 +283,7 @@ may use an explicit smaller cap, never exceeding the user's maximum. Changing `THINKING` to `inherit` resets this tool to the main setting; `on` forces thinking and bypasses local short-response caps. Restart after editing cached defaults. See the [shared policy](../../../docs/configuration.md#internal-tool-thinking) -for precedence, the retained exceptions, and migration of obsolete keys. +for precedence, output-limit exceptions, and configuration validation. ## Partial completion @@ -279,3 +295,27 @@ sections. If useful checked sections remain, the tool saves a labelled `*_summary_partial.md` with `status: partial`, `valid: false`, omissions and no PDF. Existing complete outputs remain intact. With no usable notes/sections, no report is published. Normal report validation remains unchanged. + +### Source organization settings + +- `TARGET_ROLES` (`target_roles`, default `[]`): eligible anchor roles. +- `EVIDENCE_ROLES` (`evidence_roles`, default `[]`): eligible related roles. +- `RELATED_EVIDENCE` (`related_evidence`, default `[]`): accepted relation + identifiers to expand. Empty disables expansion. Empty role lists impose + no extra role restriction. Project overrides retain their precedence. + +Only original indexed passages of the chosen target and explicitly permitted +related evidence are used. Bibliography links are not scientific evidence. +Coverage identifies each physical member; unindexed or omitted material is +not negative evidence. + +Reading parts never mix physical members. The anchor is read first, then +related members in relative-path order, each in indexed passage order. +`max_model_calls` limits planned reading-part calls across the group; final +synthesis/section calls and existing bounded recovery are separate. + +Reports with incomplete reading coverage use the partial Markdown filename +and produce no PDF. Bibliographic metadata and reference entries come only +from the anchor. Group reports include a physical passage-number source map +in addition to the template-controlled body. The explicit output operand +remains a separate single-file read and is never imported or indexed. diff --git a/kilin/tools/generate_paper_summary/__init__.py b/kilin/tools/generate_paper_summary/__init__.py index 5fd215c3..cb2c079f 100644 --- a/kilin/tools/generate_paper_summary/__init__.py +++ b/kilin/tools/generate_paper_summary/__init__.py @@ -24,6 +24,10 @@ Module Structure ---------------- +- ``PLUGIN`` + + Versioned descriptor discovered by the tool registry. + - ``SummarySettings``, ``parse_settings``, ``run`` and ``workspace_resources`` @@ -46,7 +50,9 @@ """ -from kilin.tools.generate_paper_summary._report_template import ( +from kilin.tools import Tool + +from ._report_template import ( LIMIT_TOLERANCE, SECTION_SOURCE_CHOICES, SECTION_SOURCE_CITATION, @@ -65,7 +71,7 @@ section_problem, template_names, ) -from kilin.tools.generate_paper_summary.tool import ( +from .tool import ( REFERENCE_LAYOUT, TEMPLATE_CHOOSE, SummarySettings, @@ -76,6 +82,7 @@ paper_beginning, paper_citation, parse_settings, + source_policies, references_prompt, routing, run, @@ -86,6 +93,8 @@ ) __all__ = [ + "source_policies", + "PLUGIN", "LIMIT_TOLERANCE", "REFERENCE_LAYOUT", "SECTION_SOURCE_CHOICES", @@ -121,3 +130,17 @@ "templates_answer", "workspace_resources", ] + + +PLUGIN = Tool( + name="generate_paper_summary", + summary="Summarize one paper with a report template, check the structure, " + "and save the Markdown to outputs/.", + parse_settings=parse_settings, + source_policies=source_policies, + run=run, + routing=routing, + workspace_resources=workspace_resources, + version="0.1.0", + api_version=1, +) diff --git a/kilin/tools/generate_paper_summary/_configuration.py b/kilin/tools/generate_paper_summary/_configuration.py index 49a24e59..0c5d2f7b 100644 --- a/kilin/tools/generate_paper_summary/_configuration.py +++ b/kilin/tools/generate_paper_summary/_configuration.py @@ -43,6 +43,8 @@ from __future__ import annotations +from kilin.tools import check_source_ids + from pathlib import Path import re from typing import Final @@ -57,7 +59,7 @@ require_string, require_words, ) -from kilin.tools._shared.planning import CONFIRMATION_CHOICES +from kilin.tools import CONFIRMATION_CHOICES from kilin.tools._model_calls import ( ModelCallSettings, @@ -65,6 +67,10 @@ ) __all__ = [ + "DEFAULT_TARGET_ROLES", + "DEFAULT_EVIDENCE_ROLES", + "DEFAULT_RELATED_EVIDENCE", + "SECTION_REPLY_TOKENS", "NOTE_REPLY_TOKENS", "MODEL_CALLS", @@ -108,6 +114,7 @@ "TEMPLATE", "PART_TOKENS", "REPAIR_ATTEMPTS", "MAX_MODEL_CALLS", "CONFIRMATION", "LARGE_BATCHES", + "TARGET_ROLES", "EVIDENCE_ROLES", "RELATED_EVIDENCE", }, "PAPER": { "BEGINNING_PASSAGES", "BEGINNING_CHARACTERS", @@ -255,3 +262,13 @@ MODEL_CALLS: Final[ModelCallSettings] = load_model_call_settings( Path(__file__).with_name("defaults.json") ) + +DEFAULT_TARGET_ROLES: Final[tuple[str, ...]] = check_source_ids( + "generate_paper_summary.SETTINGS", _SETTINGS, "TARGET_ROLES" +) +DEFAULT_EVIDENCE_ROLES: Final[tuple[str, ...]] = check_source_ids( + "generate_paper_summary.SETTINGS", _SETTINGS, "EVIDENCE_ROLES" +) +DEFAULT_RELATED_EVIDENCE: Final[tuple[str, ...]] = check_source_ids( + "generate_paper_summary.SETTINGS", _SETTINGS, "RELATED_EVIDENCE" +) diff --git a/kilin/tools/generate_paper_summary/_report_template.py b/kilin/tools/generate_paper_summary/_report_template.py index 6655e58f..682de5a0 100644 --- a/kilin/tools/generate_paper_summary/_report_template.py +++ b/kilin/tools/generate_paper_summary/_report_template.py @@ -72,7 +72,7 @@ count_words, template_names, ) -from kilin.tools.generate_paper_summary._configuration import ( +from ._configuration import ( LIMIT_TOLERANCE as _CONFIG_LIMIT_TOLERANCE, MIN_TOTAL_WORDS, ) diff --git a/kilin/tools/generate_paper_summary/defaults.json b/kilin/tools/generate_paper_summary/defaults.json index c5933ef1..69c8db14 100644 --- a/kilin/tools/generate_paper_summary/defaults.json +++ b/kilin/tools/generate_paper_summary/defaults.json @@ -5,7 +5,10 @@ "REPAIR_ATTEMPTS": 1, "MAX_MODEL_CALLS": 20, "CONFIRMATION": "when_large", - "LARGE_BATCHES": 3 + "LARGE_BATCHES": 3, + "TARGET_ROLES": [], + "EVIDENCE_ROLES": [], + "RELATED_EVIDENCE": [] }, "PAPER": { "BEGINNING_PASSAGES": 3, diff --git a/kilin/tools/generate_paper_summary/settings_info.json b/kilin/tools/generate_paper_summary/settings_info.json index 7a3d18e8..4772f3db 100644 --- a/kilin/tools/generate_paper_summary/settings_info.json +++ b/kilin/tools/generate_paper_summary/settings_info.json @@ -9,7 +9,7 @@ "part_tokens": { "title": "Part token budget", "summary": "Sets the token budget for one part of a multi-part operation.", - "description": "Constrains the context provided for each model call when work is split into parts." + "description": "Estimated tokens per physical reading part. An oversized indivisible passage remains a single part; parts never mix different physical files." }, "repair_attempts": { "title": "Repair attempts", @@ -18,8 +18,8 @@ }, "max_model_calls": { "title": "Maximum model calls", - "summary": "Caps model calls permitted for one tool operation.", - "description": "Limits computational cost and processing time. Work may stop early before every candidate is examined." + "summary": "Caps planned reading-part calls across all members.", + "description": "One shared limit for the chosen anchor and its evidence members, in physical source order. Synthesis, section writing and existing bounded model recovery are separate." }, "confirmation": { "title": "Confirmation policy", @@ -30,6 +30,21 @@ "title": "Large workload threshold", "summary": "Sets the batch threshold used by the confirmation policy.", "description": "Used to decide whether a planned multi-batch operation is large enough to request confirmation." + }, + "target_roles": { + "title": "Target roles", + "summary": "Restricts eligible document anchors.", + "description": "Accepted role identifiers. Empty permits all eligible anchors." + }, + "evidence_roles": { + "title": "Related evidence roles", + "summary": "Restricts supporting member roles.", + "description": "Accepted role identifiers. Empty permits any eligible related evidence role." + }, + "related_evidence": { + "title": "Related evidence", + "summary": "Selects relationships for group reading.", + "description": "Accepted relation identifiers. Empty reads only the selected physical document." } } } diff --git a/kilin/tools/generate_paper_summary/templates/README.md b/kilin/tools/generate_paper_summary/templates/README.md index 37888c74..2b44db66 100644 --- a/kilin/tools/generate_paper_summary/templates/README.md +++ b/kilin/tools/generate_paper_summary/templates/README.md @@ -7,12 +7,20 @@ template. To use one, name it in the chat by its title or file name: - "fill the lab notes template for patil25" - "use the minutes template for smith20" +If the same name is used by another report tool, name the complete path, +for example `templates/generate_paper_summary/lab notes.md`, in backticks +or quotes. Include `.md` in an unquoted path followed by other words. + KíLín reads the document in parts, writes each section of the template from what it read, checks every section against its limits, and saves the -report to `outputs/`. When you ask for a report without naming a template, -KíLín asks which one to use. "Which templates do I have?" lists them, and -"check my journal_club template" tells you whether one can be used, or -what to fix. +report to `outputs/`. A named template takes precedence over the configured +default. Without a name, KíLín uses the fixed configured template, or, with +`choose`, selects the only valid template automatically or asks you to +choose among several. An invalid named or fixed template is reported rather +than replaced silently. If none is usable, KíLín reports the problem; if +several are usable but no interactive choice is available, name one in the +question. "Which templates do I have?" lists them, and "check my +journal_club template" tells you whether one can be used, or what to fix. To make your own, copy one of these files, rename it, and edit it. A new file is available at the next question; nothing else needs changing. @@ -92,42 +100,8 @@ No other `{...}` placeholders are allowed. ## Reports on the whole project -A template with `scope: project` in its front matter is a report on all -the documents of the project rather than one: KíLín reads every document -once and writes the report from all of them ("write a project overview", -"summarize the whole project", or the template's name). Two are shipped: -`project_overview.md` and `literature_table.md`. - -Its sections can be: - -- written from all documents, like `## Main Themes (180-260 words)`, - citing the documents as `[n]`; -- **per document**: a condition and what to write for each document that - meets it, listed by KíLín with how many documents match: - - ```markdown - ## Deep-Learning Models (per document) - - When: the document trains or uses a deep-learning model. - Do: name the architecture, the training data and the task (max 40 words). - ``` - - With `(per document, table)` and `Do: | Dataset | Size | Licence |`, - each matching document is a table row. A document is listed only when - KíLín found words in it that show it meets the condition; the others are - counted as unclear. - -A section that must speak of every document, such as an overview of -the collection, says so in its brackets: `## Scope of the Collection -(80-120 words, all documents)`. KíLín then has it rewritten until it -cites every document of the project. Leave it out where only some -documents belong, such as agreements between documents. - -Project templates use `**Documents:** {documents}` (the number of -documents, written by code) and `{key_documents}` in a section's -instruction (documents chosen from the project, with an item limit), not -`{citation}` and `{references}`. Per-document sections do not count -towards `max_words`. +Place those templates in `templates/project_summary/`, not here. That +tool ships its own format guide. ## When a template cannot be used diff --git a/kilin/tools/generate_paper_summary/tool.py b/kilin/tools/generate_paper_summary/tool.py index bee079f3..5eba4804 100644 --- a/kilin/tools/generate_paper_summary/tool.py +++ b/kilin/tools/generate_paper_summary/tool.py @@ -4,7 +4,7 @@ from ``report_template``, such as ``research_briefing`` (the one-page Research Briefing format of Nature-family journals), and saves it in the project's ``outputs/`` folder. Templates live in the project's -``templates/`` folder, which receives only the project type's required +``templates/generate_paper_summary/`` folder, which receives the required templates on creation; the question picks one by title or name, and the intent's default applies otherwise. It is KíLín's reference example of a custom tool (see tutorial 170): it composes existing capabilities instead @@ -148,8 +148,9 @@ from __future__ import annotations from collections.abc import Callable -from dataclasses import dataclass +from dataclasses import dataclass, replace from functools import partial +from io import BytesIO from pathlib import Path import re from time import perf_counter @@ -167,15 +168,21 @@ ) from kilin.tools._shared.document_notes import ( NOTHING, - plan_parts, take_notes, ) -from kilin.tools._shared.choose_document import choose_document +from kilin.tools._shared.group_reading import ( + GroupReading, choose_group, reading_policy, +) +from kilin.tools import ( + SourcePolicy, check_source_ids, require_source_services, +) +from kilin.tools._shared.source_access import optional_source_bytes +from kilin.tools._shared.citations import inspect_citations from kilin.tools._shared.references import ( ReferenceLayout, reference_entries, ) -from kilin.tools._contract import ( +from kilin.tools import ( ToolContext, ToolRequest, ToolResult, @@ -192,7 +199,7 @@ save_output_file, staged_output_file, ) -from kilin.tools._shared.planning import ( +from kilin.tools import ( CONFIRMATION_ALWAYS, CONFIRMATION_CHOICES, CONFIRMATION_WHEN_LARGE, @@ -204,11 +211,12 @@ confirm_plan, ) from kilin.workspace_resources import ( - PROJECT_SOURCES_DIRECTORY, WorkspaceResource, + template_resource, templates_folder, ) -from kilin.tools.generate_paper_summary._configuration import ( +from . import _configuration as _config +from ._configuration import ( BEGINNING_CHARACTERS, BEGINNING_PASSAGES, CALL_SECONDS, @@ -238,22 +246,37 @@ RUNNING_LINE_WORDS, SECTION_PROMPT_TOKENS, ) +from kilin.tools._registry import ( + TOOL_GENERATE_PAPER_SUMMARY, + TOOL_PROJECT_SUMMARY, +) from kilin.tools._shared.report_templates import SCOPE_DOCUMENT -from kilin.tools.generate_paper_summary._report_template import ( +from kilin.tools._shared.report_selection import ( + CHECK_TEMPLATE, + LIST_TEMPLATES, + ReportEntry, + report_entries, + report_matches, + select_report_matches, + sibling_report_entries, + without_report_references, +) +from ._report_template import ( SECTION_SOURCE_CITATION, SECTION_SOURCE_NOTES, SECTION_SOURCE_REFERENCES, SHIPPED_TEMPLATES_DIR, + TEMPLATE_RULES, ReportTemplate, TemplateSection, check_report, count_words, load_template, section_problem, - template_names, ) __all__ = [ + "source_policies", "REFERENCE_LAYOUT", "TEMPLATE_CHOOSE", "SummarySettings", @@ -304,16 +327,6 @@ r"do|give\s+me|turn)\b[^\n]{0,60}?" ) _FOR_WORDS: Final[str] = r"\s+(?:of|for|on|from|about)\b" -# A request for the project's templates, or to check one. -_LIST_TEMPLATES: Final[re.Pattern[str]] = re.compile( - r"\b(?:list|which|what|show|available)\b[^\n]{0,40}\btemplates\b" - r"|\btemplates\b[^\n]{0,40}\b(?:do\s+(?:i|we)\s+have|available)\b", - re.IGNORECASE, -) -_CHECK_TEMPLATE: Final[re.Pattern[str]] = re.compile( - r"\b(?:check|validate|test|verify)\b[^\n]{0,40}\btemplate\b", - re.IGNORECASE, -) # Templates described to the router, and characters of each description. _ROUTED_TEMPLATES: Final[int] = 30 _ROUTED_DESCRIPTION: Final[int] = 120 @@ -371,7 +384,7 @@ class SummarySettings: ---------- template: str Template used when the question names none: a file name without - ``.md`` in the project's ``templates/`` folder. + ``.md`` in the tool's project template directory. part_tokens: int Estimated tokens of paper per reading part (1000-16000). repair_attempts: int @@ -384,6 +397,13 @@ class SummarySettings: With ``when_large``, plans with more parts than this ask first (0-100). + target_roles: tuple[str, ...] + Eligible anchor roles; empty means unrestricted. + evidence_roles: tuple[str, ...] + Eligible related evidence roles; empty means unrestricted. + related_evidence: tuple[str, ...] + Accepted relation identifiers to expand; empty reads only the anchor. + """ template: str = DEFAULT_TEMPLATE @@ -392,6 +412,9 @@ class SummarySettings: max_model_calls: int = DEFAULT_MAX_MODEL_CALLS confirmation: ConfirmationPolicy = DEFAULT_CONFIRMATION large_batches: int = DEFAULT_LARGE_BATCHES + target_roles: tuple[str, ...] = _config.DEFAULT_TARGET_ROLES + evidence_roles: tuple[str, ...] = _config.DEFAULT_EVIDENCE_ROLES + related_evidence: tuple[str, ...] = _config.DEFAULT_RELATED_EVIDENCE def parse_settings(data: dict, where: str) -> SummarySettings: @@ -425,6 +448,7 @@ def parse_settings(data: dict, where: str) -> SummarySettings: "max_model_calls", "confirmation", "large_batches", + "target_roles", "evidence_roles", "related_evidence", ) reject_unknown(where, data, names) @@ -458,9 +482,31 @@ def parse_settings(data: dict, where: str) -> SummarySettings: large_batches=check_int( where, data, "large_batches", defaults.large_batches, 0, 100 ), + target_roles=check_source_ids( + where, data, "target_roles", defaults.target_roles + ), + evidence_roles=check_source_ids( + where, data, "evidence_roles", defaults.evidence_roles + ), + related_evidence=check_source_ids( + where, data, "related_evidence", defaults.related_evidence + ), ) +def source_policies(settings: SummarySettings) -> tuple[SourcePolicy, ...]: + """Declare the reading policy for accepted vocabulary validation. + + Parameters + ---------- + settings: SummarySettings + Validated settings for this tool. + + """ + return (reading_policy(settings.target_roles, settings.evidence_roles, + settings.related_evidence),) + + def workspace_resources( settings: SummarySettings, ) -> tuple[WorkspaceResource, ...]: @@ -477,8 +523,7 @@ def workspace_resources( One shipped template to install when available, otherwise an empty tuple for a user-provided custom template. An intent using any template (``TEMPLATE_CHOOSE``) installs every shipped - template and ``templates/README.md``, which explains how to - write one. + template and its ``README.md`` format guide. Notes ----- @@ -489,7 +534,7 @@ def workspace_resources( if settings.template == TEMPLATE_CHOOSE: return tuple( - WorkspaceResource(source, f"templates/{source.name}") + template_resource(source, TOOL_GENERATE_PAPER_SUMMARY) for source in sorted(SHIPPED_TEMPLATES_DIR.glob("*.md")) ) name = f"{settings.template}.md" @@ -497,7 +542,7 @@ def workspace_resources( if not source.exists(): # A custom project-type template may be supplied by the user later. return () - return (WorkspaceResource(source, f"templates/{name}"),) + return (template_resource(source, TOOL_GENERATE_PAPER_SUMMARY),) def _mentions_output_name(text: str, name: str) -> bool: @@ -529,7 +574,8 @@ def _mentions_output_name(text: str, name: str) -> bool: def choose_paper( - request: ToolRequest, context: ToolContext, what: str = "summary" + request: ToolRequest, context: ToolContext, what: str = "summary", + *, settings: SummarySettings = SummarySettings(), ) -> tuple[Path, tuple[Chunk, ...], str, bool] | str: """Choose the paper to summarize and return its passages. @@ -542,6 +588,8 @@ def choose_paper( what: str, optional What will be made, for the question to the user, such as "research briefing". Defaults to ``"summary"``. + settings: SummarySettings, optional + Effective anchor and related evidence policy. Returns ------- @@ -565,14 +613,45 @@ def choose_paper( relative path. Without a filename, "my paper" or "outputs" can use the only output when no indexed source is named. "This PDF" may use the sole saved PDF only if the project has no indexed sources. - Otherwise ``choose_document`` decides from the question and earlier + Otherwise the shared group selector decides from the question and earlier turns, asking the user when the paper is unclear. Stem or author matching never silently chooses a generated report for an indexed source. """ + reading = _choose_paper(request, context, what, settings) + if isinstance(reading, str): + return reading + return reading.anchor, reading.chunks, reading.reason, reading.guessed + + +def _choose_paper( + request: ToolRequest, context: ToolContext, what: str, + settings: SummarySettings, +) -> GroupReading | str: + """Resolve a report's explicit output operand or one logical group. + + Parameters + ---------- + request: ToolRequest + Question and earlier-turn context. + context: ToolContext + Host services for the current tool operation. + what: str + Description of the requested report type. + settings: SummarySettings + Validated settings for this tool. + + """ root = context.project_root + # A qualified report path names a format, never a source or output. + question = without_report_references(request.question) + if question != request.question: + request = replace( + request, question=question, + text=without_report_references(request.text), + ) outputs = [ path for path in output_files(root) @@ -581,7 +660,7 @@ def choose_paper( def from_outputs( name: Path, reason: str - ) -> tuple[Path, tuple[Chunk, ...], str, bool]: + ) -> GroupReading: """Load an ``outputs/`` file; it is never a guess. Parameters @@ -593,13 +672,14 @@ def from_outputs( Returns ------- - tuple[Path, tuple[Chunk, ...], str, bool] - Named output file, selected chunks, selection reason, and flag. + GroupReading + Separate physical output operand without a bound source view. """ document = load_output(root, name) - return document.path, document.passages, reason, False + return GroupReading(document.path, document.passages, + (document.path,), (), reason, False) # Prefer a complete outputs/ path over an unqualified basename. # A full path disambiguates reports with the same name in subfolders. @@ -631,36 +711,37 @@ def from_outputs( if len(bare) == 1: return from_outputs(bare[0], "named in the question") - sources = list(dict.fromkeys(chunk.path for chunk in context.chunks)) + policy = source_policies(settings)[0] + targets = require_source_services( + context, SourcePolicy(target_roles=policy.target_roles), + ) + # Output shortcuts must not widen a role-restricted source request. + sources = list(targets.view.targets) has_file_name = bool(_FILE_REFERENCE.search(text)) if ( - not has_file_name + policy.target_roles is None + and not has_file_name and _OWN_PAPER.search(request.question) and not named_paths(request.question, sources, authors=True) ): if len(outputs) == 1: return from_outputs(outputs[0], "the only outputs file") - if not sources and not has_file_name and _THIS_PDF.search(text): + if (policy.target_roles is None and not sources and not has_file_name + and _THIS_PDF.search(text)): pdfs = [path for path in outputs if path.suffix.lower() == ".pdf"] if len(pdfs) == 1: return from_outputs(pdfs[0], "the only outputs PDF") if len(pdfs) > 1: return "Several PDFs are in outputs/. Name the one to use." - chosen = choose_document( - request, - context, + return choose_group( + request, context, policy, targets=targets, question=f"Which paper should I turn into a {what}?", example=f"turn smith2020.pdf into a {what}", prefer=(".pdf",), + paper_only=True, ) - if isinstance(chosen, str): - return chosen - - path, reason, guessed = chosen - passages = tuple(c for c in context.chunks if c.path == path) - return path, passages, reason, guessed def choose_template( @@ -668,6 +749,8 @@ def choose_template( folder: Path, default: str, choose: Callable[[str, tuple[str, ...]], int | None] | None = None, + *, + other: list[ReportEntry] | None = None, ) -> ReportTemplate | None: """Pick the template a question asks for, or ask which. @@ -684,6 +767,8 @@ def choose_template( ``ToolContext.choose``, to ask which template when the default is ``TEMPLATE_CHOOSE`` and the question names none. Defaults to ``None``. + other: list[ReportEntry] or None, optional + Validated whole-project entries for cross-scope diagnostics. Returns ------- @@ -704,7 +789,9 @@ def choose_template( """ found = _templates(folder) - named = _named_templates(question, found) + named = select_report_matches( + question, TOOL_GENERATE_PAPER_SUMMARY, found, other or [] + ) if len(named) > 1: raise ValueError(_ambiguous_templates(named)) if named: @@ -714,7 +801,12 @@ def choose_template( return template if default != TEMPLATE_CHOOSE: - template = load_template(default, folder) + try: + template = load_template(default, folder) + except (UnicodeError, OSError) as error: + raise ValueError( + f"Cannot read report template {default!r}: {error}" + ) from error if template.scope != SCOPE_DOCUMENT: raise ValueError( f"Template {template.name!r} is for project reports, " @@ -725,12 +817,12 @@ def choose_template( if len(usable) == 1: return usable[0] if not usable: - raise ValueError(templates_answer(folder)) + raise ValueError(templates_answer(folder, other=other)) if choose is None: raise ValueError( "Which template? Name one in the question, for example " f"“write a {usable[0].title.lower()} of smith20”.\n\n" - + templates_answer(folder) + + templates_answer(folder, other=other) ) index = choose( "Which template should the report use?", @@ -741,96 +833,22 @@ def choose_template( return usable[index] -def _templates( - folder: Path, -) -> list[tuple[str, ReportTemplate | None, str]]: - """Return the project's templates, read and checked. +def _templates(folder: Path) -> list[ReportEntry]: + """Inspect the individual-document template namespace. Parameters ---------- folder: pathlib.Path - The project's templates folder. + The tool's template directory. Returns ------- - list[tuple[str, ReportTemplate | None, str]] - Each template's file name (without ``.md``), the template (None - when it breaks a rule) and the error (``""`` when valid), by name; - empty without the folder. Project templates (``scope: project``), - for reports on a whole project, are left out. + list[ReportEntry] + Entries and problems in filename order, including misplaced files. """ - if not folder.is_dir(): - return [] - found: list[tuple[str, ReportTemplate | None, str]] = [] - for name in template_names(folder): - try: - template = load_template(name, folder) - except ValueError as error: - found.append((name, None, str(error))) - continue - if template.scope == SCOPE_DOCUMENT: - found.append((name, template, "")) - return found - - -def _named_templates( - question: str, - found: list[tuple[str, ReportTemplate | None, str]], -) -> list[tuple[str, ReportTemplate | None, str]]: - """Find templates named by complete IDs, filenames, or titles. - - Shorter names embedded in a longer matched name are discarded, but - separate mentions of distinct templates remain ambiguous. Name - separators (space, underscore, hyphen) are interchangeable. - - Parameters - ---------- - question: str - The user's request. - found: list[tuple[str, ReportTemplate | None, str]] - Project templates, including invalid ones without a usable title. - - Returns - ------- - list[tuple[str, ReportTemplate | None, str]] - All distinct templates explicitly mentioned, in folder order. - - """ - - text = " ".join(question.casefold().split()) - hits: list[tuple[str, tuple[int, int]]] = [] - for name, template, _ in found: - aliases = {name, f"{name}.md"} - if template is not None: - aliases.add(template.title) - for alias in aliases: - words = [ - part for part in re.split(r"[\s_-]+", alias.casefold()) - if part - ] - if not words: - continue - pattern = ( - r"(? list[tuple[str, ReportTemplate]]: - """Return the valid project report templates in a folder. - - Parameters - ---------- - folder: pathlib.Path - The project's templates folder. - - Returns - ------- - list[tuple[str, ReportTemplate]] - Each template with ``scope: project`` and its file name, by name. - - """ - - if not folder.is_dir(): - return [] - found: list[tuple[str, ReportTemplate]] = [] - for name in template_names(folder): - try: - template = load_template(name, folder) - except ValueError: - continue - if template.scope != SCOPE_DOCUMENT: - found.append((name, template)) - return found - - -def templates_answer(folder: Path) -> str: - """Return the answer listing the project's templates. +def templates_answer( + folder: Path, *, other: list[ReportEntry] | None = None, +) -> str: + """List report formats grouped by their owning tool. Parameters ---------- folder: pathlib.Path - The project's templates folder. + Individual-document template directory. + other: list[ReportEntry] or None, optional + Whole-project entries, already checked with their own rules. Returns ------- str - Each valid template's title, file name and description, then the - project report templates (``scope: project``, used by - ``project_summary``), the templates that break a rule with the - problem, and where the format is explained: the project's - ``templates/README.md``, or for a project created before it was - installed, the guide shipped with KíLín. + Template names, descriptions, validation problems and guide paths. """ found = _templates(folder) - lines = [ - f"- **{template.title}** (`{name}.md`): {template.description}" - for name, template, _ in found if template is not None - ] - projects = [ - f"- **{template.title}** (`{name}.md`): {template.description}" - for name, template in _project_templates(folder) - ] - broken = [ - f"- `{name}.md` cannot be used: {error}" - for name, template, error in found if template is None - ] - head = ( - "**Report templates in this project**" if lines - else "This project has no usable report template." - ) - parts = [head, "", *lines] - if projects: - parts += [ - "", "**Report templates for the whole project**", "", - *projects, - "", - "These read every document of the project (“write a " - "project overview”).", + inventories = { + TOOL_GENERATE_PAPER_SUMMARY: found, + TOOL_PROJECT_SUMMARY: other or [], + } + parts = [] + broken = [] + for owner, entries in inventories.items(): + lines = [ + f"- **{template.title}** (`templates/{owner}/{name}.md`): " + f"{template.description}" + for name, template, _ in entries if template is not None ] + broken.extend( + f"- `templates/{owner}/{name}.md` cannot be used: {error}" + for name, template, error in entries if template is None + ) + if owner == TOOL_GENERATE_PAPER_SUMMARY: + parts += [ + "**Report templates in this project**" if lines else + "This project has no usable report template.", "", *lines, + ] + elif lines: + parts += [ + "", "**Report templates for the whole project**", "", + *lines, "", "These read every document of the project.", + ] if broken: parts += ["", "**Templates with problems**", "", *broken] guide = ( - "`templates/README.md` explains how to write one" - if (folder / "README.md").is_file() - else "the guide shipped with KíLín " + "`templates/generate_paper_summary/README.md` explains " + "how to write one" + if (folder / "README.md").is_file() else + "the guide shipped with KíLín " "(`kilin/tools/generate_paper_summary/templates/README.md`) " "explains how to write one" ) parts += [ - "", - "Name one to use it (“write a research briefing of smith20”). " - "Templates are Markdown files in the project's `templates/` " - f"folder; {guide}.", + "", "Name a template by title, filename, or qualified path. " + f"For individual-document reports, {guide}. " + "For project reports see the `project_summary` template guide.", ] return "\n".join(parts) -def _template_check(question: str, folder: Path) -> str: - """Return the answer to a request to check a template. +def _template_check( + question: str, folder: Path, other: list[ReportEntry], +) -> str: + """Check a named report template in either report namespace. Parameters ---------- question: str - The question, naming the template. + Request naming the template. folder: pathlib.Path - The project's templates folder. + Individual-document template directory. + other: list[ReportEntry] + Validated whole-project entries. Returns ------- str - For the named template, that it can be used, with its sections - and their limits, or the rule it breaks; the list of templates - when the question names none. + Sections and limits, a diagnostic, or the template inventory. """ - named = _named_templates(question, _templates(folder)) + named = report_matches(question, { + TOOL_GENERATE_PAPER_SUMMARY: _templates(folder), + TOOL_PROJECT_SUMMARY: other, + }) if len(named) > 1: - return _ambiguous_templates(named) - for name, template, error in named: + paths = ", ".join(f"`templates/{owner}/{entry[0]}.md`" + for owner, entry in named) + return ( + f"Several report templates match: {paths}. " + "Name exactly one template by its qualified path." + ) + for owner, (name, template, error) in named: + path = f"templates/{owner}/{name}.md" if template is None: - return f"`{name}.md` cannot be used: {error}" + return f"`{path}` cannot be used: {error}" sections = [] for section in template.sections: limit = ( @@ -985,13 +986,10 @@ def _template_check(question: str, folder: Path) -> str: ) sections.append(f"- {section.name} ({limit})") return "\n".join([ - f"**{template.title}** (`{name}.md`) can be used.", - "", - template.description, - "", - *sections, + f"**{template.title}** (`{path}`) can be used.", + "", template.description, "", *sections, ]) - return templates_answer(folder) + return templates_answer(folder, other=other) def routing( @@ -1030,7 +1028,9 @@ def routing( claimed = {other.template for other in others} usable = [ template - for name, template, _ in _templates(templates_folder(root)) + for name, template, _ in _templates( + templates_folder(root, TOOL_GENERATE_PAPER_SUMMARY) + ) if template is not None and name not in claimed ] if not usable: @@ -1084,7 +1084,10 @@ def _shortened(text: str, limit: int) -> str: return text[:limit].rsplit(" ", 1)[0].rstrip(",;:") + "…" -def paper_citation(file: Path | None, passages: tuple[Chunk, ...]) -> str: +def paper_citation( + file: Path | None, passages: tuple[Chunk, ...], *, + name: Path | None = None, original: bytes | None = None, +) -> str: """Write a paper's citation from its metadata and first page. The language model never writes or edits the citation. @@ -1095,6 +1098,10 @@ def paper_citation(file: Path | None, passages: tuple[Chunk, ...]) -> str: The paper on disk, for PDF or Word metadata; None when unknown. passages: tuple[Chunk, ...] The paper's passages, for the DOI, year, and author count. + name: pathlib.Path | None, optional + Physical anchor name when using captured bytes. + original: bytes | None, optional + Content-verified original bytes supplied by the source host. Returns ------- @@ -1108,19 +1115,24 @@ def paper_citation(file: Path | None, passages: tuple[Chunk, ...]) -> str: """ + identity = name or file fallback = ( - f"{file.name if file else 'The paper'} (the file has no title " + f"{identity.name if identity else 'The paper'} (the file has no title " "metadata)." ) - if file is None or not file.is_file(): + if identity is None or (original is None and ( + file is None or not file.is_file() + )): return fallback - suffix = file.suffix.lower() + suffix = identity.suffix.lower() if suffix == ".pdf": try: from pypdf import PdfReader - metadata = PdfReader(file).metadata or {} + metadata = PdfReader( + BytesIO(original) if original is not None else file + ).metadata or {} raw_title = metadata.get("/Title") raw_author = metadata.get("/Author") except Exception: # pylint: disable=broad-exception-caught @@ -1128,7 +1140,10 @@ def paper_citation(file: Path | None, passages: tuple[Chunk, ...]) -> str: elif suffix in {".doc", ".docx"}: from kilin.sources._word_metadata import read_word_metadata - raw_title, raw_author = read_word_metadata(file) + raw_title, raw_author = ( + read_word_metadata(identity, original=original) + if original is not None else read_word_metadata(file) + ) else: return fallback @@ -1343,9 +1358,9 @@ def section_prompt( """ system = ( - "You write one section of a structured summary of a scientific " - "paper for KíLín. You use only the reading notes you are given " - "and never invent results." + "You write one section of a structured summary for KíLín. Use only " + "the reading notes; distinguish their physical sources and never " + "attribute a related finding to the anchor without support." ) earlier = "\n".join( f"- {heading}: " @@ -1361,7 +1376,7 @@ def section_prompt( Rules: - Use only information in the notes. If they do not cover this section, - write "Not stated in the paper." + write "Not established by the available reading notes." - {_NO_PLACEHOLDERS} - Keep names, numbers, and versions exactly as in the notes. - Mark your own inference with "Inferred:". @@ -1608,7 +1623,7 @@ def run( ------- ToolResult One line saying where the Markdown and PDF were saved, then the - saved Markdown itself; every passage of the paper as evidence; and + saved Markdown itself; successfully processed passages as evidence; and a summary of the checks, fixes, and files. When the template or the paper cannot be used, or the user cancels, a message saying so and no evidence. @@ -1623,17 +1638,28 @@ def run( trace = context.trace summary: dict[str, object] = {"name": "generate_paper_summary"} - folder = templates_folder(context.project_root) - if _LIST_TEMPLATES.search(request.question): - context.done("Listed the templates", evidence_count=0) - summary["listed_templates"] = True - return ToolResult(templates_answer(folder), (), summary) - if _CHECK_TEMPLATE.search(request.question): - context.done("Checked the template", evidence_count=0) - summary["checked_template"] = True - return ToolResult( - _template_check(request.question, folder), (), summary + try: + folder = templates_folder( + context.project_root, TOOL_GENERATE_PAPER_SUMMARY + ) + other = sibling_report_entries( + context.project_root, TOOL_GENERATE_PAPER_SUMMARY ) + action = without_report_references(request.question) + if LIST_TEMPLATES.search(action): + context.done("Listed the templates", evidence_count=0) + summary["listed_templates"] = True + return ToolResult( + templates_answer(folder, other=other), (), summary + ) + if CHECK_TEMPLATE.search(action): + answer = _template_check(request.question, folder, other) + context.done("Checked the template", evidence_count=0) + summary["checked_template"] = True + return ToolResult(answer, (), summary) + except (ValueError, OSError) as error: + context.done("Could not read templates", evidence_count=0) + return ToolResult(str(error), (), summary) # Reuse the shared choice protocol: it emits the options to the GUI # before waiting for the callback, and validates the returned index. chooser = ( @@ -1647,6 +1673,7 @@ def run( folder, settings.template, chooser, + other=other, ) except ValueError as error: context.done("Could not read the template", evidence_count=0) @@ -1658,7 +1685,9 @@ def run( context.progress("Choosing the paper to summarize") try: - chosen = choose_paper(request, context, template.title.lower()) + chosen = _choose_paper( + request, context, template.title.lower(), settings, + ) except (FileNotFoundError, ValueError) as error: context.done("Could not load the paper", evidence_count=0) return ToolResult(str(error), (), summary) @@ -1667,7 +1696,13 @@ def run( context.done("No paper chosen", evidence_count=0) return ToolResult(chosen, (), summary) - path, passages, reason, guessed = chosen + path, passages = chosen.anchor, chosen.chunks + reason, guessed = chosen.reason, chosen.guessed + if not passages: + summary["member_coverage"] = chosen.coverage(()) + context.done("No indexed passages", evidence_count=0) + return ToolResult("No indexed passages to read. " + chosen.notice(()), + (), summary) texts = [chunk.text for chunk in passages] trace.emit( "tool.generate_paper_summary.loaded", @@ -1681,7 +1716,7 @@ def run( turn_id=context.trace_turn_id, ) - parts = plan_parts(passages, settings.part_tokens) + parts = chosen.parts(settings.part_tokens) to_read = parts[: settings.max_model_calls] paper_tokens = sum(estimate_tokens(text) for text in texts) plan = ToolPlan( @@ -1712,6 +1747,7 @@ def run( else () ), f"About {paper_tokens:,} tokens", + chosen.notice(()), f"Saved to {OUTPUTS_FOLDER}/{path.stem}_summary.md", f"Model: {context.model_id}", ), @@ -1733,6 +1769,7 @@ def run( "asked": asked, } ) + summary["member_coverage"] = chosen.coverage(()) if choice == PLAN_CHOICE_CANCEL: context.done("Cancelled before reading", evidence_count=0) return ToolResult( @@ -1742,6 +1779,7 @@ def run( summary, ) + chosen.validate() started = perf_counter() runs = parts[:1] if choice == PLAN_CHOICE_QUICK else to_read failures: list[dict[str, object]] = [] @@ -1752,12 +1790,20 @@ def run( runs, context, what="paper", - whole=choice != PLAN_CHOICE_QUICK, + whole=choice != PLAN_CHOICE_QUICK and all( + row["complete"] for row in chosen.coverage( + i for part in runs for i in part + ) + ), failures=failures, + paths=[c.path for c in passages], ) - reading_incomplete = bool(failures) read_indices = {index for number, _ in notes for index in runs[number - 1]} read = len(read_indices) + coverage = chosen.coverage(read_indices) + summary["member_coverage"] = coverage + reading_incomplete = any(not row["complete"] for row in coverage) + notice = chosen.notice(read_indices) if not any(lines for _, lines in notes): if failures: @@ -1773,6 +1819,14 @@ def run( reason="no_notes", ) + # Label notes by member before synthesis; citation numbers stay global. + if len(chosen.members) > 1: + notes = [(n, [ + f"{line} (physical source: " + f"{passages[runs[n - 1][0]].path.as_posix()})" + for line in lines + ]) for n, lines in notes] + # Python owns the structure: the model writes the headline and each # section separately, and each piece is checked against its limit. try: @@ -1780,9 +1834,19 @@ def run( except IncompleteModelResponse as error: headline, fixes = template.title, [] failures.append({"item": "Headline", **error.to_dict()}) - # The PDF on disk lets the shared extractor read two columns in order. + # Publication metadata belongs to the anchor, not the related files. + # Only the output operand has a separate workspace-file access path. + anchor_passages = tuple(c for c in passages if c.path == path) + anchor_file = None + original = None + if chosen.services is None: + anchor_file = _paper_file(path, context) + elif path.suffix.lower() in (".pdf", ".doc", ".docx"): + original = optional_source_bytes(chosen.services, path) entries = reference_entries( - passages, REFERENCE_LAYOUT, _paper_file(path, context) + anchor_passages, REFERENCE_LAYOUT, + original if path.suffix.lower() == ".pdf" and original is not None + else anchor_file, ) written: list[tuple[str, str]] = [] accepted: list[tuple[str, str]] = [] @@ -1791,7 +1855,10 @@ def run( try: if section.source == SECTION_SOURCE_CITATION: # Bibliographic data is copied, not generated. - content = paper_citation(_paper_file(path, context), passages) + content = paper_citation( + anchor_file, anchor_passages, name=path, + original=original, + ) elif section.source == SECTION_SOURCE_REFERENCES: context.progress(f"Choosing {section.name}") content, problem = _fill_references( @@ -1805,6 +1872,16 @@ def run( context, incomplete_reading=reading_incomplete, ) fixes.extend(section_fixes) + if section.source == SECTION_SOURCE_NOTES: + cited = inspect_citations(content, len(passages)) + invalid = set(cited.invalid_numbers) | ( + cited.valid - {i + 1 for i in read_indices} + ) + if invalid or cited.invalid_groups: + raise IncompleteModelResponse( + "Section cites unread or nonexistent passages.", + reason="invalid_output", raw_text=content, + ) accepted.append((section.name, content)) except IncompleteModelResponse as error: failures.append({"item": section.name, **error.to_dict()}) @@ -1882,20 +1959,34 @@ def run( ) file_text = summary_file_text(draft, path) + if notice: + file_text += "\n\n" + notice + "\n" + if len(chosen.members) > 1: + # Keep saved reports interpretable without the conversation turn. + sources = [] + for member in chosen.members: + numbers = [str(i + 1) for i in sorted(read_indices) + if passages[i].path == member] + if numbers: + sources.append(f"- {member.as_posix()}: {', '.join(numbers)}") + file_text += "\n\nPassage citation sources:\n" + "\n".join(sources) suffix = "_summary.md" - if failures: + if failures or reading_incomplete: suffix = "_summary_partial.md" file_text = ( "> **Partial report:** incomplete items are marked below. " "Do not treat omissions as negative evidence.\n\n" - + file_text + incomplete_notice(failures) + "\n" + + file_text + (incomplete_notice(failures) if failures else "") + + "\n" ) + chosen.validate() saved = save_output_file( context.project_root, path.stem + suffix, file_text ) # A partial draft must not replace the completed report or its PDF. pdf, pdf_note = ( - (None, "No PDF was produced for this partial report.") if failures + (None, "No PDF was produced for this partial report.") + if failures or reading_incomplete else _write_pdf(file_text, saved, template, context) ) trace.emit( @@ -1912,7 +2003,8 @@ def run( f" and `{pdf.as_posix()}`" if pdf else "" ) lead = [ - ("Partial report: the " if failures else "Done: the ") + ("Partial report: the " if failures or reading_incomplete + else "Done: the ") + f"{template.title.lower()} of {path.name} is saved as " f"{files}." ] @@ -1932,7 +2024,9 @@ def run( { "passages_read": read, "notes": sum(len(lines) for _, lines in notes), - "valid": check.valid and not unsupported and not failures, + "valid": (check.valid and not unsupported and not failures + and not reading_incomplete), + "reading_complete": not reading_incomplete, "problems": check.problems() + unsupported, "repairs": repairs, "saved": saved.as_posix(), @@ -1941,10 +2035,10 @@ def run( "model": context.model_id, } ) - if failures: + if failures or reading_incomplete: summary.update({ "status": "partial", "reason": "item_completion", - "message": "Some report items could not be completed.", + "message": "Report reading or report items are incomplete.", "incomplete_items": failures, }) trace.emit( @@ -1959,7 +2053,7 @@ def run( ) context.done( f"Saved {saved.as_posix()}", - evidence_count=read if failures else len(passages), + evidence_count=read, ) evidence = tuple( @@ -1973,7 +2067,7 @@ def run( "cell": chunk.cell, } for index, chunk in enumerate(passages) - if not failures or index in read_indices + if index in read_indices ) answer = " ".join(lead) + "\n\n---\n\n" + file_text.strip() return ToolResult(answer, evidence, summary) @@ -2106,7 +2200,8 @@ def _write_section( context.progress(f"Writing {section.name}") system, prompt = section_prompt(template, section, name, notes, written) coverage = ( - "\n\nSome reading parts failed. Use only the supplied notes. " + "\n\nSome reading material was omitted or unavailable. " + "Use only the supplied notes. " "When these do not cover a topic, say it could not be established " "from the available notes, not that it is absent from the paper." if incomplete_reading else "" @@ -2342,28 +2437,24 @@ def _write_pdf( def _paper_file(path: Path, context: ToolContext) -> Path | None: - """Return the paper on disk, for its PDF metadata and page layout. + """Return an explicitly chosen output, never an indexed source alias. Parameters ---------- - path: pathlib.Path - The paper's path: ``outputs/...`` (relative to the project) or an - indexed source path (relative to the project's ``sources/``). + path: Path + Project-relative explicit output path. context: ToolContext - KíLín's services (``project_root``). - - Returns - ------- - pathlib.Path | None - The first of these that is a file, or None. + Host services for the current tool operation. """ - root = context.project_root - for candidate in (root / path, root / PROJECT_SOURCES_DIRECTORY / path): - if candidate.is_file(): - return candidate - + candidate = root / path + folder = root / OUTPUTS_FOLDER + if (path.parts and path.parts[0] == OUTPUTS_FOLDER + and candidate.is_file() and not candidate.is_symlink() + and candidate.resolve().is_relative_to(folder.resolve()) + and not folder.is_symlink()): + return candidate return None diff --git a/kilin/tools/paper_overview/CHANGELOG.md b/kilin/tools/paper_overview/CHANGELOG.md new file mode 100644 index 00000000..747f5508 --- /dev/null +++ b/kilin/tools/paper_overview/CHANGELOG.md @@ -0,0 +1,5 @@ +# paper_overview changelog + +This changelog records changes to the `paper_overview` tool. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/kilin/tools/paper_overview/README.md b/kilin/tools/paper_overview/README.md index 97d096f7..2878a27b 100644 --- a/kilin/tools/paper_overview/README.md +++ b/kilin/tools/paper_overview/README.md @@ -1,12 +1,15 @@ # paper_overview -This package owns the `paper_overview` registered tool. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type tool settings override the keys in `SETTINGS`. Other sections are internal execution parameters. All values are read and validated on import. +This package owns the `paper_overview` registered tool. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type intent settings override packaged `SETTINGS` values; saved project-specific overrides take precedence for exposed settings. See the [configuration policy](../../../docs/configuration.md#tool-configuration-and-resources). Other sections are internal execution parameters. Packaged values are validated on import. + +Bibliography containers (`.bib` and `.bbl`) are excluded from paper +selection. To inspect entries, ask an explicit bibliography question instead. ## Defaults ### `SETTINGS` -- `MAX_TOKENS` (default `6000`): Most estimated tokens of the paper given to the model (1000-20000). Allowed range: 1000–20000. +- `MAX_TOKENS` (default `6000`): Most estimated passage-text tokens across the chosen document and its permitted related members (1000-20000). Allowed range: 1000–20000. ### `HEURISTICS` @@ -30,4 +33,21 @@ may use an explicit smaller cap, never exceeding the user's maximum. Changing `THINKING` to `inherit` resets this tool to the main setting; `on` forces thinking and bypasses local short-response caps. Restart after editing cached defaults. See the [shared policy](../../../docs/configuration.md#internal-tool-thinking) -for precedence, the retained exceptions, and migration of obsolete keys. +for precedence, output-limit exceptions, and configuration validation. + +### Source organization settings + +- `TARGET_ROLES` (`target_roles`, default `[]`): eligible anchor roles. +- `EVIDENCE_ROLES` (`evidence_roles`, default `[]`): eligible related roles. +- `RELATED_EVIDENCE` (`related_evidence`, default `[]`): accepted relation + identifiers to expand. Empty disables expansion. Empty role lists impose + no extra role restriction. Project overrides retain their precedence. + +Only original indexed passages of the chosen target and explicitly permitted +related evidence are used. Bibliography links are not scientific evidence. +Coverage identifies each physical member; unindexed or omitted material is +not negative evidence. + +One aggregate passage-text budget is used; anchor opening passages are +preferred when they fit, and the selected evidence is restored to physical +source order. diff --git a/kilin/tools/paper_overview/__init__.py b/kilin/tools/paper_overview/__init__.py index d07b9fda..07b0e8c0 100644 --- a/kilin/tools/paper_overview/__init__.py +++ b/kilin/tools/paper_overview/__init__.py @@ -18,6 +18,10 @@ Module Structure ---------------- +- ``PLUGIN`` + + Versioned descriptor discovered by the tool registry. + - ``parse_settings`` and ``run`` The registry entry points for this tool. @@ -30,16 +34,33 @@ """ -from kilin.tools.paper_overview.tool import ( +from kilin.tools import Tool + +from .tool import ( OverviewSettings, overview_prompt, parse_settings, + source_policies, run, ) __all__ = [ + "source_policies", + "PLUGIN", "OverviewSettings", "overview_prompt", "parse_settings", "run", ] + + +PLUGIN = Tool( + name="paper_overview", + summary="Summarize one paper in the chat; ask which paper when it is " + "unclear.", + parse_settings=parse_settings, + source_policies=source_policies, + run=run, + version="0.1.0", + api_version=1, +) diff --git a/kilin/tools/paper_overview/_configuration.py b/kilin/tools/paper_overview/_configuration.py index 9b3945dc..c3d5d0dc 100644 --- a/kilin/tools/paper_overview/_configuration.py +++ b/kilin/tools/paper_overview/_configuration.py @@ -32,6 +32,8 @@ from __future__ import annotations +from kilin.tools import check_source_ids + from pathlib import Path from typing import Final @@ -50,6 +52,10 @@ ) __all__ = [ + "DEFAULT_TARGET_ROLES", + "DEFAULT_EVIDENCE_ROLES", + "DEFAULT_RELATED_EVIDENCE", + "MODEL_CALLS", "DEFAULT_MAX_TOKENS", "OPENING_PASSAGES", @@ -69,6 +75,7 @@ require_keys( _SETTINGS, { "MAX_TOKENS", + "TARGET_ROLES", "EVIDENCE_ROLES", "RELATED_EVIDENCE", }, "paper_overview.SETTINGS" ) DEFAULT_MAX_TOKENS: Final[int] = ( @@ -101,3 +108,13 @@ MODEL_CALLS: Final[ModelCallSettings] = load_model_call_settings( Path(__file__).with_name("defaults.json") ) + +DEFAULT_TARGET_ROLES: Final[tuple[str, ...]] = check_source_ids( + "paper_overview.SETTINGS", _SETTINGS, "TARGET_ROLES" +) +DEFAULT_EVIDENCE_ROLES: Final[tuple[str, ...]] = check_source_ids( + "paper_overview.SETTINGS", _SETTINGS, "EVIDENCE_ROLES" +) +DEFAULT_RELATED_EVIDENCE: Final[tuple[str, ...]] = check_source_ids( + "paper_overview.SETTINGS", _SETTINGS, "RELATED_EVIDENCE" +) diff --git a/kilin/tools/paper_overview/defaults.json b/kilin/tools/paper_overview/defaults.json index 6219b521..21ab3f07 100644 --- a/kilin/tools/paper_overview/defaults.json +++ b/kilin/tools/paper_overview/defaults.json @@ -1,6 +1,9 @@ { "SETTINGS": { - "MAX_TOKENS": 6000 + "MAX_TOKENS": 6000, + "TARGET_ROLES": [], + "EVIDENCE_ROLES": [], + "RELATED_EVIDENCE": [] }, "HEURISTICS": { "OPENING_PASSAGES": 2 diff --git a/kilin/tools/paper_overview/settings_info.json b/kilin/tools/paper_overview/settings_info.json index 67d74d16..40513d6b 100644 --- a/kilin/tools/paper_overview/settings_info.json +++ b/kilin/tools/paper_overview/settings_info.json @@ -3,8 +3,23 @@ "settings": { "max_tokens": { "title": "Maximum overview tokens", - "summary": "Limits the text budget used for the paper overview.", - "description": "Caps context included while collecting an overview of a paper." + "summary": "Limits the estimated evidence tokens across all members.", + "description": "One aggregate passage-text budget for the chosen anchor and its permitted evidence, not a separate budget per related file." + }, + "target_roles": { + "title": "Target roles", + "summary": "Restricts eligible document anchors.", + "description": "Accepted role identifiers. Empty permits all eligible anchors." + }, + "evidence_roles": { + "title": "Related evidence roles", + "summary": "Restricts supporting member roles.", + "description": "Accepted role identifiers. Empty permits any eligible related evidence role." + }, + "related_evidence": { + "title": "Related evidence", + "summary": "Selects relationships for group reading.", + "description": "Accepted relation identifiers. Empty reads only the selected physical document." } } } diff --git a/kilin/tools/paper_overview/tool.py b/kilin/tools/paper_overview/tool.py index 5bdf66f2..1a255486 100644 --- a/kilin/tools/paper_overview/tool.py +++ b/kilin/tools/paper_overview/tool.py @@ -16,8 +16,8 @@ at the end of the answer. Passages that do not fit the token budget are left out, so a long paper is -summarized from part of its text. The first passage is always included, -even when it alone is larger than the budget. +summarized from part of its text. A passage exceeding the remaining +aggregate budget is omitted. Key Features ------------ @@ -74,10 +74,14 @@ from kilin.chunking import Chunk from kilin.retrievals.document_reading import estimate_tokens from kilin.tools._shared.citations import inspect_citations -from kilin.tools._shared.document_notes import answer_citations -from kilin.tools._shared.choose_document import choose_document -from kilin.tools.paper_overview import _configuration as _config -from kilin.tools._contract import ( +from kilin.tools._shared.group_reading import ( + choose_group, reading_policy, +) +from kilin.tools import ( + SourcePolicy, check_source_ids, +) +from . import _configuration as _config +from kilin.tools import ( ToolContext, ToolRequest, ToolResult, @@ -86,6 +90,7 @@ ) __all__ = [ + "source_policies", "OverviewSettings", "overview_prompt", "parse_settings", @@ -106,9 +111,19 @@ class OverviewSettings: max_tokens: int Most estimated tokens of the paper given to the model (1000-20000). + target_roles: tuple[str, ...] + Eligible anchor roles; empty means unrestricted. + evidence_roles: tuple[str, ...] + Eligible related evidence roles; empty means unrestricted. + related_evidence: tuple[str, ...] + Accepted relation identifiers to expand; empty reads only the anchor. + """ max_tokens: int = _config.DEFAULT_MAX_TOKENS + target_roles: tuple[str, ...] = _config.DEFAULT_TARGET_ROLES + evidence_roles: tuple[str, ...] = _config.DEFAULT_EVIDENCE_ROLES + related_evidence: tuple[str, ...] = _config.DEFAULT_RELATED_EVIDENCE def parse_settings(data: dict, where: str) -> OverviewSettings: @@ -133,16 +148,40 @@ def parse_settings(data: dict, where: str) -> OverviewSettings: """ - reject_unknown(where, data, ("max_tokens",)) + reject_unknown(where, data, ( + "max_tokens", "target_roles", "evidence_roles", "related_evidence", + )) defaults = OverviewSettings() return OverviewSettings( max_tokens=check_int( where, data, "max_tokens", defaults.max_tokens, 1000, 20000 ), + target_roles=check_source_ids( + where, data, "target_roles", defaults.target_roles + ), + evidence_roles=check_source_ids( + where, data, "evidence_roles", defaults.evidence_roles + ), + related_evidence=check_source_ids( + where, data, "related_evidence", defaults.related_evidence + ), ) +def source_policies(settings: OverviewSettings) -> tuple[SourcePolicy, ...]: + """Declare the reading policy for accepted vocabulary validation. + + Parameters + ---------- + settings: OverviewSettings + Validated settings for this tool. + + """ + return (reading_policy(settings.target_roles, settings.evidence_roles, + settings.related_evidence),) + + def overview_prompt( question: str, name: str, @@ -170,14 +209,17 @@ def overview_prompt( """ system = ( - "You summarize one scientific paper for KíLín from passages of " - "it. Use only the passages, cite them like [3], and never add " + "You summarize a chosen document for KíLín from its passages and " + "explicitly permitted related evidence. Distinguish the physical " + "sources; never attribute a related passage to the anchor. " + "Use only the passages, cite them like [3], and never add " "results they do not state." ) listed = "\n\n".join( - f"[{number}] {chunk.text.strip()}" for number, chunk in passages + f"Source: {chunk.path.as_posix()}\n[{number}] {chunk.text.strip()}" + for number, chunk in passages ) - user = f"""Passages of {name}, in reading order: + user = f"""Passages for {name}, in physical source order: {listed} @@ -213,44 +255,57 @@ def run( """ context.progress("Finding the paper") - chosen = choose_document( - request, - context, + chosen = choose_group( + request, context, source_policies(settings)[0], question="Which paper should I summarize?", example="give me a short summary of smith2020.pdf", prefer=(".pdf",), + paper_only=True, ) summary: dict[str, object] = {"name": "paper_overview"} if isinstance(chosen, str): context.done("No paper chosen", evidence_count=0) return ToolResult(chosen, (), summary) - path, reason, guessed = chosen + path, reason, guessed = chosen.anchor, chosen.reason, chosen.guessed summary.update( {"paper": path.as_posix(), "reason": reason, "guessed": guessed} ) - # The opening passages first, then the best-ranked ones, while they fit - # the budget; the first passage is always taken. - paper = [chunk for chunk in context.chunks if chunk.path == path] + # Anchor openings first, then rank within the chosen physical members. + paper = chosen.chunks order = {chunk.identifier: index for index, chunk in enumerate(paper)} ranked = [ order[result.chunk.identifier] - for result in context.rank(request.question) + for result in (chosen.services.rank(request.question) if paper + else ()) if result.chunk.identifier in order ] picked: list[int] = [] used = 0 - for index in list(range(_OPENING_PASSAGES)) + ranked: + opening = [i for i, chunk in enumerate(paper) if chunk.path == path] + for index in opening[:_OPENING_PASSAGES] + ranked + list( + range(len(paper)) + ): if index >= len(paper) or index in picked: continue size = estimate_tokens(paper[index].text) - if picked and used + size > settings.max_tokens: + if used + size > settings.max_tokens: continue picked.append(index) used += size chunks = [paper[index] for index in sorted(picked)] + summary["member_coverage"] = chosen.coverage(picked) + summary["reading_complete"] = all( + row["complete"] for row in summary["member_coverage"] + ) + notice = chosen.notice(picked) + if not chunks: + context.done("No fitting indexed passages", evidence_count=0) + return ToolResult("No fitting indexed passages to read. " + notice, + (), summary) + chosen.validate() context.done( - f"Read {len(chunks)} passages of {path.name}", + f"Read {len(chunks)} passages for {path.name}", evidence_count=len(chunks), ) @@ -260,7 +315,12 @@ def run( list(enumerate(chunks, start=1)), request.guidance, ) + if notice: + prompt += "\n\n" + notice answer = context.write(system, prompt, None) + chosen.validate() + if notice: + answer += "\n\n*" + notice + "*" citation_report = inspect_citations(answer, len(chunks)) summary["invalid_citations"] = list(citation_report.invalid_numbers) if citation_report.invalid_groups: diff --git a/kilin/tools/project_inventory/CHANGELOG.md b/kilin/tools/project_inventory/CHANGELOG.md new file mode 100644 index 00000000..7992ca6e --- /dev/null +++ b/kilin/tools/project_inventory/CHANGELOG.md @@ -0,0 +1,5 @@ +# project_inventory changelog + +This changelog records changes to the `project_inventory` tool. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/kilin/tools/project_inventory/README.md b/kilin/tools/project_inventory/README.md index 6bfeea14..69e17e3d 100644 --- a/kilin/tools/project_inventory/README.md +++ b/kilin/tools/project_inventory/README.md @@ -1,6 +1,6 @@ # project_inventory -This package owns the `project_inventory` registered tool. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type tool settings override the keys in `SETTINGS`. Other sections are internal execution parameters. All values are read and validated on import. +This package owns the `project_inventory` registered tool. Its `defaults.json` is independent of `kilin_defaults.json`. Project-type intent settings override packaged `SETTINGS` values; saved project-specific overrides take precedence for exposed settings. See the [configuration policy](../../../docs/configuration.md#tool-configuration-and-resources). Other sections are internal execution parameters. Packaged values are validated on import. ## Defaults @@ -12,19 +12,11 @@ This package owns the `project_inventory` registered tool. Its `defaults.json` i ## Generation settings -Output allowances come from the active session, including per-question GUI -or API settings. They are ceilings for each model call, not target lengths -or a total budget for a multi-call tool. Prose length is controlled by the -prompt or report template; input passage budgets remain separate. +The tool derives counts and file listings deterministically from the +selected source inventory and indexed chunks. It calls neither the +answering model nor the router, so model-generation limits do not apply. `MODEL_CALLS` contains one key: `THINKING` (packaged value `"inherit"`). -It accepts `inherit`, `on`, or `off` for internal `context.ask_model` calls. -It never infers thinking from a token count. `context.write` always inherits -main-session thinking. Router calls remain nonthinking and separately bounded. - -Thinking requests use the user's full allowance. Only nonthinking requests -may use an explicit smaller cap, never exceeding the user's maximum. -Changing `THINKING` to `inherit` resets this tool to the main setting; `on` -forces thinking and bypasses local short-response caps. Restart after editing -cached defaults. See the [shared policy](../../../docs/configuration.md#internal-tool-thinking) -for precedence, the retained exceptions, and migration of obsolete keys. +It accepts `inherit`, `on`, or `off` for internal `context.ask_model` calls, +which this tool does not make. See the [shared policy](../../../docs/configuration.md#internal-tool-thinking) +for precedence and configuration validation. diff --git a/kilin/tools/project_inventory/__init__.py b/kilin/tools/project_inventory/__init__.py index fc229e56..6a03d50d 100644 --- a/kilin/tools/project_inventory/__init__.py +++ b/kilin/tools/project_inventory/__init__.py @@ -18,6 +18,10 @@ Module Structure ---------------- +- ``PLUGIN`` + + Versioned descriptor discovered by the tool registry. + - ``parse_settings`` and ``run`` The registry entry points for this tool. @@ -30,7 +34,9 @@ """ -from kilin.tools.project_inventory.tool import ( +from kilin.tools import Tool + +from .tool import ( InventorySettings, file_types_in, parse_settings, @@ -38,8 +44,20 @@ ) __all__ = [ + "PLUGIN", "InventorySettings", "file_types_in", "parse_settings", "run", ] + + +PLUGIN = Tool( + name="project_inventory", + summary="Count and list the project's files by type and folder, with " + "which have searchable text.", + parse_settings=parse_settings, + run=run, + version="0.1.0", + api_version=1, +) diff --git a/kilin/tools/project_inventory/tool.py b/kilin/tools/project_inventory/tool.py index b4a01b6c..115ad343 100644 --- a/kilin/tools/project_inventory/tool.py +++ b/kilin/tools/project_inventory/tool.py @@ -70,8 +70,8 @@ import re from typing import Final -from kilin.tools.project_inventory import _configuration as _config -from kilin.tools._contract import ( +from . import _configuration as _config +from kilin.tools import ( ToolContext, ToolRequest, ToolResult, diff --git a/kilin/tools/project_summary/CHANGELOG.md b/kilin/tools/project_summary/CHANGELOG.md new file mode 100644 index 00000000..cda45ba7 --- /dev/null +++ b/kilin/tools/project_summary/CHANGELOG.md @@ -0,0 +1,5 @@ +# project_summary changelog + +This changelog records changes to the `project_summary` tool. Changelog maintenance begins after the +first stable release of KíLín (`0.1.0`). No beta or release-candidate +history is required. diff --git a/kilin/tools/project_summary/README.md b/kilin/tools/project_summary/README.md index 1a7c5e7a..b5d70373 100644 --- a/kilin/tools/project_summary/README.md +++ b/kilin/tools/project_summary/README.md @@ -3,8 +3,8 @@ This package owns the `project_summary` registered tool: one report on all the documents of a project, written from a project template (`scope: project`). Where a search-based answer reads the few passages a question -retrieves, this tool considers all indexed documents, up to the -configured `MAX_DOCUMENTS` limit. A skipped or failed document makes the +retrieves, this tool enumerates eligible independent logical documents before the +configured `MAX_DOCUMENTS` limit. A skipped or failed member makes the saved report explicitly partial. It is offered by the `templated_project_report` intent of the Literature and Writing Assistant project types. @@ -12,10 +12,14 @@ project types. For "write a project overview", the tool: 1. **Chooses the template**: the project template the question names (by - title or complete file name), otherwise the project's only project - template, or the one the user chooses from a list. Names that overlap - are resolved by their complete boundaries; naming multiple templates - is an error. Invalid choices cancel without reading any documents. + title or complete file name), otherwise the fixed configured template. + With `choose` and no named template, the tool uses the only valid project + template or asks the user to choose among several. If none is usable, + the tool reports the problem; without an interactive callback, the user + must name one when several are available. Names that overlap are resolved + by their complete boundaries; naming multiple templates is an error. + Invalid named or fixed templates are rejected without fallback; cancelled + or invalid interactive choices stop the report before reading documents. The GUI receives the shared traced choice event before it waits for an answer. A document-scoped template named in the request or set as the fixed default is rejected; broken project templates are reported, @@ -23,8 +27,8 @@ For "write a project overview", the tool: 2. **Plans the work**: one model call per document and one per written section, with an estimated time (`ESTIMATES`). With `CONFIRMATION` `when_large`, a plan of more than `LARGE_BATCHES` calls asks first; the - quick version ("Shorter reading") reads only each document's card and - opening (`QUICK_DOCUMENT_TOKENS`). Documents beyond `MAX_DOCUMENTS`, in + quick version ("Shorter reading") uses a smaller aggregate group excerpt + (`QUICK_DOCUMENT_TOKENS`). Independent anchors beyond `MAX_DOCUMENTS`, in path order, are left out and the plan says so. The saved report also identifies omitted files in a **Coverage** section (up to ten filenames; all omitted paths remain in result metadata). @@ -32,9 +36,9 @@ For "write a project overview", the tool: 4. **Writes the report** (the reduce step, below), checks it against the template (`TEMPLATE_VALIDATION`), and saves it to `outputs/