From 7bcce157ae451a5fbf0026f8b8c0f4eb3e367c20 Mon Sep 17 00:00:00 2001 From: Giovanni Volpe Date: Wed, 2 Dec 2026 18:35:24 +0100 Subject: [PATCH 01/37] 12 --- docs/PLUGIN_API.md | 9 +- docs/configuration.md | 20 +- docs/conversation_memory.md | 6 +- docs/extension_interfaces.md | 12 +- docs/gui_protocol.md | 2 +- docs/module_map.md | 5 +- docs/project_workspaces.md | 192 ++++- docs/retrieval_pipeline.md | 6 +- docs/security.md | 3 +- docs/source_manifest.md | 84 +- docs/source_pipeline.md | 6 +- docs/versioning.md | 2 +- kilin/_source_access.py | 21 +- kilin/_source_manifest.py | 38 +- kilin/_source_ownership.py | 213 +++++ kilin/_tool_sources.py | 4 +- kilin/gui/README.md | 3 +- kilin/gui/_source_organization.py | 7 +- kilin/gui/engine.py | 136 +++- kilin/gui/web/index.html | 1 - kilin/gui/web/source_organization_panel.js | 11 +- kilin/project.py | 565 +++++++++----- kilin/project_files.py | 51 +- kilin/project_layout.py | 105 ++- kilin/rag.py | 34 +- kilin/source_manifest.py | 73 +- kilin/source_views.py | 7 +- kilin/system_testing/_semantic_replay.py | 7 +- kilin/system_testing/validation.py | 4 +- kilin/workspace.py | 731 ++++++++++++------ tests/kilin/_rag_support.py | 39 +- .../gui/test__source_organization_frontend.py | 6 +- tests/kilin/gui/test_engine__references.py | 42 +- .../kilin/gui/test_engine__saved_projects.py | 43 ++ .../gui/test_engine__source_organization.py | 14 + .../gui/test_engine__source_ownership.py | 376 +++++++++ .../system_testing/test_traces__semantics.py | 27 + tests/kilin/test__format_versions.py | 3 +- tests/kilin/test__source_discovery.py | 14 +- tests/kilin/test_project.py | 234 ++++-- tests/kilin/test_project__mirror_ownership.py | 434 +++++++++++ tests/kilin/test_project_files.py | 99 +++ tests/kilin/test_project_layout.py | 79 +- tests/kilin/test_rag.py | 4 +- tests/kilin/test_rag__conversation.py | 70 +- tests/kilin/test_rag__index_provenance.py | 39 +- tests/kilin/test_rag__retrieval.py | 29 +- tests/kilin/test_source_manifest.py | 84 +- .../kilin/test_source_manifest__lifecycle.py | 17 +- tests/kilin/test_source_views.py | 12 +- tests/kilin/test_workspace.py | 85 +- tests/kilin/test_workspace__ownership.py | 396 ++++++++++ tests/kilin/test_workspace__source_changes.py | 4 +- .../test_workspace__source_management.py | 26 +- tests/kilin/test_workspace__source_schema.py | 672 ++++++++++++++++ .../tools/_shared/test__source_access.py | 40 + tutorials/140_project_chat.ipynb | 6 +- tutorials/160_project_types.ipynb | 2 +- 58 files changed, 4292 insertions(+), 962 deletions(-) create mode 100644 kilin/_source_ownership.py create mode 100644 tests/kilin/gui/test_engine__source_ownership.py create mode 100644 tests/kilin/test_project__mirror_ownership.py create mode 100644 tests/kilin/test_workspace__ownership.py create mode 100644 tests/kilin/test_workspace__source_schema.py diff --git a/docs/PLUGIN_API.md b/docs/PLUGIN_API.md index b61eb0ba..2d3cd742 100644 --- a/docs/PLUGIN_API.md +++ b/docs/PLUGIN_API.md @@ -181,7 +181,7 @@ Treat indexed data and host-owned records as read-only. | `ToolContext` field | Supported behavior | | --- | --- | -| `project_root`, `source_root` | Workspace root and optional saved source root. | +| `project_root`, `source_root` | Workspace root and optional canonical `sources/` root. | | `chunks`, `graph`, `rank`, `retrieval_count` | Indexed `Chunk` records, `CodeGraph`, complete hybrid ranking and configured retrieval count. | | `source_files()`, `unsearchable(paths)` | Selected source paths and sizes; files without indexed text. | | `source_view(policy, scope)` | Optional host factory returning `ToolSourceServices` bound to one operation generation. | @@ -347,9 +347,10 @@ configuration, write its files or invent interaction events. See Use `selected_paths(context)` to obtain the active selected-source inventory. `selected_source_file(project_root, source_root, path, selected)` validates a -selected source-relative regular file and returns a contained path or `None`; -it does not search arbitrary folders or accept symlink traversal. Handle an -absent `source_root` explicitly. These helpers are not a security sandbox. +selected source-relative regular file under the project's real `sources/` +directory and returns a contained path or `None`. It rejects alternate roots, +symlinks, and junctions. Handle an absent `source_root` explicitly. These +helpers are not a security sandbox. `save_output_file(project_root, name, text)` writes a text output under a safe, unique filename in the workspace's outputs folder without overwriting an existing file. Use relative imports for package-local code and locate owned assets relative diff --git a/docs/configuration.md b/docs/configuration.md index d19843d9..2e4eadbe 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -123,10 +123,10 @@ These declarations are not project assignments or a new index configuration. New projects capture these defaults in the [accepted source manifest](source_manifest.md). Project-local organization settings are edited through its preview/apply API. Imports and refreshes use the accepted settings, not newly installed defaults. -Changing `profile.ini` to point to a different source root requires an -explicit semantic rebind. A moved workspace with a project-relative source -root keeps its binding. Missing/corrupt manifests and detector mismatches are -reported rather than implicitly repaired or adopted. +Every project uses its real `sources/` directory. Alternative configured +roots and source-root rebinding are unsupported. Moving the whole current +workspace preserves its relative semantic binding. Missing/corrupt manifests +and detector mismatches are reported rather than implicitly repaired or adopted. Ordinary intents have `retrieval.related_evidence` and `retrieval.related_lookup` arrays of declared relation IDs. The core behavior @@ -572,15 +572,17 @@ The current representations are: 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. +must not be assumed to match this schema. Alternative source-folder names +are also rejected; current profiles must select the real `sources/` +directory. The unrelated `kind` fields on source entities and chunks retain +their meaning. -### 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 earlier layouts +are preserved without automatic conversion. ## GUI defaults and writable preferences diff --git a/docs/conversation_memory.md b/docs/conversation_memory.md index 398c35c6..ca5758de 100644 --- a/docs/conversation_memory.md +++ b/docs/conversation_memory.md @@ -49,9 +49,9 @@ 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. +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 diff --git a/docs/extension_interfaces.md b/docs/extension_interfaces.md index e2e2d51f..8e2cd871 100644 --- a/docs/extension_interfaces.md +++ b/docs/extension_interfaces.md @@ -112,14 +112,14 @@ an error, allowing the GUI to request fresh defaults for a valid selection. Reinstall or correct the definition or its required tools and restart to restore availability; saved workspaces require no migration. -A project type does not name the source folder: every new project uses +A project type does not name the source folder: every project uses `sources/`. See [workspace source convention](project_workspaces.md#source-directory-convention) -for the layout and how existing projects keep theirs. A new type cannot bypass -the core's creation-only ownership rules or authorize reuse of an occupied -workspace. Empty projects are -supported for every type. Missing welcome content has generic fallbacks; -project-type prompts, tools and retrieval policies still control answers. +for the required layout and rejection of unsupported source paths. A type +cannot bypass the core's creation-only ownership rules or authorize reuse of +an occupied workspace. Empty projects are supported for every type. Missing +welcome content has generic fallbacks; project-type prompts, tools and +retrieval policies still control answers. Each intent key names an operation. Its fields may supply a description, shortcuts, wording `cues` that set the intent, `requires` patterns a diff --git a/docs/gui_protocol.md b/docs/gui_protocol.md index 0e3ddc14..1b4b4b5e 100644 --- a/docs/gui_protocol.md +++ b/docs/gui_protocol.md @@ -496,7 +496,7 @@ and echoes the operation, project and request ID. | Operation | Additional fields | Effect | | --- | --- | --- | | `inspect` | None | Read saved and current organization; no repair or write | -| `preview` | `revision`, `sha256`; optional `edits`, `organization`, `adopt_type_defaults`, `role_mapping`, `relation_mapping`, `rebind`, `adopt_detector_versions` | Validate a batch against the displayed exact saved identity; no write | +| `preview` | `revision`, `sha256`; optional `edits`, `organization`, `adopt_type_defaults`, `role_mapping`, `relation_mapping`, `adopt_detector_versions` | Validate a batch against the displayed exact saved identity; no write | | `apply` | `preview_id` | Consume the current server-side preview and atomically apply it through the core | | `initialize` | None | Explicitly initialize missing metadata, never overwrite malformed metadata | | `reconcile` | None | Materialize defaults and reconcile selected paths/discovery under accepted settings | diff --git a/docs/module_map.md b/docs/module_map.md index c2a4d00a..2d067c90 100644 --- a/docs/module_map.md +++ b/docs/module_map.md @@ -30,6 +30,7 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | [`kilin/_tool_sources.py`](../kilin/_tool_sources.py) | Bind tool source services to a captured generation. | [Plugin API](PLUGIN_API.md) | [Live scope tests](../tests/kilin/test_rag__source_scope.py) | | [`kilin/_source_discovery.py`](../kilin/_source_discovery.py) | Reconcile deterministic relationships under accepted project settings. | [Source manifest](source_manifest.md) | [Discovery tests](../tests/kilin/test__source_discovery.py) | | [`kilin/_source_manifest.py`](../kilin/_source_manifest.py) | Define the immutable semantic source-manifest format and its validator. | [Source manifest](source_manifest.md) | [Manifest tests](../tests/kilin/test_source_manifest.py) | +| [`kilin/_source_ownership.py`](../kilin/_source_ownership.py) | Validate exclusive import or mirror ownership and mirror provenance. | [Project workspaces](project_workspaces.md) | [Ownership tests](../tests/kilin/test_workspace__ownership.py), [Mirror tests](../tests/kilin/test_project__mirror_ownership.py) | | [`kilin/answer_timeline.py`](../kilin/answer_timeline.py) | Record lightweight, persistent timing for an answered conversation turn. | [Answering pipeline](answering_pipeline.md) | [Timeline tests](../tests/kilin/test_answer_timeline.py) | | [`kilin/answering.py`](../kilin/answering.py) | Route questions by intent and select conversation history. | [Answering pipeline](answering_pipeline.md) | [Core tests](../tests/kilin/) | | [`kilin/atomic_writes.py`](../kilin/atomic_writes.py) | Replace or exclusively publish text files atomically. | [Conversation ownership](conversation_ownership.md) | [Core tests](../tests/kilin/) | @@ -280,7 +281,7 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | Model management | 8 | | Per-tool README | 59 | | Plugin API | 9 | -| Project workspaces | 6 | +| Project workspaces | 7 | | Project-type schema | 1 | | Retrieval pipeline | 35 | | Source manifest | 5 | @@ -292,7 +293,7 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | Trace recording | 1 | | Versioning | 1 | -**Total production Python modules: 244.** +**Total production Python modules: 245.** ## Non-Python resources and UI assets diff --git a/docs/project_workspaces.md b/docs/project_workspaces.md index d43de582..f73feffe 100644 --- a/docs/project_workspaces.md +++ b/docs/project_workspaces.md @@ -37,12 +37,12 @@ not currently use a templated tool. Users can add Markdown templates or other resources manually under `templates//`. The `outputs/` directory is a general area for project-owned results. Neither `outputs/` nor `templates/` is indexed as a -source directory by default. When a project's source is its own root -(`source = .`), KíLín's RAG scans explicitly exclude these managed -folders and the project-owned metadata files `profile.ini`, `sources.json`, -`source_snapshot.json`, `source_manifest.json` and its lock sidecar; -ordinary external source directories and files -with these names are not globally excluded. +source directory. All project scans are rooted in `sources/`, so managed +folders and project-root metadata are outside the source inventory. User +files or directories inside `sources/` may use these same names. The reserved +`.kilin_versions/` directory is excluded from ordinary scans; only explicitly +recorded retained versions are selected separately. Standalone +`scan_repository()` calls can still scan arbitrary directories. The derived `indexes/index_source_state.json` records the physical source inventory used for index reuse; it is distinct from `sources.json` (managed @@ -55,8 +55,10 @@ accepted defaults and relationships once per completed batch. The optional `on_organization` observer reports new assignments, pending roles, retained versions, proposals and reconciliation errors without changing physical API return types. Use `refresh_source_manifest()` for manually arrived files. -A changed source root must be explicitly rebound; an ordinary refresh cannot -transfer old assignments to a different corpus. +The semantic format is `kilin-source-manifest-v2`, with a canonical +`project:sources` binding. Rebinding and older semantic formats are rejected; +there is no migration or compatibility field. Moving a complete current +workspace preserves its relative binding and accepted assignments. See [Accepted source organization](source_manifest.md) for the schema, editing API, reconciliation, and writer ownership. See [Index persistence](retrieval_pipeline.md#index-persistence-and-identity) @@ -64,7 +66,7 @@ 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 @@ -73,12 +75,14 @@ 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. +The saved `[project] source` value is required and must be exactly `sources`. +The field declares the current layout; it cannot redirect source access. +Project-root sources, `documents`, `repository`, original-name mirrors, +absolute paths, and alternate spellings such as `./sources` are rejected in +both the core and GUI. The physical `sources/` entry must exist as a real +directory: files, symbolic links, and junctions are rejected. Opening and +validation never move, rename, delete, or migrate an unsupported layout. +Private profile writers expose no configurable source-root argument. ### Selected sources and authorized reads @@ -87,9 +91,9 @@ workspace**, not arbitrary files visible on the host filesystem. Imports from external folders are explicit user operations; a name or relative path written inside an imported document never authorizes another import. The current index source state records selected relative paths. The -project's configured source root determines where those names resolve, -while a shared core check rejects paths outside the workspace and -symlinks. A selected file missing from its managed location is reported +project's canonical `sources/` directory determines where those names +resolve, while a shared core check rejects alternate roots, traversal, +symbolic links, and junctions. A selected file missing from its managed location is reported unavailable, not substituted from the workspace root or original folder. For example, `.bib` and `.bbl` are ordinary selectable literature sources: @@ -115,7 +119,7 @@ folder.** This rule is enforced in the core, independently of the GUI. | `kilin.open_project(path)` | Read and validate a saved profile and source path without changing files or creating missing folders. | | `kilin.add_project_sources(path, source_paths, ...)` | Explicit cumulative import using the saved profile. Preserve existing snapshots unless `replace_existing=True` is requested. | | `kilin.prepare_project_workspace(source, type_id, parent)` | Create a fresh single-source mirror in `sources/` and record `source_snapshot.json`. | -| `kilin.synchronize_project_workspace(source, path)` | Explicitly synchronize that saved mirror. May replace local snapshot edits or remove copies deleted from the original. | +| `kilin.synchronize_project_workspace(source, path)` | Synchronize only recorded mirror paths. Repair tracked edits or missing copies, remove tracked deletions, and preserve untracked local files. | | `kilin.project.configure_project(path, settings)` | Explicitly validate and update the saved profile. | | `kilin.project.delete_project(path)` | Move a closed project into the `.deleted/` folder beside it, keeping its files. A name already there gets `_2`, `_3`, ... | @@ -129,10 +133,9 @@ subclass of `kilin.WorkspaceOccupiedError`. Other nonempty destinations, partial initialization, linked roots, and in-progress creation are rejected. Even malformed `profile.ini` entries count as an existing project. Creating inside another project's directory is also rejected. There is no creation -option that overrides these safeguards. A single-source mirror also rejects -source basenames that would alias managed state, such as `logs`, `indexes`, -`profile.ini`, or the creation marker. Import such folders with the cumulative -`sources/` API instead; their basenames are safe beneath that managed root. +option that overrides these safeguards. Source basenames do not select a +project source root: single-folder mirrors always copy into `sources/`, +and cumulative imports allocate entries beneath that directory. For automatic workspace naming, omit `workspace_directory` and supply `workspace_root`. With sources, the core derives a base name from the first @@ -178,12 +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 + +`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: + +| 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. + +Generation 1 and incomplete records are rejected before ownership-dependent +operations change files. They are not upgraded, repaired by filesystem +inference, or converted automatically. This format is independent of the +physical repository snapshot and semantic `source_manifest.json` formats. ### Callers updating existing projects @@ -245,9 +291,11 @@ 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 @@ -376,8 +424,8 @@ content, and such errors must be reported to the user. When a source snapshot is deleted through `kilin.remove_workspace_sources(project, paths)`, only files within a managed `sources/` folder can be removed. Original source paths are not -modified, and `sources.json` is updated to reflect removed entries. Projects -with external or root-as-source locations cannot use that deletion API. +modified, and `sources.json` is updated to reflect removed entries. The API +revalidates the current profile and canonical source directory before removal. Index refreshing is a separate core operation. `kilin.preview_project_sources(project, paths)` previews cumulative imports @@ -402,9 +450,10 @@ is a fast heuristic, not proof of identical contents. Previously tracked paths that vanish are `deleted`, including files renamed or moved to another path. Files at the new path may independently be reported as `added`; KíLín does not infer a relocation or transfer tracking identity between paths. -Files without stamps, missing workspace copies, and symlinks are skipped. -Older pre-release manifests without copy stamps remain readable, but -their existing snapshots do not automatically acquire change tracking. +Files without a known stamp, missing workspace copies, and symlinks are +skipped. A valid partial `stamps` mapping differs from an absent required +mapping: only the partial mapping is accepted. Reimporting while preserving +local copies retains unknown stamps until an explicit copy succeeds. An original directory that is unavailable may look deleted, so a caller should confirm bulk deletions. Unreadable source paths raise errors rather than silently triggering deletion. Independently edited workspace copies @@ -475,8 +524,67 @@ after accepted changes, callers should invoke `RAGSession.refresh_sources(project)` once, or reopen a RAG session to trigger incremental indexing. The GUI refreshes once after applying a batch. This API is specific to managed multi-source workspaces; -`kilin.synchronize_project_workspace()` is an older single-source -mirroring API with different semantics. +`kilin.synchronize_project_workspace()` is the single-source mirroring +API described below. + +### Single-source mirror ownership and synchronization + +A workspace uses at most one external-source ownership format: + +| Ownership metadata | Meaning | +| --- | --- | +| Neither file | Empty or manually populated project with no recorded external owner. | +| `sources.json` only | Cumulative managed imports. | +| `source_snapshot.json` only | A mirror of one original folder. | +| Both files | Conflicting ownership; source operations are rejected. | + +A present malformed file, symlink, junction, or non-file entry is an error, +not missing ownership. The semantic `source_manifest.json` is independent of +these files and can describe sources in any of the valid ownership modes. +Neither an import nor a mirror operation converts the other ownership mode. +Cumulative import preview, import, and synchronization reject a valid mirror; +read-only selection and version queries validate its metadata without creating +import records. Explicit local source deletion remains available and retains +mirror provenance, allowing a later mirror synchronization to restore a +tracked copy. Removing manual files without an ownership record does not +create `sources.json`. + +Ownership validation precedes copying, deletion, trace creation, semantic +writer locks, and RAG session preparation. Rejected ownership changes leave +source files and saved state unchanged. Read-only access to the saved project +profile and accepted semantic record remains available for inspection. + +`prepare_project_workspace()` creates a fresh mirror and records the absolute +original directory plus selected file sizes and SHA-256 hashes. An empty +selection still records that owner. `synchronize_project_workspace()` requires +valid saved mirror provenance matching the explicitly supplied original. +Missing, corrupt, incomplete, or conflicting provenance is rejected without +writing, renaming, deleting, or reconstructing the source tree. + +Synchronization scans and validates the whole planned batch before applying +it. It repairs edited or missing **tracked** copies, deletes tracked copies +no longer selected in the original, and imports newly selected originals +only into unoccupied paths. Any new original colliding with an untracked +local file is rejected before the first copy or deletion. Linked parents +are rejected. Original file/directory transitions are supported only when +planned tracked deletions own every blocking entry; untracked descendants, +including empty directories, block replacement. A tracked leaf symlink can +be replaced without reading or modifying its external target. + +Untracked local files, links, unrelated empty directories, and retained-version +contents are preserved. Cleanup attempts only the empty parents of removed +tracked files. There is no recursive removal or reconstruction of `sources/`. +Files are copied through unique temporary siblings and checked against the +scanned hash; newly owned names are published exclusively without overwriting +a concurrent local file. Unchanged tracked copies retain their inode. + +The batch is not one filesystem transaction. If a later copy or deletion +fails, earlier completed changes remain and their actual inventory is saved +atomically so a later synchronization can continue. A provenance write error +is reported, with the original physical error preserved when both fail; +completed physical changes are never falsely described as rolled back. +Original folders are never modified. As with other workspace operations, +these checks do not provide isolation against arbitrary concurrent writers. ## Project-owned outputs and templates @@ -494,7 +602,10 @@ The following GUI-independent core functions manage user-owned files: inside **either** `outputs/` or `templates/`, but cannot remove the managed folders themselves. - `kilin.list_project_files(project)` provides a filesystem inventory, - including empty folders, without importing the GUI. + including empty folders, without importing the GUI. It revalidates the + captured source directory and saved profile, and prunes symbolic links + and junctions before enumerating their contents. An unavailable project + type does not prevent listing, and missing derived folders remain missing. All paths are checked for containment and symlink traversal. These operations do not require a model or reindexing, and the GUI only delegates @@ -560,9 +671,8 @@ 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`, `project_layout.py`, `workspace_resources.py` and the affected `workspace.py` diff --git a/docs/retrieval_pipeline.md b/docs/retrieval_pipeline.md index 235750fa..04fa3c60 100644 --- a/docs/retrieval_pipeline.md +++ b/docs/retrieval_pipeline.md @@ -760,9 +760,9 @@ Membership and availability differ: a selected file without extracted passages can be a member, reported as `unindexed`. A missing or unresolved related path is reported as `unselected` or `unresolved` and is not included in usable membership. `raw_unavailable` identifies missing captured byte -identity or a source root outside the workspace; it need not imply that -indexed evidence is absent. The view does not assert that a source was read -or that its content supports a claim. +identity; it need not imply that indexed evidence is absent. Noncanonical +source roots are rejected before creating a view. The view does not assert +that a source was read or that its content supports a claim. ### Capturing and validating an operation diff --git a/docs/security.md b/docs/security.md index e3e9d702..f695fad8 100644 --- a/docs/security.md +++ b/docs/security.md @@ -163,7 +163,8 @@ for safe draft testing and confidentiality when using a frontier LLM. Resolved [source views](retrieval_pipeline.md#source-views-and-operation-snapshots) never grant access outside the selected inventory. The verified raw-byte service additionally retains workspace containment and checks captured -content digests. External source roots remain unavailable for raw reads. +content digests. Project sources must be the real `sources/` directory; +alternate roots, symbolic links, and junctions are rejected for raw reads. These checks are best effort, not race-free or protection from malicious trusted Python. Ordinary retrieval and bounded tool `retrieve()` validate and enforce the resolved view before ranking, including code-graph traversal diff --git a/docs/source_manifest.md b/docs/source_manifest.md index b1ad187a..990678b3 100644 --- a/docs/source_manifest.md +++ b/docs/source_manifest.md @@ -64,24 +64,21 @@ saved identity, including the earlier placeholder `not-implemented`, is not automatically reinterpreted. Explicit detector adoption previews the new behavior. -### Opening a workspace created before source organization - -1. Keep a backup of the workspace, including its profile, sources and logs. - Open it normally; existing source paths and the project type are preserved. -2. In the GUI, use **Organize sources** and explicitly initialize missing - metadata when prompted. In Python, use `initialize_source_manifest()`. - Review the accepted declaration and pending assignments. Initialization - does not infer scientific roles from filenames or import new files. -3. Assign roles and relationships with preview/apply, then refresh semantic - metadata for an active session. If the configured source root differs - from the saved binding, review and explicitly rebind rather than restoring - identities solely by filename. -4. Physical index reuse is independent of this initialization. The old - `indexes/source_manifest.json` cache is not the semantic manifest; it - is ignored by current index preparation. Let normal index preparation - regenerate derived state when needed, and do not copy that cache to the - project root. Preserve historical recordings; older traces lacking the - semantic command history cannot reconstruct unrecorded edits. +### 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. +Earlier semantic generations are not migrated or reinterpreted. The current +contract requires the project's real `sources/` directory, and supports moving +the entire current workspace without changing its relative binding. [Tutorial 160](../tutorials/160_project_types.ipynb) demonstrates accepted roles, automatic bibliography links, shared supplements, restricted views @@ -90,14 +87,16 @@ and stale-view rejection using fictional sources and no model inference. ## Format and graph rules The format authority is `kilin.SOURCE_ORGANIZATION_FORMAT`, with value -`kilin-source-manifest-v1`, reported as `source_organization` by +`kilin-source-manifest-v2`, reported as `source_organization` by `kilin.version_info()`. It is independent of the managed-import -`kilin.workspace.SOURCE_MANIFEST_VERSION`. JSON contains precisely these +`kilin.workspace.SOURCE_MANIFEST_VERSION`. Generation 2 fixes the binding to +`project:sources` and removes the retired `root_rebound` state. Generation 1 +is rejected without modification or migration. JSON contains precisely these fields. An illustrative complete manifest (the digest is illustrative): ```json { - "format": "kilin-source-manifest-v1", + "format": "kilin-source-manifest-v2", "revision": 3, "source_root": {"base": "project", "path": "sources"}, "organization": { @@ -144,18 +143,18 @@ materialized defaults need not equal a later adopted default. A relation has origin `user` with `rule: null`, or `rule` with a syntactically valid rule identifier. A suppression records an exact edge independently of rule version. -File identities are exact POSIX-style paths relative to the configured source -root. Reject absolute file paths, traversal, noncanonical separators, +File identities are exact POSIX-style paths relative to the project's +`sources/` directory. Reject absolute file paths, traversal, noncanonical separators, control characters, trailing dots/spaces and portable case/Unicode aliases, including aliased directory components. Live selection uses the same scanner and recorded explicit imports/versions as RAG. Linked or escaping descendants are not permitted. An incomplete scan cannot serve as a deletion list. -A source root inside the workspace is stored relative to the project, with -`.` for the project root itself. Other roots have `base: "absolute"` and an -absolute POSIX spelling of the resolved path. The saved binding is compared -with the currently configured resolved root; it is never used to authorize -reads. Moving a project with its relative source tree preserves the binding. +The saved root binding must be exactly `{"base": "project", "path": "sources"}`. +Other roots and alternative spellings are rejected. The core validates the +physical source directory independently; the saved binding is identity evidence +and does not authorize file reads. Moving the whole current workspace keeps +this relative binding and the accepted source identities. Dependencies point from dependent to parent and may have multiple parents. Self-links and directed cycles among active declared dependencies are rejected. @@ -168,7 +167,7 @@ which is rejected. A previously missing endpoint cannot become active simply because a file appears with that name. The writer serializes UTF-8 JSON with sorted object keys and canonical ordering -of file records, edges, suppressions and unresolved records. The v1 bounds +of file records, edges, suppressions and unresolved records. The v2 bounds are 16 MiB encoded metadata, 10,000 assignments, 10,000 unresolved records, 40,000 links, 40,000 suppressions, 256 items in each declaration collection, 4,096 UTF-8 bytes per path, 128 bytes per detector identity and revisions up @@ -204,9 +203,9 @@ assert result.snapshot == kilin.read_source_manifest(project) `read_source_manifest()` parses only the saved state and returns an immutable snapshot with the original-byte SHA-256. `inspect_source_manifest()` refreshes the profile, scans the selected inventory and reports active assignments, -active relationships, pending selected paths and inactive records. A binding -mismatch yields no active assignments or links, even for identical filenames. -Neither read performs a write or consults today's project-type defaults. +active relationships, pending selected paths and inactive records. Unsupported +source layouts and saved bindings are rejected, including when filenames match +an earlier corpus. Neither read writes or consults today's project-type defaults. `preview_source_manifest(project, edits)` validates the entire proposed batch without writing. `apply_source_manifest(project, preview)` revalidates it under @@ -238,14 +237,11 @@ read-only inspection does not persist an observed removal: commit reconciliation when recording removal matters. Deletion and recreation between reconciliations cannot reliably be distinguished from ordinary replacement. -If the configured corpus changes, a normal preview raises a binding conflict. -Use `preview_source_manifest(project, rebind=True)` to inspect the transition. -The preview marks all previously accepted paths `root_rebound`; matching -filenames are not automatically associated with their old meaning. Unmatched -new paths receive the accepted default. Explicit `ResolveSourceEdit` records -can accompany a rebind when the user has deliberately resolved those identities. -The operation changes only the manifest binding; it does not change the saved -profile or import/move any source files. +There is no source-root rebind operation. Preview and apply validate the +current canonical directory before editing metadata; a profile that names a +different source root is rejected without changing sources or semantic state. +Use explicit source import, removal and synchronization for changes to the +contents of `sources/`. ## Accepted settings and adoption @@ -385,7 +381,7 @@ requested batch. A semantic error is returned separately, or warned about when the physical API has no observer. Observer failures cannot roll back completed operations. The original physical exception is still raised. Missing metadata requires explicit initialization, corruption requires -review, and a changed configured source root requires explicit rebinding. +review, and a noncanonical source root is rejected without a rebind fallback. Normal refresh never adopts installed type or detector defaults. After committing only role or relationship changes, call @@ -448,7 +444,7 @@ Inactive records, retained versions and pending roles are visible but not automatically restored. Unresolved selected files can be restored or reset explicitly. Ordinary settings provide role and discovery-mode controls; advanced settings retain explicit vocabulary mappings, rule declarations, -installed defaults and detector adoption, and deliberate root rebinding. +installed defaults and detector adoption. Every staged batch is previewed through the core before Apply; closing the editor without applying leaves the manifest unchanged. Missing metadata can be initialized after confirmation, while malformed @@ -456,8 +452,8 @@ metadata remains an inspection error. See the [GUI guide](../kilin/gui/README.md Organization is not authorization. A link may refer to a selected SVG or other file with no reader; it does not make the contents searchable or widen -the authority of a raw source-reading tool. Rebinding and reconciliation -use the current scanner, not the stored graph, to establish live selection. +the authority of a raw source-reading tool. Reconciliation uses the current +scanner, not the stored graph, to establish live selection. Locks coordinate cooperating KíLín writers; they do not prevent external programs from bypassing them, nor guarantee race-free protection against hostile filesystem or profile changes. See [Security](security.md). diff --git a/docs/source_pipeline.md b/docs/source_pipeline.md index e4b9c7bb..4cbfe2f1 100644 --- a/docs/source_pipeline.md +++ b/docs/source_pipeline.md @@ -79,8 +79,10 @@ An empty newly created managed workspace is valid. It uses the same as a populated project; no example corpus is invented. Creation eligibility and later import APIs are documented with [workspace creation](project_workspaces.md#creation-opening-and-explicit-updates). -Opening a saved profile retains its source path. Outputs/templates are -separately managed user files, not automatically added to source indexing. +Opening a saved profile requires the canonical real `sources/` directory. +Alternative roots and source-root rebinding are rejected without changing +user files. Outputs/templates are separately managed user files and remain +outside source indexing. After explicit source changes, the GUI asks the core to refresh indexes. Imports and indexing are not a single multi-file transaction: successful diff --git a/docs/versioning.md b/docs/versioning.md index 3f178890..536057c5 100644 --- a/docs/versioning.md +++ b/docs/versioning.md @@ -194,7 +194,7 @@ for the trace format or the application version. | Operation recording | `kilin._trace_project.OPERATION_RECORDING_VERSION` | | Repository manifest | `kilin.repository._MANIFEST_VERSION` | | Managed source manifest | `kilin.workspace.SOURCE_MANIFEST_VERSION` | -| [Semantic source organization](source_manifest.md) | `kilin.SOURCE_ORGANIZATION_FORMAT` (`kilin-source-manifest-v1`) | +| [Semantic source organization](source_manifest.md) | `kilin.SOURCE_ORGANIZATION_FORMAT` (`kilin-source-manifest-v2`) | | Pending plugin operation | `kilin.plugins._management.PENDING_OPERATION_FORMAT_VERSION` | | Comparison report | `kilin.system_testing.comparison.COMPARISON_FORMAT_VERSION` | | Reference receipt | `kilin.system_testing.reference.REFERENCE_RECEIPT_FORMAT_VERSION` | diff --git a/kilin/_source_access.py b/kilin/_source_access.py index 1d0b4356..0c99689b 100644 --- a/kilin/_source_access.py +++ b/kilin/_source_access.py @@ -26,6 +26,8 @@ from collections.abc import Collection from pathlib import Path +from kilin.workspace_resources import PROJECT_SOURCES_DIRECTORY + __all__ = [] @@ -42,7 +44,7 @@ def selected_source_file( project_root: pathlib.Path Workspace root, containing project state and managed sources. source_root: pathlib.Path - Saved profile's source directory, which must be in the workspace. + Canonical real ``sources`` directory inside the workspace. path: pathlib.Path Source-relative file path, as recorded by the source inventory. selected: Collection[pathlib.Path] @@ -57,9 +59,10 @@ def selected_source_file( Notes ----- No fallback searches the workspace root or an original import folder. - Paths inherited from legacy profiles outside the workspace are not - read by tools through this helper. The checks do not prevent an - uncooperative process from changing files after validation. + Alternate source roots are not read through this helper. Aliases of + ancestor directories do not change the identity of a real source root. + The checks do not prevent an uncooperative process from changing files + or links after validation. """ @@ -71,10 +74,16 @@ def selected_source_file( return None try: root = project_root.resolve(strict=True) + # Reject a linked or differently named source entry, not aliases of + # its ancestors (such as /var on macOS). + if ( + source_root.name != PROJECT_SOURCES_DIRECTORY + or source_root.is_symlink() or source_root.is_junction() + ): + return None source = source_root.resolve(strict=True) if ( - source_root.is_symlink() or source_root.is_junction() - or not source.is_relative_to(root) + source != root / PROJECT_SOURCES_DIRECTORY or not source.is_dir() ): return None diff --git a/kilin/_source_manifest.py b/kilin/_source_manifest.py index 852799a5..84776774 100644 --- a/kilin/_source_manifest.py +++ b/kilin/_source_manifest.py @@ -18,7 +18,7 @@ -------- >>> from kilin.source_manifest import SOURCE_ORGANIZATION_FORMAT >>> SOURCE_ORGANIZATION_FORMAT -'kilin-source-manifest-v1' +'kilin-source-manifest-v2' """ @@ -26,7 +26,7 @@ from collections import deque from dataclasses import asdict, dataclass -from pathlib import PurePosixPath, PureWindowsPath +from pathlib import PureWindowsPath import re from typing import Final import unicodedata @@ -38,7 +38,7 @@ __all__ = [] -SOURCE_ORGANIZATION_FORMAT: Final[str] = "kilin-source-manifest-v1" +SOURCE_ORGANIZATION_FORMAT: Final[str] = "kilin-source-manifest-v2" SOURCE_MANIFEST_FILE: Final[str] = "source_manifest.json" _MAX_BYTES: Final[int] = 16 * 1024 * 1024 _MAX_FILES: Final[int] = 10_000 @@ -49,14 +49,14 @@ @dataclass(frozen=True, slots=True) class SourceRoot: - """Bind accepted file identities to a project-relative or external root. + """Bind accepted file identities to the canonical project sources. Attributes ---------- base: str - ``project`` or ``absolute``. + ``project``; other source-root bases are unsupported. path: str - Canonical POSIX spelling; ``.`` denotes the project root. + ``sources``; identities remain relative when the workspace moves. """ @@ -178,7 +178,7 @@ class UnresolvedSource: path: str Path whose prior assignment is retained. reason: str - ``removed``, ``root_rebound`` or ``missing_assignment``. + ``removed`` or ``missing_assignment``. """ @@ -348,27 +348,13 @@ def root_binding(value: object) -> SourceRoot: Returns ------- SourceRoot - Validated portable binding. + Validated binding to the project's ``sources`` directory. """ raw = _exact(value, "base path", "source_root") - path = _text(raw["path"], "source_root.path") - if raw["base"] == "project": - if path != ".": - canonical_path(path) - elif raw["base"] == "absolute": - posix = PurePosixPath(path) - windows = PureWindowsPath(path) - if "\\" in path or not ( - posix.is_absolute() and posix.as_posix() == path - and ".." not in posix.parts - or windows.is_absolute() and windows.as_posix() == path - and ".." not in windows.parts - ): - raise ValueError("Noncanonical absolute source root.") - else: - raise ValueError("Invalid source_root.base.") - return SourceRoot(raw["base"], path) + if raw["base"] != "project" or raw["path"] != "sources": + raise ValueError("Source root must be the project sources directory.") + return SourceRoot("project", "sources") def _identity(value: object) -> OrganizationIdentity: @@ -622,7 +608,7 @@ def parse_manifest(value: object) -> SourceManifest: row = _exact(value, "path reason", "unresolved source") path = canonical_path(row["path"]) if row["reason"] not in ( - "removed", "root_rebound", "missing_assignment" + "removed", "missing_assignment" ): raise ValueError("Invalid unresolved reason.") unresolved.append(UnresolvedSource(path, row["reason"])) diff --git a/kilin/_source_ownership.py b/kilin/_source_ownership.py new file mode 100644 index 00000000..7f2639ed --- /dev/null +++ b/kilin/_source_ownership.py @@ -0,0 +1,213 @@ +"""Validate the separate import and mirror ownership metadata. + +A canonical workspace may have cumulative import provenance in +``sources.json``, single-folder mirror provenance in +``source_snapshot.json``, or neither. Both files together are a conflict. +Missing metadata is distinct from an invalid or unsafe existing entry. + +Key Features +------------ +- Read-only ownership classification without inferring an owner's identity. +- Strict mirror provenance using the existing repository content format. + +Module Structure +---------------- +- ``source_ownership`` checks metadata entries and mutual exclusion. +- ``read_mirror_manifest`` validates the complete single-folder inventory. + +Examples +-------- +>>> from pathlib import Path +>>> from kilin._source_ownership import source_ownership +>>> kind = source_ownership(Path("/path/to/workspace")) + +""" + +from __future__ import annotations + +import json +from pathlib import Path +import stat +from typing import Literal + +from kilin._source_manifest import canonical_path, check_aliases +from kilin.repository import _manifest_files + +__all__ = [] + + +def _metadata_exists(path: Path) -> bool: + """Distinguish a missing ownership file from an unsafe existing entry. + + Parameters + ---------- + path: pathlib.Path + Expected ordinary ownership JSON file. + + Returns + ------- + bool + Whether a regular file exists at the exact requested path. + + Raises + ------ + ValueError + If the entry is a symbolic link, junction, or nonregular file. + OSError + If the entry cannot be inspected. + + """ + try: + status = path.lstat() + except FileNotFoundError: + return False + if path.is_junction() or not stat.S_ISREG(status.st_mode): + raise ValueError( + f"Source ownership metadata must be a regular file: {path.name}" + ) + return True + + +def source_ownership(root: Path) -> Literal["imports", "mirror"] | None: + """Classify safe, mutually exclusive ownership metadata entries. + + Parameters + ---------- + root: pathlib.Path + Canonical workspace root. + + Returns + ------- + str | None + ``imports``, ``mirror``, or None for a manual/empty project. + + Raises + ------ + ValueError + If both ownership files exist or either entry is unsafe. + + Notes + ----- + This checks entries, not JSON contents. Import callers also validate + ``sources.json`` with the workspace reader; mirror callers use + ``read_mirror_manifest``. Neither reader changes the ownership mode. + + """ + imports = _metadata_exists(root / "sources.json") + mirror = _metadata_exists(root / "source_snapshot.json") + if imports and mirror: + raise ValueError( + "Conflicting source ownership: sources.json and " + "source_snapshot.json cannot both exist." + ) + if imports: + return "imports" + return "mirror" if mirror else None + + +def _unique_pairs(pairs: list[tuple[str, object]]) -> dict[str, object]: + """Reject duplicate JSON keys before ownership records are interpreted. + + Parameters + ---------- + pairs: list[tuple[str, object]] + One JSON object's ordered key/value pairs. + + Returns + ------- + dict[str, object] + Mapping preserving every distinct recorded key. + + """ + result: dict[str, object] = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate mirror provenance key: {key!r}.") + result[key] = value + return result + + +def read_mirror_manifest(root: Path) -> dict[str, object]: + """Read a complete mirror inventory without repairing missing metadata. + + Parameters + ---------- + root: pathlib.Path + Canonical workspace root containing only mirror ownership. + + Returns + ------- + dict[str, object] + Validated original identity and repository content inventory. + + Raises + ------ + ValueError + If mirror ownership is absent, conflicting, or malformed. + OSError + If an existing metadata file cannot be read. + + Notes + ----- + The saved original need not currently exist. Its absolute recorded + identity remains authoritative. Missing local copies do not invalidate + their recorded ownership, and an empty file inventory is valid. + + """ + if source_ownership(root) != "mirror": + raise ValueError( + "Synchronization requires saved mirror provenance in " + "source_snapshot.json." + ) + path = root / "source_snapshot.json" + try: + value = json.loads( + path.read_text(encoding="utf-8"), object_pairs_hook=_unique_pairs, + ) + except (UnicodeError, json.JSONDecodeError) as error: + raise ValueError("Invalid mirror provenance JSON.") from error + return validate_mirror_manifest(value) + + +def validate_mirror_manifest(value: object) -> dict[str, object]: + """Check mirror provenance from either disk or a fresh complete scan. + + Parameters + ---------- + value: object + Complete original identity and repository content inventory. + + Returns + ------- + dict[str, object] + Checked mapping, unchanged and without consulting the filesystem. + + Raises + ------ + ValueError + If fields, identities, paths, or content records are invalid. + + """ + if not isinstance(value, dict) or set(value) != { + "format_version", "files", "source_directory", + }: + raise ValueError("Invalid mirror provenance fields.") + source = value["source_directory"] + if (not isinstance(source, str) or not source + or not Path(source).is_absolute() + or str(Path(source)) != source + or ".." in Path(source).parts + or "\0" in source): + raise ValueError("Invalid original directory in mirror provenance.") + files = _manifest_files(value) + for name, record in value["files"].items(): + canonical_path(name) + if set(record) != {"size_bytes", "sha256"}: + raise ValueError("Invalid mirror file record fields.") + if name.split("/", 1)[0] == ".kilin_versions": + raise ValueError("Mirror provenance cannot own retained versions.") + if any(parent.as_posix() in files + for parent in Path(name).parents if parent != Path(".")): + raise ValueError("Mirror file paths overlap their directories.") + check_aliases(files) + return value diff --git a/kilin/_tool_sources.py b/kilin/_tool_sources.py index cb52c15f..48fd590e 100644 --- a/kilin/_tool_sources.py +++ b/kilin/_tool_sources.py @@ -114,7 +114,9 @@ def bind( self.validate() inspection, inventory = self._state if not inspection.binding_matches: - raise SourceViewConflict("Source root changed; rebind first.") + raise SourceViewConflict( + "Source root does not match the project sources directory." + ) # Resolve before caching: native Path equality must not authorize # differently spelled operands on Windows. view = resolve_source_view(inspection, inventory, policy, scope) diff --git a/kilin/gui/README.md b/kilin/gui/README.md index 2cfba845..8e179aaa 100644 --- a/kilin/gui/README.md +++ b/kilin/gui/README.md @@ -272,7 +272,8 @@ dependency is disconnected. disable). Disabling removes that rule from the declaration; restore it in Advanced settings or explicitly adopt the installed type's declarations. Advanced settings retain relationship types, rule definitions, explicit - JSON mappings, detector adoption and deliberate source-root rebinding. + JSON mappings and detector adoption. All project sources use `sources/`; + the editor does not support changing the source root. The core validates all declaration fields against the [source organization schema](../../docs/PROJECT_TYPE_SCHEMA.md#source-organization-declarations). - Review the ordered staged changes and choose **Preview / reconcile**. The diff --git a/kilin/gui/_source_organization.py b/kilin/gui/_source_organization.py index 13119c0f..5a67fbb8 100644 --- a/kilin/gui/_source_organization.py +++ b/kilin/gui/_source_organization.py @@ -35,6 +35,7 @@ from kilin._source_manifest import manifest_data from kilin.source_manifest import ( + _current_project, RelationEdit, ResolveSourceEdit, RoleEdit, @@ -47,7 +48,6 @@ initialize_source_manifest, inspect_source_manifest, preview_source_manifest, - read_source_manifest, refresh_source_manifest, ) from kilin.source_organization import parse_source_organization @@ -263,7 +263,7 @@ def _preview(project: QAProject, request: dict) -> SourceManifestPreview: raise ValueError("Expected source revision and SHA-256 digest.") edits = _edits(request.get("edits", [])) options = {key: request[key] for key in ( - "adopt_type_defaults", "role_mapping", "relation_mapping", "rebind", + "adopt_type_defaults", "role_mapping", "relation_mapping", "adopt_detector_versions", ) if key in request} if "organization" in request: @@ -340,7 +340,7 @@ def execute(self, engine: ChatEngine, request: object) -> None: "preview": { "revision", "sha256", "edits", "organization", "adopt_type_defaults", "role_mapping", - "relation_mapping", "rebind", + "relation_mapping", "adopt_detector_versions", }} if (not isinstance(operation, str) or operation not in allowed @@ -350,6 +350,7 @@ def execute(self, engine: ChatEngine, request: object) -> None: fields = json.loads(json.dumps(fields, allow_nan=False)) response["project"] = str(project.root) name += f".{operation}" + project = _current_project(project) command = {"command_id": uuid4().hex, "request": fields} if (operation == "apply" and self.pending is not None and fields.get("preview_id") == self.pending[0]): diff --git a/kilin/gui/engine.py b/kilin/gui/engine.py index 1d06ea7b..0949d35b 100644 --- a/kilin/gui/engine.py +++ b/kilin/gui/engine.py @@ -88,7 +88,6 @@ from kilin._trace_project import OPERATION_RECORDING_VERSION from kilin.model_settings import ( SourceCardGenerationSettings, - default_source_card_generation_settings, read_source_card_generation_settings, write_source_card_generation_settings, ) @@ -151,6 +150,7 @@ ) from kilin import RAGSession, prepare_sources_workspace from kilin.workspace import ( + _source_records, add_project_sources, default_workspace_path, find_source_changes, @@ -201,6 +201,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, @@ -1233,14 +1234,9 @@ def _saved_projects( continue if type_id is not None and saved_type_id != type_id: continue - if not source_text.strip(): - continue - source = Path(source_text).expanduser() - source_path = ( - source if source.is_absolute() else folder / source - ) - if not source_path.is_dir(): + if source_text != PROJECT_SOURCES_DIRECTORY: continue + validate_project_sources(folder) chat_records = tuple( (folder / "logs" / "traces").glob("conversation_*.json") ) @@ -1262,6 +1258,47 @@ def _saved_projects( reverse=True, ) + def _preflight_source_project( + self, directory: str | Path, message: str, *, + allow_mirror: bool = True, **event_fields: object, + ) -> QAProject | None: + """Validate current source authority before GUI side effects. + + Parameters + ---------- + directory: str | pathlib.Path + Workspace whose profile and ownership are checked by the core. + message: str + Context for a frontend-only error response. + allow_mirror: bool, optional + Permit mirrors for activation, inspection and local removal. + False requires cumulative-import or manual ownership. + **event_fields: object + Additional response fields, such as resume recovery state. + + Returns + ------- + QAProject | None + Current project, or None after reporting a rejected operation. + + Notes + ----- + A rejected preflight never opens a conversation, initializes GUI + settings, changes the live session, or appends a project trace. + Schema and filesystem policy remain entirely in the core readers. + + """ + try: + project = open_project(directory) + _source_records(project.root, allow_mirror=allow_mirror) + except Exception as error: + self._send( + "error", message=f"{message}: {error}", trace_path=None, + **event_fields, + ) + return None + return project + def resume_project( self, directory: str, conversation_id: str | None = None ) -> None: @@ -1279,7 +1316,12 @@ def resume_project( previous_released = False try: - project = open_project(directory) + project = self._preflight_source_project( + directory, "Could not resume the project", + resume_released=False, + ) + if project is None: + return # Once closing starts, the previous UI cannot assume its # session remains usable if a subsequent load fails. previous_released = True @@ -2270,6 +2312,7 @@ def _activate_project( """ + _source_records(project.root, allow_mirror=True) options: dict[str, object] = { "progress_callback": lambda progress: self._send( "progress", **asdict(progress) @@ -3076,6 +3119,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 = ( @@ -3381,6 +3434,12 @@ def check_sources(self, sources: list[str]) -> None: try: if self.session is None: raise RuntimeError("Open a project first.") + project = self._preflight_source_project( + self.session.project.root, "Could not check the sources", + allow_mirror=False, + ) + if project is None: + return if ( not sources or not isinstance(sources, list) @@ -3389,7 +3448,6 @@ def check_sources(self, sources: list[str]) -> None: ) ): raise ValueError("Choose source files or folders.") - project = self.session.project plan = preview_project_sources(project, sources) changes = {"added": [], "changed": [], "deleted": [], "edited": []} existing = [ @@ -3456,6 +3514,12 @@ def add_project_sources( try: if self.session is None or self.active_conversation is None: raise RuntimeError("Open a project first.") + project = self._preflight_source_project( + self.session.project.root, "Could not finish adding sources", + allow_mirror=False, + ) + if project is None: + return if ( not sources or not isinstance(sources, list) @@ -3464,7 +3528,7 @@ def add_project_sources( ) ): raise ValueError("Choose source files or folders.") - root = self.session.project.root + root = project.root conversation_id = self.active_conversation.conversation_id self.project_trace.emit( "gui.sources.add.requested", @@ -3488,7 +3552,7 @@ def add_project_sources( # A folder without a single file of the project's types cannot # be copied, and a source already in the project changes only # through the user's choices; the check told the user both. - plan = preview_project_sources(self.session.project, sources) + plan = preview_project_sources(project, sources) new = [ value for value, item in zip(plan["sources"], plan["add"]) @@ -3501,7 +3565,7 @@ def add_project_sources( options = { "trace": self.project_trace, "on_organization": self._organization_observer( - self.session.project, "add"), + project, "add"), } if selected_files is not None: options["selected_files"] = selected_files @@ -3510,7 +3574,7 @@ def add_project_sources( options = { "decisions": decisions, "on_organization": self._organization_observer( - self.session.project, "sync"), + project, "sync"), } if self.project_trace.enabled: options["trace"] = self.project_trace @@ -3568,7 +3632,12 @@ def remove_project_sources(self, paths: list[str]) -> None: try: if self.session is None or self.active_conversation is None: raise RuntimeError("Open a project first.") - root = self.session.project.root + project = self._preflight_source_project( + self.session.project.root, "Could not remove sources", + ) + if project is None: + return + root = project.root conversation_id = self.active_conversation.conversation_id self.project_trace.emit( "gui.sources.remove.requested", @@ -3579,9 +3648,9 @@ def remove_project_sources(self, paths: list[str]) -> None: "status", message="Removing sources and updating the index…" ) removed = remove_workspace_sources( - self.session.project, paths, trace=self.project_trace, + project, paths, trace=self.project_trace, on_organization=self._organization_observer( - self.session.project, "remove"), + project, "remove"), ) self.project_trace.emit( "gui.sources.remove.completed", component="gui_engine", @@ -3638,6 +3707,12 @@ def sync_sources(self, decisions: object = None) -> None: try: if self.session is None: raise RuntimeError("Open a project first.") + project = self._preflight_source_project( + self.session.project.root, "Could not update sources", + allow_mirror=False, + ) + if project is None: + return if decisions is not None and not ( isinstance(decisions, dict) and all( @@ -3646,7 +3721,6 @@ def sync_sources(self, decisions: object = None) -> None: ) ): raise ValueError("Source decisions must map paths to actions.") - project = self.session.project self._send( "status", message="Updating sources and the index…" ) @@ -3751,6 +3825,7 @@ def _refresh_source_indexes( Triggering refresh or recovery operation. """ + _source_records(project.root, allow_mirror=True) self._source_organization_commands.clear() self.session.refresh_sources( project, on_organization=self._organization_observer( @@ -3795,6 +3870,7 @@ def _reopen_project_conversation( """ + _source_records(project.root, allow_mirror=True) self._close_traces() store = ConversationStore(project.root) store.ensure() @@ -4396,8 +4472,13 @@ def preview_reference(self, turn_index: int, citation: int) -> None: return try: + source_root = validate_project_sources( + self.session.project.root, self.session.project.source, + ) + current = open_project(self.session.project.root) + _source_records(current.root, allow_mirror=True) report = { - "repository": str(self.session.project.source), + "repository": str(source_root), "selected_files": [evidence.path.as_posix()], } # Read as the index read it, so line numbers match. @@ -4857,6 +4938,11 @@ def save_source_card_settings(self, request: object) -> None: try: if self.session is None or getattr(self.session, "_closed", False): raise RuntimeError("Open a project before changing cards.") + current = self._preflight_source_project( + self.session.project.root, "Could not update source cards", + ) + if current is None: + return policy, models = self._validate_source_card_settings(request) session = self.session root = session.project.root @@ -4917,6 +5003,11 @@ def regenerate_source_cards(self) -> None: try: if self.session is None or getattr(self.session, "_closed", False): raise RuntimeError("Open a project before regenerating.") + current = self._preflight_source_project( + self.session.project.root, "Could not regenerate source cards", + ) + if current is None: + return self._send("status", message="Regenerating source cards…") self.session.regenerate_source_cards() self._send( @@ -4958,13 +5049,18 @@ def apply_indexing_settings(self, settings: object) -> None: try: if self.session is None: raise RuntimeError("Open a project before changing indexing.") + current = self._preflight_source_project( + self.session.project.root, "Could not apply indexing settings", + ) + if current is None: + return if ( not isinstance(settings, dict) or not settings or not set(settings) <= _INDEXING_SETTINGS ): raise ValueError("Invalid indexing settings.") - root = self.session.project.root + root = current.root profile_text = (root / PROFILE_FILE).read_text(encoding="utf-8") conversation_id = self.active_conversation.conversation_id self._send("status", message="Rebuilding the index…") diff --git a/kilin/gui/web/index.html b/kilin/gui/web/index.html index e62394bb..1a51aa59 100644 --- a/kilin/gui/web/index.html +++ b/kilin/gui/web/index.html @@ -466,7 +466,6 @@

Automatic discovery

-
diff --git a/kilin/gui/web/source_organization_panel.js b/kilin/gui/web/source_organization_panel.js index d5351a78..222b5b4d 100644 --- a/kilin/gui/web/source_organization_panel.js +++ b/kilin/gui/web/source_organization_panel.js @@ -77,7 +77,7 @@ class SourceOrganizationPanel { /** 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", "rebind"]; + "relation-mapping", "adopt-type", "adopt-detectors"]; } /** Read only the saved, canonical state supplied by the engine. */ @@ -369,7 +369,7 @@ class SourceOrganizationPanel { 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", "rebind"]) this.element(id).checked = false; + for (const id of ["adopt-type", "adopt-detectors"]) this.element(id).checked = false; this.savedSettings = this.settingsFingerprint(); } @@ -458,7 +458,6 @@ class SourceOrganizationPanel { 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("rebind").checked) fields.rebind = true; if (this.element("adopt-detectors").checked) fields.adopt_detector_versions = true; return fields; } @@ -744,7 +743,7 @@ class SourceOrganizationPanel { 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." : "Binding differs; preview explicit rebind in settings."}`; + 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})`])); @@ -873,7 +872,7 @@ class SourceOrganizationPanel { 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 changed; explicit rebind is required." + : !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, @@ -915,7 +914,7 @@ class SourceOrganizationPanel { 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 && !this.element("rebind").checked) + 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")) { diff --git a/kilin/project.py b/kilin/project.py index 79d0503a..e9366ee8 100644 --- a/kilin/project.py +++ b/kilin/project.py @@ -117,7 +117,6 @@ from __future__ import annotations -from collections.abc import Mapping from configparser import ConfigParser from contextlib import contextmanager from dataclasses import asdict, dataclass @@ -128,9 +127,12 @@ import re import shutil from tempfile import NamedTemporaryFile -from typing import Callable, Final, Iterator, TYPE_CHECKING, cast +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, @@ -160,6 +162,7 @@ ensure_project_folders, install_project_resources, plan_project_layout, + validate_project_sources, ) from kilin.query_formats import ( QUERY_FORMAT_CHOICES, @@ -168,7 +171,6 @@ ) from kilin.repository import ( build_repository_manifest, - compare_repository_manifests, normalize_extensions, scan_repository, ) @@ -299,7 +301,6 @@ def _default_profile_text( type_id: ProjectTypeId, - source: str, extensions: str, ) -> str: """Format the built-in profile with shared core defaults. @@ -308,8 +309,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. @@ -334,7 +333,7 @@ def _default_profile_text( ) return _DEFAULT_PROFILE.format( type_id=type_id, - source=source, + source=PROJECT_SOURCES_DIRECTORY, extensions=extensions, max_file_bytes=definition.max_file_bytes, allow_download=str(_PROFILE_ALLOW_DOWNLOAD).lower(), @@ -422,7 +421,7 @@ def default_project_profile(type_id: ProjectTypeId) -> ProjectProfile: 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) @@ -523,8 +522,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 @@ -567,8 +566,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 @@ -617,14 +616,15 @@ class ProjectProfile: Notes ----- Values normally come from the validated INI reader. Direct dataclass - construction is not validated. Model accessors return the configured MLX + construction validates the source layout name. Other settings 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 @@ -643,6 +643,19 @@ class ProjectProfile: max_new_tokens: int | None block_unrequested_cjk: bool = _PROFILE_BLOCK_UNREQUESTED_CJK + 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. @@ -918,7 +931,6 @@ def _creation_provenance( def _prepared_profile( type_id: ProjectTypeId, - source: str, settings: dict[str, object] | None, ) -> tuple[str, ProjectProfile, ProjectCreationProvenance]: """Validate and render the complete profile before filesystem writes. @@ -927,8 +939,6 @@ def _prepared_profile( ---------- 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``. @@ -940,7 +950,7 @@ def _prepared_profile( """ extensions = ", ".join(load_project_types()[type_id].extensions) - text = _default_profile_text(type_id, source, extensions) + text = _default_profile_text(type_id, extensions) parser = ConfigParser() parser.read_string(text) if settings: @@ -1007,7 +1017,7 @@ def _preparing_project( 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, PROJECT_SOURCES_DIRECTORY, settings + type_id, settings ) layout = plan_project_layout(type_id) with claim_workspace(root, allocate=allocate) as actual_root: @@ -1145,7 +1155,8 @@ def prepare_project_workspace( with _preparing_project( 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) @@ -1159,9 +1170,8 @@ def synchronize_project_workspace( 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. @@ -1183,43 +1193,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.") + 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, project.root.parent, None) + _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 ---------- @@ -1228,150 +1350,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) - # A failed copy must not leave a partial selected file behind. - with NamedTemporaryFile( - dir=target.parent, prefix=f".{target.name}.", - suffix=".tmp", delete=False, - ) as stream: - temporary = Path(stream.name) - try: - shutil.copy2(source_path, temporary) - temporary.replace(target) - finally: - temporary.unlink(missing_ok=True) - - _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: @@ -1398,8 +1573,9 @@ 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 + 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 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 @@ -1421,7 +1597,7 @@ def _read_project( Existing workspace containing a saved profile. require_registered_type: bool Require the current runtime's available project type. False is - reserved for historical recording inspection; it still validates + reserved for read-only project inspection; it still validates the identifier syntax, settings and filesystem layout, but must not initialize the current plugin catalogs. @@ -1450,12 +1626,7 @@ def _read_project( parser, require_registered_type=require_registered_type, ) provenance = _read_creation_provenance(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}") + source = validate_project_sources(root) for name in CORE_PROJECT_FOLDERS: folder = root / name @@ -1531,36 +1702,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. @@ -1584,27 +1725,31 @@ 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: @@ -1643,6 +1788,10 @@ def _read_profile( """ + 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 require_registered_type: _require_project_type(type_id_value, "project.type_id") @@ -1706,7 +1855,7 @@ def _read_profile( return ProjectProfile( type_id=type_id, - source=_required(parser, "project", "source"), + source=cast('Literal["sources"]', source), extensions=extensions, max_file_bytes=_positive_integer( parser, diff --git a/kilin/project_files.py b/kilin/project_files.py index 0dd673dc..cef3ea4d 100644 --- a/kilin/project_files.py +++ b/kilin/project_files.py @@ -50,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, @@ -535,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 175d81d3..38756c63 100644 --- a/kilin/project_layout.py +++ b/kilin/project_layout.py @@ -71,7 +71,6 @@ import shutil from typing import Final -from kilin._source_manifest import SOURCE_MANIFEST_FILE from kilin.project_type import project_type from kilin.tools import Tool, registered_tools from kilin.workspace_resources import ( @@ -89,6 +88,7 @@ "install_project_resources", "plan_project_layout", "source_scan_exclusions", + "validate_project_sources", ] CORE_PROJECT_FOLDERS: Final[tuple[str, ...]] = ( @@ -97,14 +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", - SOURCE_MANIFEST_FILE, - f".{SOURCE_MANIFEST_FILE}.lock", -) @dataclass(frozen=True, slots=True) @@ -393,41 +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; the exact - semantic manifest and sidecar when source contains the project; - 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: - return (".kilin_versions",) - if resolved_root.is_relative_to(resolved_source): - prefix = resolved_root.relative_to(resolved_source) - return tuple((prefix / name).as_posix() for name in ( - SOURCE_MANIFEST_FILE, f".{SOURCE_MANIFEST_FILE}.lock", - )) - return () + validate_project_sources(root, source) + return (".kilin_versions",) diff --git a/kilin/rag.py b/kilin/rag.py index 87035943..8359dc5a 100644 --- a/kilin/rag.py +++ b/kilin/rag.py @@ -153,7 +153,7 @@ from hashlib import sha256 import json from math import isfinite -from pathlib import Path, PureWindowsPath +from pathlib import Path import platform import re import sys @@ -229,7 +229,9 @@ effective_project_type, ) from kilin.model_settings import read_router_model, validate_model_id -from kilin.project_layout import source_scan_exclusions +from kilin.project_layout import ( + source_scan_exclusions, validate_project_sources, +) from kilin.question_suggestions import ( Suggestion, SuggestionWords, @@ -237,7 +239,7 @@ suggestion_words, welcome_prompts, ) -from kilin.workspace import include_explicit_imports +from kilin.workspace import _source_records, include_explicit_imports from kilin.project_type import ( HISTORY_POLICY_NONE, Intent, @@ -280,9 +282,6 @@ SourceViewConflict, capture_source_inventory, resolve_source_view, validate_source_view, ) -from kilin.retrievals.strategies.retrieval_semantic import ( - _validate_semantic_embeddings, -) from kilin.retrievals.source_coverage import ( asks_for_all_sources, group_operation_data, @@ -1275,6 +1274,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 ) @@ -3448,7 +3448,8 @@ def refresh_sources( 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. @@ -3468,6 +3469,11 @@ def refresh_sources( 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 organization = refresh_source_manifest( project, trace=self._project_diagnostics(), @@ -3547,6 +3553,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 ----- @@ -3558,6 +3566,9 @@ 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() ) @@ -3583,6 +3594,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 ----- @@ -3593,6 +3606,9 @@ def refresh_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) with self._project_embedding_diagnostics(): cards, vectors = self._prepare_source_cards( self.chunks, self.indexes, self.embedding_session, @@ -4846,10 +4862,10 @@ def _source_operation_state( 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 if binding.base == "project" - else Path(binding.path)).resolve() + 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.") diff --git a/kilin/source_manifest.py b/kilin/source_manifest.py index c50ddf4d..dca814e5 100644 --- a/kilin/source_manifest.py +++ b/kilin/source_manifest.py @@ -11,7 +11,7 @@ Key Features ------------ -- Immutable snapshots, accepted defaults, and explicit root rebinding. +- 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. @@ -66,7 +66,9 @@ ConversationFileLock, ConversationLockedError, ) from kilin.project import QAProject, _read_project -from kilin.project_layout import source_scan_exclusions +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 @@ -120,7 +122,7 @@ class SourceManifestInspection: snapshot: SourceManifestSnapshot Saved state and exact-content identity. source_root: SourceRoot - Current profile's resolved source-root binding. + Validated canonical source-root binding. selected: tuple[str, ...] Authoritative scanner and managed-import selection. active_files: tuple[SourceRole, ...] @@ -250,9 +252,6 @@ class SourceManifestPreview: Explicitly adopt the current installed type's declarations. role_mapping, relation_mapping: tuple[tuple[str, str], ...] Explicit resolutions for previously used vocabulary identifiers. - rebind: bool - Explicitly accept the current configured root, marking old paths - unresolved before materializing new assignments. adopt_detector_versions: bool Explicitly accept installed detector implementations. discovery: SourceDiscovery @@ -268,7 +267,6 @@ class SourceManifestPreview: adopt_type_defaults: bool role_mapping: tuple[tuple[str, str], ...] relation_mapping: tuple[tuple[str, str], ...] - rebind: bool adopt_detector_versions: bool = False discovery: SourceDiscovery = SourceDiscovery() @@ -309,8 +307,8 @@ class SourceLifecycleResult: Attributes ---------- inspection: SourceManifestInspection | None - Current resolved organization, when safe to inspect. A changed root - can be inspected but cannot be automatically rebound. + 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 @@ -452,11 +450,15 @@ def _current_project(project: QAProject) -> QAProject: Current saved project profile and resolved directories. """ - return _read_project(project.root, require_registered_type=False) + 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 to the resolved configured source directory. + """Bind file identities after validating the canonical source directory. Parameters ---------- @@ -466,13 +468,11 @@ def _binding(project: QAProject) -> SourceRoot: Returns ------- SourceRoot - Relative identity when contained in the workspace; otherwise absolute. + Project-relative identity that survives moving the whole workspace. """ - root, source = project.root.resolve(), project.source.resolve() - if source.is_relative_to(root): - return SourceRoot("project", source.relative_to(root).as_posix()) - return SourceRoot("absolute", source.as_posix()) + validate_project_sources(project.root, project.source) + return SourceRoot("project", "sources") def _selected(project: QAProject) -> tuple[str, ...]: @@ -953,7 +953,7 @@ def _change_settings( def _propose( manifest: SourceManifest, selected: tuple[str, ...], binding: SourceRoot, - edits: tuple[SourceManifestEdit, ...], *, rebind: bool, + edits: tuple[SourceManifestEdit, ...], ) -> SourceManifest: """Reconcile selection and apply explicit edits as one proposed state. @@ -967,8 +967,6 @@ def _propose( Current configured root identity. edits: tuple[SourceManifestEdit, ...] Ordered explicit edits; validation of graph cycles occurs at the end. - rebind: bool - Permit a changed root only with deliberate invalidation of old roles. Returns ------- @@ -983,11 +981,9 @@ def _propose( unresolved = {r.path: r for r in manifest.unresolved} available = set(selected) if binding != manifest.source_root: - if not rebind: - raise SourceManifestConflict( - "Source root changed; preview an explicit rebind first." - ) - unresolved = {p: UnresolvedSource(p, "root_rebound") for p in files} + 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 @@ -1053,7 +1049,7 @@ def _propose( else: raise ValueError("Unknown source-manifest edit record.") return replace( - manifest, source_root=binding, files=tuple(files.values()), + manifest, files=tuple(files.values()), relations=tuple(links.values()), suppressed_automatic=tuple(suppressed), unresolved=tuple(unresolved.values()), @@ -1064,7 +1060,7 @@ 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], ...], rebind: bool, + relation_mapping: tuple[tuple[str, str], ...], adopt_detector_versions: bool = False, before: SourceManifestInspection | None = None, ) -> SourceManifestPreview: @@ -1084,8 +1080,6 @@ def _preview( Explicit resolutions for used roles. relation_mapping: tuple[tuple[str, str], ...] Explicit resolutions for used relations. - rebind: bool - Whether to explicitly accept a changed source root. adopt_detector_versions: bool, optional Explicitly accept installed detector identities. before: SourceManifestInspection | None, optional @@ -1098,9 +1092,9 @@ def _preview( """ if any(type(flag) is not bool for flag in ( - rebind, adopt_type_defaults, adopt_detector_versions, + adopt_type_defaults, adopt_detector_versions, )): - raise ValueError("Rebind and adoption flags must be booleans.") + raise ValueError("Adoption flags must be booleans.") if organization is not None and ( adopt_type_defaults or type(organization) is not SourceOrganization ): @@ -1137,8 +1131,7 @@ def _preview( accepted, detector_versions=detector_versions( accepted.declaration), )) - after = _propose(manifest, before.selected, before.source_root, edits, - rebind=rebind) + 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, @@ -1163,7 +1156,7 @@ def _preview( _serialize(after) return SourceManifestPreview( current.root, before, after, edits, organization, adopt_type_defaults, - role_mapping, relation_mapping, rebind, adopt_detector_versions, + role_mapping, relation_mapping, adopt_detector_versions, discovery, ) @@ -1174,7 +1167,7 @@ def preview_source_manifest( adopt_type_defaults: bool = False, role_mapping: Mapping[str, str] | None = None, relation_mapping: Mapping[str, str] | None = None, - rebind: bool = False, adopt_detector_versions: bool = False, + adopt_detector_versions: bool = False, ) -> SourceManifestPreview: """Preview an atomic batch, reconciliation or explicit settings change. @@ -1194,8 +1187,6 @@ def preview_source_manifest( relation_mapping: Mapping[str, str] | None, optional Explicit old-to-new relation IDs. Include an identity mapping to explicitly accept a changed behavior. - rebind: bool, optional - Permit a different configured root, retaining old records inactive. adopt_detector_versions: bool, optional Accept installed detector versions without changing the saved type declarations. Automatic edge changes are included in the preview. @@ -1208,7 +1199,7 @@ def preview_source_manifest( """ return _preview( _current_project(project), tuple(edits), organization=organization, - adopt_type_defaults=adopt_type_defaults, rebind=rebind, + adopt_type_defaults=adopt_type_defaults, adopt_detector_versions=adopt_detector_versions, role_mapping=_mapping(role_mapping), relation_mapping=_mapping(relation_mapping), @@ -1268,7 +1259,7 @@ def apply_source_manifest( current, preview.edits, organization=preview.organization, adopt_type_defaults=preview.adopt_type_defaults, role_mapping=preview.role_mapping, - relation_mapping=preview.relation_mapping, rebind=preview.rebind, + relation_mapping=preview.relation_mapping, adopt_detector_versions=preview.adopt_detector_versions, before=inspected, ) @@ -1333,8 +1324,8 @@ def refresh_source_manifest( ------- SourceLifecycleResult One batch outcome, or an actionable error when reconciliation is - unsafe. Missing metadata requires explicit initialization; changed - roots require explicit rebinding. No installed defaults are adopted. + unsafe. Missing metadata requires explicit initialization; source + roots outside ``sources`` are rejected. No defaults are adopted. Notes ----- @@ -1354,7 +1345,7 @@ def refresh_source_manifest( inspected = _inspect(current) preview = _preview( current, (), organization=None, adopt_type_defaults=False, - role_mapping=(), relation_mapping=(), rebind=False, + role_mapping=(), relation_mapping=(), before=inspected, ) # Source operations do not share the semantic writer lease. diff --git a/kilin/source_views.py b/kilin/source_views.py index ada16324..ba6b2589 100644 --- a/kilin/source_views.py +++ b/kilin/source_views.py @@ -590,7 +590,9 @@ def _operation( """ if not inspection.binding_matches: - raise SourceViewConflict("Source root changed; rebind the manifest.") + 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: @@ -762,8 +764,7 @@ def resolve_source_view( state = states[member] if not state.indexed and policy.purpose != "raw": unavailable.append(UnavailableMember(member, "unindexed")) - if (state.sha256 is None - or operation.source_root.base != "project"): + if state.sha256 is None: unavailable.append(UnavailableMember( member, "raw_unavailable" )) diff --git a/kilin/system_testing/_semantic_replay.py b/kilin/system_testing/_semantic_replay.py index 4c798eea..fa777690 100644 --- a/kilin/system_testing/_semantic_replay.py +++ b/kilin/system_testing/_semantic_replay.py @@ -53,7 +53,7 @@ "apply": {"preview_id"}, "preview": {"revision", "sha256", "edits", "organization", "adopt_type_defaults", "role_mapping", "relation_mapping", - "rebind", "adopt_detector_versions"}, + "adopt_detector_versions"}, } @@ -230,7 +230,7 @@ def _validate_transition(before: SourceManifest, after: SourceManifest, from kilin.gui._source_organization import _edits from kilin.source_organization import parse_source_organization - for flag in ("adopt_type_defaults", "adopt_detector_versions", "rebind"): + 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) @@ -268,8 +268,7 @@ def _validate_transition(before: SourceManifest, after: SourceManifest, elif detectors: candidate = replace(candidate, organization=new) candidate = _propose(candidate, tuple(sorted(selected)), - before.source_root, _edits(request.get("edits", [])), - rebind=request.get("rebind", False)) + 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 diff --git a/kilin/system_testing/validation.py b/kilin/system_testing/validation.py index 635edcf8..5975e51f 100644 --- a/kilin/system_testing/validation.py +++ b/kilin/system_testing/validation.py @@ -469,12 +469,12 @@ def finish(self, recording: Recording) -> None: origins = {} for record in records: source, name = record["original"], record["name"] - kind = record.get("kind") + 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.get("files", []): + for relative in record["files"]: path = destination if kind == "file" else ( f"{destination}/{relative}") observed[path] = (source, kind, relative) diff --git a/kilin/workspace.py b/kilin/workspace.py index 23a4ebe7..bc2bdcc3 100644 --- a/kilin/workspace.py +++ b/kilin/workspace.py @@ -3,6 +3,9 @@ ``prepare_sources_workspace`` exclusively creates a new project, copies selected local inputs into ``sources``, and records origins in ``sources.json``, with each copy's size and modification time at import. +The current ownership format requires explicit source kinds and inventory +containers. Missing copy stamps remain unknown after partial failures; +unsupported record generations are rejected without conversion. An explicit destination must be nonexistent or empty. Default names are allocated without reusing occupied folders, even for identical sources. ``add_project_sources`` deliberately imports into a saved project, preserving @@ -139,8 +142,11 @@ TypeAlias, TypedDict, cast, ) +import unicodedata from kilin._project_creation import check_available, destination_path +from kilin._source_ownership import read_mirror_manifest, source_ownership +from kilin._source_manifest import canonical_path, check_aliases from kilin.project import ( _require_project_type, _read_project, ProjectTypeId, @@ -148,6 +154,7 @@ _preparing_project, open_project, ) +from kilin.project_layout import validate_project_sources from kilin.repository import scan_repository from kilin.source_manifest import ( SourceLifecycleResult, _reconcile_source_operation, @@ -181,7 +188,7 @@ "SOURCE_MANIFEST_VERSION", ] -SOURCE_MANIFEST_VERSION: Final[int] = 1 +SOURCE_MANIFEST_VERSION: Final[int] = 2 # Workspace folders whose files may be copied into the sources: what KíLín # wrote (kilin.tools._shared.outputs) and the report templates. @@ -280,12 +287,12 @@ class _SourceRecord(TypedDict): Recorded path of the external source selected for import. name: str Unique name allocated inside the managed ``sources/`` directory. - files: list[str], optional - Imported files relative to the source directory; absent in old records. - stamps: dict[str, _CopyStamp], optional - Copy-time file metadata keyed by imported relative filename. - kind: "file" | "folder", optional - Source type; absent in older manifests. + files: list[str] + Explicit inventory of imported files relative to the original source. + stamps: dict[str, _CopyStamp] + Known copy-time metadata; may be empty or partial after a failure. + kind: "file" | "folder" + Recorded source type, independent of the current original or copy. versions: list[_StoredVersion], optional Versions retained from earlier imports, with paths and digests. @@ -293,9 +300,9 @@ class _SourceRecord(TypedDict): original: str name: str - files: NotRequired[list[str]] - stamps: NotRequired[dict[str, _CopyStamp]] - kind: NotRequired[Literal["file", "folder"]] + files: list[str] + stamps: dict[str, _CopyStamp] + kind: Literal["file", "folder"] versions: NotRequired[list[_StoredVersion]] @@ -531,13 +538,11 @@ def preview_project_sources( """ root = _managed_root(project) - if root is None: - raise ValueError("Only managed sources/ snapshots can be imported.") if not isinstance(source_paths, (list, tuple)): raise ValueError("Choose source files or folders.") - records = _read_records(root / "sources.json") - imported = {item["original"]: item["name"] for item in records} - used = set(imported.values()) + records = _source_records(root) + imported = {item["original"]: item for item in records} + used = {item["name"] for item in records} shown = { SELECTION_REASON_FILE_TYPE_NOT_SELECTED, SELECTION_REASON_FILE_TOO_LARGE, @@ -547,6 +552,7 @@ def preview_project_sources( "add": [], "sources": [], "files": [], "skipped": [] } seen: set[Path] = set() + paths = [] for value in source_paths: if not isinstance(value, (str, Path)) or not str(value).strip(): raise ValueError("Choose source files or folders.") @@ -565,6 +571,10 @@ def preview_project_sources( for folder in _COPYABLE_WORKSPACE_FOLDERS ): raise ValueError("Do not add the workspace as its own source.") + kind = "file" if source.is_file() else "folder" + record = imported.get(str(source)) + if record is not None and record["kind"] != kind: + raise ValueError(f"Original source kind changed: {source}") if source.is_file(): size = source.stat().st_size if not _eligible_file_size(source, project.profile.max_file_bytes): @@ -576,8 +586,8 @@ def preview_project_sources( ), }) continue + files = [source.name] selected = 1 - kind = "file" else: excluded = ( (root.relative_to(source).as_posix(),) @@ -599,25 +609,32 @@ def preview_project_sources( } for row in report["entries"] if ( row["kind"] == "file" and row["reason_code"] in shown )) - selected = len(report["selected_files"]) + files = report["selected_files"] + selected = len(files) if not selected: plan["skipped"].append(str(value)) continue - kind = "folder" - name = imported.get(str(source)) - if name is None: + if record is None: name = _unique_name( source, used, root / PROJECT_SOURCES_DIRECTORY ) state = "renamed" if name != source.name else "new" used.add(name) else: + name = record["name"] state = "existing" + for relative in files: + canonical_path(relative) + paths.extend(name if kind == "file" else f"{name}/{relative}" + for relative in files) plan["add"].append({ "name": name, "kind": kind, "files": selected, "state": state, }) plan["sources"].append(str(value)) + _validate_import_paths( + root / PROJECT_SOURCES_DIRECTORY, records, paths, reserved=used, + ) return plan @@ -698,6 +715,9 @@ def _prepare_sources_workspace( ) if not allocate and workspace.exists() and not workspace.is_dir(): raise NotADirectoryError(f"Choose a workspace folder: {workspace}") + if existing is not None: + # Reject invalid ownership before even borrowed trace failure events. + _source_records(workspace) chosen: list[Path] = [] for value in source_paths: source = Path(value).expanduser() @@ -790,6 +810,47 @@ def complete(prepared: QAProject) -> None: for source in chosen ): raise ValueError("Do not add the workspace as its own source.") + managed = (workspace / PROJECT_SOURCES_DIRECTORY).resolve( + strict=True + ) + if project.source != managed: + raise ValueError( + "project.source must use the managed sources/ folder." + ) + manifest_path = workspace / "sources.json" + records = _source_records(workspace) + by_original = {item["original"]: item for item in records} + used = {item["name"] for item in records} + imports = [] + paths = [] + for source in chosen: + original = str(source) + kind = "file" if source.is_file() else "folder" + record = by_original.get(original) + if record is not None and record["kind"] != kind: + raise ValueError( + f"Original source kind changed: {source}" + ) + if record is None: + record = _SourceRecord( + original=original, + name=_unique_name(source, used, source_root), + kind=kind, files=[], stamps={}, + ) + selection = ( + selections[original] if selections is not None else None + ) + files = _selected_source_files( + source, project, workspace, selection + ) + paths.extend( + record["name"] if kind == "file" + else f"{record['name']}/{relative}" + for relative in files + ) + used.add(record["name"]) + imports.append((source, record, files, selection)) + _validate_import_paths(source_root, records, paths, reserved=used) if isinstance(trace, TraceConfig): if trace.enabled and journal is not None: directory = project.logs / "traces" @@ -824,48 +885,18 @@ def complete(prepared: QAProject) -> None: }, status="started", ) - managed = (workspace / PROJECT_SOURCES_DIRECTORY).resolve( - strict=True - ) - if project.source != managed: - raise ValueError( - "project.source must use the managed sources/ folder." - ) - manifest_path = workspace / "sources.json" - records = _read_records(manifest_path) reconciliation = ( _reconcile_source_operation(project, active_trace, on_organization) if existing is not None else nullcontext() ) with reconciliation: - used = {item["name"] for item in records} - for source in chosen: - original = str(source) - record = next( - (item for item in records - if item["original"] == original), - None, - ) - if record is None: - name = _unique_name(source, used, source_root) - record = _SourceRecord( - original=original, name=name, - kind="file" if source.is_file() else "folder", - ) - else: - record.setdefault( - "kind", "file" if source.is_file() else "folder" - ) + for source, record, files, selection in imports: destination = source_root / record["name"] - selection = ( - selections[original] if selections is not None - else None - ) copied, preserved = [], [] try: copied, preserved = _copy_source( - source, destination, project, workspace, selection, + source, destination, files, kind=record["kind"], replace_existing=replace_existing, on_create=(journal.note if journal is not None else None), @@ -888,7 +919,6 @@ def complete(prepared: QAProject) -> None: journal.note(manifest_path) _record_import(record, records, destination, copied, preserved, manifest_path) - used.add(record["name"]) active_trace.emit( "workspace.source.copied", component="workspace", @@ -953,10 +983,10 @@ def _record_import( Managed import provenance path. """ - if record.get("kind") == "file": + if record["kind"] == "file": record["files"] = list(copied) + list(preserved) else: - inventory = set(record.get("files", [])) | set(copied) + inventory = set(record["files"]) | set(copied) record["files"] = sorted( relative for relative in inventory if _is_regular_snapshot(destination, relative) @@ -968,7 +998,7 @@ def _record_import( # stale stamps as if they described the newly imported bytes. unchanged = set(record["files"]) - set(copied) record["stamps"] = {name: stamp for name, stamp in - record.get("stamps", {}).items() + record["stamps"].items() if name in unchanged} if record not in records: records.append(record) @@ -1042,25 +1072,18 @@ def _eligible_file_size(source: Path, max_file_bytes: int) -> bool: return 0 < source.stat().st_size <= max_file_bytes -def _copy_source( +def _selected_source_files( source: Path, - destination: Path, project: QAProject, workspace: Path, selected_files: Sequence[str] | None, - *, - replace_existing: bool = False, - on_create: Callable[[Path], None] | None = None, - progress: tuple[list[str], list[str]] | None = None, -) -> tuple[list[str], list[str]]: - """Copy eligible files while protecting existing snapshots. +) -> list[str]: + """Resolve eligible source files before diagnostics or copying begin. Parameters ---------- source: pathlib.Path Original local source file or directory. - destination: pathlib.Path - Managed destination path for the selected source or file. project: QAProject Resolved project whose profile provides extension and size-selection rules. @@ -1070,40 +1093,29 @@ def _copy_source( selected_files: Sequence[str] | None Optional selected filenames relative to a directory or the original filename for a direct source file. None uses the scan selection. - replace_existing: bool, optional - Replace existing regular snapshot files when True. Defaults to False. - on_create: Callable[[pathlib.Path], None] | None, optional - Record newly created snapshot paths for first-creation rollback. - - progress: tuple[list[str], list[str]] | None, optional - Caller-owned copied and preserved lists, recording actual successes - even if a later file copy fails. Returns ------- - tuple[list[str], list[str]] - Original-relative filenames copied and preserved, respectively. + list[str] + Canonical selected filenames relative to the original source. Raises ------ ValueError If a source file violates size rules, a directory scan is - incomplete, or an explicit selection is empty or outside the eligible - scan set. + incomplete, a selected name is unsafe, or an explicit selection is + empty or outside the eligible scan set. OSError - If scanning or copying fails. + If scanning fails. Notes ----- The directory path applies scan_repository rules and excludes a nested workspace. Explicitly selected files bypass extension and protected-name selection filters but retain size and containment safeguards. - Files omitted from this copy operation are left in place, as are files - selected again without an explicit replacement request. """ - copied, preserved = progress if progress is not None else ([], []) profile = project.profile if source.is_file(): if selected_files is not None and list(selected_files) != [ @@ -1114,14 +1126,7 @@ def _copy_source( raise ValueError( f"File is empty or exceeds the size limit: {source}" ) - if _copy_file( - source, destination, replace_existing=replace_existing, - on_create=on_create, - ): - copied.append(source.name) - else: - preserved.append(source.name) - return copied, preserved + return [canonical_path(source.name)] excludes: tuple[str, ...] = () if workspace.is_relative_to(source): @@ -1142,20 +1147,67 @@ def _copy_source( selected = [path for path in selected if path in requested] if not selected: raise ValueError(f"No selected files in source folder: {source}") - if on_create is not None: - on_create(destination) - destination.mkdir(parents=True, exist_ok=True) - for relative in selected: - path = str(relative) + return [canonical_path(relative) for relative in selected] + + +def _copy_source( + source: Path, + destination: Path, + selected_files: Sequence[str], + *, + kind: Literal["file", "folder"], + replace_existing: bool = False, + on_create: Callable[[Path], None] | None = None, + progress: tuple[list[str], list[str]] | None = None, +) -> tuple[list[str], list[str]]: + """Copy a validated selection while protecting existing snapshots. + + Parameters + ---------- + source: pathlib.Path + Original local source file or directory. + destination: pathlib.Path + Managed destination path for the selected source or file. + selected_files: Sequence[str] + Preflighted filenames relative to the original source. + kind: {"file", "folder"} + Explicit source kind validated before the batch begins. + replace_existing: bool, optional + Replace existing regular snapshot files when True. Defaults to False. + on_create: Callable[[pathlib.Path], None] | None, optional + Record newly created snapshot paths for first-creation rollback. + progress: tuple[list[str], list[str]] | None, optional + Caller-owned copied and preserved lists, recording actual successes + even if a later file copy fails. + + Returns + ------- + tuple[list[str], list[str]] + Original-relative filenames copied and preserved, respectively. + + Notes + ----- + Omitted files stay in place. Reselected copies are preserved unless the + caller requests replacement. Filesystem failures can leave a completed + subset whose provenance the caller must retain. + + """ + + copied, preserved = progress if progress is not None else ([], []) + if kind == "folder": + if on_create is not None: + on_create(destination) + destination.mkdir(parents=True, exist_ok=True) + for relative in selected_files: if _copy_file( - source / path, - destination / path, + source if kind == "file" else source / relative, + destination if kind == "file" else destination / relative, replace_existing=replace_existing, on_create=on_create, ): - copied.append(path) + copied.append(relative) else: - preserved.append(path) + preserved.append(relative) return copied, preserved @@ -1302,25 +1354,26 @@ def _stamp_copies( Notes ----- - Files kept from an earlier import keep their stamps. Files without one, - from manifests written before stamps existed, are stamped as they are - now. Stamps of files no longer tracked are dropped. + Preserved files keep their known stamps. An absent stamp represents an + unknown baseline after a failed operation, so only an actual copy may + establish it. Stamps of files no longer tracked are dropped. """ - stamps = record.get("stamps", {}) + stamps = record["stamps"] renewed: dict[str, _CopyStamp] = {} - for relative in record.get("files", []): - path = destination if destination.is_file() else destination / relative - if relative in copied or relative not in stamps: + for relative in record["files"]: + path = (destination if record["kind"] == "file" + else destination / relative) + if relative in copied: renewed[relative] = _copy_stamp(path) - else: + elif relative in stamps: renewed[relative] = stamps[relative] record["stamps"] = renewed def _safe_relative(value: str) -> bool: - """Check that an untrusted manifest path is a normalized POSIX path. + """Apply the shared canonical path rules to an ownership field. Parameters ---------- @@ -1330,19 +1383,196 @@ def _safe_relative(value: str) -> bool: Returns ------- bool - Whether the path has safe components and no drive or traversal. + Whether the path is canonical without ambiguous or unsafe components. """ - if not value or "\\" in value or "\0" in value: + try: + canonical_path(value) + except ValueError: return False - path = PurePosixPath(value) - return ( - not path.is_absolute() - and not PureWindowsPath(value).drive - and all(part not in ("", ".", "..") for part in value.split("/")) - and path.as_posix() == value - ) + return True + + +def _record_paths( + records: Sequence[_SourceRecord], *, removed: set[str] | None = None, +) -> list[str]: + """Collect effective managed paths, including reserved source names. + + Parameters + ---------- + records: Sequence[_SourceRecord] + Validated current source ownership records. + removed: set[str] | None, optional + Active copies explicitly scheduled for deletion. Defaults to None. + + Returns + ------- + list[str] + Source-relative names, active copies, and retained version paths. + + """ + + paths = [_VERSION_DIRECTORY] + for record in records: + name = record["name"] + paths.append(name) + if record["kind"] == "folder": + paths.extend(f"{name}/{relative}" for relative in record["files"] + if f"{name}/{relative}" not in (removed or ())) + paths.extend(item["path"] for item in record.get("versions", [])) + return paths + + +def _validate_import_paths( + root: Path, + records: Sequence[_SourceRecord], + paths: Sequence[str], + *, + reserved: set[str] | None = None, + removed: set[str] | None = None, +) -> None: + """Reject unsafe destinations before copying or acquiring batch state. + + Parameters + ---------- + root: pathlib.Path + Managed sources directory. + records: Sequence[_SourceRecord] + Current ownership, including copies that are temporarily absent. + paths: Sequence[str] + Source-relative file destinations selected for the pending batch. + reserved: set[str] | None, optional + Additional names allocated by this batch or preview. Defaults to None. + removed: set[str] | None, optional + Tracked regular copies explicitly deleted by this batch before its + imports. Defaults to None. Untracked files cannot authorize traversal. + + Notes + ----- + Canonical and alias checks use the same identity rules as semantic source + manifests. Existing sibling spellings are checked without following links + or scanning unrelated subtrees. This preflight does not reserve paths + against concurrent filesystem changes. + + """ + + for relative in paths: + canonical_path(relative) + removed = removed or set() + check_aliases((*_record_paths(records, removed=removed), + *(reserved or ()), *paths)) + files = set(paths) + for record in records: + active = (record["name"] if record["kind"] == "file" + else f"{record['name']}/{relative}" + for relative in record["files"]) + files.update(path for path in active if path not in removed) + files.update(item["path"] for item in record.get("versions", [])) + if any(parent.as_posix() in files + for relative in files + for parent in PurePosixPath(relative).parents): + raise ValueError("Conflicting workspace source file destinations.") + children: dict[Path, set[str]] = {} + for relative in paths: + parent = root + for component in relative.split("/"): + children.setdefault(parent, set()).add(component) + parent /= component + for parent, selected in children.items(): + if parent.is_symlink() or parent.is_junction(): + raise ValueError(f"Do not copy through a symbolic link: {parent}") + if not parent.exists(): + continue + if not parent.is_dir(): + if parent.relative_to(root).as_posix() in removed: + continue + raise ValueError(f"Snapshot parent is not a directory: {parent}") + keys = {unicodedata.normalize("NFC", name).casefold() + for name in selected} + # Ignore unrelated existing aliases; inspect each directory once. + matching = [entry.name for entry in parent.iterdir() + if unicodedata.normalize("NFC", entry.name).casefold() + in keys and entry.relative_to(root).as_posix() + not in removed] + check_aliases((*selected, *matching)) + for relative in paths: + target = root / relative + if target.is_symlink() or target.is_junction(): + raise ValueError(f"Do not copy through a symbolic link: {target}") + if target.exists() and not target.is_file(): + raise ValueError( + f"Snapshot destination is not a regular file: {target}" + ) + + +def _source_records( + root: Path, *, allow_mirror: bool = False, +) -> list[_SourceRecord]: + """Validate ownership before an operation observes or changes sources. + + Parameters + ---------- + root: pathlib.Path + Current canonical workspace root. + allow_mirror: bool, optional + Permit valid mirror ownership for selection, inspection, or explicit + local removal. Defaults to False for cumulative import operations. + + Returns + ------- + list[_SourceRecord] + Validated cumulative imports, or an empty list for a manual project + or an allowed mirror. No ownership is inferred from local files. + + Raises + ------ + ValueError + If metadata is malformed, unsafe, conflicting, or an import operation + is requested for a mirror. + OSError + If recorded ownership cannot be read. + + """ + + kind = source_ownership(root) + if kind == "mirror": + read_mirror_manifest(root) + if not allow_mirror: + raise ValueError( + "Cumulative imports cannot modify a mirror workspace; " + "use synchronize_project_workspace for mirror updates." + ) + return [] + return _read_records(root / "sources.json") + + +def _unique_source_fields( + pairs: list[tuple[str, object]], +) -> dict[str, object]: + """Reject duplicate fields before interpreting source ownership JSON. + + Parameters + ---------- + pairs: list[tuple[str, object]] + JSON object fields in their original order. + + Returns + ------- + dict[str, object] + Object containing every distinct field. + + Raises + ------ + ValueError + If an object repeats a field with an ambiguous recorded value. + + """ + + result = dict(pairs) + if len(result) != len(pairs): + raise ValueError("Duplicate workspace source fields.") + return result def _read_records(path: Path) -> list[_SourceRecord]: @@ -1367,21 +1597,25 @@ def _read_records(path: Path) -> list[_SourceRecord]: Notes ----- - Missing ``files`` and ``stamps`` are accepted for older manifest - records. Present inventories must contain unique, normalized relative - paths, and every stamp must belong to a tracked file. + Each record requires its original, destination name, kind, file inventory, + and stamp mapping. Inventories may be empty and stamps may be partial, + but fields are never inferred from the current filesystem. Optional + retained versions remain valid without an active source copy. """ if not path.is_file(): return [] - payload = json.loads(path.read_text(encoding="utf-8")) + payload = json.loads( + path.read_text(encoding="utf-8"), + object_pairs_hook=_unique_source_fields, + ) if (not isinstance(payload, dict) or type(payload.get("version")) is not int or payload["version"] != SOURCE_MANIFEST_VERSION): raise ValueError("Invalid workspace source list format version.") records = payload.get("sources") - if not isinstance(records, list): + if set(payload) != {"version", "sources"} or not isinstance(records, list): raise ValueError("Invalid workspace source list.") seen_names: set[str] = set() seen_originals: set[str] = set() @@ -1389,45 +1623,48 @@ def _read_records(path: Path) -> list[_SourceRecord]: for item in records: if not isinstance(item, dict): raise ValueError("Invalid workspace source entry.") + if not set(item) <= { + "original", "name", "kind", "files", "stamps", "versions" + }: + raise ValueError("Invalid workspace source entry fields.") original, name = item.get("original"), item.get("name") if not isinstance(original, str) or not isinstance(name, str): raise ValueError("Invalid workspace source entry.") if ( - name in {"", ".", ".."} - or Path(name).name != name - or "\\" in name - or PureWindowsPath(name).drive + not _safe_relative(name) + or len(PurePosixPath(name).parts) != 1 + or name == _VERSION_DIRECTORY ): raise ValueError("Invalid workspace source name.") - if not original.strip(): + if not original.strip() or "\0" in original: raise ValueError("Invalid workspace source entry.") if original in seen_originals or name in seen_names: raise ValueError("Duplicate or conflicting workspace sources.") kind = item.get("kind") - if kind is not None and kind not in ("file", "folder"): + if kind not in ("file", "folder"): raise ValueError("Invalid workspace source kind.") seen_originals.add(original) seen_names.add(name) - files = item.get("files", []) + files = item.get("files") if not isinstance(files, list): raise ValueError("Invalid workspace source files inventory.") seen_files: set[str] = set() for relative in files: - if not isinstance(relative, str) or not relative: - raise ValueError("Invalid workspace source files inventory.") - normalized = PurePosixPath(relative) if ( - normalized.is_absolute() - or not normalized.parts - or ".." in normalized.parts - or PureWindowsPath(relative).drive - or "\\" in relative - or normalized.as_posix() != relative + not isinstance(relative, str) + or not _safe_relative(relative) or relative in seen_files + or (kind == "file" and relative != Path(original).name) ): raise ValueError("Invalid workspace source files inventory.") seen_files.add(relative) - stamps = item.get("stamps", {}) + if any( + parent.as_posix() in seen_files + for relative in seen_files + for parent in PurePosixPath(relative).parents + ): + raise ValueError("Conflicting workspace source files inventory.") + stamps = item.get("stamps") if not isinstance(stamps, dict) or not set(stamps) <= seen_files: raise ValueError("Invalid workspace source copy stamps.") for stamp in stamps.values(): @@ -1451,7 +1688,11 @@ def _read_records(path: Path) -> list[_SourceRecord]: relative, stored, digest = ( version["file"], version["path"], version["sha256"] ) - if not isinstance(relative, str) or not _safe_relative(relative): + if ( + not isinstance(relative, str) + or not _safe_relative(relative) + or (kind == "file" and relative != Path(original).name) + ): raise ValueError("Invalid workspace source version file.") prefix = f"{_VERSION_DIRECTORY}/{name}/" if ( @@ -1467,6 +1708,16 @@ def _read_records(path: Path) -> list[_SourceRecord]: ): raise ValueError("Invalid workspace source version digest.") seen_versions.add(stored) + if any( + parent.as_posix() in seen_versions + for stored in seen_versions + for parent in PurePosixPath(stored).parents + ): + raise ValueError("Conflicting workspace source version paths.") + paths = _record_paths(records) + if not all(_safe_relative(relative) for relative in paths): + raise ValueError("Invalid effective workspace source path.") + check_aliases(paths) return cast("list[_SourceRecord]", records) @@ -1478,8 +1729,8 @@ def _write_records(path: Path, records: list[_SourceRecord]) -> None: path: pathlib.Path Source-origin JSON manifest path. records: list[_SourceRecord] - Source-origin records with original and name strings and, when written - by preparation, a list of copied files. + Complete current source ownership records, including required file + and stamp containers and optional retained versions. Notes ----- @@ -1554,14 +1805,8 @@ def remove_workspace_sources( if current.source != project.source: raise ValueError("Project source changed; reopen before removal.") project = current - root = project.root.resolve(strict=True) + root = _managed_root(project) managed = root / PROJECT_SOURCES_DIRECTORY - if ( - managed.is_symlink() - or not managed.is_dir() - or project.source.resolve(strict=True) != managed - ): - raise ValueError("Only managed sources/ snapshots can be removed.") if not isinstance(paths, (list, tuple)) or not paths: raise ValueError("Choose source files or folders to delete.") @@ -1602,7 +1847,7 @@ def remove_workspace_sources( raise ValueError("Cannot remove a folder and its child together.") manifest = root / "sources.json" - records = _read_records(manifest) + records = _source_records(root, allow_mirror=True) with _reconcile_source_operation(project, trace, on_organization): with _finish_source_batch( lambda: _prune_removed_records(manifest, managed, records) @@ -1663,18 +1908,18 @@ def _prune_removed_records( destination = managed / record["name"] if destination.is_symlink(): record["files"] = [] - elif destination.is_file(): + elif record["kind"] == "file" and destination.is_file(): record["files"] = [ Path(record["original"]).name if Path(record["original"]).name in - record.get("files", []) else "" + record["files"] else "" ] record["files"] = [ value for value in record["files"] if value ] - elif destination.is_dir(): + elif record["kind"] == "folder" and destination.is_dir(): record["files"] = [ - item for item in record.get("files", []) + item for item in record["files"] if _is_regular_snapshot(destination, item) ] else: @@ -1686,12 +1931,11 @@ def _prune_removed_records( ] if not record["files"] and not record.get("versions"): continue - if "stamps" in record: - record["stamps"] = { - relative: stamp - for relative, stamp in record["stamps"].items() - if relative in record["files"] - } + record["stamps"] = { + relative: stamp + for relative, stamp in record["stamps"].items() + if relative in record["files"] + } retained.append(record) _write_records(manifest, retained) @@ -1722,9 +1966,7 @@ def find_source_changes(project: QAProject) -> SourceChanges: root = _managed_root(project) changes = _empty_changes() - if root is None: - return changes - records = _read_records(root / "sources.json") + records = _source_records(root, allow_mirror=True) for _record, group, _source, copy, _relative in _differences( project, root, records ): @@ -1757,17 +1999,15 @@ def list_source_versions(project: QAProject) -> list[SourceVersion]: """ root = _managed_root(project) - if root is None: - return [] versions: list[SourceVersion] = [] managed = root / PROJECT_SOURCES_DIRECTORY - for record in _read_records(root / "sources.json"): + for record in _source_records(root, allow_mirror=True): copy = f"{PROJECT_SOURCES_DIRECTORY}/{record['name']}" for item in record.get("versions", []): if not _is_regular_snapshot(managed, item["path"]): continue versions.append(SourceVersion( - source=copy if record.get("kind") == "file" + source=copy if record["kind"] == "file" else f"{copy}/{item['file']}", version=f"{PROJECT_SOURCES_DIRECTORY}/{item['path']}", sha256=item["sha256"], @@ -1842,12 +2082,8 @@ def sync_project_sources( project = current root = _managed_root(project) done = _empty_changes() - if root is None: - if decisions: - raise ValueError("Only managed sources can be synchronized.") - return done manifest = root / "sources.json" - records = _read_records(manifest) + records = _source_records(root) pending = _differences(project, root, records) changes_by_path = { copy.relative_to(root).as_posix(): ( @@ -1892,13 +2128,22 @@ def sync_project_sources( raise ValueError( f"New source conflicts with a workspace copy: {path}" ) + paths = [] + archives: dict[str, _StoredVersion] = {} + removed: set[str] = set() for record, group, source, copy, relative in pending: path = copy.relative_to(root).as_posix() action = ( decisions.get(path, "keep") if decisions is not None else - "replace" if group == "changed" and relative in - record.get("files", []) else "keep" + { + "added": "keep", "changed": ( + "replace" if relative in record["files"] else "keep" + ), + "deleted": "delete", "edited": "keep", + }[group] ) + if action == "delete": + removed.add(copy.relative_to(project.source).as_posix()) if action in ("import", "replace", "keep_both") and ( _regular_original(source) and not _eligible_file_size( @@ -1908,6 +2153,14 @@ def sync_project_sources( raise ValueError( f"Source is empty or exceeds the file-size limit: {source}" ) + if action in ("import", "replace", "keep_both"): + canonical_path(relative) + paths.append(copy.relative_to(project.source).as_posix()) + if action == "keep_both" and not _same_contents(source, copy): + version = _plan_source_version(root, record, relative, copy) + archives[path] = version + paths.append(version["path"]) + _validate_import_paths(project.source, records, paths, removed=removed) active_trace = trace if trace is not None else NullTraceLogger() batch_id = active_trace.new_id("source_sync") active_trace.emit( @@ -1928,7 +2181,7 @@ def persist() -> None: decisions.get(path, "keep") if decisions is not None else { "added": "keep", "changed": ( - "replace" if relative in record.get("files", []) + "replace" if relative in record["files"] else "keep" ), "deleted": "delete", "edited": "keep", @@ -1971,9 +2224,9 @@ def persist() -> None: _copy_file(source, copy) modified = True record["files"] = sorted( - set(record.get("files", [])) | {relative} + set(record["files"]) | {relative} ) - stamps = record.setdefault("stamps", {}) + stamps = record["stamps"] stamps.pop(relative, None) stamps[relative] = _copy_stamp(copy) done["added"].append(path) @@ -1990,8 +2243,13 @@ def persist() -> None: ) identical = _same_contents(source, copy) if action == "keep_both" and not identical: + if path not in archives: + raise ValueError( + "The snapshot changed during synchronization: " + f"{path}" + ) retained = _archive_source_version( - root, record, relative, copy + root, archives[path], copy ) record.setdefault("versions", []).append(retained) modified = True @@ -2001,9 +2259,9 @@ def persist() -> None: _copy_file(source, copy, replace_existing=True) modified = True record["files"] = sorted( - set(record.get("files", [])) | {relative} + set(record["files"]) | {relative} ) - stamps = record.setdefault("stamps", {}) + stamps = record["stamps"] stamps.pop(relative, None) stamps[relative] = _copy_stamp(copy) done["changed"].append(path) @@ -2030,7 +2288,7 @@ def persist() -> None: "batch_id": batch_id, "action": action, "path": path, "source": str(source), "original": record["original"], - "relative": relative, "kind": record.get("kind"), + "relative": relative, "kind": record["kind"], }, ) for paths in done.values(): @@ -2068,9 +2326,9 @@ def _untrack_file(record: _SourceRecord, relative: str) -> None: """ record["files"] = [ - item for item in record.get("files", []) if item != relative + item for item in record["files"] if item != relative ] - record.get("stamps", {}).pop(relative, None) + record["stamps"].pop(relative, None) def _regular_original(source: Path) -> bool: @@ -2094,10 +2352,10 @@ def _regular_original(source: Path) -> bool: return False -def _archive_source_version( +def _plan_source_version( root: Path, record: _SourceRecord, relative: str, copy: Path ) -> _StoredVersion: - """Store one historical snapshot at a unique, indexable source path. + """Plan one historical snapshot without creating version storage. Parameters ---------- @@ -2113,7 +2371,7 @@ def _archive_source_version( Returns ------- _StoredVersion - Source-relative archived version path and its content digest. + Prospective source-relative version path and current content digest. Notes ----- @@ -2129,6 +2387,7 @@ def _archive_source_version( count = sum( item["file"] == relative for item in record.get("versions", []) ) + occupied = {item["path"] for item in record.get("versions", [])} while True: count += 1 name = ( @@ -2140,13 +2399,47 @@ def _archive_source_version( original.parent / name ).as_posix() destination = root / PROJECT_SOURCES_DIRECTORY / archived - if not destination.exists() and not destination.is_symlink(): + if (archived not in occupied and not destination.exists() + and not destination.is_symlink()): break - _copy_file(copy, destination) - if _hash_file(destination) != identity: + return _StoredVersion(file=relative, path=archived, sha256=identity) + + +def _archive_source_version( + root: Path, version: _StoredVersion, copy: Path +) -> _StoredVersion: + """Create a preflighted historical snapshot and verify its bytes. + + Parameters + ---------- + root: pathlib.Path + Managed project root. + version: _StoredVersion + Validated destination and content digest captured during preflight. + copy: pathlib.Path + Existing workspace snapshot to preserve. + + Returns + ------- + _StoredVersion + Verified independent version for the source ownership record. + + Raises + ------ + OSError + If copying fails or the snapshot changed after planning its version. + + """ + + destination = root / PROJECT_SOURCES_DIRECTORY / version["path"] + if not _copy_file(copy, destination): + raise FileExistsError( + f"Version destination became occupied: {destination}" + ) + if _hash_file(destination) != version["sha256"]: destination.unlink() raise OSError("The snapshot changed while creating its version.") - return _StoredVersion(file=relative, path=archived, sha256=identity) + return version def _hash_file(path: Path) -> str: @@ -2200,31 +2493,34 @@ def _same_contents(source: Path, copy: Path) -> bool: return _hash_file(source) == _hash_file(copy) -def _managed_root(project: QAProject) -> Path | None: - """Return the project root when its sources are a managed folder. +def _managed_root(project: QAProject) -> Path: + """Return the project root after validating its canonical source tree. Parameters ---------- project: QAProject - Opened project. + Opened project, including a provisional project during creation. Returns ------- - pathlib.Path | None - Resolved project root, or None for external or linked sources. + pathlib.Path + Resolved project root with an ordinary real ``sources`` directory. + + Raises + ------ + TypeError + If the input is not a project. + ValueError + If sources are noncanonical or linked. + OSError + If the project or sources directory is absent or not a directory. """ if not isinstance(project, QAProject): raise TypeError("Expected an opened QAProject.") root = project.root.resolve(strict=True) - managed = root / PROJECT_SOURCES_DIRECTORY - if ( - managed.is_symlink() - or not managed.is_dir() - or project.source.resolve(strict=True) != managed - ): - return None + validate_project_sources(root, project.source) return root @@ -2299,28 +2595,23 @@ def _differences( destination = managed / record["name"] if original.is_symlink() or destination.is_symlink(): continue - kind = record.get("kind") - if kind is None: - kind = ( - "file" if destination.is_file() and - record.get("files") == [original.name] else "folder" - ) + kind = record["kind"] if kind == "file": pairs = [ (original, destination, original.name) - for relative in record.get("files", []) + for relative in record["files"] if relative == original.name and destination.is_file() ] elif destination.is_dir(): pairs = [ (original / relative, destination / relative, relative) - for relative in record.get("files", []) + for relative in record["files"] if _is_regular_snapshot(destination, relative) ] else: pairs = [] for source, copy, relative in pairs: - stamp = record.get("stamps", {}).get(relative) + stamp = record["stamps"].get(relative) if stamp is None or _linked_source_parent(original, source): continue try: @@ -2347,7 +2638,7 @@ def _differences( # not turn inaccessible source folders into an empty selection. if kind == "file": if ( - not record.get("files") and _regular_original(original) + not record["files"] and _regular_original(original) and _eligible_file_size( original, project.profile.max_file_bytes ) @@ -2375,7 +2666,7 @@ def _differences( raise OSError( f"Could not completely scan source folder: {original}" ) - tracked = set(record.get("files", [])) + tracked = set(record["files"]) for relative in report["selected_files"]: if relative not in tracked: group = ( @@ -2425,14 +2716,11 @@ def include_explicit_imports( """ - root = project.root.resolve(strict=True) + root = _managed_root(project) managed = root / PROJECT_SOURCES_DIRECTORY - if ( - project.source.resolve(strict=True) != managed - or not (root / "sources.json").is_file() - ): + records = _source_records(root, allow_mirror=True) + if not (root / "sources.json").exists(): return report - records = _read_records(root / "sources.json") rows = report.get("entries") if not isinstance(rows, list): raise ValueError("Invalid project source scan report.") @@ -2452,7 +2740,10 @@ def include_explicit_imports( for record in records: name = record["name"] snapshot = managed / name - if not snapshot.is_symlink() and snapshot.is_file(): + if ( + record["kind"] == "file" + and not snapshot.is_symlink() and snapshot.is_file() + ): size = snapshot.stat().st_size if 0 < size <= project.profile.max_file_bytes: indexed[name] = { diff --git a/tests/kilin/_rag_support.py b/tests/kilin/_rag_support.py index 3e2495c1..c6d88795 100644 --- a/tests/kilin/_rag_support.py +++ b/tests/kilin/_rag_support.py @@ -11,12 +11,13 @@ from __future__ import annotations from contextlib import contextmanager -from dataclasses import asdict +from dataclasses import asdict, replace from pathlib import Path from types import SimpleNamespace from unittest.mock import DEFAULT, MagicMock, patch, sentinel from kilin import rag from kilin.answering import RouteDecision +from kilin.project import QAProject, default_project_profile from kilin.project_type import ( HISTORY_POLICY_RECENT, Intent, @@ -52,6 +53,42 @@ def _profile() -> SimpleNamespace: ) +def _source_project(root: Path) -> QAProject: + """Build a canonical project for tests that access real source files. + + Parameters + ---------- + root: Path + Temporary project directory whose subdirectories the caller creates. + + Returns + ------- + QAProject + Current project and profile types with the isolated RAG settings. + + """ + + settings = vars(_profile()).copy() + embedding_model = settings.pop("embedding_model") + chat_model = settings.pop("chat_model") + profile = replace( + default_project_profile("code"), + **settings, + embedding_mlx=embedding_model("mlx"), + embedding_torch=embedding_model("torch"), + chat_mlx=chat_model("mlx"), + chat_torch=chat_model("torch"), + ) + directory = root.resolve() + return QAProject( + root=directory, + source=directory / "sources", + indexes=directory / "indexes", + logs=directory / "logs", + profile=profile, + ) + + def _session(root: Path | None = None) -> rag.RAGSession: """Create a coordinator without initializing or downloading models.""" directory = root or Path("/unused-kilin-test-project") diff --git a/tests/kilin/gui/test__source_organization_frontend.py b/tests/kilin/gui/test__source_organization_frontend.py index c2725768..668a6b87 100644 --- a/tests/kilin/gui/test__source_organization_frontend.py +++ b/tests/kilin/gui/test__source_organization_frontend.py @@ -37,7 +37,7 @@ dropTargetsChanged() {}, element(id) { if (!fields.has(id)) fields.set(id, {value: "", checked: false, - type: ["adopt-type", "adopt-detectors", "rebind"].includes(id) + type: ["adopt-type", "adopt-detectors"].includes(id) ? "checkbox" : "text"}); return fields.get(id); }, @@ -158,11 +158,11 @@ def test_exact_scope_and_declaration_options(self): panel.element("roles").value += "\nnew_role"; panel.element("default-role").value = "new_role"; panel.element("role-mapping").value = '{"primary":"new_role"}'; -panel.element("rebind").checked = true; const changed = panel.previewFields(); assert.equal(changed.organization.default_role, "new_role"); assert.deepEqual(changed.role_mapping, {primary: "new_role"}); -assert.equal(changed.rebind, true); +assert.equal(Object.hasOwn(changed, "rebind"), false); +assert.equal(panel.settingsFields().includes("rebind"), false); assert.deepEqual(panel.inspection, accepted); panel.element("adopt-type").checked = true; assert.equal(panel.previewFields().organization, undefined); diff --git a/tests/kilin/gui/test_engine__references.py b/tests/kilin/gui/test_engine__references.py index f13f6b18..95a04aae 100644 --- a/tests/kilin/gui/test_engine__references.py +++ b/tests/kilin/gui/test_engine__references.py @@ -10,17 +10,20 @@ from __future__ import annotations +from configparser import ConfigParser from pathlib import Path import json from tempfile import TemporaryDirectory from types import SimpleNamespace import unittest +from unittest.mock import patch from kilin.gui.engine import ( ChatEngine, _reference_context, _turn_payloads ) from kilin.answer_timeline import AnswerTimeline, AnswerTimelineStep from kilin.rag import ConversationTurn, Evidence +from kilin.project import initialize_project class TestReferencePreview(unittest.TestCase): @@ -71,7 +74,9 @@ def test_pdf_preview_finds_the_matching_page(self) -> None: def test_engine_opens_only_saved_evidence(self) -> None: """Reject unknown citations and fall back to saved evidence.""" with TemporaryDirectory() as temporary: - source = Path(temporary).resolve() + root = Path(temporary).resolve() + project = initialize_project(root / "project", "code") + source = project.source file = source / "notes.md" file.write_text( "before\nmemory\ncapacity\nafter\n", encoding="utf-8" @@ -87,7 +92,7 @@ def test_engine_opens_only_saved_evidence(self) -> None: events: list[dict[str, object]] = [] engine = ChatEngine(source, events.append) engine.session = SimpleNamespace( - project=SimpleNamespace(source=source), + project=project, turns=[SimpleNamespace(evidence=(evidence,))], _reads_as_code=lambda: False, ) @@ -95,6 +100,7 @@ def test_engine_opens_only_saved_evidence(self) -> None: engine.preview_reference(0, 1) self.assertEqual(events[-1]["event"], "reference_preview") self.assertEqual(events[-1]["path"], "notes.md") + self.assertEqual(events[-1]["lines"][0]["text"], "before") engine.preview_reference(0, 2) self.assertEqual(events[-1]["event"], "reference_error") @@ -105,6 +111,38 @@ def test_engine_opens_only_saved_evidence(self) -> None: all(line["highlighted"] for line in events[-1]["lines"]) ) + def test_invalid_source_root_uses_saved_passage_without_reading(self): + with TemporaryDirectory() as temporary: + root = Path(temporary).resolve() + project = initialize_project(root / "project", "code") + outside = root / "outside" + outside.mkdir() + (outside / "notes.md").write_text("unrelated", encoding="utf-8") + evidence = Evidence(1, Path("notes.md"), 1, 1, None, "saved") + events = [] + engine = ChatEngine(root, events.append) + engine.session = SimpleNamespace( + project=SimpleNamespace(root=project.root, source=outside), + turns=[SimpleNamespace(evidence=(evidence,))], + _reads_as_code=lambda: False, + ) + for changed_profile in (False, True): + with self.subTest(changed_profile=changed_profile): + if changed_profile: + engine.session.project = project + profile = project.root / "profile.ini" + config = ConfigParser() + config.read(profile, encoding="utf-8") + config.set("project", "source", str(outside)) + with profile.open("w", encoding="utf-8") as stream: + config.write(stream) + with patch("kilin.gui.engine.read_repository_files", + side_effect=AssertionError("Unexpected read")): + engine.preview_reference(0, 1) + self.assertEqual(events[-1]["event"], "reference_preview") + self.assertIn("saved passage", events[-1]["note"]) + self.assertEqual(events[-1]["lines"][0]["text"], "saved") + class TestAnswerTimelines(unittest.TestCase): """Receive recorded core timelines without GUI-side persistence.""" diff --git a/tests/kilin/gui/test_engine__saved_projects.py b/tests/kilin/gui/test_engine__saved_projects.py index fa8ffaad..4d111ebe 100644 --- a/tests/kilin/gui/test_engine__saved_projects.py +++ b/tests/kilin/gui/test_engine__saved_projects.py @@ -127,6 +127,49 @@ def test_saved_project_checks_custom_workspace(self) -> None: engine.find_saved_project("literature", str(custom)) self.assertIsNone(events[-1]["project"]) + def test_retired_source_layouts_are_not_advertised_as_projects(self): + with TemporaryDirectory() as temporary: + root = Path(temporary).resolve() + outside = root / "outside" + outside.mkdir() + sandbox = root / "sandbox" + for index, value in enumerate(( + ".", "documents", "repository", "./sources", "sources/", + str(outside), + )): + folder = sandbox / str(index) + (folder / "sources").mkdir(parents=True) + (folder / "documents").mkdir() + (folder / "repository").mkdir() + (folder / "profile.ini").write_text( + f"[project]\ntype_id = code\nsource = {value}\n", + encoding="utf-8", + ) + linked = sandbox / "linked" + linked.mkdir() + with self.subTest(linked_sources=True): + try: + (linked / "sources").symlink_to( + outside, target_is_directory=True, + ) + except (OSError, NotImplementedError): + self.skipTest("Symbolic links are unavailable") + (linked / "profile.ini").write_text( + "[project]\ntype_id = code\nsource = sources\n", + encoding="utf-8", + ) + before = {p: p.read_bytes() for p in root.rglob("*") + if p.is_file()} + events = [] + engine = ChatEngine(sandbox, events.append) + engine.list_saved_projects("") + self.assertEqual(events[-1], {"event": "projects", "projects": []}) + engine.find_saved_project("code", "") + self.assertIsNone(events[-1]["project"]) + self.assertEqual(before, {p: p.read_bytes() + for p in root.rglob("*") + if p.is_file()}) + def test_empty_sandbox_starts_without_workspace(self) -> None: """An empty sandbox does not show an empty workspace sidebar.""" diff --git a/tests/kilin/gui/test_engine__source_organization.py b/tests/kilin/gui/test_engine__source_organization.py index 06e5b2ae..0cdc7b3b 100644 --- a/tests/kilin/gui/test_engine__source_organization.py +++ b/tests/kilin/gui/test_engine__source_organization.py @@ -185,6 +185,20 @@ def test_wrong_project_busy_and_invalid_payload_do_not_write(self): self.assertEqual(self.manifest.read_bytes(), before) self.session.refresh_source_metadata.assert_not_called() + def test_rebind_request_is_rejected_without_changes(self): + before = {p: p.read_bytes() for p in self.project.root.rglob("*") + if p.is_file()} + for value in (False, True): + with self.subTest(rebind=value): + result = self.preview(rebind=value) + self.assertIn("error", result) + self.assertNotIn("preview_id", result) + self.assertEqual(before, {p: p.read_bytes() + for p in self.project.root.rglob("*") + if p.is_file()}) + self.session.refresh_source_metadata.assert_not_called() + self.session.refresh_sources.assert_not_called() + def test_initialize_is_explicit_and_never_repairs_corruption(self): self.manifest.unlink() self.assertIn("error", self.command("inspect")) diff --git a/tests/kilin/gui/test_engine__source_ownership.py b/tests/kilin/gui/test_engine__source_ownership.py new file mode 100644 index 00000000..f632adce --- /dev/null +++ b/tests/kilin/gui/test_engine__source_ownership.py @@ -0,0 +1,376 @@ +"""Reject unsafe source ownership before GUI persistence and activation. + +Use real profiles and ownership files with model-free engine sessions. +Whole-tree comparisons include conversations, trace sidecars and GUI settings, +so a rejected operation cannot appear safe merely because sources survived. + +""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from __future__ import annotations + +import json +from pathlib import Path +from tempfile import TemporaryDirectory +from types import SimpleNamespace +import unittest +from unittest.mock import Mock, patch + +from kilin.conversation_format import conversation_state +from kilin.conversations import ConversationStore +from kilin.rag import Evidence +from kilin.gui import engine as gui_engine +from kilin.project import initialize_project +from kilin.repository import _MANIFEST_VERSION +from kilin.source_manifest import read_source_manifest +from kilin.workspace import SOURCE_MANIFEST_VERSION + + +class TestEngineSourceOwnership(unittest.TestCase): + """Exercise real ownership checks at GUI persistence boundaries.""" + + INVALID_STATES = ( + "corrupt_import", "unsupported_import", "invalid_import_record", + "corrupt_mirror", "conflict", "linked_import", "linked_mirror", + ) + + def setUp(self): + """Create a current project and independent original source.""" + + temporary = TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.project = initialize_project(self.root / "project", "code") + (self.project.source / "note.py").write_text("current source\n") + self.original = self.root / "original" + self.original.mkdir() + self.new_source = self.original / "new.py" + self.new_source.write_text("new original\n") + self.imports = self.project.root / "sources.json" + self.mirror = self.project.root / "source_snapshot.json" + + @staticmethod + def inventory(root): + """Capture files, folders and link targets without following links.""" + + entries = {} + for path in root.rglob("*"): + name = path.relative_to(root).as_posix() + if path.is_symlink(): + entries[name] = ("link", str(path.readlink())) + elif path.is_dir(): + entries[name] = ("directory",) + else: + entries[name] = ("file", path.read_bytes()) + return entries + + def ownership(self, state): + """Install one explicit valid or invalid ownership fixture.""" + + self.imports.unlink(missing_ok=True) + self.mirror.unlink(missing_ok=True) + imports = {"version": SOURCE_MANIFEST_VERSION, "sources": []} + mirror = { + "format_version": _MANIFEST_VERSION, "files": {}, + "source_directory": str(self.original), + } + if state in {"imports", "conflict"}: + self.imports.write_text(json.dumps(imports)) + if state in {"mirror", "conflict"}: + self.mirror.write_text(json.dumps(mirror)) + if state == "corrupt_import": + self.imports.write_text("{broken") + if state == "unsupported_import": + self.imports.write_text(json.dumps({ + **imports, "version": SOURCE_MANIFEST_VERSION + 100, + })) + if state == "invalid_import_record": + self.imports.write_text(json.dumps({ + **imports, "sources": [{"name": "unowned"}], + })) + if state == "corrupt_mirror": + self.mirror.write_text("{broken") + if state in {"linked_import", "linked_mirror"}: + target = self.root / "linked-owner.json" + target.write_text(json.dumps(imports if state == "linked_import" + else mirror)) + path = self.imports if state == "linked_import" else self.mirror + try: + path.symlink_to(target) + except (OSError, NotImplementedError): + self.skipTest("Creating file symlinks is unavailable") + + def engine(self): + """Build a model-free engine with captured protocol events.""" + + events = [] + engine = gui_engine.ChatEngine(self.root, events.append) + self.addCleanup(engine.close) + return engine, events + + def active_engine(self): + """Attach an existing session and spies for all writable services.""" + + engine, events = self.engine() + session = SimpleNamespace( + project=self.project, _closed=False, close=Mock(), + refresh_sources=Mock(), refresh_source_cards=Mock(), + regenerate_source_cards=Mock(), turns=[], + ) + engine.session = session + engine.active_conversation = SimpleNamespace( + conversation_id="conversation_existing", + ) + engine.conversation_store = Mock() + engine.project_trace = Mock(enabled=True) + engine.conversation_trace = Mock(enabled=True) + return engine, events, session + + def test_resume_rejects_before_profiles_conversations_or_traces_change( + self, + ): + for state in self.INVALID_STATES: + for tracing in (False, True): + with self.subTest(state=state, tracing=tracing): + self.ownership(state) + engine, events = self.engine() + engine.trace_enabled = tracing + before = self.inventory(self.project.root) + with patch.object(engine, "_open_conversation_store", + wraps=engine._open_conversation_store) \ + as store, patch.object( + engine, "_start_conversation_trace", + wraps=engine._start_conversation_trace, + ) as trace, patch( + "kilin.gui.engine.save_project_settings", + wraps=gui_engine.save_project_settings, + ) as settings, patch( + "kilin.gui.engine.RAGSession", + side_effect=AssertionError("Unexpected RAG"), + ) as rag: + engine.resume_project(str(self.project.root)) + store.assert_not_called() + trace.assert_not_called() + settings.assert_not_called() + rag.assert_not_called() + self.assertEqual(self.inventory(self.project.root), before) + self.assertIsNone(engine.session) + self.assertIsNone(engine.active_conversation) + self.assertEqual(events[-1]["event"], "error") + self.assertFalse(events[-1]["resume_released"]) + + def test_failed_resume_preserves_the_existing_live_session(self): + engine, events, session = self.active_engine() + active = engine.active_conversation + store = engine.conversation_store + self.ownership("conflict") + before = self.inventory(self.project.root) + engine.resume_project(str(self.project.root)) + self.assertIs(engine.session, session) + self.assertIs(engine.active_conversation, active) + self.assertIs(engine.conversation_store, store) + session.close.assert_not_called() + engine.project_trace.assert_not_called() + self.assertEqual(engine.project_trace.mock_calls, []) + self.assertEqual(engine.conversation_trace.mock_calls, []) + self.assertEqual(self.inventory(self.project.root), before) + self.assertFalse(events[-1]["resume_released"]) + + def test_private_activation_and_reopen_validate_before_side_effects(self): + self.ownership("corrupt_import") + engine, _events, session = self.active_engine() + before = self.inventory(self.project.root) + with patch("kilin.gui.engine.save_project_settings") as settings, \ + patch("kilin.gui.engine.RAGSession") as rag, \ + patch.object(engine, "_close_traces") as close_traces, \ + patch("kilin.gui.engine.ConversationStore") as store: + with self.assertRaises(ValueError): + engine._activate_project( + self.project, engine.active_conversation, + ) + with self.assertRaises(ValueError): + engine._reopen_project_conversation( + self.project, "conversation_existing", + ) + settings.assert_not_called() + rag.assert_not_called() + close_traces.assert_not_called() + store.assert_not_called() + self.assertIs(engine.session, session) + self.assertEqual(self.inventory(self.project.root), before) + + def test_source_actions_reject_before_trace_or_recovery_refresh(self): + engine, events, session = self.active_engine() + actions = ( + lambda: engine.check_sources([str(self.new_source)]), + lambda: engine.add_project_sources([str(self.new_source)]), + lambda: engine.remove_project_sources(["sources/note.py"]), + lambda: engine.sync_sources(), + lambda: engine.apply_indexing_settings({"max_file_bytes": 100}), + lambda: engine.save_source_card_settings({}), + engine.regenerate_source_cards, + ) + for state in self.INVALID_STATES: + with self.subTest(state=state): + self.ownership(state) + for index, action in enumerate(actions): + with self.subTest(state=state, action=index): + events.clear() + before = self.inventory(self.project.root) + with patch.object( + engine, "_refresh_sources", + ) as refresh: + action() + refresh.assert_not_called() + self.assertEqual(events[-1]["event"], "error") + self.assertEqual(engine.project_trace.mock_calls, []) + self.assertEqual( + engine.conversation_trace.mock_calls, [], + ) + self.assertEqual( + self.inventory(self.project.root), before, + ) + self.assertIs(engine.session, session) + session.close.assert_not_called() + session.refresh_sources.assert_not_called() + session.refresh_source_cards.assert_not_called() + session.regenerate_source_cards.assert_not_called() + + def test_mirror_rejects_cumulative_actions_without_refreshing_indexes( + self, + ): + self.ownership("mirror") + engine, events, _session = self.active_engine() + before = self.inventory(self.project.root) + for action in ( + lambda: engine.check_sources([str(self.new_source)]), + lambda: engine.add_project_sources([str(self.new_source)]), + engine.sync_sources, + ): + events.clear() + with patch.object(engine, "_refresh_sources") as refresh: + action() + refresh.assert_not_called() + self.assertIn("Cumulative imports", events[-1]["message"]) + self.assertEqual(engine.project_trace.mock_calls, []) + self.assertEqual(self.inventory(self.project.root), before) + + def test_valid_mirror_still_allows_explicit_local_source_removal(self): + self.ownership("mirror") + engine, events, _session = self.active_engine() + before = self.mirror.read_bytes() + with patch.object(engine, "_refresh_sources") as refresh: + engine.remove_project_sources(["sources/note.py"]) + self.assertFalse((self.project.source / "note.py").exists()) + self.assertEqual(self.mirror.read_bytes(), before) + self.assertFalse(self.imports.exists()) + refresh.assert_called_once() + self.assertFalse(any(event["event"] == "error" for event in events)) + + def test_metadata_commands_reject_without_recording_or_mutation(self): + engine, events, _session = self.active_engine() + for state in self.INVALID_STATES: + with self.subTest(state=state): + self.ownership(state) + for operation in ("inspect", "preview", "initialize", + "reconcile", "apply"): + with self.subTest(state=state, operation=operation): + before = self.inventory(self.project.root) + engine.source_organization({ + "operation": operation, + "project": str(self.project.root), "request_id": 7, + }) + self.assertEqual(events[-1]["event"], + "source_organization") + self.assertEqual(events[-1]["request_id"], 7) + self.assertIn("error", events[-1]) + self.assertEqual(engine.project_trace.mock_calls, []) + self.assertEqual( + self.inventory(self.project.root), before, + ) + + def test_capability_settings_keep_the_correlated_failure_response(self): + engine, events, session = self.active_engine() + self.ownership("unsupported_import") + before = self.inventory(self.project.root) + with patch("kilin.gui.engine.save_project_behavior") as save: + engine.save_behavior_settings( + str(self.project.root), "capabilities", None, {}, "revision", + 23, + ) + save.assert_not_called() + self.assertEqual(events[-1]["event"], "project_behavior") + self.assertEqual(events[-1]["request_id"], 23) + self.assertEqual(events[-1]["scope"], "capabilities") + self.assertIn("error", events[-1]) + self.assertEqual(engine.project_trace.mock_calls, []) + self.assertEqual(self.inventory(self.project.root), before) + self.assertIs(engine.session, session) + + def test_reference_preview_falls_back_to_saved_evidence_without_reading( + self, + ): + engine, events, session = self.active_engine() + evidence = Evidence(1, Path("note.py"), 1, 1, None, "saved passage") + session.turns = [SimpleNamespace(evidence=(evidence,))] + session._reads_as_code = lambda: True + for state in self.INVALID_STATES: + with self.subTest(state=state): + self.ownership(state) + before = self.inventory(self.project.root) + with patch("kilin.gui.engine.read_repository_files", + side_effect=AssertionError("Unexpected read")): + engine.preview_reference(0, 1) + self.assertEqual(events[-1]["event"], "reference_preview") + self.assertIn("saved passage", events[-1]["note"]) + self.assertEqual(events[-1]["lines"][0]["text"], + "saved passage") + self.assertEqual(self.inventory(self.project.root), before) + self.assertEqual(engine.project_trace.mock_calls, []) + + def test_valid_modes_keep_current_reference_context_available(self): + engine, events, session = self.active_engine() + evidence = Evidence(1, Path("note.py"), 1, 1, None, "current source") + session.turns = [SimpleNamespace(evidence=(evidence,))] + session._reads_as_code = lambda: True + for state in ("manual", "imports", "mirror"): + with self.subTest(state=state): + self.ownership(state) + before = self.inventory(self.project.root) + engine.preview_reference(0, 1) + self.assertEqual(events[-1]["event"], "reference_preview") + self.assertEqual(events[-1]["note"], "") + self.assertEqual(events[-1]["lines"][0]["text"], + "current source") + self.assertEqual(self.inventory(self.project.root), before) + + def test_saved_conversations_and_metadata_remain_readable(self): + store = ConversationStore(self.project.root) + conversation = store.ensure() + path = store.state_path(conversation) + value = json.loads(path.read_text()) + conversation_state(value)["turns"] = [ + {"question": "Saved question", "answer": "Saved answer"}, + ] + path.write_text(json.dumps(value)) + saved = read_source_manifest(self.project) + self.ownership("conflict") + before = self.inventory(self.project.root) + engine, events = self.engine() + engine.list_saved_projects(str(self.project.root)) + self.assertEqual(events[-1]["projects"][0]["project"], + str(self.project.root)) + self.assertEqual(read_source_manifest(self.project), saved) + reader = ConversationStore(self.project.root) + self.assertEqual(reader.ensure().conversation_id, + conversation.conversation_id) + self.assertEqual(conversation_state(json.loads(path.read_text())) + ["turns"][0]["answer"], "Saved answer") + self.assertEqual(self.inventory(self.project.root), before) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/system_testing/test_traces__semantics.py b/tests/kilin/system_testing/test_traces__semantics.py index 6293c028..30d78599 100644 --- a/tests/kilin/system_testing/test_traces__semantics.py +++ b/tests/kilin/system_testing/test_traces__semantics.py @@ -239,6 +239,33 @@ def test_noop_apply_preserves_full_gui_result_and_current_inspection(self): self.assertEqual(report.events[:len(self.report.events)], self.report.events) + def test_retired_rebind_request_blocks_replay_without_changes(self): + payload = json.loads(self.path.read_text("utf-8")) + changed = 0 + + def add_retired_option(value): + nonlocal changed + if isinstance(value, dict): + if value.get("operation") == "preview": + value["rebind"] = False + changed += 1 + for item in value.values(): + add_retired_option(item) + elif isinstance(value, list): + for item in value: + add_retired_option(item) + + add_retired_option(payload) + self.assertGreater(changed, 0) + self.path.write_text(json.dumps(payload), "utf-8") + before = test_experiment._snapshot(self.workspace) + report = self.fixture.experiment.validate() + self.assertFalse(report.valid) + with self.assertRaises(InvalidRecordingError): + self.fixture.experiment.replay(self.fixture.target) + self.assertFalse(self.fixture.target.exists()) + self.assertEqual(before, test_experiment._snapshot(self.workspace)) + def test_corrupt_reference_blocks_replay_and_creates_no_destination(self): payload = json.loads(self.path.read_text("utf-8")) for node in writer.semantic_nodes(payload): diff --git a/tests/kilin/test__format_versions.py b/tests/kilin/test__format_versions.py index 8f246515..e7d7bff0 100644 --- a/tests/kilin/test__format_versions.py +++ b/tests/kilin/test__format_versions.py @@ -149,12 +149,13 @@ def test_timing_analysis_rejects_declared_bad_versions(self): def test_managed_source_manifest_round_trip_and_strict_versions(self): path = self.root / "sources.json" + self.assertEqual(SOURCE_MANIFEST_VERSION, 2) _write_records(path, []) self.assertEqual(json.loads(path.read_text(encoding="utf-8")), { "version": SOURCE_MANIFEST_VERSION, "sources": [], }) self.assertEqual(_read_records(path), []) - for invalid in (*_INVALID_VERSIONS, "missing"): + for invalid in (True, False, 2.0, "2", None, 0, 1, 3, "missing"): with self.subTest(version=invalid): data = {"version": invalid, "sources": []} if invalid == "missing": diff --git a/tests/kilin/test__source_discovery.py b/tests/kilin/test__source_discovery.py index 3b4d9a8f..ca531a33 100644 --- a/tests/kilin/test__source_discovery.py +++ b/tests/kilin/test__source_discovery.py @@ -301,11 +301,15 @@ def test_external_root_is_not_new_raw_authority(self): parser.set("project", "source", str(external)) with profile.open("w", encoding="utf-8") as stream: parser.write(stream) - result = self.apply(rebind=True) - self.assertEqual(self.keys(), set()) - self.assertEqual(result.discovery.diagnostics[0].reason, - "source_unavailable") - self.assertEqual(result.discovery.diagnostics[0].target, "other.tex") + before = {p: p.read_bytes() for p in self.root.rglob("*") + if p.is_file()} + with patch("kilin._source_discovery.selected_source_file", + side_effect=AssertionError("Unexpected source read")): + with self.assertRaisesRegex(ValueError, "sources"): + self.apply() + self.assertEqual(before, {p: p.read_bytes() + for p in self.root.rglob("*") + if p.is_file()}) def test_disabled_rules_do_not_read_latex(self): declaration = read_source_manifest(self.project).manifest.organization diff --git a/tests/kilin/test_project.py b/tests/kilin/test_project.py index b5020413..9e38ab60 100644 --- a/tests/kilin/test_project.py +++ b/tests/kilin/test_project.py @@ -14,7 +14,7 @@ from __future__ import annotations from configparser import ConfigParser -from dataclasses import FrozenInstanceError, asdict +from dataclasses import FrozenInstanceError, asdict, replace import json from pathlib import Path import shutil @@ -23,6 +23,7 @@ from unittest.mock import MagicMock, patch from kilin import project +from kilin._source_ownership import read_mirror_manifest from kilin.defaults import load_defaults_section from kilin.model_defaults import ( DEFAULT_CHAT_MODEL_MLX, @@ -69,7 +70,7 @@ def _profile( name: str = "configured", *, type_id: str = "code", - source: str = ".", + source: str = "sources", ) -> Path: """Write a profile using the production template and JSON defaults. @@ -80,7 +81,7 @@ def _profile( type_id: str, optional Existing built-in project type. Defaults to ``code``. source: str, optional - Relative or absolute source path. Defaults to the project root. + Source setting to write. Defaults to the canonical ``sources``. Returns ------- @@ -92,11 +93,11 @@ def _profile( directory = self._folder(name) definition = project_type(type_id) text = project._default_profile_text( - type_id, source, ", ".join(definition.extensions) - ) - (directory / "profile.ini").write_text( - text, encoding="utf-8" + type_id, ", ".join(definition.extensions) ) + text = text.replace("source = sources", f"source = {source}") + (directory / "profile.ini").write_text(text, encoding="utf-8") + (directory / "sources").mkdir() return directory def _edit( @@ -310,30 +311,34 @@ def test_every_creation_path_uses_sources(self) -> None: result.source, result.root / PROJECT_SOURCES_DIRECTORY ) - def test_existing_source_folders_open_without_being_moved( - self, - ) -> None: - """Older documents/ or repository/ projects stay as they are.""" + def test_existing_source_folders_require_canonical_layout(self) -> None: + """Reject retired source folders without moving any user data.""" - for type_id, folder in ( - ("literature", "documents"), - ("code", "repository"), - ("code", "sources"), - ): - with self.subTest(type_id=type_id, folder=folder): - directory = self._profile( - f"saved-{type_id}-{folder}", type_id=type_id, - source=folder, - ) + for folder in ("documents", "repository", "original-name", "sources"): + with self.subTest(folder=folder): + directory = self._profile(f"saved-{folder}", source=folder) paper = self._write(directory / folder, "a.md", "text") - opened = project.open_project(directory) - self.assertEqual(opened.source, directory / folder) - self.assertEqual(opened.profile.source, folder) - # Opening never renames, moves, or adds a source folder. + before = { + p.relative_to(directory): p.read_bytes() + for p in directory.rglob("*") if p.is_file() + } + entries = sorted(str(p) for p in directory.rglob("*")) + if folder == "sources": + opened = project.open_project(directory) + self.assertEqual(opened.source, directory / "sources") + self.assertEqual(opened.profile.source, "sources") + else: + with self.assertRaisesRegex(ValueError, "project.source"): + project.open_project(directory) self.assertEqual(paper.read_text(encoding="utf-8"), "text") self.assertEqual( - sorted(path.name for path in directory.iterdir()), - sorted([folder, "profile.ini"]), + before, { + p.relative_to(directory): p.read_bytes() + for p in directory.rglob("*") if p.is_file() + }, + ) + self.assertEqual( + entries, sorted(str(p) for p in directory.rglob("*")) ) def test_initialize_is_idempotent_and_preserves_existing_profile( @@ -383,21 +388,58 @@ def test_open_project_requires_profile_and_valid_source(self) -> None: directory = self._folder("missingprofile") with self.assertRaisesRegex(FileNotFoundError, "profile"): project.open_project(directory) - directory = self._profile("missingsource", source="missing") + directory = self._profile("missingsource") + (directory / "sources").rmdir() with self.assertRaises(FileNotFoundError): project.open_project(directory) - directory = self._profile("file-as-source", source="some.txt") - self._write(directory, "some.txt", "data") + directory = self._profile("file-as-source") + (directory / "sources").rmdir() + self._write(directory, "sources", "data") with self.assertRaises(NotADirectoryError): project.open_project(directory) - def test_open_accepts_absolute_source_outside_project(self) -> None: - """Resolve absolute source paths without replacing source content.""" + def test_open_rejects_noncanonical_source_spellings(self) -> None: + """A different path spelling cannot redirect the project source.""" source = self._folder("external") - directory = self._profile("absolute", source=str(source)) - self.assertEqual(project.open_project(directory).source, source) - self.assertFalse((source / "profile.ini").exists()) + external_file = self._write(source, "a.py", "external = True") + for index, value in enumerate(( + ".", "./sources", "sources/", "sources/../sources", + "Sources", "sources\\", str(source), "C:\\sources", + )): + with self.subTest(source=value): + directory = self._profile(f"invalid-{index}", source=value) + profile = directory / "profile.ini" + before = profile.read_bytes() + with self.assertRaisesRegex(ValueError, "project.source"): + project.open_project(directory) + self.assertEqual(profile.read_bytes(), before) + self.assertEqual(external_file.read_text(), "external = True") + self.assertFalse((source / "profile.ini").exists()) + + def test_source_links_are_rejected_without_writes(self) -> None: + """Resolve neither a symlink nor a junction as project sources.""" + + external = self._folder("outside") + sentinel = self._write(external, "keep.py", "untouched") + directory = self._profile("linked") + canonical = directory / "sources" + canonical.rmdir() + try: + canonical.symlink_to(external, target_is_directory=True) + except (NotImplementedError, OSError): + self.skipTest("Symbolic links are unavailable") + with self.assertRaisesRegex(ValueError, "must not be a link"): + project.open_project(directory) + self.assertTrue(canonical.is_symlink()) + self.assertEqual(sentinel.read_text(), "untouched") + canonical.unlink() + canonical.mkdir() + with patch.object(Path, "is_junction", return_value=True): + with self.assertRaisesRegex(ValueError, "must not be a link"): + project.open_project(directory) + self.assertEqual(list(canonical.iterdir()), []) + class TestProjectProfileValidation(ProjectFixture): @@ -413,9 +455,16 @@ def test_default_template_round_trip(self) -> None: default = project.default_project_profile(type_id) self.assertEqual( asdict(parsed.profile), - {**asdict(default), "source": "."}, + asdict(default), ) + def test_direct_profile_cannot_select_another_source(self) -> None: + """Direct core callers obey the same fixed source-name contract.""" + + default = project.default_project_profile("code") + with self.assertRaisesRegex(ValueError, "project.source"): + replace(default, source="repository") + def test_missing_required_sections_and_options(self) -> None: """Identify missing INI keys using section-qualified errors.""" @@ -905,23 +954,27 @@ def test_deletion_prunes_empty_snapshot_directories(self) -> None: self.assertFalse((refreshed.source / "unneeded").exists()) self.assertTrue((refreshed.source / "pkg").exists()) - def test_corrupt_manifest_recovers_from_source(self) -> None: - """An unreadable baseline triggers a complete snapshot refresh.""" + def test_corrupt_manifest_rejects_without_rebuilding(self) -> None: + """Invalid ownership cannot authorize replacing any local copy.""" first = self._prepare() - self._write(first.source, "stale.txt", "stale\n") - (first.root / "source_snapshot.json").write_text( - "{broken", encoding="utf-8" - ) - refreshed = self._prepare() - self.assertFalse((refreshed.source / "stale.txt").exists()) + extra = self._write(first.source, "stale.txt", "stale\n") + manifest = first.root / "source_snapshot.json" + manifest.write_text("{broken", encoding="utf-8") + before = {path.relative_to(first.root): path.read_bytes() + for path in first.root.rglob("*") if path.is_file()} + with self.assertRaisesRegex(ValueError, "mirror provenance"): + self._prepare() self.assertEqual( - (refreshed.source / self.file).read_text(encoding="utf-8"), - "first version\n", + {path.relative_to(first.root): path.read_bytes() + for path in first.root.rglob("*") if path.is_file()}, before, ) + self.assertEqual(extra.read_text(encoding="utf-8"), "stale\n") + self.assertEqual((first.source / self.file).read_text(), + "first version\n") - def test_stale_manifest_structure_rebuilds_snapshot(self) -> None: - """Recover from a readable but structurally invalid manifest.""" + def test_stale_manifest_structure_rejects_without_rebuilding(self): + """Readable but invalid ownership leaves every saved file intact.""" initial = self._prepare() snapshot_path = initial.root / "source_snapshot.json" @@ -929,9 +982,12 @@ def test_stale_manifest_structure_rebuilds_snapshot(self) -> None: json.dumps({"source_directory": str(self.source)}), encoding="utf-8", ) - result = self._prepare() + before = snapshot_path.read_bytes() + with self.assertRaisesRegex(ValueError, "mirror provenance"): + self._prepare() + self.assertEqual(snapshot_path.read_bytes(), before) self.assertEqual( - (result.source / self.file).read_text(encoding="utf-8"), + (initial.source / self.file).read_text(encoding="utf-8"), "first version\n", ) @@ -977,25 +1033,27 @@ def test_workspace_rejects_wrong_kind_without_rewriting_profile( self.assertEqual((original.root / "profile.ini").read_bytes(), before) - def test_older_mirror_keeps_its_source_folder(self) -> None: - """A mirror copied into the original's name syncs in place.""" + def test_older_mirror_source_folder_is_rejected(self) -> None: + """Retired named mirrors are neither moved nor synchronized.""" first = self._prepare() older = first.root / self.source.name first.source.rename(older) self._edit(first.root, "project", "source", self.source.name) self._write(self.source, "pkg/extra" + self.suffix, "new\n") + before = { + p.relative_to(first.root): p.read_bytes() + for p in first.root.rglob("*") if p.is_file() + } + with self.assertRaisesRegex(ValueError, "project.source"): + self._prepare() + self.assertFalse((first.root / "sources").exists()) + self.assertEqual(before, { + p.relative_to(first.root): p.read_bytes() + for p in first.root.rglob("*") if p.is_file() + }) + self.assertFalse((older / "pkg" / f"extra{self.suffix}").exists()) - result = self._prepare() - - self.assertEqual(result.source, older) - self.assertFalse((result.root / "sources").exists()) - self.assertEqual( - (older / "pkg" / f"extra{self.suffix}").read_text( - encoding="utf-8" - ), - "new\n", - ) def test_workspace_rejects_tampered_profile_source(self) -> None: """Reject profile sources that no longer point to the owned copy.""" @@ -1074,7 +1132,7 @@ def test_workspace_rejects_symlinked_managed_source(self) -> None: first.source.symlink_to(outside, target_is_directory=True) except (NotImplementedError, OSError): self.skipTest("Creating directory symlinks is unavailable") - with self.assertRaisesRegex(ValueError, "symbolic link"): + with self.assertRaisesRegex(ValueError, "must not be a link"): self._prepare() self.assertEqual(list(outside.iterdir()), []) @@ -1116,15 +1174,19 @@ def test_snapshot_heals_same_size_content_change(self) -> None: "first version\n", ) - def test_snapshot_heals_extra_selected_file(self) -> None: - """Remove selected content not present in the original manifest.""" + def test_snapshot_preserves_extra_selected_file(self) -> None: + """Untracked selected content is outside mirror ownership.""" first = self._prepare() unexpected = self._write( first.source, f"pkg/unexpected{self.suffix}", "new file\n" ) self._prepare() - self.assertFalse(unexpected.exists()) + self.assertEqual(unexpected.read_text(), "new file\n") + self.assertNotIn( + unexpected.relative_to(first.source).as_posix(), + read_mirror_manifest(first.root)["files"], + ) def test_snapshot_integrity_checks_previous_state_before_sync( self, @@ -1147,7 +1209,7 @@ def test_snapshot_integrity_checks_previous_state_before_sync( "new original\n", ) - def test_snapshot_rebuild_does_not_follow_symlink(self) -> None: + def test_snapshot_repair_does_not_follow_symlink(self) -> None: """Treat a selected symlink in the copy as changed content.""" first = self._prepare() @@ -1207,7 +1269,7 @@ def test_removed_copy_can_disappear_after_integrity_check( first = self._prepare() target = first.source / self.file (self.source / self.file).unlink() - actual_verify = project._snapshot_matches_manifest + actual_verify = project._snapshot_content def delete_after_verification(*args): verified = actual_verify(*args) @@ -1216,7 +1278,7 @@ def delete_after_verification(*args): with patch.object( project, - "_snapshot_matches_manifest", + "_snapshot_content", side_effect=delete_after_verification, ): refreshed = self._prepare() @@ -1300,20 +1362,23 @@ def test_a_project_named_deleted_is_not_used_as_the_bin(self) -> None: class TestWorkspaceHelpers(ProjectFixture): """Cover manifest helpers and collision decisions independently.""" - def test_read_json_returns_none_for_missing_corrupt_and_nonobject( - self, - ) -> None: - """Treat invalid or unreadable snapshot records as unavailable.""" + def test_read_mirror_rejects_missing_corrupt_and_nonobject(self): + """Missing, invalid, and unreadable ownership never grants access.""" - path = self.root / "manifest.json" - self.assertIsNone(project._read_json_if_possible(path)) + path = self.root / "source_snapshot.json" + with self.assertRaisesRegex(ValueError, "requires saved"): + read_mirror_manifest(self.root) for text in ("{", "[]", '"a"'): path.write_text(text, encoding="utf-8") - self.assertIsNone(project._read_json_if_possible(path)) - path.write_text('{"key": 1}', encoding="utf-8") - self.assertEqual(project._read_json_if_possible(path), {"key": 1}) + with self.assertRaises(ValueError): + read_mirror_manifest(self.root) + value = {"format_version": 1, "files": {}, + "source_directory": str(self.root / "original")} + path.write_text(json.dumps(value), encoding="utf-8") + self.assertEqual(read_mirror_manifest(self.root), value) with patch.object(Path, "read_text", side_effect=OSError("bad")): - self.assertIsNone(project._read_json_if_possible(path)) + with self.assertRaisesRegex(OSError, "bad"): + read_mirror_manifest(self.root) def test_write_json_is_sorted_atomic_and_creates_parents(self) -> None: """Write deterministic JSON without leaving the temporary file.""" @@ -1325,8 +1390,7 @@ def test_write_json_is_sorted_atomic_and_creates_parents(self) -> None: ) self.assertFalse(path.with_suffix(".json.tmp").exists()) project._write_json(path, {"different": True}) - self.assertEqual(project._read_json_if_possible(path), - {"different": True}) + self.assertEqual(json.loads(path.read_text()), {"different": True}) def test_remove_empty_directories_preserves_nonempty_ones(self) -> None: """Prune only empty nested folders, ignoring expected OS errors.""" @@ -1334,11 +1398,15 @@ def test_remove_empty_directories_preserves_nonempty_ones(self) -> None: root = self._folder("cleanup") (root / "empty" / "deep").mkdir(parents=True) self._write(root, "keep/file.txt", "content") - project._remove_empty_directories(root) + (root / "untracked-empty").mkdir() + project._remove_empty_directories(root, ("empty/deep/removed.txt",)) self.assertFalse((root / "empty").exists()) self.assertTrue((root / "keep").exists()) + self.assertTrue((root / "untracked-empty").is_dir()) with patch.object(Path, "rmdir", side_effect=OSError("busy")): - project._remove_empty_directories(root) + project._remove_empty_directories( + root, ("empty/deep/removed.txt",), + ) self.assertTrue((root / "keep").exists()) def test_select_workspace_root_for_new_and_known_owners(self) -> None: diff --git a/tests/kilin/test_project__mirror_ownership.py b/tests/kilin/test_project__mirror_ownership.py new file mode 100644 index 00000000..55196da0 --- /dev/null +++ b/tests/kilin/test_project__mirror_ownership.py @@ -0,0 +1,434 @@ +"""Test mirror ownership, rejected operations, and partial synchronization. + +Every case uses disposable filesystem trees. Rejection checks compare file +bytes, directory entries, and symbolic-link targets before and after the +operation, including metadata outside the managed source folder. + +""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from __future__ import annotations + +from copy import deepcopy +import json +from pathlib import Path +import shutil +from tempfile import TemporaryDirectory +import unittest +from unittest.mock import patch + +from kilin import project +from kilin._source_ownership import ( + read_mirror_manifest, source_ownership, validate_mirror_manifest, +) + + +class TestMirrorOwnership(unittest.TestCase): + + def setUp(self): + temporary = TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.original = self.root / "original" + self.original.mkdir() + self.write(self.original, "a.py", "a original\n") + self.write(self.original, "old.py", "old original\n") + self.mirror = project.prepare_project_workspace( + self.original, "code", self.root / "workspaces", + ) + self.manifest = self.mirror.root / "source_snapshot.json" + + @staticmethod + def write(root, relative, text): + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return path + + @staticmethod + def inventory(root): + entries = {} + for path in root.rglob("*"): + name = path.relative_to(root).as_posix() + if path.is_symlink(): + entries[name] = ("link", str(path.readlink())) + elif path.is_dir(): + entries[name] = ("directory",) + else: + entries[name] = ("file", path.read_bytes()) + return entries + + def synchronize(self, **options): + return project.synchronize_project_workspace( + self.original, self.mirror.root, **options, + ) + + def assert_rejected_unchanged(self, message): + before = self.inventory(self.root) + observed = [] + with self.assertRaisesRegex(ValueError, message): + self.synchronize(on_organization=observed.append) + self.assertEqual(self.inventory(self.root), before) + self.assertEqual(observed, []) + + def test_missing_provenance_never_adopts_an_existing_project(self): + self.manifest.unlink() + self.write(self.mirror.source, "manual.py", "manual\n") + self.assert_rejected_unchanged("requires saved mirror provenance") + + def test_conflicting_import_and_mirror_ownership_rejects_all_writes(self): + (self.mirror.root / "sources.json").write_text("{}") + self.assert_rejected_unchanged("Conflicting source ownership") + + def test_wrong_original_identity_cannot_authorize_synchronization(self): + value = read_mirror_manifest(self.mirror.root) + value["source_directory"] = str(self.root / "different") + self.manifest.write_text(json.dumps(value)) + self.assert_rejected_unchanged("conflicts with saved mirror") + + def test_invalid_provenance_fields_preserve_all_saved_data(self): + valid = read_mirror_manifest(self.mirror.root) + invalid = [ + {key: value for key, value in valid.items() + if key != "source_directory"}, + {**valid, "original": str(self.original)}, + {**valid, "format_version": True}, + {**valid, "format_version": 999}, + {**valid, "source_directory": "relative"}, + {**valid, "source_directory": str(self.original / "..")}, + {**valid, "files": []}, + ] + for value in invalid: + with self.subTest(value=value): + self.manifest.write_text(json.dumps(value)) + self.assert_rejected_unchanged("mirror|manifest") + + def test_unsafe_duplicate_or_overlapping_file_paths_are_rejected(self): + valid = read_mirror_manifest(self.mirror.root) + record = valid["files"]["a.py"] + for names in ( + ("../outside.py",), ("/absolute.py",), ("C:/outside.py",), + ("a//b.py",), ("a/./b.py",), ("a\\b.py",), + ("a.py", "a.py/child.py"), ("A/a.py", "a/b.py"), + (".kilin_versions/a.py",), + ): + with self.subTest(names=names): + value = {**valid, "files": {name: record for name in names}} + self.manifest.write_text(json.dumps(value)) + self.assert_rejected_unchanged("manifest|Mirror|path") + self.manifest.write_text( + '{"files": {}, "files": {}, "format_version": 1, ' + '"source_directory": ' + json.dumps(str(self.original)) + '}', + ) + self.assert_rejected_unchanged("Duplicate mirror provenance") + + def test_untracked_collision_rejects_before_any_copy_or_deletion(self): + (self.original / "old.py").unlink() + self.write(self.original, "a.py", "changed original\n") + self.write(self.original, "new.py", "new original\n") + self.write(self.mirror.source, "new.py", "manual local\n") + self.assert_rejected_unchanged("conflicts with untracked file") + + def test_directory_collision_preserves_its_untracked_descendants(self): + self.write(self.original, "new.py", "new original\n") + self.write(self.mirror.source, "new.py/manual.txt", "manual\n") + self.assert_rejected_unchanged("destination is not a file") + + def test_untracked_file_cannot_be_replaced_by_a_source_directory(self): + self.write(self.original, "nested/new.py", "new original\n") + self.write(self.mirror.source, "nested", "manual local\n") + self.assert_rejected_unchanged("parent is not a folder") + + def test_owned_file_replaced_by_directory_is_not_recursively_deleted(self): + (self.mirror.source / "a.py").unlink() + self.write(self.mirror.source, "a.py/manual.txt", "manual\n") + self.assert_rejected_unchanged("destination is not a file") + + def test_tracked_original_file_can_become_a_directory(self): + (self.original / "a.py").unlink() + self.write(self.original, "a.py/nested.py", "nested original\n") + self.synchronize() + self.assertTrue((self.mirror.source / "a.py").is_dir()) + self.assertEqual((self.mirror.source / "a.py/nested.py").read_text(), + "nested original\n") + self.assertEqual(set(read_mirror_manifest(self.mirror.root)["files"]), + {"a.py/nested.py", "old.py"}) + + def test_fully_tracked_original_directory_can_become_a_file(self): + self.write(self.original, "nested.py/first.py", "first\n") + self.write(self.original, "nested.py/deeper/second.py", "second\n") + self.synchronize() + shutil.rmtree(self.original / "nested.py") + self.write(self.original, "nested.py", "replacement original\n") + self.synchronize() + self.assertEqual((self.mirror.source / "nested.py").read_text(), + "replacement original\n") + self.assertEqual(set(read_mirror_manifest(self.mirror.root)["files"]), + {"a.py", "nested.py", "old.py"}) + + def test_directory_to_file_preserves_untracked_files_and_empty_folders( + self, + ): + self.write(self.original, "nested.py/tracked.py", "tracked\n") + self.synchronize() + shutil.rmtree(self.original / "nested.py") + self.write(self.original, "nested.py", "replacement original\n") + local = self.mirror.source / "nested.py" + untracked = self.write(local, "manual.txt", "manual local\n") + self.assert_rejected_unchanged("destination is not a file") + untracked.unlink() + (local / "manual-empty").mkdir() + self.assert_rejected_unchanged("destination is not a file") + + def test_linked_parent_cannot_redirect_a_tracked_operation(self): + self.write(self.original, "nested/a.py", "nested original\n") + self.synchronize() + outside = self.root / "outside" + (self.mirror.source / "nested").rename(outside) + try: + (self.mirror.source / "nested").symlink_to( + outside, target_is_directory=True, + ) + except (OSError, NotImplementedError): + self.skipTest("Creating directory symlinks is unavailable") + self.write(self.original, "nested/a.py", "changed original\n") + self.assert_rejected_unchanged("parent cannot be a link") + + def test_junction_parent_rejects_before_any_operation(self): + self.write(self.original, "nested/a.py", "nested original\n") + self.synchronize() + parent = self.mirror.source / "nested" + actual = Path.is_junction + + def junction(path): + return path == parent or actual(path) + + with patch.object(Path, "is_junction", junction): + self.assert_rejected_unchanged("parent cannot be a link") + + def test_ownership_metadata_links_and_directories_are_not_missing(self): + payload = self.manifest.read_bytes() + self.manifest.unlink() + self.manifest.mkdir() + self.assert_rejected_unchanged("must be a regular file") + self.manifest.rmdir() + outside = self.root / "outside.json" + outside.write_bytes(payload) + for target in (outside, self.root / "missing.json"): + with self.subTest(target=target.name): + try: + self.manifest.symlink_to(target) + except (OSError, NotImplementedError): + self.skipTest("Creating file symlinks is unavailable") + try: + self.assert_rejected_unchanged("must be a regular file") + finally: + self.manifest.unlink() + + def test_untracked_files_links_empty_folders_and_versions_survive(self): + self.write(self.mirror.source, "manual.py", "manual selected\n") + self.write(self.mirror.source, "private.data", "manual unselected\n") + self.write(self.mirror.source, ".kilin_versions/a.py", "archive\n") + (self.mirror.source / "manual-empty").mkdir() + outside = self.write(self.root, "outside.py", "outside\n") + with self.subTest(entry="manual-link.py"): + try: + (self.mirror.source / "manual-link.py").symlink_to(outside) + except (OSError, NotImplementedError): + self.skipTest("Creating file symlinks is unavailable") + (self.original / "old.py").unlink() + self.write(self.original, "a.py", "updated original\n") + before = self.inventory(self.mirror.source) + self.synchronize() + after = self.inventory(self.mirror.source) + for name in set(before) - {"a.py", "old.py"}: + self.assertEqual(after[name], before[name]) + self.assertEqual(set(read_mirror_manifest(self.mirror.root)["files"]), + {"a.py"}) + self.assertEqual(outside.read_text(), "outside\n") + + def test_partial_copy_records_success_and_can_resume_without_adoption( + self, + ): + (self.original / "old.py").unlink() + self.write(self.original, "b.py", "b original\n") + self.write(self.original, "c.py", "c original\n") + original_bytes = self.inventory(self.original) + copy = shutil.copy2 + + def fail_c(source, destination, **options): + if source.name == "c.py": + destination.write_bytes(b"incomplete") + raise OSError("copy failed") + return copy(source, destination, **options) + + with patch.object(project.shutil, "copy2", side_effect=fail_c): + with self.assertRaisesRegex(OSError, "copy failed"): + self.synchronize() + saved = read_mirror_manifest(self.mirror.root) + self.assertEqual(set(saved["files"]), {"a.py", "b.py"}) + self.assertFalse((self.mirror.source / "old.py").exists()) + self.assertFalse((self.mirror.source / "c.py").exists()) + self.assertFalse(list(self.mirror.source.glob("*.tmp"))) + copied_inode = (self.mirror.source / "b.py").stat().st_ino + self.synchronize() + self.assertEqual((self.mirror.source / "b.py").stat().st_ino, + copied_inode) + self.assertEqual((self.mirror.source / "c.py").read_text(), + "c original\n") + self.assertEqual(self.inventory(self.original), original_bytes) + + def test_partial_deletion_records_only_successfully_removed_files(self): + (self.original / "a.py").unlink() + (self.original / "old.py").unlink() + actual = Path.unlink + + def fail_old(path, *args, **kwargs): + if path == self.mirror.source / "old.py": + raise OSError("deletion failed") + return actual(path, *args, **kwargs) + + with patch.object(Path, "unlink", fail_old): + with self.assertRaisesRegex(OSError, "deletion failed"): + self.synchronize() + self.assertEqual(set(read_mirror_manifest(self.mirror.root)["files"]), + {"old.py"}) + self.assertFalse((self.mirror.source / "a.py").exists()) + self.assertEqual((self.mirror.source / "old.py").read_text(), + "old original\n") + self.synchronize() + self.assertEqual(read_mirror_manifest(self.mirror.root)["files"], {}) + + def test_changed_original_during_copy_does_not_replace_local_bytes(self): + self.write(self.original, "a.py", "updated original\n") + before = self.inventory(self.mirror.root) + copy = shutil.copy2 + + def changed_copy(source, destination, **options): + result = copy(source, destination, **options) + destination.write_bytes(b"different content") + return result + + with patch.object(project.shutil, "copy2", side_effect=changed_copy): + with self.assertRaisesRegex(OSError, "changed during copy"): + self.synchronize() + after = self.inventory(self.mirror.root) + # Semantic reconciliation may create its normal writer lock after + # a physical attempt; sources and provenance must remain identical. + after.pop(".source_manifest.json.lock", None) + before.pop(".source_manifest.json.lock", None) + self.assertEqual(after, before) + + def test_concurrent_new_destination_is_not_overwritten(self): + self.write(self.original, "new.py", "new original\n") + target = self.mirror.source / "new.py" + copy = shutil.copy2 + + def appear_during_copy(source, destination, **options): + result = copy(source, destination, **options) + target.write_text("concurrent manual\n") + return result + + with patch.object(project.shutil, "copy2", + side_effect=appear_during_copy): + with self.assertRaises(FileExistsError): + self.synchronize() + self.assertEqual(target.read_text(), "concurrent manual\n") + self.assertNotIn("new.py", + read_mirror_manifest(self.mirror.root)["files"]) + + def test_original_failure_is_preserved_if_provenance_write_also_fails( + self, + ): + self.write(self.original, "b.py", "b original\n") + self.write(self.original, "c.py", "c original\n") + copy = shutil.copy2 + + def fail_c(source, destination, **options): + if source.name == "c.py": + raise OSError("primary copy failure") + return copy(source, destination, **options) + + with patch.object(project.shutil, "copy2", side_effect=fail_c), \ + patch.object(project, "_write_json", + side_effect=OSError("metadata failure")): + with self.assertRaisesRegex(OSError, "primary copy failure") as cm: + self.synchronize() + self.assertTrue(any("metadata failure" in note + for note in cm.exception.__notes__)) + self.assertEqual((self.mirror.source / "b.py").read_text(), + "b original\n") + self.assertFalse((self.mirror.source / "c.py").exists()) + + def test_missing_original_and_local_copies_preserve_readable_ownership( + self, + ): + valid = read_mirror_manifest(self.mirror.root) + shutil.rmtree(self.original) + (self.mirror.source / "a.py").unlink() + self.assertEqual(read_mirror_manifest(self.mirror.root), valid) + self.assertEqual(source_ownership(self.mirror.root), "mirror") + + def test_workspace_relocation_keeps_the_same_explicit_mirror_owner(self): + before = read_mirror_manifest(self.mirror.root) + moved = self.root / "moved" + self.mirror.root.rename(moved) + self.mirror = project.open_project(moved) + self.manifest = moved / "source_snapshot.json" + self.assertEqual(read_mirror_manifest(moved), before) + self.write(self.original, "new.py", "new original\n") + self.synchronize() + self.assertEqual((self.mirror.source / "new.py").read_text(), + "new original\n") + + def test_workspace_moved_inside_original_excludes_only_its_own_tree(self): + moved = self.original / "moved-workspace" + self.mirror.root.rename(moved) + self.mirror = project.open_project(moved) + self.synchronize() + self.assertEqual(set(read_mirror_manifest(moved)["files"]), + {"a.py", "old.py"}) + self.assertFalse((self.mirror.source / "moved-workspace").exists()) + self.assertEqual((self.mirror.source / "a.py").read_text(), + "a original\n") + + def test_failed_fresh_creation_rolls_back_copies_and_partial_provenance( + self, + ): + destination = self.root / "failed-creation" + copy = shutil.copy2 + original_bytes = self.inventory(self.original) + + def fail_second(source, target, **options): + if source.name == "old.py": + raise OSError("initial copy failed") + return copy(source, target, **options) + + with patch.object(project.shutil, "copy2", side_effect=fail_second): + with self.assertRaisesRegex(OSError, "initial copy failed"): + project.prepare_project_workspace( + self.original, "code", destination, + ) + self.assertEqual(list(destination.iterdir()), []) + self.assertEqual(self.inventory(self.original), original_bytes) + + def test_invalid_content_record_is_rejected_without_disk_inference(self): + value = read_mirror_manifest(self.mirror.root) + for record in ( + {"size_bytes": True, "sha256": "0" * 64}, + {"size_bytes": -1, "sha256": "0" * 64}, + {"size_bytes": 1, "sha256": "not a digest"}, + {"size_bytes": 1, "sha256": "0" * 64, "mtime": 0}, + ): + with self.subTest(record=record): + invalid = deepcopy(value) + invalid["files"]["a.py"] = record + with self.assertRaises(ValueError): + validate_mirror_manifest(invalid) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/test_project_files.py b/tests/kilin/test_project_files.py index fe0ab3dc..bceddd93 100644 --- a/tests/kilin/test_project_files.py +++ b/tests/kilin/test_project_files.py @@ -11,9 +11,12 @@ from __future__ import annotations +from dataclasses import replace +import os from pathlib import Path from tempfile import TemporaryDirectory import unittest +from unittest.mock import patch from kilin.project import initialize_project from kilin.project_files import ( @@ -128,6 +131,102 @@ def test_empty_folders_remain_listed(self) -> None: self.assertIn("memory/", listed) self.assertIn("profile.ini", listed) + def test_inventory_rejects_linked_sources_before_traversal(self) -> None: + """An opened project cannot authorize a replaced source root.""" + + for predicate in ("is_symlink", "is_junction"): + with self.subTest(predicate=predicate): + with patch.object( + Path, predicate, autospec=True, + side_effect=lambda path: path == self.project.source, + ), patch.object(Path, "walk") as walk: + with self.assertRaisesRegex(ValueError, "link"): + list_project_files(self.project) + walk.assert_not_called() + + def test_inventory_rejects_noncanonical_captured_source(self) -> None: + """A fabricated source path must fail before any file listing.""" + + for source in ( + self.project.root, self.root / "external", + self.project.source / "nested", + ): + with self.subTest(source=source): + captured = replace(self.project, source=source) + with patch.object(Path, "walk") as walk: + with self.assertRaisesRegex(ValueError, "sources"): + list_project_files(captured) + walk.assert_not_called() + + def test_inventory_rejects_redirected_saved_profile(self) -> None: + """Recheck the saved profile even when the captured path is valid.""" + + profile = self.project.root / "profile.ini" + redirected = profile.read_text(encoding="utf-8").replace( + "source = sources", "source = documents" + ) + profile.write_text(redirected, encoding="utf-8") + with patch.object(Path, "walk") as walk: + with self.assertRaisesRegex(ValueError, "project.source"): + list_project_files(self.project) + walk.assert_not_called() + self.assertEqual(profile.read_text(encoding="utf-8"), redirected) + self.assertTrue(self.project.source.is_dir()) + self.assertFalse((self.project.root / "documents").exists()) + + def test_inventory_prunes_nested_links_before_enumerating(self) -> None: + """Linked descendants must not expose their names or target files.""" + + hidden = self.project.source / "linked" + hidden.mkdir() + (hidden / "hidden.py").write_text("hidden\n", encoding="utf-8") + visible = self.project.source / "regular" + visible.mkdir() + (visible / "visible.py").write_text("visible\n", encoding="utf-8") + scan = os.scandir + + def guarded_scan(path): + if Path(path) == hidden: + raise AssertionError("Linked target must not be enumerated.") + return scan(path) + + for predicate in ("is_symlink", "is_junction"): + with self.subTest(predicate=predicate): + with patch.object( + Path, predicate, autospec=True, + side_effect=lambda path: path == hidden, + ), patch("os.scandir", side_effect=guarded_scan): + listed = list_project_files(self.project) + self.assertIn("sources/regular/", listed) + self.assertIn("sources/regular/visible.py", listed) + self.assertNotIn("sources/linked/", listed) + self.assertNotIn("sources/linked/hidden.py", listed) + + def test_inventory_keeps_unavailable_types_and_missing_folders( + self, + ) -> None: + """Read-only listing needs no plugin and repairs no derived folder.""" + + profile = self.project.root / "profile.ini" + saved = profile.read_text(encoding="utf-8").replace( + "type_id = code", "type_id = unavailable_type" + ) + profile.write_text(saved, encoding="utf-8") + self.project.indexes.rmdir() + (self.project.root / "memory").rmdir() + with patch( + "kilin.project._require_project_type", + side_effect=AssertionError("Listing must not load project types"), + ): + listed = list_project_files(self.project) + self.assertIn("sources/", listed) + self.assertIn("profile.ini", listed) + self.assertNotIn("indexes/", listed) + self.assertNotIn("memory/", listed) + self.assertEqual(profile.read_text(encoding="utf-8"), saved) + self.assertFalse(self.project.indexes.exists()) + self.assertFalse((self.project.root / "memory").exists()) + def test_invalid_paths_and_managed_root_are_rejected(self) -> None: """Deletion cannot escape, or remove, a protected project folder.""" diff --git a/tests/kilin/test_project_layout.py b/tests/kilin/test_project_layout.py index 2b908db0..7b0ed08a 100644 --- a/tests/kilin/test_project_layout.py +++ b/tests/kilin/test_project_layout.py @@ -261,24 +261,19 @@ def test_workspace_inventory_reports_empty_folders(self) -> None: self.assertIn(f"{name}/", listed) self.assertNotIn(name, listed) - def test_root_source_excludes_metadata_not_external_files(self) -> None: - """Internal profile and manifests are excluded only at project root.""" + def test_canonical_source_scan_keeps_user_metadata_names(self) -> None: + """Workspace metadata is outside sources; user names stay selected.""" from kilin.project import configure_project root = self._project("code") - profile = root / "profile.ini" - profile.write_text( - profile.read_text(encoding="utf-8").replace( - "source = sources", "source = ." - ), encoding="utf-8", - ) project = configure_project( root, {"extensions": [".py", ".ini", ".json"]} ) - (root / "analysis.py").write_text("x = 1\n", encoding="utf-8") (root / "sources.json").write_text("{}\n", encoding="utf-8") (root / "source_snapshot.json").write_text("{}\n", encoding="utf-8") + for name in ("analysis.py", "profile.ini", "sources.json"): + (project.source / name).write_text("source", encoding="utf-8") report = scan_repository( project.source, extensions=project.profile.extensions, @@ -286,8 +281,10 @@ def test_root_source_excludes_metadata_not_external_files(self) -> None: project.root, project.source ), ) - self.assertEqual(report["selected_files"], ["analysis.py"]) - + self.assertEqual( + report["selected_files"], + ["analysis.py", "profile.ini", "sources.json"], + ) external = self.root / "external" external.mkdir() (external / "profile.ini").write_text("[external]\n", encoding="utf-8") @@ -299,7 +296,8 @@ def test_root_source_excludes_metadata_not_external_files(self) -> None: external_report["selected_files"], ["profile.ini", "sources.json"], ) - + with self.assertRaisesRegex(ValueError, "project's sources"): + source_scan_exclusions(root, root) def test_managed_source_versions_are_not_automatically_scanned( self, @@ -333,45 +331,37 @@ def test_managed_source_versions_are_not_automatically_scanned( report["selected_files"], ) - def test_root_source_excludes_managed_templates_from_scans(self) -> None: - """Template Markdown is not indexed when source equals project root.""" + def test_managed_templates_are_outside_canonical_source_scans( + self, + ) -> None: + """Only sources are scanned, including user-owned nested templates.""" root = self._project("literature") - profile = root / "profile.ini" - text = profile.read_text(encoding="utf-8") - text = text.replace("source = sources", "source = .") - profile.write_text(text, encoding="utf-8") opened = open_project(root) - self.assertEqual(opened.source.resolve(), root.resolve()) - (root / "study.md").write_text("# Source", encoding="utf-8") + (opened.source / "study.md").write_text("# Source", encoding="utf-8") (root / "memory/feedback.json").write_text( '{"records": "not a source"}', encoding="utf-8" ) excluded = source_scan_exclusions(opened.root, opened.source) report = scan_repository( - opened.source, - extensions=(".md",), - exclude_paths=excluded, + opened.source, extensions=(".md",), exclude_paths=excluded, ) self.assertEqual(report["selected_files"], ["study.md"]) - self.assertIn("memory", excluded) - # An unrelated source directory named target is not managed. - target = root / "target" + self.assertEqual(excluded, (".kilin_versions",)) + target = opened.source / "templates" target.mkdir() (target / "notes.md").write_text("# Notes", encoding="utf-8") report = scan_repository( opened.source, extensions=(".md",), exclude_paths=excluded, ) - self.assertIn("target/notes.md", report["selected_files"]) - self.assertEqual( - source_scan_exclusions(root, root / "external"), () - ) + self.assertIn("templates/notes.md", report["selected_files"]) + with self.assertRaisesRegex(ValueError, "project's sources"): + source_scan_exclusions(root, root / "external") - - def test_resolved_root_alias_still_excludes_managed_folders( + def test_resolved_workspace_alias_preserves_canonical_source_scans( self, ) -> None: - """Resolve filesystem aliases when applying source scan limits. + """A workspace alias still selects the same real sources directory. """ @@ -381,12 +371,23 @@ def test_resolved_root_alias_still_excludes_managed_folders( alias.symlink_to(root, target_is_directory=True) except (NotImplementedError, OSError): self.skipTest("Symbolic links are unavailable") - exclusions = source_scan_exclusions(alias, root.resolve()) - self.assertIn("templates", exclusions) - self.assertIn("outputs", exclusions) - self.assertEqual( - source_scan_exclusions(alias, self.root / "external"), () - ) + for project_path in (root, alias): + for source in (root.resolve() / "sources", alias / "sources"): + with self.subTest(root=project_path, source=source): + exclusions = source_scan_exclusions(project_path, source) + self.assertEqual(exclusions, (".kilin_versions",)) + with self.assertRaisesRegex(ValueError, "project's sources"): + source_scan_exclusions(alias, self.root / "external") + # An alias of the source entry itself is not a workspace alias. + source = root / "sources" + alternate = root / "documents" + alternate.symlink_to(source, target_is_directory=True) + with self.assertRaisesRegex(ValueError, "project's sources"): + source_scan_exclusions(alias, alternate) + source.rename(root / "real_sources") + source.symlink_to(root / "real_sources", target_is_directory=True) + with self.assertRaisesRegex(ValueError, "must not be a link"): + source_scan_exclusions(alias, alias / "sources") def test_template_accessor_has_no_side_effects(self) -> None: """A tool helper cannot create folders or install templates.""" diff --git a/tests/kilin/test_rag.py b/tests/kilin/test_rag.py index 7046fe40..0e10952d 100644 --- a/tests/kilin/test_rag.py +++ b/tests/kilin/test_rag.py @@ -32,6 +32,7 @@ _evidence, _intent, _session, + _source_project, _turn, ) @@ -1110,8 +1111,9 @@ def setUp(self) -> None: """Create isolated state and arrange test-specific fixtures.""" temporary = TemporaryDirectory() self.addCleanup(temporary.cleanup) - self.root = Path(temporary.name) + self.root = Path(temporary.name).resolve() self.session = _session(self.root) + self.session.project = _source_project(self.root) self.session.project.indexes.mkdir() self.session.project.source.mkdir() self.embedding = FakeEmbeddings() diff --git a/tests/kilin/test_rag__conversation.py b/tests/kilin/test_rag__conversation.py index 2bdbdca7..11b1f697 100644 --- a/tests/kilin/test_rag__conversation.py +++ b/tests/kilin/test_rag__conversation.py @@ -10,10 +10,11 @@ from __future__ import annotations +from configparser import ConfigParser +from dataclasses import replace import json from pathlib import Path from tempfile import TemporaryDirectory -from types import SimpleNamespace import unittest from unittest.mock import MagicMock, Mock, patch, sentinel from kilin import rag @@ -22,6 +23,7 @@ CONVERSATION_SESSION_KEY, new_conversation_session, ) +from kilin.project import initialize_project from kilin.runtime import BACKEND_MLX from kilin.trace_logging import NullTraceLogger, TraceConfig from tests.kilin.retrievals._support import chunk @@ -36,6 +38,12 @@ class TestRAGLifecycle(unittest.TestCase): """Test model ownership, switching, refresh, and token bookkeeping.""" + def project_for_refresh(self): + """Use a real current profile while keeping model services mocked.""" + temporary = TemporaryDirectory() + self.addCleanup(temporary.cleanup) + return initialize_project(Path(temporary.name) / "project", "code") + def test_close_releases_sessions_once(self) -> None: """Close model resources exactly once per RAG session.""" session = _session() @@ -73,7 +81,7 @@ def test_refresh_sources_replaces_only_retrieval_state(self) -> None: """Refresh indexed sources without reloading chat resources.""" session = _session() previous_chat = session.chat_session - new_project = SimpleNamespace(root=Path("/new")) + new_project = self.project_for_refresh() values = ([chunk("new")], sentinel.indexes, "reused", {"a": 1}) session._prepare_retrieval = Mock(return_value=values) session._prepare_source_cards = Mock( @@ -93,7 +101,7 @@ def test_refresh_sources_replaces_only_retrieval_state(self) -> None: ) self.assertIs(session.source_cards, sentinel.cards) self.assertIs(session.source_card_vectors, sentinel.card_vectors) - self.assertIs(session.project, new_project) + self.assertEqual(session.project, new_project) self.assertEqual(session.chunks, values[0]) self.assertIs(session.indexes, sentinel.indexes) self.assertEqual(session.index_status, "reused") @@ -105,7 +113,7 @@ def test_source_refresh_notifies_before_failed_indexing(self): from kilin.source_manifest import SourceLifecycleResult session = _session() - project = SimpleNamespace(root=Path("/new")) + project = self.project_for_refresh() outcome = SourceLifecycleResult(changed=True) observed = [] original_indexes = session.indexes @@ -124,9 +132,57 @@ def fail(*args): self.assertIs(session.indexes, original_indexes) self.assertEqual(observed, [outcome]) + def test_source_refresh_rejects_invalid_layout_before_any_work(self): + project = self.project_for_refresh() + external = project.root.parent / "external" + external.mkdir() + (external / "secret.py").write_text("private", encoding="utf-8") + profile = project.root / "profile.ini" + config = ConfigParser() + config.read(profile, encoding="utf-8") + session = _session(project.root) + current = session.project + session._project_diagnostics = Mock(side_effect=AssertionError( + "Invalid source layout must not open diagnostics.")) + session._prepare_retrieval = Mock(side_effect=AssertionError( + "Invalid source layout must not prepare retrieval.")) + for changed_profile in (False, True): + with self.subTest(changed_profile=changed_profile): + candidate = replace(project, source=external) + if changed_profile: + candidate = project + config.set("project", "source", str(external)) + with profile.open("w", encoding="utf-8") as stream: + config.write(stream) + before = {p: p.read_bytes() + for p in project.root.parent.rglob("*") + if p.is_file()} + with patch.object(rag, "refresh_source_manifest") as refresh: + with self.assertRaisesRegex(ValueError, "sources"): + session.refresh_sources(candidate) + refresh.assert_not_called() + self.assertIs(session.project, current) + self.assertEqual(before, {p: p.read_bytes() + for p in + project.root.parent.rglob("*") + if p.is_file()}) + session._prepare_retrieval.assert_not_called() + session._project_diagnostics.assert_not_called() + + def test_source_state_rejects_a_fabricated_root_before_inspection(self): + project = self.project_for_refresh() + session = _session(project.root) + session.project = replace(project, source=project.root) + with patch.object(rag, "inspect_source_manifest", + side_effect=AssertionError("Unexpected scan")): + with self.assertRaisesRegex(ValueError, "sources"): + session._source_operation_state() + def test_card_refresh_uses_existing_indexes(self) -> None: """Reconcile cards without rescanning or embedding source chunks.""" - session = _session() + project = self.project_for_refresh() + session = _session(project.root) + session.project = project session._prepare_retrieval = Mock() session._prepare_source_cards = Mock(return_value=( sentinel.cards, sentinel.vectors, @@ -220,7 +276,7 @@ def test_refresh_failure_keeps_old_index_but_new_project(self) -> None: """Preserve the existing index after a failed source refresh.""" session = _session() original_index = session.indexes - project = SimpleNamespace(root=Path("/new")) + project = self.project_for_refresh() session._prepare_retrieval = Mock(side_effect=OSError("bad scan")) from kilin.source_manifest import SourceLifecycleResult @@ -228,7 +284,7 @@ def test_refresh_failure_keeps_old_index_but_new_project(self) -> None: return_value=SourceLifecycleResult()), self.assertRaisesRegex(OSError, "bad scan")): session.refresh_sources(project) - self.assertIs(session.project, project) + self.assertEqual(session.project, project) self.assertIs(session.indexes, original_index) def test_close_attempts_every_resource_after_multiple_failures( diff --git a/tests/kilin/test_rag__index_provenance.py b/tests/kilin/test_rag__index_provenance.py index 55faec3c..874562ae 100644 --- a/tests/kilin/test_rag__index_provenance.py +++ b/tests/kilin/test_rag__index_provenance.py @@ -13,11 +13,11 @@ from __future__ import annotations +from dataclasses import replace import json import os from pathlib import Path from tempfile import TemporaryDirectory -from types import SimpleNamespace import unittest from unittest.mock import Mock, patch @@ -27,6 +27,7 @@ from kilin.retrievals.model_identity import embedding_model_identity from kilin.retrievals.persistence import load_indexes from kilin.trace_logging import NullTraceLogger +from tests.kilin._rag_support import _source_project from tests.kilin.retrievals._support import FakeEmbeddings, chunk # Code passages are embedded with their file path in front. @@ -43,7 +44,7 @@ def setUp(self) -> None: temporary = TemporaryDirectory() self.addCleanup(temporary.cleanup) - root = Path(temporary.name) + root = Path(temporary.name).resolve() environment = patch.dict( os.environ, {"XDG_CACHE_HOME": str(root / "xdg")}, ) @@ -102,13 +103,10 @@ def _coordinator( """ session = object.__new__(RAGSession) - session.project = SimpleNamespace( - root=self.index_directory.parent, - source=self.source, - indexes=self.index_directory, - profile=SimpleNamespace( - extensions=(".py",), max_file_bytes=100000, - ), + project = _source_project(self.index_directory.parent) + session.project = replace( + project, + profile=replace(project.profile, max_file_bytes=100000), ) session.trace = NullTraceLogger() session._emit_progress = Mock() @@ -509,15 +507,20 @@ def test_real_index_metadata_tracks_embedding_settings(self) -> None: coordinator = self._coordinator() coordinator.backend = "torch" - coordinator.project.profile = SimpleNamespace( - type_id="code", - extensions=(".py",), - max_file_bytes=100000, - target_tokens=500, - max_tokens=700, - overlap_tokens=80, - query_format="plain", - embedding_model=lambda backend: str(self.models), + coordinator.project = replace( + coordinator.project, + profile=replace( + coordinator.project.profile, + type_id="code", + extensions=(".py",), + max_file_bytes=100000, + target_tokens=500, + max_tokens=700, + overlap_tokens=80, + query_format="plain", + embedding_mlx=str(self.models), + embedding_torch=str(self.models), + ), ) metadata = RAGSession._index_metadata(coordinator) self.assertNotIn("format_version", metadata) diff --git a/tests/kilin/test_rag__retrieval.py b/tests/kilin/test_rag__retrieval.py index d3aba997..ad1188db 100644 --- a/tests/kilin/test_rag__retrieval.py +++ b/tests/kilin/test_rag__retrieval.py @@ -37,6 +37,7 @@ from tests.kilin._rag_support import ( _search_patches, _session, + _source_project, _turn, ) @@ -421,8 +422,9 @@ def setUp(self) -> None: """Create isolated state and arrange test-specific fixtures.""" temporary = TemporaryDirectory() self.addCleanup(temporary.cleanup) - self.root = Path(temporary.name) + self.root = Path(temporary.name).resolve() self.session = _session(self.root) + self.session.project = _source_project(self.root) self.session.project.source.mkdir() self.session.project.indexes.mkdir() self.first = self.session.project.source / "a.py" @@ -542,7 +544,12 @@ def test_html_text_does_not_create_code_graph_links(self) -> None: "example</button>", encoding="utf-8", ) - self.session.project.profile.extensions = (".py", ".html") + self.session.project = replace( + self.session.project, + profile=replace( + self.session.project.profile, extensions=(".py", ".html") + ), + ) with patch.object(rag, "project_type") as lookup: lookup.return_value.code_graph = "auto" chunks, code_graph = self.session._prepare_source( @@ -565,7 +572,12 @@ def test_html_without_visible_text_has_no_graph(self) -> None: '', encoding="utf-8", ) - self.session.project.profile.extensions = (".html",) + self.session.project = replace( + self.session.project, + profile=replace( + self.session.project.profile, extensions=(".html",) + ), + ) with patch.object(rag, "project_type") as lookup: lookup.return_value.code_graph = "auto" chunks, code_graph = self.session._prepare_source( @@ -581,7 +593,12 @@ def test_html_cache_representation_does_not_invalidate_python( page = self.session.project.source / "page.html" page.write_text("

Notes

", encoding="utf-8") - self.session.project.profile.extensions = (".py", ".html") + self.session.project = replace( + self.session.project, + profile=replace( + self.session.project.profile, extensions=(".py", ".html") + ), + ) report = self._report(["a.py", "page.html"]) self.session._prepare_source(self.embedding, report=report) with patch.object( @@ -759,7 +776,9 @@ def setUp(self) -> None: """Create isolated state and arrange test-specific fixtures.""" temporary = TemporaryDirectory() self.addCleanup(temporary.cleanup) - self.session = _session(Path(temporary.name)) + root = Path(temporary.name).resolve() + self.session = _session(root) + self.session.project = _source_project(root) self.session.project.indexes.mkdir() self.session.project.source.mkdir() self.embedding = FakeEmbeddings() diff --git a/tests/kilin/test_source_manifest.py b/tests/kilin/test_source_manifest.py index 65ea9da7..3fa910a0 100644 --- a/tests/kilin/test_source_manifest.py +++ b/tests/kilin/test_source_manifest.py @@ -223,7 +223,7 @@ def test_removal_and_reappearance_requires_explicit_resolution(self): self.assertEqual(reset.snapshot.manifest.relations, ()) self.assertEqual(self.role(self.a).role, "unassigned") - def test_rebind_does_not_reactivate_same_named_files(self): + def test_changed_root_is_rejected_without_reactivating_sources(self): self.edit(RoleEdit(self.a, "primary"), RelationEdit(self.c, self.a, "bibliography_for")) new = self.root / "new-corpus" @@ -231,25 +231,46 @@ def test_rebind_does_not_reactivate_same_named_files(self): for name in (self.a, self.c, "fresh.md"): (new / name).write_text("different\n", encoding="utf-8") self.change_root(new) - inspected = inspect_source_manifest(self.project) - self.assertFalse(inspected.binding_matches) - self.assertEqual(inspected.active_files, ()) - self.assertEqual(inspected.active_relations, ()) - with self.assertRaisesRegex(SourceManifestConflict, "rebind"): - self.reconcile() - result = self.edit(rebind=True) - self.assertEqual(result.snapshot.manifest.source_root.base, "absolute") - self.assertEqual( - {r.reason for r in result.snapshot.manifest.unresolved}, - {"root_rebound"}, - ) - self.assertEqual(self.role("fresh.md").role, "unassigned") - self.assertEqual(inspect_source_manifest(self.project) - .active_relations, ()) - self.edit(ResolveSourceEdit(self.a), ResolveSourceEdit(self.c)) - self.assertEqual(self.role(self.a).role, "unassigned") - self.assertEqual(read_source_manifest(self.project).manifest.relations, - ()) + before = {p: p.read_bytes() for p in self.root.rglob("*") + if p.is_file()} + for operation in (lambda: inspect_source_manifest(self.project), + self.reconcile): + with self.subTest(operation=operation): + with self.assertRaisesRegex(ValueError, "sources"): + operation() + with self.assertRaises(TypeError): + self.edit(rebind=True) + self.assertEqual(before, {p: p.read_bytes() + for p in self.root.rglob("*") + if p.is_file()}) + + def test_retired_root_bindings_and_format_are_rejected(self): + self.edit(RoleEdit(self.a, "primary")) + baseline = self.data() + invalid = [ + {"format": "kilin-source-manifest-v1"}, + {"unresolved": [{"path": self.a, "reason": "root_rebound"}]}, + ] + invalid.extend({"source_root": root} for root in ( + {"base": "absolute", "path": self.root.as_posix()}, + {"base": "project", "path": "."}, + {"base": "project", "path": "documents"}, + {"base": "project", "path": "./sources"}, + {"base": "project", "path": "sources/"}, + {"base": "project", "path": "sources", "old": True}, + )) + for changes in invalid: + with self.subTest(changes=changes): + self.write({**baseline, **changes}) + before = {p: p.read_bytes() for p in self.root.rglob("*") + if p.is_file()} + with self.assertRaises(ValueError): + read_source_manifest(self.project) + with self.assertRaises(ValueError): + self.reconcile() + self.assertEqual(before, {p: p.read_bytes() + for p in self.root.rglob("*") + if p.is_file()}) def test_relative_binding_survives_workspace_move(self): self.edit(RoleEdit(self.a, "primary")) @@ -591,27 +612,28 @@ def test_creation_failure_rolls_back_semantic_manifest_and_sources(self): kilin.initialize_project(destination, "code") self.assertFalse(destination.exists()) - def test_exact_root_exclusions_preserve_nested_and_external_names(self): + def test_canonical_scans_preserve_metadata_named_user_files(self): project = kilin.initialize_project(self.root / "project", "code") - nested = project.root / "nested" + nested = project.source / "nested" nested.mkdir() for name in (SOURCE_MANIFEST_FILE, ".source_manifest.json.lock"): (nested / name).write_text("nested user data", encoding="utf-8") lock = project.root / ".source_manifest.json.lock" lock.write_text("stable lock", encoding="utf-8") - report = scan_repository(project.root, extensions=[".json", ".lock"], + report = scan_repository(project.source, extensions=[".json", ".lock"], exclude_paths=source_scan_exclusions( - project.root, project.root)) + project.root, project.source)) self.assertEqual(set(report["selected_files"]), { "nested/source_manifest.json", "nested/.source_manifest.json.lock", }) - self.assertEqual(source_scan_exclusions(project.root, nested), ()) - outer = scan_repository(self.root, extensions=[".json", ".lock"], - exclude_paths=source_scan_exclusions( - project.root, self.root)) - self.assertNotIn("project/source_manifest.json", - outer["selected_files"]) - self.assertIn("project/nested/source_manifest.json", + for source in (project.root, nested, self.root): + with self.subTest(source=source): + with self.assertRaisesRegex(ValueError, "sources"): + source_scan_exclusions(project.root, source) + # The standalone scanner has no project-specific metadata policy. + outer = scan_repository(self.root, extensions=[".json", ".lock"]) + self.assertIn("project/source_manifest.json", outer["selected_files"]) + self.assertIn("project/sources/nested/source_manifest.json", outer["selected_files"]) def test_independent_format_owner_and_public_exports(self): diff --git a/tests/kilin/test_source_manifest__lifecycle.py b/tests/kilin/test_source_manifest__lifecycle.py index 4049d2e2..e292e158 100644 --- a/tests/kilin/test_source_manifest__lifecycle.py +++ b/tests/kilin/test_source_manifest__lifecycle.py @@ -310,7 +310,7 @@ def fail_second(source, destination, **options): "old.md") self.assertFalse((project.source / "c.md").exists()) - def test_changed_source_root_requires_rebinding(self): + def test_changed_source_root_is_rejected_without_rebinding(self): project = self.create(self.file("a.md")) self.edit(project, kilin.RoleEdit("a.md", "primary")) external = self.file("external/a.md").parent @@ -323,16 +323,19 @@ def test_changed_source_root_requires_rebinding(self): before = (project.root / SOURCE_MANIFEST_FILE).read_bytes() result = kilin.refresh_source_manifest(project) self.assertIsNotNone(result.error) - self.assertFalse(result.inspection.binding_matches) + self.assertIsNone(result.inspection) self.assertEqual(before, (project.root / SOURCE_MANIFEST_FILE).read_bytes()) - with self.assertRaisesRegex(ValueError, "source changed"): + with self.assertRaisesRegex(ValueError, "sources"): kilin.remove_workspace_sources(project, ["sources/a.md"]) - with self.assertRaisesRegex(ValueError, "source changed"): + with self.assertRaisesRegex(ValueError, "sources"): kilin.sync_project_sources(project) - reopened = kilin.open_project(project.root) - self.edit(reopened, rebind=True) - self.assertEqual(self.inspect(reopened).pending_roles, ("a.md",)) + with self.assertRaisesRegex(ValueError, "sources"): + kilin.open_project(project.root) + with self.assertRaises(TypeError): + self.edit(project, rebind=True) + self.assertEqual(before, + (project.root / SOURCE_MANIFEST_FILE).read_bytes()) self.assertIsNone(selected_source_file( project.root, external, Path("a.md"), {Path("a.md")}, )) diff --git a/tests/kilin/test_source_views.py b/tests/kilin/test_source_views.py index a8e4cd6e..3c01638c 100644 --- a/tests/kilin/test_source_views.py +++ b/tests/kilin/test_source_views.py @@ -427,14 +427,14 @@ def test_external_root_is_not_a_raw_read_authorization(self): ) inspected = replace(self.inspection, snapshot=snapshot, source_root=external) - view = resolve_source_view(inspected, self.inventory, - SourcePolicy(purpose="raw"), self.scope) - self.assertIn(UnavailableMember(self.a, "raw_unavailable"), - view.unavailable) + with self.assertRaisesRegex(ValueError, "project sources"): + resolve_source_view(inspected, self.inventory, + SourcePolicy(purpose="raw"), self.scope) + view = self.view() with patch.object(Path, "read_bytes", side_effect=AssertionError): - with self.assertRaisesRegex(SourceViewConflict, "workspace"): + with self.assertRaisesRegex(SourceViewConflict, "Source root"): read_source_bytes(self.project.root, self.root, view, self.a) - with self.assertRaisesRegex(SourceViewConflict, "rebind"): + with self.assertRaisesRegex(SourceViewConflict, "project sources"): resolve_source_view(replace(self.inspection, source_root=external), self.inventory) diff --git a/tests/kilin/test_workspace.py b/tests/kilin/test_workspace.py index 4cfa99f2..5fee81be 100644 --- a/tests/kilin/test_workspace.py +++ b/tests/kilin/test_workspace.py @@ -17,7 +17,6 @@ from __future__ import annotations -from dataclasses import replace from hashlib import sha256 import json from pathlib import Path @@ -151,10 +150,13 @@ def _records(self) -> list[dict[str, object]]: encoding="utf-8" ) ) - self.assertEqual(payload["version"], 1) + self.assertEqual(payload["version"], workspace.SOURCE_MANIFEST_VERSION) return payload["sources"] - def _write_records(self, records: object, version: object = 1) -> None: + def _write_records( + self, records: object, + version: object = workspace.SOURCE_MANIFEST_VERSION, + ) -> None: """Replace fixture provenance with an explicit payload. Parameters @@ -162,7 +164,7 @@ def _write_records(self, records: object, version: object = 1) -> None: records: object Candidate source-record collection. version: object, optional - Format version to write. Defaults to 1. + Format version to write. Defaults to the current generation. """ @@ -171,6 +173,23 @@ def _write_records(self, records: object, version: object = 1) -> None: encoding="utf-8", ) + def _tree_bytes(self) -> dict[str, bytes | None]: + """Capture source and workspace contents around rejected operations. + + Returns + ------- + dict[str, bytes | None] + Relative file contents and directory entries in the fixture. + + """ + + return { + path.relative_to(self.root).as_posix(): ( + path.read_bytes() if path.is_file() else None + ) + for path in self.root.rglob("*") + } + class TestWorkspaceInitialization(WorkspaceFixture): """Check project creation, managed ownership, and safe reopening. @@ -1545,9 +1564,10 @@ def test_invalid_manifest_structure_is_rejected(self) -> None: "{broken", "[]", "{}", - '{"version": 2, "sources": []}', - '{"version": 1, "sources": null}', - '{"version": 1, "sources": {}}', + '{"version": 1, "sources": []}', + '{"version": 3, "sources": []}', + '{"version": 2, "sources": null}', + '{"version": 2, "sources": {}}', ) for raw in invalid: with self.subTest(payload=raw): @@ -1579,10 +1599,14 @@ def test_invalid_destination_names_are_rejected(self) -> None: original = self._file("code.py") self._prepare([original]) - for name in ("", ".", "..", "../outside", "sub/file.py"): + valid = self._records()[0] + for name in ( + "", ".", "..", "../outside", "sub/file.py", "a\0b", + ".kilin_versions", + ): with self.subTest(name=name): self._write_records( - [{"original": str(original), "name": name}] + [{**valid, "name": name}] ) with self.assertRaisesRegex(ValueError, "source name"): self._prepare([]) @@ -1620,7 +1644,8 @@ def test_records_are_written_atomically_with_temporary_sibling( self.assertFalse((self.destination / "sources.json.tmp").exists()) raw = (self.destination / "sources.json").read_text(encoding="utf-8") self.assertTrue(raw.endswith("\n")) - self.assertEqual(json.loads(raw)["version"], 1) + self.assertEqual(json.loads(raw)["version"], + workspace.SOURCE_MANIFEST_VERSION) def test_failed_manifest_replacement_cleans_temporary_file( self, @@ -1678,9 +1703,10 @@ def test_duplicate_stored_names_must_be_rejected(self) -> None: first = self._file("one/code.py", "first = 1\n") second = self._file("two/code.py", "second = 2\n") self._prepare([first]) + valid = self._records()[0] self._write_records([ - {"original": str(first), "name": "code.py"}, - {"original": str(second), "name": "code.py"}, + valid, + {**valid, "original": str(second)}, ]) with self.assertRaisesRegex(ValueError, "duplicate|conflict"): self._prepare([second]) @@ -1690,9 +1716,10 @@ def test_duplicate_stored_originals_must_be_rejected(self) -> None: original = self._file("code.py") self._prepare([original]) + valid = self._records()[0] self._write_records([ - {"original": str(original), "name": "code.py"}, - {"original": str(original), "name": "duplicate.py"}, + valid, + {**valid, "name": "duplicate.py"}, ]) with self.assertRaisesRegex(ValueError, "Duplicate|conflict"): self._prepare([]) @@ -1702,6 +1729,7 @@ def test_invalid_stored_file_inventories_are_rejected(self) -> None: original = self._file("code.py") self._prepare([original]) + valid = self._records()[0] invalid = ( "code.py", None, @@ -1717,29 +1745,29 @@ def test_invalid_stored_file_inventories_are_rejected(self) -> None: ["./code.py"], ["folder\\code.py"], ["code.py", "code.py"], + ["code.py\0"], + ["other.py"], ) for inventory in invalid: with self.subTest(inventory=inventory): self._write_records([ - { - "original": str(original), - "name": "code.py", - "files": inventory, - } + {**valid, "files": inventory} ]) with self.assertRaisesRegex(ValueError, "inventory"): self._prepare([]) - def test_legacy_record_without_inventory_is_accepted(self) -> None: - """Old ownership records lacking files remain readable.""" + def test_legacy_record_without_inventory_is_rejected(self) -> None: + """Incomplete ownership records never acquire inferred fields.""" original = self._file("code.py") self._prepare([original]) self._write_records([ {"original": str(original), "name": "code.py"} ]) - self._prepare([]) - self.assertNotIn("files", self._records()[0]) + before = self._tree_bytes() + with self.assertRaises(ValueError): + self._prepare([]) + self.assertEqual(self._tree_bytes(), before) def test_inventory_removes_locally_deleted_retained_files( self, @@ -1800,7 +1828,7 @@ def test_cross_platform_drive_qualified_owner_is_rejected( original = self._file("code.py") self._prepare([original]) self._write_records([ - {"original": str(original), "name": "C:code.py"} + {**self._records()[0], "name": "C:code.py"} ]) with self.assertRaisesRegex(ValueError, "source name"): self._prepare([]) @@ -1811,7 +1839,7 @@ def test_empty_original_provenance_is_rejected(self) -> None: original = self._file("code.py") self._prepare([original]) self._write_records([ - {"original": " ", "name": "code.py"} + {**self._records()[0], "original": " "} ]) with self.assertRaisesRegex(ValueError, "source entry"): self._prepare([]) @@ -1824,7 +1852,7 @@ def test_invalid_cross_platform_source_names_are_rejected( original = self._file("code.py") self._prepare([original]) self._write_records([ - {"original": str(original), "name": "folder\\code.py"} + {**self._records()[0], "name": "folder\\code.py"} ]) with self.assertRaisesRegex(ValueError, "source name"): self._prepare([]) @@ -1893,15 +1921,16 @@ def test_configure_project_receives_caller_trace(self) -> None: trace.settings_changed.assert_called_once() def test_trace_events_are_not_emitted_for_failed_copies(self) -> None: - """Failed imports should not emit copied or completed events.""" + """Invalid selections are rejected before batch diagnostics begin.""" trace = MagicMock() with self.assertRaisesRegex(ValueError, "empty or exceeds"): self._prepare([self._file("empty.png", "")], trace=trace) self.assertEqual( [call.args[0] for call in trace.emit.call_args_list], - ["workspace.prepare.started"], + [], ) + trace.new_id.assert_not_called() def test_owned_creation_trace_and_selected_folder_inventory(self): diff --git a/tests/kilin/test_workspace__ownership.py b/tests/kilin/test_workspace__ownership.py new file mode 100644 index 00000000..8c2d83ca --- /dev/null +++ b/tests/kilin/test_workspace__ownership.py @@ -0,0 +1,396 @@ +"""Enforce exclusive source ownership across workspace and session APIs. + +Invalid ownership must be rejected before sources, semantic metadata, traces, +or conversation ownership change. Saved project and semantic records remain +available for read-only inspection independently of operational eligibility. + +""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from __future__ import annotations + +from functools import partial +import json +import os +from pathlib import Path +import stat +from tempfile import TemporaryDirectory +import unittest +from unittest.mock import Mock, patch, sentinel + +from kilin import project, rag, source_manifest, workspace +from kilin._source_ownership import source_ownership +from kilin.repository import build_repository_manifest, scan_repository +from kilin.trace_logging import TraceConfig +from tests.kilin._rag_support import _session + + +_INVALID_STATES = tuple( + (owner, state) + for owner in ("imports", "mirror") + for state in ("json", "version", "structure", "link", "dangling", "folder") +) + (("both", "conflict"),) + + +class TestWorkspaceOwnership(unittest.TestCase): + """Use ordinary local projects to check ownership at every boundary.""" + + def setUp(self) -> None: + temporary = TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.original = self.root / "original" / "a.py" + self.original.parent.mkdir() + self.original.write_text("original source\n", encoding="utf-8") + self.extra = self.root / "additional" / "a.py" + self.extra.parent.mkdir() + self.extra.write_text("additional source\n", encoding="utf-8") + self.project = workspace.prepare_sources_workspace( + [self.original], "code", self.root / "workspace" + ) + self.imports = self.project.root / "sources.json" + self.mirror = self.project.root / "source_snapshot.json" + self.valid_imports = json.loads(self.imports.read_text()) + self.valid_mirror = { + **build_repository_manifest(scan_repository( + self.original.parent, extensions=(".py",), + )), + "source_directory": str(self.original.parent), + } + self.saved_semantics = source_manifest.read_source_manifest( + self.project + ) + self.preview = source_manifest.preview_source_manifest(self.project) + self.report = scan_repository( + self.project.source, extensions=self.project.profile.extensions, + ) + + def _inventory(self) -> dict[str, tuple]: + """Capture entry kinds, contents, modes and modification times.""" + + entries = {} + for path in self.root.rglob("*"): + status = path.lstat() + name = path.relative_to(self.root).as_posix() + metadata = (stat.S_IMODE(status.st_mode), status.st_mtime_ns) + if stat.S_ISLNK(status.st_mode): + entries[name] = ("link", os.readlink(path), *metadata) + elif stat.S_ISREG(status.st_mode): + entries[name] = ("file", path.read_bytes(), *metadata) + else: + entries[name] = ("directory", *metadata) + return entries + + def _clear_ownership(self) -> None: + """Remove only metadata entries created by this disposable fixture.""" + + for path in (self.imports, self.mirror): + if path.is_symlink() or path.is_file(): + path.unlink() + elif path.exists(): + path.rmdir() + + def _damage(self, owner: str, state: str) -> None: + """Install one malformed, unsafe, or conflicting ownership state.""" + + self._clear_ownership() + if owner == "both": + self.imports.write_text(json.dumps(self.valid_imports)) + self.mirror.write_text(json.dumps(self.valid_mirror)) + return + path = self.imports if owner == "imports" else self.mirror + valid = self.valid_imports if owner == "imports" else self.valid_mirror + if state == "json": + path.write_text("{broken", encoding="utf-8") + elif state == "structure": + path.write_text("[]", encoding="utf-8") + elif state == "version": + payload = dict(valid) + key = "version" if owner == "imports" else "format_version" + payload[key] += 1 + path.write_text(json.dumps(payload), encoding="utf-8") + elif state == "folder": + path.mkdir() + else: + target = self.root / "outside-ownership.json" + if target.exists(): + target.unlink() + if state == "link": + target.write_text(json.dumps(valid), encoding="utf-8") + try: + path.symlink_to(target) + except (OSError, NotImplementedError): + self.skipTest("Creating symbolic links is unavailable") + + def _workspace_operations(self) -> dict[str, partial]: + """Return source consumers with real trace creation requested.""" + + return { + "add": partial( + workspace.add_project_sources, + self.project.root, [self.extra], + trace=TraceConfig(enabled=True), + ), + "preview": partial( + workspace.preview_project_sources, + self.project, [self.extra], + ), + "find": partial(workspace.find_source_changes, self.project), + "sync": partial(workspace.sync_project_sources, self.project), + "remove": partial( + workspace.remove_workspace_sources, + self.project, ["sources/a.py"], + ), + "versions": partial(workspace.list_source_versions, self.project), + "selection": partial( + workspace.include_explicit_imports, + self.project, self.report, + ), + } + + def _assert_rejected(self, operations: dict[str, partial]) -> None: + """Ensure rejection precedes every observable filesystem change.""" + + before = self._inventory() + for name, operation in operations.items(): + with self.subTest(operation=name): + with self.assertRaises((ValueError, OSError)): + operation() + self.assertEqual(self._inventory(), before) + + def test_invalid_import_ownership_blocks_all_source_operations(self): + """Malformed imports cannot mutate data or create tracing files.""" + + for owner, state in _INVALID_STATES: + if owner != "imports": + continue + with self.subTest(state=state): + self._damage(owner, state) + self._assert_rejected(self._workspace_operations()) + + def test_invalid_mirror_ownership_blocks_all_source_operations(self): + """Malformed mirrors cannot become unowned cumulative projects.""" + + for owner, state in _INVALID_STATES: + if owner != "mirror": + continue + with self.subTest(state=state): + self._damage(owner, state) + self._assert_rejected(self._workspace_operations()) + + def test_conflicting_valid_ownership_blocks_all_source_operations(self): + """Two individually valid manifests never grant shared ownership.""" + + self._damage("both", "conflict") + self._assert_rejected(self._workspace_operations()) + + def test_semantic_writes_reject_before_acquiring_the_writer_lock(self): + """A valid saved preview cannot authorize invalid source ownership.""" + + trace = Mock() + operations = { + "initialize": partial( + source_manifest.initialize_source_manifest, + self.project, trace=trace, + ), + "preview": partial( + source_manifest.preview_source_manifest, self.project, + ), + "apply": partial( + source_manifest.apply_source_manifest, + self.project, self.preview, trace=trace, + ), + } + for owner, state in _INVALID_STATES: + with self.subTest(owner=owner, state=state): + self._damage(owner, state) + self._assert_rejected(operations) + trace.emit.assert_not_called() + + def test_semantic_refresh_reports_invalid_ownership_without_writes(self): + """Failed reconciliation reports an error without a lock or trace.""" + + trace = Mock() + for owner, state in _INVALID_STATES: + with self.subTest(owner=owner, state=state): + self._damage(owner, state) + before = self._inventory() + result = source_manifest.refresh_source_manifest( + self.project, trace=trace, + ) + self.assertIsNotNone(result.error) + self.assertFalse(result.changed) + self.assertIsNone(result.inspection) + self.assertEqual(self._inventory(), before) + trace.emit.assert_not_called() + + def test_saved_records_remain_readable_with_invalid_ownership(self): + """Operational errors do not hide saved configuration or semantics.""" + + for owner, state in _INVALID_STATES: + with self.subTest(owner=owner, state=state): + self._damage(owner, state) + before = self._inventory() + opened = project.open_project(self.project.root) + self.assertEqual(opened, self.project) + self.assertEqual( + source_manifest.read_source_manifest(opened), + self.saved_semantics, + ) + self.assertEqual(self._inventory(), before) + + def test_rag_rejects_before_conversation_models_trace_or_progress(self): + """Invalid ownership cannot start an active answering session.""" + + progress = Mock() + with ( + patch.object(rag.RAGSession, "_resolve_conversation_path") as path, + patch.object(rag, "_conversation_trace") as trace, + patch.object(rag, "ConversationFileLock") as lock, + patch.object(rag, "EmbeddingSession") as embedding, + patch.object(rag, "ChatSession") as chat, + ): + for owner, state in _INVALID_STATES: + with self.subTest(owner=owner, state=state): + self._damage(owner, state) + before = self._inventory() + with self.assertRaises((ValueError, OSError)): + rag.RAGSession( + self.project.root, trace=TraceConfig(enabled=True), + progress_callback=progress, + ) + self.assertEqual(self._inventory(), before) + for observer in (path, trace, lock, embedding, chat, progress): + observer.assert_not_called() + + def test_rag_refresh_preserves_loaded_state_before_rejecting(self): + """Neither physical nor semantic refresh adopts invalid ownership.""" + + session = _session(self.project.root) + session.project = self.project + session._suggestion_pool = sentinel.suggestions + session.source_cards = sentinel.cards + session.source_card_vectors = sentinel.vectors + candidate = project.open_project(self.project.root) + protected = { + key: getattr(session, key) + for key in ( + "project", "chunks", "indexes", "turns", "chat_session", + "embedding_session", "source_cards", "source_card_vectors", + "_suggestion_pool", + ) + } + operations = { + "sources": partial(session.refresh_sources, candidate), + "semantics": partial(session.refresh_source_metadata), + "refresh_cards": partial(session.refresh_source_cards), + "regenerate_cards": partial(session.regenerate_source_cards), + } + with ( + patch.object(session, "_prepare_retrieval") as retrieval, + patch.object(session, "_prepare_source_cards") as cards, + patch.object(session, "_project_diagnostics") as diagnostics, + patch.object( + session, "_project_embedding_diagnostics", + ) as embedding_diagnostics, + patch.object(session, "question_suggestions") as suggestions, + patch.object(session, "welcome_prompts") as prompts, + ): + for owner, state in _INVALID_STATES: + with self.subTest(owner=owner, state=state): + self._damage(owner, state) + self._assert_rejected(operations) + for key, value in protected.items(): + self.assertIs(getattr(session, key), value) + for observer in ( + retrieval, cards, diagnostics, embedding_diagnostics, + suggestions, prompts, + ): + observer.assert_not_called() + + def test_valid_mirror_rejects_conversion_and_allows_inspection(self): + """Valid mirrors remain selectable without cumulative ownership.""" + + self._clear_ownership() + self.mirror.write_text(json.dumps(self.valid_mirror), encoding="utf-8") + before = self._inventory() + operations = self._workspace_operations() + self._assert_rejected({key: operations[key] + for key in ("add", "preview", "sync")}) + self.assertEqual(workspace.find_source_changes(self.project), { + "added": [], "changed": [], "deleted": [], "edited": [], + }) + self.assertEqual(workspace.list_source_versions(self.project), []) + self.assertIs(workspace.include_explicit_imports( + self.project, self.report, + ), self.report) + self.assertEqual(self._inventory(), before) + + def test_mirror_removal_keeps_ownership_and_sync_heals_only_owned(self): + """Local removal stays reversible without adopting untracked files.""" + + mirror = project.prepare_project_workspace( + self.original.parent, "code", self.root / "mirrors", + ) + manifest = mirror.root / "source_snapshot.json" + ownership = manifest.read_bytes() + manual = mirror.source / "manual.py" + manual.write_text("keep manual\n", encoding="utf-8") + original = self.original.read_bytes() + self.assertEqual(workspace.remove_workspace_sources( + mirror, ["sources/a.py"], + ), ["sources/a.py"]) + self.assertFalse((mirror.source / "a.py").exists()) + self.assertEqual(manifest.read_bytes(), ownership) + self.assertFalse((mirror.root / "sources.json").exists()) + project.synchronize_project_workspace( + self.original.parent, mirror.root, + ) + self.assertEqual((mirror.source / "a.py").read_bytes(), original) + self.assertEqual(manual.read_text(encoding="utf-8"), "keep manual\n") + self.assertEqual(manifest.read_bytes(), ownership) + self.assertEqual(self.original.read_bytes(), original) + + def test_manual_project_acquires_import_ownership_without_adopting_files( + self, + ): + """Explicit imports disambiguate existing untracked source copies.""" + + self._clear_ownership() + manual = self.project.source / "a.py" + before = manual.read_bytes() + self.assertIsNone(source_ownership(self.project.root)) + updated = workspace.add_project_sources( + self.project.root, [self.extra] + ) + records = json.loads(self.imports.read_text())["sources"] + self.assertEqual(len(records), 1) + self.assertEqual(records[0]["original"], str(self.extra)) + self.assertNotEqual(records[0]["name"], "a.py") + self.assertEqual(manual.read_bytes(), before) + self.assertEqual( + (updated.source / records[0]["name"]).read_bytes(), + self.extra.read_bytes(), + ) + self.assertEqual(source_ownership(updated.root), "imports") + self.assertFalse(self.mirror.exists()) + + def test_ownerless_removal_does_not_create_import_provenance(self): + """Manual deletion leaves the project without external ownership.""" + + self._clear_ownership() + original = self.original.read_bytes() + keep = self.project.source / "keep.py" + keep.write_text("keep\n", encoding="utf-8") + workspace.remove_workspace_sources(self.project, ["sources/a.py"]) + self.assertFalse((self.project.source / "a.py").exists()) + self.assertEqual(keep.read_text(encoding="utf-8"), "keep\n") + self.assertEqual(self.original.read_bytes(), original) + self.assertIsNone(source_ownership(self.project.root)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/test_workspace__source_changes.py b/tests/kilin/test_workspace__source_changes.py index 8fd2c641..828850df 100644 --- a/tests/kilin/test_workspace__source_changes.py +++ b/tests/kilin/test_workspace__source_changes.py @@ -312,12 +312,12 @@ def test_removed_workspace_copy_is_not_recreated(self) -> None: self.assertFalse((self.copies / "repository/a.py").exists()) def test_files_without_stamps_are_skipped(self) -> None: - """Copies imported before stamps existed cannot be compared.""" + """Valid partial inventories have no baseline for unstamped copies.""" manifest = self.project.root / "sources.json" payload = json.loads(manifest.read_text(encoding="utf-8")) for record in payload["sources"]: - del record["stamps"] + record["stamps"] = {} manifest.write_text(json.dumps(payload), encoding="utf-8") self._write(self.folder / "a.py", "x = 22\n", 2) self._changes() diff --git a/tests/kilin/test_workspace__source_management.py b/tests/kilin/test_workspace__source_management.py index 096b5afe..8037e063 100644 --- a/tests/kilin/test_workspace__source_management.py +++ b/tests/kilin/test_workspace__source_management.py @@ -162,8 +162,8 @@ def test_reimport_renews_only_replaced_stamps(self) -> None: ) self.assertEqual(after["kept.py"], before["kept.py"]) - def test_manifest_without_stamps_is_still_accepted(self) -> None: - """Older manifests open, and the next import adds stamps.""" + def test_manifest_without_stamps_is_rejected(self) -> None: + """A required stamp mapping is never inferred on subsequent import.""" original = self._file("note.md") prepare_sources_workspace([original], "code", self.destination) @@ -173,10 +173,16 @@ def test_manifest_without_stamps_is_still_accepted(self) -> None: manifest.write_text(json.dumps(payload), encoding="utf-8") open_project(self.destination) - add_project_sources(self.destination, []) + before = manifest.read_bytes() + snapshot = self.destination / "sources/note.md" + copied = snapshot.read_bytes() + for inputs in ([], [original]): + with self.subTest(inputs=inputs): + with self.assertRaisesRegex(ValueError, "stamps"): + add_project_sources(self.destination, inputs) + self.assertEqual(manifest.read_bytes(), before) + self.assertEqual(snapshot.read_bytes(), copied) self.assertNotIn("stamps", self._records()[0]) - add_project_sources(self.destination, [original]) - self.assertEqual(set(self._records()[0]["stamps"]), {"note.md"}) def test_invalid_stamps_are_rejected(self) -> None: """Stamps must be non-negative integers for tracked files only.""" @@ -263,11 +269,13 @@ def test_external_source_projects_cannot_delete_original_files( ) original = external / "analysis.py" original.write_text("number = 1\n", encoding="utf-8") - project = open_project(external) - self.assertEqual(project.source, external) - with self.assertRaisesRegex(ValueError, "managed sources"): + before = profile.read_bytes() + with self.assertRaisesRegex(ValueError, "project.source"): + open_project(external) + with self.assertRaisesRegex(ValueError, "project.source"): remove_workspace_sources(project, ["sources/analysis.py"]) - self.assertTrue(original.is_file()) + self.assertEqual(profile.read_bytes(), before) + self.assertEqual(original.read_text(), "number = 1\n") def test_removed_explicit_file_is_no_longer_scanned(self) -> None: """RAG selection tracks only remaining direct import snapshots.""" diff --git a/tests/kilin/test_workspace__source_schema.py b/tests/kilin/test_workspace__source_schema.py new file mode 100644 index 00000000..d7fe6aec --- /dev/null +++ b/tests/kilin/test_workspace__source_schema.py @@ -0,0 +1,672 @@ +"""Validate the current managed-source ownership format at API boundaries. + +Every ownership-dependent operation rejects unsupported or incomplete records +before changing source copies, originals, or project metadata. Empty and +partial inventories remain valid states after explicit operations or failures. + +""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from __future__ import annotations + +from copy import deepcopy +from functools import partial +from hashlib import sha256 +import json +from pathlib import Path +from tempfile import TemporaryDirectory +import unittest +from unittest.mock import Mock, patch + +from kilin import workspace +from kilin.repository import scan_repository +from kilin.trace_logging import TraceConfig + + +class TestSourceOwnershipSchema(unittest.TestCase): + """Exercise schema rejection without granting ownership by inference.""" + + def setUp(self) -> None: + temporary = TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.original = self.root / "inputs" + self.original.mkdir() + for name in ("a.py", "b.py"): + (self.original / name).write_text(name, encoding="utf-8") + self.extra = self.root / "extra.py" + self.extra.write_text("extra", encoding="utf-8") + self.project = workspace.prepare_sources_workspace( + [self.original], "code", self.root / "workspace" + ) + self.manifest = self.project.root / "sources.json" + self.valid = json.loads(self.manifest.read_text(encoding="utf-8")) + + def _tree(self) -> dict[str, bytes | None]: + """Record all fixture files and directories around an operation.""" + + return { + path.relative_to(self.root).as_posix(): ( + path.read_bytes() if path.is_file() else None + ) + for path in self.root.rglob("*") + } + + def _save(self, payload: dict[str, object]) -> None: + """Install one deliberate on-disk fixture without normalizing it.""" + + self.manifest.write_text(json.dumps(payload), encoding="utf-8") + + def _write_sources( + self, folder: Path, names: tuple[str, ...], + ) -> list[Path]: + """Create exact test spellings when the filesystem supports them.""" + + folder.mkdir() + try: + for name in names: + path = folder / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("selected", encoding="utf-8") + except OSError as error: + self.skipTest(f"Filesystem cannot represent test names: {error}") + actual = {path.relative_to(folder).as_posix() + for path in folder.rglob("*") if path.is_file()} + if actual != set(names): + self.skipTest("Filesystem merges the requested test spellings.") + return [folder / name for name in names] + + def _reject_at_boundaries(self, message: str) -> None: + """Check every ownership consumer preserves the complete tree.""" + + operations = { + "import": partial( + workspace.add_project_sources, + self.project.root, [self.extra], + trace=TraceConfig(enabled=True, failure_policy="raise"), + ), + "preview": partial( + workspace.preview_project_sources, + self.project, [self.extra], + ), + "changes": partial(workspace.find_source_changes, self.project), + "sync": partial(workspace.sync_project_sources, self.project), + "remove": partial( + workspace.remove_workspace_sources, self.project, + ["sources/inputs/a.py"], + ), + "versions": partial(workspace.list_source_versions, self.project), + "selection": partial( + workspace.include_explicit_imports, self.project, + {"entries": [], "selected_files": []}, + ), + } + before = self._tree() + for name, operation in operations.items(): + with self.subTest(operation=name): + with self.assertRaisesRegex(ValueError, message): + operation() + self.assertEqual(self._tree(), before) + + def test_every_current_field_is_required(self) -> None: + """No operation supplies defaults for absent ownership fields.""" + + for field in ("original", "name", "kind", "files", "stamps"): + with self.subTest(field=field): + payload = deepcopy(self.valid) + del payload["sources"][0][field] + self._save(payload) + self._reject_at_boundaries("workspace source") + + def test_unknown_fields_are_rejected(self) -> None: + """Unexpected persisted fields cannot acquire an implicit meaning.""" + + for container in ("manifest", "source"): + with self.subTest(container=container): + payload = deepcopy(self.valid) + target = payload if container == "manifest" else ( + payload["sources"][0] + ) + target["legacy"] = True + self._save(payload) + self._reject_at_boundaries("workspace source") + + def test_previous_and_coerced_versions_are_rejected(self) -> None: + """Only exact integer generation two accepts ownership records.""" + + for version in (1, 0, 3, True, False, 2.0, "2", None): + with self.subTest(version=version): + payload = deepcopy(self.valid) + payload["version"] = version + self._save(payload) + self._reject_at_boundaries("format version") + + def test_duplicate_json_keys_are_rejected_at_every_depth(self) -> None: + """Repeated manifest, record, or stamp fields are not normalized.""" + + valid = json.dumps(self.valid) + for field in ('"version": 2', '"kind": "folder"', '"size": 4'): + with self.subTest(field=field): + self.assertIn(field, valid) + raw = valid.replace(field, f"{field}, {field}", 1) + self.manifest.write_text(raw, encoding="utf-8") + self._reject_at_boundaries("Duplicate workspace source") + + def test_invalid_kinds_are_rejected(self) -> None: + """Current disk contents never repair missing or invalid kinds.""" + + for kind in (None, "directory", "FILE", "", True, 1, [], {}): + with self.subTest(kind=kind): + payload = deepcopy(self.valid) + payload["sources"][0]["kind"] = kind + self._save(payload) + self._reject_at_boundaries("source kind") + + def test_ancestor_and_descendant_cannot_both_be_files(self) -> None: + """A file inventory cannot simultaneously own a parent directory.""" + + payload = deepcopy(self.valid) + payload["sources"][0].update(files=["a", "a/b.py"], stamps={}) + self._save(payload) + self._reject_at_boundaries("files inventory") + + def test_noncanonical_record_paths_are_rejected(self) -> None: + """Every path field shares canonical semantic identity rules.""" + + for field in ("name", "files", "version_file", "version_path"): + for value in ( + "a.py.", "a.py ", "notes:data.py", "a\t.py", "a\ud800.py", + ): + with self.subTest(field=field, value=value): + payload = deepcopy(self.valid) + record = payload["sources"][0] + if field == "name": + record["name"] = value + elif field == "files": + record.update(files=[value], stamps={}) + else: + record["versions"] = [{ + "file": value if field == "version_file" + else "a.py", + "path": ".kilin_versions/inputs/" + ( + value if field == "version_path" else "a.py" + ), + "sha256": "0" * 64, + }] + self._save(payload) + self._reject_at_boundaries("workspace source") + + def test_effective_record_aliases_are_rejected(self) -> None: + """Names, directory prefixes, and archives cannot alias each other.""" + + for field in ("name", "files", "versions"): + for first, second in ( + ("A.py", "a.py"), ("é.py", "e\u0301.py"), + ("DIR/a.py", "dir/b.py"), + ): + if field == "name" and "/" in first: + continue + with self.subTest(field=field, paths=(first, second)): + payload = deepcopy(self.valid) + record = payload["sources"][0] + if field == "name": + record["name"] = first + other = deepcopy(record) + other.update(name=second, original="/other") + payload["sources"].append(other) + elif field == "files": + record.update(files=[first, second], stamps={}) + else: + record["versions"] = [{ + "file": "a.py", + "path": f".kilin_versions/inputs/{name}", + "sha256": "0" * 64, + } for name in (first, second)] + self._save(payload) + self._reject_at_boundaries("Source path alias") + payload = deepcopy(self.valid) + payload["sources"][0]["name"] = ".KILIN_VERSIONS" + self._save(payload) + self._reject_at_boundaries("Source path alias") + + def test_retained_paths_cannot_own_another_versions_parent(self): + """History cannot claim a path both as a file and as a directory.""" + + payload = deepcopy(self.valid) + payload["sources"][0]["versions"] = [{ + "file": "a.py", "path": f".kilin_versions/inputs/{name}", + "sha256": "0" * 64, + } for name in ("old.py", "old.py/child.py")] + self._save(payload) + self._reject_at_boundaries("source version paths") + + def test_effective_paths_obey_the_shared_length_bound(self) -> None: + """An individually valid filename can exceed its managed identity.""" + + payload = deepcopy(self.valid) + payload["sources"][0].update(files=["a" * 4090], stamps={}) + self._save(payload) + self._reject_at_boundaries("workspace source path") + + def test_import_preflights_every_selected_path_before_tracing(self): + """A later unsafe selection cannot leave earlier copies or logs.""" + + candidates = ( + ("notes:data.py",), ("nested./a.py",), + ("A.py", "a.py"), ("é.py", "e\u0301.py"), + ("DIR/a.py", "dir/b.py"), + ) + for number, paths in enumerate(candidates): + with self.subTest(paths=paths): + folder = self.root / f"candidate_{number}" + self._write_sources(folder, paths) + before = self._tree() + for operation in ( + partial(workspace.preview_project_sources, + self.project, [self.extra, folder]), + partial( + workspace.add_project_sources, self.project.root, + [self.extra, folder], trace=TraceConfig( + enabled=True, failure_policy="raise" + ), + ), + ): + with self.assertRaises(ValueError): + operation() + self.assertEqual(self._tree(), before) + + def test_new_source_names_cannot_alias_allocated_names(self) -> None: + """Distinct source inputs must have distinct effective identities.""" + + for number, names in enumerate(( + ("A.py", "a.py"), ("é.py", "e\u0301.py"), + )): + with self.subTest(names=names): + folder = self.root / f"direct_{number}" + sources = self._write_sources(folder, names) + before = self._tree() + for operation in ( + partial(workspace.preview_project_sources, + self.project, sources), + partial(workspace.add_project_sources, + self.project.root, sources), + ): + with self.assertRaisesRegex(ValueError, "path alias"): + operation() + self.assertEqual(self._tree(), before) + + def test_new_paths_cannot_alias_untracked_or_absent_owned_copies(self): + """Effective ownership includes missing copies and local spellings.""" + + for mode in ("untracked", "absent"): + with self.subTest(mode=mode): + candidate = "new.py" if mode == "untracked" else "A.py" + source = self.original / candidate + if source.exists(): + self.skipTest("Filesystem merges source name case.") + source.write_text("new original", encoding="utf-8") + if mode == "untracked": + target = self.project.source / "inputs/NEW.py" + target.write_text("local content", encoding="utf-8") + if (target.parent / candidate).exists(): + self.skipTest("Filesystem merges source name case.") + else: + (self.project.source / "inputs/a.py").unlink() + before = self._tree() + trace = Mock() + operations = ( + partial(workspace.add_project_sources, + self.project.root, [self.original], + selected_files={str(self.original): [candidate]}, + trace=trace), + partial(workspace.sync_project_sources, self.project, + decisions={ + f"sources/inputs/{candidate}": "import" + }, + trace=trace), + ) + for operation in operations: + with self.assertRaisesRegex(ValueError, "path alias"): + operation() + self.assertEqual(self._tree(), before) + self.assertEqual(trace.mock_calls, []) + source.unlink() + if mode == "untracked": + target.unlink() + + def test_sync_preflights_new_paths_before_applying_any_decision(self): + """Selected new originals cannot publish invalid ownership records.""" + + for number, names in enumerate(( + ("notes:data.py",), ("New.py", "new.py"), + ("é.py", "e\u0301.py"), + )): + with self.subTest(names=names): + folder = self.original / f"new_{number}" + self._write_sources(folder, names) + decisions = {"sources/inputs/a.py": "replace"} + for name in names: + decisions[f"sources/inputs/new_{number}/{name}"] = "import" + (self.original / "a.py").write_text( + "updated", encoding="utf-8" + ) + before = self._tree() + trace = Mock() + with self.assertRaises(ValueError): + workspace.sync_project_sources( + self.project, decisions=decisions, trace=trace + ) + self.assertEqual(self._tree(), before) + self.assertEqual(trace.mock_calls, []) + + def test_sync_can_replace_a_deleted_owned_file_with_a_directory(self): + """A tracked removal can clear the parent of an explicitly new file.""" + + node = self.original / "node.py" + node.write_text("old file", encoding="utf-8") + workspace.add_project_sources(self.project.root, [self.original]) + node.unlink() + node.mkdir() + (node / "child.py").write_text("new child", encoding="utf-8") + before = self._tree() + trace = Mock() + with self.assertRaisesRegex(ValueError, "file destinations"): + workspace.sync_project_sources(self.project, decisions={ + "sources/inputs/node.py/child.py": "import", + }, trace=trace) + self.assertEqual(self._tree(), before) + self.assertEqual(trace.mock_calls, []) + result = workspace.sync_project_sources(self.project, decisions={ + "sources/inputs/node.py": "delete", + "sources/inputs/node.py/child.py": "import", + }) + self.assertEqual(result["deleted"], ["sources/inputs/node.py"]) + self.assertEqual(result["added"], ["sources/inputs/node.py/child.py"]) + copy = self.project.source / "inputs/node.py/child.py" + self.assertEqual(copy.read_bytes(), b"new child") + record = workspace._read_records(self.manifest)[0] + self.assertNotIn("node.py", record["files"]) + self.assertIn("node.py/child.py", record["files"]) + + def test_sync_cannot_clear_an_untracked_parent_file(self) -> None: + """New descendants cannot displace local files without ownership.""" + + node = self.original / "node.py" + node.mkdir() + (node / "child.py").write_text("new child", encoding="utf-8") + (self.project.source / "inputs/node.py").write_text( + "local file", encoding="utf-8" + ) + before = self._tree() + trace = Mock() + with self.assertRaisesRegex(ValueError, "parent is not a directory"): + workspace.sync_project_sources(self.project, decisions={ + "sources/inputs/node.py/child.py": "import", + }, trace=trace) + self.assertEqual(self._tree(), before) + self.assertEqual(trace.mock_calls, []) + + def test_version_storage_is_preflighted_before_replacing_copies(self): + """A reserved-directory alias cannot leave an earlier replacement.""" + + for name in ("a.py", "b.py"): + (self.original / name).write_text("updated", encoding="utf-8") + (self.project.source / ".KILIN_VERSIONS").mkdir() + before = self._tree() + trace = Mock() + with self.assertRaisesRegex(ValueError, "path alias"): + workspace.sync_project_sources(self.project, decisions={ + "sources/inputs/a.py": "replace", + "sources/inputs/b.py": "keep_both", + }, trace=trace) + self.assertEqual(self._tree(), before) + self.assertEqual(trace.mock_calls, []) + + def test_missing_version_paths_remain_reserved_for_their_history(self): + """A newly retained copy cannot reuse a saved but absent version.""" + + payload = deepcopy(self.valid) + digest = sha256(b"a.py").hexdigest() + saved = { + "file": "a.py", + "path": f".kilin_versions/inputs/a__v0002__{digest[:12]}.py", + "sha256": digest, + } + payload["sources"][0]["versions"] = [saved] + self._save(payload) + (self.original / "a.py").write_text("updated", encoding="utf-8") + workspace.sync_project_sources(self.project, decisions={ + "sources/inputs/a.py": "keep_both", + }) + record = workspace._read_records(self.manifest)[0] + self.assertEqual(record["versions"][0], saved) + self.assertEqual(len(record["versions"]), 2) + self.assertNotEqual(record["versions"][1]["path"], saved["path"]) + self.assertFalse((self.project.source / saved["path"]).exists()) + retained = self.project.source / record["versions"][1]["path"] + self.assertEqual(retained.read_bytes(), b"a.py") + + def test_new_archive_cannot_descend_through_a_missing_saved_version(self): + """Absent history still owns its path as a file, never a directory.""" + + folder = self.original / "nested" + folder.mkdir() + (folder / "a.py").write_text("nested", encoding="utf-8") + workspace.add_project_sources(self.project.root, [self.original]) + payload = json.loads(self.manifest.read_text(encoding="utf-8")) + payload["sources"][0]["versions"] = [{ + "file": "nested", "path": ".kilin_versions/inputs/nested", + "sha256": "0" * 64, + }] + self._save(payload) + (folder / "a.py").write_text("updated", encoding="utf-8") + before = self._tree() + trace = Mock() + with self.assertRaisesRegex(ValueError, "file destinations"): + workspace.sync_project_sources(self.project, decisions={ + "sources/inputs/nested/a.py": "keep_both", + }, trace=trace) + self.assertEqual(self._tree(), before) + self.assertEqual(trace.mock_calls, []) + + def test_version_collision_after_preflight_preserves_untracked_bytes(self): + """An occupied archive is neither adopted nor removed on failure.""" + + original_archive = workspace._archive_source_version + occupied = [] + + def reserve_untracked(root, version, copy): + path = root / "sources" / version["path"] + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"untracked version") + occupied.append(path) + return original_archive(root, version, copy) + + before = self.manifest.read_bytes() + (self.original / "a.py").write_text("updated", encoding="utf-8") + with patch("kilin.workspace._archive_source_version", + side_effect=reserve_untracked): + with self.assertRaises(FileExistsError): + workspace.sync_project_sources(self.project, decisions={ + "sources/inputs/a.py": "keep_both", + }) + self.assertEqual(occupied[0].read_bytes(), b"untracked version") + self.assertEqual(self.manifest.read_bytes(), before) + self.assertEqual((self.project.source / "inputs/a.py").read_bytes(), + b"a.py") + + def test_only_selected_effective_paths_participate_in_alias_checks(self): + """A valid subset and independent source folders keep their names.""" + + first = self.root / "first" + second = self.root / "second" + self._write_sources(first, ("A.py", "a.py")) + self._write_sources(second, ("a.py", "e\u0301.py")) + workspace.add_project_sources( + self.project.root, [first, second], selected_files={ + str(first): ["A.py"], str(second): ["a.py", "e\u0301.py"], + }, + ) + records = workspace._read_records(self.manifest) + self.assertEqual(records[1]["files"], ["A.py"]) + self.assertEqual(records[2]["files"], ["a.py", "e\u0301.py"]) + self.assertFalse((self.project.source / "first/a.py").exists()) + self.assertTrue((self.project.source / "second/e\u0301.py").is_file()) + + def test_empty_inventory_with_optional_versions_is_valid(self) -> None: + """A current record may retain an origin without copied files.""" + + for versions in (None, []): + with self.subTest(versions=versions): + payload = deepcopy(self.valid) + record = payload["sources"][0] + record.update(files=[], stamps={}) + if versions is not None: + record["versions"] = versions + self._save(payload) + before = self._tree() + self.assertEqual( + workspace._read_records(self.manifest), [record] + ) + self.assertEqual(self._tree(), before) + + def test_missing_originals_and_copies_do_not_invalidate_schema(self): + """Recorded identity does not depend on either live filesystem tree.""" + + (self.original / "a.py").unlink() + (self.original / "b.py").unlink() + self.original.rmdir() + (self.project.source / "inputs/a.py").unlink() + before = self._tree() + self.assertEqual( + workspace._read_records(self.manifest), self.valid["sources"] + ) + changes = workspace.find_source_changes(self.project) + self.assertEqual(changes["deleted"], ["sources/inputs/b.py"]) + self.assertEqual(self._tree(), before) + + def test_partial_stamps_survive_preservation_until_explicit_copy(self): + """A preserved copy cannot supply its own missing import baseline.""" + + payload = deepcopy(self.valid) + record = payload["sources"][0] + del record["stamps"]["a.py"] + self._save(payload) + copied = self.project.source / "inputs/a.py" + copied.write_text("local edit", encoding="utf-8") + workspace.add_project_sources(self.project.root, [self.original]) + observed = workspace._read_records(self.manifest)[0] + self.assertEqual(observed["files"], ["a.py", "b.py"]) + self.assertEqual(observed["stamps"], record["stamps"]) + self.assertEqual(copied.read_text(encoding="utf-8"), "local edit") + + workspace.add_project_sources( + self.project.root, [self.original], replace_existing=True, + selected_files={str(self.original): ["a.py"]}, + ) + observed = workspace._read_records(self.manifest)[0] + self.assertEqual(set(observed["stamps"]), {"a.py", "b.py"}) + self.assertEqual(observed["stamps"]["b.py"], record["stamps"]["b.py"]) + self.assertEqual( + copied.read_bytes(), (self.original / "a.py").read_bytes() + ) + + def test_failed_first_stamp_persists_a_complete_current_record(self): + """A completed copy retains ownership even if stamping then fails.""" + + with patch("kilin.workspace._copy_stamp", side_effect=OSError("stat")): + with self.assertRaisesRegex(OSError, "stat"): + workspace.add_project_sources( + self.project.root, [self.extra] + ) + records = workspace._read_records(self.manifest) + added = next(row for row in records if row["name"] == "extra.py") + self.assertEqual(added, { + "original": str(self.extra), "name": "extra.py", "kind": "file", + "files": ["extra.py"], "stamps": {}, + }) + self.assertEqual((self.project.source / "extra.py").read_bytes(), + self.extra.read_bytes()) + workspace.add_project_sources(self.project.root, [self.extra]) + self.assertEqual(workspace._read_records(self.manifest)[1], added) + + def test_reimport_rejects_changed_original_kind_before_copying(self): + """A replaced original cannot redefine the stored file identity.""" + + workspace.add_project_sources(self.project.root, [self.extra]) + self.extra.unlink() + self.extra.mkdir() + (self.extra / "other.py").write_text("replacement", encoding="utf-8") + for populated in (True, False): + if not populated: + (self.extra / "other.py").unlink() + before = self._tree() + for operation in ( + partial(workspace.preview_project_sources, + self.project, [self.extra]), + partial(workspace.add_project_sources, + self.project.root, [self.extra], trace=TraceConfig( + enabled=True, failure_policy="raise" + )), + ): + with self.assertRaisesRegex(ValueError, "source kind changed"): + operation() + self.assertEqual(self._tree(), before) + + def test_folder_record_never_selects_a_replacement_as_a_direct_file(self): + """Explicit selection follows the saved kind rather than disk shape.""" + + folder = self.project.source / "inputs" + for path in folder.iterdir(): + path.unlink() + folder.rmdir() + folder.write_text("untracked replacement", encoding="utf-8") + report = scan_repository( + self.project.source, extensions=self.project.profile.extensions, + ) + selected = workspace.include_explicit_imports(self.project, report) + self.assertNotIn("inputs", selected["selected_files"]) + + def test_direct_versions_survive_without_original_or_active_copy(self): + """Historical file identity remains explicit after active removal.""" + + workspace.add_project_sources(self.project.root, [self.extra]) + self.extra.write_text("updated source", encoding="utf-8") + workspace.sync_project_sources(self.project, decisions={ + "sources/extra.py": "keep_both", + }) + versions = workspace.list_source_versions(self.project) + self.assertEqual(len(versions), 1) + workspace.remove_workspace_sources(self.project, ["sources/extra.py"]) + self.extra.unlink() + records = workspace._read_records(self.manifest) + retained = next(row for row in records if row["name"] == "extra.py") + self.assertEqual(retained["kind"], "file") + self.assertEqual(retained["files"], []) + self.assertEqual(retained["stamps"], {}) + self.assertEqual( + workspace.list_source_versions(self.project), versions + ) + self.assertEqual( + (self.project.root / versions[0]["version"]).read_bytes(), b"extra" + ) + + def test_direct_version_cannot_claim_another_original_filename(self): + """A file record cannot acquire another file's retained history.""" + + workspace.add_project_sources(self.project.root, [self.extra]) + payload = json.loads(self.manifest.read_text(encoding="utf-8")) + payload["sources"][1]["versions"] = [{ + "file": "unrelated.py", + "path": ".kilin_versions/extra.py/history.py", + "sha256": "0" * 64, + }] + self._save(payload) + self._reject_at_boundaries("version file") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/tools/_shared/test__source_access.py b/tests/kilin/tools/_shared/test__source_access.py index c4f2b28e..66f45974 100644 --- a/tests/kilin/tools/_shared/test__source_access.py +++ b/tests/kilin/tools/_shared/test__source_access.py @@ -69,6 +69,46 @@ def test_only_selected_regular_workspace_files(self) -> None: allowed), paper.resolve(), ) + def test_workspace_ancestor_alias_preserves_source_access(self) -> None: + """Resolve workspace identity without authorizing linked sources.""" + + with TemporaryDirectory() as temporary: + outer = Path(temporary).resolve() + root = outer / "physical" / "project" + source = root / "sources" + source.mkdir(parents=True) + relative = Path("paper.tex") + paper = source / relative + paper.write_text("Text", encoding="utf-8") + alias = outer / "alias" + try: + alias.symlink_to(root.parent, target_is_directory=True) + except (NotImplementedError, OSError): + self.skipTest("Symbolic links are unavailable") + alias_root = alias / root.name + for project_path in (root, alias_root): + for source_path in (source, alias_root / "sources"): + with self.subTest(root=project_path, source=source_path): + self.assertEqual(selected_source_file( + project_path, source_path, relative, {relative}, + ), paper.resolve()) + external = outer / "elsewhere" / "sources" + external.mkdir(parents=True) + (external / relative).write_text("Private", encoding="utf-8") + self.assertIsNone(selected_source_file( + alias_root, external, relative, {relative}, + )) + alternate = root / "documents" + alternate.symlink_to(source, target_is_directory=True) + self.assertIsNone(selected_source_file( + root, alternate, relative, {relative}, + )) + source.rename(root / "real_sources") + source.symlink_to(root / "real_sources", target_is_directory=True) + self.assertIsNone(selected_source_file( + alias_root, alias_root / "sources", relative, {relative}, + )) + def test_external_saved_source_root_is_not_authorized(self) -> None: with TemporaryDirectory() as temporary: outer = Path(temporary) diff --git a/tutorials/140_project_chat.ipynb b/tutorials/140_project_chat.ipynb index e5315ead..115bd307 100644 --- a/tutorials/140_project_chat.ipynb +++ b/tutorials/140_project_chat.ipynb @@ -156,7 +156,7 @@ "KíLín never writes project settings or indexes into the original source\n", "folder. It mirrors the selected files into a **managed workspace** under\n", "`sandbox/`. For example, a folder named `my_sources` becomes\n", - "`sandbox/project_my_sources/my_sources`, with `indexes/`, `logs/`, `profile.ini`,\n", + "`sandbox/project_my_sources/sources`, with `indexes/`, `logs/`, `profile.ini`,\n", "and `source_snapshot.json` beside the copied source folder.\n" ] }, @@ -194,7 +194,7 @@ "Later imports are cumulative; do not call the creation function again on the\n", "same destination. See [Project workspaces](../docs/project_workspaces.md).\n", "\n", - "Both mirror creation and explicit synchronization accept an `on_organization` observer. It reports the accepted semantic state after the physical batch without prompting. New files receive saved defaults, removed files become unresolved, and same-path replacements retain their assignments. The report also identifies proposals and pending roles; missing metadata and changed root bindings require explicit recovery." + "Both mirror creation and explicit synchronization accept an `on_organization` observer. It reports the accepted semantic state after the physical batch without prompting. New files receive saved defaults, removed files become unresolved, and same-path replacements retain their assignments. The report also identifies proposals and pending roles; missing semantic metadata requires explicit initialization. Noncanonical source roots and unsupported metadata are rejected without rebinding or migration." ] }, { @@ -614,7 +614,7 @@ "\n", "The accepted semantic `source_manifest.json` is distinct from physical index state and mirror provenance. After manual source arrivals, use `kilin.refresh_source_manifest(project)` (and `session.refresh_sources(project)` when the physical indexes need updating). After a role/link-only edit through preview/apply, `session.refresh_source_metadata()` returns a new inspection and refreshes headings from saved data, without embedding or card generation. See [Accepted source organization](../docs/source_manifest.md).\n", "\n", - "If an older workspace lacks semantic metadata, opening it does not silently\n", + "If a current workspace lacks semantic metadata, opening it does not silently\n", "initialize that state. Explicitly initialize it through `kilin.initialize_source_manifest(project)`\n", "or the GUI editor and review its assignments. For a model-free example of\n", "roles, shared supporting files and scoped views, see\n", diff --git a/tutorials/160_project_types.ipynb b/tutorials/160_project_types.ipynb index 1ba92cd7..a84ba95b 100644 --- a/tutorials/160_project_types.ipynb +++ b/tutorials/160_project_types.ipynb @@ -43,7 +43,7 @@ "`ProjectType` configurations. Use `config.id` and `profile.type_id`;\n", "`kilin.project_type_ids()` lists usable distribution and user types.\n", "`kilin.project_type_catalog()` retains availability diagnostics.\n", - "A project type does not choose the source folder: every new project keeps\n", + "A project type does not choose the source folder: every project keeps\n", "its sources in `sources/`, whether it is created with `initialize_project()`\n", "or a managed workspace, which can also start empty at an explicit location.\n", "\n", From 7fed0700d1d3d9bd3d4149dbd12fb7c3cbfd708d Mon Sep 17 00:00:00 2001 From: Giovanni Volpe Date: Wed, 2 Dec 2026 19:37:46 +0100 Subject: [PATCH 02/37] Saved profiles must contain the complete current configuration The saved generation.block_unrequested_cjk option is now required. Package defaults supply values when creating a project; they no longer fill an absent field when opening a saved profile. Creation provenance is also mandatory. The profile must contain all five fields: - created_with_kilin - created_with_project_type - created_with_project_type_version - created_with_project_type_schema_version - created_with_project_type_sha256 Missing or malformed creation metadata is rejected without rewriting the profile or inventing a creation identity. The corresponding object contracts are enforced as well: ProjectProfile requires the CJK setting, and QAProject.creation_provenance is required and nonnullable. --- docs/configuration.md | 30 ++++++- docs/gui_protocol.md | 5 +- docs/versioning.md | 17 ++-- kilin/gui/engine.py | 7 +- kilin/gui/web/version_panel.js | 19 ++++- kilin/project.py | 78 +++++++++++-------- tests/kilin/_rag_support.py | 5 +- tests/kilin/gui/test__versions_frontend.py | 22 +++++- tests/kilin/gui/test_engine__creation.py | 39 ++++++++++ tests/kilin/gui/test_engine__versions.py | 10 +-- tests/kilin/test_project.py | 40 +++++++--- .../test_project__creation_provenance.py | 46 +++++++++-- tests/kilin/test_rag.py | 10 ++- 13 files changed, 252 insertions(+), 76 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 2e4eadbe..01e3ab61 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -261,6 +261,30 @@ search-depth steps are separate. Historical `effort_levels.json` and old choices, back up the files and transfer the desired values explicitly 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 Project-type JSON can declare `capabilities.source_cards` with `enabled`, @@ -348,8 +372,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 diff --git a/docs/gui_protocol.md b/docs/gui_protocol.md index 1b4b4b5e..e544bd51 100644 --- a/docs/gui_protocol.md +++ b/docs/gui_protocol.md @@ -195,8 +195,9 @@ responses by request ID and delegates rendering to `plugin_panel.js`. `kilin.__version__` for the banner. `ChatBridge.requestVersions(request_id)` forwards a version-report request to the engine. The `versions` event echoes the request ID and carries the active project path (or an empty string), -`creation_provenance` (or null), and `inventory` from `kilin.version_info()`; -failures carry `error`. The Versions section is application-wide and does +`creation_provenance`, and `inventory` from `kilin.version_info()`. Creation +provenance is the complete recorded identity for an open project and is +null only when no project is open; failures carry `error`. The Versions section is application-wide and does not require an open project. The frontend rejects stale replies, renders local data as text, and can copy the complete snapshot as JSON. Runtime catalog discovery follows the normal trusted plugin lifecycle; reporting diff --git a/docs/versioning.md b/docs/versioning.md index 536057c5..35b7a4ca 100644 --- a/docs/versioning.md +++ b/docs/versioning.md @@ -225,8 +225,10 @@ created_with_project_type_sha256 = These illustrative values MUST NOT be hard-coded into creation code. Renaming, relocation, settings changes, or application and plugin upgrades MUST NOT -modify creation provenance. Existing projects with unknown provenance MUST -NOT be assigned invented historical values. Creation provenance is descriptive, +modify creation provenance. Every persisted project MUST contain all five +fields, including projects created through the core Python API. Profiles +without creation metadata are invalid and MUST NOT be assigned invented +historical values. Creation provenance is descriptive, not a compatibility gate or an instruction to pin the active project type. The instance evolves through its own user configuration, sources, outputs, and conversation history. No independently incremented project-instance @@ -235,9 +237,10 @@ records the actual identities used at each execution independently of origin. Python exposes the saved record as `QAProject.creation_provenance`, a frozen `kilin.ProjectCreationProvenance` object separate from `ProjectProfile`. -For a workspace without the metadata section, this property is `None`. -Present but incomplete or malformed metadata is reported as an invalid -profile without rewriting it. The application version is validated against +The property is required and is never `None` on a valid project. Absent, +incomplete, or malformed metadata is reported as an invalid profile without +rewriting it. Read-only inspection with `require_registered_type=False` +uses the same schema without activating the current project-type catalog. The application version is validated against the canonical stable, beta, and release-candidate syntax during both creation and reopening. Historical, well-formed versions are read without checking them against the current runtime, catalog, or supported generations. Native @@ -348,8 +351,8 @@ strings independently in frontend assets. The desktop Versions section is application-wide and available before a project is opened. It presents the core inventory in collapsible groups and can copy the complete snapshot as JSON, including separate active-project -creation provenance (None if absent). The bridge obtains the banner value -from `kilin.__version__`; report requests are correlated by request ID and +creation provenance (`None` only when no project is open). The bridge +obtains the banner value from `kilin.__version__`; report requests are correlated by request ID and project, and stale replies are discarded. The Plugins panel consumes the same plugin-record inventory rather than a separately collected catalog. diff --git a/kilin/gui/engine.py b/kilin/gui/engine.py index 0949d35b..bec8d8e2 100644 --- a/kilin/gui/engine.py +++ b/kilin/gui/engine.py @@ -3247,10 +3247,9 @@ def versions(self, request_id: object) -> None: if self.session is not None: project = self.session.project reply["project"] = str(project.root) - if project.creation_provenance is not None: - reply["creation_provenance"] = asdict( - project.creation_provenance - ) + reply["creation_provenance"] = asdict( + project.creation_provenance + ) reply["inventory"] = kilin.version_info() except Exception as error: reply["error"] = str(error) diff --git a/kilin/gui/web/version_panel.js b/kilin/gui/web/version_panel.js index 5e49a47f..bb5244b0 100644 --- a/kilin/gui/web/version_panel.js +++ b/kilin/gui/web/version_panel.js @@ -182,7 +182,6 @@ class VersionPanel { 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 if (!snapshot.creation_provenance) provenance.append(this.row("Origin", "Unknown (no recorded creation metadata)")); else for (const [key, value] of Object.entries(snapshot.creation_provenance)) { provenance.append(this.row(key.replaceAll("_", " "), value)); } @@ -201,9 +200,25 @@ class VersionPanel { 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) { + } 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, diff --git a/kilin/project.py b/kilin/project.py index e9366ee8..fdc3c073 100644 --- a/kilin/project.py +++ b/kilin/project.py @@ -26,8 +26,9 @@ - **Validated profiles** Read backend, model, query-format, scan, chunk, retrieval, and generation - settings. Capture immutable creation provenance independently of the - editable profile. + 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** @@ -559,8 +560,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. Attributes ---------- @@ -603,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 ------- @@ -616,10 +617,11 @@ class ProjectProfile: Notes ----- Values normally come from the validated INI reader. Direct dataclass - construction validates the source layout name. Other settings 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. + 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. """ @@ -641,7 +643,7 @@ 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. @@ -744,9 +746,8 @@ class QAProject: Folder containing persistent conversation records. profile: ProjectProfile Parsed project settings. - creation_provenance: ProjectCreationProvenance | None, optional - Recorded origin, or None for a project without creation metadata. - Defaults to None. + creation_provenance: ProjectCreationProvenance + Required recorded origin, captured when the project was created. Attributes ---------- @@ -760,7 +761,7 @@ class QAProject: Folder containing persistent conversation records. profile: ProjectProfile Parsed project settings. - creation_provenance: ProjectCreationProvenance | None + creation_provenance: ProjectCreationProvenance Recorded origin, independent of the editable profile. """ @@ -770,7 +771,22 @@ class QAProject: indexes: Path logs: Path profile: ProjectProfile - creation_provenance: ProjectCreationProvenance | None = None + 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( @@ -1576,10 +1592,11 @@ def open_project(directory: str | Path) -> QAProject: 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 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. + 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. """ @@ -1888,11 +1905,8 @@ def _read_profile( "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", ), ) @@ -1935,7 +1949,7 @@ def _require_creation_application_version(value: object) -> str: def _read_creation_provenance( parser: ConfigParser, -) -> ProjectCreationProvenance | None: +) -> ProjectCreationProvenance: """Read historical creation metadata without consulting the catalog. Parameters @@ -1945,25 +1959,23 @@ def _read_creation_provenance( Returns ------- - ProjectCreationProvenance | None - Complete recorded identity, or None when the section is absent. + ProjectCreationProvenance + Complete recorded identity required by every persisted project. Raises ------ ValueError - If a present creation record is incomplete or malformed. + If the creation record is absent, incomplete, or malformed. Notes ----- Historical versions need not equal the currently supported versions. - An absent section is not backfilled, and invalid records are never - rewritten or replaced with the active identity. + Absent or invalid records are rejected without rewriting or replacing + them with the active identity. """ section = "metadata" - if not parser.has_section(section): - return None app = _require_creation_application_version( _required(parser, section, "created_with_kilin"), ) diff --git a/tests/kilin/_rag_support.py b/tests/kilin/_rag_support.py index c6d88795..5a8f663c 100644 --- a/tests/kilin/_rag_support.py +++ b/tests/kilin/_rag_support.py @@ -17,7 +17,9 @@ from unittest.mock import DEFAULT, MagicMock, patch, sentinel from kilin import rag from kilin.answering import RouteDecision -from kilin.project import QAProject, default_project_profile +from kilin.project import ( + QAProject, _creation_provenance, default_project_profile, +) from kilin.project_type import ( HISTORY_POLICY_RECENT, Intent, @@ -86,6 +88,7 @@ def _source_project(root: Path) -> QAProject: indexes=directory / "indexes", logs=directory / "logs", profile=profile, + creation_provenance=_creation_provenance("code"), ) diff --git a/tests/kilin/gui/test__versions_frontend.py b/tests/kilin/gui/test__versions_frontend.py index 5ea5c305..a61c713a 100644 --- a/tests/kilin/gui/test__versions_frontend.py +++ b/tests/kilin/gui/test__versions_frontend.py @@ -127,7 +127,9 @@ def test_full_report_copy_busy_and_project_correlation(self): assert.ok(panel.request); const creation = {created_with_kilin: "0.0.1", created_with_project_type: "example", - created_with_project_type_version: "0.0.2"}; + created_with_project_type_version: "0.0.2", + created_with_project_type_schema_version: 1, + created_with_project_type_sha256: "a".repeat(64)}; reply({creation_provenance: creation}); assert.ok(text(get("version-inventory")).includes("0.0.1")); panel.copy(); @@ -142,6 +144,24 @@ def test_full_report_copy_busy_and_project_correlation(self): reply({error: "Failed to read report", inventory: undefined}); assert.equal(get("version-copy").disabled, true); assert.equal(get("version-status").textContent, "Failed to read report"); +const invalidOrigins = [null, undefined, [], "unknown", ...Object.keys( + creation).map((key) => { + const missing = { ...creation }; + delete missing[key]; + return missing; + }), { ...creation, created_with_kilin: null }, + { ...creation, created_with_project_type_schema_version: "1" }, + { ...creation, obsolete: true }]; +for (const origin of invalidOrigins) { + panel.refresh(); + reply({ creation_provenance: origin }); + assert.equal(get("version-copy").disabled, true); + assert.equal(get("version-status").textContent, + "Version report unavailable."); + assert.equal(panel.snapshot, null); + assert.equal(text(get("version-inventory")).includes( + "Unknown (no recorded creation metadata)"), false); +} console.log("versions frontend passed"); ''' result = subprocess.run( diff --git a/tests/kilin/gui/test_engine__creation.py b/tests/kilin/gui/test_engine__creation.py index cdd4db13..d7d038a1 100644 --- a/tests/kilin/gui/test_engine__creation.py +++ b/tests/kilin/gui/test_engine__creation.py @@ -8,6 +8,7 @@ # pylint: disable=C0116:missing-function-docstring # pylint: disable=C0103:invalid-name +from configparser import ConfigParser import os from pathlib import Path from tempfile import TemporaryDirectory @@ -88,6 +89,44 @@ def test_explicit_conflict_leaves_session_and_trace_bytes_unchanged(self): self.assertTrue(conflict["existing_project"]) self.assertEqual(conflict["workspace"], str(self.project.root)) + def test_incomplete_profile_rejects_resume_before_side_effects(self): + """Reject missing core fields before releasing the active project.""" + + session = self.engine.session + conversation = self.engine.active_conversation + for section, option in ( + ("metadata", None), + ("generation", "block_unrequested_cjk"), + ): + with self.subTest(section=section, option=option): + target = kilin.initialize_project( + self.root / section, "code", + ) + path = target.root / "profile.ini" + parser = ConfigParser() + parser.read(path, encoding="utf-8") + if option is None: + parser.remove_section(section) + else: + parser.remove_option(section, option) + with path.open("w", encoding="utf-8") as stream: + parser.write(stream) + previous = self.snapshot(self.project.root) + rejected = self.snapshot(target.root) + with patch("kilin.gui.engine.ConversationStore") as store, \ + patch("kilin.gui.engine.RAGSession") as rag: + self.engine.resume_project(str(target.root)) + store.assert_not_called() + rag.assert_not_called() + self.assertIs(self.engine.session, session) + self.assertFalse(session.closed) + self.assertIs(self.engine.active_conversation, conversation) + self.assertEqual(self.snapshot(self.project.root), previous) + self.assertEqual(self.snapshot(target.root), rejected) + self.assertEqual(self.events[-1]["event"], "error") + self.assertIn(option or section, self.events[-1]["message"]) + self.assertFalse(self.events[-1]["resume_released"]) + def test_start_screen_choices_go_into_the_new_project(self): """The intent model and search depth chosen before creation.""" target = self.root / "chosen" diff --git a/tests/kilin/gui/test_engine__versions.py b/tests/kilin/gui/test_engine__versions.py index 458446c5..59aadb7a 100644 --- a/tests/kilin/gui/test_engine__versions.py +++ b/tests/kilin/gui/test_engine__versions.py @@ -64,12 +64,12 @@ def test_selected_project_origin_is_separate_and_historical(self): self.assertEqual(event["creation_provenance"], asdict(historical)) self.assertEqual(event["inventory"]["application"]["version"], kilin.__version__) - self.engine.session.project = replace( - project, creation_provenance=None, - ) - self.engine.versions("old") + with self.assertRaisesRegex(TypeError, "creation_provenance"): + replace(project, creation_provenance=None) + self.engine.versions("current") self.assertEqual(self.events[-1]["project"], str(project.root)) - self.assertIsNone(self.events[-1]["creation_provenance"]) + self.assertEqual(self.events[-1]["creation_provenance"], + asdict(historical)) self.assertEqual((project.root / "profile.ini").read_bytes(), before) def test_diagnostics_retain_request_correlation(self): diff --git a/tests/kilin/test_project.py b/tests/kilin/test_project.py index 9e38ab60..b2648b79 100644 --- a/tests/kilin/test_project.py +++ b/tests/kilin/test_project.py @@ -91,10 +91,7 @@ def _profile( """ directory = self._folder(name) - definition = project_type(type_id) - text = project._default_profile_text( - type_id, ", ".join(definition.extensions) - ) + text, _, _ = project._prepared_profile(type_id, None) text = text.replace("source = sources", f"source = {source}") (directory / "profile.ini").write_text(text, encoding="utf-8") (directory / "sources").mkdir() @@ -465,6 +462,20 @@ def test_direct_profile_cannot_select_another_source(self) -> None: with self.assertRaisesRegex(ValueError, "project.source"): replace(default, source="repository") + def test_direct_profile_requires_explicit_cjk_setting(self) -> None: + """Require the CJK field when constructing profiles directly.""" + + settings = asdict(project.default_project_profile("code")) + del settings["block_unrequested_cjk"] + with self.assertRaisesRegex(TypeError, "block_unrequested_cjk"): + project.ProjectProfile(**settings) + for value in (False, True): + with self.subTest(value=value): + profile = project.ProjectProfile( + **settings, block_unrequested_cjk=value, + ) + self.assertIs(profile.block_unrequested_cjk, value) + def test_missing_required_sections_and_options(self) -> None: """Identify missing INI keys using section-qualified errors.""" @@ -487,6 +498,7 @@ def test_missing_required_sections_and_options(self) -> None: ("generation", "thinking"), ("generation", "temperature"), ("generation", "max_new_tokens"), + ("generation", "block_unrequested_cjk"), )): with self.subTest(section=section, option=option): root = self._profile(f"missing{index}") @@ -586,8 +598,8 @@ def test_boolean_settings_use_configparser_spellings(self) -> None: with self.assertRaisesRegex(ValueError, "true or false"): project.open_project(root) - def test_cjk_blocking_setting_is_optional(self) -> None: - """New profiles write the flag; older profiles use the default.""" + def test_cjk_blocking_setting_is_required(self) -> None: + """Keep explicit true and false values; reject an absent flag.""" root = self._profile("cjk") text = (root / "profile.ini").read_text(encoding="utf-8") @@ -600,9 +612,19 @@ def test_cjk_blocking_setting_is_optional(self) -> None: project.open_project(root).profile.block_unrequested_cjk ) self._edit(root, "generation", "block_unrequested_cjk", None) - self.assertTrue( - project.open_project(root).profile.block_unrequested_cjk - ) + path = root / "profile.ini" + before = path.read_bytes() + for read in ( + lambda: project.open_project(root), + lambda: project._read_project(root, require_registered_type=False), + lambda: project.configure_project(root, {"temperature": 0.4}), + ): + with self.subTest(read=read): + with self.assertRaisesRegex( + ValueError, "generation.block_unrequested_cjk", + ): + read() + self.assertEqual(path.read_bytes(), before) self._edit(root, "generation", "block_unrequested_cjk", "possibly") with self.assertRaisesRegex(ValueError, "true or false"): project.open_project(root) diff --git a/tests/kilin/test_project__creation_provenance.py b/tests/kilin/test_project__creation_provenance.py index 14751108..da605f9b 100644 --- a/tests/kilin/test_project__creation_provenance.py +++ b/tests/kilin/test_project__creation_provenance.py @@ -9,7 +9,7 @@ # pylint: disable=C0103:invalid-name from configparser import ConfigParser -from dataclasses import FrozenInstanceError, asdict +from dataclasses import FrozenInstanceError, asdict, replace from hashlib import sha256 import json import os @@ -91,19 +91,27 @@ def test_edits_relocation_and_runtime_upgrade_do_not_change_origin(self): self.assertEqual(dict(self._parser(relocated)["metadata"]), {k: str(v) for k, v in asdict(expected).items()}) - def test_old_profiles_and_historical_versions(self): + def test_absent_metadata_is_rejected_without_writing(self): project = kilin.initialize_project(self.destination, "code") parser = self._parser(project) parser.remove_section("metadata") self._save(project, parser) path = project.root / "profile.ini" before = path.read_bytes() - self.assertIsNone(kilin.open_project(project.root).creation_provenance) - self.assertEqual(path.read_bytes(), before) - self.assertIsNone(configure_project(project.root, { - "temperature": 0.4, - }).creation_provenance) - self.assertFalse(self._parser(project).has_section("metadata")) + for read in ( + lambda: kilin.open_project(project.root), + lambda: _read_project(project.root, require_registered_type=False), + lambda: configure_project(project.root, {"temperature": 0.4}), + ): + with self.subTest(read=read): + with self.assertRaisesRegex(ValueError, "metadata"): + read() + self.assertEqual(path.read_bytes(), before) + self.assertFalse(self._parser(project).has_section("metadata")) + + def test_historical_versions_are_preserved_without_catalog_access(self): + project = kilin.initialize_project(self.destination, "code") + parser = self._parser(project) parser["metadata"] = { "created_with_kilin": "0.0.1", "created_with_project_type": "removed-type", @@ -122,6 +130,18 @@ def test_old_profiles_and_historical_versions(self): "a" * 64, )) + def test_project_objects_require_creation_provenance(self): + project = kilin.initialize_project(self.destination, "code") + fields = {name: getattr(project, name) for name in ( + "root", "source", "indexes", "logs", "profile", + )} + with self.assertRaisesRegex(TypeError, "creation_provenance"): + kilin.QAProject(**fields) + for value in (None, {}, "unknown"): + with self.subTest(value=value): + with self.assertRaisesRegex(TypeError, "creation_provenance"): + replace(project, creation_provenance=value) + def test_historical_application_release_forms_are_preserved(self): project = kilin.initialize_project(self.destination, "code") parser = self._parser(project) @@ -218,7 +238,11 @@ def test_malformed_provenance_fails_without_writing(self): ("created_with_kilin", "0.1.0+local"), ("created_with_kilin", "1!0.1.0"), ("created_with_kilin", "0.1.\u0661"), + ("created_with_project_type", None), ("created_with_project_type", "Invalid Name"), + ("created_with_project_type_version", None), + ("created_with_project_type_schema_version", None), + ("created_with_project_type_sha256", None), ("created_with_project_type_version", "1.0"), ("created_with_project_type_schema_version", "1.0"), ("created_with_project_type_sha256", "unknown"), @@ -235,6 +259,12 @@ def test_malformed_provenance_fails_without_writing(self): with self.assertRaisesRegex(ValueError, name): kilin.open_project(project.root) self.assertEqual(path.read_bytes(), before) + with patch("kilin.project.project_type_catalog", + side_effect=AssertionError("catalog access")): + with self.assertRaisesRegex(ValueError, name): + _read_project(project.root, + require_registered_type=False) + self.assertEqual(path.read_bytes(), before) with self.assertRaisesRegex(ValueError, name): configure_project(project.root, {"temperature": 0.4}) self.assertEqual(path.read_bytes(), before) diff --git a/tests/kilin/test_rag.py b/tests/kilin/test_rag.py index 0e10952d..77e27d46 100644 --- a/tests/kilin/test_rag.py +++ b/tests/kilin/test_rag.py @@ -655,7 +655,9 @@ def setUp(self) -> None: self.addCleanup(temporary.cleanup) self.root = Path(temporary.name) (self.root / "logs").mkdir() - from kilin.project import QAProject, default_project_profile + from kilin.project import ( + QAProject, _creation_provenance, default_project_profile, + ) self.project = QAProject( self.root, @@ -663,6 +665,7 @@ def setUp(self) -> None: self.root / "indexes", self.root / "logs", default_project_profile("code"), + _creation_provenance("code"), ) @contextmanager @@ -1082,12 +1085,15 @@ def test_constructor_does_not_close_caller_owned_trace_on_error( ) -> None: """Preserve a caller-owned trace after constructor failure.""" with TemporaryDirectory() as directory: - from kilin.project import QAProject, default_project_profile + from kilin.project import ( + QAProject, _creation_provenance, default_project_profile, + ) root = Path(directory) (root / "logs").mkdir() project = QAProject( root, root / "sources", root / "indexes", root / "logs", default_project_profile("code"), + _creation_provenance("code"), ) trace = MagicMock() with patch.object( From cf3f6904ae13f9a164207f93f63d5ced77a023c3 Mon Sep 17 00:00:00 2001 From: Giovanni Volpe Date: Wed, 2 Dec 2026 19:40:30 +0100 Subject: [PATCH 03/37] PR13b MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One shared validator defines current conversation state kilin.conversation_format now owns the shared structural validation used by persistence and its consumers. It remains independent of RAG, model, and GUI imports. The schema distinguishes legitimate lifecycle states from incomplete records: Area Enforced behavior Registration metadata The complete group may be absent for a core-only conversation; partial registration metadata is invalid. Resumable history system_prompt and turns form a complete group. Completed turns UUID, timestamp, question, answer, evidence, parameters, and timeline must all be present. Nullable fields A valid null must be explicitly stored. Absence no longer substitutes for null. Fixed records Unknown fields are rejected. Turn parameters Remain extensible, but must contain valid finite JSON values. Checkpoints Outer and inner IDs, turn count, and the saved conversation-content hash must agree. For example, timeline: null remains a valid current untimed answer. A completed turn with no timeline field is rejected. Evidence records likewise require their complete current fields, including explicit nullable cell and context_role values. Scalar coercions such as converting a string citation into an integer have been removed. A missing conversation file can start a new history. An existing malformed document, an existing {} document without the canonical envelope, or a nonregular target cannot silently become a new empty history. Validation precedes persistence and initialization RAG and TraceLogger validate existing conversation state under the existing ownership rules before project diagnostics, indexing, or model initialization. Writes validate the complete merged candidate. TraceLogger validates a detached copy so later caller mutation cannot alter the accepted snapshot. Rejected state and failed writes preserve the previous saved conversation bytes and committed in-memory state; turns are committed only after persistence succeeds. Conversation-store operations use the same validation. Discovery exposes rejected paths and reasons through discovery_errors(), while valid registered conversations remain accessible. An all-invalid catalog raises an error instead of creating an empty replacement conversation. Consumers use the same schema Conversation memory, read-only inspectors, GUI file reading, usage totals, and system-test inspection now use the shared current-state validation. Two additional defects found during implementation are covered: - A saved memory index cannot bypass the first schema validation in a process merely because its file signatures match. Subsequent unchanged reads can reuse the validated observation. - GUI usage totals deduplicate by durable turn UUID. Independent answers with identical text and timestamps remain distinct. Invalid usage data in one branch copy cannot hide valid usage from another copy. The current diagnostic writer’s support for NaN and infinities is preserved outside resumable state. A regression test exercises emit, close, reopen, and RAG loading. Nonfinite values inside resumable parameters are rejected. This preserves the current diagnostic contract without accepting incomplete historical conversation formats. --- docs/conversation_memory.md | 10 + docs/conversation_ownership.md | 97 ++++ docs/gui_protocol.md | 11 + docs/module_map.md | 2 +- docs/trace_recording.md | 8 + docs/versioning.md | 9 + kilin/conversation_format.py | 513 +++++++++++++++++- kilin/conversation_memory/index.py | 43 +- kilin/conversation_memory/inspection.py | 32 +- kilin/conversations.py | 222 ++++---- kilin/gui/engine.py | 37 +- kilin/gui/window.py | 11 +- kilin/rag.py | 157 +++--- kilin/system_testing/traces.py | 12 +- kilin/system_testing/validation.py | 9 +- kilin/trace_logging.py | 38 +- tests/kilin/_conversation_support.py | 186 +++++++ .../conversation_memory/test_feedback.py | 1 + .../conversation_memory/test_inspection.py | 1 + tests/kilin/gui/test__read_while_answering.py | 21 +- .../gui/test_engine__conversation_memory.py | 1 + .../gui/test_engine__memory_management.py | 1 + tests/kilin/gui/test_engine__projects.py | 10 +- .../gui/test_engine__source_ownership.py | 7 +- tests/kilin/gui/test_engine__workflow.py | 14 +- tests/kilin/system_testing/test_experiment.py | 6 +- tests/kilin/test__conversation_lifecycle.py | 26 +- .../kilin/test__conversation_memory_index.py | 1 + .../test__conversation_memory_integrated.py | 1 + .../test__conversation_schema_consumers.py | 263 +++++++++ tests/kilin/test__trace_json.py | 21 +- tests/kilin/test_conversation_format.py | 6 + .../kilin/test_conversation_format__schema.py | 384 +++++++++++++ tests/kilin/test_conversations.py | 242 +++++++-- tests/kilin/test_rag.py | 35 +- tests/kilin/test_rag__conversation.py | 42 +- tests/kilin/test_rag__conversation_memory.py | 6 +- tests/kilin/test_rag__conversation_schema.py | 333 ++++++++++++ tests/kilin/test_rag__disliked_history.py | 7 +- tests/kilin/test_rag__historical_recall.py | 6 +- .../kilin/test_rag__retrieval_corrections.py | 5 +- tests/kilin/test_rag__timeline.py | 8 +- tests/kilin/test_trace_logging.py | 53 +- tests/kilin/test_trace_logging__project.py | 5 +- 44 files changed, 2467 insertions(+), 436 deletions(-) create mode 100644 tests/kilin/_conversation_support.py create mode 100644 tests/kilin/test__conversation_schema_consumers.py create mode 100644 tests/kilin/test_conversation_format__schema.py create mode 100644 tests/kilin/test_rag__conversation_schema.py diff --git a/docs/conversation_memory.md b/docs/conversation_memory.md index ca5758de..f68bf68c 100644 --- a/docs/conversation_memory.md +++ b/docs/conversation_memory.md @@ -196,6 +196,16 @@ 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. +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 +prevents a cache built by a permissive reader from bypassing current +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 `RAGSession.ask()` retrieves memory only when the project has enabled it, diff --git a/docs/conversation_ownership.md b/docs/conversation_ownership.md index 53e38820..fddcba43 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) diff --git a/docs/gui_protocol.md b/docs/gui_protocol.md index e544bd51..7cb6f8fa 100644 --- a/docs/gui_protocol.md +++ b/docs/gui_protocol.md @@ -79,6 +79,17 @@ 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`, diff --git a/docs/module_map.md b/docs/module_map.md index 2d067c90..b30ff6b7 100644 --- a/docs/module_map.md +++ b/docs/module_map.md @@ -37,7 +37,7 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | [`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/) | diff --git a/docs/trace_recording.md b/docs/trace_recording.md index d40451b7..8babf724 100644 --- a/docs/trace_recording.md +++ b/docs/trace_recording.md @@ -93,6 +93,14 @@ The current prerelease trace format does not support the earlier compact configuration or file-artifact representations. Regenerate system-test recordings using the current writer and reader. +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 diff --git a/docs/versioning.md b/docs/versioning.md index 35b7a4ca..739b65eb 100644 --- a/docs/versioning.md +++ b/docs/versioning.md @@ -208,6 +208,15 @@ reports unsupported traces without decoding their events. Existing numbered and descriptive retrieval, source-card, and settings format identifiers retain their own declarations and meanings. +The persisted project profile and standalone conversation resume state are +unnumbered current schemas. Required fields are enforced directly; a missing +field is not a request for an older-version default. This prerelease cleanup +does not add migration paths or invent historical format generations. +Conversation state embedded in a trace follows the same strict validation +while the pre-stable trace contract remains generation 1 under the policy +above. The schema and legitimate lifecycle states are documented in +[conversation-file ownership](conversation_ownership.md#current-persisted-schema). + ## Project creation provenance A new project records immutable origin metadata in `profile.ini` at the diff --git a/kilin/conversation_format.py b/kilin/conversation_format.py index 3ea7443c..67bc9aee 100644 --- a/kilin/conversation_format.py +++ b/kilin/conversation_format.py @@ -41,6 +41,15 @@ Construct a complete grouped conversation-session record. +- ``validate_conversation_*`` + + Validate complete persisted candidates without coercion or mutation. + +- ``decode_conversation_json`` and ``read_conversation_json`` + + Reject duplicate keys before interpreting records. Diagnostic numbers + retain their existing representation; resumable values must be finite. + The names are internal to persistence and are not exported by ``kilin``. Examples @@ -54,9 +63,19 @@ from __future__ import annotations +from datetime import datetime +from hashlib import sha256 +import json +import math +import re from typing import Final from kilin._trace_project import TRACE_FORMAT_VERSION +from kilin.answer_timeline import _timeline_from_data +from kilin.conversation_memory.models import ( + require_saved_turn_ids, + require_turn_uuid, +) __all__ = [ "CONVERSATION_SESSION_KEY", @@ -65,6 +84,12 @@ "CONVERSATION_RESUME_STATE_KEY", "new_conversation_session", "conversation_state", + "validate_conversation_state", + "validate_conversation_payload", + "validate_conversation_metadata", + "validate_conversation_turn", + "decode_conversation_json", + "read_conversation_json", ] CONVERSATION_SESSION_KEY: Final[str] = "05_conversations" @@ -73,6 +98,37 @@ CONVERSATION_RESUME_STATE_KEY: Final[str] = "resume_state" +_METADATA_FIELDS: Final[frozenset[str]] = frozenset(( + "conversation_id", "name", "parent_conversation_id", + "origin_checkpoint_id", "origin_turn_count", "created_at_utc", + "updated_at_utc", +)) +_RESUME_FIELDS: Final[frozenset[str]] = frozenset(("system_prompt", "turns")) +_CHECKPOINT_FIELDS: Final[frozenset[str]] = frozenset(( + "checkpoint_id", "parent_checkpoint_id", "conversation_sha256", + "index_fingerprint", "turn_count", +)) +_STATE_FIELDS: Final[frozenset[str]] = ( + _METADATA_FIELDS | _RESUME_FIELDS | {"checkpoint_id", "checkpoint"} +) +_TURN_FIELDS: Final[frozenset[str]] = frozenset(( + "conversation_turn_uuid", "timestamp", "question", "answer", "evidence", + "parameters", "timeline", +)) +_EVIDENCE_FIELDS: Final[frozenset[str]] = frozenset(( + "citation", "path", "start_line", "end_line", "symbol", "text", "cell", + "context_role", +)) +_ID_PATTERN: Final[re.Pattern[str]] = re.compile( + r"[A-Za-z0-9][A-Za-z0-9_-]*" +) +_UTC_TIMESTAMP_PATTERN: Final[re.Pattern[str]] = re.compile( + r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}" + r"(?:\.\d{1,6})?(?:Z|\+00:00)" +) +_SHA256_PATTERN: Final[re.Pattern[str]] = re.compile(r"[0-9a-f]{64}") + + def new_conversation_session( resume_state: dict[str, object] | None = None, ) -> dict[str, object]: @@ -129,8 +185,10 @@ def conversation_state( Notes ----- Creation does not migrate obsolete records. Both modes reject invalid - existing data before making any change. Unrelated valid trace sessions - and top-level metadata are retained. + envelopes before making any change. Unrelated trace sessions and top-level + metadata are retained. This construction helper does not validate complete + resumable state; persisted readers use ``validate_conversation_payload`` + or ``read_conversation_json`` before interpreting it. """ @@ -200,3 +258,454 @@ def conversation_state( if not isinstance(state, dict) or "chat_messages" in state: raise ValueError(invalid) return state + + +def _require_fields( + value: object, fields: frozenset[str], label: str, +) -> dict[str, object]: + """Require exactly the declared keys of one fixed persisted record. + + Parameters + ---------- + value: object + Candidate JSON mapping. + fields: frozenset[str] + Complete required key set. + label: str + Record description used in the error message. + + Returns + ------- + dict[str, object] + Original mapping, without copying or mutation. + + Raises + ------ + ValueError + If the candidate is not a mapping with exactly these fields. + + """ + + if not isinstance(value, dict) or set(value) != fields: + raise ValueError(f"The saved conversation {label} fields are invalid.") + return value + + +def validate_conversation_metadata( + state: dict[str, object], +) -> dict[str, object]: + """Require the complete current registration metadata group. + + Parameters + ---------- + state: dict[str, object] + Resumable state containing all seven registration fields. Additional + resumable fields are validated by ``validate_conversation_state``. + + Returns + ------- + dict[str, object] + A new mapping containing the validated registration fields only. + + Raises + ------ + ValueError + If metadata is missing or a field has an unsupported value. + + Notes + ----- + The whole registration group may be absent from a core-only record. + Calling this helper explicitly requires it, as the named store does. + Opaque safe identifiers and both UTC timestamp spellings remain valid. + + """ + + if not isinstance(state, dict) or not _METADATA_FIELDS <= state.keys(): + raise ValueError("The saved conversation metadata is incomplete.") + metadata = {field: state[field] for field in sorted(_METADATA_FIELDS)} + for field in ("conversation_id", "parent_conversation_id"): + value = metadata[field] + if value is None and field == "parent_conversation_id": + continue + if not isinstance(value, str) or _ID_PATTERN.fullmatch(value) is None: + raise ValueError(f"The saved conversation {field} is invalid.") + name = metadata["name"] + if not isinstance(name, str) or not name.strip() or len(name) > 80: + raise ValueError("The saved conversation name is invalid.") + origin = metadata["origin_checkpoint_id"] + if origin is not None and (not isinstance(origin, str) or not origin): + raise ValueError( + "The saved conversation origin checkpoint is invalid." + ) + count = metadata["origin_turn_count"] + if count is not None and (type(count) is not int or count < 0): + raise ValueError("The saved conversation branch point is invalid.") + for field in ("created_at_utc", "updated_at_utc"): + value = metadata[field] + if ( + not isinstance(value, str) + or _UTC_TIMESTAMP_PATTERN.fullmatch(value) is None + ): + raise ValueError("The saved conversation timestamp is invalid.") + try: + datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError as error: + raise ValueError( + "The saved conversation timestamp is invalid." + ) from error + return metadata + + +def _validate_json_value(value: object, active: set[int]) -> None: + """Reject coercible objects, cycles, and nonfinite parameter values. + + Parameters + ---------- + value: object + A candidate JSON value within the extensible parameter mapping. + active: set[int] + Identities of containers in the current recursion chain. + + Raises + ------ + ValueError + If a value cannot be represented as JSON without coercion. + + """ + + if value is None or type(value) in (str, bool, int): + return + if type(value) is float and math.isfinite(value): + return + if type(value) not in (dict, list) or id(value) in active: + raise ValueError("The saved conversation parameters are invalid.") + active.add(id(value)) + try: + if isinstance(value, dict): + for key, child in value.items(): + if not isinstance(key, str): + raise ValueError( + "The saved conversation parameter key is invalid." + ) + _validate_json_value(child, active) + else: + for child in value: + _validate_json_value(child, active) + finally: + active.remove(id(value)) + + +def _validate_evidence(value: object) -> None: + """Validate one saved evidence record without opening its source. + + Parameters + ---------- + value: object + Candidate evidence mapping with all eight current fields. + + Raises + ------ + ValueError + If a required field is missing, unknown, or has an invalid value. + + Notes + ----- + Historical source paths are descriptive references, not permission to + access the filesystem. Validation does not require sources to still exist. + + """ + + item = _require_fields(value, _EVIDENCE_FIELDS, "evidence") + for field in ("citation", "start_line", "end_line"): + number = item[field] + if type(number) is not int or number <= 0: + raise ValueError(f"The saved evidence {field} is invalid.") + if item["end_line"] < item["start_line"]: + raise ValueError("The saved evidence line range is invalid.") + path = item["path"] + if not isinstance(path, str) or not path or "\x00" in path: + raise ValueError("The saved evidence path is invalid.") + if not isinstance(item["text"], str): + raise ValueError("The saved evidence text is invalid.") + symbol = item["symbol"] + if symbol is not None and not isinstance(symbol, str): + raise ValueError("The saved evidence symbol is invalid.") + cell = item["cell"] + if cell is not None and (type(cell) is not int or cell <= 0): + raise ValueError("The saved evidence cell is invalid.") + role = item["context_role"] + if role is not None and ( + not isinstance(role, str) + or role not in ("direct", "related", "alternative") + ): + raise ValueError("The saved evidence context_role is invalid.") + + +def validate_conversation_turn(value: object) -> dict[str, object]: + """Validate a complete saved turn before reconstructing typed objects. + + Parameters + ---------- + value: object + Candidate turn mapping containing the seven required current fields. + + Returns + ------- + dict[str, object] + The original validated mapping. + + Raises + ------ + ValueError + If identity, text, evidence, parameters, or timing is invalid. + + Notes + ----- + Explicit null timing is valid. Missing timing is not an untimed turn. + Parameter keys vary by execution path, so only JSON structure is fixed. + + """ + + if not isinstance(value, dict): + raise ValueError("The saved conversation turn is invalid.") + require_turn_uuid(value.get("conversation_turn_uuid")) + turn = _require_fields(value, _TURN_FIELDS, "turn") + for field in ("timestamp", "question", "answer"): + if not isinstance(turn[field], str): + raise ValueError(f"The saved conversation {field} is invalid.") + evidence = turn["evidence"] + if not isinstance(evidence, list): + raise ValueError("Saved evidence must be a list.") + for item in evidence: + _validate_evidence(item) + parameters = turn["parameters"] + if not isinstance(parameters, dict): + raise ValueError("Saved parameters must be a mapping.") + _validate_json_value(parameters, set()) + timeline = turn["timeline"] + if timeline is not None: + _require_fields(timeline, frozenset(("elapsed_ms", "steps")), + "timeline") + if isinstance(timeline["steps"], list): + for step in timeline["steps"]: + _require_fields(step, frozenset(("phase", "label", "ms")), + "timeline step") + _timeline_from_data(timeline) + return turn + + +def _validate_checkpoint(state: dict[str, object]) -> None: + """Verify saved checkpoint identity, count, and conversation content. + + Parameters + ---------- + state: dict[str, object] + Validated resumable fields with both checkpoint fields present. + + Raises + ------ + ValueError + If the checkpoint has invalid structure or describes different turns. + + Notes + ----- + The checkpoint identifier also depends on original runtime data that is + not persisted here. Only the saved conversation content hash can be + recomputed, using precisely the existing writer's serialization. + + """ + + checkpoint = _require_fields(state["checkpoint"], _CHECKPOINT_FIELDS, + "checkpoint") + identifier = state["checkpoint_id"] + if not isinstance(identifier, str) or not identifier or ( + checkpoint["checkpoint_id"] != identifier + ): + raise ValueError("The saved conversation checkpoint ID is invalid.") + parent = checkpoint["parent_checkpoint_id"] + if parent is not None and (not isinstance(parent, str) or not parent): + raise ValueError( + "The saved conversation parent checkpoint is invalid." + ) + if not isinstance(checkpoint["index_fingerprint"], str): + raise ValueError("The saved checkpoint index fingerprint is invalid.") + count = checkpoint["turn_count"] + if type(count) is not int or count != len(state["turns"]): + raise ValueError("The saved conversation checkpoint count is invalid.") + digest = checkpoint["conversation_sha256"] + if ( + not isinstance(digest, str) + or _SHA256_PATTERN.fullmatch(digest) is None + ): + raise ValueError("The saved conversation checkpoint hash is invalid.") + saved = {"system_prompt": state["system_prompt"], "turns": state["turns"]} + actual = sha256(json.dumps( + saved, sort_keys=True, ensure_ascii=False, allow_nan=False, + ).encode("utf-8")).hexdigest() + if digest != actual: + raise ValueError("The saved conversation checkpoint hash is invalid.") + + +def validate_conversation_state(value: object) -> dict[str, object]: + """Require one complete current lifecycle state without altering it. + + Parameters + ---------- + value: object + Candidate resumable-state mapping. Registration and resumable history + are independent optional groups; each present group must be complete. + + Returns + ------- + dict[str, object] + The original validated state mapping. + + Raises + ------ + ValueError + If a group is partial, a field is invalid, or a checkpoint disagrees + with its saved conversation content. + + Notes + ----- + Empty, metadata-only, and core-only states are valid. A state with saved + history may omit checkpoint fields, as a truncated branch does. Present + checkpoint fields must form a complete consistent pair. Diagnostics are + independent and cannot supply missing persisted fields. + + """ + + if not isinstance(value, dict) or not value.keys() <= _STATE_FIELDS: + raise ValueError("The saved conversation state fields are invalid.") + if value.keys() & _METADATA_FIELDS: + validate_conversation_metadata(value) + has_resume = bool(value.keys() & _RESUME_FIELDS) + if has_resume: + if not _RESUME_FIELDS <= value.keys(): + raise ValueError( + "The saved conversation resume fields are invalid." + ) + if not isinstance(value["system_prompt"], str): + raise ValueError( + "The saved conversation system prompt is invalid." + ) + require_saved_turn_ids(value["turns"]) + for turn in value["turns"]: + validate_conversation_turn(turn) + checkpoints = {"checkpoint", "checkpoint_id"} & value.keys() + if checkpoints: + if not has_resume or len(checkpoints) != 2: + raise ValueError("The saved conversation checkpoint is invalid.") + _validate_checkpoint(value) + return value + + +def validate_conversation_payload( + payload: dict[str, object], +) -> dict[str, object]: + """Locate and validate persisted state in its canonical envelope. + + Parameters + ---------- + payload: dict[str, object] + Decoded complete conversation document. + + Returns + ------- + dict[str, object] + Validated state by reference, without modifying the document. + + Raises + ------ + ValueError + If either the envelope or resumable state is invalid. + + """ + + return validate_conversation_state(conversation_state(payload)) + + +def _unique_json_object(pairs: list[tuple[str, object]]) -> dict[str, object]: + """Reject repeated JSON object keys before a parser can discard values. + + Parameters + ---------- + pairs: list[tuple[str, object]] + Ordered pairs supplied by the JSON decoder. + + Returns + ------- + dict[str, object] + Mapping with every supplied key represented once. + + Raises + ------ + ValueError + If any key occurs more than once. + + """ + + result: dict[str, object] = {} + for key, value in pairs: + if key in result: + raise ValueError("The saved conversation has duplicate JSON keys.") + result[key] = value + return result + + +def decode_conversation_json(text: str) -> dict[str, object]: + """Decode a JSON object without discarding duplicate key values. + + Parameters + ---------- + text: str + Complete UTF-8-decoded document text. + + Returns + ------- + dict[str, object] + Parsed document. Its lifecycle schema is not interpreted here. + Diagnostic nonfinite numbers retain the current trace representation. + + Raises + ------ + ValueError + If JSON is invalid, has duplicate keys, or is not an object. + + """ + + try: + payload = json.loads( + text, object_pairs_hook=_unique_json_object, + ) + except json.JSONDecodeError as error: + raise ValueError("The saved conversation JSON is invalid.") from error + if not isinstance(payload, dict): + raise ValueError("The saved conversation is invalid.") + return payload + + +def read_conversation_json(text: str) -> dict[str, object]: + """Decode and validate a complete current conversation document. + + Parameters + ---------- + text: str + Complete UTF-8-decoded document text. + + Returns + ------- + dict[str, object] + Newly decoded document with validated resumable state. Numeric + diagnostics are independent; nonfinite resumable values are rejected. + + Raises + ------ + ValueError + If JSON, the grouped envelope, or persisted state is invalid. + + """ + + payload = decode_conversation_json(text) + validate_conversation_payload(payload) + return payload diff --git a/kilin/conversation_memory/index.py b/kilin/conversation_memory/index.py index 47913df8..5a26573e 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 observed conversation snapshot in this process, including a +# snapshot matching an index built before current schema enforcement. 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..901a1693 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() @@ -283,7 +278,7 @@ def read_memory_summaries( ----- 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. + the saved compact representation then supplies the available summary. No summary is written to message provenance or another cache. """ @@ -323,7 +318,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 +331,14 @@ 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 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/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/engine.py b/kilin/gui/engine.py index bec8d8e2..14bb050a 100644 --- a/kilin/gui/engine.py +++ b/kilin/gui/engine.py @@ -175,7 +175,10 @@ remove_project_files, replace_project_file, ) -from kilin.conversation_format import conversation_state +from kilin.conversation_format import ( + conversation_state, + read_conversation_json, +) from kilin.conversation_memory.feedback import FeedbackStore from kilin.conversation_memory.inspection import ( inspect_memory_messages, @@ -4259,7 +4262,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 @@ -4269,6 +4272,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 = ( @@ -4277,9 +4285,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) @@ -4288,22 +4304,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: diff --git a/kilin/gui/window.py b/kilin/gui/window.py index 2e0990a2..f956c574 100644 --- a/kilin/gui/window.py +++ b/kilin/gui/window.py @@ -85,7 +85,10 @@ 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 ( default_workspace_directory, @@ -1681,17 +1684,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 diff --git a/kilin/rag.py b/kilin/rag.py index 8359dc5a..2a21fe91 100644 --- a/kilin/rag.py +++ b/kilin/rag.py @@ -181,7 +181,6 @@ ) from kilin.conversation_memory.models import ( new_turn_uuid, - require_saved_turn_ids, require_turn_uuid, ) from kilin.answer_timeline import ( @@ -218,7 +217,12 @@ ) from kilin.chunking import Chunk, chunk_source_units from kilin.embeddings import EmbeddingSession -from kilin.conversation_format import conversation_state +from kilin.conversation_format import ( + conversation_state, + read_conversation_json, + validate_conversation_state, + validate_conversation_turn, +) from kilin.conversation_ownership import ( ConversationFileLock, conversation_write_ownership, @@ -832,8 +836,8 @@ class Evidence: context_role: "direct" | "related" | "alternative" | None, optional Retrieval provenance: a requested target, supporting context, or an unresolved name-match alternative. ``None`` denotes unclassified - evidence, including records saved before this field was added. - Defaults to ``None``. + evidence. Persisted records explicitly store this field, including + a null value for unclassified evidence. Defaults to ``None``. Attributes ---------- @@ -1286,6 +1290,9 @@ def _initialize( ownership = ConversationFileLock(self.conversation_path) ownership.acquire() self._conversation_ownership = ownership + # 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( @@ -1398,9 +1405,8 @@ def _initialize( 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", @@ -3186,8 +3192,9 @@ 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 @@ -7831,24 +7838,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( @@ -7860,10 +7870,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, @@ -7949,6 +7956,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: @@ -7956,12 +7964,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 @@ -8815,97 +8828,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/system_testing/traces.py b/kilin/system_testing/traces.py index 73743e70..4ba47e7b 100644 --- a/kilin/system_testing/traces.py +++ b/kilin/system_testing/traces.py @@ -43,9 +43,10 @@ resolve_semantic_reference, resolve_source_reference, semantic_snapshot, source_snapshot, ) -from kilin.conversation_format import conversation_state -from kilin.conversations import _validated_metadata -from kilin.conversation_memory.models import require_saved_turn_ids +from kilin.conversation_format import ( + validate_conversation_metadata, + validate_conversation_payload, +) __all__ = ["TraceEvent", "ValidationIssue", "Recording", "read_recording"] @@ -402,9 +403,8 @@ def _document(recording: Recording, path: str, payload: dict) -> None: path) if not project: try: - state = conversation_state(payload) - _validated_metadata(state) - require_saved_turn_ids(state.get("turns", [])) + 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) diff --git a/kilin/system_testing/validation.py b/kilin/system_testing/validation.py index 5975e51f..a4f8f1a6 100644 --- a/kilin/system_testing/validation.py +++ b/kilin/system_testing/validation.py @@ -34,6 +34,7 @@ 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, @@ -998,6 +999,7 @@ def finish(self) -> None: 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.") @@ -1032,13 +1034,6 @@ def finish(self) -> None: and type(checkpoint.get("turn_count")) is int and checkpoint["turn_count"] == len(turns), "Invalid saved checkpoint metadata.") - content = {"system_prompt": state.get("system_prompt"), - "turns": turns} - digest = sha256(json.dumps(content, sort_keys=True, - ensure_ascii=False).encode("utf-8") - ).hexdigest() - _require(checkpoint.get("conversation_sha256") == digest, - "Saved conversation content hash mismatch.") else: _require(state.get("checkpoint") is None, "Checkpoint exists without recorded identity.") diff --git a/kilin/trace_logging.py b/kilin/trace_logging.py index 5c2cf305..3011728e 100644 --- a/kilin/trace_logging.py +++ b/kilin/trace_logging.py @@ -130,7 +130,6 @@ from dataclasses import asdict, dataclass, is_dataclass from datetime import datetime, timezone from importlib.metadata import PackageNotFoundError, version -import json import os from pathlib import Path import platform @@ -168,6 +167,8 @@ CONVERSATION_SESSION_TITLE, conversation_state, new_conversation_session, + read_conversation_json, + validate_conversation_state, ) __all__ = [ @@ -517,9 +518,14 @@ def __init__( if scope == "conversation": self._file_lock.acquire() try: - if scope == "conversation" and self.output_path.is_file(): + if scope == "conversation" and self.output_path.exists(): + if not self.output_path.is_file(): + raise ValueError( + "The conversation trace is invalid: " + "expected a regular file." + ) try: - existing = json.loads( + existing = read_conversation_json( self.output_path.read_text(encoding="utf-8") ) # Validate before the constructor writes its first event. @@ -538,10 +544,10 @@ def __init__( ) ) except ( - OSError, json.JSONDecodeError, TypeError, KeyError + OSError, ValueError, TypeError, KeyError ) as error: raise ValueError( - "The conversation trace is invalid." + f"The conversation trace is invalid: {error}" ) from error # Keep prior trace state immutable during current writes. self._conversation = deepcopy(self._conversation) @@ -1074,17 +1080,19 @@ def update_conversation(self, data: Mapping[str, object]) -> None: Parameters ---------- data: Mapping[str, object] - Optional event or conversation-state mapping. Values are converted - through the implemented JSON conversion helper. + Partial current conversation-state mapping. Omitted fields are + retained; the complete merged state must satisfy its schema. Raises ------ + ValueError + If the merged state violates the current persisted schema. OSError If the direct state rewrite fails. Notes ----- - Merges converted fields into a candidate state under the event lock + Copies fields without scalar coercion into a candidate under the lock and writes it atomically. If serialization or writing fails, the previous in-memory state is restored so subsequent events cannot accidentally commit the failed checkpoint. Omitted fields are kept. @@ -1096,14 +1104,16 @@ def update_conversation(self, data: Mapping[str, object]) -> None: raise ValueError( "Project traces cannot store conversation state." ) - changes = { - str(key): _json_value(value) for key, value in data.items() - } + if not isinstance(data, Mapping): + raise ValueError("Conversation state updates must be mappings.") + changes = dict(data) with self._lock: if self._closed: raise RuntimeError("This trace logger is closed.") previous = self._conversation - self._conversation = {**previous, **changes} + candidate = deepcopy({**previous, **changes}) + validate_conversation_state(candidate) + self._conversation = candidate try: self._write_readable_trace() except BaseException: @@ -1648,8 +1658,8 @@ def update_conversation(self, data: Mapping[str, object]) -> None: Parameters ---------- data: Mapping[str, object] - Optional event or conversation-state mapping. Values are converted - through the implemented JSON conversion helper. + Supplied resumable-state fields. This sink does not inspect or + retain them; the caller owns persistence when tracing is disabled. """ diff --git a/tests/kilin/_conversation_support.py b/tests/kilin/_conversation_support.py new file mode 100644 index 00000000..89adba7e --- /dev/null +++ b/tests/kilin/_conversation_support.py @@ -0,0 +1,186 @@ +"""Build complete current conversation records for persistence tests. + +These explicit constructors describe legitimate lifecycle states. They never +repair supplied records, so tests can mutate one field to isolate rejection +behavior without accidentally supplying unrelated missing-field failures. + +""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from __future__ import annotations + +from hashlib import sha256 +import json +from uuid import uuid4 + + +def saved_turn( + question: str = "Question", + answer: str = "Answer", + *, + turn_uuid: str | None = None, + timestamp: str = "2026-01-01T00:00:00Z", + evidence: list[dict[str, object]] | None = None, + parameters: dict[str, object] | None = None, + timeline: dict[str, object] | None = None, +) -> dict[str, object]: + """Construct an explicit completed turn, including nullable timing. + + Parameters + ---------- + question: str, optional + User question. Defaults to "Question". + answer: str, optional + Completed answer. Defaults to "Answer". + turn_uuid: str | None, optional + Persisted identity. None generates a fresh UUID4. + timestamp: str, optional + Saved display timestamp. Defaults to a fixed UTC timestamp. + evidence: list[dict[str, object]] | None, optional + Complete evidence records. None supplies an empty list. + parameters: dict[str, object] | None, optional + JSON generation and orchestration settings. None supplies a mapping. + timeline: dict[str, object] | None, optional + Valid explicit timing, or None for an untimed completed turn. + + Returns + ------- + dict[str, object] + Seven-field turn record with independent empty mutable defaults. + + """ + + return { + "conversation_turn_uuid": uuid4().hex if turn_uuid is None + else turn_uuid, + "timestamp": timestamp, + "question": question, + "answer": answer, + "evidence": [] if evidence is None else evidence, + "parameters": {} if parameters is None else parameters, + "timeline": timeline, + } + + +def resumable_state( + turns: list[dict[str, object]] | None = None, + *, + system_prompt: str = "Use project sources.", +) -> dict[str, object]: + """Construct resumable state without claiming a checkpoint. + + Parameters + ---------- + turns: list[dict[str, object]] | None, optional + Completed turns, or None for a new empty history. + system_prompt: str, optional + Saved model instruction. Defaults to "Use project sources.". + + Returns + ------- + dict[str, object] + Complete prompt and turn group, suitable for a truncated branch. + + """ + + return { + "system_prompt": system_prompt, + "turns": [] if turns is None else turns, + } + + +def checkpoint_state( + checkpoint_id: str = "checkpoint_1", + turns: list[dict[str, object]] | None = None, + *, + system_prompt: str = "Use project sources.", + parent_checkpoint_id: str | None = None, + index_fingerprint: str = "fixture-index", +) -> dict[str, object]: + """Construct a complete checkpoint with an independently computed digest. + + Parameters + ---------- + checkpoint_id: str, optional + Opaque saved checkpoint identity. Defaults to "checkpoint_1". + turns: list[dict[str, object]] | None, optional + Completed turns, or None for a saved empty history. + system_prompt: str, optional + Saved model instruction. Defaults to "Use project sources.". + parent_checkpoint_id: str | None, optional + Previous checkpoint, or None for an independent initial state. + index_fingerprint: str, optional + Captured source index identity. Defaults to "fixture-index". + + Returns + ------- + dict[str, object] + Resumable state and matching checkpoint identity, count, and digest. + + """ + + state = resumable_state(turns, system_prompt=system_prompt) + digest = sha256(json.dumps( + state, sort_keys=True, ensure_ascii=False, + ).encode("utf-8")).hexdigest() + return { + **state, + "checkpoint_id": checkpoint_id, + "checkpoint": { + "checkpoint_id": checkpoint_id, + "parent_checkpoint_id": parent_checkpoint_id, + "conversation_sha256": digest, + "index_fingerprint": index_fingerprint, + "turn_count": len(state["turns"]), + }, + } + + +def conversation_metadata( + conversation_id: str = "fixture-conversation", + name: str = "Fixture conversation", + *, + created_at_utc: str = "2026-01-01T00:00:00Z", + updated_at_utc: str = "2026-01-01T00:00:00Z", + parent_conversation_id: str | None = None, + origin_checkpoint_id: str | None = None, + origin_turn_count: int | None = None, +) -> dict[str, object]: + """Construct complete current registration metadata. + + Parameters + ---------- + conversation_id: str, optional + Safe opaque identity. Defaults to "fixture-conversation". + name: str, optional + Visible name. Defaults to "Fixture conversation". + created_at_utc: str, optional + Original creation timestamp. Defaults to a fixed UTC timestamp. + updated_at_utc: str, optional + Last update timestamp. Defaults to the same fixed UTC timestamp. + parent_conversation_id: str | None, optional + Parent identity, or None for an independent conversation. + origin_checkpoint_id: str | None, optional + Captured branch checkpoint, or None when no checkpoint existed. + origin_turn_count: int | None, optional + Branch prefix length, or None for an independent conversation. + + Returns + ------- + dict[str, object] + Seven explicitly present registration fields. + + """ + + return { + "conversation_id": conversation_id, + "name": name, + "created_at_utc": created_at_utc, + "updated_at_utc": updated_at_utc, + "parent_conversation_id": parent_conversation_id, + "origin_checkpoint_id": origin_checkpoint_id, + "origin_turn_count": origin_turn_count, + } diff --git a/tests/kilin/conversation_memory/test_feedback.py b/tests/kilin/conversation_memory/test_feedback.py index 30c73774..4b77ea1c 100644 --- a/tests/kilin/conversation_memory/test_feedback.py +++ b/tests/kilin/conversation_memory/test_feedback.py @@ -50,6 +50,7 @@ def setUp(self): def _set_turns(self, conversation_id, turns): path = self.conversations.state_path(conversation_id) payload = json.loads(path.read_text(encoding="utf-8")) + conversation_state(payload)["system_prompt"] = "Use project sources." conversation_state(payload)["turns"] = [ _turn_to_data(turn) for turn in turns ] diff --git a/tests/kilin/conversation_memory/test_inspection.py b/tests/kilin/conversation_memory/test_inspection.py index 0382c867..1c333ca5 100644 --- a/tests/kilin/conversation_memory/test_inspection.py +++ b/tests/kilin/conversation_memory/test_inspection.py @@ -45,6 +45,7 @@ def setUp(self): ) path = self.store.state_path(self.conversation) data = json.loads(path.read_text()) + conversation_state(data)["system_prompt"] = "Use project sources." conversation_state(data)["turns"] = [rag._turn_to_data(self.turn)] path.write_text(json.dumps(data), encoding="utf-8") self.config = project_type("writing") diff --git a/tests/kilin/gui/test__read_while_answering.py b/tests/kilin/gui/test__read_while_answering.py index 55818d68..8caa8289 100644 --- a/tests/kilin/gui/test__read_while_answering.py +++ b/tests/kilin/gui/test__read_while_answering.py @@ -24,6 +24,11 @@ ) from kilin.conversation_format import new_conversation_session +from tests.kilin._conversation_support import ( + conversation_metadata, + resumable_state, + saved_turn, +) _WEB = Path(__file__).resolve().parents[3] / "kilin/gui/web" @@ -68,16 +73,15 @@ def test_turns_of_the_requested_chat_with_their_timing(self): "phase": "generating", "label": "Generating answer", "ms": 1200, }]} - first = { - "timestamp": "t1", "question": "Q1", "answer": "A1", - "timeline": timing, - } - second = {"timestamp": "t2", "question": "Q2", "answer": "A2"} + first = saved_turn("Q1", "A1", timestamp="t1", timeline=timing) + second = saved_turn("Q2", "A2", timestamp="t2") self._save(root, "conversation_1.json", { - "conversation_id": "other", "turns": [second], + **conversation_metadata("other"), + **resumable_state([second]), }) self._save(root, "conversation_2.json", { - "conversation_id": "wanted", "turns": [first], + **conversation_metadata("wanted"), + **resumable_state([first]), }) turns = self.read(root, "wanted") self.assertFalse( @@ -96,7 +100,8 @@ def test_missing_or_unreadable_chats_give_none(self): (traces / "conversation_bad.json").write_text("{", "utf-8") self.assertIsNone(self.read(root, "wanted")) self._save(root, "conversation_3.json", { - "conversation_id": "wanted", "turns": "not a list", + **conversation_metadata("wanted"), + **resumable_state(), "turns": "not a list", }) self.assertIsNone(self.read(root, "wanted")) diff --git a/tests/kilin/gui/test_engine__conversation_memory.py b/tests/kilin/gui/test_engine__conversation_memory.py index 17450a31..19db0846 100644 --- a/tests/kilin/gui/test_engine__conversation_memory.py +++ b/tests/kilin/gui/test_engine__conversation_memory.py @@ -55,6 +55,7 @@ def setUp(self) -> None: ) path = self.store.state_path(self.conversation) saved = json.loads(path.read_text(encoding="utf-8")) + conversation_state(saved)["system_prompt"] = "Use project sources." conversation_state(saved)["turns"] = [ rag._turn_to_data(self.turn) ] diff --git a/tests/kilin/gui/test_engine__memory_management.py b/tests/kilin/gui/test_engine__memory_management.py index 80a1b655..293a13b8 100644 --- a/tests/kilin/gui/test_engine__memory_management.py +++ b/tests/kilin/gui/test_engine__memory_management.py @@ -44,6 +44,7 @@ def setUp(self): ) path = self.store.state_path(self.conversation) data = json.loads(path.read_text(encoding="utf-8")) + conversation_state(data)["system_prompt"] = "Use project sources." conversation_state(data)["turns"] = [rag._turn_to_data(self.turn)] path.write_text(json.dumps(data), encoding="utf-8") self.checkpoint = path.read_bytes() diff --git a/tests/kilin/gui/test_engine__projects.py b/tests/kilin/gui/test_engine__projects.py index 63b06cea..f066c2ce 100644 --- a/tests/kilin/gui/test_engine__projects.py +++ b/tests/kilin/gui/test_engine__projects.py @@ -25,6 +25,7 @@ from kilin.project import configure_project, open_project from kilin.workspace import prepare_sources_workspace +from tests.kilin._conversation_support import saved_turn @dataclass @@ -33,6 +34,9 @@ class Turn: answer: str parameters: dict = field(default_factory=dict) evidence: tuple = () + timestamp: str = "2026-01-01T00:00:00Z" + conversation_turn_uuid: str = "" + timeline: dict | None = None class FakeSession: @@ -106,11 +110,9 @@ def setUp(self): self.active = store.ensure() self.history_path = store.state_path(self.active) payload = json.loads(self.history_path.read_text(encoding="utf-8")) + conversation_state(payload)["system_prompt"] = "Use project sources." conversation_state(payload)["turns"] = [ - { - "question": "Original question", - "answer": "Original answer.", - } + saved_turn("Original question", "Original answer.") ] self.history_path.write_text(json.dumps(payload), encoding="utf-8") # Ensure the selected chat is not the most recently created one. diff --git a/tests/kilin/gui/test_engine__source_ownership.py b/tests/kilin/gui/test_engine__source_ownership.py index f632adce..45f2c531 100644 --- a/tests/kilin/gui/test_engine__source_ownership.py +++ b/tests/kilin/gui/test_engine__source_ownership.py @@ -27,6 +27,7 @@ from kilin.repository import _MANIFEST_VERSION from kilin.source_manifest import read_source_manifest from kilin.workspace import SOURCE_MANIFEST_VERSION +from tests.kilin._conversation_support import resumable_state, saved_turn class TestEngineSourceOwnership(unittest.TestCase): @@ -352,9 +353,9 @@ def test_saved_conversations_and_metadata_remain_readable(self): conversation = store.ensure() path = store.state_path(conversation) value = json.loads(path.read_text()) - conversation_state(value)["turns"] = [ - {"question": "Saved question", "answer": "Saved answer"}, - ] + conversation_state(value).update(resumable_state([ + saved_turn("Saved question", "Saved answer"), + ])) path.write_text(json.dumps(value)) saved = read_source_manifest(self.project) self.ownership("conflict") diff --git a/tests/kilin/gui/test_engine__workflow.py b/tests/kilin/gui/test_engine__workflow.py index f1964c07..30708657 100644 --- a/tests/kilin/gui/test_engine__workflow.py +++ b/tests/kilin/gui/test_engine__workflow.py @@ -19,7 +19,6 @@ from kilin._model_completion import GenerationCancelled from kilin.conversation_format import conversation_state -from kilin.conversation_memory.models import new_turn_uuid from kilin.gui.engine import ChatEngine from kilin.project_behavior import ( effective_project_type, @@ -27,6 +26,7 @@ ) from kilin.gui.model_catalog import MODEL_CHOICES from kilin.workspace import prepare_sources_workspace +from tests.kilin._conversation_support import saved_turn @dataclass @@ -632,10 +632,8 @@ def test_new_chat_reopens_an_unused_empty_chat(self, rag): first = engine.active_conversation path = store.state_path(first) payload = json.loads(path.read_text(encoding="utf-8")) - conversation_state(payload)["turns"] = [{ - "conversation_turn_uuid": new_turn_uuid(), - "question": "Asked", - }] + conversation_state(payload)["system_prompt"] = "Use project sources." + conversation_state(payload)["turns"] = [saved_turn("Asked")] path.write_text(json.dumps(payload), encoding="utf-8") engine.create_conversation() @@ -663,11 +661,9 @@ def test_branch_from_a_message_keeps_its_first_turns(self, rag): path = engine.conversation_store.state_path(parent) payload = json.loads(path.read_text(encoding="utf-8")) turns = [ - {"conversation_turn_uuid": new_turn_uuid(), - "question": "First"}, - {"conversation_turn_uuid": new_turn_uuid(), - "question": "Second"}, + saved_turn("First"), saved_turn("Second"), ] + conversation_state(payload)["system_prompt"] = "Use project sources." conversation_state(payload)["turns"] = turns path.write_text(json.dumps(payload), encoding="utf-8") diff --git a/tests/kilin/system_testing/test_experiment.py b/tests/kilin/system_testing/test_experiment.py index c2b5d27c..db1e699e 100644 --- a/tests/kilin/system_testing/test_experiment.py +++ b/tests/kilin/system_testing/test_experiment.py @@ -671,7 +671,11 @@ def test_invalid_saved_conversation_content(self): if "resume_state" in s) state["turns"][0]["answer"] = "Altered" path.write_text(json.dumps(data), encoding="utf-8") - self.assertInvalid("conversation.state") + before = path.read_bytes() + # Shared schema validation rejects the stale content hash before + # recording-history comparison can consume the altered answer. + self.assertInvalid("conversation.invalid") + self.assertEqual(path.read_bytes(), before) def test_invalid_interaction_label(self): self.fixture.commands.append({"action": "plan_choice", diff --git a/tests/kilin/test__conversation_lifecycle.py b/tests/kilin/test__conversation_lifecycle.py index af31e545..f6e80606 100644 --- a/tests/kilin/test__conversation_lifecycle.py +++ b/tests/kilin/test__conversation_lifecycle.py @@ -32,6 +32,11 @@ TraceConfig, TraceLogger, ) +from tests.kilin._conversation_support import ( + checkpoint_state, + conversation_metadata, + resumable_state, +) def _read(path: Path) -> dict: @@ -187,7 +192,7 @@ def test_reset_preserves_archive_and_clears_active_state(self): data={"question": "Old question"}, ) trace.update_conversation( - {"turns": [], "checkpoint_id": "old-checkpoint"} + checkpoint_state("old-checkpoint") ) before = self.path.read_bytes() session.turns = [object()] @@ -258,7 +263,7 @@ def test_sequential_reopens_preserve_turns_and_operations(self): turn_id=f"id-{number}", data={"question": f"Question {number}"}, ) - trace.update_conversation({"checkpoint_id": f"cp-{number}"}) + trace.update_conversation(checkpoint_state(f"cp-{number}")) trace.close() group = _group(self.path) self.assertEqual( @@ -406,12 +411,12 @@ def test_reject_obsolete_and_malformed_existing_files(self): def test_reopen_keeps_canonical_resume_state_and_trace_operations(self): trace = _logger(self.path) - trace.update_conversation({"checkpoint_id": "before"}) + trace.update_conversation(checkpoint_state("before")) trace.emit("conversation.restored", component="rag") trace.close() previous = _group(self.path) trace = _logger(self.path) - trace.update_conversation({"checkpoint_id": "after"}) + trace.update_conversation(checkpoint_state("after")) trace.emit("turn.started", component="rag", turn_id="new") trace.close() current = _group(self.path) @@ -561,7 +566,7 @@ def test_untraced_rag_checkpoint_keeps_canonical_metadata(self): path = self.store.state_path(item) payload = _read(path) group = payload["sessions"][CONVERSATION_SESSION_KEY] - group["resume_state"]["custom_note"] = {"origin": "session"} + group["custom_note"] = {"origin": "session"} group["operations"] = {"01_action": {"title": "Retained"}} path.write_text(json.dumps(payload), encoding="utf-8") @@ -571,7 +576,7 @@ def test_untraced_rag_checkpoint_keeps_canonical_metadata(self): session._save_conversation() saved = _read(path)["sessions"][CONVERSATION_SESSION_KEY] - self.assertEqual(saved["resume_state"]["custom_note"], + self.assertEqual(saved["custom_note"], {"origin": "session"}) self.assertEqual(saved["resume_state"]["conversation_id"], item.conversation_id) @@ -674,7 +679,7 @@ def test_reset_closed_session_does_not_touch_disk(self): def test_grouped_state_survives_trace_restart(self): trace = _logger(self.path) - trace.update_conversation({"turns": [], "checkpoint_id": "saved"}) + trace.update_conversation(checkpoint_state("saved")) trace.close() new_trace = _logger(self.path) self.addCleanup(new_trace.close) @@ -685,11 +690,14 @@ def test_grouped_state_survives_trace_restart(self): def test_sequential_trace_reopens_preserve_grouped_metadata(self): trace = _logger(self.path) - trace.update_conversation({"name": "Session", "turns": []}) + trace.update_conversation({ + **conversation_metadata(name="Session"), + **resumable_state(), + }) trace.close() reopened = _logger(self.path) self.addCleanup(reopened.close) - reopened.update_conversation({"checkpoint_id": "updated"}) + reopened.update_conversation(checkpoint_state("updated")) state = conversation_state(_read(self.path)) self.assertEqual(state["name"], "Session") self.assertEqual(state["checkpoint_id"], "updated") diff --git a/tests/kilin/test__conversation_memory_index.py b/tests/kilin/test__conversation_memory_index.py index ffa3c836..2a4f6ee8 100644 --- a/tests/kilin/test__conversation_memory_index.py +++ b/tests/kilin/test__conversation_memory_index.py @@ -80,6 +80,7 @@ def setUp(self): def _write(self, info, turns): path = self.store.state_path(info) data = json.loads(path.read_text(encoding="utf-8")) + conversation_state(data)["system_prompt"] = "Use project sources." conversation_state(data)["turns"] = [ rag._turn_to_data(turn) for turn in turns ] diff --git a/tests/kilin/test__conversation_memory_integrated.py b/tests/kilin/test__conversation_memory_integrated.py index 4dc67cca..3c8d0fe2 100644 --- a/tests/kilin/test__conversation_memory_integrated.py +++ b/tests/kilin/test__conversation_memory_integrated.py @@ -166,6 +166,7 @@ def setUp(self): def _write(self, info, turns): path = self.store.state_path(info) saved = json.loads(path.read_text(encoding="utf-8")) + conversation_state(saved)["system_prompt"] = "Use project sources." conversation_state(saved)["turns"] = [ rag._turn_to_data(item) for item in turns ] diff --git a/tests/kilin/test__conversation_schema_consumers.py b/tests/kilin/test__conversation_schema_consumers.py new file mode 100644 index 00000000..526f1916 --- /dev/null +++ b/tests/kilin/test__conversation_schema_consumers.py @@ -0,0 +1,263 @@ +"""Enforce current conversation records across read-only consumers. + +Exercise actual saved files and derived memory caches. Invalid records must +not become usable through a GUI, memory, or recording-inspection shortcut. + +""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from copy import deepcopy +from dataclasses import replace +import json +from pathlib import Path +from tempfile import TemporaryDirectory +from types import SimpleNamespace +import unittest +from unittest.mock import Mock + +from kilin.conversation_format import conversation_state +from kilin.conversation_memory import index as memory_index +from kilin.conversation_memory.inspection import ( + inspect_memory_messages, + read_memory_summaries, +) +from kilin.conversation_memory.persistence import ( + memory_index_path, + read_memory_index, + write_memory_index, +) +from kilin.conversations import ConversationStore +from kilin.gui.engine import ChatEngine +from kilin.project_type import project_type +from kilin.system_testing.traces import read_recording +from kilin.trace_logging import TraceConfig, TraceLogger +from tests.kilin._conversation_support import ( + checkpoint_state, + resumable_state, + saved_turn, +) + + +class TestConversationSchemaConsumers(unittest.TestCase): + """Use the same complete turn contract at every read boundary.""" + + def setUp(self): + directory = TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name).resolve() + self.store = ConversationStore(self.root) + self.info = self.store.create() + self.path = self.store.state_path(self.info) + self.payload = json.loads(self.path.read_text(encoding="utf-8")) + self.turn = saved_turn(parameters={ + "intent": "writing", + "usage": {"input_tokens": 3, "output_tokens": 5}, + "representation": {"summary": "Saved scientific summary"}, + }) + conversation_state(self.payload).update(checkpoint_state( + turns=[self.turn], + )) + self._write(self.payload) + config = project_type("writing") + self.config = replace(config, conversation_memory=replace( + config.conversation_memory, enabled=True, + )) + self.embedding = Mock() + self.embedding.embed_documents.side_effect = ( + lambda texts, **_kwargs: [[1.0] for _ in texts] + ) + self.engine = ChatEngine(self.root, lambda _event: None) + self.engine.session = SimpleNamespace( + project=SimpleNamespace(root=self.root), turns=[], + ) + + def _write(self, payload): + self.path.write_text(json.dumps(payload), encoding="utf-8") + + def _sync(self): + return memory_index.synchronize_memory( + self.root, self.config, self.embedding, + model_identity="test-embedding", + ) + + def _references(self): + return [{ + "turn_uuid": self.turn["conversation_turn_uuid"], + "role": "assistant", + "origins": [{ + "conversation_id": self.info.conversation_id, + "turn_number": 1, + }], + }] + + def test_malformed_turn_and_checkpoint_fail_before_memory_work(self): + for kind in ("timeline", "parameters", "hash", "origin"): + with self.subTest(kind=kind): + payload = deepcopy(self.payload) + state = conversation_state(payload) + if kind in ("timeline", "parameters"): + del state["turns"][0][kind] + elif kind == "hash": + state["checkpoint"]["conversation_sha256"] = "0" * 64 + else: + del state["origin_turn_count"] + self._write(payload) + before = self.path.read_bytes() + with self.assertRaises(ValueError): + self._sync() + with self.assertRaises(ValueError): + inspect_memory_messages(self.root, self.config) + with self.assertRaises(ValueError): + read_memory_summaries(self.store, self._references()) + self.assertEqual(self.path.read_bytes(), before) + self.assertFalse(memory_index_path(self.root).exists()) + self.embedding.embed_documents.assert_not_called() + self.assertEqual(self.engine._usage_totals()["project"], { + "input_tokens": 0, "output_tokens": 0, "answers": 0, + }) + self.assertEqual(self.path.read_bytes(), before) + + def test_valid_untimed_turn_has_consistent_reader_results(self): + before = self.path.read_bytes() + page = inspect_memory_messages(self.root, self.config) + self.assertEqual(page.total, 2) + self.assertEqual(read_memory_summaries( + self.store, self._references(), + )[0]["text"], "Saved scientific summary") + self.assertEqual(self.engine._usage_totals()["project"], { + "input_tokens": 3, "output_tokens": 5, "answers": 1, + }) + self.assertIsNone(self.turn["timeline"]) + self.assertEqual(self.path.read_bytes(), before) + + def test_core_only_state_and_metadata_only_state_remain_readable(self): + core = deepcopy(self.payload) + state = conversation_state(core) + state.clear() + state.update(resumable_state([self.turn])) + self._write(core) + before = self.path.read_bytes() + page = inspect_memory_messages(self.root, self.config) + self.assertEqual(page.total, 2) + self.assertTrue(all(item["conversation_id"] == self.path.stem + for item in page.messages)) + self.assertEqual(self.engine._usage_totals()["project"]["answers"], 1) + self.assertEqual(self.path.read_bytes(), before) + + metadata_only = deepcopy(self.payload) + state = conversation_state(metadata_only) + for key in ("system_prompt", "turns", "checkpoint", "checkpoint_id"): + del state[key] + self._write(metadata_only) + self.assertEqual(inspect_memory_messages( + self.root, self.config, + ).messages, ()) + self.assertEqual(self.engine._usage_totals()["project"]["answers"], 0) + + def test_existing_index_cannot_bypass_first_schema_validation(self): + self._sync() + index_path = memory_index_path(self.root) + saved = read_memory_index(index_path) + self.assertIsNotNone(saved) + payload = deepcopy(self.payload) + del conversation_state(payload)["turns"][0]["timeline"] + self._write(payload) + # Model a cache built by a previous permissive reader: its source + # file signature agrees exactly, despite the unsupported source data. + saved["manifest"] = [list(item) for item in memory_index._manifest( + self.root, + )] + write_memory_index(index_path, saved) + memory_index._OBSERVED_MANIFESTS.pop( + (str(self.root), "test-embedding"), None, + ) + before = index_path.read_bytes(), self.path.read_bytes() + self.embedding.reset_mock() + with self.assertRaises(ValueError): + self._sync() + self.embedding.embed_documents.assert_not_called() + self.assertEqual(before, ( + index_path.read_bytes(), self.path.read_bytes(), + )) + + def test_recording_reader_reports_the_same_invalid_saved_state(self): + (self.root / "profile.ini").touch() + logger = TraceLogger( + TraceConfig(enabled=True, output_path=self.path, + failure_policy="raise"), + default_directory=self.path.parent, project_directory=self.root, + ) + logger.close() + original = json.loads(self.path.read_text(encoding="utf-8")) + for kind in ("evidence", "count", "timeline"): + with self.subTest(kind=kind): + payload = deepcopy(original) + state = conversation_state(payload) + if kind == "count": + state["checkpoint"]["turn_count"] = True + else: + del state["turns"][0][kind] + self._write(payload) + before = self.path.read_bytes() + recording = read_recording(self.root) + self.assertIn("conversation.invalid", { + issue.code for issue in recording.issues + }) + self.assertNotIn( + self.path.relative_to(self.root).as_posix(), + recording.states, + ) + self.assertEqual(self.path.read_bytes(), before) + + def test_usage_extension_rejects_coerced_token_counts(self): + for value in ("3", True, 3.5, -1, None): + with self.subTest(value=value): + turn = deepcopy(self.turn) + turn["parameters"]["usage"]["input_tokens"] = value + payload = deepcopy(self.payload) + conversation_state(payload).update(checkpoint_state( + turns=[turn], + )) + self._write(payload) + before = self.path.read_bytes() + self.assertEqual( + self.engine._usage_totals()["project"]["answers"], 0, + ) + self.assertEqual(self.path.read_bytes(), before) + + def test_usage_deduplicates_branches_and_preserves_new_answers(self): + self.store.create(branch_from=self.info.conversation_id) + self.assertEqual(self.engine._usage_totals()["project"]["answers"], 1) + second = self.store.create() + path = self.store.state_path(second) + payload = json.loads(path.read_text(encoding="utf-8")) + turn = saved_turn( + self.turn["question"], self.turn["answer"], + timestamp=self.turn["timestamp"], + parameters=deepcopy(self.turn["parameters"]), + ) + conversation_state(payload).update(checkpoint_state(turns=[turn])) + path.write_text(json.dumps(payload), encoding="utf-8") + self.assertEqual(self.engine._usage_totals()["project"], { + "input_tokens": 6, "output_tokens": 10, "answers": 2, + }) + + def test_invalid_usage_does_not_hide_valid_branch_usage(self): + self.store.create(branch_from=self.info.conversation_id) + payload = deepcopy(self.payload) + turn = deepcopy(self.turn) + turn["parameters"]["usage"]["input_tokens"] = "3" + conversation_state(payload).update(checkpoint_state(turns=[turn])) + self._write(payload) + before = self.path.read_bytes() + self.assertEqual(self.engine._usage_totals()["project"], { + "input_tokens": 3, "output_tokens": 5, "answers": 1, + }) + self.assertEqual(self.path.read_bytes(), before) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/test__trace_json.py b/tests/kilin/test__trace_json.py index e80cd2c3..9c76d922 100644 --- a/tests/kilin/test__trace_json.py +++ b/tests/kilin/test__trace_json.py @@ -19,6 +19,11 @@ TraceConfig, TraceLogger, ) +from tests.kilin._conversation_support import ( + conversation_metadata, + resumable_state, + saved_turn, +) class TestTraceJSON(unittest.TestCase): @@ -172,14 +177,14 @@ def test_both_writers_retain_decoded_events_and_receipt_digest(self): self.addCleanup(logger.close) if scope == "conversation": logger.update_conversation({ - "conversation_id": "a", - "name": "Formatter fixture", - "parent_conversation_id": None, - "origin_checkpoint_id": None, - "created_at_utc": "2026-12-02T00:00:00Z", - "updated_at_utc": "2026-12-02T00:00:00Z", - "turns": [], - "token_fixture": tokens, + **conversation_metadata( + "a", "Formatter fixture", + created_at_utc="2026-12-02T00:00:00Z", + updated_at_utc="2026-12-02T00:00:00Z", + ), + **resumable_state([saved_turn( + parameters={"token_fixture": tokens}, + )]), }) logger.emit( TRACE_EVENT_LLM_CALL_INPUT, diff --git a/tests/kilin/test_conversation_format.py b/tests/kilin/test_conversation_format.py index 9dd8376e..c5190891 100644 --- a/tests/kilin/test_conversation_format.py +++ b/tests/kilin/test_conversation_format.py @@ -30,6 +30,12 @@ def test_public_exports_are_canonical(self) -> None: "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", } self.assertEqual(set(fmt.__all__), expected) for name in expected: diff --git a/tests/kilin/test_conversation_format__schema.py b/tests/kilin/test_conversation_format__schema.py new file mode 100644 index 00000000..0b8c92ee --- /dev/null +++ b/tests/kilin/test_conversation_format__schema.py @@ -0,0 +1,384 @@ +"""Validate each current conversation lifecycle without repairing saved data. + +Use complete positive records and isolate missing fields, exact JSON types, +checkpoint relationships, and reader ambiguity. Parameters remain extensible; +registration metadata, completed turns, and checkpoints have fixed shapes. + +""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from __future__ import annotations + +from copy import deepcopy +import json +import math +from pathlib import Path +import unittest + +from kilin import conversation_format as fmt +from tests.kilin._conversation_support import ( + checkpoint_state, + conversation_metadata, + resumable_state, + saved_turn, +) + + +def _evidence() -> dict[str, object]: + """Return a complete descriptive reference to a historical source.""" + + return { + "citation": 1, + "path": "removed/paper.tex", + "start_line": 3, + "end_line": 8, + "symbol": None, + "text": "Historical source text.", + "cell": None, + "context_role": None, + } + + +def _payload(state: dict[str, object]) -> dict[str, object]: + """Wrap state in an independent current diagnostic envelope.""" + + return {"sessions": { + fmt.CONVERSATION_SESSION_KEY: fmt.new_conversation_session(state), + }} + + +class TestConversationStateSchema(unittest.TestCase): + """Exercise legitimate states and every fixed record boundary.""" + + def _reject_unchanged(self, state: object) -> None: + before = deepcopy(state) + with self.assertRaises(ValueError): + fmt.validate_conversation_state(state) + self.assertEqual(state, before) + + def test_lifecycle_groups_are_independent_and_preserved(self): + core = resumable_state([saved_turn()]) + completed = checkpoint_state("original-runtime", [saved_turn()]) + metadata = conversation_metadata() + states = ( + {}, metadata, resumable_state(), core, completed, + {**metadata, **resumable_state()}, {**metadata, **core}, + {**metadata, **completed}, + ) + for state in states: + with self.subTest(fields=tuple(state)): + before = deepcopy(state) + self.assertIs(fmt.validate_conversation_state(state), state) + payload = _payload(state) + self.assertIs(fmt.validate_conversation_payload(payload), + state) + self.assertEqual(state, before) + encoded = json.dumps(payload, ensure_ascii=False) + self.assertEqual(fmt.read_conversation_json(encoded), payload) + + def test_registration_requires_every_nullable_field_explicitly(self): + valid = conversation_metadata() + for field in valid: + with self.subTest(field=field): + state = deepcopy(valid) + state.pop(field) + self._reject_unchanged(state) + self.assertIsNone(valid["parent_conversation_id"]) + self.assertIsNone(valid["origin_checkpoint_id"]) + self.assertIsNone(valid["origin_turn_count"]) + + def test_registration_accepts_safe_opaque_ids_and_equivalent_utc(self): + state = conversation_metadata( + "project_7-other", "Ångström 日本語", + created_at_utc="2026-01-01T00:00:00+00:00", + updated_at_utc="2026-01-01T00:00:00.123456Z", + parent_conversation_id="parent_A", origin_checkpoint_id="c:1/x", + origin_turn_count=0, + ) + before = deepcopy(state) + self.assertEqual(fmt.validate_conversation_metadata(state), before) + self.assertEqual(state, before) + + def test_partial_prompt_and_turn_groups_are_rejected(self): + for state in ({"system_prompt": "Prompt"}, {"turns": []}): + self._reject_unchanged(state) + for prompt in (None, False, 1, [], {}): + with self.subTest(prompt=prompt): + self._reject_unchanged({"system_prompt": prompt, "turns": []}) + for turns in (None, False, 1, "", {}): + with self.subTest(turns=turns): + self._reject_unchanged({"system_prompt": "", "turns": turns}) + + def test_completed_turn_requires_every_field(self): + valid = saved_turn(evidence=[_evidence()]) + for field in valid: + with self.subTest(field=field): + turn = deepcopy(valid) + turn.pop(field) + self._reject_unchanged(resumable_state([turn])) + + def test_turn_text_is_never_coerced(self): + for field in ("timestamp", "question", "answer"): + for value in (None, 7, True, [], {}): + with self.subTest(field=field, value=value): + turn = saved_turn() + turn[field] = value + self._reject_unchanged(resumable_state([turn])) + empty = saved_turn("", "", timestamp="") + self.assertIs(fmt.validate_conversation_turn(empty), empty) + + def test_turns_require_distinct_canonical_uuid4_identities(self): + turn = saved_turn() + for value in (None, "", "f" * 32, 7, {}, []): + with self.subTest(value=value): + bad = {**turn, "conversation_turn_uuid": value} + self._reject_unchanged(resumable_state([bad])) + self._reject_unchanged(resumable_state([turn, deepcopy(turn)])) + + def test_evidence_requires_all_eight_fields(self): + valid = _evidence() + for field in valid: + with self.subTest(field=field): + item = deepcopy(valid) + item.pop(field) + self._reject_unchanged(resumable_state([ + saved_turn(evidence=[item]), + ])) + + def test_evidence_exact_values_and_ranges_are_required(self): + invalid = { + "citation": (None, True, False, 0, -1, 1.0, "1", [], {}), + "start_line": (None, True, False, 0, -1, 3.0, "3", [], {}), + "end_line": (None, True, False, 0, 2, 8.0, "8", [], {}), + "path": (None, True, 3, [], {}, "", "bad\x00path"), + "symbol": (True, 3, [], {}), + "text": (None, True, 3, [], {}), + "cell": (True, False, 0, -1, 1.0, "1", [], {}), + "context_role": (False, 1, "primary", [], {}), + } + for field, values in invalid.items(): + for value in values: + with self.subTest(field=field, value=value): + item = {**_evidence(), field: value} + self._reject_unchanged(resumable_state([ + saved_turn(evidence=[item]), + ])) + for value in (None, False, "text", {}, 1): + with self.subTest(evidence=value): + turn = saved_turn() + turn["evidence"] = value + self._reject_unchanged(resumable_state([turn])) + + def test_evidence_nullable_fields_and_historical_paths_are_valid(self): + for role in (None, "direct", "related", "alternative"): + for cell in (None, 1, 18): + with self.subTest(role=role, cell=cell): + item = {**_evidence(), "context_role": role, "cell": cell} + turn = saved_turn(evidence=[item]) + self.assertIs(fmt.validate_conversation_turn(turn), turn) + self.assertEqual(turn["evidence"][0]["path"], + "removed/paper.tex") + empty = saved_turn(evidence=[]) + self.assertIs(fmt.validate_conversation_turn(empty), empty) + + def test_parameters_have_extensible_keys_but_json_values_only(self): + parameters = { + "tool-specific": [{"tuple_is_not_required": [None, True, 1, 1.5]}], + "question": "研究", "null_value": None, + } + turn = saved_turn(parameters=parameters) + self.assertIs(fmt.validate_conversation_turn(turn), turn) + self.assertIs(turn["parameters"], parameters) + for value in (None, [], "", 1, False): + with self.subTest(parameters=value): + invalid = {**saved_turn(), "parameters": value} + self._reject_unchanged(resumable_state([invalid])) + for value in (Path("file"), object(), (1, 2), {3}, {1: "coerced"}): + with self.subTest(nested=type(value).__name__): + invalid = saved_turn(parameters={"nested": [value]}) + with self.assertRaises(ValueError): + fmt.validate_conversation_turn(invalid) + for number in (float("nan"), float("inf"), float("-inf")): + with self.subTest(number=number): + invalid = saved_turn(parameters={"nested": {"x": number}}) + with self.assertRaises(ValueError): + fmt.validate_conversation_turn(invalid) + cycle = {} + cycle["self"] = cycle + with self.assertRaises(ValueError): + fmt.validate_conversation_turn(saved_turn(parameters=cycle)) + + def test_timeline_explicit_null_and_valid_duration_are_preserved(self): + untimed = saved_turn(timeline=None) + self.assertIs(fmt.validate_conversation_turn(untimed), untimed) + timed = saved_turn(timeline={ + "elapsed_ms": 5, + "steps": [{"phase": "generating", "label": "Answer", "ms": 5}], + }) + self.assertIs(fmt.validate_conversation_turn(timed), timed) + invalid = deepcopy(timed) + invalid["timeline"]["elapsed_ms"] = 6 + self._reject_unchanged(resumable_state([invalid])) + invalid = deepcopy(timed) + invalid["timeline"]["steps"][0]["ms"] = True + self._reject_unchanged(resumable_state([invalid])) + + def test_unknown_fields_are_rejected_at_every_fixed_record(self): + state = {**conversation_metadata(), **checkpoint_state( + "saved", [saved_turn(evidence=[_evidence()], timeline={ + "elapsed_ms": 1, + "steps": [{"phase": "x", "label": "X", "ms": 1}], + })], + )} + paths = ( + (), ("checkpoint",), ("turns", 0), + ("turns", 0, "evidence", 0), ("turns", 0, "timeline"), + ("turns", 0, "timeline", "steps", 0), + ) + for path in paths: + with self.subTest(path=path): + invalid = deepcopy(state) + target = invalid + for component in path: + target = target[component] + target["obsolete"] = None + self._reject_unchanged(invalid) + + def test_checkpoint_fields_are_mandatory_when_checkpoint_present(self): + valid = checkpoint_state("original", [saved_turn()]) + for field in valid["checkpoint"]: + with self.subTest(field=field): + state = deepcopy(valid) + state["checkpoint"].pop(field) + self._reject_unchanged(state) + for field in ("checkpoint", "checkpoint_id"): + with self.subTest(outer=field): + state = deepcopy(valid) + state.pop(field) + self._reject_unchanged(state) + for fields in ( + {"checkpoint_id": "saved"}, {"checkpoint": valid["checkpoint"]}, + {"checkpoint_id": "saved", "checkpoint": valid["checkpoint"]}, + ): + self._reject_unchanged(fields) + + def test_checkpoint_exact_types_and_consistency_are_required(self): + valid = checkpoint_state("original", [saved_turn()]) + invalid_fields = { + "checkpoint_id": (None, "", 3, False, [], {}, "different"), + "parent_checkpoint_id": ("", 3, False, [], {}), + "conversation_sha256": (None, 5, [], {}, "bad", "0" * 64), + "index_fingerprint": (None, 5, False, [], {}), + "turn_count": (None, "1", 1.0, True, False, -1, 0, 2, [], {}), + } + for field, values in invalid_fields.items(): + for value in values: + with self.subTest(field=field, value=value): + state = deepcopy(valid) + state["checkpoint"][field] = value + self._reject_unchanged(state) + for value in (None, "", 3, False, [], {}, "different"): + with self.subTest(outer=value): + state = deepcopy(valid) + state["checkpoint_id"] = value + self._reject_unchanged(state) + for field in ("system_prompt", "turns"): + with self.subTest(tampered=field): + state = deepcopy(valid) + if field == "turns": + state[field][0]["answer"] += " Changed" + else: + state[field] += " Changed" + self._reject_unchanged(state) + + def test_checkpoint_hash_uses_original_unicode_and_nullable_values(self): + state = checkpoint_state( + "opaque-runtime-id", [saved_turn("日本語", "Ångström")], + system_prompt="答え", parent_checkpoint_id="older:1/x", + index_fingerprint="", + ) + self.assertIs(fmt.validate_conversation_state(state), state) + self.assertEqual(state["checkpoint_id"], "opaque-runtime-id") + reordered = dict(reversed(list(state.items()))) + self.assertIs(fmt.validate_conversation_state(reordered), reordered) + + +class TestStrictConversationJson(unittest.TestCase): + """Reject parser ambiguity before any reader chooses one interpretation.""" + + def test_duplicate_keys_are_rejected_at_any_depth(self): + payload = _payload(checkpoint_state("check", [saved_turn()])) + text = json.dumps(payload) + cases = ( + text.replace('"sessions":', '"sessions": {}, "sessions":', 1), + text.replace('"turns": []', '"turns": [], "turns": []', 1), + text.replace('"answer": "Answer"', + '"answer": "First", "answer": "Answer"', 1), + text.replace('"parameters": {}', + '"parameters": {"x": 1, "x": 2}', 1), + ) + # The empty checkpoint is separate so its saved turn list is present. + empty = json.dumps(_payload(checkpoint_state())) + cases = cases[:1] + (empty.replace( + '"turns": []', '"turns": [], "turns": []', 1, + ),) + cases[2:] + for encoded in cases: + with self.subTest(encoded=encoded): + with self.assertRaisesRegex(ValueError, "duplicate"): + fmt.read_conversation_json(encoded) + + def test_nonfinite_parameters_and_number_overflow_are_rejected(self): + template = json.dumps(_payload(resumable_state([saved_turn()]))) + for token in ("NaN", "Infinity", "-Infinity", "1e999"): + with self.subTest(token=token): + text = template.replace('"parameters": {}', + '"parameters": {"nested": [' + + token + ']}') + self.assertNotEqual(text, template) + with self.assertRaisesRegex(ValueError, "parameters"): + fmt.read_conversation_json(text) + + def test_diagnostic_nonfinite_numbers_do_not_block_valid_resume(self): + state = checkpoint_state("retained", [saved_turn()]) + payload = _payload(state) + payload["diagnostic"] = { + "values": [float("nan"), float("inf"), float("-inf")], + } + parsed = fmt.read_conversation_json(json.dumps(payload)) + values = parsed["diagnostic"]["values"] + self.assertTrue(math.isnan(values[0])) + self.assertEqual(values[1:], [float("inf"), float("-inf")]) + self.assertEqual(fmt.validate_conversation_payload(parsed), state) + + def test_decode_requires_an_object_and_valid_json(self): + for encoded in ("{", "[]", "null", '"string"', "false", "7"): + with self.subTest(encoded=encoded): + with self.assertRaises(ValueError): + fmt.decode_conversation_json(encoded) + self.assertEqual(fmt.decode_conversation_json('{"a": 0.5}'), + {"a": 0.5}) + + def test_reader_rejects_missing_envelopes_and_partial_saved_groups(self): + unrelated = {"sessions": {"runtime": {"category": "runtime"}}} + for payload in ({}, {"sessions": {}}, unrelated): + with self.subTest(payload=payload): + text = json.dumps(payload) + with self.assertRaises(ValueError): + fmt.read_conversation_json(text) + self.assertEqual(fmt.decode_conversation_json(text), payload) + # Construction is explicit and separate from persisted-file reads. + result = deepcopy(unrelated) + self.assertEqual(fmt.conversation_state(result, create=True), {}) + self.assertEqual(result["sessions"]["runtime"], + {"category": "runtime"}) + for state in ({"turns": []}, {"conversation_id": "partial"}): + with self.subTest(state=state): + with self.assertRaises(ValueError): + fmt.read_conversation_json(json.dumps(_payload(state))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/test_conversations.py b/tests/kilin/test_conversations.py index c1d90c0b..99cae39e 100644 --- a/tests/kilin/test_conversations.py +++ b/tests/kilin/test_conversations.py @@ -24,7 +24,6 @@ from unittest.mock import patch from kilin import conversations as module -from kilin.conversation_memory.models import new_turn_uuid from kilin.conversation_ownership import ( ConversationFileLock, ConversationLockedError, @@ -35,12 +34,18 @@ new_conversation_session, ) +from tests.kilin._conversation_support import ( + checkpoint_state, + resumable_state, + saved_turn, +) + def _identified(turns: list[dict]) -> list[dict]: - """Give branching fixtures distinct current-format completed-turn IDs.""" + """Build complete turns with explicit fields and independent identities.""" return [ - {"conversation_turn_uuid": new_turn_uuid(), **item} + {**saved_turn(), **item} for item in turns ] @@ -142,9 +147,9 @@ def _candidate( "name": "Saved conversation", "parent_conversation_id": None, "origin_checkpoint_id": None, + "origin_turn_count": None, "created_at_utc": "2026-10-10T09:00:00.000Z", "updated_at_utc": "2026-10-10T10:00:00.000Z", - "turns": [], } state.update(metadata) path = self.store.root / filename @@ -329,7 +334,7 @@ def test_duplicate_ids_keep_first_sorted_file(self): def test_scan_discards_non_dictionary_state_from_helper(self): """Retain a defensive guard if the format helper changes.""" self._candidate("conversation_saved.json") - with patch("kilin.conversations.conversation_state", + with patch("kilin.conversations.validate_conversation_payload", return_value=[]): self.store._scan() self.assertEqual(self.store.conversations(), []) @@ -448,7 +453,7 @@ def test_metadata_validator_skips_missing_required_fields(self): missing = ( "conversation_id", "name", "parent_conversation_id", "origin_checkpoint_id", "created_at_utc", - "updated_at_utc", + "updated_at_utc", "origin_turn_count", ) for index, field in enumerate(missing): with self.subTest(field=field): @@ -652,13 +657,11 @@ class TestStoreBranching(ConversationStoreFixture): def test_branch_copies_resume_state_but_not_trace_operations(self): parent = self.store.create() turns = _identified([{"question": "Original", "answer": "Yes"}]) - self._persist(parent, { - "turns": turns, - "checkpoint_id": "checkpoint-123", - "checkpoint": {"parent_checkpoint_id": "before"}, - "system_prompt": "Do science", - "profile": {"kind": "literature"}, - }) + turns[0]["parameters"] = {"profile": {"kind": "literature"}} + self._persist(parent, checkpoint_state( + "checkpoint-123", turns, system_prompt="Do science", + parent_checkpoint_id="before", + )) payload = self._saved(self.store.state_path(parent)) session = payload["sessions"][CONVERSATION_SESSION_KEY] session["turns"] = {"turn_0001": {"title": "Parent event"}} @@ -676,7 +679,8 @@ def test_branch_copies_resume_state_but_not_trace_operations(self): self.assertEqual(saved["turns"], turns) self.assertEqual(saved["system_prompt"], "Do science") self.assertEqual(saved["checkpoint_id"], "checkpoint-123") - self.assertEqual(saved["profile"], {"kind": "literature"}) + self.assertEqual(saved["turns"][0]["parameters"]["profile"], + {"kind": "literature"}) self.assertEqual(saved["conversation_id"], branch.conversation_id) branched = self._saved(self.store.state_path(branch)) group = branched["sessions"][CONVERSATION_SESSION_KEY] @@ -700,7 +704,7 @@ def test_branch_preserves_core_timeline_on_selected_turns(self): {"question": "Q1", "answer": "A1", "timeline": activity}, {"question": "Q2", "answer": "A2", "timeline": activity}, ]) - self._persist(parent, {"turns": turns}) + self._persist(parent, resumable_state(turns)) branch = self.store.create( branch_from=parent.conversation_id, turn_count=1 ) @@ -714,10 +718,13 @@ def test_branch_preserves_core_timeline_on_selected_turns(self): def test_branch_does_not_copy_parent_identity_or_metadata(self): parent = self.store.create() - self._persist(parent, {"checkpoint_id": "one", "custom": 4}) + self._persist(parent, checkpoint_state( + "one", index_fingerprint="retained-index", + )) branched = self.store.create(branch_from=parent.conversation_id) state = self._state(branched) - self.assertEqual(state["custom"], 4) + self.assertEqual(state["checkpoint"]["index_fingerprint"], + "retained-index") for key, value in asdict(branched).items(): self.assertEqual(state[key], value) self.assertEqual(self._state(parent)["conversation_id"], @@ -727,8 +734,7 @@ def test_branch_from_imported_conversation_uses_canonical_state(self): turns = _identified([{"question": "Imported"}]) source = self._candidate( "conversation_external.json", - checkpoint_id="source-checkpoint", - turns=turns, + **checkpoint_state("source-checkpoint", turns), ) self.store.ensure() branch = self.store.create(branch_from="conversation_external") @@ -767,15 +773,21 @@ def test_long_branch_names_fit_the_name_limit(self): self.assertEqual(first.name, "Branch: " + "x" * 72) self.assertEqual(second.name, "Branch 2: " + "x" * 70) - def test_branches_without_valid_checkpoint_have_no_origin(self): + def test_branches_reject_invalid_checkpoint_without_mutation(self): parent = self.store.create() for value in (None, 23, "", [], {}): with self.subTest(value=value): - self._persist(parent, {"checkpoint_id": value}) - branched = self.store.create( - branch_from=parent.conversation_id - ) - self.assertIsNone(branched.origin_checkpoint_id) + invalid = checkpoint_state() + invalid["checkpoint_id"] = value + self._persist(parent, invalid) + path = self.store.state_path(parent) + before = path.read_bytes() + paths = set(self.store.root.iterdir()) + with self.assertRaisesRegex(ValueError, "checkpoint"): + self.store.create(branch_from=parent.conversation_id) + self.assertEqual(path.read_bytes(), before) + self.assertEqual(set(self.store.root.iterdir()), paths) + self.assertEqual(self.store.active(), parent) def test_branch_unknown_parent_does_not_create_file(self): before = list(self.store.root.glob("*.json")) if ( @@ -800,7 +812,9 @@ def test_branch_refuses_saved_turn_without_uuid(self): """Unsupported previous turn formats are never silently upgraded.""" parent = self.store.create() - self._persist(parent, {"turns": [{"question": "no identity"}]}) + self._persist(parent, resumable_state( + [{"question": "no identity"}], + )) before = self.store.state_path(parent).read_bytes() paths = set(self.store.root.iterdir()) with self.assertRaisesRegex(ValueError, "UUID4"): @@ -811,7 +825,7 @@ def test_branch_refuses_saved_turn_without_uuid(self): def test_branch_parent_with_missing_checkpoint_is_valid(self): parent = self.store.create() turns = _identified([{"question": "Q"}]) - self._persist(parent, {"turns": turns}) + self._persist(parent, resumable_state(turns)) branch = self.store.create(branch_from=parent.conversation_id) self.assertIsNone(branch.origin_checkpoint_id) self.assertEqual(self._state(branch)["turns"], turns) @@ -821,12 +835,9 @@ def test_branch_keeps_only_the_first_turns(self): turns = _identified([ {"question": f"Q{index}"} for index in range(1, 4) ]) - self._persist(parent, { - "turns": turns, - "checkpoint_id": "checkpoint-3", - "checkpoint": {"turn_count": 3}, - "system_prompt": "Do science", - }) + self._persist(parent, checkpoint_state( + "checkpoint-3", turns, system_prompt="Do science", + )) branch = self.store.create( branch_from=parent.conversation_id, turn_count=2 ) @@ -849,7 +860,7 @@ def test_branch_keeps_only_the_first_turns(self): def test_branch_turn_count_from_none_to_all_turns(self): parent = self.store.create() turns = _identified([{"question": "Q1"}, {"question": "Q2"}]) - self._persist(parent, {"turns": turns, "checkpoint_id": "two"}) + self._persist(parent, checkpoint_state("two", turns)) for turn_count, kept in ((0, []), (2, turns), (None, turns)): with self.subTest(turn_count=turn_count): branch = self.store.create( @@ -863,9 +874,9 @@ def test_branch_turn_count_from_none_to_all_turns(self): def test_branch_turn_count_outside_saved_turns_creates_nothing(self): parent = self.store.create() - self._persist(parent, { - "turns": _identified([{"question": "Q1"}, {"question": "Q2"}]) - }) + self._persist(parent, resumable_state( + _identified([{"question": "Q1"}, {"question": "Q2"}]), + )) before = set(self.store.root.iterdir()) for value in (-1, 3, True, 1.5, "1"): with self.subTest(value=value): @@ -884,13 +895,19 @@ def test_only_a_branch_can_keep_a_number_of_turns(self): self.store.create(turn_count=1) self.assertEqual(set(self.store.root.iterdir()), before) - def test_records_saved_before_branch_points_still_load(self): - self._candidate( + def test_records_missing_branch_points_are_rejected(self): + path = self._candidate( "conversation_older.json", parent_conversation_id="parent_01" ) - item = self.store.ensure() - self.assertEqual(item.conversation_id, "conversation_older") - self.assertIsNone(item.origin_turn_count) + payload = self._saved(path) + conversation_state(payload).pop("origin_turn_count") + path.write_text(json.dumps(payload), encoding="utf-8") + before = path.read_bytes() + with self.assertRaisesRegex(ValueError, "invalid"): + self.store.ensure() + self.assertEqual(path.read_bytes(), before) + self.assertEqual(self.store.conversations(), []) + self.assertIn(path, self.store.discovery_errors()) self.assertIsNone(self.store.create().origin_turn_count) @@ -914,13 +931,10 @@ def test_rename_collapses_whitespace_and_persists(self): def test_rename_preserves_saved_conversation_state(self): item = self.store.create() - self._persist(item, { - "turns": [{"question": "keep"}], - "checkpoint_id": "unchanged", - }) + turns = _identified([{"question": "keep"}]) + self._persist(item, checkpoint_state("unchanged", turns)) self.store.rename(item.conversation_id, "Updated") - self.assertEqual(self._state(item)["turns"], - [{"question": "keep"}]) + self.assertEqual(self._state(item)["turns"], turns) self.assertEqual(self._state(item)["checkpoint_id"], "unchanged") def test_rename_rejects_grouped_legacy_field_without_rewriting(self): @@ -968,7 +982,8 @@ def test_rename_stringifies_non_string_names(self): def test_touch_updates_metadata_and_preserves_other_fields(self): item = self.store.create() - self._persist(item, {"turns": [1], "checkpoint_id": "one"}) + turns = _identified([{"question": "Keep this turn"}]) + self._persist(item, checkpoint_state("one", turns)) with patch("kilin.conversations._utc_timestamp", return_value="2026-10-12T15:00:00.000Z"): touched = self.store.touch(item.conversation_id) @@ -976,7 +991,7 @@ def test_touch_updates_metadata_and_preserves_other_fields(self): self.assertEqual(touched.created_at_utc, item.created_at_utc) self.assertEqual(touched.updated_at_utc, "2026-10-12T15:00:00.000Z") - self.assertEqual(self._state(touched)["turns"], [1]) + self.assertEqual(self._state(touched)["turns"], turns) self.assertEqual(self._state(touched)["checkpoint_id"], "one") self.assertEqual(self.store.active(), touched) @@ -1072,16 +1087,20 @@ def test_missing_turn_field_counts_as_empty(self): def test_saved_turns_are_not_empty(self): item = self.store.create() - self._persist(item, {"turns": [{"question": "Hello"}]}) + self._persist(item, resumable_state( + _identified([{"question": "Hello"}]), + )) self.assertFalse(self.store.is_empty(item.conversation_id)) - self._persist(item, {"turns": []}) + self._persist(item, resumable_state([])) self.assertTrue(self.store.is_empty(item.conversation_id)) def test_non_list_turns_are_rejected(self): item = self.store.create() for invalid in ({}, "hello", None, 2, False): with self.subTest(invalid=invalid): - self._persist(item, {"turns": invalid}) + self._persist(item, { + **resumable_state(), "turns": invalid, + }) with self.assertRaisesRegex(ValueError, "invalid"): self.store.is_empty(item.conversation_id) @@ -1383,6 +1402,123 @@ def test_missing_source_archive_does_not_change_registry(self): self.assertEqual(self.store.active(), item) +class TestStoreStrictState(ConversationStoreFixture): + """Reject corruption before selecting, replacing, or moving records.""" + + def test_only_invalid_files_do_not_create_an_empty_replacement(self): + path = self._candidate("conversation_broken.json") + data = self._saved(path) + conversation_state(data)["turns"] = [] + path.write_text(json.dumps(data), encoding="utf-8") + before = {p: p.read_bytes() for p in self.store.root.iterdir()} + with self.assertRaisesRegex(ValueError, "no empty"): + self.store.ensure() + self.assertEqual(self.store.conversations(), []) + self.assertEqual( + {p: p.read_bytes() for p in self.store.root.iterdir()}, before, + ) + errors = self.store.discovery_errors() + self.assertIn(path, errors) + errors.clear() + self.assertIn(path, self.store.discovery_errors()) + + def test_valid_sibling_remains_accessible_with_visible_errors(self): + good = self._candidate("conversation_good.json") + bad = self._candidate("conversation_bad.json", origin_turn_count=True) + before = bad.read_bytes() + selected = self.store.ensure() + self.assertEqual(self.store.state_path(selected), good) + self.assertIn(bad, self.store.discovery_errors()) + self.assertEqual(bad.read_bytes(), before) + + def test_core_only_files_remain_unregistered_without_data_changes(self): + self.store.root.mkdir(parents=True) + path = self.store.root / "conversation_core.json" + payload = {"sessions": { + CONVERSATION_SESSION_KEY: new_conversation_session( + checkpoint_state("core", [saved_turn()]), + ), + }} + path.write_text(json.dumps(payload), encoding="utf-8") + before = path.read_bytes() + named = self.store.ensure() + self.assertNotEqual(self.store.state_path(named), path) + self.assertEqual(path.read_bytes(), before) + self.assertEqual(self.store.discovery_errors(), {}) + self.assertEqual(self.store.conversations(), [named]) + + def test_corruption_rejects_registered_operations_without_changes(self): + item = self.store.create() + state = checkpoint_state("saved", [saved_turn()]) + self._persist(item, state) + state["checkpoint"]["turn_count"] = True + self._persist(item, state) + path = self.store.state_path(item) + before, paths = path.read_bytes(), set(self.store.root.iterdir()) + operations = ( + lambda: self.store.select(item.conversation_id), + lambda: self.store.rename(item.conversation_id, "Changed"), + lambda: self.store.touch(item.conversation_id), + lambda: self.store.is_empty(item.conversation_id), + lambda: self.store.create(branch_from=item.conversation_id), + lambda: self.store.archive(item.conversation_id), + lambda: self.store.contains_turn(item.conversation_id, + state["turns"][0][ + "conversation_turn_uuid"]), + self.store.ensure, + ) + for operation in operations: + with self.subTest(operation=operation): + with self.assertRaises(ValueError): + operation() + self.assertEqual(path.read_bytes(), before) + self.assertEqual(set(self.store.root.iterdir()), paths) + self.assertEqual(self.store.active(), item) + self.assertEqual(self.store.conversations(), [item]) + self.assertFalse((self.store.root / ".deleted").exists()) + + def test_changed_registration_preserves_new_identity(self): + item = self.store.create() + self._persist(item, {"conversation_id": "external_identity"}) + path = self.store.state_path(item) + before = path.read_bytes() + for operation in (self.store.touch, self.store.select): + with self.subTest(operation=operation): + with self.assertRaisesRegex(ValueError, "registration"): + operation(item.conversation_id) + self.assertEqual(path.read_bytes(), before) + self.assertEqual(self.store.active(), item) + + def test_duplicate_json_is_rejected_before_metadata_update(self): + item = self.store.create() + path = self.store.state_path(item) + original = path.read_text(encoding="utf-8") + text = original.replace('"origin_turn_count": null', + '"origin_turn_count": 3, ' + '"origin_turn_count": null') + self.assertNotEqual(text, original) + path.write_text(text, encoding="utf-8") + before = path.read_bytes() + with self.assertRaisesRegex(ValueError, "duplicate"): + self.store.touch(item.conversation_id) + self.assertEqual(path.read_bytes(), before) + self.assertEqual(self.store.active(), item) + + def test_coordinated_writer_never_receives_invalid_saved_state(self): + item = self.store.create() + self._persist(item, {"checkpoint_id": "incomplete"}) + path = self.store.state_path(item) + before = path.read_bytes() + writes = [] + with ConversationFileLock(path) as owner: + with self.assertRaises(ValueError): + self.store.touch(item.conversation_id, ownership=owner, + state_writer=writes.append) + self.assertEqual(writes, []) + self.assertEqual(path.read_bytes(), before) + self.assertEqual(self.store.active(), item) + + class TestConversationJsonHelpers(ConversationStoreFixture): """Test isolated JSON utilities and their failure mapping.""" diff --git a/tests/kilin/test_rag.py b/tests/kilin/test_rag.py index 77e27d46..54efef6c 100644 --- a/tests/kilin/test_rag.py +++ b/tests/kilin/test_rag.py @@ -384,12 +384,17 @@ def test_turn_serialization_roundtrip_with_notebook_cell(self) -> None: self.assertEqual(payload["evidence"][0]["path"], "src/a.py") self.assertEqual(payload["evidence"][0]["cell"], 4) self.assertEqual(rag._turn_from_data(payload), original) - legacy = json.loads(json.dumps(payload)) - del legacy["evidence"][0]["cell"] - self.assertIsNone(rag._turn_from_data(legacy).evidence[0].cell) - legacy["evidence"][0]["citation"] = "2" - self.assertEqual(rag._turn_from_data(legacy).evidence[0].citation, - 2) + missing = json.loads(json.dumps(payload)) + del missing["evidence"][0]["cell"] + with self.assertRaisesRegex(ValueError, "evidence fields"): + rag._turn_from_data(missing) + missing["evidence"][0]["cell"] = None + self.assertIsNone(rag._turn_from_data(missing).evidence[0].cell) + missing["evidence"][0]["citation"] = "2" + with self.assertRaisesRegex(ValueError, "citation"): + rag._turn_from_data(missing) + missing["evidence"][0]["citation"] = 2 + self.assertEqual(rag._turn_from_data(missing).evidence[0].citation, 2) def test_turn_deserialization_rejects_invalid_records(self) -> None: """Reject malformed persisted turn and evidence records.""" @@ -398,10 +403,12 @@ def test_turn_deserialization_rejects_invalid_records(self) -> None: rag._turn_from_data({**payload, "evidence": "bad"}) with self.assertRaisesRegex(ValueError, "parameters"): rag._turn_from_data({**payload, "parameters": []}) - with self.assertRaises(KeyError): + with self.assertRaises(ValueError): rag._turn_from_data({**payload, "question": None, "timestamp": None, "answer": None, "evidence": [{}]}) + with self.assertRaisesRegex(ValueError, "evidence fields"): + rag._turn_from_data({**payload, "evidence": [{}]}) with self.assertRaises(ValueError): rag._turn_from_data({ **payload, "evidence": [ @@ -890,7 +897,12 @@ def test_constructor_closes_models_and_trace_on_index_failure( def test_constructor_closes_both_models_on_restore_failure(self) -> None: """Close loaded models if conversation restoration fails.""" with self._construction_patches() as mocks: - mocks.loaded.side_effect = ValueError("bad conversation") + mocks.loaded.return_value = ( + [{"role": "system", "content": "Saved"}], [], None, + ) + mocks.chat.return_value.restore_history.side_effect = ( + ValueError("bad conversation") + ) with self.assertRaisesRegex(ValueError, "bad conversation"): rag.RAGSession(self.root) mocks.embeddings.return_value.close.assert_called_once() @@ -983,7 +995,12 @@ def test_constructor_keeps_primary_error_when_cleanup_fails( """Attempt each cleanup step without masking restoration errors.""" with self._construction_patches() as mocks: - mocks.loaded.side_effect = ValueError("invalid history") + mocks.loaded.return_value = ( + [{"role": "system", "content": "Saved"}], [], None, + ) + mocks.chat.return_value.restore_history.side_effect = ( + ValueError("invalid history") + ) mocks.chat.return_value.close.side_effect = OSError( "chat cleanup failed" ) diff --git a/tests/kilin/test_rag__conversation.py b/tests/kilin/test_rag__conversation.py index 11b1f697..8b00621c 100644 --- a/tests/kilin/test_rag__conversation.py +++ b/tests/kilin/test_rag__conversation.py @@ -34,6 +34,8 @@ _turn, ) +from tests.kilin._conversation_support import checkpoint_state + class TestRAGLifecycle(unittest.TestCase): """Test model ownership, switching, refresh, and token bookkeeping.""" @@ -763,11 +765,10 @@ def test_load_canonical_turns_reconstructs_model_history(self) -> None: """Restore chat messages and turns from canonical saved records.""" session = self.session data = {"sessions": {CONVERSATION_SESSION_KEY: - new_conversation_session({ - "system_prompt": "Saved system prompt", - "turns": [rag._turn_to_data(_turn())], - "checkpoint_id": "checkpoint_previous", - })}} + new_conversation_session(checkpoint_state( + "checkpoint_previous", [rag._turn_to_data(_turn())], + system_prompt="Saved system prompt", + ))}} session.conversation_path.write_text( json.dumps(data), encoding="utf-8" ) @@ -810,7 +811,9 @@ def test_missing_or_duplicate_uuids_rejected_without_modifying_file( for items in invalid: with self.subTest(items=items): payload = {"sessions": {CONVERSATION_SESSION_KEY: - new_conversation_session({"turns": items})}} + new_conversation_session({ + "system_prompt": "Saved", "turns": items, + })}} self.session.conversation_path.write_text( json.dumps(payload), encoding="utf-8" ) @@ -853,22 +856,28 @@ def test_load_conversation_rejects_corrupt_records(self) -> None: with self.assertRaisesRegex(ValueError, "invalid"): session._load_conversation() - def test_load_conversation_ignores_invalid_checkpoint(self) -> None: - """Ignore invalid checkpoint identifiers while restoring turns.""" + def test_load_conversation_rejects_invalid_checkpoint(self) -> None: + """Reject malformed present checkpoints without changing the file.""" session = self.session + state = checkpoint_state() + state["checkpoint_id"] = 100 session.conversation_path.write_text(json.dumps({ "sessions": {CONVERSATION_SESSION_KEY: - new_conversation_session({ - "turns": [], "checkpoint_id": 100, - })}, + new_conversation_session(state)}, }), encoding="utf-8") - self.assertIsNone(session._load_conversation()[2]) + before = session.conversation_path.read_bytes() + with self.assertRaisesRegex(ValueError, "checkpoint ID"): + session._load_conversation() + self.assertEqual(session.conversation_path.read_bytes(), before) def test_save_preserves_existing_unrelated_sessions(self) -> None: """Keep unrelated trace sessions when saving without tracing.""" session = self.session session.conversation_path.write_text(json.dumps({ - "sessions": {"custom": {"title": "Keep"}}, + "sessions": { + "custom": {"title": "Keep"}, + CONVERSATION_SESSION_KEY: new_conversation_session(), + }, }), encoding="utf-8") session._save_conversation() payload = json.loads( @@ -1001,10 +1010,9 @@ def test_switch_conversation_reuses_models_and_restores_settings( }) target.write_text(json.dumps({ "sessions": {CONVERSATION_SESSION_KEY: - new_conversation_session({ - "turns": [rag._turn_to_data(earlier)], - "checkpoint_id": "restored", - })}, + new_conversation_session(checkpoint_state( + "restored", [rag._turn_to_data(earlier)], + ))}, }), encoding="utf-8") old_chat = session.chat_session turns = session.switch_conversation(target, trace=NullTraceLogger()) diff --git a/tests/kilin/test_rag__conversation_memory.py b/tests/kilin/test_rag__conversation_memory.py index d6c6efa1..9acab55d 100644 --- a/tests/kilin/test_rag__conversation_memory.py +++ b/tests/kilin/test_rag__conversation_memory.py @@ -30,6 +30,8 @@ ) from tests.kilin.test__conversation_memory_index import FakeEmbedding +from tests.kilin._conversation_support import resumable_state + class TestRAGConversationMemory(unittest.TestCase): def setUp(self): @@ -46,7 +48,9 @@ def setUp(self): ) path = self.store.state_path(earlier) data = json.loads(path.read_text(encoding="utf-8")) - conversation_state(data)["turns"] = [rag._turn_to_data(history)] + conversation_state(data).update(resumable_state( + [rag._turn_to_data(history)] + )) path.write_text(json.dumps(data), encoding="utf-8") current = self.store.create() self.session = _session(self.root) diff --git a/tests/kilin/test_rag__conversation_schema.py b/tests/kilin/test_rag__conversation_schema.py new file mode 100644 index 00000000..e0ddd09f --- /dev/null +++ b/tests/kilin/test_rag__conversation_schema.py @@ -0,0 +1,333 @@ +"""Exercise strict conversation boundaries across RAG and trace ownership. + +Use real persistence and locks with offline model doubles. Malformed state +must fail before diagnostic writes, inference initialization, or a committed +turn changes. Complete current lifecycle states remain independently usable. + +""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from __future__ import annotations + +from copy import deepcopy +from dataclasses import replace +import json +import math +from pathlib import Path +from tempfile import TemporaryDirectory +import unittest +from unittest.mock import patch + +from kilin import rag +from kilin.conversation_format import ( + CONVERSATION_SESSION_KEY, + conversation_state, + new_conversation_session, +) +from kilin.conversation_ownership import ConversationFileLock +from kilin.project import initialize_project +from kilin.trace_logging import NullTraceLogger, TraceConfig, TraceLogger +from tests.kilin._conversation_support import ( + checkpoint_state, + conversation_metadata, + resumable_state, + saved_turn, +) +from tests.kilin._rag_support import _session, _turn + + +def _document(state: dict[str, object]) -> dict[str, object]: + """Place one explicit state in its canonical grouped envelope.""" + + return {"sessions": { + CONVERSATION_SESSION_KEY: new_conversation_session(state), + }} + + +class TestRAGConversationSchema(unittest.TestCase): + """Keep failed restores and checkpoints outside the commit boundary.""" + + def setUp(self) -> None: + directory = TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name).resolve() + self.session = _session(self.root) + self.path = self.session.conversation_path + self.path.parent.mkdir(parents=True, exist_ok=True) + + def _write(self, state: dict[str, object]) -> None: + """Save one explicitly supplied fixture without normalizing it.""" + + self.path.write_text(json.dumps(_document(state)), encoding="utf-8") + + def test_invalid_state_precedes_models_and_trace_events(self) -> None: + project = initialize_project(self.root / "project", "code") + path = project.logs / "traces" / "conversation_invalid.json" + path.parent.mkdir(parents=True, exist_ok=True) + missing = checkpoint_state(turns=[saved_turn()]) + del missing["turns"][0]["timeline"] + inconsistent = checkpoint_state() + inconsistent["checkpoint"]["turn_count"] = 1 + nonfinite = checkpoint_state(turns=[saved_turn()]) + nonfinite["turns"][0]["parameters"]["temperature"] = float("nan") + texts = [ + json.dumps(_document(missing)), + json.dumps(_document(inconsistent)), + json.dumps(_document({"origin_turn_count": None})), + '{"sessions": {}, "sessions": {}}', + json.dumps(_document(nonfinite)), + ] + for enabled in (False, True): + for text in texts: + with self.subTest(enabled=enabled, text=text): + path.write_text(text, encoding="utf-8") + before = path.read_bytes() + with patch.object(rag, "choose_backend") as backend, ( + patch.object(rag, "EmbeddingSession") + ) as embeddings, patch.object(rag, "ChatSession") as chat: + with self.assertRaises(ValueError): + rag.RAGSession( + project.root, + conversation_path=path, + trace=TraceConfig(enabled=enabled), + ) + backend.assert_not_called() + embeddings.assert_not_called() + chat.assert_not_called() + self.assertEqual(path.read_bytes(), before) + self.assertFalse((path.parent / "project.json").exists()) + self.assertFalse( + (path.parent / ".sequence.json").exists() + ) + with ConversationFileLock(path): + pass + + def test_existing_directory_cannot_start_a_new_conversation(self) -> None: + project = initialize_project(self.root / "project", "code") + path = project.logs / "traces" / "conversation_directory.json" + path.mkdir(parents=True) + marker = path / "keep.txt" + marker.write_text("User data", encoding="utf-8") + for enabled in (False, True): + with self.subTest(enabled=enabled): + with patch.object(rag, "EmbeddingSession") as embedding, ( + patch.object(rag, "ChatSession") + ) as chat: + with self.assertRaisesRegex(ValueError, "regular file"): + rag.RAGSession( + project.root, conversation_path=path, + trace=TraceConfig(enabled=enabled), + ) + embedding.assert_not_called() + chat.assert_not_called() + self.assertTrue(path.is_dir()) + self.assertEqual(list(path.iterdir()), [marker]) + self.assertEqual(marker.read_text(encoding="utf-8"), + "User data") + self.assertFalse((path.parent / "project.json").exists()) + self.assertFalse((path.parent / ".sequence.json").exists()) + with ConversationFileLock(path): + pass + + def test_current_initial_states_do_not_fabricate_history(self) -> None: + for state in ({}, conversation_metadata(), resumable_state()): + with self.subTest(state=state): + self._write(state) + before = self.path.read_bytes() + messages, turns, checkpoint = self.session._load_conversation() + self.assertEqual(turns, []) + self.assertIsNone(checkpoint) + self.assertEqual(messages, ( + [{"role": "system", "content": state["system_prompt"]}] + if "system_prompt" in state else [] + )) + self.assertEqual(self.path.read_bytes(), before) + + def test_invalid_switch_preserves_session_files_and_ownership( + self, + ) -> None: + self.session.turns = [_turn()] + self.session._save_conversation() + ownership = ConversationFileLock(self.path) + ownership.acquire() + self.addCleanup(ownership.release) + self.session._conversation_ownership = ownership + old_checkpoint = self.session._checkpoint_id + old_turns = self.session.turns + old_trace = self.session.trace + target = self.path.with_name("conversation_invalid.json") + invalid = checkpoint_state(turns=[saved_turn()]) + invalid["checkpoint"]["conversation_sha256"] = "0" * 64 + target.write_text(json.dumps(_document(invalid)), encoding="utf-8") + old_bytes, target_bytes = self.path.read_bytes(), target.read_bytes() + with self.assertRaises(ValueError): + self.session.switch_conversation(target, trace=NullTraceLogger()) + self.assertEqual(self.session.conversation_path, self.path) + self.assertEqual(self.session._checkpoint_id, old_checkpoint) + self.assertIs(self.session.turns, old_turns) + self.assertIs(self.session.trace, old_trace) + self.assertTrue(ownership.holds(self.path)) + self.session.chat_session.reset.assert_not_called() + self.session.chat_session.restore_history.assert_not_called() + self.assertEqual(self.path.read_bytes(), old_bytes) + self.assertEqual(target.read_bytes(), target_bytes) + with ConversationFileLock(target): + pass + + def test_untraced_save_rejects_corrupt_existing_state(self) -> None: + self.session.turns = [_turn()] + self.session._save_conversation() + checkpoint = self.session._checkpoint_id + saved = json.loads(self.path.read_text(encoding="utf-8")) + state = conversation_state(saved) + state["custom_note"] = {"origin": "unknown state field"} + self.path.write_text(json.dumps(saved), encoding="utf-8") + before = self.path.read_bytes() + pending = _turn("Pending", "Must not be committed") + with self.assertRaises(ValueError): + self.session._save_conversation(pending_turn=pending) + self.assertEqual(self.path.read_bytes(), before) + self.assertEqual(self.session._checkpoint_id, checkpoint) + self.assertEqual(len(self.session.turns), 1) + self.assertNotIn(pending, self.session.turns) + + def test_existing_missing_envelope_is_never_completed_by_save(self): + self.session.turns = [_turn()] + self.session._save_conversation() + checkpoint = self.session._checkpoint_id + for document in ( + {}, {"sessions": {}}, + {"sessions": {"custom": {"title": "Retain"}}}, + ): + with self.subTest(document=document): + self.path.write_text(json.dumps(document), encoding="utf-8") + before = self.path.read_bytes() + pending = _turn("Pending", "Must not be committed") + with self.assertRaises(ValueError): + self.session._save_conversation(pending_turn=pending) + self.assertEqual(self.path.read_bytes(), before) + self.assertEqual(self.session._checkpoint_id, checkpoint) + self.assertEqual(len(self.session.turns), 1) + self.assertNotIn(pending, self.session.turns) + + def test_invalid_pending_turn_never_commits(self) -> None: + for traced in (False, True): + with self.subTest(traced=traced): + if traced: + logger = TraceLogger( + TraceConfig(enabled=True, output_path=self.path), + default_directory=self.path.parent, + ) + self.session.trace = logger + self.addCleanup(logger.close) + self.session._save_conversation() + checkpoint = self.session._checkpoint_id + before = self.path.read_bytes() + pending = replace(_turn(), parameters={"bad": float("nan")}) + with self.assertRaises(ValueError): + self.session._save_conversation(pending_turn=pending) + self.assertEqual(self.path.read_bytes(), before) + self.assertEqual(self.session._checkpoint_id, checkpoint) + self.assertEqual(self.session.turns, []) + + +class TestTraceConversationSchema(unittest.TestCase): + """Validate complete candidate state before changing a live trace.""" + + def setUp(self) -> None: + directory = TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.path = Path(directory.name) / "conversation.json" + self.logger = TraceLogger( + TraceConfig(enabled=True, output_path=self.path), + default_directory=self.path.parent, + ) + self.addCleanup(self.logger.close) + self.saved = checkpoint_state(turns=[saved_turn()]) + self.logger.update_conversation(self.saved) + + def test_invalid_merges_leave_state_bytes_and_events_unchanged( + self, + ) -> None: + malformed = deepcopy(self.saved) + malformed["checkpoint"]["turn_count"] = True + wrong_type = deepcopy(self.saved) + wrong_type["turns"][0]["evidence"] = "not a list" + unsupported = deepcopy(self.saved) + unsupported["turns"][0]["parameters"] = {"path": Path("notes.md")} + before = self.path.read_bytes() + events = deepcopy(self.logger._events) + for update in ( + {"checkpoint_id": "unmatched"}, + {"checkpoint": None}, + {"custom_note": "unsupported"}, + {17: "coerced keys are forbidden"}, + malformed, wrong_type, unsupported, + ): + with self.subTest(update=update): + with self.assertRaises(ValueError): + self.logger.update_conversation(update) + self.assertEqual(self.path.read_bytes(), before) + self.assertEqual(self.logger._conversation, self.saved) + self.assertEqual(self.logger._events, events) + self.logger.emit("after.rejected.state", component="test") + payload = json.loads(self.path.read_text(encoding="utf-8")) + self.assertEqual(conversation_state(payload), self.saved) + + def test_nonfinite_diagnostics_do_not_invalidate_completed_state(self): + self.logger.emit( + "numeric.diagnostic", component="test", data={ + "undefined": float("nan"), + "upper": float("inf"), + "lower": -float("inf"), + }, + ) + self.logger.close() + reopened = TraceLogger( + TraceConfig(enabled=True, output_path=self.path), + default_directory=self.path.parent, + ) + self.addCleanup(reopened.close) + before = self.path.read_bytes() + payload = json.loads(before) + self.assertEqual(conversation_state(payload), self.saved) + diagnostics = [ + operation + for group in payload["sessions"].values() + for operation in group.get("operations", {}).values() + if operation.get("event", {}).get("event_type") + == "numeric.diagnostic" + ] + self.assertEqual(len(diagnostics), 1) + values = diagnostics[0]["details"] + self.assertTrue(math.isnan(values["undefined"])) + self.assertEqual(values["upper"], float("inf")) + self.assertEqual(values["lower"], -float("inf")) + session = _session(self.path.parent) + session.trace = reopened + session.conversation_path = self.path + messages, turns, checkpoint = session._load_conversation() + self.assertEqual(checkpoint, self.saved["checkpoint_id"]) + self.assertEqual(len(messages), 3) + self.assertEqual(len(turns), 1) + self.assertEqual(turns[0].conversation_turn_uuid, + self.saved["turns"][0]["conversation_turn_uuid"]) + self.assertEqual(self.path.read_bytes(), before) + + def test_snapshot_does_not_follow_caller_mutation(self) -> None: + caller = checkpoint_state("next", [saved_turn("Saved question")]) + expected = deepcopy(caller) + self.logger.update_conversation(caller) + caller["turns"][0]["question"] = "Changed after commit" + caller["checkpoint"]["turn_count"] = 99 + self.logger.emit("after.caller.mutation", component="test") + payload = json.loads(self.path.read_text(encoding="utf-8")) + self.assertEqual(conversation_state(payload), expected) + self.assertEqual(self.logger._conversation, expected) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/test_rag__disliked_history.py b/tests/kilin/test_rag__disliked_history.py index e969c35e..3c092154 100644 --- a/tests/kilin/test_rag__disliked_history.py +++ b/tests/kilin/test_rag__disliked_history.py @@ -31,9 +31,10 @@ _intent, _session, _turn, - _type_config, ) +from tests.kilin._conversation_support import resumable_state + class TestRAGDislikedHistory(unittest.TestCase): def setUp(self): @@ -55,9 +56,9 @@ def setUp(self): {"related_turn_ids": [2]}), ] payload = json.loads(self.path.read_text(encoding="utf-8")) - conversation_state(payload)["turns"] = [ + conversation_state(payload).update(resumable_state([ rag._turn_to_data(turn) for turn in self.turns - ] + ])) self.path.write_text(json.dumps(payload), encoding="utf-8") self.session = _session(self.root) self.session.conversation_path = self.path diff --git a/tests/kilin/test_rag__historical_recall.py b/tests/kilin/test_rag__historical_recall.py index 8658e38b..db641d03 100644 --- a/tests/kilin/test_rag__historical_recall.py +++ b/tests/kilin/test_rag__historical_recall.py @@ -25,6 +25,8 @@ from tests.kilin._rag_support import _answer_patches, _session, _turn from tests.kilin.test__conversation_memory_index import FakeEmbedding +from tests.kilin._conversation_support import resumable_state + class TestRAGHistoricalRecall(unittest.TestCase): def setUp(self): @@ -42,9 +44,9 @@ def setUp(self): ) path = self.store.state_path(previous) data = json.loads(path.read_text()) - conversation_state(data)["turns"] = [ + conversation_state(data).update(resumable_state([ rag._turn_to_data(self.turn) - ] + ])) path.write_text(json.dumps(data), encoding="utf-8") current = self.store.create() self.session = _session(self.root) diff --git a/tests/kilin/test_rag__retrieval_corrections.py b/tests/kilin/test_rag__retrieval_corrections.py index c1632575..3ac1093f 100644 --- a/tests/kilin/test_rag__retrieval_corrections.py +++ b/tests/kilin/test_rag__retrieval_corrections.py @@ -208,7 +208,7 @@ def test_prior_targets_become_related_but_alternatives_stay_cautious(self): self.assertEqual(reused[0].context_role, expected) self.assertEqual(turn.evidence[0].context_role, old) - def test_new_provenance_roundtrips_and_old_records_still_load(self): + def test_provenance_roundtrips_and_requires_explicit_null(self): for role in (None, "direct", "related", "alternative"): with self.subTest(role=role): evidence = replace(fixtures._evidence(), context_role=role) @@ -216,6 +216,9 @@ def test_new_provenance_roundtrips_and_old_records_still_load(self): saved = rag._turn_to_data(turn) self.assertEqual(rag._turn_from_data(saved), turn) del saved["evidence"][0]["context_role"] + with self.assertRaisesRegex(ValueError, "evidence fields"): + rag._turn_from_data(saved) + saved["evidence"][0]["context_role"] = None restored = rag._turn_from_data(saved) self.assertIsNone(restored.evidence[0].context_role) self.assertEqual(restored.evidence[0].text, evidence.text) diff --git a/tests/kilin/test_rag__timeline.py b/tests/kilin/test_rag__timeline.py index 1e1ac693..8c0d353a 100644 --- a/tests/kilin/test_rag__timeline.py +++ b/tests/kilin/test_rag__timeline.py @@ -322,12 +322,14 @@ def process(*args, **kwargs): self.session.turns[0].timeline.elapsed_ms, ) - def test_absent_timeline_remains_a_readable_conversation_turn(self): - """Keep untimed turns readable without migrating GUI sidecars.""" + def test_timeline_must_be_explicit_even_for_untimed_turns(self): + """Accept explicit null timing and reject absent persisted fields.""" turn = rag.ConversationTurn("now", "Q", "A", (), {}) payload = rag._turn_to_data(turn) - payload.pop("timeline") self.assertIsNone(rag._turn_from_data(payload).timeline) + payload.pop("timeline") + with self.assertRaisesRegex(ValueError, "turn fields"): + rag._turn_from_data(payload) payload["timeline"] = {"elapsed_ms": 1, "steps": []} with self.assertRaisesRegex(ValueError, "durations do not add up"): rag._turn_from_data(payload) diff --git a/tests/kilin/test_trace_logging.py b/tests/kilin/test_trace_logging.py index 7d065644..181d8b1a 100644 --- a/tests/kilin/test_trace_logging.py +++ b/tests/kilin/test_trace_logging.py @@ -41,6 +41,11 @@ create_trace_logger, trace_text_preview, ) +from tests.kilin._conversation_support import ( + checkpoint_state, + resumable_state, + saved_turn, +) def _payload(path: Path) -> dict[str, object]: @@ -712,15 +717,15 @@ def _open(self) -> TraceLogger: def test_conversation_update_merges_state_and_uses_same_file(self) -> None: """Write resumable conversation data into the grouped trace file.""" logger = self._open() - logger.update_conversation({"turns": [{"question": "first"}]}) - logger.update_conversation({"checkpoint_id": "checkpoint_1"}) + turns = [saved_turn("first")] + logger.update_conversation(resumable_state(turns)) + expected = checkpoint_state("checkpoint_1", turns) + logger.update_conversation({ + "checkpoint_id": expected["checkpoint_id"], + "checkpoint": expected["checkpoint"], + }) session = _payload(self.path)["sessions"][CONVERSATION_SESSION_KEY] - self.assertEqual( - session["resume_state"], { - "turns": [{"question": "first"}], - "checkpoint_id": "checkpoint_1", - }, - ) + self.assertEqual(session["resume_state"], expected) self.assertEqual(session["operations"], {}) self.assertFalse(self.path.with_suffix(".json.tmp").exists()) @@ -731,14 +736,14 @@ def test_reopen_appends_new_readable_turns_and_retains_state(self) -> None: "turn.started", component="rag", turn_id="turn-reused", data={"question": "First"}, ) - first.update_conversation({"checkpoint_id": "first"}) + first.update_conversation(checkpoint_state("first")) first.close() second = self._open() second.emit( "turn.started", component="rag", turn_id="turn-reused", data={"question": "Second"}, ) - second.update_conversation({"checkpoint_id": "second"}) + second.update_conversation(checkpoint_state("second")) second.close() payload = _payload(self.path) turns = _turns(payload) @@ -818,14 +823,14 @@ def test_reset_clears_only_conversation_events_and_state(self) -> None: first = self._open() first.emit("project.ready", component="project") first.emit("turn.started", component="rag", turn_id="old") - first.update_conversation({"checkpoint_id": "old"}) + first.update_conversation(checkpoint_state("old")) first.close() second = self._open() second.emit("turn.started", component="rag", turn_id="discard") second.reset_conversation_state() second.emit("conversation.reset", component="rag") second.emit("turn.started", component="rag", turn_id="fresh") - second.update_conversation({"checkpoint_id": "fresh"}) + second.update_conversation(checkpoint_state("fresh")) payload = _payload(self.path) self.assertEqual(list(_turns(payload)), ["turn_0001"]) self.assertEqual( @@ -926,10 +931,9 @@ def test_failed_state_write_cannot_be_committed_by_later_event( ) -> None: """Roll back attempted state even when logging subsequently works.""" logger = self._logger(FAILURE_POLICY_WARN) - logger.update_conversation({ - "checkpoint_id": "committed", - "turns": [{"question": "Earlier"}], - }) + logger.update_conversation(checkpoint_state( + "committed", [saved_turn("Earlier")], + )) before = _payload(self.path)["sessions"][ CONVERSATION_SESSION_KEY ]["resume_state"] @@ -937,10 +941,9 @@ def test_failed_state_write_cannot_be_committed_by_later_event( logger, "_write_readable_trace", side_effect=OSError("full") ): with self.assertRaisesRegex(OSError, "full"): - logger.update_conversation({ - "checkpoint_id": "uncommitted", - "turns": [{"question": "Unsaved"}], - }) + logger.update_conversation(checkpoint_state( + "uncommitted", [saved_turn("Unsaved")], + )) self.assertEqual(logger._conversation, before) logger.emit("after.failed.checkpoint", component="test") actual = _payload(self.path)["sessions"][ @@ -948,7 +951,9 @@ def test_failed_state_write_cannot_be_committed_by_later_event( ]["resume_state"] self.assertEqual(actual, before) self.assertFalse(logger._failed) - logger.update_conversation({"checkpoint_id": "next"}) + logger.update_conversation(checkpoint_state( + "next", before["turns"], + )) actual = _payload(self.path)["sessions"][ CONVERSATION_SESSION_KEY ]["resume_state"] @@ -958,12 +963,12 @@ def test_failed_state_write_cannot_be_committed_by_later_event( def test_failed_rename_preserves_saved_resume_state(self) -> None: """Leave an earlier checkpoint intact when atomic rename fails.""" logger = self._logger(FAILURE_POLICY_WARN) - logger.update_conversation({"checkpoint_id": "committed"}) + logger.update_conversation(checkpoint_state("committed")) with patch.object( Path, "replace", side_effect=OSError("rename refused") ): with self.assertRaisesRegex(OSError, "rename refused"): - logger.update_conversation({"checkpoint_id": "unsaved"}) + logger.update_conversation(checkpoint_state("unsaved")) logger.emit("after.rename.failure", component="test") self.assertEqual( _payload(self.path)["sessions"][CONVERSATION_SESSION_KEY][ @@ -979,7 +984,7 @@ def test_conversation_update_propagates_io_error(self) -> None: logger, "_write_readable_trace", side_effect=OSError("full") ): with self.assertRaisesRegex(OSError, "full"): - logger.update_conversation({"checkpoint_id": "next"}) + logger.update_conversation(checkpoint_state("next")) class TestTraceFactoryAndNull(unittest.TestCase): diff --git a/tests/kilin/test_trace_logging__project.py b/tests/kilin/test_trace_logging__project.py index e77c3b04..55e5bf83 100644 --- a/tests/kilin/test_trace_logging__project.py +++ b/tests/kilin/test_trace_logging__project.py @@ -18,6 +18,9 @@ TraceConfig, TraceLogger, ) +from tests.kilin._conversation_support import ( + conversation_metadata, +) def _event_numbers(value): @@ -169,7 +172,7 @@ def test_checkpoint_publishes_pending_events(self): TRACE_EVENT_PROGRESS_UPDATED, component="tests", data={"stage": "embedding", "percent": 50.0}, ) - logger.update_conversation({"name": "Saved"}) + logger.update_conversation(conversation_metadata(name="Saved")) self.assertEqual(len(self._numbers("conversation_c.json")), 2) before = logger.readable_path.read_bytes() with patch.object( From 06344e25ac0de4bd46bf64f0b60f5d91c9d1f5c5 Mon Sep 17 00:00:00 2001 From: Giovanni Volpe Date: Wed, 2 Dec 2026 20:04:51 +0100 Subject: [PATCH 04/37] Update of macOS installation and launcher Use only current versioned macOS runtimes Remove historical runtime activation without modifying obsolete installations. Require matching release identity and complete executable entry points. Reject unsafe managed runtime paths before installation, cleanup or activation. Preserve atomic activation, locking, failure recovery and existing releases. Retain current backend repair and legitimate ancestor/interpreter aliases. Extend regression tests and update developer and release documentation. --- docs/development.md | 19 +- docs/release.md | 8 +- setup/macos/launcher.sh | 130 +++++++-- tests/kilin/gui/test__paths.py | 7 +- tests/setup/_macos_launcher_support.py | 42 ++- tests/setup/test__macos_backend_repair.py | 29 +- tests/setup/test__macos_launcher_lock.py | 46 +++- tests/setup/test__macos_launcher_update.py | 297 +++++++++++++++++++-- 8 files changed, 512 insertions(+), 66 deletions(-) diff --git a/docs/development.md b/docs/development.md index e1091181..a522ee32 100644 --- a/docs/development.md +++ b/docs/development.md @@ -498,10 +498,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 diff --git a/docs/release.md b/docs/release.md index 4d231447..30d7ab90 100644 --- a/docs/release.md +++ b/docs/release.md @@ -105,9 +105,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. diff --git a/setup/macos/launcher.sh b/setup/macos/launcher.sh index d3593b03..a178dff2 100644 --- a/setup/macos/launcher.sh +++ b/setup/macos/launcher.sh @@ -17,7 +17,6 @@ resources="$contents/Resources" support=${KILIN_APP_SUPPORT:-"$HOME/Library/Application Support/kilin"} # Only what the app installs; projects and preferences stay beside it. runtime_root="$support/runtime" -legacy_runtime="$runtime_root/app" releases="$runtime_root/releases" active_file="$runtime_root/active" log="$runtime_root/install.log" @@ -51,6 +50,25 @@ export KILIN_APP_SPEC="$spec" # What is installed: the spec, plus the wheel's checksum, so a rebuilt # wheel with an unchanged version and file name is installed too. build="$spec${KILIN_WHEEL_SHA:+ $KILIN_WHEEL_SHA}" +# Validate managed directory entries without rejecting aliases of their +# ancestors (for example /var on macOS). Never traverse a linked runtime +# or releases directory, especially when cleaning an incomplete release. +validate_runtime_layout() { + if [ -L "$runtime_root" ]; then + fail "KíLín's runtime folder must not be a symlink." + fi + if [ -e "$runtime_root" ] && [ ! -d "$runtime_root" ]; then + fail "KíLín cannot create its runtime folder. Check permissions and disk space." + fi + if [ -L "$releases" ]; then + fail "KíLín's releases folder must not be a symlink." + fi + if [ -e "$releases" ] && [ ! -d "$releases" ]; then + fail "KíLín's releases folder is not a directory." + fi +} + +validate_runtime_layout if ! mkdir -p "$runtime_root"; then fail "KíLín cannot create its runtime folder. Check permissions and disk space." fi @@ -72,11 +90,22 @@ fi target_name="releases/$release_id" target_runtime="$runtime_root/$target_name" -# An active pointer contains either a relative release name or the legacy -# 'app' directory. Never use an unvalidated value as a filesystem path. -# Without a pointer, the existing legacy installation remains active -# until a complete replacement has been committed. +# A named release must be a real directory if it exists. Missing inactive +# releases can be installed, but a link or other entry is not staging. +validate_release_directory() { + if [ -L "$1" ]; then + fail "KíLín's release runtime must not be a symlink." + fi + if [ -e "$1" ] && [ ! -d "$1" ]; then + fail "KíLín's release runtime is not a directory." + fi +} + +# Only a canonical relative release name can select an environment. +# An absent pointer starts installation; do not discover other layouts. read_active() { + validate_runtime_layout + validate_release_directory "$target_runtime" runtime="" if [ -L "$active_file" ]; then fail "KíLín's active runtime pointer must not be a symlink." @@ -85,11 +114,20 @@ read_active() { if [ ! -f "$active_file" ]; then fail "KíLín's active runtime pointer is not a file." fi - if ! selection=$(cat "$active_file"); then + # Read once: another launcher may atomically replace the pointer. + # Keep the final newline and turn NUL bytes into invalid characters + # rather than letting command substitution silently discard them. + if ! selection=$(LC_ALL=C tr '\000' '?' <"$active_file" && printf '.'); then fail "KíLín cannot read its active runtime pointer." fi case "$selection" in - app) runtime="$legacy_runtime" ;; + *$'\n.') selection=${selection%$'\n.'} ;; + *) fail "Invalid KíLín active runtime pointer." ;; + esac + case "$selection" in + app) + fail "KíLín's active runtime pointer uses an unsupported installation layout. Inspect runtime/active before retrying." + ;; releases/*) selected_id=${selection#releases/} case "$selected_id" in @@ -104,24 +142,64 @@ read_active() { ;; *) fail "Invalid KíLín active runtime pointer." ;; esac - elif [ -f "$legacy_runtime/.installed" ]; then - runtime="$legacy_runtime" fi - if [ -n "$runtime" ] && [ -L "$runtime" ]; then - fail "KíLín's active runtime must not be a symlink." + if [ -n "$runtime" ]; then + validate_release_directory "$runtime" fi } +# A virtual environment may legitimately use a symlink to its installed +# Python interpreter. The managed release and bin directory must be real. +valid_entry_points() { + [ -d "$1" ] && [ ! -L "$1" ] && + [ -d "$1/bin" ] && [ ! -L "$1/bin" ] && + [ -f "$1/bin/python" ] && [ -x "$1/bin/python" ] && + [ -f "$1/bin/kilin-gui" ] && [ ! -L "$1/bin/kilin-gui" ] && + [ -x "$1/bin/kilin-gui" ] +} + installed_for_build() { - [ -n "$1" ] && [ -x "$1/bin/kilin-gui" ] && - [ "$(cat "$1/.installed" 2>/dev/null)" = "$build" ] + [ "$1" = "$target_runtime" ] && valid_entry_points "$1" && + [ -f "$1/.installed" ] && [ ! -L "$1/.installed" ] && + cmp -s "$1/.installed" <(printf '%s\n' "$build") +} + +# Installation writes only ordinary managed paths. Check before opening the +# lock or truncating the log, and again after waiting for another installer. +validate_install_paths() { + if [ -L "$lock" ] || { [ -e "$lock" ] && [ ! -f "$lock" ]; }; then + fail "KíLín cannot open its installation lock. Inspect the lock file." + fi + if [ -L "$log" ] || { [ -e "$log" ] && [ ! -f "$log" ]; }; then + fail "KíLín's installation log must be a regular file." + fi + for directory in "$runtime_root/python" "$runtime_root/uv-cache"; do + if [ -L "$directory" ] || { [ -e "$directory" ] && [ ! -d "$directory" ]; }; then + fail "KíLín's installation folders must be real directories." + fi + done +} + +# Only the inactive directory for this exact release is disposable. Use +# this check for failed installations as well as abandoned partial attempts. +remove_incomplete_release() { + validate_runtime_layout + validate_release_directory "$target_runtime" + if [ -d "$target_runtime" ] && ! rm -rf "$target_runtime"; then + fail "KíLín cannot clean an incomplete release." + fi } # Atomic activation writes a relative pointer inside runtime/, never a # replacement virtual environment. A crash before rename leaves the old # active value intact; a crash after rename selects a complete release. activate_release() { - if [ -d "$active_file" ] || [ -L "$active_file" ]; then + validate_runtime_layout + validate_release_directory "$target_runtime" + if ! installed_for_build "$target_runtime"; then + fail "KíLín cannot activate an incomplete release." + fi + if [ -L "$active_file" ] || { [ -e "$active_file" ] && [ ! -f "$active_file" ]; }; then fail "KíLín cannot replace its active runtime pointer." fi if ! pointer_tmp=$(mktemp "$runtime_root/.active.XXXXXX"); then @@ -150,6 +228,7 @@ if ! installed_for_build "$runtime"; then fail "The macOS lockf utility is required to install KíLín." fi lock="$runtime_root/.install.lock" + validate_install_paths if ! exec 9>>"$lock"; then fail "KíLín cannot open its installation lock. Check permissions." fi @@ -167,6 +246,7 @@ if ! installed_for_build "$runtime"; then # we waited, so re-read the pointer under the installation lock. read_active if ! installed_for_build "$runtime"; then + validate_install_paths if [ "$runtime" = "$target_runtime" ]; then fail "The active KíLín runtime is incomplete. Repair it manually." fi @@ -176,11 +256,7 @@ if ! installed_for_build "$runtime"; then if ! installed_for_build "$target_runtime"; then # Delete only an incomplete *inactive* attempt for this exact # build. An active runtime and every other release are untouched. - if [ -e "$target_runtime" ] || [ -L "$target_runtime" ]; then - if ! rm -rf "$target_runtime"; then - fail "KíLín cannot clean an incomplete release." - fi - fi + remove_incomplete_release if [ -n "$runtime" ] && [ -f "$runtime/.installed" ]; then notify "Updating KíLín. The previous version is kept." else @@ -194,21 +270,25 @@ if ! installed_for_build "$runtime"; then "$resources/uv" pip install \ --python "$target_runtime/bin/python" "$spec" } >"$log" 2>&1; then - rm -rf "$target_runtime" + remove_incomplete_release fail "KíLín could not be installed. Check the internet connection and try again. Details: $log" fi # Verify both entry points and installed distribution metadata # before recording a release as complete. - if [ ! -x "$target_runtime/bin/python" ] || - [ ! -x "$target_runtime/bin/kilin-gui" ] || + validate_runtime_layout + validate_release_directory "$target_runtime" + validate_install_paths + if ! valid_entry_points "$target_runtime" || ! "$target_runtime/bin/python" -c \ 'from importlib.metadata import version; version("kilin")' \ >>"$log" 2>&1; then - rm -rf "$target_runtime" + remove_incomplete_release fail "KíLín installation validation failed. Details: $log" fi - if ! printf '%s\n' "$build" >"$target_runtime/.installed"; then - rm -rf "$target_runtime" + if [ -L "$target_runtime/.installed" ] || + { [ -e "$target_runtime/.installed" ] && [ ! -f "$target_runtime/.installed" ]; } || + ! printf '%s\n' "$build" >"$target_runtime/.installed"; then + remove_incomplete_release fail "KíLín could not record its installation." fi fi diff --git a/tests/kilin/gui/test__paths.py b/tests/kilin/gui/test__paths.py index 4d22b670..69258958 100644 --- a/tests/kilin/gui/test__paths.py +++ b/tests/kilin/gui/test__paths.py @@ -11,6 +11,7 @@ from __future__ import annotations +import hashlib import json import shlex import subprocess @@ -240,9 +241,13 @@ def test_backend_repair_uses_bundled_uv_and_exact_wheel( uv.parent.mkdir(parents=True) uv.write_text("#!/bin/sh\n", encoding="utf-8") uv.chmod(0o755) - python = self.root / "Application Support/runtime/app/bin/python" wheel = uv.parent / "kilin-0.1.0-py3-none-any.whl" for spec in (str(wheel) + "[app]", "kilin[app]==0.1.0"): + release = hashlib.sha256(spec.encode("utf-8")).hexdigest() + python = ( + self.root / "Application Support/kilin/runtime/releases" + / release / "bin/python" + ) with ( self.subTest(spec=spec), patch.dict( diff --git a/tests/setup/_macos_launcher_support.py b/tests/setup/_macos_launcher_support.py index b0791569..e3aac39f 100644 --- a/tests/setup/_macos_launcher_support.py +++ b/tests/setup/_macos_launcher_support.py @@ -67,7 +67,8 @@ def __init__( self.root = Path(self.temporary.name) self.support = self.root / "Application Support" / "kilin" self.runtime_root = self.support / "runtime" - self.runtime = self.runtime_root / "app" + # Reserved for tests that must preserve an obsolete installation. + self.legacy_runtime = self.runtime_root / "app" self.spec = spec self.wheel_sha = wheel_sha self.uv_calls = self.root / "uv-calls.txt" @@ -208,6 +209,45 @@ def release_runtime(self) -> Path: digest = hashlib.sha256(build.encode("utf-8")).hexdigest() return self.runtime_root / "releases" / digest + @staticmethod + def tree_state(path: Path) -> dict[str, tuple[object, ...]]: + """Capture entries and contents without traversing symbolic links. + + Parameters + ---------- + path: pathlib.Path + Directory or single filesystem entry to inspect. + + Returns + ------- + dict[str, tuple[object, ...]] + Relative paths, modes, modification times and file contents or + link targets. Access times are excluded because reads change + them on some filesystems. + + """ + + result = {} + + def visit(entry: Path) -> None: + info = entry.lstat() + if entry.is_symlink(): + content = os.readlink(entry) + elif entry.is_file(): + content = entry.read_bytes() + else: + content = None + result[entry.relative_to(path).as_posix()] = ( + info.st_mode, info.st_mtime_ns, content, + ) + if not entry.is_symlink() and entry.is_dir(): + for child in sorted(entry.iterdir()): + visit(child) + + if path.exists() or path.is_symlink(): + visit(path) + return result + def run( self, environment: dict[str, str] | None = None, timeout: float = 15, diff --git a/tests/setup/test__macos_backend_repair.py b/tests/setup/test__macos_backend_repair.py index 638dcfa9..78487a6f 100644 --- a/tests/setup/test__macos_backend_repair.py +++ b/tests/setup/test__macos_backend_repair.py @@ -11,6 +11,7 @@ from __future__ import annotations +import hashlib import os from pathlib import Path import shlex @@ -49,15 +50,7 @@ def test_launcher_exports_its_original_installation_source(self) -> None: uv.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") uv.chmod(0o755) support = root / "Application Support" / "kilin" - runtime = support / "runtime" / "app" - script = runtime / "bin" / "kilin-gui" - script.parent.mkdir(parents=True) - script.write_text( - '#!/bin/sh\nprintf "%s\\n%s\\n" ' - '"$KILIN_APP_UV" "$KILIN_APP_SPEC"\n', - encoding="utf-8", - ) - script.chmod(0o755) + runtime_root = support / "runtime" mock_bin = root / "mock-bin" mock_bin.mkdir() uname = mock_bin / "uname" @@ -76,8 +69,21 @@ def test_launcher_exports_its_original_installation_source(self) -> None: "@RESOURCES@/kilin-0.1.0-py3-none-any.whl[app]", ): with self.subTest(spec=spec): - # A matching marker skips installation entirely. + # Both release identity and marker match the build. expanded = spec.replace("@RESOURCES@", str(resources)) + digest = hashlib.sha256( + expanded.encode("utf-8") + ).hexdigest() + runtime = runtime_root / "releases" / digest + executable(runtime / "bin/python", "#!/bin/sh\nexit 0\n") + executable( + runtime / "bin/kilin-gui", + '#!/bin/sh\nprintf "%s\\n%s\\n" ' + '"$KILIN_APP_UV" "$KILIN_APP_SPEC"\n', + ) + (runtime_root / "active").write_text( + "releases/" + digest + "\n", encoding="utf-8", + ) (runtime / ".installed").write_text( expanded + "\n", encoding="utf-8" ) @@ -107,6 +113,9 @@ def test_launcher_exports_its_original_installation_source(self) -> None: result.stdout.strip().splitlines(), [str(uv), expanded], ) + self.assertFalse( + (runtime_root / ".install.lock").exists() + ) @unittest.skipUnless(shutil.which("bash"), "bash is required") def test_versioned_release_passes_bundled_repair_context(self) -> None: diff --git a/tests/setup/test__macos_launcher_lock.py b/tests/setup/test__macos_launcher_lock.py index d3d683cb..00c08343 100644 --- a/tests/setup/test__macos_launcher_lock.py +++ b/tests/setup/test__macos_launcher_lock.py @@ -37,7 +37,7 @@ def setUp(self) -> None: self.sandbox = LauncherSandbox() self.support = self.sandbox.support self.runtime_root = self.sandbox.runtime_root - self.runtime = self.sandbox.runtime + self.legacy_runtime = self.sandbox.legacy_runtime self.launcher = self.sandbox.launcher self.uv_calls = self.sandbox.uv_calls self.gui_calls = self.sandbox.gui_calls @@ -101,14 +101,14 @@ def test_stale_file_and_partial_runtime_are_recoverable(self) -> None: """ - self.runtime.mkdir(parents=True) - (self.runtime / "partial").write_text("old", encoding="utf-8") + self.legacy_runtime.mkdir(parents=True) + (self.legacy_runtime / "partial").write_text("old", encoding="utf-8") (self.runtime_root / ".install.lock").write_text( "old", encoding="utf-8" ) result = self._run() self.assertEqual(result.returncode, 0, result.stderr) - self.assertTrue((self.runtime / "partial").is_file()) + self.assertTrue((self.legacy_runtime / "partial").is_file()) self.assertTrue( (self.sandbox.release_runtime() / ".installed").is_file() ) @@ -136,6 +136,44 @@ def test_lock_open_failure_is_reported(self) -> None: self.assertIn("cannot open its installation lock", result.stderr) self.assertFalse(self.uv_calls.exists()) + def test_installation_paths_are_not_followed_through_links(self) -> None: + """Reject linked lock, log, Python and cache paths before writing. + + """ + + self.runtime_root.mkdir(parents=True) + for name, directory in ( + (".install.lock", False), ("install.log", False), + ("python", True), ("uv-cache", True), + ): + with self.subTest(name=name): + external = self.sandbox.root / "external" + if directory: + external.mkdir() + (external / "valuable").write_text( + "keep", encoding="utf-8", + ) + else: + external.write_text("keep", encoding="utf-8") + link = self.runtime_root / name + link.symlink_to(external, target_is_directory=directory) + before = self.sandbox.tree_state(self.runtime_root) + outside = self.sandbox.tree_state(external) + result = self._run() + self.assertNotEqual(result.returncode, 0) + self.assertIn("installation", result.stderr) + self.assertFalse(self.uv_calls.exists()) + self.assertFalse(self.gui_calls.exists()) + self.assertEqual( + self.sandbox.tree_state(self.runtime_root), before, + ) + self.assertEqual(self.sandbox.tree_state(external), outside) + link.unlink() + if directory: + shutil.rmtree(external) + else: + external.unlink() + def test_invalid_timeouts_are_rejected_before_installing(self) -> None: """Reject malformed or unreasonably long lock waits. diff --git a/tests/setup/test__macos_launcher_update.py b/tests/setup/test__macos_launcher_update.py index 63ac38ca..7f147112 100644 --- a/tests/setup/test__macos_launcher_update.py +++ b/tests/setup/test__macos_launcher_update.py @@ -18,7 +18,10 @@ import time import unittest -from tests.setup._macos_launcher_support import LauncherSandbox +from tests.setup._macos_launcher_support import ( + LauncherSandbox, + executable, +) @unittest.skipUnless( @@ -269,6 +272,28 @@ def test_completed_uncommitted_release_is_reused(self) -> None: "releases/" + target.name, ) + def test_marked_inactive_release_without_python_is_rebuilt(self) -> None: + """A completion marker cannot authorize an incomplete release. + + """ + + old = self._install("0.1.0") + before = self.sandbox.tree_state(old) + self.sandbox.set_launcher("kilin[app]==0.2.0") + target = self.sandbox.release_runtime() + executable(target / "bin/kilin-gui", "#!/bin/sh\nexit 77\n") + (target / ".installed").write_text( + self.sandbox.spec + "\n", encoding="utf-8", + ) + result = self.sandbox.run() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue((target / "bin/python").is_file()) + self.assertEqual(self.active.read_text(encoding="utf-8"), + "releases/" + target.name + "\n") + self.assertEqual(self.sandbox.tree_state(old), before) + self.assertEqual(self.sandbox.uv_calls.read_text(encoding="utf-8"), + "venv\npip\nvenv\npip\n") + def test_rebuilt_wheel_has_distinct_release_identity(self) -> None: """Same package version with changed wheel bytes upgrades safely. @@ -287,32 +312,266 @@ def test_rebuilt_wheel_has_distinct_release_identity(self) -> None: "releases/" + new.name, ) - def test_legacy_runtime_remains_usable_during_transition(self) -> None: - """An existing runtime installation survives a failed upgrade. + def _legacy_installation(self) -> Path: + """Create a complete but unsupported pre-versioned installation. + + Returns + ------- + pathlib.Path + Obsolete runtime, which must never be executed or modified. """ - legacy = self.sandbox.runtime - (legacy / "bin").mkdir(parents=True) - shutil.copy2( - self.sandbox.gui_script, legacy / "bin/kilin-gui" + legacy = self.sandbox.legacy_runtime + executable( + legacy / "bin/kilin-gui", + '#!/bin/sh\nprintf "legacy\\n" >> "$KILIN_TEST_GUI_CALLS"\n', ) + shutil.copy2(self.sandbox.python_script, legacy / "bin/python") (legacy / ".installed").write_text( - "kilin[app]==0.1.0\n", encoding="utf-8" + self.sandbox.spec + "\n", encoding="utf-8" ) - self.assertEqual(self.sandbox.run().returncode, 0) - self.assertFalse(self.active.exists()) - self.sandbox.set_launcher("kilin[app]==0.2.0") + return legacy + + def _assert_rejected_without_installing(self, message: str) -> None: + """Reject an invalid runtime without modifying its managed tree. + + Parameters + ---------- + message: str + Expected substring of the launcher's failure diagnostic. + + """ + + before = self.sandbox.tree_state(self.runtime_root) + calls = { + path: path.read_bytes() if path.exists() else None + for path in (self.sandbox.uv_calls, self.sandbox.gui_calls) + } + result = self.sandbox.run() + self.assertNotEqual(result.returncode, 0) + self.assertIn(message, result.stderr) + self.assertEqual(self.sandbox.tree_state(self.runtime_root), before) + for path, content in calls.items(): + actual = path.read_bytes() if path.exists() else None + self.assertEqual(actual, content) + + def test_unpointed_legacy_runtime_is_never_executed(self) -> None: + """Install the versioned layout without migrating the old one. + + """ + + legacy = self._legacy_installation() + before = self.sandbox.tree_state(legacy) + # A matching old marker is not enough to bypass a fresh install. failed = self.sandbox.run({"KILIN_TEST_FAIL_UV": "pip"}) self.assertNotEqual(failed.returncode, 0) self.assertFalse(self.active.exists()) - self.assertTrue((legacy / ".installed").is_file()) - self.sandbox.set_launcher("kilin[app]==0.1.0") + self.assertFalse(self.sandbox.gui_calls.exists()) + self.assertEqual(self.sandbox.tree_state(legacy), before) self.assertEqual(self.sandbox.run().returncode, 0) + first = self.sandbox.release_runtime() + self.assertEqual(self.active.read_text(encoding="utf-8"), + "releases/" + first.name + "\n") self.sandbox.set_launcher("kilin[app]==0.2.0") self.assertEqual(self.sandbox.run().returncode, 0) + self.assertTrue((first / ".installed").is_file()) self.assertTrue((legacy / ".installed").is_file()) - self.assertTrue(self.active.is_file()) + self.assertEqual(self.sandbox.tree_state(legacy), before) + self.assertEqual( + self.sandbox.gui_calls.read_text(encoding="utf-8").splitlines(), + ["gui", "gui"], + ) + + def test_explicit_legacy_pointer_is_rejected(self) -> None: + """Never activate a historical layout, even if fully installed. + + """ + + self._legacy_installation() + self.active.write_text("app\n", encoding="utf-8") + self._assert_rejected_without_installing("unsupported installation") + + def test_release_identity_must_match_requested_build(self) -> None: + """A matching marker in a different release is not authoritative. + + """ + + requested = self.sandbox.release_runtime() + wrong = requested.with_name("f" * 64) + self.assertNotEqual(wrong, requested) + executable( + wrong / "bin/kilin-gui", + '#!/bin/sh\nprintf "wrong\\n" >> "$KILIN_TEST_GUI_CALLS"\n', + ) + shutil.copy2(self.sandbox.python_script, wrong / "bin/python") + (wrong / ".installed").write_text( + self.sandbox.spec + "\n", encoding="utf-8" + ) + self.active.write_text("releases/" + wrong.name + "\n", + encoding="utf-8") + before = self.active.read_bytes() + wrong_before = self.sandbox.tree_state(wrong) + failed = self.sandbox.run({"KILIN_TEST_FAIL_UV": "pip"}) + self.assertNotEqual(failed.returncode, 0) + self.assertFalse(self.sandbox.gui_calls.exists()) + self.assertEqual(self.active.read_bytes(), before) + self.assertEqual(self.sandbox.tree_state(wrong), wrong_before) + result = self.sandbox.run() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.active.read_text(encoding="utf-8"), + "releases/" + requested.name + "\n") + self.assertEqual(self.sandbox.tree_state(wrong), wrong_before) + self.assertEqual(self.sandbox.gui_calls.read_text(encoding="utf-8"), + "gui\n") + + def test_linked_runtime_root_is_rejected(self) -> None: + """Refuse to create locks or releases under an external link. + + """ + + external = self.sandbox.root / "external-runtime" + external.mkdir() + (external / "valuable").write_text("keep", encoding="utf-8") + self.runtime_root.parent.mkdir(parents=True) + self.runtime_root.symlink_to(external, target_is_directory=True) + before = self.sandbox.tree_state(external) + self._assert_rejected_without_installing("runtime folder") + self.assertEqual(self.sandbox.tree_state(external), before) + + def test_linked_releases_folder_cannot_delete_external_files(self) -> None: + """Never clean a target through a linked parent directory. + + """ + + old = self._install("0.1.0") + external = self.sandbox.root / "external-releases" + old.parent.rename(external) + old.parent.symlink_to(external, target_is_directory=True) + self.sandbox.set_launcher("kilin[app]==0.2.0") + partial = external / self.sandbox.release_runtime().name + partial.mkdir() + (partial / "valuable").write_text("keep", encoding="utf-8") + before = self.sandbox.tree_state(external) + self._assert_rejected_without_installing("releases folder") + self.assertEqual(self.sandbox.tree_state(external), before) + # Even a completed matching release cannot be reused through a link. + self.sandbox.set_launcher("kilin[app]==0.1.0") + self._assert_rejected_without_installing("releases folder") + self.assertEqual(self.sandbox.tree_state(external), before) + + def test_linked_release_is_rejected_before_activation(self) -> None: + """Do not select or delete a linked complete or partial release. + + """ + + old = self._install("0.1.0") + self.sandbox.set_launcher("kilin[app]==0.2.0") + target = self.sandbox.release_runtime() + external = self.sandbox.root / "external-release" + external.mkdir() + (external / "valuable").write_text("keep", encoding="utf-8") + target.symlink_to(external, target_is_directory=True) + for complete in (False, True): + with self.subTest(complete=complete): + if complete: + (external / "bin").mkdir() + for name, script in ( + ("kilin-gui", self.sandbox.gui_script), + ("python", self.sandbox.python_script), + ): + shutil.copy2(script, external / "bin" / name) + (external / ".installed").write_text( + self.sandbox.spec + "\n", encoding="utf-8" + ) + before = self.sandbox.tree_state(external) + self._assert_rejected_without_installing("release runtime") + self.assertEqual(self.sandbox.tree_state(external), before) + self.assertTrue(old.is_dir()) + self.active.write_text("releases/" + target.name + "\n", + encoding="utf-8") + self._assert_rejected_without_installing("release runtime") + target.unlink() + target.symlink_to(self.sandbox.root / "missing", + target_is_directory=True) + self._assert_rejected_without_installing("release runtime") + + def test_non_directory_release_is_not_disposable(self) -> None: + """A file at the requested release path is not an install attempt. + + """ + + self._install("0.1.0") + self.sandbox.set_launcher("kilin[app]==0.2.0") + self.sandbox.release_runtime().write_text("keep", encoding="utf-8") + self._assert_rejected_without_installing("not a directory") + + def test_incomplete_entry_points_cannot_launch(self) -> None: + """Both entry points must be executable files, not directories. + + """ + + release = self._install("0.1.0") + for name in ("python", "kilin-gui"): + entry = release / "bin" / name + saved = entry.with_name(name + ".saved") + entry.rename(saved) + with self.subTest(entry=name, kind="missing"): + self._assert_rejected_without_installing("incomplete") + with self.subTest(entry=name, kind="directory"): + entry.mkdir() + self._assert_rejected_without_installing("incomplete") + entry.rmdir() + saved.rename(entry) + mode = entry.stat().st_mode + entry.chmod(0o644) + with self.subTest(entry=name, kind="nonexecutable"): + self._assert_rejected_without_installing("incomplete") + entry.chmod(mode) + # A genuine venv Python symlink to an installed interpreter is valid. + python = release / "bin/python" + python.unlink() + python.symlink_to(self.sandbox.python_script) + result = self.sandbox.run() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.sandbox.uv_calls.read_text(encoding="utf-8"), + "venv\npip\n") + + def test_linked_bin_gui_and_marker_are_not_trusted(self) -> None: + """Reject linked launch scripts, metadata, or entry directories. + + """ + + release = self._install("0.1.0") + for relative in ("bin/kilin-gui", ".installed", "bin"): + with self.subTest(relative=relative): + path = release / relative + external = self.sandbox.root / "external-entry" + path.rename(external) + path.symlink_to( + external, target_is_directory=external.is_dir(), + ) + before = self.sandbox.tree_state(external) + self._assert_rejected_without_installing("incomplete") + self.assertEqual(self.sandbox.tree_state(external), before) + path.unlink() + external.rename(path) + + def test_runtime_ancestor_alias_remains_supported(self) -> None: + """An alias above the managed runtime is not a linked release. + + """ + + self._install("0.1.0") + before = self.sandbox.uv_calls.read_bytes() + alias = self.sandbox.root / "ancestor-alias" + alias.symlink_to(self.sandbox.support.parent, + target_is_directory=True) + result = self.sandbox.run({ + "KILIN_APP_SUPPORT": str(alias / self.sandbox.support.name), + }) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.sandbox.uv_calls.read_bytes(), before) def test_invalid_active_pointer_is_not_followed(self) -> None: """Corrupted state cannot select an arbitrary filesystem path. @@ -320,12 +579,14 @@ def test_invalid_active_pointer_is_not_followed(self) -> None: """ old = self._install("0.1.0") - for selection in ("../../escape", "releases/../escape", ""): + valid = "releases/" + old.name + for selection in ( + "../../escape\n", "releases/../escape\n", "", valid, + valid + "\n\n", valid + "\x00\n", valid + "\nextra\n", + ): with self.subTest(selection=selection): self.active.write_text(selection, encoding="utf-8") - result = self.sandbox.run() - self.assertNotEqual(result.returncode, 0) - self.assertIn("active", result.stderr) + self._assert_rejected_without_installing("active") self.assertTrue(old.exists()) def test_symlinked_active_pointer_is_rejected(self) -> None: From 550a31245fae9e8601af3e2f2c033c1d74d331a8 Mon Sep 17 00:00:00 2001 From: Giovanni Volpe Date: Wed, 2 Dec 2026 20:33:53 +0100 Subject: [PATCH 05/37] Canonical preference environment variable --- docs/configuration.md | 2 +- examples/plugins/check_examples.py | 2 +- kilin/gui/README.md | 2 +- kilin/gui/_paths.py | 4 ++-- kilin/gui/preferences.py | 2 +- tests/kilin/gui/test__activation.py | 2 +- tests/kilin/gui/test__paths.py | 24 ++++++++++++++++--- tests/kilin/gui/test_engine__creation.py | 2 +- tests/kilin/gui/test_engine__models.py | 2 +- tests/kilin/gui/test_engine__plugins.py | 2 +- tests/kilin/gui/test_engine__readiness.py | 4 ++-- tests/kilin/gui/test_engine__versions.py | 2 +- tests/kilin/gui/test_model_catalog__cache.py | 2 +- tests/kilin/gui/test_model_settings.py | 2 +- tests/kilin/gui/test_preferences.py | 2 +- .../system_testing/test__plugin_provenance.py | 2 +- tests/kilin/test__pending_plugin_versions.py | 2 +- tests/kilin/test__plugin_management.py | 2 +- .../test_project__creation_provenance.py | 2 +- tests/kilin/test_versioning.py | 2 +- .../data/200_210_llm_plugins/check_drafts.py | 2 +- 21 files changed, 43 insertions(+), 25 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 01e3ab61..6b978d15 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -620,7 +620,7 @@ 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 +`KILIN_PREFERENCES_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. diff --git a/examples/plugins/check_examples.py b/examples/plugins/check_examples.py index c73c803f..cd9c6531 100644 --- a/examples/plugins/check_examples.py +++ b/examples/plugins/check_examples.py @@ -38,7 +38,7 @@ def _child(phase: str, root: Path) -> None: options = ["-I"] if sys.flags.isolated else [] env = dict(os.environ, KILIN_PLUGINS_DIR=str(root / "plugins"), - KILIN_DEFAULTS_FILE=str(root / "preferences.json"), + KILIN_PREFERENCES_FILE=str(root / "preferences.json"), KILIN_WORKSPACES_DIR=str(root / "workspaces"), HF_HUB_OFFLINE="1", HF_HUB_DISABLE_TELEMETRY="1") result = subprocess.run( diff --git a/kilin/gui/README.md b/kilin/gui/README.md index 8e179aaa..2a38f5ed 100644 --- a/kilin/gui/README.md +++ b/kilin/gui/README.md @@ -605,7 +605,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 diff --git a/kilin/gui/_paths.py b/kilin/gui/_paths.py index 4a054436..dee6a23d 100644 --- a/kilin/gui/_paths.py +++ b/kilin/gui/_paths.py @@ -74,7 +74,7 @@ "standard_workspace_directory", ] -PREFERENCES_ENVIRONMENT: Final[str] = "KILIN_DEFAULTS_FILE" +PREFERENCES_ENVIRONMENT: Final[str] = "KILIN_PREFERENCES_FILE" WORKSPACES_ENVIRONMENT: Final[str] = "KILIN_WORKSPACES_DIR" # Set by the macOS .app launcher; the CLI must use that exact bundled wheel @@ -227,7 +227,7 @@ def preferences_path() -> Path: Returns ------- pathlib.Path - Explicit absolute ``KILIN_DEFAULTS_FILE`` path, or a user + Explicit absolute ``KILIN_PREFERENCES_FILE`` path, or a user configuration file. The packaged defaults are never the default. Raises diff --git a/kilin/gui/preferences.py b/kilin/gui/preferences.py index 527774df..8cdbc1f4 100644 --- a/kilin/gui/preferences.py +++ b/kilin/gui/preferences.py @@ -379,7 +379,7 @@ def preferences_file() -> Path: Returns ------- pathlib.Path - ``KILIN_DEFAULTS_FILE`` when explicitly supplied, or a + ``KILIN_PREFERENCES_FILE`` when explicitly supplied, or a platform-specific user configuration path. """ diff --git a/tests/kilin/gui/test__activation.py b/tests/kilin/gui/test__activation.py index d9ccbf57..34c702db 100644 --- a/tests/kilin/gui/test__activation.py +++ b/tests/kilin/gui/test__activation.py @@ -65,7 +65,7 @@ def setUp(self) -> None: def test_record_sits_beside_preferences(self) -> None: preferences = self.folder / "custom" / "preferences.json" with patch.dict( - "os.environ", {"KILIN_DEFAULTS_FILE": str(preferences)} + "os.environ", {"KILIN_PREFERENCES_FILE": str(preferences)} ): self.assertEqual( activation_record(), preferences.with_name("activation.json") diff --git a/tests/kilin/gui/test__paths.py b/tests/kilin/gui/test__paths.py index 69258958..4ffc34f9 100644 --- a/tests/kilin/gui/test__paths.py +++ b/tests/kilin/gui/test__paths.py @@ -155,7 +155,7 @@ def test_environment_overrides_are_explicit(self) -> None: with patch.dict( "os.environ", { - "KILIN_DEFAULTS_FILE": str(self.root / "prefs.json"), + "KILIN_PREFERENCES_FILE": str(self.root / "prefs.json"), "KILIN_WORKSPACES_DIR": str(self.root / "workspaces"), }, ): @@ -167,6 +167,24 @@ def test_environment_overrides_are_explicit(self) -> None: self.root / "workspaces", ) + def test_retired_preferences_environment_is_ignored(self) -> None: + """Do not retain an alias for the retired override name.""" + + old = self.root / "old.json" + new = self.root / "new.json" + with ( + patch.object(_paths.sys, "platform", "linux"), + patch.dict("os.environ", {"KILIN_DEFAULTS_FILE": str(old)}), + ): + self.assertEqual( + _paths.preferences_path(), + self.home / ".config/kilin/preferences.json", + ) + with patch.dict( + "os.environ", {"KILIN_PREFERENCES_FILE": str(new)} + ): + self.assertEqual(_paths.preferences_path(), new) + def test_projects_folder_from_settings_is_remembered(self) -> None: """Use the chosen folder while it exists; otherwise the standard.""" @@ -177,7 +195,7 @@ def test_projects_folder_from_settings_is_remembered(self) -> None: json.dumps({"workspace_folder": str(chosen)}), encoding="utf-8" ) standard = self.home / "Documents/KíLín" - environment = {"KILIN_DEFAULTS_FILE": str(preferences)} + environment = {"KILIN_PREFERENCES_FILE": str(preferences)} with ( patch.dict("os.environ", environment), patch.object(_paths.sys, "platform", "darwin"), @@ -206,7 +224,7 @@ def test_relative_environment_paths_are_rejected(self) -> None: """Avoid silently writing relative paths under site-packages.""" with patch.dict( - "os.environ", {"KILIN_DEFAULTS_FILE": "preferences.json"} + "os.environ", {"KILIN_PREFERENCES_FILE": "preferences.json"} ): with self.assertRaisesRegex(ValueError, "absolute path"): _paths.preferences_path() diff --git a/tests/kilin/gui/test_engine__creation.py b/tests/kilin/gui/test_engine__creation.py index d7d038a1..b8dedce8 100644 --- a/tests/kilin/gui/test_engine__creation.py +++ b/tests/kilin/gui/test_engine__creation.py @@ -215,7 +215,7 @@ def test_gui_router_preference_is_saved_for_new_projects(self): settings = self.root / "preferences.json" target = self.root / "custom-router" with patch.dict( - os.environ, {"KILIN_DEFAULTS_FILE": str(settings)} + os.environ, {"KILIN_PREFERENCES_FILE": str(settings)} ): write_defaults({ "router_models": {"mlx": "example/preferred-router"}, diff --git a/tests/kilin/gui/test_engine__models.py b/tests/kilin/gui/test_engine__models.py index 00a07ee3..0f90fa9d 100644 --- a/tests/kilin/gui/test_engine__models.py +++ b/tests/kilin/gui/test_engine__models.py @@ -39,7 +39,7 @@ def setUp(self): source.write_text("Original document about memory.", encoding="utf-8") user_preferences = patch.dict( "os.environ", - {"KILIN_DEFAULTS_FILE": str(self.root / "preferences.json")}, + {"KILIN_PREFERENCES_FILE": str(self.root / "preferences.json")}, ) user_preferences.start() self.addCleanup(user_preferences.stop) diff --git a/tests/kilin/gui/test_engine__plugins.py b/tests/kilin/gui/test_engine__plugins.py index bbbf484e..495ce2ad 100644 --- a/tests/kilin/gui/test_engine__plugins.py +++ b/tests/kilin/gui/test_engine__plugins.py @@ -151,7 +151,7 @@ def test_real_engine_protocol_without_models_and_restart(self): env = dict( os.environ, KILIN_PLUGINS_DIR=str(root / "plugins"), KILIN_WORKSPACES_DIR=str(root / "workspaces"), - KILIN_DEFAULTS_FILE=str(root / "preferences.json"), + KILIN_PREFERENCES_FILE=str(root / "preferences.json"), ) source = root / "example" source.mkdir() diff --git a/tests/kilin/gui/test_engine__readiness.py b/tests/kilin/gui/test_engine__readiness.py index 1c9d0f51..f8347036 100644 --- a/tests/kilin/gui/test_engine__readiness.py +++ b/tests/kilin/gui/test_engine__readiness.py @@ -71,7 +71,7 @@ def test_readiness_can_use_installed_models_without_package_writes( replacement = "example/Qwen3-8B-MLX-4bit" with patch.dict( os.environ, - {"KILIN_DEFAULTS_FILE": str(preference_file)}, + {"KILIN_PREFERENCES_FILE": str(preference_file)}, ): required = required_models("mlx") self.assertIn(missing_model, required) @@ -135,7 +135,7 @@ def setUp(self) -> None: self.root = Path(folder.name).resolve() settings = patch.dict( os.environ, - {"KILIN_DEFAULTS_FILE": str(self.root / "preferences.json")}, + {"KILIN_PREFERENCES_FILE": str(self.root / "preferences.json")}, ) settings.start() self.addCleanup(settings.stop) diff --git a/tests/kilin/gui/test_engine__versions.py b/tests/kilin/gui/test_engine__versions.py index 59aadb7a..60558a8e 100644 --- a/tests/kilin/gui/test_engine__versions.py +++ b/tests/kilin/gui/test_engine__versions.py @@ -90,7 +90,7 @@ def test_diagnostics_retain_request_correlation(self): def test_real_protocol_without_models(self): env = dict( os.environ, KILIN_PLUGINS_DIR=str(self.root / "plugins"), - KILIN_DEFAULTS_FILE=str(self.root / "defaults.json"), + KILIN_PREFERENCES_FILE=str(self.root / "defaults.json"), PYTHONPATH=str(Path(kilin.__file__).resolve().parents[1]), PYTHONIOENCODING="utf-8", ) diff --git a/tests/kilin/gui/test_model_catalog__cache.py b/tests/kilin/gui/test_model_catalog__cache.py index af6c91de..17f1c140 100644 --- a/tests/kilin/gui/test_model_catalog__cache.py +++ b/tests/kilin/gui/test_model_catalog__cache.py @@ -320,7 +320,7 @@ def test_readiness_uses_the_conservative_cache_result(self) -> None: with patch.dict( "os.environ", - {"KILIN_DEFAULTS_FILE": str(self.root / "preferences.json")}, + {"KILIN_PREFERENCES_FILE": str(self.root / "preferences.json")}, ): model_id = required_models("torch")[0] entry = self._snapshot(model_id, { diff --git a/tests/kilin/gui/test_model_settings.py b/tests/kilin/gui/test_model_settings.py index fc62805e..c1a68c2b 100644 --- a/tests/kilin/gui/test_model_settings.py +++ b/tests/kilin/gui/test_model_settings.py @@ -32,7 +32,7 @@ def setUp(self) -> None: self.addCleanup(temporary.cleanup) self.root = Path(temporary.name) override = patch.dict("os.environ", { - "KILIN_DEFAULTS_FILE": str(self.root / "preferences.json"), + "KILIN_PREFERENCES_FILE": str(self.root / "preferences.json"), }) override.start() self.addCleanup(override.stop) diff --git a/tests/kilin/gui/test_preferences.py b/tests/kilin/gui/test_preferences.py index 5fb5432e..3bbcbe64 100644 --- a/tests/kilin/gui/test_preferences.py +++ b/tests/kilin/gui/test_preferences.py @@ -37,7 +37,7 @@ def setUp(self) -> None: self.root = Path(temporary.name) self.path = self.root / "config" / "preferences.json" self.override = patch.dict( - "os.environ", {"KILIN_DEFAULTS_FILE": str(self.path)} + "os.environ", {"KILIN_PREFERENCES_FILE": str(self.path)} ) self.override.start() self.addCleanup(self.override.stop) diff --git a/tests/kilin/system_testing/test__plugin_provenance.py b/tests/kilin/system_testing/test__plugin_provenance.py index 6e994050..7607c385 100644 --- a/tests/kilin/system_testing/test__plugin_provenance.py +++ b/tests/kilin/system_testing/test__plugin_provenance.py @@ -274,7 +274,7 @@ def test_external_plugin_replay_and_offline_inspection(self): definition = definitions / (_TYPE + ".json") definition.write_text(json.dumps(_type_data()), encoding="utf-8") env = dict(os.environ, KILIN_PLUGINS_DIR=str(plugins), - KILIN_DEFAULTS_FILE=str(root / "preferences.json")) + KILIN_PREFERENCES_FILE=str(root / "preferences.json")) env["PYTHONPATH"] = str(_ROOT) self._child(root, env, "_record") # Replacing code without bumping its declared version must diff --git a/tests/kilin/test__pending_plugin_versions.py b/tests/kilin/test__pending_plugin_versions.py index 215698ce..ceb79110 100644 --- a/tests/kilin/test__pending_plugin_versions.py +++ b/tests/kilin/test__pending_plugin_versions.py @@ -63,7 +63,7 @@ def setUp(self): self.import_log = self.root / "imports.txt" self.env = dict( os.environ, KILIN_PLUGINS_DIR=str(self.plugins), - KILIN_DEFAULTS_FILE=str(self.root / "defaults.json"), + KILIN_PREFERENCES_FILE=str(self.root / "defaults.json"), KILIN_TEST_IMPORT_LOG=str(self.import_log), PYTHONPATH=str(Path(kilin.__file__).resolve().parents[1]), ) diff --git a/tests/kilin/test__plugin_management.py b/tests/kilin/test__plugin_management.py index f0f19059..3aabecba 100644 --- a/tests/kilin/test__plugin_management.py +++ b/tests/kilin/test__plugin_management.py @@ -54,7 +54,7 @@ def setUp(self): self.env = dict( os.environ, KILIN_PLUGINS_DIR=str(self.store), KILIN_WORKSPACES_DIR=str(self.root / "workspaces"), - KILIN_DEFAULTS_FILE=str(self.root / "preferences.json"), + KILIN_PREFERENCES_FILE=str(self.root / "preferences.json"), ) self.drafts = self.root / "drafts" self.drafts.mkdir() diff --git a/tests/kilin/test_project__creation_provenance.py b/tests/kilin/test_project__creation_provenance.py index da605f9b..5bef81c4 100644 --- a/tests/kilin/test_project__creation_provenance.py +++ b/tests/kilin/test_project__creation_provenance.py @@ -176,7 +176,7 @@ def test_new_runtime_uses_updated_type_but_retains_previous_origin(self): definition.write_text(json.dumps(raw), encoding="utf-8") original_digest = sha256(definition.read_bytes()).hexdigest() env = dict(os.environ, KILIN_PLUGINS_DIR=str(plugins), - KILIN_DEFAULTS_FILE=str(self.root / "defaults.json"), + KILIN_PREFERENCES_FILE=str(self.root / "defaults.json"), PYTHONPATH=str(Path(kilin.__file__).resolve().parents[1])) script = """ from dataclasses import asdict diff --git a/tests/kilin/test_versioning.py b/tests/kilin/test_versioning.py index f200c110..85eac411 100644 --- a/tests/kilin/test_versioning.py +++ b/tests/kilin/test_versioning.py @@ -207,7 +207,7 @@ def test_real_discovery_and_clean_json_in_fresh_processes(self): (package / "__init__.py").write_text(_TOOL, encoding="utf-8") environment = dict( os.environ, KILIN_PLUGINS_DIR=str(root / "plugins"), - KILIN_DEFAULTS_FILE=str(root / "defaults.json"), + KILIN_PREFERENCES_FILE=str(root / "defaults.json"), PYTHONPATH=str(Path(kilin.__file__).resolve().parents[1]), PYTHONIOENCODING="utf-8", ) diff --git a/tutorials/data/200_210_llm_plugins/check_drafts.py b/tutorials/data/200_210_llm_plugins/check_drafts.py index 3ad7c406..6cb9e0f2 100644 --- a/tutorials/data/200_210_llm_plugins/check_drafts.py +++ b/tutorials/data/200_210_llm_plugins/check_drafts.py @@ -59,7 +59,7 @@ def _child( env = dict( os.environ, PYTHONPATH=str(ROOT), KILIN_PLUGINS_DIR=str(root / "plugins"), - KILIN_DEFAULTS_FILE=str(root / "preferences.json"), + KILIN_PREFERENCES_FILE=str(root / "preferences.json"), KILIN_WORKSPACES_DIR=str(root / "workspaces"), HF_HUB_OFFLINE="1", HF_HUB_DISABLE_TELEMETRY="1", TRANSFORMERS_OFFLINE="1", From 0fe8962f548face2e2b892d0b466e2e147687d74 Mon Sep 17 00:00:00 2001 From: Giovanni Volpe Date: Wed, 2 Dec 2026 20:34:24 +0100 Subject: [PATCH 06/37] Explicit retrieval scopes --- docs/retrieval_pipeline.md | 3 + kilin/rag.py | 116 ++++++---------- tests/kilin/test_rag__answering.py | 2 + tests/kilin/test_rag__empty_workspace.py | 6 +- tests/kilin/test_rag__retrieval.py | 124 +++++++++++++----- .../kilin/test_rag__retrieval_corrections.py | 22 +++- tests/kilin/test_rag__source_first.py | 52 ++++++-- tests/kilin/test_rag__source_first_budget.py | 6 + 8 files changed, 208 insertions(+), 123 deletions(-) diff --git a/docs/retrieval_pipeline.md b/docs/retrieval_pipeline.md index 04fa3c60..13cb0df7 100644 --- a/docs/retrieval_pipeline.md +++ b/docs/retrieval_pipeline.md @@ -987,6 +987,9 @@ 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 diff --git a/kilin/rag.py b/kilin/rag.py index 2a21fe91..f3bb52ac 100644 --- a/kilin/rag.py +++ b/kilin/rag.py @@ -2362,6 +2362,7 @@ def notify() -> None: 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, @@ -2375,6 +2376,11 @@ def notify() -> None: 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. @@ -2394,6 +2400,7 @@ def notify() -> None: 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, @@ -5100,7 +5107,7 @@ def _retrieve( include_bibliographies: bool | None = None, _query_vectors: dict[str, list[float]] | None = None, view: SourceView | None = None, - scope_mode: ScopeMode | None = None, + scope_mode: ScopeMode, ) -> tuple[Evidence, ...]: """Run hybrid retrieval and deterministic context expansion. @@ -5119,10 +5126,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``), @@ -5152,9 +5158,9 @@ def _retrieve( from independent-document discovery. Defaults to None. view: SourceView | None, optional Frozen operation. Only its ranked physical members participate. - scope_mode: ScopeMode | None, optional - Explicit physical scope for callers without a resolved view. - None preserves the private legacy preference convention. + 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 @@ -5173,12 +5179,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. """ @@ -5196,6 +5202,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 @@ -5235,7 +5243,7 @@ def report(message: str) -> None: metadata=source_report, exhaustive=source_limits.coverage == COVERAGE_EXHAUSTIVE, requested=requested_source_count(question), - scope_mode=scope_mode, view=view, + view=view, ) report("No indexed group evidence; skipping retrieval") return () @@ -5354,8 +5362,8 @@ 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( scoped.semantic, query_text, @@ -5496,7 +5504,6 @@ 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, ...] = () @@ -5543,8 +5550,6 @@ def keep(results: list) -> list: ), requested=requested_source_count(question), include_bibliographies=include_bibliographies, - **({"scope_mode": scope_mode} - if scope_mode is not None else {}), **({"view": view} if grouped else {}), ) chosen_source_paths = tuple( @@ -5565,34 +5570,11 @@ def keep(results: list) -> list: if item.chunk.path in allowed] chunks = [chunk for chunk in chunks if chunk.path in allowed] graph = scoped_graph(graph, allowed) - if chosen or scope_mode is not None: - 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 and scope_mode is None: - 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, - ) + 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. @@ -5665,11 +5647,6 @@ def keep(results: list) -> list: if not grouped: allowed = set(chosen_source_paths) expanded = [chunk for chunk in expanded if chunk.path in allowed] - elif (scope_mode is None and source_first is not None - and len(named) > 1): - # Retain explicit scopes for direct calls without evidence limits. - allowed = set(named) - expanded = [chunk for chunk in expanded if chunk.path in allowed] if allowed is not None: expanded = [chunk for chunk in expanded if chunk.path in allowed] if exclude_bibliographies: @@ -6614,7 +6591,6 @@ def _source_passages( exhaustive: bool = False, requested: int = 0, include_bibliographies: bool = False, - scope_mode: ScopeMode | None = None, view: SourceView | None = None, ) -> list[HybridResult]: """Select sources by four-channel RRF, then original passages. @@ -6634,9 +6610,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 @@ -6653,12 +6630,6 @@ def _source_passages( include_bibliographies: bool, optional Allow bibliography text in explicit lookup. Defaults to False. - scope_mode: ScopeMode | None, optional - When supplied, channel membership has already been restricted - by the host; named operands are prioritized, not used to drop - permitted supporting members. None keeps the private legacy - convention. - view: SourceView | None, optional Grouped document operation. Returns the complete ranking of selected groups' original evidence for final budget allocation. @@ -6667,11 +6638,10 @@ def _source_passages( ------- 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 ----- @@ -6713,15 +6683,7 @@ def _source_passages( else: available = [item for item in ranked_sources if item.path in indexed_paths] - if scope_mode is not None: - available.sort(key=lambda item: item.path not in named) - elif 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 + available.sort(key=lambda item: item.path not in named) full_passages = hybrid_search( semantic=semantic, @@ -6730,7 +6692,7 @@ def _source_passages( count=max(len(self.chunks), 1), ) unrelated: list[Path] = [] - if not exhaustive and (scope_mode is not None or len(named) < 2): + if not exhaustive: relevant = relevant_sources( available, full_passages, diff --git a/tests/kilin/test_rag__answering.py b/tests/kilin/test_rag__answering.py index fbc7a87d..6100258c 100644 --- a/tests/kilin/test_rag__answering.py +++ b/tests/kilin/test_rag__answering.py @@ -373,6 +373,8 @@ def test_search_uses_document_scope_candidates(self) -> None: [Path("one.py"), Path("two.py")]) self.assertEqual(mocks.retrieve.call_args.kwargs["scope"], (Path("one.py"),)) + self.assertEqual(mocks.retrieve.call_args.kwargs["scope_mode"], + "restricted") def test_document_answer_keeps_document_metadata(self) -> None: """Retain selected-document provenance and answer parameters.""" diff --git a/tests/kilin/test_rag__empty_workspace.py b/tests/kilin/test_rag__empty_workspace.py index 7c540dad..f7f30428 100644 --- a/tests/kilin/test_rag__empty_workspace.py +++ b/tests/kilin/test_rag__empty_workspace.py @@ -127,7 +127,11 @@ def test_empty_chat_reopen_import_and_remove_sources(self) -> None: self.assertEqual(session._unsearchable_sources([]), []) count = len(embedding.queries) - self.assertEqual(session._retrieve("diffusion"), ()) + self.assertEqual( + session._retrieve( + "diffusion", scope_mode="project", + ), (), + ) self.assertEqual(len(embedding.queries), count) self.assertEqual(len(session.turns), 2) finally: diff --git a/tests/kilin/test_rag__retrieval.py b/tests/kilin/test_rag__retrieval.py index ad1188db..ffc001f3 100644 --- a/tests/kilin/test_rag__retrieval.py +++ b/tests/kilin/test_rag__retrieval.py @@ -53,7 +53,11 @@ def test_retrieval_uses_formatted_semantic_and_raw_lexical_query( session.chunks = [chunk("indexed")] session._format_query = Mock(return_value="formatted question") with _search_patches() as mocks: - self.assertEqual(session._retrieve("question", 8), ()) + self.assertEqual( + session._retrieve( + "question", 8, scope_mode="project", + ), (), + ) mocks["semantic_search"].assert_called_once_with( sentinel.semantic_index, "formatted question", @@ -78,8 +82,12 @@ def test_retrieval_widening_reuses_one_query_embedding(self) -> None: session.embedding_session.embed_query.return_value = [1.0, 0.0] vectors = {} with _search_patches() as mocks: - session._retrieve("question", 2, _query_vectors=vectors) - session._retrieve("question", 4, _query_vectors=vectors) + session._retrieve( + "question", 2, _query_vectors=vectors, scope_mode="project", + ) + session._retrieve( + "question", 4, _query_vectors=vectors, scope_mode="project", + ) session.embedding_session.embed_query.assert_called_once_with( "question" ) @@ -94,7 +102,10 @@ def test_retrieval_reports_all_search_stages(self) -> None: session.chunks = [chunk("indexed")] messages = [] with _search_patches() as mocks: - session._retrieve("question", status_callback=messages.append) + session._retrieve( + "question", status_callback=messages.append, + scope_mode="project", + ) self.assertIn("Running lexical search", messages) self.assertIn("Combining and ranking search results", messages) self.assertIn("Expanding related context", messages) @@ -115,7 +126,9 @@ def test_code_graph_search_is_conditional_on_entities(self) -> None: mocks["code_search"].return_value = [ ranked(session.chunks[0]) ] - session._retrieve("func", trace_turn_id="turn-1") + session._retrieve( + "func", trace_turn_id="turn-1", scope_mode="project", + ) mocks["code_search"].assert_called_once_with( session.indexes.code_graph, session.chunks, "func", count=5 ) @@ -132,7 +145,7 @@ def test_retrieval_renumbers_expanded_chunks_and_keeps_cells(self) -> None: mocks["expand_retrieval_context"].return_value = [ first, second ] - evidence = session._retrieve("question") + evidence = session._retrieve("question", scope_mode="project") self.assertEqual([item.citation for item in evidence], [1, 2]) self.assertEqual([item.path for item in evidence], [Path("a.py"), Path("b.ipynb")]) @@ -162,14 +175,19 @@ def test_source_code_preference_ranks_documentation_later(self) -> None: mocks["hybrid_search"].return_value = [ tutorial, guide, test, source ] - session._retrieve("question", 2, prefer_source_code=prefer) + session._retrieve( + "question", 2, prefer_source_code=prefer, + scope_mode="project", + ) self.assertEqual( mocks["expand_retrieval_context"].call_args.args[0], expected, ) with _search_patches() as mocks: mocks["hybrid_search"].return_value = [tutorial, test, source] - session._retrieve("question", 3, prefer_source_code=True) + session._retrieve( + "question", 3, prefer_source_code=True, scope_mode="project", + ) self.assertEqual( mocks["expand_retrieval_context"].call_args.args[0], [source, tutorial, test], @@ -187,7 +205,9 @@ def test_source_code_preference_searches_deeper(self) -> None: source = ranked(chunk("s", path="pkg/a.py")) with _search_patches() as mocks: mocks["lexical_search"].return_value = [*guides, source] - session._retrieve("question", 1, prefer_source_code=True) + session._retrieve( + "question", 1, prefer_source_code=True, scope_mode="project", + ) depth = rag.SOURCE_SEARCH_DEPTH self.assertEqual( mocks["lexical_search"].call_args.kwargs["count"], depth @@ -197,53 +217,90 @@ def test_source_code_preference_searches_deeper(self) -> None: ) with _search_patches() as mocks: mocks["lexical_search"].return_value = [*guides, source] - session._retrieve("question", 1) + session._retrieve("question", 1, scope_mode="project") self.assertEqual( mocks["lexical_search"].call_args.kwargs["count"], 1 ) def test_single_document_scope_uses_full_ranking(self) -> None: - """Apply full ranking to evidence scoped to a single document.""" + """Preferred operands can outrank higher-ranked general results.""" session = _session() - session.chunks = [chunk("indexed")] + session.chunks = [chunk("indexed"), chunk("target", path="target.py")] first = ranked(chunk("a", path="other.py")) - focused = ranked(chunk("b", path="target.py")) - session._rank_everything = Mock(return_value=[first, focused]) + focused = ranked(session.chunks[1]) + session._rank_everything = Mock() with _search_patches() as mocks: - mocks["hybrid_search"].return_value = [first] - mocks["expand_retrieval_context"].return_value = [ - focused.chunk - ] - session._retrieve("question", 1, scope=[Path("target.py")]) - session._rank_everything.assert_called_once_with( - "question", None, semantic_results=[] + mocks["semantic_search"].return_value = [first, focused] + mocks["hybrid_search"].return_value = [first, focused] + mocks["expand_retrieval_context"].return_value = [focused.chunk] + evidence = session._retrieve( + "question", 1, scope=[Path("target.py")], + scope_mode="preferred", + ) + session._rank_everything.assert_not_called() + self.assertEqual( + mocks["hybrid_search"].call_args.kwargs["semantic"], + [first, focused], ) self.assertEqual( mocks["expand_retrieval_context"].call_args.args[0], [focused], ) + self.assertEqual(evidence[0].path, Path("target.py")) def test_empty_scoped_ranking_retains_general_results(self) -> None: - """Fall back to general ranking when scoped results are empty.""" + """A missing preferred operand does not restrict general results.""" session = _session() session.chunks = [chunk("indexed")] general = ranked(chunk("a", path="other.py")) - session._rank_everything = Mock(return_value=[general]) + session._rank_everything = Mock() with _search_patches() as mocks: mocks["hybrid_search"].return_value = [general] - session._retrieve("question", scope=[Path("missing.py")]) + session._retrieve( + "question", scope=[Path("missing.py")], + scope_mode="preferred", + ) + session._rank_everything.assert_not_called() self.assertEqual( mocks["expand_retrieval_context"].call_args.args[0], [general], ) def test_multiple_scoped_paths_do_not_focus_ranking(self) -> None: - """Avoid special single-document handling for multiple paths.""" + """Prioritize multiple preferred paths within a single ranking.""" session = _session() + session.chunks = [chunk("a", path="a.py"), chunk("b", path="b.py")] session._rank_everything = Mock() - with _search_patches(): - session._retrieve("question", scope=[Path("a"), Path("b")]) + first = ranked(session.chunks[0]) + second = ranked(session.chunks[1]) + general = ranked(chunk("other", path="other.py")) + with _search_patches() as mocks: + mocks["hybrid_search"].return_value = [general, first, second] + session._retrieve( + "question", 2, scope=[Path("a.py"), Path("b.py")], + scope_mode="preferred", + ) session._rank_everything.assert_not_called() + self.assertEqual( + mocks["expand_retrieval_context"].call_args.args[0], + [first, second], + ) + + def test_retrieval_requires_explicit_scope_mode(self) -> None: + """Reject omitted or invalid private modes before searching.""" + session = _session() + session.chunks = [chunk("indexed")] + with _search_patches() as mocks: + with self.assertRaises(TypeError): + session._retrieve("question") + for mode in (None, "unknown"): + with self.subTest(mode=mode), self.assertRaisesRegex( + ValueError, "Unknown source scope mode" + ): + session._retrieve("question", scope_mode=mode) + mocks["semantic_search"].assert_not_called() + mocks["lexical_search"].assert_not_called() + session.embedding_session.embed_query.assert_not_called() def test_retrieval_emits_content_when_tracing_enabled(self) -> None: """Attach exact retrieved content when tracing is enabled.""" @@ -255,7 +312,9 @@ def test_retrieval_emits_content_when_tracing_enabled(self) -> None: sample = chunk("a", "private source") with _search_patches() as mocks: mocks["expand_retrieval_context"].return_value = [sample] - session._retrieve("question", trace_turn_id="t") + session._retrieve( + "question", trace_turn_id="t", scope_mode="project", + ) event = [ item for item in session.trace.emit.call_args_list if item.args[0] == "retrieval.context.expanded" @@ -347,7 +406,10 @@ def test_empty_retrieval_skips_models_and_all_search_stages(self) -> None: messages = [] with _search_patches() as mocks: self.assertEqual( - session._retrieve("hello", status_callback=messages.append), + session._retrieve( + "hello", status_callback=messages.append, + scope_mode="project", + ), (), ) self.assertEqual(session._rank_everything("hello"), []) @@ -376,6 +438,7 @@ def test_relationship_progress_is_generic_and_reports_real_work( session._retrieve( "How does func_name work?", status_callback=messages.append, + scope_mode="project", ) if available: mocks["code_search"].assert_called_once() @@ -407,7 +470,8 @@ def test_prose_question_skips_the_code_graph_channel(self) -> None: messages = [] with _search_patches() as mocks: session._retrieve( - "Which files are valid?", status_callback=messages.append + "Which files are valid?", status_callback=messages.append, + scope_mode="project", ) mocks["code_search"].assert_not_called() self.assertIn( diff --git a/tests/kilin/test_rag__retrieval_corrections.py b/tests/kilin/test_rag__retrieval_corrections.py index 3ac1093f..aeef424f 100644 --- a/tests/kilin/test_rag__retrieval_corrections.py +++ b/tests/kilin/test_rag__retrieval_corrections.py @@ -93,6 +93,7 @@ def test_expansion_and_named_scope_embed_once(self): evidence = session._retrieve( "Explain loading settings", 3, trace_turn_id="turn-7", scope=scope, + scope_mode="preferred" if scope else "project", ) self.assertTrue(evidence) session.embedding_session.embed_query.assert_called_once_with( @@ -101,8 +102,8 @@ def test_expansion_and_named_scope_embed_once(self): def test_each_new_query_gets_its_own_embedding(self): session = _retrieval_session() - session._retrieve("Explain loading", 3) - session._retrieve("Explain parsing", 3) + session._retrieve("Explain loading", 3, scope_mode="project") + session._retrieve("Explain parsing", 3, scope_mode="project") self.assertEqual(session.embedding_session.embed_query.call_count, 2) self.assertEqual( [call.args[0] for call in @@ -117,7 +118,9 @@ def test_invalid_query_vectors_fail_before_expansion(self): session.embedding_session.embed_query.return_value = vector with patch.object(rag, "expand_retrieval_context") as expand: with self.assertRaises(ValueError): - session._retrieve("Explain loading", 3) + session._retrieve( + "Explain loading", 3, scope_mode="project", + ) expand.assert_not_called() self.assertEqual( session.embedding_session.embed_query.call_count, 1 @@ -140,7 +143,7 @@ def test_fusion_retains_original_semantic_depth(self): with patch.object( rag, "hybrid_search", wraps=rag.hybrid_search ) as fuse: - session._retrieve("Explain the process", 1) + session._retrieve("Explain the process", 1, scope_mode="project") semantic = fuse.call_args_list[0].kwargs["semantic"] self.assertEqual(len(semantic), 1) self.assertEqual(semantic[0].chunk.identifier, "guide") @@ -152,7 +155,8 @@ class TestFocusedAndAlternativeEvidence(unittest.TestCase): def test_named_file_is_first_but_cross_file_expansion_remains(self): session = _retrieval_session() evidence = session._retrieve( - "Explain pkg/a.py", 3, scope=(Path("pkg/a.py"),) + "Explain pkg/a.py", 3, scope=(Path("pkg/a.py"),), + scope_mode="preferred", ) self.assertEqual(evidence[0].path, Path("pkg/a.py")) self.assertEqual(evidence[0].context_role, "direct") @@ -170,7 +174,9 @@ def test_named_file_is_first_but_cross_file_expansion_remains(self): def test_named_function_precedes_higher_ranked_unrelated_text(self): session = _retrieval_session() - evidence = session._retrieve("Explain load_value()", 3) + evidence = session._retrieve( + "Explain load_value()", 3, scope_mode="project", + ) self.assertEqual(evidence[0].symbol, "load_value") self.assertEqual(evidence[0].context_role, "direct") self.assertIn(Path("docs/guide.md"), [item.path for item in evidence]) @@ -185,7 +191,9 @@ def test_fallback_remains_available_but_is_labeled_alternative(self): session.indexes.semantic, chunks=tuple(session.chunks) ) session.indexes.lexical = build_lexical_index(session.chunks) - evidence = session._retrieve("Explain settings", 3) + evidence = session._retrieve( + "Explain settings", 3, scope_mode="project", + ) candidate = next( item for item in evidence if item.symbol == "parse_config" ) diff --git a/tests/kilin/test_rag__source_first.py b/tests/kilin/test_rag__source_first.py index 023ed0c8..9c9319d5 100644 --- a/tests/kilin/test_rag__source_first.py +++ b/tests/kilin/test_rag__source_first.py @@ -91,6 +91,7 @@ def test_card_discovers_source_outside_top_passages(self): session = _session() evidence = session._retrieve( "memory", 2, source_first=(2, False), trace_turn_id="turn", + scope_mode="project", ) self.assertEqual(len(evidence), 2) self.assertEqual(evidence[0].path, Path("c.pdf")) @@ -106,7 +107,9 @@ def test_all_source_channels_are_ranked_without_extra_query(self): with patch.object( rag, "lexical_search", wraps=rag.lexical_search ) as lexical: - session._retrieve("memory", 2, source_first=(2, False)) + session._retrieve( + "memory", 2, source_first=(2, False), scope_mode="project", + ) self.assertEqual( lexical.call_args.kwargs["count"], len(session.chunks) ) @@ -124,14 +127,16 @@ def test_registered_card_kind_does_not_change_generic_ranking(self): ) ) evidence = session._retrieve( - "memory", 2, source_first=(2, False) + "memory", 2, source_first=(2, False), + scope_mode="project", ) self.assertEqual(evidence[0].path, Path("c.pdf")) def test_without_cards_ordinary_source_rankings_still_work(self): session = _session(cards=False) evidence = session._retrieve( - "memory", 2, source_first=(2, False) + "memory", 2, source_first=(2, False), + scope_mode="project", ) self.assertEqual(len(evidence), 2) self.assertNotIn(Path("c.pdf"), [item.path for item in evidence]) @@ -144,6 +149,7 @@ def test_multiple_named_sources_restrict_evidence(self): evidence = session._retrieve( "memory", 3, source_first=(3, True), scope=(Path("a.pdf"), Path("c.pdf")), + scope_mode="restricted", ) self.assertEqual( {item.path for item in evidence}, @@ -156,6 +162,7 @@ def test_single_named_source_is_primary(self): evidence = session._retrieve( "memory", 3, source_first=(3, False), scope=(Path("b.pdf"),), + scope_mode="restricted", ) self.assertEqual({item.path for item in evidence}, {Path("b.pdf")}) @@ -164,23 +171,45 @@ def test_single_named_source_can_be_compared(self): evidence = session._retrieve( "memory", 3, source_first=(3, True), scope=(Path("b.pdf"),), + scope_mode="preferred", ) self.assertEqual(evidence[0].path, Path("b.pdf")) self.assertGreater(len({item.path for item in evidence}), 1) + def test_empty_source_selection_does_not_fall_back(self): + session = _session() + with patch.object(session, "_source_passages", return_value=[]): + evidence = session._retrieve( + "memory", 2, source_first=(2, False), scope_mode="project", + ) + self.assertEqual(evidence, ()) + session.embedding_session.embed_query.assert_called_once() + + def test_restricted_empty_scope_skips_all_search(self): + for strategy in (None, (2, False)): + with self.subTest(strategy=strategy): + session = _session() + self.assertEqual(session._retrieve( + "memory", 2, source_first=strategy, + scope_mode="restricted", scope=(), + ), ()) + session.embedding_session.embed_query.assert_not_called() + def test_source_count_is_bounded(self): session = _session() evidence = session._retrieve( - "memory", 1, source_first=(12, False) + "memory", 1, source_first=(12, False), + scope_mode="project", ) self.assertEqual(len(evidence), 1) def test_hybrid_retrieval_is_independent_of_source_first(self): session = _session() - hybrid = session._retrieve("memory", 2) + hybrid = session._retrieve("memory", 2, scope_mode="project") self.assertEqual([item.path for item in hybrid], [Path("a.pdf")] * 2) selected = session._retrieve( - "memory", 2, source_first=(2, False) + "memory", 2, source_first=(2, False), + scope_mode="project", ) self.assertIn(Path("c.pdf"), [item.path for item in selected]) @@ -205,7 +234,9 @@ def test_source_rank_trace_records_four_channel_provenance(self): session = _session() session.trace = MagicMock() session.trace.include_content = False - session._retrieve("memory", 2, source_first=(2, False)) + session._retrieve( + "memory", 2, source_first=(2, False), scope_mode="project", + ) events = [ item for item in session.trace.emit.call_args_list if item.args[0] == "retrieval.sources.ranked" @@ -245,6 +276,7 @@ def test_unrelated_sources_are_left_out_of_a_comparison(self): evidence = session._retrieve( "memory capacity", 4, source_first=(8, True), source_report=details, + scope_mode="project", ) self.assertEqual( {item.path for item in evidence}, {Path("a.pdf"), Path("b.pdf")} @@ -256,6 +288,7 @@ def test_unrelated_sources_are_left_out_of_a_comparison(self): evidence = session._retrieve( "Review the four articles on memory capacity", 4, source_first=(8, True), + scope_mode="project", ) self.assertEqual(len({item.path for item in evidence}), 4) # Asking about every source keeps them all. @@ -263,6 +296,7 @@ def test_unrelated_sources_are_left_out_of_a_comparison(self): evidence = session._retrieve( "memory capacity", 8, source_first=(8, False), source_limits=budget, + scope_mode="project", ) self.assertEqual(len({item.path for item in evidence}), 4) @@ -326,7 +360,9 @@ def test_reject_invalid_source_first_requests(self): for argument in ((0, False), (2, "no"), (True, False)): with self.subTest(argument=argument): with self.assertRaises(ValueError): - session._retrieve("memory", source_first=argument) + session._retrieve( + "memory", source_first=argument, scope_mode="project", + ) if __name__ == "__main__": diff --git a/tests/kilin/test_rag__source_first_budget.py b/tests/kilin/test_rag__source_first_budget.py index 0d04b582..25e97f51 100644 --- a/tests/kilin/test_rag__source_first_budget.py +++ b/tests/kilin/test_rag__source_first_budget.py @@ -39,6 +39,7 @@ def test_initial_retrieval_ignores_low_project_retrieval_count(self): "memory", retrieval_count=1, source_first=(3, True), source_limits=budget, source_report=details, + scope_mode="project", ) self.assertEqual(len({item.path for item in evidence}), 3) self.assertLessEqual(len(evidence), 5) @@ -75,6 +76,8 @@ def test_comparison_scope_reaches_answer_retrieval_without_a_router(self): mocks.retrieve.call_args.kwargs["scope"], [Path("new.pdf"), Path("old.pdf")], ) + self.assertEqual(mocks.retrieve.call_args.kwargs["scope_mode"], + "restricted") self.assertEqual(session.chat_session.reply.call_count, 1) def test_oversized_chunks_do_not_bypass_expansion_budget(self): @@ -93,6 +96,7 @@ def test_oversized_chunks_do_not_bypass_expansion_budget(self): session.indexes.lexical = build_lexical_index(session.chunks) evidence = session._retrieve( "memory", source_first=(3, True), source_limits=budget, + scope_mode="project", ) self.assertLessEqual(len(evidence), 3) self.assertLessEqual(evidence_tokens(evidence), 100) @@ -156,6 +160,8 @@ def test_all_sources_overrides_inferred_single_document_focus(self): self.assertEqual( mocks.retrieve.call_args.kwargs["scope"], () ) + self.assertEqual(mocks.retrieve.call_args.kwargs["scope_mode"], + "project") self.assertIn("1 of 2 requested sources", answer) def test_bounded_answer_does_not_claim_exhaustive_coverage(self): From eb9107cde227184b790ae59655b0eaf154755e9d Mon Sep 17 00:00:00 2001 From: Giovanni Volpe Date: Wed, 2 Dec 2026 20:52:57 +0100 Subject: [PATCH 07/37] Hugging Face cache compatibility --- kilin/huggingface.py | 34 +++++++++------------- tests/kilin/test_huggingface.py | 50 ++++++++++++++++++++------------- 2 files changed, 44 insertions(+), 40 deletions(-) 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/tests/kilin/test_huggingface.py b/tests/kilin/test_huggingface.py index 6a4914e9..94c3fe9d 100644 --- a/tests/kilin/test_huggingface.py +++ b/tests/kilin/test_huggingface.py @@ -17,6 +17,11 @@ import unittest from unittest.mock import Mock, patch +from huggingface_hub.errors import ( + IncompleteSnapshotError, + LocalEntryNotFoundError, +) + from kilin import huggingface @@ -148,35 +153,40 @@ def test_rejects_snapshot_without_config(self) -> None: with self.assertRaisesRegex(FileNotFoundError, "config.json"): huggingface.cached_model_snapshot("group/model") - def test_legacy_incomplete_snapshot_uses_same_validation(self) -> None: - """Apply config validation to older Hub partial-snapshot errors.""" - - class PartialSnapshotError(Exception): - """Represent the legacy Hub exception with a snapshot path.""" - - def __init__(self, snapshot_path): - """Store the snapshot path reported by the Hub.""" - self.snapshot_path = snapshot_path + def test_incomplete_snapshot_uses_same_validation(self) -> None: + """Apply config validation to the path reported by the Hub.""" with TemporaryDirectory() as directory: snapshot = Path(directory) - error = PartialSnapshotError(str(snapshot)) - with ( - patch.object( - huggingface, - "_IncompleteSnapshotError", - PartialSnapshotError, - ), - patch.object( - huggingface, "snapshot_download", side_effect=error - ), - ): + error = IncompleteSnapshotError( + "Incomplete snapshot", snapshot_path=str(snapshot) + ) + with patch.object( + huggingface, "snapshot_download", side_effect=error + ) as lookup: with self.assertRaisesRegex(FileNotFoundError, "config.json"): huggingface.cached_model_snapshot("group/model") (snapshot / "config.json").write_text("{}", encoding="utf-8") self.assertEqual( huggingface.cached_model_snapshot("group/model"), snapshot ) + self.assertEqual(lookup.call_count, 2) + lookup.assert_called_with( + repo_id="group/model", + revision=None, + local_files_only=True, + ) + + def test_missing_cached_snapshot_error_propagates(self) -> None: + """Preserve the Hub error when no local snapshot is available.""" + + error = LocalEntryNotFoundError("No cached snapshot") + with patch.object( + huggingface, "snapshot_download", side_effect=error + ): + with self.assertRaises(LocalEntryNotFoundError) as raised: + huggingface.cached_model_snapshot("group/model") + self.assertIs(raised.exception, error) def test_rejects_invalid_identifier_before_lookup(self) -> None: """Avoid Hub calls for invalid model identifiers.""" From e425970ea8d3d3364e2eb29d3b3073eab0a1dd07 Mon Sep 17 00:00:00 2001 From: Giovanni Volpe Date: Wed, 2 Dec 2026 21:03:05 +0100 Subject: [PATCH 08/37] Update generation.py --- kilin/system_testing/generation.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/kilin/system_testing/generation.py b/kilin/system_testing/generation.py index f27d1586..3975faac 100644 --- a/kilin/system_testing/generation.py +++ b/kilin/system_testing/generation.py @@ -347,9 +347,8 @@ def generate_reference(root: Path, experiment: str, project_type: str, recording = staging / f"{experiment}_recording" relocated = staging / f"{experiment}_relocated_recording" # Run the complete script once. Preserve failed or unfinished attempts. - legacy = (workspaces / recording.name, workspaces / relocated.name) protected = (original, replay, recording, relocated, - receipt_path(original), *legacy) + 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(): From 0ac6e768bc8bf44c97cf15fe95d1bd445db563ac Mon Sep 17 00:00:00 2001 From: Giovanni Volpe Date: Wed, 2 Dec 2026 21:03:11 +0100 Subject: [PATCH 09/37] Update test_generation.py --- tests/kilin/system_testing/test_generation.py | 74 ++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/tests/kilin/system_testing/test_generation.py b/tests/kilin/system_testing/test_generation.py index 67dd4184..f7a5dd99 100644 --- a/tests/kilin/system_testing/test_generation.py +++ b/tests/kilin/system_testing/test_generation.py @@ -64,7 +64,9 @@ def record(recorder): def test_existing_paths_refuse_before_engine_construction(self): for path in (self.original, self.workspaces / "recipe_replay", - self.staged, receipt_path(self.original)): + self.staged, + self.staged.with_name("recipe_relocated_recording"), + receipt_path(self.original)): with self.subTest(path=path): path.parent.mkdir(parents=True, exist_ok=True) path.write_text("protected", encoding="utf-8") @@ -76,6 +78,76 @@ def test_existing_paths_refuse_before_engine_construction(self): "protected") path.unlink() + def test_existing_directories_refuse_before_engine_construction(self): + for path in (self.original, self.workspaces / "recipe_replay", + self.staged, + self.staged.with_name("recipe_relocated_recording"), + receipt_path(self.original)): + with self.subTest(path=path): + path.mkdir(parents=True) + sentinel = path / "protected.txt" + sentinel.write_bytes(b"protected") + with patch("kilin.system_testing.generation.Recorder") as r: + with self.assertRaises(FileExistsError): + self.generate(Mock()) + r.assert_not_called() + self.assertEqual(list(path.iterdir()), [sentinel]) + self.assertEqual(sentinel.read_bytes(), b"protected") + sentinel.unlink() + path.rmdir() + + def test_dangling_links_refuse_before_engine_construction(self): + target = self.root / "missing" + for path in (self.original, self.workspaces / "recipe_replay", + self.staged, + self.staged.with_name("recipe_relocated_recording"), + receipt_path(self.original)): + with self.subTest(path=path): + path.parent.mkdir(parents=True, exist_ok=True) + try: + path.symlink_to(target) + except (OSError, NotImplementedError) as error: + self.skipTest(f"Cannot create a symbolic link: {error}") + with patch("kilin.system_testing.generation.Recorder") as r: + with self.assertRaises(FileExistsError): + self.generate(Mock()) + r.assert_not_called() + self.assertTrue(path.is_symlink()) + self.assertEqual(path.readlink(), target) + self.assertFalse(target.exists()) + path.unlink() + + def test_historical_staging_does_not_block_publication(self): + # Older locations are outside the current publication lifecycle. + historical = [self.workspaces / name for name in ( + "recipe_recording", "recipe_relocated_recording", + )] + for path in historical: + path.mkdir() + (path / "protected.txt").write_bytes(path.name.encode()) + + fixture = test_replay.TestReplay() + fixture.setUp() + self.addCleanup(fixture.doCleanups) + fixture.engine.close() + + def record(recorder): + recorder.open() + recorder.ask("Q01", "What is saved?") + + with fixture._model(): + recorder, report = self.generate(record) + self.assertTrue(report.valid, report.issues) + self.assertEqual(recorder.directory, self.original) + self.assertFalse(self.staged.exists()) + self.assertEqual(inspect_receipt(self.original, report)["status"], + "unchanged") + for path in historical: + self.assertTrue(path.is_dir()) + sentinel = path / "protected.txt" + self.assertEqual(list(path.iterdir()), [sentinel]) + self.assertEqual(sentinel.read_bytes(), path.name.encode()) + def test_failure_closes_engine_and_preserves_staging(self): def fail(recorder): self.staged.mkdir() From 469c94a62676ddb83e976fc4191d690bf041b936 Mon Sep 17 00:00:00 2001 From: Giovanni Volpe Date: Wed, 2 Dec 2026 21:15:28 +0100 Subject: [PATCH 10/37] Relocation of the test-only trace traversal helper --- kilin/system_testing/analysis.py | 39 ---------------- tests/kilin/system_testing/_trace_support.py | 46 +++++++++++++++++++ .../system_testing/test_analysis__traces.py | 5 +- tests/kilin/test__format_versions.py | 5 +- 4 files changed, 52 insertions(+), 43 deletions(-) create mode 100644 tests/kilin/system_testing/_trace_support.py diff --git a/kilin/system_testing/analysis.py b/kilin/system_testing/analysis.py index 5761249c..f089c0a1 100644 --- a/kilin/system_testing/analysis.py +++ b/kilin/system_testing/analysis.py @@ -40,7 +40,6 @@ from pathlib import Path from tempfile import NamedTemporaryFile -from kilin._trace_project import TRACE_FORMAT_VERSION from .comparison import COMPARISON_FORMAT_VERSION from .traces import read_recording @@ -1805,44 +1804,6 @@ def _stages(op): for x in _list(op.get("stages"))]) -def _trace_events(data): - """Yield raw stored nodes for explicit hierarchy inspection only. - - Parameters - ---------- - data: dict - Decoded local hierarchical trace JSON. Compact references remain - raw; semantic analysis uses ``read_recording`` instead. - - """ - def visit(value): - """Traverse stored trace containers without interpreting event text. - - Parameters - ---------- - value: object - Nested trace node or container to traverse. - - """ - if isinstance(value, dict): - event = value.get("event") - if isinstance(event, dict) and type(event.get("sequence")) is int: - yield value - for key, child in value.items(): - if key not in ("event", "completion", "details", - "exact_content", "timing"): - yield from visit(child) - elif isinstance(value, list): - for child in value: - yield from visit(child) - - if (type(data.get("trace_format_version")) is not int - or data["trace_format_version"] != TRACE_FORMAT_VERSION - or data.get("sequence_scope") != "project"): - raise ValueError("Unsupported local trace format.") - yield from visit(data.get("sessions")) - - def _trace_index(root, relative, cache): """Index verified events from the requested and shared project traces. diff --git a/tests/kilin/system_testing/_trace_support.py b/tests/kilin/system_testing/_trace_support.py new file mode 100644 index 00000000..179d9064 --- /dev/null +++ b/tests/kilin/system_testing/_trace_support.py @@ -0,0 +1,46 @@ +"""Inspect raw trace fixtures independently of the canonical reader. + +This traversal leaves stored references and event numbers unchanged so tests +can inspect or deliberately corrupt stored nodes without decoding them. + +""" + +from kilin._trace_project import TRACE_FORMAT_VERSION + + +def _trace_events(data): + """Yield raw stored nodes for explicit hierarchy inspection only. + + Parameters + ---------- + data: dict + Decoded local hierarchical trace JSON. Compact references remain + raw; semantic analysis uses ``read_recording`` instead. + + """ + def visit(value): + """Traverse stored trace containers without interpreting event text. + + Parameters + ---------- + value: object + Nested trace node or container to traverse. + + """ + if isinstance(value, dict): + event = value.get("event") + if isinstance(event, dict) and type(event.get("sequence")) is int: + yield value + for key, child in value.items(): + if key not in ("event", "completion", "details", + "exact_content", "timing"): + yield from visit(child) + elif isinstance(value, list): + for child in value: + yield from visit(child) + + if (type(data.get("trace_format_version")) is not int + or data["trace_format_version"] != TRACE_FORMAT_VERSION + or data.get("sequence_scope") != "project"): + raise ValueError("Unsupported local trace format.") + yield from visit(data.get("sessions")) diff --git a/tests/kilin/system_testing/test_analysis__traces.py b/tests/kilin/system_testing/test_analysis__traces.py index af1b47c6..cdbf0ec1 100644 --- a/tests/kilin/system_testing/test_analysis__traces.py +++ b/tests/kilin/system_testing/test_analysis__traces.py @@ -17,6 +17,7 @@ from kilin.system_testing.traces import read_recording from tests.kilin import test_trace_logging__configuration as configurations from tests.kilin import test_trace_logging__sources as sources +from tests.kilin.system_testing._trace_support import _trace_events from tests.kilin.system_testing.test__batch_diagnostics import report @@ -74,7 +75,7 @@ def test_configuration_and_source_details_are_verified_and_read_only(self): "metadata": event.metadata, "details": event.details, "exact_content": event.exact_content, }) - raw = list(analysis._trace_events(self.fixture._raw())) + raw = list(_trace_events(self.fixture._raw())) self.assertTrue(any(sources.REFERENCE in node.get("details", {}) for node in raw)) self.assertEqual(before, {p: p.read_bytes() @@ -173,7 +174,7 @@ def test_sequence_ambiguity_in_another_conversation_is_not_hidden(self): other, _, _ = self._model("conversation_b.json") path = self.root / other payload = json.loads(path.read_text("utf-8")) - node = next(node for node in analysis._trace_events(payload) + node = next(node for node in _trace_events(payload) if node["event"]["event_type"] == "llm.call.input") node["event"]["sequence"] = row["input_sequence"] path.write_text(json.dumps(payload), encoding="utf-8") diff --git a/tests/kilin/test__format_versions.py b/tests/kilin/test__format_versions.py index e7d7bff0..a0088aa2 100644 --- a/tests/kilin/test__format_versions.py +++ b/tests/kilin/test__format_versions.py @@ -23,6 +23,7 @@ from kilin.system_testing import replay_management, traces from kilin.workspace import SOURCE_MANIFEST_VERSION, _read_records from kilin.workspace import _write_records +from tests.kilin.system_testing._trace_support import _trace_events _INVALID_VERSIONS = (True, False, 1.0, "1", None, 0, 2) @@ -120,8 +121,8 @@ def test_system_testing_rejects_incompatible_trace_before_decoding(self): ["trace.format"]) self.assertEqual(recording.events, []) with self.assertRaisesRegex(ValueError, "trace format"): - list(analysis._trace_events(payload)) - self.assertEqual(list(analysis._trace_events({ + list(_trace_events(payload)) + self.assertEqual(list(_trace_events({ "trace_format_version": TRACE_FORMAT_VERSION, "sequence_scope": "project", "sessions": {}, })), []) From 17a596eb0e587ec728678e2ce74d32d5291ecd63 Mon Sep 17 00:00:00 2001 From: Giovanni Volpe Date: Wed, 2 Dec 2026 21:25:12 +0100 Subject: [PATCH 11/37] Removal of redundant private parameters --- kilin/chat.py | 14 +---- kilin/tools/find_fact/tool.py | 5 -- kilin/trace_logging.py | 7 +-- tests/kilin/test_chat__unit.py | 69 ++++++++++++++++++++- tests/kilin/tools/find_fact/test_tool.py | 36 ++++++++++- tests/kilin/tools/test__partial_recovery.py | 2 +- 6 files changed, 104 insertions(+), 29 deletions(-) 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/tools/find_fact/tool.py b/kilin/tools/find_fact/tool.py index 865be807..8bc212f4 100644 --- a/kilin/tools/find_fact/tool.py +++ b/kilin/tools/find_fact/tool.py @@ -472,7 +472,6 @@ def run( request.question, quick_by_file, texts, - settings, context, whole=False, failures=failures, @@ -518,7 +517,6 @@ def run( request.question, in_budget, texts, - settings, context, whole=True, failures=failures, @@ -627,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, @@ -646,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/trace_logging.py b/kilin/trace_logging.py index 3011728e..eb6a65f5 100644 --- a/kilin/trace_logging.py +++ b/kilin/trace_logging.py @@ -484,7 +484,6 @@ def __init__( self.output_path = _trace_path( config.output_path, Path(default_directory), - self.trace_id, ) directory = project_trace_directory( self.output_path, project_directory @@ -1883,7 +1882,6 @@ def _project_trace_logger( def _trace_path( configured: str | Path | None, default_directory: Path, - trace_id: str, ) -> Path: """Resolve a configured trace path or choose a timestamped JSON filename. @@ -1894,9 +1892,6 @@ def _trace_path( default_directory: pathlib.Path Fallback output directory when the configuration does not name an exact JSON file. - trace_id: str - Logger correlation identifier. This parameter is retained by the helper - signature but is not used to construct the path. Returns ------- @@ -1908,7 +1903,7 @@ def _trace_path( ----- Directory-based names use a UTC timestamp with microseconds. The helper neither checks for collisions nor reserves the file. An exact .json path - may already exist. The trace_id argument does not participate in naming. + may already exist. """ diff --git a/tests/kilin/test_chat__unit.py b/tests/kilin/test_chat__unit.py index 13544ca4..f1b5a9ac 100644 --- a/tests/kilin/test_chat__unit.py +++ b/tests/kilin/test_chat__unit.py @@ -782,7 +782,7 @@ def test_mlx_dispatch_without_callback_or_trace(self) -> None: generate.assert_called_once_with([4, 5, 6], 29) def test_mlx_dispatch_includes_trace_turn(self) -> None: - """Forward trace correlation and callbacks to MLX generation.""" + """Keep trace correlation in orchestration, not MLX dispatch.""" trace = Mock() trace.enabled = True @@ -806,10 +806,22 @@ def test_mlx_dispatch_includes_trace_turn(self) -> None: "Answer", ) generate.assert_called_once_with( - [4, 5, 6], 29, trace_turn_id="turn-1", - token_callback=callback, + [4, 5, 6], 29, token_callback=callback, ) callback.assert_not_called() + self.assertEqual(trace.emit.call_count, 2) + first, second = trace.emit.call_args_list + self.assertEqual(first.args[0], TRACE_EVENT_LLM_CALL_INPUT) + self.assertEqual(second.args[0], TRACE_EVENT_LLM_CALL_OUTPUT) + self.assertEqual(first.kwargs["turn_id"], "turn-1") + self.assertEqual(second.kwargs["turn_id"], "turn-1") + self.assertEqual(trace.span.call_count, 1) + self.assertEqual(trace.span.call_args.args[0], "llm.call") + self.assertEqual(trace.span.call_args.kwargs["turn_id"], "turn-1") + call_id = first.kwargs["data"]["call_id"] + self.assertEqual(second.kwargs["data"]["call_id"], call_id) + self.assertEqual(trace.span.call_args.kwargs["data"]["call_id"], + call_id) def test_closed_session_rejects_reply(self) -> None: """Fail before accessing tokenizer when resources are released.""" @@ -1218,6 +1230,57 @@ def test_enabled_trace_emits_input_and_output_metadata(self) -> None: ) trace.artifact.assert_not_called() + def test_traced_mlx_generation_keeps_call_and_turn_ids(self) -> None: + """Correlate actual streaming generation with or without a callback.""" + + for streaming in (True, False): + with self.subTest(streaming=streaming): + trace = self._trace(content=True, tokens=True) + session = _session(trace=trace, max_new_tokens=8) + session.backend = "mlx" + session._tokenizer.apply_chat_template.side_effect = [ + "rendered prompt", [4, 5, 6], + ] + mlx_lm = Mock() + mlx_lm.stream_generate.return_value = iter([ + SimpleNamespace(text="A", finish_reason=None), + SimpleNamespace(text="", finish_reason=None), + SimpleNamespace(text="B", finish_reason="stop"), + ]) + sampling = Mock() + modules = {"mlx_lm": mlx_lm, + "mlx_lm.sample_utils": sampling} + callback = Mock() if streaming else None + with patch.object( + chat, "import_module", side_effect=modules.get + ): + answer = session.reply( + "Hello", trace_turn_id="turn-1", + token_callback=callback, + ) + self.assertEqual(answer, "AB") + mlx_lm.stream_generate.assert_called_once() + self.assertEqual(session.input_token_total, 3) + self.assertEqual(session.output_token_total, 3) + self.assertEqual(trace.emit.call_count, 2) + first, second = trace.emit.call_args_list + self.assertEqual(first.args[0], TRACE_EVENT_LLM_CALL_INPUT) + self.assertEqual(second.args[0], TRACE_EVENT_LLM_CALL_OUTPUT) + for event in (first, second, trace.span.call_args): + self.assertEqual(event.kwargs["turn_id"], "turn-1") + self.assertEqual(event.kwargs["data"]["call_id"], + "llm-call-1") + data = second.kwargs["data"] + self.assertEqual(data["output_token_count"], 3) + self.assertEqual(data["output_token_count_source"], + "generated_tokens") + self.assertEqual(data["finish_reason"], "stop") + self.assertEqual(data["answer_artifact"]["value"], "AB") + session._tokenizer.encode.assert_not_called() + if callback is not None: + self.assertEqual([c.args for c in callback.call_args_list], + [("A",), ("B",)]) + def test_content_and_token_flags_create_artifacts(self) -> None: """Record structured input, rendered prompt, and answer content.""" diff --git a/tests/kilin/tools/find_fact/test_tool.py b/tests/kilin/tools/find_fact/test_tool.py index cefd0a43..505afcb2 100644 --- a/tests/kilin/tools/find_fact/test_tool.py +++ b/tests/kilin/tools/find_fact/test_tool.py @@ -20,7 +20,10 @@ from kilin.tools import ToolRequest from kilin.tools import find_fact as tool from kilin.tools.find_fact.tool import _cited -from kilin.tools._shared.planning import PLAN_CHOICE_QUICK +from kilin.tools._shared.planning import ( + PLAN_CHOICE_CONTINUE, + PLAN_CHOICE_QUICK, +) from tests.kilin.tools._contract_support import ( assert_packaged_defaults, @@ -182,6 +185,37 @@ def test_quick_answer_ranks_when_no_passage_has_the_terms(self) -> None: self.assertEqual(plan.quick_label, "Quick answer") self.assertIn("No passage mentions", plan.quick_note) + def test_notes_follow_selected_reading_plan(self) -> None: + """Read exact-term passages or all passages through real notes.""" + + passages = [ + chunk("a", "Implemented in MATLAB with C++.", path="a.md"), + chunk("b", "Additional implementation details.", path="a.md"), + ] + question = "How is MATLAB used?" + for choice, expected_count in ((PLAN_CHOICE_QUICK, 1), + (PLAN_CHOICE_CONTINUE, 2)): + with self.subTest(choice=choice): + context = _quick_context(passages, ["MATLAB"]) + context.confirm.return_value = choice + context.ask_model = Mock(return_value="- MATLAB and C++ [1]") + result = tool.run( + tool.FactSettings(confirmation="always"), + ToolRequest(question, question), context, + ) + context.ask_model.assert_called_once() + prompt = context.ask_model.call_args.args[1] + self.assertIn("[1] Implemented in MATLAB", prompt) + self.assertEqual("[2] Additional implementation" in prompt, + choice == PLAN_CHOICE_CONTINUE) + self.assertEqual(result.summary["passages_read"], + expected_count) + self.assertEqual(result.summary["choice"], choice) + context.write.assert_called_once() + self.assertIn("- MATLAB and C++ [1]", + context.write.call_args.args[1]) + self.assertEqual([e["citation"] for e in result.evidence], [1]) + def test_quick_plan_estimates_optional_extra_page(self) -> None: """Show a worst-case passage count before the user confirms.""" diff --git a/tests/kilin/tools/test__partial_recovery.py b/tests/kilin/tools/test__partial_recovery.py index 2f63d150..c8ef9fbc 100644 --- a/tests/kilin/tools/test__partial_recovery.py +++ b/tests/kilin/tools/test__partial_recovery.py @@ -278,7 +278,7 @@ def test_fact_reading_omits_failed_document_not_negative_notes(self): material = fact_tool._notes( "Task", [(Path("failed.md"), [[0]]), (Path("valid.md"), [[1]]), (Path("empty.md"), [[2]])], - ["one", "two", "three"], fact_tool.FactSettings(), context, + ["one", "two", "three"], context, whole=True, failures=failures, ) self.assertEqual(material, From 6d4b37e6ffe23a334098b27998074439d356695f Mon Sep 17 00:00:00 2001 From: Giovanni Volpe Date: Wed, 2 Dec 2026 21:32:53 +0100 Subject: [PATCH 12/37] Removal of obsolete project discovery --- docs/gui_protocol.md | 10 +- kilin/gui/engine.py | 105 ++---------- kilin/gui/window.py | 31 +--- tests/kilin/gui/test__protocol.py | 37 +++- .../kilin/gui/test_engine__saved_projects.py | 159 ++++++++++++++---- tests/kilin/test_project_type__catalog.py | 13 +- 6 files changed, 184 insertions(+), 171 deletions(-) diff --git a/docs/gui_protocol.md b/docs/gui_protocol.md index 7cb6f8fa..9cb6744a 100644 --- a/docs/gui_protocol.md +++ b/docs/gui_protocol.md @@ -92,8 +92,8 @@ 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 @@ -119,15 +119,13 @@ 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 `""` | @@ -622,8 +620,6 @@ 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. -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 diff --git a/kilin/gui/engine.py b/kilin/gui/engine.py index 14bb050a..e55efc08 100644 --- a/kilin/gui/engine.py +++ b/kilin/gui/engine.py @@ -345,8 +345,6 @@ class ChatEngine: **Startup and model configuration.** - startup() - Suggest the most recently used valid sandbox project. readiness() Report runtime packages and the preferred models' availability. use_installed_models() @@ -365,9 +363,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) @@ -784,16 +780,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. @@ -1105,7 +1091,8 @@ def list_saved_projects(self, workspace: str) -> None: Parameters ---------- workspace: str - Workspace containing saved projects. + Explicit workspace path, or an empty string to discover saved + projects in the engine workspace root. """ @@ -1127,88 +1114,28 @@ def list_saved_projects(self, workspace: str) -> None: }) self._send("projects", projects=projects) - def find_saved_project(self, type_id: str, workspace: str) -> None: - """Refresh Resume for the selected type and workspace folder. - - A chosen workspace is checked directly. Without one, the most recent - valid sandbox project of the selected type is suggested. - - Parameters - ---------- - type_id: str - Requested registered project-type identifier. Discovery helpers - also accept None to search all registered types. - workspace: str - Explicit workspace path string. An empty string requests discovery - or default allocation under the engine workspace root. - - """ - - project = self._find_saved_project(type_id or None, workspace) - self._send( - "saved_project", - project=str(project[0]) if project is not None else None, - type_id=type_id, - workspace=workspace, - ) - - def _find_saved_project( - self, type_id: str | None, workspace: str - ) -> tuple[Path, str] | None: - """Find a current project, ignoring deleted or incomplete folders. - - Parameters - ---------- - type_id: str | None - Requested registered project-type identifier. Discovery helpers - also accept None to search all registered types. - workspace: str - Explicit workspace path string. An empty string requests discovery - or default allocation under the engine workspace root. - - Returns - ------- - tuple[pathlib.Path, str] | None - Pair (workspace_path, project_type_id) for the most recently used - valid candidate, or None. - - Notes - ----- - Discovery inspects profile/source existence and profile/conversation - modification times without loading a model. Invalid candidate profiles - are skipped; the whole project schema is checked later when opening. - - """ - - available = set(project_type_ids()) - projects = [ - item for item in self._saved_projects(workspace, type_id) - if item[2] in available - ] - if not projects: - return None - _, folder, saved_type_id = max( - projects, key=lambda item: (item[0], str(item[1])) - ) - return folder, saved_type_id - def _saved_projects( - self, workspace: str, type_id: str | None = None + self, workspace: str ) -> list[tuple[float, Path, str]]: """Recognize saved projects independently of type availability. Parameters ---------- workspace: str - Workspace containing saved projects. - type_id: str | None, optional - Project-type identifier to filter by. Defaults to ``None``. + Explicit workspace path, or an empty string to discover saved + projects in the engine workspace root. Returns ------- list[tuple[float, Path, str]] Recognized saved projects ordered from newest to oldest. + Notes + ----- + Discovery checks profiles, source layouts and modification times of + profiles and conversations without loading a model. Invalid candidate + profiles are skipped; the full project schema is checked when opening. + """ if workspace.strip(): @@ -1235,8 +1162,6 @@ def _saved_projects( source_text = parser.get("project", "source") if not _ID_PATTERN.fullmatch(saved_type_id): continue - if type_id is not None and saved_type_id != type_id: - continue if source_text != PROJECT_SOURCES_DIRECTORY: continue validate_project_sources(folder) @@ -6044,18 +5969,12 @@ def read_input() -> None: engine.apply_model_settings(command["settings"]) elif action == "download_model": engine.download(command["model_id"]) - elif action == "startup": - engine.startup() elif action == "readiness": engine.readiness() elif action == "install_required_models": engine.install_required_models() elif action == "use_installed_models": engine.use_installed_models() - elif action == "saved_project": - engine.find_saved_project( - command["type_id"], command["workspace"] - ) elif action == "saved_projects": engine.list_saved_projects(command["workspace"]) elif action == "resume": diff --git a/kilin/gui/window.py b/kilin/gui/window.py index f956c574..a8bbc140 100644 --- a/kilin/gui/window.py +++ b/kilin/gui/window.py @@ -233,10 +233,8 @@ class ChatBridge(QObject): 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) @@ -1466,36 +1464,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. """ diff --git a/tests/kilin/gui/test__protocol.py b/tests/kilin/gui/test__protocol.py index 84e4baec..f296b434 100644 --- a/tests/kilin/gui/test__protocol.py +++ b/tests/kilin/gui/test__protocol.py @@ -70,7 +70,6 @@ def test_core_command_dispatch(self) -> None: """Map existing command names to the corresponding engine calls.""" samples = [ - ({"action": "startup"}, "startup"), ({"action": "readiness"}, "readiness"), ( {"action": "install_required_models"}, @@ -112,14 +111,6 @@ def test_core_command_dispatch(self) -> None: {"action": "saved_projects", "workspace": "/parent"}, "list_saved_projects", ), - ( - { - "action": "saved_project", - "type_id": "code", - "workspace": "/parent", - }, - "find_saved_project", - ), ( { "action": "settings", @@ -224,6 +215,23 @@ def test_core_command_dispatch(self) -> None: getattr(worker, method).call_count, expected ) + def test_retired_discovery_commands_are_rejected(self) -> None: + """Reject retired commands and keep the catalog available.""" + + worker, events = self._run([ + json.dumps({"action": "startup"}), + json.dumps({"action": "saved_project", "type_id": "code", + "workspace": "/parent"}), + json.dumps({"action": "saved_projects", "workspace": ""}), + ]) + self.assertEqual(events, [ + {"event": "error", "message": "Unknown command."}, + {"event": "error", "message": "Unknown command."}, + ]) + worker.list_saved_projects.assert_called_once_with("") + worker.startup.assert_not_called() + worker.find_saved_project.assert_not_called() + def test_semantic_source_command_forwards_exact_request(self): """Preserve the command envelope through the JSON-line dispatcher.""" request = {"operation": "apply", "request_id": 3, @@ -940,6 +948,17 @@ def test_answer_and_resume_command_payloads(self) -> None: }, ]) + def test_saved_project_catalog_is_the_only_discovery_slot(self): + """Forward the canonical catalog command, not a type-filtered one.""" + + self.bridge.listSavedProjects("") + self.bridge.listSavedProjects("/parent/project") + self.assertEqual(self.commands, [ + {"action": "saved_projects", "workspace": ""}, + {"action": "saved_projects", "workspace": "/parent/project"}, + ]) + self.assertFalse(hasattr(self.bridge, "findSavedProject")) + def test_invalid_open_sources_emit_local_error(self) -> None: """Reject non-list sources before they enter the child process.""" diff --git a/tests/kilin/gui/test_engine__saved_projects.py b/tests/kilin/gui/test_engine__saved_projects.py index 4d111ebe..bde659b6 100644 --- a/tests/kilin/gui/test_engine__saved_projects.py +++ b/tests/kilin/gui/test_engine__saved_projects.py @@ -1,4 +1,4 @@ -"""Verify GUI startup and discovery of saved KíLín workspaces. +"""Verify GUI catalog discovery of saved KíLín workspaces. No model backend or Qt application is needed for these checks. @@ -14,15 +14,16 @@ from pathlib import Path from tempfile import TemporaryDirectory import unittest +from unittest.mock import patch from kilin.gui.engine import ChatEngine class TestEngineSavedProjects(unittest.TestCase): - """Test startup and explicit saved-workspace selection.""" + """Test catalog discovery and explicit saved-workspace selection.""" - def test_startup_finds_recent_saved_project(self) -> None: - """Only saved workspaces are candidates for automatic reopening.""" + def test_catalog_excludes_unrelated_folders(self) -> None: + """List only saved workspaces, with the newest one first.""" with TemporaryDirectory() as temporary: sandbox = Path(temporary).resolve() @@ -41,14 +42,21 @@ def test_startup_finds_recent_saved_project(self) -> None: events: list[dict[str, object]] = [] engine = ChatEngine(sandbox, events.append) - engine.startup() + with patch("kilin.gui.engine.RAGSession") as session: + engine.list_saved_projects("") + session.assert_not_called() - self.assertEqual(events[-1]["event"], "startup") - self.assertEqual(events[-1]["project"], str(sandbox / "newer")) - self.assertEqual(events[-1]["type_id"], "literature") + self.assertEqual(events[-1]["event"], "projects") + self.assertEqual([ + (row["project"], row["type_id"]) + for row in events[-1]["projects"] + ], [ + (str(sandbox / "newer"), "literature"), + (str(sandbox / "older"), "code"), + ]) - def test_saved_project_tracks_type_and_deleted_folder(self) -> None: - """Resume follows the selected type and a removed folder disappears.""" + def test_catalog_includes_types_and_excludes_removed_folders(self): + """List all types and stop advertising a removed folder.""" with TemporaryDirectory() as temporary: root = Path(temporary).resolve() @@ -66,19 +74,24 @@ def test_saved_project_tracks_type_and_deleted_folder(self) -> None: events: list[dict[str, object]] = [] engine = ChatEngine(sandbox, events.append) - engine.find_saved_project("code", "") - self.assertEqual( - events[-1]["project"], str(sandbox / "code-project") - ) - engine.find_saved_project("literature", "") - self.assertEqual(events[-1]["project"], str(sandbox / "papers")) + engine.list_saved_projects("") + self.assertEqual({ + (row["project"], row["type_id"]) + for row in events[-1]["projects"] + }, { + (str(sandbox / "code-project"), "code"), + (str(sandbox / "papers"), "literature"), + }) (sandbox / "papers").rename(root / "removed-papers") - engine.find_saved_project("literature", "") - self.assertIsNone(events[-1]["project"]) + engine.list_saved_projects("") + self.assertEqual([ + (row["project"], row["type_id"]) + for row in events[-1]["projects"] + ], [(str(sandbox / "code-project"), "code")]) def test_saved_projects_are_newest_first(self) -> None: - """The project-list refresh shares startup's discovery rules.""" + """Order saved projects by their most recent activity.""" with TemporaryDirectory() as temporary: sandbox = Path(temporary).resolve() @@ -118,14 +131,27 @@ def test_saved_project_checks_custom_workspace(self) -> None: events: list[dict[str, object]] = [] engine = ChatEngine(root / "sandbox", events.append) - engine.find_saved_project("literature", str(custom)) - self.assertEqual(events[-1]["project"], str(custom)) - engine.find_saved_project("code", str(custom)) - self.assertIsNone(events[-1]["project"]) + # An explicit workspace must not fall back to the sandbox. + default = root / "sandbox" / "default" + (default / "sources").mkdir(parents=True) + (default / "profile.ini").write_text( + "[project]\ntype_id = code\nsource = sources\n", + encoding="utf-8", + ) + engine.list_saved_projects(str(custom)) + self.assertEqual([ + (row["project"], row["type_id"]) + for row in events[-1]["projects"] + ], [(str(custom), "literature")]) custom.rename(root / "moved-project") - engine.find_saved_project("literature", str(custom)) - self.assertIsNone(events[-1]["project"]) + engine.list_saved_projects(str(custom)) + self.assertEqual(events[-1], {"event": "projects", "projects": []}) + engine.list_saved_projects("") + self.assertEqual( + [row["project"] for row in events[-1]["projects"]], + [str(default)], + ) def test_retired_source_layouts_are_not_advertised_as_projects(self): with TemporaryDirectory() as temporary: @@ -164,17 +190,88 @@ def test_retired_source_layouts_are_not_advertised_as_projects(self): engine = ChatEngine(sandbox, events.append) engine.list_saved_projects("") self.assertEqual(events[-1], {"event": "projects", "projects": []}) - engine.find_saved_project("code", "") - self.assertIsNone(events[-1]["project"]) + for folder in sandbox.iterdir(): + with self.subTest(explicit_workspace=folder.name): + engine.list_saved_projects(str(folder)) + self.assertEqual(events[-1], { + "event": "projects", "projects": [], + }) self.assertEqual(before, {p: p.read_bytes() for p in root.rglob("*") if p.is_file()}) - def test_empty_sandbox_starts_without_workspace(self) -> None: - """An empty sandbox does not show an empty workspace sidebar.""" + def test_empty_sandbox_has_empty_catalog(self) -> None: + """An empty sandbox does not advertise a workspace.""" with TemporaryDirectory() as temporary: events: list[dict[str, object]] = [] - ChatEngine(Path(temporary).resolve(), events.append).startup() + engine = ChatEngine(Path(temporary).resolve(), events.append) + engine.list_saved_projects("") + + self.assertEqual(events[-1], {"event": "projects", "projects": []}) - self.assertEqual(events[-1], {"event": "startup", "project": None}) + def test_catalog_excludes_incomplete_and_linked_projects(self): + """Keep incomplete projects and links out of the catalog.""" + + with TemporaryDirectory() as temporary: + sandbox = Path(temporary).resolve() + profile = "[project]\ntype_id = code\nsource = sources\n" + for name in ("valid", "incomplete", "linked-profile"): + folder = sandbox / name + (folder / "sources").mkdir(parents=True) + if name != "linked-profile": + (folder / "profile.ini").write_text( + profile, encoding="utf-8", + ) + marker = sandbox / "incomplete" / ".kilin-creating" + marker.write_text("pid=42\ncreated=1\n", encoding="utf-8") + try: + (sandbox / "linked-folder").symlink_to( + sandbox / "valid", target_is_directory=True, + ) + (sandbox / "linked-profile" / "profile.ini").symlink_to( + sandbox / "valid" / "profile.ini", + ) + except (OSError, NotImplementedError): + self.skipTest("Symbolic links are unavailable") + events = [] + engine = ChatEngine(sandbox, events.append) + engine.list_saved_projects("") + self.assertEqual( + [row["name"] for row in events[-1]["projects"]], ["valid"], + ) + for name in ("incomplete", "linked-folder", "linked-profile"): + with self.subTest(explicit_workspace=name): + engine.list_saved_projects(str(sandbox / name)) + self.assertEqual(events[-1], { + "event": "projects", "projects": [], + }) + self.assertEqual( + marker.read_text(encoding="utf-8"), "pid=42\ncreated=1\n", + ) + + def test_catalog_accounts_for_recent_conversation_activity(self): + """Recent conversation files can make an older project newer.""" + + with TemporaryDirectory() as temporary: + sandbox = Path(temporary).resolve() + for index, name in enumerate(("older", "newer")): + folder = sandbox / name + (folder / "sources").mkdir(parents=True) + profile = folder / "profile.ini" + profile.write_text( + "[project]\ntype_id = code\nsource = sources\n", + encoding="utf-8", + ) + os.utime(profile, (100 + index, 100 + index)) + trace = sandbox / "older/logs/traces/conversation_example.json" + trace.parent.mkdir(parents=True) + trace.write_text("{}", encoding="utf-8") + os.utime(trace, (200, 200)) + events = [] + engine = ChatEngine(sandbox, events.append) + engine.list_saved_projects("") + self.assertEqual([ + (row["name"], row["updated_at"]) + for row in events[-1]["projects"] + ], [("older", 200), ("newer", 101)]) diff --git a/tests/kilin/test_project_type__catalog.py b/tests/kilin/test_project_type__catalog.py index 764d30a0..2a48652f 100644 --- a/tests/kilin/test_project_type__catalog.py +++ b/tests/kilin/test_project_type__catalog.py @@ -235,10 +235,15 @@ def test_discovery_and_preflight_preserve_unavailable_workspaces(self): self.assertIn("not installed", rows[1]["unavailable_reason"]) self.assertTrue(rows[2]["available"]) self.assertIsNone(rows[2]["unavailable_reason"]) - engine.startup() - self.assertEqual(events[-1]["type_id"], "good") - engine.find_saved_project("removed", "") - self.assertIsNone(events[-1]["project"]) + for name in ("good", "removed", "needs-tools"): + with self.subTest(explicit_workspace=name): + engine.list_saved_projects(str(self.workspaces / name)) + self.assertEqual(events[-1], { + "event": "projects", + "projects": [ + row for row in rows if row["type_id"] == name + ], + }) previous = object() engine.session = previous for name in ("removed", "needs-tools"): From 3481495498bb014e3c5261d3e82e49262a6b07e8 Mon Sep 17 00:00:00 2001 From: Giovanni Volpe Date: Wed, 2 Dec 2026 21:34:43 +0100 Subject: [PATCH 13/37] Update test_generation.py --- tests/kilin/system_testing/test_generation.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/kilin/system_testing/test_generation.py b/tests/kilin/system_testing/test_generation.py index f7a5dd99..244a0bc8 100644 --- a/tests/kilin/system_testing/test_generation.py +++ b/tests/kilin/system_testing/test_generation.py @@ -113,7 +113,11 @@ def test_dangling_links_refuse_before_engine_construction(self): self.generate(Mock()) r.assert_not_called() self.assertTrue(path.is_symlink()) - self.assertEqual(path.readlink(), target) + # Windows may return an extended-length target path. + link_target = path.readlink() + self.assertTrue(link_target.is_absolute()) + self.assertEqual(link_target.name, target.name) + self.assertTrue(link_target.parent.samefile(target.parent)) self.assertFalse(target.exists()) path.unlink() From dc1a627b168e835bd29ca99712219682de8c7182 Mon Sep 17 00:00:00 2001 From: Giovanni Volpe Date: Wed, 2 Dec 2026 21:46:53 +0100 Subject: [PATCH 14/37] GUI assets and graphical resources --- kilin/gui/web/index.html | 2 +- kilin/gui/web/styles.css | 20 -------------------- tests/kilin/gui/test__visual_identity.py | 9 ++++++++- 3 files changed, 9 insertions(+), 22 deletions(-) diff --git a/kilin/gui/web/index.html b/kilin/gui/web/index.html index 1a51aa59..9fa7a8eb 100644 --- a/kilin/gui/web/index.html +++ b/kilin/gui/web/index.html @@ -15,7 +15,7 @@