diff --git a/docs/PLUGIN_API.md b/docs/PLUGIN_API.md index 036d695a..b61eb0ba 100644 --- a/docs/PLUGIN_API.md +++ b/docs/PLUGIN_API.md @@ -402,12 +402,10 @@ Explicit directory validation remains strict. Python paths. `parse_tool(where, data)` resolves a configured ID and validates settings; `run_tool(use, request, context)` dispatches a validated `ToolUse`. -The older `TOOL_CHOICES`, `TOOL_REGISTRY`, and `PROJECT_TYPE_IDS` exports still -resolve on access for existing callers. The legacy registry dictionary remains -mutable for compatibility; do not mutate it from plugins. Use the explicit -read-only accessor for new code. Likewise, importing a legacy tool-specific -convenience export loads the corresponding executable package. Do not rely on -those exports or private modules when implementing independent plugins. +Use the explicit catalog accessors rather than mutable registry dictionaries +or import-time snapshots. Tool-specific settings, constants and helpers belong +to their owning tool packages, not the shared authoring facade. Independent +plugins should use the documented shared interfaces, not private modules. ## User storage, discovery and validation @@ -678,12 +676,12 @@ API or schema generation, and SHA-256 digest. Tool identity hashes sorted relative file names and contents, excluding bytecode and `__pycache__`; JSON identity hashes the captured definition bytes. These portable identities do not include absolute user paths. The trace's -`turn.settings.snapshot` includes `project_type_plugin`, and the selected -`tool.run` span includes `plugin`. Persisted turn parameters include the +`turn.settings.snapshot` includes `project_type_plugin` when available, +and the selected `tool.run` span always includes `plugin` (null if the +identity is unavailable). Persisted turn parameters include the selected identities as `project_type_plugin` and `tool_plugin` when known. These describe the package bytes captured during registration, not a proof -of the behavior of arbitrary code or external dependencies. Historical -records need not contain them. +of the behavior of arbitrary code or external dependencies. ## System-testing provenance and replay @@ -700,10 +698,13 @@ selected implementation, not just the set of available plugins. fresh execution. Validation, comparison, and retained-replay receipt reading use the recorded identities without importing installed plugin packages or requiring the original project type to exist. The saved profile still must -satisfy its syntax, value, filesystem and recorded-state contracts. Missing -older identities are explicitly `unknown`; a malformed supplied identity is -a recording diagnostic. A difference in identity alone is not a change to -persistent workspace settings and does not invalidate a recording. +satisfy its syntax, value, filesystem and recorded-state contracts. Every +opening configuration requires the complete plugin snapshot, and every tool +execution requires its plugin field. Missing required metadata or malformed +identities block recording validation. Null identities and unavailable +turn identities are `unknown`; no historical identity is inferred. A difference +in identity alone is not a change to persistent workspace settings and does +not invalidate a recording. Fresh replay preflight resolves the current project type and all tools required by its definition, the historical configuration, or historical @@ -717,7 +718,7 @@ plugin locations are included in this receipt field. Comparison JSON contains per-workspace and per-aligned-operation `plugin_provenance` observations. Markdown and notebook reports distinguish -known changes, unknown older identities and one-sided observations (for +known changes, unknown identities and one-sided observations (for example, a different routed tool); only known changes become plugin identity differences in `ReplayResult.differences`. Batch reports flag these as environment changes for review, not answer-quality verdicts. A missing diff --git a/docs/configuration.md b/docs/configuration.md index d0bcb184..d19843d9 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -252,9 +252,14 @@ model and parameters in `[source_card_generation]`. These are core settings, not a way to change active answering or routing sessions. The GUI maintains effort levels and search-depth steps in the same `profile.ini` through `kilin.gui.model_settings`; it no longer owns router persistence. These -settings are not a separate active `effort_levels.json` database. The GUI -still supports controlled migration of recognized older files on first use; -moving or deleting files outside that migration is not authorized. +settings are initialized from effective application preferences only when +missing, including when a valid core-created project is first opened in the +GUI. Saved settings take precedence and invalid present values are rejected. +Each effort-level record in GUI settings must have exactly `name` and `model`; +search-depth steps are separate. Historical `effort_levels.json` and +`model_choices.json` sidecars are neither read nor deleted. To retain their +old choices, back up the files and transfer the desired values explicitly +through Settings. ### Source-card indexing policy @@ -603,12 +608,11 @@ location for conversations, workspaces or preferences. Documents may be synchronized by iCloud, OneDrive or another external service; users needing strictly local project storage should choose a non-synchronized path. -If the previous installed-app `workspaces/` data directory contains project -profiles, GUI setup offers to reuse that folder. Choosing it records a -folder preference without moving or rewriting any project files. Otherwise -KíLín keeps the proposed Documents folder. An existing confirmed choice or -environment override is never silently replaced by legacy detection. See -[GUI architecture](gui_architecture.md) and [GUI README](../kilin/gui/README.md). +Choose any existing projects folder explicitly using Browse. KíLín does +not search former default locations. Selecting a folder records a preference +without moving or rewriting its projects, which must satisfy the current +project format. See [GUI architecture](gui_architecture.md) and +[GUI README](../kilin/gui/README.md). ### Saved project settings take precedence diff --git a/docs/gui_architecture.md b/docs/gui_architecture.md index f5a61ad5..82750502 100644 --- a/docs/gui_architecture.md +++ b/docs/gui_architecture.md @@ -152,6 +152,9 @@ user state. A development checkout and an installed distribution can have different suggested workspace parents. The exact path overrides and preferences rules are owned by [Configuration](configuration.md#gui-defaults-and-writable-preferences). +The GUI uses the saved or explicitly selected projects folder without +scanning former default locations. Selecting a folder does not move or +migrate its projects. `gui/_activation.py` implements the desktop passkey check. It is called from `gui/app.py`'s `main` after the Qt application exists and before @@ -161,8 +164,9 @@ settings or workspace files. An existing project's profile remains authoritative. `gui/model_settings.py` stores GUI-specific effort/search/router choices there rather than replacing -them from current global defaults. Its controlled legacy import is not a -general project migration. For changes to the saved source tree or resources, +them from current global defaults. Only missing settings are initialized; +obsolete sidecars are not read or removed. For changes to the saved source +tree or resources, use the [workspace APIs](project_workspaces.md#creation-opening-and-explicit-updates). ## Operation lifecycle and answer display diff --git a/docs/gui_protocol.md b/docs/gui_protocol.md index db8f6ffb..0e3ddc14 100644 --- a/docs/gui_protocol.md +++ b/docs/gui_protocol.md @@ -570,7 +570,7 @@ can accompany an event. | --- | --- | | Setup | `readiness` (`backend`, `ready`, `environment_ready`, `unavailable_reason` (empty unless the selected backend is unsupported), `required_models`, `cached_models`, `missing_models`, `replacements`, `can_use_installed`, `install_command`, `install_commands` (backend-to-command map), `projects_folder`, `folder_confirmed`, `terms`, `terms_version`, `terms_accepted`, `copyright` (the Settings copyright line, built from the package authors)); `installed_models_used` (`replacements`, updated model settings); `backend_preference_saved`, `backend_preference_failed` (Qt events: saved `backend` or failed `backend` and `message`); `terms_acceptance_saved` (`version`); `terms_acceptance_failed` (`version`, `reason`, `message`, and `current_version` for outdated terms) | | Installation | `installation_started` (`total`, `backend`, `models`: the missing models in download order); `installation_progress` (`index`, `total`, `model_id`, progress details); `installation_model_complete` (`model_id`, elapsed times); `installation_complete` (`elapsed_seconds`) | -| Projects folder (Qt) | `projects_folder` (`folder`: effective folder, `standard`: default without a saved choice, `saved`: saved choice or empty string, `missing`: whether a saved folder is unavailable, `legacy`: previous installed-app root with candidate profiles, or empty); `projects_folder_cancelled` (native Browse dialog dismissed); `projects_folder_failed` (`message`: unable to save or old folder no longer exists) | +| Projects folder (Qt) | `projects_folder` (`folder`: effective folder, `standard`: default without a saved choice, `saved`: saved choice or empty string, `missing`: whether a saved folder is unavailable); `projects_folder_cancelled` (native Browse dialog dismissed); `projects_folder_failed` (`message`: unable to save the chosen folder) | | Settings/models | `settings` (`profile`, project types, model choices, backend, search depth, `selection_reason_codes`, `thinking_switches`: cached model IDs mapped to `True` when toggling `enable_thinking` changes one sample rendered prompt, `False` when unchanged; omitted when unknown (not verified model reasoning)); `models_applied` (updated levels, models and profile, plus `thinking_switches`); `indexing_applied` (`profile` after the index was rebuilt); `source_cards_applied` (validated settings and card counts), `source_cards_regenerated` (card counts); `answer_settings_saved` (confirmed `temperature`, `thinking`, `max_new_tokens`, plus `request_id` and `project` for correlated saves); `answer_settings_failed` (`request_id`, `project`, `message`, `verified`, plus reconciled settings when verified); `model_download_started`, `model_download_progress`, `model_downloaded` (model ID and download status); `project_behavior` (validated project editor, defaults, revision, and correlated saved or error status); `settings_info` (validated core/tool descriptive catalog), `settings_info_failed` (metadata diagnostic only); `tool_settings` (`tools`, each with `name`, `summary`, `intents`, `settings`, `type_settings`, `per_intent`; after a save also `tool` and `saved` or `error`) | | Plugins | `plugins` (`request_id`, `operation`, optional `error`, `validation`, `change`, `canceled`, `inventory` with installed, runtime and pending records) | | Versions | `versions` (`request_id`, `project`, `creation_provenance`, `inventory` or `error`) | diff --git a/docs/model_management.md b/docs/model_management.md index acae562d..2c5553de 100644 --- a/docs/model_management.md +++ b/docs/model_management.md @@ -229,8 +229,8 @@ may require controlled evaluation. `RAGSession` normally holds an answering chat session, embedding session and possibly a separate router session. The core loads the selected router ID from the project's `[router]` section (separately for MLX and PyTorch). -When absent, it checks the legacy `effort_levels.json` router choice, then -uses the packaged `DEFAULT_ROUTER_MODEL_*` for the selected backend. An +When absent, it uses the packaged `DEFAULT_ROUTER_MODEL_*` for the selected +backend, unless an initial choice is supplied to `read_router_model()`. An explicit `RAGSession(router_model=...)` overrides that choice for the session without changing `profile.ini`. Core callers do not need the GUI to read or update router configuration: use diff --git a/docs/module_map.md b/docs/module_map.md index 7f7f8bbe..c2a4d00a 100644 --- a/docs/module_map.md +++ b/docs/module_map.md @@ -257,8 +257,10 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | [`kilin/system_testing/_comparison_report.py`](../kilin/system_testing/_comparison_report.py) | Render and publish sibling JSON and Markdown comparison reports. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | | [`kilin/system_testing/generation.py`](../kilin/system_testing/generation.py) | Record, validate and publish scripted reference experiments. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | | [`kilin/system_testing/batch.py`](../kilin/system_testing/batch.py) | Run managed experiments and execute independent report notebooks. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | -| [`kilin/system_testing/analysis.py`](../kilin/system_testing/analysis.py) | Render saved comparison snapshots, diagnostics and visual reports. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | -| [`kilin/_trace_configuration.py`](../kilin/_trace_configuration.py) | Encode complete effective configurations and construct and verify compact references. | [Trace architecture](trace_architecture.md) | [Configuration trace tests](../tests/kilin/test_trace_logging__configuration.py) | +| [`kilin/system_testing/analysis.py`](../kilin/system_testing/analysis.py) | Render saved comparison snapshots and diagnostics with verified local trace references. | [System testing](system_testing.md) | [System tests](../tests/kilin/system_testing/) | +| [`kilin/_trace_configuration.py`](../kilin/_trace_configuration.py) | Encode complete effective configurations and verify exact or path-preserving content references. | [Trace architecture](trace_architecture.md) | [Configuration trace tests](../tests/kilin/test_trace_logging__configuration.py) | +| [`kilin/_trace_snapshots.py`](../kilin/_trace_snapshots.py) | Encode canonical snapshots and verify direct source-group and shared semantic-manifest references. | [Trace architecture](trace_architecture.md) | [Source trace tests](../tests/kilin/test_trace_logging__sources.py), [semantic trace tests](../tests/kilin/test_trace_logging__semantics.py) | +| [`kilin/_trace_json.py`](../kilin/_trace_json.py) | Format long integer arrays compactly without changing diagnostic JSON values. | [Trace architecture](trace_architecture.md) | [Trace JSON tests](../tests/kilin/test__trace_json.py) | | [`kilin/_trace_project.py`](../kilin/_trace_project.py) | Coordinate project-wide event numbering and shared trace publication. | [Trace architecture](trace_architecture.md) | [Project trace tests](../tests/kilin/test__trace_project.py) | | [`kilin/trace_logging.py`](../kilin/trace_logging.py) | Record structured execution events and resumable conversation state. | [Trace recording](trace_recording.md) | [Core tests](../tests/kilin/) | | [`kilin/workspace.py`](../kilin/workspace.py) | Copy selected local sources into a managed multi-source workspace. | [Project workspaces](project_workspaces.md) | [Core tests](../tests/kilin/) | @@ -286,11 +288,11 @@ unit test. Consult source docstrings and nearby tests for exact contracts. | System testing | 22 | | Tool extension contracts | 29 | | Tool packages | 2 | -| Trace architecture | 2 | +| Trace architecture | 4 | | Trace recording | 1 | | Versioning | 1 | -**Total production Python modules: 242.** +**Total production Python modules: 244.** ## Non-Python resources and UI assets diff --git a/docs/package_defaults.md b/docs/package_defaults.md index fc074852..e89a1b44 100644 --- a/docs/package_defaults.md +++ b/docs/package_defaults.md @@ -32,8 +32,8 @@ identifiers supplied by a project or caller. The identifiers use the form All eight values must be nonempty strings. Core router selection reads the project's saved ``[router]`` setting first; the packaged router default -is used only when the project has no saved or legacy router. Explicit -``RAGSession(router_model=...)`` overrides the saved selection for that +is used when the project has no saved router or supplied initial choice. +Explicit ``RAGSession(router_model=...)`` overrides the saved selection for that session. The GUI may save a user-preference router for a newly created project. These defaults do not automatically download a model. diff --git a/docs/project_workspaces.md b/docs/project_workspaces.md index ec19f355..d43de582 100644 --- a/docs/project_workspaces.md +++ b/docs/project_workspaces.md @@ -147,11 +147,11 @@ numbered-sibling allocation. The final name is reserved exclusively; import kilin first = kilin.prepare_sources_workspace( - ["/path/to/source"], kilin.PROJECT_TYPE_IDS[0], + ["/path/to/source"], kilin.project_type_ids()[0], workspace_root="/path/to/projects", ) second = kilin.prepare_sources_workspace( - ["/path/to/source"], kilin.PROJECT_TYPE_IDS[0], + ["/path/to/source"], kilin.project_type_ids()[0], workspace_root="/path/to/projects", ) assert first.root != second.root @@ -162,12 +162,12 @@ Both contain no placeholder sources or dummy indexes: ```python project = kilin.prepare_sources_workspace( - [], kilin.PROJECT_TYPE_IDS[0], + [], kilin.project_type_ids()[0], workspace_root="/path/to/projects", ) # For an explicitly chosen name, use the third positional argument instead: # project = kilin.prepare_sources_workspace( -# [], kilin.PROJECT_TYPE_IDS[0], "/path/to/new_workspace" +# [], kilin.project_type_ids()[0], "/path/to/new_workspace" # ) project = kilin.add_project_sources( project.root, ["/path/to/notes.txt"] diff --git a/docs/source_manifest.md b/docs/source_manifest.md index 02338e88..b1ad187a 100644 --- a/docs/source_manifest.md +++ b/docs/source_manifest.md @@ -419,12 +419,13 @@ the returned snapshot is still committed and must not be retried as if it had rolled back. Lifecycle refresh emits `source_organization.reconciled` with the same state and identity fields when it changes the manifest. Initial creation is part of the existing creation operation, not a separate mutation. -System-test validation of older recordings without the semantic command -protocol is limited to default-only additive lifecycle histories with a -complete revision/digest chain. Recordings with the current protocol can -include explicit edits, declarations and automatic-discovery outcomes, but -must contain the complete chronological history. Direct core mutations -without corresponding replayable engine commands are not replayable. See +System-test validation requires the current semantic command protocol and +the complete chronological history, including for default-only assignments. +Recorded creation and lifecycle observations, accepted revision/digest, and +question-start identities must form a consistent history ending at the saved +semantic state. Explicit edits, declarations and automatic-discovery outcomes +are supported. Direct core mutations without corresponding replayable engine +commands are not replayable. See [semantic source organization in system testing](system_testing.md#semantic-source-organization). The [headless engine protocol](gui_protocol.md#semantic-source-commands) diff --git a/docs/system_testing.md b/docs/system_testing.md index 03759339..d16d4612 100644 --- a/docs/system_testing.md +++ b/docs/system_testing.md @@ -40,11 +40,9 @@ semantics. GUI appearance and view-only actions are not replay inputs. Older recordings or direct core-only sessions that do not contain the required command and -creation metadata are not complete reference experiments. No migration of traces or -inference of missing commands is attempted. A narrow exception for earlier -recordings is an already-recorded internal reopening that can be identified -as a successful sibling-directory rename from independent path and lifecycle -metadata. Such identification is reported as a validation warning. +creation metadata are not complete reference experiments. No migration of +traces or inference of missing commands is attempted. Regenerate references +that lack the current recording protocol. ## Inspecting a recording @@ -94,12 +92,11 @@ supported detached-writer case is an active conversation archived by a recorded successful deletion. A project rename is validated using matching request/completion markers around a successful close and internal reopening, corroborated by recorded directory paths and the restored conversation. -For older traces without either marker, only independently corroborated -sibling moves are accepted. Incomplete markers, same-directory internal -reopens, mismatched active conversations, failed renames, and persistent -configuration mutations remain blocking issues. Recorded absolute paths -are compared lexically in their original platform's path syntax, never -opened on the inspection machine. +Missing or incomplete rename markers, same-directory internal reopens, +mismatched active conversations, failed renames, and persistent configuration +mutations are blocking issues. Recorded absolute paths are compared +lexically in their original platform's path syntax, never opened on the +inspection machine. The source checks use recorded copy outcomes and historical indexing manifests. The final managed source inventory and content hashes must agree @@ -180,19 +177,21 @@ automatically replaces or deletes a workspace. ### Semantic source organization -Recordings with the headless semantic command protocol retain creation and -lifecycle observations, correlated inspect/preview/apply/initialize/reconcile -commands, explicit edits, accepted revision/digest and question-start -semantic identity. Validation verifies their chronological chain, validates +Complete recordings require creation and lifecycle observations, accepted +revision/digest and question-start semantic identity. Executed semantic +commands (inspect, preview, apply, initialize and reconcile) require +correlated requests and outcomes, including explicit edits. Validation +verifies their chronological chain, validates explicit edits with the core's pure transformations, checks recorded automatic relationship deltas against the proposal and requires the final saved [semantic source organization](source_manifest.md) to match its recorded state. Physical indexing manifests remain separate. A direct core mutation without a correlated replayable command, missing or externally replaced metadata, incomplete preview linkage, stale question identity, or unrecorded mutation -blocks validation. Older recordings without the command protocol retain the -previous default-only additive validation rules; nontrivial older semantic -histories cannot be reconstructed safely. +blocks validation. Recordings without the current semantic command protocol +are rejected, even for empty workspaces or unchanged default roles. A saved +manifest or core reconciliation history alone cannot establish a replayable +semantic history. Replay executes semantic commands through the ordinary headless engine. It rebinds preview requests to the actual replay revision and digest and uses the @@ -326,15 +325,15 @@ while the changed provenance remains observable. `comparison.complete` means the full valid command histories align, not that their outputs match or that every metric is available. -`comparison.data` is a JSON-compatible snapshot with `format_version`, -`original`, `replayed`, `alignment`, `summary`, `operations`, `final_state`, -`embedding_evaluation`, `files`, and `report_issues`. The workspace sections -include validation issues, recorded model/environment provenance, command -counts, final catalogs, and token coverage. Alignment includes the mapped -conversation IDs and turn UUIDs and any unmatched command suffixes. Each -operation retains intermediate stage observations, source manifests and -settings differences. Each matched committed question is counted once, -including when its turn is inherited in multiple branches. +`comparison.data` is a JSON-compatible snapshot with `format_version` +(currently 2), `original`, `replayed`, `alignment`, `summary`, `operations`, +`final_state`, `embedding_evaluation`, `files`, and `report_issues`. The +workspace sections include validation issues, recorded model/environment +provenance, command counts, final catalogs, and token coverage. Alignment +includes the mapped conversation IDs and turn UUIDs and any unmatched +command suffixes. Each operation retains intermediate stage observations, +source manifests and settings differences. Each matched committed question +is counted once, including when its turn is inherited in multiple branches. ### Metrics and coverage @@ -392,14 +391,18 @@ unverified or changed inputs. Unlocalized changes and unavailable metrics remain explicit. Later changed question numbers are possible downstream observations, not evidence of causality. Unmatched operations, timing and final file inventories are covered by the existing independent diagnostics. -Older reports remain readable without this optional field. +Supported-format reports remain readable without this optional field. ### Context, tool coverage and independent inspection Each side's independent event inventory and saved-question observations are -retained even without alignment. Unverified saved text from an invalid -recording is labeled as such; unmatched questions do not contribute to paired -metrics. Aligned history selections resolve branch-local turn numbers through +retained even without alignment. Comparison report format 2 requires +independent event counts reconciling with each side's event total. These +counts are not inferred from aligned stages or outside-command observations. +Regenerate unsupported or incomplete reports using the current comparison +implementation; older reports are not migrated in place. Unverified saved +text from an invalid recording is labeled as such; unmatched questions do +not contribute to paired metrics. Aligned history selections resolve branch-local turn numbers through validated saved prefixes and the reconstructed identity map. Memory inventories compare mapped turn/role identities and origins without regard to inventory order; retrieval order, content fingerprints, priorities and scores remain @@ -407,13 +410,13 @@ separate. Missing observations and unknown identities are unavailable, not empty selections. In addition to raw rendered prompts, structured-input comparisons normalize -only corroborated memory headers in the final user message. Legacy headers -must agree with the selected-memory record's label, role, UUID and origins; -current headers must agree with its label, role and deterministic turn label. -Both formats are mapped to the same recorded identity for diagnostics. -Ordinary question text and memory content remain unchanged. Ambiguous or -uncorroborated headers are unavailable. Neither model input nor trace data -are changed; raw rendered-prompt comparison still uses the actual input. +only corroborated memory headers in the final user message. Headers must +agree with the selected-memory record's label, role and deterministic +prompt-local turn label. The label is mapped to the recorded identity for +diagnostics. Ordinary question text and memory content remain unchanged. +Obsolete, ambiguous or uncorroborated headers are unavailable. Neither model +input nor trace data are changed; raw rendered-prompt comparison still uses +the actual input. Functional tool-summary comparisons separate known elapsed-time and plan-time fields. Explicit incomplete or invalid outcomes remain visible even when @@ -633,8 +636,15 @@ retain their format and interpretation. - `kilin.system_testing.analysis` presents comparison snapshots as escaped HTML and Markdown. It includes answer and operation explorers, batch summaries, event inventories, and optional exact local trace text - verified against its recorded hashes. Rendering does not load models or - revalidate a saved report. + verified against its recorded hashes. Optional local event details and + exact-text lookups use the same trace decoder and reference verification + as validation and replay. Each workspace is decoded once per render, + across conversations. Local decoding issues remain visible, including + issues in incomplete standalone recordings. Event details with decoding + failures are labelled unverified; they may contain independently expanded + fields and are not claimed to be either raw or fully verified data. + Original trace files are unchanged. Rendering does not load models, + revalidate a saved report, or change its metrics. ### Release verification diff --git a/docs/trace_architecture.md b/docs/trace_architecture.md index 8d52845e..8cbf6114 100644 --- a/docs/trace_architecture.md +++ b/docs/trace_architecture.md @@ -20,6 +20,22 @@ project-trace writer replaces only its own hierarchical session projection; other writers' sessions are preserved. No workspace-wide session lock is introduced. A project trace does not own a conversation checkpoint. +### Readable JSON layout + +Project and conversation traces share the private `_trace_json` formatter. +Arrays containing at least sixteen integers use sixteen values per line; +other values retain the standard two-space JSON layout. This reduces token +array whitespace without removing events, changing values or adding a storage +format. Booleans, floating-point values and mixed arrays retain their original +layout. The standard JSON encoder still owns escaping and validation. + +This layout changes only whitespace outside JSON strings. Event identities, +token identifiers, Unicode text, scalar types, mapping and array order, and +conversation resume state are unchanged. Canonical event fingerprints and +reference receipts therefore remain identical. The writers retain their +existing atomic replacement, ownership and failure policies. Existing files +are not proactively reformatted; ordinary future writes use the shared layout. + ## Event identity Each newly recorded event in a managed project receives a positive project-wide @@ -111,9 +127,9 @@ Explicit [semantic source-manifest mutations](source_manifest.md) emit and committed revision/digest and the state under `source_organization`. Lifecycle reconciliation emits `source_organization.reconciled` with the same identity and state fields on a changed manifest. Neither is the physical -`source_manifest` field of index events. Replay validates complete semantic -command and lifecycle chains when the engine recording protocol is present; -older histories retain default-only additive validation. See +`source_manifest` field of index events. Replay requires complete semantic +command and lifecycle chains, including creation and opening observations, +regardless of whether any roles or relationships were edited. See [semantic replay](system_testing.md#semantic-source-organization). The headless engine records explicit source-organization commands in the @@ -168,30 +184,41 @@ A failed diagnostic snapshot is recorded explicitly. Subsequent saved profile, model, tool, behavior and card settings changes are traced in the project. Each activation retains its own configuration event and global sequence -number. The first complete configuration, and any configuration that differs -from the most recent complete observation, retains all seven settings groups. -An unchanged configuration instead records a direct reference: +number. The first complete configuration retains all settings groups and +additional fields. When all settings other than the observed project path +match the most recent complete observation, store one direct reference: ```json { - "configuration_reference": { + "configuration_content_reference": { "sequence": 124, "sha256": "<64 lowercase hexadecimal characters>" - } + }, + "project": "/exact/recorded/workspace/path" } ``` -The digest is SHA-256 of the referenced complete payload encoded as UTF-8 -JSON with sorted object keys, compact separators, unescaped Unicode, and no -nonfinite numbers. Array ordering and scalar representations are significant. -The historical workspace path in `behavior.project` is included, so a -workspace rename creates a new full observation. Restoring an earlier -configuration after a different full observation also creates a new full -observation; references never form chains or skip a newer full snapshot. - -The configuration event alone selects its payload and reserves its sequence -under the project publication lease. It uses the project trace already read -for that publication and requires no separate persistent index or cache. +This is the only compact configuration representation, whether the workspace +path is unchanged or has moved. The digest is SHA-256 of the referenced +payload with only `behavior.project` removed, encoded as UTF-8 JSON with +sorted object keys, compact separators, unescaped Unicode, and no nonfinite +numbers. Array ordering and scalar representations are significant. +Inspection restores `behavior.project` from `project`, without normalizing +its spelling or consulting the current filesystem. An explicit null value is +preserved; an absent project field is ineligible for compaction. All other +behavior values and unknown fields remain significant. A reference is written +only when it is smaller than the full payload. The reserved reference field +cannot be mixed with full settings groups. + +Changed settings require a new full observation. Restoring settings after a +different full observation also writes a new full observation. References +point directly to the latest full snapshot, never to another reference or a +superseded snapshot. + +Compact configuration and source observations select their payloads and +reserve their sequences under the project publication lease. Each uses the +project trace already read for that publication and requires no separate +persistent index or cache. The lock order is project publication lease, then short sequence lease; ordinary events release the sequence lease before taking the publication lease. A failed publication releases the project lease before applying the @@ -201,10 +228,93 @@ multi-file atomic transaction. Do not mix older and newer concurrent writers. System-testing inspection resolves references in global sequence order, checks their digest and latest-full-snapshot identity, and supplies independent copies of the complete payload to validation, timeline reconstruction, replay -and comparison. Invalid references are blocking recording issues. Original -files are not rewritten. Existing full-snapshot recordings remain readable -without migration; older readers need the updated inspector to interpret new -compact recordings. The trace hierarchy and counter format remain unchanged. +and comparison. Publication receipts fingerprint these decoded payloads, so a +full configuration and its compact representation have the same trace-prefix +digest. Invalid references are blocking recording issues. Original +files are not rewritten. Full observations remain part of the current +format. The earlier prerelease `configuration_reference` payload is no longer +supported; regenerate recordings that use it. The trace hierarchy and +counter format remain unchanged. + +### Repeated source snapshots + +The same direct-reference mechanism reduces repeated project-level source +payloads without eliding operations. For completed non-turn observations the +following fixed groups can be replaced by `source_snapshot_reference`: + +| Event | Snapshot fields | +| --- | --- | +| `source.scan.completed` | `selected_files`, `entries` | +| `index.check.completed` | `source_manifest`, `expected_metadata`, `saved_metadata` | +| `gui.source_organization.observed` | `source_organization`, `selected`, `pending`, `pending_roles`, `retained_versions` | + +The top-level `source_snapshot_reference` field is reserved for this format. +The reference has the same `sequence` and `sha256` structure as the +configuration reference. Its digest covers exactly the omitted fields as a +canonical JSON object. Other details (including historical paths, completeness, +index reuse decisions, semantic revision/digest, and lifecycle outcomes) stay +inline. A changed group is stored in full. A complete scan is required, and +failed or incomplete full observations do not become reference targets. The +next complete observation is retained in full after such an observation. +These group references are local to one project trace and one event type, +and are used only when the canonical compact representation is smaller. +Empty-index and conversation events keep their existing formats. Semantic +commits and completed applications additionally support the independent +manifest representation below. Historical event values are not compacted +retroactively. + +The inspector expands source snapshots before validation, replay, comparison, +and publication-receipt fingerprinting, checking that the target is the latest +preceding full observation of the same event type. Missing, ambiguous, forward, +chained, superseded, mixed full/reference, and digest-mismatched references are +blocking recording issues. A compact observation is never reconstructed from +the current source files or manifest. Older full-snapshot recordings remain +readable; direct JSON readers must understand the new reference field. + +Local analysis details also use the recording reader, so references have the +same meaning in event inventories and exact-text lookup as in replay and +comparison. Decoder issues are shown alongside partial local diagnostics. +Invalid event payloads remain available as explicitly labelled unverified +details, which may contain independently decoded fields. They are not claimed +to be raw or fully verified, and current workspace state never repairs them. +Raw hierarchy inspection remains available independently; exact model text +must additionally match its saved comparison-report digest. + +### Shared semantic manifests + +`source_organization.committed`, `source_organization.reconciled`, and +`gui.source_organization.apply.completed` can replace an unchanged top-level +`source_organization` field with `semantic_snapshot_reference`. This reference +contains a sequence number and SHA-256 digest of the canonical JSON object +`{"source_organization": }`. The manifest's own +recorded revision and file digest remain separate and unchanged. + +The target is the latest preceding raw full semantic observation among these +three event types and `gui.source_organization.observed`, in the same project +trace. Mapping order is immaterial; scalar types, array order, and all manifest +fields remain significant. References are direct, digest-checked and emitted +only when smaller. An incomplete or failed full semantic observation requires +fresh full evidence. A reference never becomes a target, including an opening +observation using `source_snapshot_reference`. + +Opening observations continue to use their existing complete source-group +compaction; they supply full manifest targets but do not emit semantic-only +references. This preserves savings across repeated GUI openings and avoids +making a later source-group reference depend indirectly on a semantic +reference. A first opening after a semantic change may therefore retain one +additional full manifest as its source-group target. + +All event identities, sequencing, span and command correlations, requests, +revision chains, errors, refresh results and nested inspection data stay +intact. In particular, an inspection result is not assumed to equal the +earlier committed state. Shared manifests resolve before source groups, so +validation, replay, comparison, analysis and receipt hashes see the original +full details. Malformed, ambiguous, wrong-scope, mixed, forward, chained, +superseded and digest-invalid references are blocking recording issues. +Resolution never consults the workspace's current semantic manifest. + +### Session closure + `gui.project.closed` records the selected conversation when the GUI releases the project. A standalone RAG session similarly records its initialization and closure in its project sink; switching its conversation does not change that diff --git a/docs/trace_recording.md b/docs/trace_recording.md index bb91032b..d40451b7 100644 --- a/docs/trace_recording.md +++ b/docs/trace_recording.md @@ -85,11 +85,13 @@ are recorded without mode-based filtering. A grouped `conversation_*.json` file holds diagnostic events and resumable conversation state. The latter stores the question, answer, evidence, history, and checkpoint identity needed to reopen the conversation. Disabling tracing -does not remove this state. A legacy `"mode": "forensic"` string is still -emitted in the `trace.started` event for readers of older files; this is a -fixed historical metadata value, not a configuration option. Existing JSON -files with a `"standard"` or `"forensic"` marker remain readable. Previously -stored events are preserved when reopening, without retroactive filtering. +does not remove this state. `trace.started` records the scope, output path, +embedding-vector policy and runtime environment; it has no tracing-mode +field. Exact diagnostic artifacts are stored inline, not loaded from separate +files. Previously stored events are not retroactively filtered or rewritten. +The current prerelease trace format does not support the earlier compact +configuration or file-artifact representations. Regenerate system-test +recordings using the current writer and reader. Managed workspaces use shared event numbering across conversation and project traces. Initialization, source operations, indexing and configuration are @@ -270,7 +272,9 @@ include the same `rename_id`, `source_directory`, `destination_directory`, and `conversation_id`. Paths are historical provenance. Neither a span nor an owned trace file is held across the filesystem move. Failed renames do not emit a successful completion, even if the old workspace is reopened during -recovery. A no-op rename emits neither marker. +recovery. A no-op rename emits neither marker. System-test validation requires +both matching markers for every successful internal reopening; independent +path observations alone cannot substitute for a recorded rename command. Shared trace publication uses atomic UTF-8 replacement. Transient Windows access-denied or sharing/lock violations during replacement receive a bounded diff --git a/kilin/__init__.py b/kilin/__init__.py index 4699605b..60893825 100644 --- a/kilin/__init__.py +++ b/kilin/__init__.py @@ -409,7 +409,6 @@ "LexicalResult", "PersistentIndexes", "PROJECT_BEHAVIOR_FILE", - "PROJECT_TYPE_IDS", "ProjectTypeId", "QUERY_FORMAT_CHOICES", "QUERY_FORMAT_PLAIN", @@ -523,7 +522,6 @@ "PLAN_CHOICE_CONTINUE", "PLAN_CHOICE_QUICK", "TOOL_BATCH_CLASSIFY", - "TOOL_CHOICES", "TOOL_SCAN_AND_LIST", "ConfirmationPolicy", "PlanChoice", @@ -616,30 +614,3 @@ "project_type_catalog", "project_type_raw", ] - - -def __getattr__(name: str) -> object: - """Resolve legacy catalog exports without constructing them on import. - - Parameters - ---------- - name: str - Requested module attribute. - - Returns - ------- - object - The requested deferred export. - - Raises - ------ - AttributeError - If the module does not provide the requested attribute. - - """ - - if name == "PROJECT_TYPE_IDS": - return project_type_ids() - if name == "TOOL_CHOICES": - return tool_choices() - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/kilin/_tool_sources.py b/kilin/_tool_sources.py index 0025d953..cb52c15f 100644 --- a/kilin/_tool_sources.py +++ b/kilin/_tool_sources.py @@ -8,7 +8,7 @@ Key Features ------------ -- Lazy operation capture for scoped tools, with no cost for legacy tools. +- Lazy operation capture only for tools requesting scoped services. - Exact membership and generation validation for every bound service. - Independent policy views and shared query vectors within one tool run. diff --git a/kilin/_trace_configuration.py b/kilin/_trace_configuration.py index ab62b108..0b566665 100644 --- a/kilin/_trace_configuration.py +++ b/kilin/_trace_configuration.py @@ -3,106 +3,116 @@ Only project-opening configuration observations use this representation. A reference preserves the original event identity and identifies the latest complete configuration by sequence number and a digest of its canonical JSON. -The original project path remains part of the recorded configuration. +References retain the exact observed project path inline while sharing all +other configuration content with the latest complete snapshot. Key Features ------------ - Canonical JSON equality independent of mapping order. - Direct references to complete snapshots, never to other references. +- One path-preserving reference format for identical settings. Module Structure ---------------- -- ``CONFIGURATION_EVENT`` and ``CONFIGURATION_REFERENCE`` identify the - configuration observation and its compact payload. -- ``configuration_bytes`` encodes a complete snapshot for comparison. -- ``configuration_reference`` constructs a compact reference. +- ``CONFIGURATION_EVENT`` and ``CONFIGURATION_CONTENT_REFERENCE`` identify + the configuration observation and its compact payload. +- ``configuration_content_bytes`` encodes path-independent content. +- ``configuration_content_reference`` constructs a compact reference without + changing the observed configuration. - ``resolve_configuration_reference`` verifies and expands a reference. Examples -------- ->>> from kilin._trace_configuration import configuration_reference ->>> reference = configuration_reference(12, b"{}") ->>> reference["configuration_reference"]["sequence"] +>>> from kilin._trace_configuration import configuration_content_reference +>>> reference = configuration_content_reference(12, b"{}", "workspace") +>>> reference["configuration_content_reference"]["sequence"] 12 """ from collections.abc import Mapping from copy import deepcopy -from hashlib import sha256 -import json from typing import Final +from kilin._trace_snapshots import snapshot_bytes, snapshot_reference + __all__ = [ "CONFIGURATION_EVENT", - "CONFIGURATION_REFERENCE", - "configuration_bytes", - "configuration_reference", + "CONFIGURATION_CONTENT_REFERENCE", + "configuration_content_bytes", + "configuration_content_reference", "resolve_configuration_reference", ] CONFIGURATION_EVENT: Final[str] = "gui.project.configuration.effective" -CONFIGURATION_REFERENCE: Final[str] = "configuration_reference" +CONFIGURATION_CONTENT_REFERENCE: Final[str] = "configuration_content_reference" _CONFIGURATION_FIELDS: Final[frozenset[str]] = frozenset({ "profile", "effort_levels", "router_models", "search_depth", "source_cards", "behavior", "tools", }) -def configuration_bytes(configuration: Mapping[str, object]) -> bytes: - """Encode a complete JSON-ready configuration for exact comparison. +def configuration_content_bytes(configuration: Mapping[str, object]) -> bytes: + """Encode every configuration value except the observed project path. Parameters ---------- configuration: mapping of str to object - Complete effective configuration, already converted to trace JSON - values. Extra fields are retained and included in equality. + Complete JSON-ready effective configuration. The ``behavior`` mapping + must contain ``project``; absence never means a null or empty path. Returns ------- bytes - UTF-8 JSON with ordered object keys and compact separators. List - ordering and JSON scalar representations remain significant. + Canonical JSON preserving all other settings and unknown fields. Raises ------ ValueError - If required fields are missing, the payload is a reference, or a - nonfinite number cannot be represented in standard JSON. + If the configuration is incomplete, compact, or has no project path. TypeError - If a value cannot be serialized as JSON. + If a retained value cannot be serialized as JSON. """ - if (CONFIGURATION_REFERENCE in configuration - or not _CONFIGURATION_FIELDS <= configuration.keys()): - raise ValueError("Expected a complete effective configuration.") - return json.dumps( - dict(configuration), sort_keys=True, separators=(",", ":"), - ensure_ascii=False, allow_nan=False, - ).encode("utf-8") + behavior = configuration.get("behavior") + if (CONFIGURATION_CONTENT_REFERENCE in configuration + or not _CONFIGURATION_FIELDS <= configuration.keys() + or not isinstance(behavior, dict) or "project" not in behavior): + raise ValueError("Expected a configuration with a project path.") + content = dict(configuration) + content["behavior"] = {key: value for key, value in behavior.items() + if key != "project"} + return snapshot_bytes(content) -def configuration_reference(sequence: int, encoded: bytes) -> dict: - """Construct the compact payload for an already published snapshot. +def configuration_content_reference( + sequence: int, encoded: bytes, project: object, +) -> dict: + """Reference shared settings while retaining the exact observed path. Parameters ---------- sequence: int Project-wide sequence number of the complete snapshot. encoded: bytes - Canonical JSON of the complete snapshot. + Canonical configuration content with only ``behavior.project`` absent. + project: object + Original JSON value of ``behavior.project`` in the current event. + Explicit null remains present and is never confused with absence. Returns ------- dict - Reference containing the sequence number and lowercase SHA-256 digest. + Direct content reference and an independent copy of the current path. """ - return {CONFIGURATION_REFERENCE: { - "sequence": sequence, "sha256": sha256(encoded).hexdigest(), - }} + return { + **snapshot_reference(CONFIGURATION_CONTENT_REFERENCE, sequence, + encoded), + "project": deepcopy(project), + } def resolve_configuration_reference( @@ -133,8 +143,9 @@ def resolve_configuration_reference( """ - reference = details.get(CONFIGURATION_REFERENCE) - if (set(details) != {CONFIGURATION_REFERENCE} + key = CONFIGURATION_CONTENT_REFERENCE + reference = details.get(key) + if (set(details) != {key, "project"} or not isinstance(reference, dict) or set(reference) != {"sequence", "sha256"} or type(reference["sequence"]) is not int @@ -145,9 +156,9 @@ def resolve_configuration_reference( raise ValueError( "Configuration reference does not identify the latest snapshot." ) - expected = configuration_reference( - latest[0], configuration_bytes(latest[1]) - ) - if details != expected: + encoded = configuration_content_bytes(latest[1]) + if reference != snapshot_reference(key, latest[0], encoded)[key]: raise ValueError("Project configuration reference digest mismatch.") - return deepcopy(latest[1]) + resolved = deepcopy(latest[1]) + resolved["behavior"]["project"] = deepcopy(details["project"]) + return resolved diff --git a/kilin/_trace_json.py b/kilin/_trace_json.py new file mode 100644 index 00000000..f85930d5 --- /dev/null +++ b/kilin/_trace_json.py @@ -0,0 +1,95 @@ +"""Format diagnostic JSON without expanding every token onto its own line. + +The standard JSON encoder remains responsible for every value, escape and +validation rule. A formatting pass groups long integer arrays into rows of +sixteen values while retaining the ordinary two-space layout elsewhere. +Only whitespace changes; readers and canonical event digests are unchanged. + +Key Features +------------ +- Preserve standard JSON serialization, including scalar types and ordering. +- Share one readable format between project and conversation trace writers. + +Module Structure +---------------- +- ``trace_json_dumps`` serializes and formats a complete diagnostic payload. + +Examples +-------- +>>> import json +>>> from kilin._trace_json import trace_json_dumps +>>> payload = {"token_ids": list(range(32))} +>>> json.loads(trace_json_dumps(payload)) == payload +True + +""" + +import json +import re +from typing import Final + +__all__ = ["trace_json_dumps"] + +_INTEGERS_PER_LINE: Final[int] = 16 +_INTEGER_ARRAY: Final[re.Pattern[str]] = re.compile( + r"\[\n(?P +)" + r"(?P-?[0-9]+(?:,\n +-?[0-9]+){15,})\n *\]" +) + + +def _compact_integer_array(match: re.Match[str]) -> str: + """Replace only the inter-value whitespace of one encoded integer array. + + Parameters + ---------- + match: re.Match[str] + An array produced by the two-space standard JSON encoder. + + Returns + ------- + str + The same bracketed integer lexemes and commas, in rows of sixteen. + + """ + + indentation = match["indent"] + values = match["integers"].split() + rows = [ + " ".join(values[start:start + _INTEGERS_PER_LINE]) + for start in range(0, len(values), _INTEGERS_PER_LINE) + ] + return ("[\n" + indentation + + ("\n" + indentation).join(rows) + + "\n" + indentation[:-2] + "]") + + +def trace_json_dumps(payload: object) -> str: + """Serialize a trace with compact rows for arrays of at least 16 integers. + + Parameters + ---------- + payload: object + JSON-ready diagnostic payload accepted by ``json.dumps``. + + Returns + ------- + str + Two-space JSON with unescaped Unicode and no trailing newline. + Integer arrays use sixteen values per line. All other formatting + and the standard encoder's validation behavior are preserved. + + Raises + ------ + TypeError + If the standard encoder cannot serialize a payload value or key. + ValueError + If the standard encoder detects a circular reference or an integer + exceeds Python's configured conversion limit. + + """ + + encoded = json.dumps(payload, indent=2, ensure_ascii=False) + # Literal ASCII newlines cannot occur inside JSON strings: the standard + # encoder escapes them. Requiring those newlines keeps this whitespace + # pass outside strings without interpreting user text or JSON escapes. + return _INTEGER_ARRAY.sub(_compact_integer_array, encoded) diff --git a/kilin/_trace_project.py b/kilin/_trace_project.py index c8337726..d0754b56 100644 --- a/kilin/_trace_project.py +++ b/kilin/_trace_project.py @@ -33,10 +33,13 @@ Update the shared project trace under short-lived ownership. - ``project_trace_publication`` - Coordinate a configuration observation with a single publication lease. -- ``compact_project_configuration`` + Coordinate a snapshot observation with a single publication lease. +- ``compact_project_configuration`` and ``compact_project_source_snapshot`` - Compare a new configuration with the latest persisted full observation. + Compare new observations with the latest persisted full snapshots. +- ``compact_project_semantic_snapshot`` + + Share exact semantic manifests across supported operation types. Examples -------- @@ -60,11 +63,18 @@ from typing import Final, TypeAlias from kilin.atomic_writes import atomic_write_text +from kilin._trace_json import trace_json_dumps from kilin._trace_configuration import ( + CONFIGURATION_CONTENT_REFERENCE, CONFIGURATION_EVENT, - CONFIGURATION_REFERENCE, - configuration_bytes, - configuration_reference, + configuration_content_bytes, + configuration_content_reference, +) +from kilin._trace_snapshots import ( + SEMANTIC_SNAPSHOT_EVENTS, SEMANTIC_SNAPSHOT_REFERENCE, + SEMANTIC_SNAPSHOT_WRITERS, + SOURCE_SNAPSHOT_REFERENCE, snapshot_bytes, snapshot_reference, + semantic_snapshot, source_snapshot, ) from kilin.conversation_ownership import ( ConversationFileLock, @@ -78,6 +88,8 @@ "project_trace_directory", "ProjectTracePublisher", "compact_project_configuration", + "compact_project_source_snapshot", + "compact_project_semantic_snapshot", "project_trace_publication", "write_project_trace", ] @@ -169,7 +181,7 @@ def _short_ownership(path: Path) -> Iterator[None]: Notes ----- Ordinary publication and sequence allocation take separate leases. - Configuration observations may reserve a sequence while holding the + Compactable observations may reserve a sequence while holding the project publication lease; no path holds the sequence lease while acquiring the project lease. The lock companion is never removed. @@ -405,8 +417,9 @@ def compact_project_configuration( ------- dict Original full configuration or a direct reference to the latest - equal full configuration. Ineligible or ambiguous history is not - used for compaction. + configuration with identical path-independent content. Keep the + exact current path inline whether or not it has changed. Ineligible + or ambiguous history is not used for compaction. Notes ----- @@ -443,15 +456,21 @@ def compact_project_configuration( or "turn_id" in event): return configuration seen.add(number) - if CONFIGURATION_REFERENCE in details: + if CONFIGURATION_CONTENT_REFERENCE in details: continue if latest is None or number > latest[0]: latest = (number, details) if latest is not None: try: - encoded = configuration_bytes(configuration) - if encoded == configuration_bytes(latest[1]): - return configuration_reference(latest[0], encoded) + content = configuration_content_bytes(configuration) + if content == configuration_content_bytes(latest[1]): + compact = configuration_content_reference( + latest[0], content, configuration["behavior"]["project"] + ) + if len(snapshot_bytes(compact)) < len( + snapshot_bytes(configuration) + ): + return compact except (ValueError, TypeError, RecursionError): # Keep full evidence rather than guessing when a configuration # cannot be compared. Inspection still validates the history. @@ -459,6 +478,164 @@ def compact_project_configuration( return configuration +def _latest_project_snapshot( + previous: Mapping[str, object], event_types: frozenset[str], + sequence: int, reference_fields: tuple[str, ...], +) -> tuple[int, dict, dict] | None: + """Find the latest full snapshot without traversing arbitrary payloads. + + Parameters + ---------- + previous: mapping of str to object + Project trace read under the current publication lease. + event_types: frozenset of str + Event types sharing this snapshot's namespace. + sequence: int + New allocation under the project publication lease. + reference_fields: tuple of str + Reserved reference markers. Compact nodes never become targets. + + Returns + ------- + tuple of int, dict and dict or None + Latest number, metadata and full details, or no usable candidate. + + Notes + ----- + Retain the latest full node even when its payload or status is invalid: + the caller must then store new full evidence rather than skipping it. + + """ + + latest = None + seen = set() + sessions = previous.get("sessions", {}) + if not isinstance(sessions, dict): + return None + for session in sessions.values(): + if not isinstance(session, dict): + return None + operations = session.get("operations", {}) + if not isinstance(operations, dict): + return None + for node in operations.values(): + if not isinstance(node, dict): + continue + event = node.get("event") + if (not isinstance(event, dict) + or event.get("event_type") not in event_types): + continue + number = event.get("sequence") + payload = node.get("details", {}) + if (type(number) is not int or not 0 < number < sequence + or number in seen or not isinstance(payload, dict) + or "turn_id" in event): + return None + seen.add(number) + if any(key in payload for key in reference_fields): + continue + if latest is None or number > latest[0]: + latest = (number, event, payload) + return latest + + +def compact_project_source_snapshot( + previous: Mapping[str, object], event_type: str, details: dict, + sequence: int, +) -> dict: + """Replace unchanged source snapshot fields with a direct reference. + + Parameters + ---------- + previous: mapping of str to object + Project trace read under the current publication lease. + event_type: str + Source observation type. References never cross event types. + details: dict + New complete JSON-ready observation. + sequence: int + Newly allocated sequence under the publication lease. + + Returns + ------- + dict + Full observation or smaller compact observation with all independent + fields intact. Invalid full observations reset the candidate. + + """ + + latest = _latest_project_snapshot( + previous, frozenset({event_type}), sequence, + (SOURCE_SNAPSHOT_REFERENCE,), + ) + if latest is None or latest[1].get("status") != "completed": + return details + try: + snapshot = source_snapshot(event_type, details) + encoded = snapshot_bytes(snapshot) + if encoded != snapshot_bytes(source_snapshot(event_type, latest[2])): + return details + reference = snapshot_reference( + SOURCE_SNAPSHOT_REFERENCE, latest[0], encoded, + ) + if len(snapshot_bytes(reference)) >= len(encoded): + return details + except (ValueError, TypeError, RecursionError): + return details + return {**{key: value for key, value in details.items() + if key not in snapshot}, **reference} + + +def compact_project_semantic_snapshot( + previous: Mapping[str, object], event_type: str, details: dict, + sequence: int, +) -> dict: + """Share a semantic manifest without eliding an operation or its result. + + Parameters + ---------- + previous: mapping of str to object + Project trace read under the current publication lease. + event_type: str + Supported semantic commit, reconciliation or application event. + details: dict + Full JSON-ready event details, including its operation context. + sequence: int + Newly allocated sequence number under the same publication lease. + + Returns + ------- + dict + Original details or a smaller representation referencing the latest + raw full semantic manifest. No historical event is rewritten. + + """ + + if event_type not in SEMANTIC_SNAPSHOT_WRITERS: + return details + latest = _latest_project_snapshot( + previous, SEMANTIC_SNAPSHOT_EVENTS, sequence, + (SOURCE_SNAPSHOT_REFERENCE, SEMANTIC_SNAPSHOT_REFERENCE), + ) + if latest is None or latest[1].get("status") != "completed": + return details + try: + snapshot = semantic_snapshot(event_type, details) + encoded = snapshot_bytes(snapshot) + target = semantic_snapshot(latest[1]["event_type"], latest[2]) + if encoded != snapshot_bytes(target): + return details + reference = snapshot_reference( + SEMANTIC_SNAPSHOT_REFERENCE, latest[0], encoded, + ) + if len(snapshot_bytes(reference)) >= len(encoded): + return details + except (ValueError, TypeError, RecursionError): + return details + return {**{key: value for key, value in details.items() + if key not in snapshot}, **reference} + + @contextmanager def project_trace_publication( path: Path, @@ -478,8 +655,8 @@ def project_trace_publication( Notes ----- - The configuration event reserves its sequence and chooses its payload - inside this context. This prevents another configuration writer from + Compactable observations reserve their sequence and choose their payload + inside this context. This prevents another snapshot writer from publishing an intervening full snapshot. Other operations continue to allocate numbers before separately acquiring the publication lease. @@ -521,7 +698,7 @@ def publish( != TRACE_FORMAT_VERSION): raise ValueError("Unsupported project trace format version.") saved = dict(previous.get("sessions", {})) - # Preserve other runs, including their configuration snapshots. + # Preserve other runs, including their full snapshots. for key, value in sessions.items(): saved[f"{key}_{trace_id}"] = value payload = { @@ -533,7 +710,7 @@ def publish( "sessions": dict(sorted(saved.items())), } atomic_write_text( - path, json.dumps(payload, indent=2, ensure_ascii=False) + "\n" + path, trace_json_dumps(payload) + "\n" ) yield previous, publish diff --git a/kilin/_trace_snapshots.py b/kilin/_trace_snapshots.py new file mode 100644 index 00000000..597ea2c3 --- /dev/null +++ b/kilin/_trace_snapshots.py @@ -0,0 +1,306 @@ +"""Encode repeated source observations without discarding event context. + +Key Features +------------ +- Exact canonical JSON equality shared with configuration observations. +- Direct, digest-checked references to complete source snapshot fields. +- Event-specific snapshot boundaries that retain paths, decisions, errors, + and other operation-specific details in their original observations. + +Module Structure +---------------- +- ``snapshot_bytes`` and ``snapshot_reference`` encode snapshots and their + direct references. +- ``source_snapshot`` extracts the supported source observation fields. +- ``resolve_source_reference`` verifies and expands a compact observation. +- ``semantic_snapshot`` and ``resolve_semantic_reference`` share the exact + semantic manifest between supported project event types. + +Examples +-------- +>>> from kilin._trace_snapshots import snapshot_bytes +>>> snapshot_bytes({"b": 2, "a": 1}) +b'{"a":1,"b":2}' + +""" + +from collections.abc import Mapping +from copy import deepcopy +from hashlib import sha256 +import json +from typing import Final + +__all__ = [ + "SOURCE_SNAPSHOT_REFERENCE", + "SOURCE_SNAPSHOT_FIELDS", + "snapshot_bytes", + "snapshot_reference", + "source_snapshot", + "resolve_source_reference", + "SEMANTIC_SNAPSHOT_REFERENCE", + "SEMANTIC_SNAPSHOT_EVENTS", + "SEMANTIC_SNAPSHOT_WRITERS", + "semantic_snapshot", + "resolve_semantic_reference", +] + +SOURCE_SNAPSHOT_REFERENCE: Final[str] = "source_snapshot_reference" +SOURCE_SNAPSHOT_FIELDS: Final[Mapping[str, tuple[str, ...]]] = { + "source.scan.completed": ("selected_files", "entries"), + "index.check.completed": ( + "source_manifest", "expected_metadata", "saved_metadata", + ), + "gui.source_organization.observed": ( + "source_organization", "selected", "pending", "pending_roles", + "retained_versions", + ), +} +SEMANTIC_SNAPSHOT_REFERENCE: Final[str] = "semantic_snapshot_reference" +SEMANTIC_SNAPSHOT_WRITERS: Final[frozenset[str]] = frozenset({ + "source_organization.committed", + "source_organization.reconciled", + "gui.source_organization.apply.completed", +}) +# Opening observations retain their existing whole-group compaction. They +# may supply a full manifest, but never acquire an indirect group reference. +SEMANTIC_SNAPSHOT_EVENTS: Final[frozenset[str]] = ( + SEMANTIC_SNAPSHOT_WRITERS | {"gui.source_organization.observed"} +) + + +def snapshot_bytes(snapshot: Mapping[str, object]) -> bytes: + """Encode JSON-ready snapshot fields for exact comparison. + + Parameters + ---------- + snapshot: mapping of str to object + Complete snapshot data, with JSON-compatible values. + + Returns + ------- + bytes + Canonical UTF-8 JSON. Mapping order is ignored; scalar types and + array order remain significant. Nonfinite numbers are rejected. + + """ + + return json.dumps( + dict(snapshot), sort_keys=True, separators=(",", ":"), + ensure_ascii=False, allow_nan=False, + ).encode("utf-8") + + +def snapshot_reference(key: str, sequence: int, encoded: bytes) -> dict: + """Construct a reference to an already published full snapshot. + + Parameters + ---------- + key: str + Reserved reference field in the observation payload. + sequence: int + Project-wide allocation number of the full snapshot. + encoded: bytes + Canonical snapshot bytes. + + Returns + ------- + dict + Reference containing the target sequence and SHA-256 digest. + + """ + + return {key: {"sequence": sequence, "sha256": sha256(encoded).hexdigest()}} + + +def source_snapshot(event_type: str, details: Mapping[str, object]) -> dict: + """Extract only complete, supported source snapshot fields. + + Parameters + ---------- + event_type: str + Physical scan, index check, or semantic observation event type. + details: mapping of str to object + Full observation payload. Operation-specific fields are not extracted. + + Returns + ------- + dict + Exact fields eligible for compaction. + + Raises + ------ + ValueError + If the event is unsupported, incomplete, or already compact. + + """ + + fields = SOURCE_SNAPSHOT_FIELDS.get(event_type) + if (fields is None or SOURCE_SNAPSHOT_REFERENCE in details + or any(field not in details for field in fields) + or (event_type == "source.scan.completed" + and details.get("complete") is not True) + or (event_type == "gui.source_organization.observed" + and details.get("error") is not None)): + raise ValueError("Expected a complete source snapshot.") + snapshot = {field: details[field] for field in fields} + if event_type == "index.check.completed": + valid = (isinstance(snapshot["source_manifest"], dict) + and isinstance(snapshot["expected_metadata"], dict) + and (snapshot["saved_metadata"] is None + or isinstance(snapshot["saved_metadata"], dict))) + elif event_type == "source.scan.completed": + valid = all(isinstance(value, list) for value in snapshot.values()) + else: + valid = (isinstance(snapshot["source_organization"], dict) + and all(isinstance(snapshot[field], list) + for field in fields[1:]) + and details.get("trace_error") is None) + if not valid: + raise ValueError("Invalid source snapshot fields.") + return snapshot + + +def resolve_source_reference( + event_type: str, details: dict, sequence: int, + latest: tuple[int, dict] | None, +) -> dict: + """Verify and expand a direct reference to the latest full observation. + + Parameters + ---------- + event_type: str + Type of the current observation and its required target. + details: dict + Compact observation, including its independent inline fields. + sequence: int + Sequence number of the current observation. + latest: tuple of int and dict or None + Latest preceding complete observation of this type, not a reference. + + Returns + ------- + dict + Independent copy of the complete observation. + + Raises + ------ + ValueError + If the reference or snapshot is invalid, the target is unavailable, + inline fields overlap the snapshot, or the digest differs. + + """ + + key = SOURCE_SNAPSHOT_REFERENCE + reference = details.get(key) + fields = SOURCE_SNAPSHOT_FIELDS.get(event_type) + if (fields is None or any(field in details for field in fields) + or not isinstance(reference, dict) + or set(reference) != {"sequence", "sha256"} + or type(reference["sequence"]) is not int + or not 0 < reference["sequence"] < sequence + or not isinstance(reference["sha256"], str)): + raise ValueError("Invalid source snapshot reference.") + if latest is None or latest[0] != reference["sequence"]: + raise ValueError("Source reference does not identify latest snapshot.") + snapshot = source_snapshot(event_type, latest[1]) + if {key: reference} != snapshot_reference( + key, latest[0], snapshot_bytes(snapshot)): + raise ValueError("Source snapshot reference digest mismatch.") + expanded = {field: value for field, value in details.items() + if field != key} + expanded.update(deepcopy(snapshot)) + # A compact observation must itself satisfy the snapshot preconditions. + source_snapshot(event_type, expanded) + return expanded + + +def semantic_snapshot( + event_type: str, details: Mapping[str, object], +) -> dict: + """Extract a complete semantic manifest from a supported full event. + + Parameters + ---------- + event_type: str + Semantic commit, reconciliation, application or opening observation. + details: mapping of str to object + Original payload. Revisions, command inputs, inspection results and + operation outcomes remain separate from the shared manifest. + + Returns + ------- + dict + The exact ``source_organization`` field, without normalization. + + Raises + ------ + ValueError + If the event is unsupported, incomplete, failed or already compact. + + """ + + if (event_type not in SEMANTIC_SNAPSHOT_EVENTS + or SEMANTIC_SNAPSHOT_REFERENCE in details + or SOURCE_SNAPSHOT_REFERENCE in details + or not isinstance(details.get("source_organization"), dict) + or details.get("error") is not None + or details.get("trace_error") is not None): + raise ValueError("Expected a complete semantic snapshot.") + if event_type == "gui.source_organization.observed": + source_snapshot(event_type, details) + return {"source_organization": details["source_organization"]} + + +def resolve_semantic_reference( + event_type: str, details: dict, sequence: int, + latest: tuple[int, str, dict] | None, +) -> dict: + """Expand a direct semantic reference across supported event types. + + Parameters + ---------- + event_type: str + Semantic event whose manifest was omitted. + details: dict + Compact payload with all independent operation details still inline. + sequence: int + Sequence number of the current event. + latest: tuple of int, str and dict or None + Number, type and full details of the most recent eligible semantic + observation. A compact event never becomes a reference target. + + Returns + ------- + dict + Independent reconstruction of the original full event details. + + Raises + ------ + ValueError + If the reference is malformed, mixed, chained, forward, superseded, + or inconsistent with the full target's canonical digest. + + """ + + key = SEMANTIC_SNAPSHOT_REFERENCE + reference = details.get(key) + if (event_type not in SEMANTIC_SNAPSHOT_WRITERS + or "source_organization" in details + or SOURCE_SNAPSHOT_REFERENCE in details + or not isinstance(reference, dict) + or set(reference) != {"sequence", "sha256"} + or type(reference["sequence"]) is not int + or not 0 < reference["sequence"] < sequence + or not isinstance(reference["sha256"], str)): + raise ValueError("Invalid semantic snapshot reference.") + if latest is None or latest[0] != reference["sequence"]: + raise ValueError("Semantic reference does not identify latest state.") + snapshot = semantic_snapshot(latest[1], latest[2]) + if {key: reference} != snapshot_reference( + key, latest[0], snapshot_bytes(snapshot)): + raise ValueError("Semantic snapshot reference digest mismatch.") + expanded = {field: value for field, value in details.items() + if field != key} + expanded.update(deepcopy(snapshot)) + semantic_snapshot(event_type, expanded) + return expanded diff --git a/kilin/gui/README.md b/kilin/gui/README.md index 606fc592..2cfba845 100644 --- a/kilin/gui/README.md +++ b/kilin/gui/README.md @@ -102,7 +102,9 @@ preserving explicit line breaks and indentation. Other code blocks retain their horizontal scrolling behavior. Files attached to a message are first added to the project's sources and indexed, without the add dialog; the question then lists their `sources/` -paths. The question shows them as chips that open the workspace tree there. +paths under `Attached files:`. The question shows valid managed-relative +paths as chips that open the workspace tree there. Other attachment text is +displayed literally, without workspace actions. If an attached source still needs a role, KíLín instead opens the source organization editor and keeps the question and imported paths in the composer. Review the roles, close the editor, and send the draft explicitly. @@ -184,15 +186,11 @@ creates it. A chosen folder that is missing or not mounted is skipped with a note, and setup asks again. Changing it restarts the engine, so it is offered only on the start screen. Existing projects are never moved. -For installed versions upgraded from before 7 November 2026, KíLín also -checks the previous user-data `workspaces/` location for a direct subfolder -containing `profile.ini`. If found, setup offers **Use existing projects** -and displays the old directory; the user must explicitly select it. The -folder is rechecked before saving and the engine restarts to discover its -projects normally. This only changes the saved projects-folder preference: -there is no automatic copy, deletion, or migration of sources, indexes, or -conversations. A saved choice (or `KILIN_WORKSPACES_DIR`) remains authoritative. -Projects with outdated or invalid profiles may still require separate repair. +Browse can explicitly select any existing projects folder, including a folder +used by an earlier installation. KíLín does not search former default +locations or migrate their project files. Projects must satisfy the current +profile and workspace format. A saved choice (or `KILIN_WORKSPACES_DIR`) +remains authoritative. Cancelling Browse and failures when choosing a folder return to setup so the user can choose again. @@ -574,13 +572,11 @@ settings remain authoritative: later changes to packaged defaults or user preferences affect new projects, not existing ones. To change an existing project's choices, use Settings rather than deleting its saved profile. -Earlier KíLín versions stored effort levels, router models, and search depth -in `effort_levels.json`, and model substitutions in `model_choices.json`. -When opening an older project, the GUI imports compatible values into -`profile.ini` and removes the legacy files after saving the settings. -Customized per-level retrieval counts in legacy data can supply the new -search-depth steps; unchanged legacy defaults do not override the current -search-depth defaults. Changing a language model does not rebuild the index; +Historical `effort_levels.json` and `model_choices.json` files are ignored +and left untouched. Back up these files and transfer any desired old choices +explicitly through Settings. An effort-level record contains only `name` and +`model`; retrieval depth is configured separately. Changing a language +model does not rebuild the index; changing the embedding model (also a dropdown of cached embedding models) or query format requires confirmation and rebuilds it. A note above the levels appears only when the selected backend's packages are not installed. diff --git a/kilin/gui/_paths.py b/kilin/gui/_paths.py index b7642d10..4a054436 100644 --- a/kilin/gui/_paths.py +++ b/kilin/gui/_paths.py @@ -39,10 +39,6 @@ Select an installer and an explicit backend extra for the current checkout, installed environment, or macOS application runtime. -- ``available_legacy_workspace_directory`` - - Find an older installed-application project directory without moving it. - - ``projects_folder_confirmed`` Tell whether the user confirmed a projects folder that still exists. @@ -70,7 +66,6 @@ from kilin.runtime import BACKEND_MLX, BACKEND_TORCH __all__ = [ - "available_legacy_workspace_directory", "default_workspace_directory", "gui_install_command", "preferences_path", @@ -200,74 +195,6 @@ def _user_projects_directory() -> Path: return _documents_directory() / "KíLín" -def _previous_installed_workspace_directory() -> Path | None: - """Return the pre-November 7 installed GUI workspace parent. - - Returns - ------- - pathlib.Path | None - Old application-data workspace directory, or None for a checkout - or an explicit environment override. - - Notes - ----- - This is a discovery location, never a default or migration target. - Paths match the old installed-app policy on each supported platform. - - """ - - if _development_checkout() is not None or os.environ.get( - WORKSPACES_ENVIRONMENT - ): - return None - home = Path.home() - if sys.platform == "darwin": - base = home / "Library" / "Application Support" / "kilin" - elif sys.platform == "win32": - value = os.environ.get("LOCALAPPDATA") - base = Path(value) / "kilin" if value else ( - home / "AppData" / "Local" / "kilin" - ) - else: - configured = Path(os.environ.get("XDG_DATA_HOME", "")) - base = (configured if configured.is_absolute() else - home / ".local" / "share") / "kilin" - return base / "workspaces" - - -def available_legacy_workspace_directory() -> Path | None: - """Find old installed projects that a user may choose to keep using. - - Returns - ------- - pathlib.Path | None - Existing legacy parent containing at least one candidate project, - or None if no suitable old directory exists. - - Notes - ----- - Only immediate, real subdirectories with a regular ``profile.ini`` - are considered. The actual project schema is checked by the engine - when listing or opening projects. This function never creates, - deletes, copies, or modifies project data. - - """ - - root = _previous_installed_workspace_directory() - if root is None or root.is_symlink() or not root.is_dir(): - return None - try: - for folder in root.iterdir(): - if not folder.is_dir() or folder.is_symlink(): - continue - profile = folder / "profile.ini" - if profile.is_file() and not profile.is_symlink(): - return root.resolve() - except OSError: - return None - return None - - def _development_checkout() -> Path | None: """Find the KíLín source root only when running from its source tree. diff --git a/kilin/gui/model_settings.py b/kilin/gui/model_settings.py index 4f470d65..0b61aaa6 100644 --- a/kilin/gui/model_settings.py +++ b/kilin/gui/model_settings.py @@ -25,14 +25,14 @@ mlx = Qwen/Qwen3-4B-MLX-4bit torch = Qwen/Qwen3-4B -``save_project_settings`` writes them when a project is created or first -opened, from the defaults, or from the ``effort_levels.json`` and -``model_choices.json`` files earlier versions kept, which it then removes. +``save_project_settings`` initializes genuinely missing settings when a +project is created or first activated in the GUI, from the effective +application preferences. Historical sidecars are ignored and retained. GUI effort and search defaults live in ``kilin.gui.preferences``. Router model validation, persistence, and packaged defaults live in KíLín core. The GUI supplies its application preference only when a project has no -saved or legacy router choice. +saved router choice. Key Features ------------ @@ -42,9 +42,10 @@ Read and update effort levels and search-depth steps in the project's ``profile.ini``. Router read/write functions are imported from core. -- **Legacy migration** +- **Current initialization** - Import compatible settings from earlier project files when they exist. + Fill absent settings from current defaults without replacing saved + values or reading historical sidecars. Module Structure ---------------- @@ -63,7 +64,7 @@ - ``save_project_settings`` - Write missing settings or migrate compatible legacy values. + Initialize missing settings without overriding saved values. Examples -------- @@ -75,7 +76,6 @@ from configparser import ConfigParser from io import StringIO -import json from pathlib import Path from kilin.atomic_writes import atomic_write_text @@ -87,7 +87,6 @@ default_router_model, default_search_depth, validate_effort_levels, - validate_model_id, validate_search_depth, ) from kilin.model_settings import read_router_model, write_router_model @@ -117,11 +116,6 @@ _SEARCH_SECTION = "search" _ROUTER_SECTION = "router" _SEPARATOR = " | " -# Files of earlier versions, migrated into profile.ini and removed. -_LEGACY_EFFORT_FILE = "effort_levels.json" -_LEGACY_CHOICES_FILE = "model_choices.json" -# Per-level reference counts of earlier versions, before search depth. -_LEGACY_RETRIEVAL = (5, 20, 20, 50, 50) def read_effort_levels( @@ -140,8 +134,8 @@ def read_effort_levels( ------- list[dict[str, object]] Five ``{"name", "model"}`` levels from ``profile.ini``; for a - project that has not saved them yet, from an earlier version's - files, otherwise the defaults. + project that has not saved them yet, from current application + preferences. """ @@ -157,22 +151,7 @@ def read_effort_levels( ).partition(_SEPARATOR.strip()) levels.append({"name": name.strip(), "model": model.strip()}) return validate_effort_levels(levels) - legacy = _legacy(root) - if backend in legacy: - return validate_effort_levels( - [ - {"name": level["name"], "model": level["model"]} - for level in legacy[backend] - ] - ) - levels = default_effort_levels(backend) - choices = _read_json(root / _LEGACY_CHOICES_FILE) - replacements = choices if isinstance(choices, dict) else {} - for level in levels: - replacement = replacements.get(level["model"]) - if isinstance(replacement, str) and replacement.strip(): - level["model"] = validate_model_id(replacement) - return levels + return default_effort_levels(backend) def write_effort_levels( @@ -197,8 +176,6 @@ def write_effort_levels( """ levels = validate_effort_levels(levels) - if any(_SEPARATOR.strip() in str(level["name"]) for level in levels): - raise ValueError("Effort level names cannot contain '|'.") profile = _read(root) section = _EFFORT_SECTION.format(backend=backend) if not profile.has_section(section): @@ -224,7 +201,7 @@ def read_search_depth(root: Path | None) -> list[int]: ------- list[int] Five steps from ``profile.ini``; for a project that has not saved - them yet, from an earlier version's files, otherwise the defaults. + them yet, from current application preferences. Raises ------ @@ -247,10 +224,7 @@ def read_search_depth(root: Path | None) -> list[int]: "Search depth steps must be whole numbers." ) from error return validate_search_depth(steps) - legacy = _legacy(root) - if "search_depth" in legacy: - return validate_search_depth(legacy["search_depth"]) - return _legacy_depth(legacy) or default_search_depth() + return default_search_depth() def write_search_depth(root: Path, steps: list[int]) -> None: @@ -284,35 +258,49 @@ def save_project_settings(root: Path) -> bool: Returns ------- bool - Whether anything was written. Saved values are never changed; - missing ones come from an earlier version's ``effort_levels.json`` - and ``model_choices.json`` (then removed) or the defaults, so the - project no longer follows later changes to the defaults. + Whether missing settings were written. Saved values are never + changed; missing ones come from current application preferences. + A core-created project may legitimately lack GUI settings. + + Raises + ------ + ValueError + If a current saved setting or a required default is invalid. + + Notes + ----- + Validate current values and the defaults needed for initialization + before writing any missing settings. Historical sidecars are neither + read nor removed. A fully initialized profile is not rewritten. """ profile = _read(root) - changed = False + pending_levels = {} + pending_routers = {} + # Read current settings first, so invalid settings cannot trigger a + # partial initialization of other missing settings. for backend in (BACKEND_MLX, BACKEND_TORCH): + levels = read_effort_levels(root, backend) if not profile.has_section(_EFFORT_SECTION.format(backend=backend)): - levels = read_effort_levels(root, backend) - write_effort_levels(root, backend, levels) - changed = True - if not profile.has_option(_ROUTER_SECTION, backend): - initial_router = read_router_model( - root, backend, - default_model=default_router_model(backend), + pending_levels[backend] = levels + if profile.has_option(_ROUTER_SECTION, backend): + read_router_model(root, backend) + else: + pending_routers[backend] = read_router_model( + root, backend, default_model=default_router_model(backend), ) - write_router_model(root, backend, initial_router) - changed = True - if not profile.has_option(_SEARCH_SECTION, "depth"): - write_search_depth(root, read_search_depth(root)) - changed = True - for name in (_LEGACY_EFFORT_FILE, _LEGACY_CHOICES_FILE): - if (root / name).exists(): - (root / name).unlink() - changed = True - return changed + depth = read_search_depth(root) + pending_depth = not profile.has_option(_SEARCH_SECTION, "depth") + # Preserve the profile section order used during initialization. + for backend in (BACKEND_MLX, BACKEND_TORCH): + if backend in pending_levels: + write_effort_levels(root, backend, pending_levels[backend]) + if backend in pending_routers: + write_router_model(root, backend, pending_routers[backend]) + if pending_depth: + write_search_depth(root, depth) + return bool(pending_levels or pending_routers or pending_depth) def _read(root: Path) -> ConfigParser: @@ -352,79 +340,3 @@ def _write(root: Path, profile: ConfigParser) -> None: stream = StringIO() profile.write(stream) atomic_write_text(path, stream.getvalue()) - - -def _read_json(path: Path) -> object: - """Read a JSON file, returning None if the file is absent. - - Parameters - ---------- - path: Path - Optional JSON file to parse. - - Returns - ------- - object - Parsed JSON object, or None when the file does not exist. - - Raises - ------ - json.JSONDecodeError - If the file does not contain valid JSON. - - """ - - if not path.is_file(): - return None - return json.loads(path.read_text(encoding="utf-8")) - - -def _legacy(root: Path) -> dict: - """The ``effort_levels.json`` an earlier version kept, if any. - - Parameters - ---------- - root: Path - Project or workspace root directory. - - Returns - ------- - dict - Earlier-version effort settings, or an empty mapping. - - """ - - saved = _read_json(root / _LEGACY_EFFORT_FILE) - return saved if isinstance(saved, dict) else {} - - -def _legacy_depth(saved: dict) -> list[int] | None: - """Customized per-level counts saved by even earlier versions. - - Parameters - ---------- - saved: dict - Settings loaded from an earlier profile format. - - Returns - ------- - list[int] | None - Earlier per-level retrieval counts, or None when unavailable. - - """ - - for key, levels in saved.items(): - if key in ("router", "search_depth") or not isinstance(levels, list): - continue - counts = [ - level.get("retrieval") for level in levels - if isinstance(level, dict) - ] - if ( - len(counts) == LEVEL_COUNT - and all(type(c) is int and 1 <= c <= MAX_SEARCH_DEPTH - for c in counts) - and tuple(counts) != _LEGACY_RETRIEVAL - ): - return counts - return None diff --git a/kilin/gui/preferences.py b/kilin/gui/preferences.py index 8029eef8..527774df 100644 --- a/kilin/gui/preferences.py +++ b/kilin/gui/preferences.py @@ -128,7 +128,7 @@ def validate_effort_levels(value: object) -> list[dict[str, object]]: - """Check five levels of name and model ID. + """Check five levels, each containing only a name and model ID. Parameters ---------- @@ -138,14 +138,14 @@ def validate_effort_levels(value: object) -> list[dict[str, object]]: Returns ------- list[dict[str, object]] - Levels with names collapsed to single spaces. A ``retrieval`` - count saved by earlier versions is ignored; see - ``kilin.gui.model_settings.read_search_depth``. + Levels with names collapsed to single spaces. Each record has + exactly ``name`` and ``model``; search depth is independent. Raises ------ ValueError - If there are not five levels or a field is invalid. + If there are not five levels, a record has missing or extra fields, + or a field is invalid. """ @@ -153,19 +153,23 @@ def validate_effort_levels(value: object) -> list[dict[str, object]]: raise ValueError(f"Expected {LEVEL_COUNT} effort levels.") levels = [] for item in value: - if not isinstance(item, dict): - raise ValueError("Invalid effort level.") - name = item.get("name") + if not isinstance(item, dict) or set(item) != {"name", "model"}: + raise ValueError( + "Each effort level must contain only 'name' and 'model'." + ) + name = item["name"] if not isinstance(name, str) or not name.strip(): raise ValueError("Give every effort level a name.") name = " ".join(name.split()) + if "|" in name: + raise ValueError("Effort level names cannot contain '|'.") if len(name) > MAX_LEVEL_NAME: raise ValueError( f"Effort level names can have at most {MAX_LEVEL_NAME} " "characters." ) levels.append( - {"name": name, "model": validate_model_id(item.get("model"))} + {"name": name, "model": validate_model_id(item["model"])} ) return levels diff --git a/kilin/gui/web/app.js b/kilin/gui/web/app.js index 5f89046d..d2a55037 100644 --- a/kilin/gui/web/app.js +++ b/kilin/gui/web/app.js @@ -2841,7 +2841,6 @@ function showSetupLock() { install.textContent = installingModels ? "Stop downloading" : "Install required models"; install.disabled = installingModels ? false : busy || !readinessEnvironmentReady || !readinessMissingCount; byId("use-installed").disabled = busy || !readinessEnvironmentReady; - byId("use-legacy-workspace").disabled = busy || ready; byId("open").disabled = busy || !bridge || !kilinReady; byId("close-models").disabled = false; byId("close-models").title = ""; @@ -5976,9 +5975,8 @@ function branchFromMessage(item, withAnswer, draft) { bridge.branchConversation(withAnswer ? index + 1 : index); } -// The list KíLín adds under a question with attached files; older chats -// listed the original paths under "Attached paths to consider". -const ATTACHED_LIST = /\n\nAttached (?:files|paths to consider):\n((?:- [^\n]+(?:\n|$))+)$/; +// The list KíLín adds under a question with managed source attachments. +const ATTACHED_LIST = /\n\nAttached files:\n((?:- [^\n]+(?:\n|$))+)$/; /** * Split a saved question into the user's text and its attached files. @@ -5990,17 +5988,23 @@ function splitAttached(text) { const value = String(text || ""); const match = value.match(ATTACHED_LIST); if (!match) return { question: value, files: [] }; - return { - question: value.slice(0, match.index), - files: match[1].trim().split("\n").map((line) => line.slice(2).trim()), - }; + const files = match[1].replace(/\n$/, "").split("\n").map((line) => line.slice(2)); + // Only normalized managed-relative paths may become workspace actions. + // Keep an unsupported or malformed list as literal question text. + if (files.some((path) => { + const parts = path.replace(/\/$/, "").split("/"); + return parts[0] !== "sources" || parts.length < 2 + || /[\\\x00]/.test(path) + || parts.some((part) => !part || part === "." || part === ".."); + })) return { question: value, files: [] }; + return { question: value.slice(0, match.index), files }; } /** * Show a question with its attached files as chips under the text. * - * A file in sources opens its place in the workspace tree; a path from an - * older chat, never copied, is shown by name only. + * A managed file or folder opens its place in the workspace tree. Text + * without a valid current attachment list is displayed unchanged. * * @param element The question bubble. * @param text Question as sent to the engine. @@ -6012,15 +6016,12 @@ function fillQuestion(element, text) { const row = document.createElement("div"); row.className = "question-attachments"; for (const path of files) { - const inSources = path.startsWith("sources/"); - const chip = document.createElement(inSources ? "button" : "span"); + const chip = document.createElement("button"); chip.className = "question-attachment"; - chip.textContent = path.replace(/\/$/, "").split(/[\\/]/).pop() || path; - chip.title = inSources ? `Show ${path} in the workspace` : path; - if (inSources) { - chip.type = "button"; - chip.addEventListener("click", () => revealWorkspacePath(path)); - } + chip.textContent = path.replace(/\/$/, "").split("/").pop(); + chip.title = `Show ${path} in the workspace`; + chip.type = "button"; + chip.addEventListener("click", () => revealWorkspacePath(path)); row.append(chip); } element.append(row); @@ -8086,9 +8087,6 @@ byId("memory-next").addEventListener("click", () => { }); byId("browse-workspace").addEventListener("click", () => changeProjectsFolder(false)); byId("default-workspace").addEventListener("click", () => changeProjectsFolder(true)); -byId("use-legacy-workspace").addEventListener( - "click", useLegacyProjectsFolder, -); byId("confirm-workspace").addEventListener("click", () => { if (!bridge || busy) return; if (ready) return changeProjectsFolder(false); @@ -8370,8 +8368,6 @@ function showProjectSettings() { // saved folder, Confirm projects folder confirms the one in use. byId("default-workspace").disabled = ready || !projectsFolderInfo?.saved || projectsFolderInfo.saved === projectsFolderInfo.standard; - byId("use-legacy-workspace").disabled = ready || busy; - byId("use-legacy-workspace").title = why; byId("browse-workspace").title = why; byId("default-workspace").title = why; // A note only when the chosen folder is missing. @@ -8380,18 +8376,6 @@ function showProjectSettings() { ? `${projectsFolderInfo.saved} is not available, so KíLín uses the default folder.` : ""; byId("workspace-note").classList.toggle("hidden", !missing); - const legacy = projectsFolderInfo?.legacy || ""; - const canReuseLegacy = Boolean( - legacy && legacy !== projectsFolderInfo?.folder, - ); - byId("legacy-workspace-choice").classList.toggle( - "hidden", !canReuseLegacy, - ); - byId("legacy-workspace-note").textContent = canReuseLegacy - ? `Existing KíLín projects may be at ${legacy}. Use that folder to ` - + "keep working with them, or confirm a different folder. " - + "No project files will be moved." - : ""; showSetupConfirmations(); // An open project keeps the backend it was made with. byId("backend").title = ready ? "Set when the project was created." : ""; @@ -8479,19 +8463,6 @@ function changeProjectsFolder(useDefault) { bridge.useDefaultProjectsFolder(); } -/** - * Reuse a previous installed-app projects directory without moving files. - * - * Qt rechecks the old folder before saving it as the user's choice. - */ -function useLegacyProjectsFolder() { - if (!bridge || busy || !projectsFolderInfo?.legacy) return; - if (ready) return changeProjectsFolder(false); - switchingProjectsFolder = true; - setBusy(true, "Opening the previous projects folder…"); - bridge.useLegacyProjectsFolder(); -} - /** * Restore the start screen after a cancelled or failed folder selection. * diff --git a/kilin/gui/web/index.html b/kilin/gui/web/index.html index b352d1a1..e62394bb 100644 --- a/kilin/gui/web/index.html +++ b/kilin/gui/web/index.html @@ -197,10 +197,6 @@

Projects folder
-

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

diff --git a/kilin/gui/window.py b/kilin/gui/window.py index 0b359e91..2e0990a2 100644 --- a/kilin/gui/window.py +++ b/kilin/gui/window.py @@ -88,7 +88,6 @@ from kilin.conversation_format import conversation_state from kilin.plugins._lifecycle import _ensure_runtime from kilin.gui._paths import ( - available_legacy_workspace_directory, default_workspace_directory, saved_workspace_folder, standard_workspace_directory, @@ -177,8 +176,6 @@ class ChatBridge(QObject): Choose the folder where KíLín keeps its projects. useDefaultProjectsFolder() Choose the standard projects folder. - useLegacyProjectsFolder() - Reuse the previous installed-app folder, without moving projects. confirmProjectsFolder() Confirm the projects folder in use, as KíLín setup asks. acceptTerms(version) @@ -489,29 +486,6 @@ def useDefaultProjectsFolder(self) -> None: return self.projectsFolderChosen.emit(folder) - @Slot() - def useLegacyProjectsFolder(self) -> None: - """Reuse an existing legacy projects folder, without moving data. - - Notes - ----- - Resolve and validate the candidate again when clicked; the folder - may have changed since the frontend received its suggestion. - - """ - - folder = available_legacy_workspace_directory() - if folder is None: - self.event.emit(json.dumps({ - "event": "projects_folder_failed", - "message": ( - "The previous projects folder is no longer available. " - "Choose a folder with Browse instead." - ), - })) - return - self.projectsFolderChosen.emit(str(folder)) - @Slot() def confirmProjectsFolder(self) -> None: """Confirm the projects folder in use, as KíLín setup asks.""" @@ -580,8 +554,7 @@ def requestProjectsFolder(self) -> None: Notes ----- Sends ``projects_folder`` with the effective, standard, and saved - folders; ``missing`` reports an unavailable saved folder, while - ``legacy`` offers an existing old installed-app directory. No + folders; ``missing`` reports an unavailable saved folder. No project is moved or selected without user confirmation. """ @@ -595,7 +568,6 @@ def requestProjectsFolder(self) -> None: ) return saved = saved_workspace_folder() - legacy = available_legacy_workspace_directory() self.event.emit( json.dumps( { @@ -603,7 +575,6 @@ def requestProjectsFolder(self) -> None: "folder": folder, "standard": standard, "saved": saved, - "legacy": str(legacy) if legacy else "", "missing": bool(saved) and not Path(saved).expanduser().is_dir(), } diff --git a/kilin/model_settings.py b/kilin/model_settings.py index c85b9fd6..3358f02c 100644 --- a/kilin/model_settings.py +++ b/kilin/model_settings.py @@ -8,8 +8,8 @@ The GUI may use a different application-wide preference when first saving settings for a project. Once saved, the project value is authoritative. -Older ``effort_levels.json`` router selections are read without mutating the -workspace; the GUI's existing migration workflow owns their removal. +Only the current profile supplies saved router selections. Historical +sidecars are neither read nor modified. Key Features ------------ @@ -100,7 +100,6 @@ _ROUTER_SECTION: Final[str] = "router" _PROFILE_FILE: Final[str] = "profile.ini" -_LEGACY_FILE: Final[str] = "effort_levels.json" _SOURCE_CARD_SECTION: Final[str] = "source_card_generation" _MAX_SOURCE_CARD_TOKENS: Final[int] = 200_000 _SOURCE_CARD_DEFAULTS = load_defaults_section("SOURCE_CARD_GENERATION") @@ -189,26 +188,25 @@ def read_router_model( backend: str Selected calculation backend, ``"mlx"`` or ``"torch"``. default_model: str | None, optional - Initial choice when neither current nor legacy settings specify a - router. GUI project setup may provide its user preference; core - callers default to the packaged model. Defaults to ``None``. + Initial choice when the project profile has no saved router. GUI + setup may provide its user preference; core callers default to the + packaged model. Defaults to ``None``. Returns ------- str - Validated saved router, legacy router, or default in that order. + Validated saved router, supplied initial choice, or packaged default + in that order. Raises ------ ValueError If the backend or a present model identifier is invalid. - json.JSONDecodeError - If the legacy router settings contain malformed JSON. Notes ----- - This reader does not migrate or write project files. Consequently a - model selection made through the GUI is respected by a core-only + This reader does not read historical sidecars or write project files. + A model selection made through the GUI is respected by a core-only session without first initializing a GUI engine. """ @@ -222,15 +220,6 @@ def read_router_model( return validate_model_id( profile.get(_ROUTER_SECTION, backend) ) - legacy_path = directory / _LEGACY_FILE - if legacy_path.is_file(): - legacy = json.loads(legacy_path.read_text(encoding="utf-8")) - if isinstance(legacy, dict): - routers = legacy.get("router") - if isinstance(routers, dict) and isinstance( - routers.get(backend), str - ): - return validate_model_id(routers[backend]) return ( validate_model_id(default_model) if default_model is not None diff --git a/kilin/project.py b/kilin/project.py index c8d5dfcf..79d0503a 100644 --- a/kilin/project.py +++ b/kilin/project.py @@ -44,9 +44,9 @@ Module Structure ---------------- -- ``project_type_ids`` and ``PROJECT_TYPE_IDS`` +- ``project_type_ids`` - All packaged type IDs in deterministic filename order, not an enum. + Available project-type IDs in catalog order, not an enum. - ``ProjectTypeId`` @@ -110,7 +110,7 @@ >>> import kilin.project >>> profile = kilin.project.default_project_profile( -... kilin.PROJECT_TYPE_IDS[0] +... kilin.project_type_ids()[0] ... ) """ @@ -188,7 +188,6 @@ __all__ = [ "project_type_ids", - "PROJECT_TYPE_IDS", "ProjectTypeId", "ProjectProfile", "ProjectCreationProvenance", @@ -369,31 +368,6 @@ def project_type_ids() -> tuple[ProjectTypeId, ...]: return tuple(load_project_types()) -def __getattr__(name: str) -> object: - """Resolve the legacy project identifier export on demand. - - Parameters - ---------- - name: str - Requested module attribute. - - Returns - ------- - object - The requested deferred export. - - Raises - ------ - AttributeError - If the module does not provide the requested attribute. - - """ - - if name == "PROJECT_TYPE_IDS": - return project_type_ids() - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - - def _require_project_type(type_id: ProjectTypeId, field: str) -> None: """Reject unknown or unavailable types before touching a workspace. @@ -425,7 +399,7 @@ def default_project_profile(type_id: ProjectTypeId) -> ProjectProfile: Parameters ---------- type_id: ProjectTypeId - Registered project-type identifier from ``PROJECT_TYPE_IDS``. + Registered project-type identifier from ``project_type_ids()``. Returns ------- @@ -435,7 +409,7 @@ def default_project_profile(type_id: ProjectTypeId) -> ProjectProfile: Raises ------ ValueError - If ``type_id`` is not one of ``PROJECT_TYPE_IDS``. + If ``type_id`` is not one of ``project_type_ids()``. Notes ----- diff --git a/kilin/system_testing/_comparison_diagnostics.py b/kilin/system_testing/_comparison_diagnostics.py index 3d42a61d..77c03209 100644 --- a/kilin/system_testing/_comparison_diagnostics.py +++ b/kilin/system_testing/_comparison_diagnostics.py @@ -25,7 +25,6 @@ from collections import Counter from copy import deepcopy -from datetime import datetime import json import re @@ -38,10 +37,6 @@ _CONTEXT = ("history.selection.result", "memory.sync.result", "project.memory.sync.result", "conversation_memory.retrieved") _HEADER = re.compile( - r"Memory (M[1-9]\d*) \| (user|assistant) \| UUID (\S+) \| " - r"([^\n|]+) \| (.+)" -) -_LOCAL_HEADER = re.compile( r"Memory (M[1-9]\d*) \| (user|assistant) \| Turn (T[1-9]\d*)" ) _MEMORY_HEADING = ( @@ -245,29 +240,14 @@ def _header(record: dict, line: str, turns: dict[str, str], Expected prompt-local label for the selected turn UUID. """ - match = _LOCAL_HEADER.fullmatch(line) - if match: - label, role, turn = match.groups() - if (label, role, turn) != ( - record["label"], record["role"], local_turn - ): - raise ValueError("Memory header does not match selected memory.") - else: - match = _HEADER.fullmatch(line) - if not match: - raise ValueError("Memory header does not match recorded format.") - label, role, uid, stamp, origins = match.groups() - # Corroborate legacy metadata before normalizing it. - if datetime.fromisoformat(stamp).utcoffset() is None: - raise ValueError("Memory timestamp has no timezone.") - expected = ", ".join( - f"{o['conversation_id']} turn {o['turn_number']}" - for o in record["origins"] - ) - if (label, role, uid, origins) != ( - record["label"], record["role"], record["turn_uuid"], expected - ): - raise ValueError("Memory header does not match selected memory.") + match = _HEADER.fullmatch(line) + if not match: + raise ValueError("Memory header does not match recorded format.") + label, role, turn = match.groups() + if (label, role, turn) != ( + record["label"], record["role"], local_turn + ): + raise ValueError("Memory header does not match selected memory.") identity = _memory_record(record, turns, conversations) return f"Memory {label} | {_key(identity)}" diff --git a/kilin/system_testing/_inspection.py b/kilin/system_testing/_inspection.py index e3b84d5f..c6082fa0 100644 --- a/kilin/system_testing/_inspection.py +++ b/kilin/system_testing/_inspection.py @@ -149,9 +149,8 @@ def relocation_event_differences(data: dict, before: ValidationReport, move = row.get("relocation") if not move or move["physical_rename_replayed"]: continue - if move["original"]["provenance"] == "recorded": - expected["gui.project.rename.requested"] -= 1 - expected["gui.project.rename.completed"] -= 1 + expected["gui.project.rename.requested"] -= 1 + expected["gui.project.rename.completed"] -= 1 a, b = before.operations[i], after.operations[i] # A successful opening may be followed by a source check outside # its command span. Only an explicitly empty diagnostic qualifies. diff --git a/kilin/system_testing/_plugin_provenance.py b/kilin/system_testing/_plugin_provenance.py index bef1257f..3ded534d 100644 --- a/kilin/system_testing/_plugin_provenance.py +++ b/kilin/system_testing/_plugin_provenance.py @@ -6,7 +6,7 @@ Key Features ------------ -- Preserve unknown identities in older traces without reconstructing them. +- Validate required metadata and retain genuinely unknown identities. - Compare captured identities at matching command boundaries. - Resolve historical and current plugin requirements before replay. @@ -37,9 +37,11 @@ __all__ = [] +_MISSING = object() + def _observation( - event: TraceEvent, scope: str, kind: str, name: str, identity: object, + event: TraceEvent, scope: str, kind: str, name: object, identity: object, ) -> dict: """Decode an optional portable identity without consulting a catalog. @@ -51,10 +53,10 @@ def _observation( Opening, turn, or tool execution boundary. kind: str Project type or tool identity category. - name: str + name: object Identifier recorded independently of the identity payload. identity: object - Optional identity payload. None represents unknown provenance. + Identity payload; None is unknown and _MISSING is a missing field. Returns ------- @@ -64,7 +66,14 @@ def _observation( """ result = {"sequence": event.sequence, "scope": scope, "kind": kind, - "name": name, "status": "unknown", "identity": None} + "name": name if isinstance(name, str) else None, + "status": "unknown", "identity": None} + if not isinstance(name, str) or not name: + result.update(status="invalid", error="Missing plugin identifier.") + return result + if identity is _MISSING: + result.update(status="invalid", error="Missing plugin identity field.") + return result if identity is None: return result key = "type_id" if kind == "project_type" else "name" @@ -94,9 +103,9 @@ def plugin_observations(events: tuple[TraceEvent, ...]) -> list[dict]: Returns ------- list[dict] - Chronological observations. Legacy configurations retain known IDs - but explicitly unknown identities. Invalid optional provenance is - reported without pretending it is a verified identity. + Chronological observations. Required metadata must be present. + Explicitly unknown identities and unavailable turn identities are + retained without inferring them from an installed catalog. """ @@ -108,38 +117,41 @@ def plugin_observations(events: tuple[TraceEvent, ...]) -> list[dict]: name = (profile.get("type_id") if isinstance(profile, dict) else None) tools = data.get("tools") - names = sorted({entry["name"] for entry in tools - if isinstance(entry, dict) - and isinstance(entry.get("name"), str)}) if ( - isinstance(tools, list)) else [] - snapshot = data.get("plugins", {"project_type": None, - "tools": dict.fromkeys(names)}) - if (not isinstance(snapshot, dict) + snapshot = data.get("plugins") + if (not isinstance(name, str) or not name + or not isinstance(tools, list) + or not all(isinstance(entry, dict) + and isinstance(entry.get("name"), str) + and entry["name"] for entry in tools) + or not isinstance(snapshot, dict) or set(snapshot) != {"project_type", "tools"} or not isinstance(snapshot["tools"], dict) - or set(snapshot["tools"]) != set(names)): + or set(snapshot["tools"]) != { + entry["name"] for entry in tools}): result.append({"sequence": event.sequence, "scope": "open", - "kind": "project_type", "name": name, + "kind": "project_type", + "name": (name if isinstance(name, str) + else None), "status": "invalid", "identity": None, - "error": "Invalid plugin snapshot."}) + "error": "Invalid or missing plugin snapshot."}) continue - if isinstance(name, str): - result.append(_observation(event, "open", "project_type", - name, snapshot["project_type"])) - for tool in names: + result.append(_observation(event, "open", "project_type", + name, snapshot["project_type"])) + for tool in sorted(snapshot["tools"]): result.append(_observation(event, "open", "tool", tool, snapshot["tools"][tool])) elif event.event_type == "turn.settings.snapshot": - name = data.get("project_type_id") - if isinstance(name, str): - result.append(_observation(event, "turn", "project_type", - name, data.get( - "project_type_plugin"))) + # The producer omits an unavailable project-type identity. + result.append(_observation( + event, "turn", "project_type", data.get("project_type_id"), + data.get("project_type_plugin"), + )) elif event.event_type == "tool.run.started": - name = data.get("name") - if isinstance(name, str): - result.append(_observation(event, "execution", "tool", - name, data.get("plugin"))) + # Unlike turn settings, tool execution always records the key. + result.append(_observation( + event, "execution", "tool", data.get("name"), + data.get("plugin", _MISSING), + )) return result diff --git a/kilin/system_testing/_semantic_replay.py b/kilin/system_testing/_semantic_replay.py index 12e67dc4..4c798eea 100644 --- a/kilin/system_testing/_semantic_replay.py +++ b/kilin/system_testing/_semantic_replay.py @@ -8,7 +8,7 @@ Module Structure ---------------- -- ``validate_semantic_history`` checks PR14 producer records. +- ``validate_semantic_history`` checks the current recording protocol. - ``semantic_observations`` and ``compare_semantics`` describe differences. - ``semantic_request`` isolates portable explicit command inputs. @@ -297,7 +297,7 @@ def _validate_transition(before: SourceManifest, after: SourceManifest, def validate_semantic_history(recording: Recording, operations: tuple[TimelineOperation, ...] ) -> None: - """Verify PR14 semantic commands, lifecycle and question checkpoints. + """Verify semantic commands, lifecycle and question checkpoints. Parameters ---------- @@ -308,6 +308,7 @@ def validate_semantic_history(recording: Recording, Notes ----- + The complete semantic history is required for every recording. Physical source history is validated separately. Missing, externally replaced or unrecorded semantic states are not reconstructed from the final file. The supported physical history remains additive. @@ -438,7 +439,9 @@ def validate_semantic_history(recording: Recording, pending = None elif kind in ("index.check.completed", "index.empty"): indexed = set(_manifest_files(data["source_manifest"])) - _require(state is not None and selected == indexed, + _require(state is not None, + "Missing initial semantic creation state.") + _require(selected == indexed, "Semantic state has no matching physical index " "checkpoint.") _require(lifecycle_before is None, diff --git a/kilin/system_testing/analysis.py b/kilin/system_testing/analysis.py index 5b92c3ac..5761249c 100644 --- a/kilin/system_testing/analysis.py +++ b/kilin/system_testing/analysis.py @@ -5,6 +5,7 @@ - Read-only report discovery and visual, coverage-aware summaries. - Side-by-side saved answers and expandable execution diagnostics. - Optional exact model texts verified against recorded SHA-256 digests. +- Shared reference decoding for local diagnostics, with explicit read issues. - Independent visual Markdown exports alongside native reports. Module Structure @@ -41,6 +42,7 @@ from kilin._trace_project import TRACE_FORMAT_VERSION from .comparison import COMPARISON_FORMAT_VERSION +from .traces import read_recording __all__ = [ "load_report", "discover_reports", "overview", "batch_overview", @@ -583,7 +585,7 @@ def load_report(path: str | Path) -> dict: Raises ------ ValueError - Unsupported schema or malformed top-level sections. + Unsupported schema, malformed sections or invalid event inventory. OSError Report cannot be read. @@ -594,7 +596,8 @@ def load_report(path: str | Path) -> dict: data = json.loads(path.read_text(encoding="utf-8")) if type(_at(data, "format_version")) is not int or ( data["format_version"] != COMPARISON_FORMAT_VERSION): - raise ValueError("Unsupported comparison report format version.") + raise ValueError("Unsupported comparison report format version; " + "regenerate the comparison report.") for key in ("alignment", "summary", "original", "replayed", "files", "final_state", "embedding_evaluation"): if not isinstance(data.get(key), dict): @@ -607,6 +610,9 @@ def load_report(path: str | Path) -> dict: if data["alignment"].get("status") not in ( "complete", "diverged", "invalid_recording"): raise ValueError("Unknown alignment status.") + if not event_inventory(data)["complete"]: + raise ValueError("Missing or invalid independent event counts; " + "regenerate the comparison report.") return data @@ -884,10 +890,11 @@ def overview(data: dict) -> str: def event_inventory(data: dict) -> dict: - """Count events in aligned commands and outside command boundaries. + """Check the independent event inventories recorded for both sides. - Prefer independent counts from PR5. Legacy reports require complete - alignment and reconciled totals before claiming full coverage. + Counts must reconcile with each recording's total independently of + alignment. Missing or malformed inventories cannot establish event + differences and are never reconstructed from aligned operations. Parameters ---------- @@ -897,47 +904,22 @@ def event_inventory(data: dict) -> dict: Returns ------- dict - Count coverage, per-side inventories and event-type - differences. + Count coverage, per-side inventories and event-type differences. """ counts = {side: Counter() for side in SIDES} expected = {side: _at(data, side, "event_count") for side in SIDES} - independent = all(isinstance(_at(data, s, "event_counts"), dict) - for s in SIDES) - complete = independent or data["alignment"].get("status") == "complete" + complete = True for side in SIDES: - if independent: - raw = data[side]["event_counts"] - if all(isinstance(k, str) and type(v) is int and v >= 0 - for k, v in raw.items()): - counts[side].update(raw) - else: - complete = False - if sum(counts[side].values()) != expected[side]: - complete = False - continue - outside = _at(data, side, "outside_commands", "event_counts") - if not isinstance(outside, dict): + raw = _at(data, side, "event_counts") + if not isinstance(raw, dict) or not all( + isinstance(k, str) and type(v) is int and v >= 0 + for k, v in raw.items()): complete = False - for name, count in _dict(outside).items(): - if type(count) is int and count >= 0: - counts[side][name] += count - else: - complete = False - for op in data["operations"]: - for stage in _list(op.get("stages")): - record = stage.get(side) - if record is None: - continue - name = stage.get("event_type") - count = _at(record, "count") - if (not isinstance(name, str) or type(count) is not int - or count < 0): - complete = False - continue - counts[side][name] += count - if sum(counts[side].values()) != expected[side]: + continue + counts[side].update(raw) + if (type(expected[side]) is not int or + sum(counts[side].values()) != expected[side]): complete = False differences = [] if complete: @@ -952,8 +934,49 @@ def event_inventory(data: dict) -> dict: "differences": differences} +def _local_trace_data(root): + """Decode local diagnostics through the authoritative recording reader. + + Parameters + ---------- + root: pathlib.Path or None + Explicit local workspace directory. + + Returns + ------- + dict + Decoded events, readable issues and event-specific decoding failures. + Partial recordings remain inspectable, with all issues retained. + + """ + empty = {"events": [], "errors": [], "invalid": set()} + if root is None: + empty["errors"].append("Local workspace unavailable.") + return empty + try: + root = Path(root) + trace_dir = root / "logs" / "traces" + if (root.is_symlink() or (root / "logs").is_symlink() + or trace_dir.is_symlink() or not trace_dir.is_dir()): + raise ValueError("Local trace directory unavailable.") + recording = read_recording(root) + except (OSError, ValueError, TypeError, RecursionError) as error: + empty["errors"].append(str(error)) + return empty + errors = [] + invalid = set() + for issue in recording.issues: + location = issue.path or "workspace" + if issue.sequence is not None: + location += f" (sequence {issue.sequence})" + invalid.add((issue.path, issue.sequence)) + errors.append(f"{location}: {issue.code}: {issue.message}") + return {"events": recording.events, "errors": errors, + "invalid": invalid} + + def _local_events(root, kinds): - """Read local trace nodes of selected types, including merged ends. + """Read resolved local events of selected types, including merged ends. Parameters ---------- @@ -965,49 +988,38 @@ def _local_events(root, kinds): Returns ------- dict or None - Local events and read errors, or None for an omitted root. + Local events and decoding issues, or None for an omitted root. + Failed payloads remain labelled as unverified details. Other decoder + passes may have expanded independent fields, so these are not + claimed to be the raw stored payload or a verified observation. """ if root is None: return None - root = Path(root) - trace_dir = root / "logs" / "traces" - if (root.is_symlink() or (root / "logs").is_symlink() or - trace_dir.is_symlink() or not trace_dir.is_dir()): - return {"error": "Local trace directory unavailable."} - records, errors = [], [] - # Include archived conversation traces, but never follow links or - # read unrelated JSON outside the trace tree. - for path in sorted(trace_dir.rglob("*.json")): - if path.name.startswith("."): + local = _local_trace_data(root) + records = [] + for event in local["events"]: + if event.event_type not in kinds: continue - try: - relative = path.relative_to(root).as_posix() - safe = _trace_path(root, relative) - trace = json.loads(safe.read_text(encoding="utf-8")) - for node in _trace_events(trace): - for key in ("event", "completion"): - meta = _dict(node.get(key)) - if meta.get("event_type") in kinds: - record = {"path": relative, "metadata": meta} - if key == "event": - record.update(details=node.get("details"), - exact_content=node.get( - "exact_content")) - records.append(record) - except (OSError, ValueError, TypeError, AttributeError) as error: - errors.append(f"{path.name}: {error}") - records.sort(key=lambda row: row["metadata"].get("sequence", 0)) - return {"events": records, "errors": errors} + record = {"path": event.path, "location": event.location, + "metadata": event.metadata, + "exact_content": event.exact_content} + if (event.path, event.sequence) in local["invalid"]: + record.update(details=None, unverified_details=event.details) + else: + record["details"] = event.details + records.append(record) + return {"events": records, "errors": local["errors"]} def event_inventory_html(data: dict, *, original=None, replayed=None, include_details: bool = False) -> str: """Render reconciled event counts and optional local trace details. - Local event text is for inspection only: it is not hash-verified or - used to modify the saved comparison metrics. Events of a changed type - are listed on both sides without claiming individual event pairing. + Local references are verified and expanded by the recording reader. + Event text is not verified against the saved report and never changes + its metrics. Events of a changed type are listed on both sides without + claiming individual event pairing. Decoding issues remain visible. Parameters ---------- @@ -1034,7 +1046,8 @@ def event_inventory_html(data: dict, *, original=None, replayed=None, sum(result["counts"][side].values())) for side in SIDES]) if not result["complete"]: return _wrap(body + "

Complete event inventory unavailable; " - "do not interpret partial counts as differences.

") + "do not interpret partial counts as differences. " + "Regenerate the comparison report.

") differences = result["differences"] if differences: body += _table(("Event type", "Original", "Replay", "Delta"), [ @@ -1086,7 +1099,7 @@ def _release_measurements(data: dict) -> dict: Parameters ---------- data: dict - Native comparison snapshot, possibly a partial or older report. + Native comparison snapshot, possibly from an incomplete recording. Returns ------- @@ -1792,47 +1805,14 @@ def _stages(op): for x in _list(op.get("stages"))]) -def _trace_path(root, relative): - """Resolve only nonlinked local JSON files under logs/traces. - - Parameters - ---------- - root: pathlib.Path - Explicit local repository or workspace directory. - relative: str - Workspace-relative recorded trace or artifact path. - - Returns - ------- - pathlib.Path - Validated local trace path. - - """ - if root is None or not isinstance(relative, str): - raise ValueError("Local workspace or trace path unavailable.") - root = Path(root) - path = Path(relative) - if (root.is_symlink() or not root.is_dir() or path.is_absolute() - or len(path.parts) < 3 or path.parts[:2] != ("logs", "traces") - or ".." in path.parts or path.suffix.lower() != ".json"): - raise ValueError("Unsafe or unavailable local trace path.") - current = root - for part in path.parts: - current = current / part - if current.is_symlink(): - raise ValueError("Linked trace path rejected.") - if not current.is_file(): - raise ValueError("Local trace file unavailable.") - return current - - def _trace_events(data): - """Yield stored event nodes from the hierarchical trace, not content. + """Yield raw stored nodes for explicit hierarchy inspection only. Parameters ---------- data: dict - Decoded local hierarchical trace JSON. + Decoded local hierarchical trace JSON. Compact references remain + raw; semantic analysis uses ``read_recording`` instead. """ def visit(value): @@ -1864,7 +1844,7 @@ def visit(value): def _trace_index(root, relative, cache): - """Index the reported conversation trace and optional project trace. + """Index verified events from the requested and shared project traces. Parameters ---------- @@ -1873,31 +1853,40 @@ def _trace_index(root, relative, cache): relative: str Workspace-relative recorded trace or artifact path. cache: dict - Per-render local trace index cache. + Per-render local recording and trace index cache. Returns ------- dict - Local trace nodes indexed by sequence. + Event nodes indexed by sequence and all local decoding issues. + A render reads each workspace once, across conversation lookups. """ relative = relative if isinstance(relative, str) else None - key = (str(root), relative) + key = ("index", str(root), relative) if key in cache: return cache[key] + recording_key = ("recording", str(root)) + if recording_key not in cache: + cache[recording_key] = _local_trace_data(root) + local = cache[recording_key] index = {} - paths = [relative, "logs/traces/project.json"] - for path in dict.fromkeys(paths): - try: - file = _trace_path(root, path) - data = json.loads(file.read_text(encoding="utf-8")) - for node in _trace_events(data): - meta = node["event"] - index.setdefault(meta["sequence"], []).append(node) - except (OSError, ValueError, TypeError, AttributeError): + paths = {relative, "logs/traces/project.json"} + sequences = {event.sequence for event in local["events"] + if event.path in paths} + # Keep competing allocations even in another conversation: a project + # sequence must identify one event, not merely one event in this pane. + for event in local["events"]: + if event.sequence not in sequences: continue - cache[key] = index - return index + node = {"event": event.metadata, "details": event.details, + "exact_content": event.exact_content} + if (event.path, event.sequence) in local["invalid"]: + node["invalid"] = True + index.setdefault(event.sequence, []).append(node) + result = {"events": index, "errors": local["errors"]} + cache[key] = result + return result def _exact_model_text(row, field, index): @@ -1910,7 +1899,7 @@ def _exact_model_text(row, field, index): field: str Recorded field to inspect. index: dict - Trace nodes keyed by project event sequence. + Trace nodes keyed by project event sequence and local read issues. Returns ------- @@ -1925,10 +1914,12 @@ def _exact_model_text(row, field, index): digest = _at(row, field + "_sha256") if type(sequence) is not int or not isinstance(digest, str): return None, "No exact artifact recorded in the report." - events = index.get(sequence, []) + events = index["events"].get(sequence, []) if len(events) != 1: return None, "Local trace event missing or ambiguous." node = events[0] + if node.get("invalid"): + return None, "Local trace event failed decoding or verification." if _at(node, "event", "event_type") != "llm.call." + key: return None, "Local event type does not match the report." value = _at(node, "exact_content", artifact, "value") @@ -1986,9 +1977,13 @@ def _model_calls(op, roots, cache, include_text): q.get(side + "_trace"), cache) value, note = _exact_model_text(row.get(side), field, index) - panes.append(f'

{_e(note)}

' - + (f'
{_e(value)}
' - if value is not None else "")) + pane = f'

{_e(note)}

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

No aligned model-call records.

" @@ -2460,7 +2455,8 @@ def analysis_markdown(data: dict, name: str = "Workspace") -> str: sum(events["counts"][side].values())) for side in SIDES]) if not events["complete"]: lines += ["Complete inventory unavailable; partial counts are not " - "interpreted as differences.", ""] + "interpreted as differences. Regenerate the comparison " + "report.", ""] elif events["differences"]: lines += _md_table(("Event type", "Original", "Replay", "Delta"), [ (r["event_type"], r["original"], r["replayed"], r["delta"]) diff --git a/kilin/system_testing/batch.py b/kilin/system_testing/batch.py index cd9be20f..828f08ee 100644 --- a/kilin/system_testing/batch.py +++ b/kilin/system_testing/batch.py @@ -555,8 +555,7 @@ def add(level, code, message, sequence=None, *, side=None): ("validation_warnings", "review")): for issue in workspace.get(field, []): severity = ("info" if issue.get("code") in ( - "recording.limit", "relocation.inferred", - "environment.difference") else level) + "recording.limit", "environment.difference") else level) add(severity, f'{side}.{issue.get("code")}', issue.get("message"), issue.get("sequence"), side=side) for issue in data.get("report_issues", []): diff --git a/kilin/system_testing/comparison.py b/kilin/system_testing/comparison.py index 426c32d8..a58871a3 100644 --- a/kilin/system_testing/comparison.py +++ b/kilin/system_testing/comparison.py @@ -61,7 +61,7 @@ __all__ = ["Comparison", "compare", "COMPARISON_FORMAT_VERSION"] -COMPARISON_FORMAT_VERSION: Final[int] = 1 +COMPARISON_FORMAT_VERSION: Final[int] = 2 @dataclass(frozen=True, slots=True) diff --git a/kilin/system_testing/replay.py b/kilin/system_testing/replay.py index 656d049e..259b6101 100644 --- a/kilin/system_testing/replay.py +++ b/kilin/system_testing/replay.py @@ -344,7 +344,7 @@ def _plugin_differences( Returns ------- list[ReplayDifference] - Known differences in the common command prefix. Missing historical + Known differences in the common command prefix. Unavailable identities are not inferred differences; comparison reports retain their explicit unknown status. diff --git a/kilin/system_testing/timeline.py b/kilin/system_testing/timeline.py index 70ef37bc..72be9d12 100644 --- a/kilin/system_testing/timeline.py +++ b/kilin/system_testing/timeline.py @@ -198,12 +198,11 @@ def _relocations(recording: Recording, Notes ----- - New recordings require matching rename markers when either marker is - present. Older recordings can establish a sibling rename through the - preceding and following opening configurations and independently - recorded trace paths, a complete close/open boundary, and unchanged - conversation identity. Persistent settings and source manifests are - checked separately by validation. Historical paths are never opened. + Require a matching request and completion for every internal reopen. + Corroborate their paths and conversation identity with independent + opening configurations, trace paths and close/open boundaries. + Persistent settings and source manifests are checked separately by + validation. Historical paths are never opened. """ events = recording.events @@ -267,29 +266,27 @@ def _relocations(recording: Recording, or (e.event_type == "gui.project.rename.completed" and op.end_sequence < e.sequence < upper))] + request = one(relevant, "gui.project.rename.requested") + result = one(relevant, "gui.project.rename.completed") + identity = request.details.get("rename_id") + if (not isinstance(identity, str) or not identity or + identity in identities or + request.path != _PROJECT or result.path != _PROJECT or + not lower < request.sequence < close.start_sequence < + op.start_sequence <= op.end_sequence < + result.sequence < upper or + request.details != result.details or + request.details.get("conversation_id") != active or + _historical_directory(request.details.get( + "source_directory")) != source or + _historical_directory(request.details.get( + "destination_directory")) != destination): + raise ValueError("Uncorrelated project rename markers.") + consumed.update((request.sequence, result.sequence)) + identities.add(identity) relocation = {"source_directory": str(source), "destination_directory": str(destination), - "provenance": "inferred"} - if relevant: - request = one(relevant, "gui.project.rename.requested") - result = one(relevant, "gui.project.rename.completed") - identity = request.details.get("rename_id") - if (not isinstance(identity, str) or not identity or - identity in identities or len(relevant) != 2 or - request.path != _PROJECT or result.path != _PROJECT or - not lower < request.sequence < close.start_sequence < - op.start_sequence <= op.end_sequence < - result.sequence < upper or - request.details != result.details or - request.details.get("conversation_id") != active or - _historical_directory(request.details.get( - "source_directory")) != source or - _historical_directory(request.details.get( - "destination_directory")) != destination): - raise ValueError("Uncorrelated project rename markers.") - consumed.update((request.sequence, result.sequence)) - identities.add(identity) - relocation.update(provenance="recorded", rename_id=identity) + "provenance": "recorded", "rename_id": identity} operations[i] = replace(op, request={ **op.request, "requested_conversation_id": active, "relocation": relocation, diff --git a/kilin/system_testing/traces.py b/kilin/system_testing/traces.py index b329a885..73743e70 100644 --- a/kilin/system_testing/traces.py +++ b/kilin/system_testing/traces.py @@ -5,7 +5,7 @@ - Decode only the diagnostic hierarchy, including compact span completions. - Inspect active and archived conversations without silent discovery skips. - Preserve raw event identity and report malformed records without repair. -- Expand verified configuration references for downstream consumers. +- Expand verified configuration and source references for downstream readers. Module Structure ---------------- @@ -31,11 +31,18 @@ from pathlib import Path, PureWindowsPath from kilin._trace_configuration import ( + CONFIGURATION_CONTENT_REFERENCE, CONFIGURATION_EVENT, - CONFIGURATION_REFERENCE, + configuration_content_bytes, resolve_configuration_reference, ) from kilin._trace_project import TRACE_FORMAT_VERSION +from kilin._trace_snapshots import ( + SEMANTIC_SNAPSHOT_EVENTS, SEMANTIC_SNAPSHOT_REFERENCE, + SOURCE_SNAPSHOT_FIELDS, SOURCE_SNAPSHOT_REFERENCE, + resolve_semantic_reference, resolve_source_reference, + semantic_snapshot, source_snapshot, +) from kilin.conversation_format import conversation_state from kilin.conversations import _validated_metadata from kilin.conversation_memory.models import require_saved_turn_ids @@ -80,7 +87,7 @@ class TraceEvent: Original event metadata, not the readable span summary. details: dict Input, result, or sampled progress payload. Valid compact project - configuration observations expose their full resolved payload. + configuration and source observations expose their resolved payload. exact_content: dict Separately retained artifact contents, if present. @@ -496,7 +503,7 @@ def _resolve_configurations(recording: Recording) -> None: Notes ----- Track the most recent full project configuration, not the most recent - reference. Legacy full observations pass through unchanged. A reference + reference. Complete full observations pass through unchanged. A reference must belong to the same project trace and cannot target a later event, a different event type, an earlier superseded snapshot, or another reference. @@ -505,7 +512,14 @@ def _resolve_configurations(recording: Recording) -> None: latest = None for index, event in enumerate(recording.events): + compact = CONFIGURATION_CONTENT_REFERENCE in event.details if event.event_type != CONFIGURATION_EVENT: + if compact: + recording.issue( + "configuration.reference", + "Reference is not a configuration observation.", + event.path, event.sequence, + ) continue # A duplicate allocation cannot identify a unique reference target. duplicate = ( @@ -515,11 +529,15 @@ def _resolve_configurations(recording: Recording) -> None: and recording.events[index + 1].sequence == event.sequence) ) try: - if CONFIGURATION_REFERENCE not in event.details: + if not compact: if event.path == "logs/traces/project.json": if (not duplicate and event.metadata.get("status") == "completed" and "turn_id" not in event.metadata): + # An invalid full observation (including obsolete + # compact payloads) cannot supply historical state. + latest = None + configuration_content_bytes(event.details) latest = (event.sequence, event.details) else: latest = None @@ -541,6 +559,120 @@ def _resolve_configurations(recording: Recording) -> None: event.path, event.sequence) +def _resolve_semantic_snapshots(recording: Recording) -> None: + """Resolve shared manifests using only raw full project observations. + + Parameters + ---------- + recording: Recording + Globally ordered events. Invalid references add blocking issues; + no source file, semantic manifest or trace is modified. + + Notes + ----- + Resolve before same-type source groups so a previously compact opening + can never become an implicit reference target. Only the exact manifest + is shared; revision, provenance and command outcome stay inline. + + """ + + latest = None + for index, event in enumerate(recording.events): + kind = event.event_type + compact = SEMANTIC_SNAPSHOT_REFERENCE in event.details + if kind not in SEMANTIC_SNAPSHOT_EVENTS and not compact: + continue + duplicate = ( + (index > 0 + and recording.events[index - 1].sequence == event.sequence) + or (index + 1 < len(recording.events) + and recording.events[index + 1].sequence == event.sequence) + ) + project = (event.path == "logs/traces/project.json" + and "turn_id" not in event.metadata + and event.location.endswith("/event")) + eligible = (project and not duplicate + and event.metadata.get("status") == "completed") + if not compact: + if project and SOURCE_SNAPSHOT_REFERENCE not in event.details: + latest = None + if eligible: + try: + semantic_snapshot(kind, event.details) + except ValueError: + pass + else: + latest = (event.sequence, kind, event.details) + continue + try: + if not eligible: + raise ValueError("Reference is not a unique project event.") + details = resolve_semantic_reference( + kind, event.details, event.sequence, latest, + ) + recording.events[index] = replace(event, details=details) + except (ValueError, TypeError, RecursionError) as error: + recording.issue("semantic_snapshot.reference", str(error), + event.path, event.sequence) + + +def _resolve_source_snapshots(recording: Recording) -> None: + """Expand source observations before validation and replay. + + Parameters + ---------- + recording: Recording + Events in global sequence order. Invalid references are blocking + issues; the original files are never changed. + + Notes + ----- + Candidates are independent for each supported event type. A full failed + or incomplete observation resets its candidate. References never become + candidates, and invalid references cannot use current workspace data. + + """ + + latest = {} + for index, event in enumerate(recording.events): + kind = event.event_type + compact = SOURCE_SNAPSHOT_REFERENCE in event.details + if kind not in SOURCE_SNAPSHOT_FIELDS and not compact: + continue + duplicate = ( + (index > 0 + and recording.events[index - 1].sequence == event.sequence) + or (index + 1 < len(recording.events) + and recording.events[index + 1].sequence == event.sequence) + ) + project = (event.path == "logs/traces/project.json" + and "turn_id" not in event.metadata + and event.location.endswith("/event")) + eligible = (project and not duplicate + and event.metadata.get("status") == "completed") + if not compact: + if project: + latest.pop(kind, None) + if eligible: + try: + source_snapshot(kind, event.details) + except ValueError: + pass + else: + latest[kind] = (event.sequence, event.details) + continue + try: + if not eligible: + raise ValueError("Reference is not a unique project event.") + details = resolve_source_reference( + kind, event.details, event.sequence, latest.get(kind), + ) + recording.events[index] = replace(event, details=details) + except (ValueError, TypeError, RecursionError) as error: + recording.issue("source_snapshot.reference", str(error), + event.path, event.sequence) + + def read_recording(root: Path) -> Recording: """Read the project counter and all trace documents independently. @@ -585,4 +717,6 @@ def read_recording(root: Path) -> Recording: recording.issue("trace.invalid", str(error), path) recording.events.sort(key=lambda event: event.sequence) _resolve_configurations(recording) + _resolve_semantic_snapshots(recording) + _resolve_source_snapshots(recording) return recording diff --git a/kilin/system_testing/validation.py b/kilin/system_testing/validation.py index 4b4e341c..635edcf8 100644 --- a/kilin/system_testing/validation.py +++ b/kilin/system_testing/validation.py @@ -23,7 +23,7 @@ from __future__ import annotations from configparser import ConfigParser, Error as ConfigError -from dataclasses import asdict, dataclass, field, replace +from dataclasses import asdict, dataclass, field from hashlib import sha256 import json import os @@ -41,16 +41,11 @@ ) from kilin.project import _read_project from kilin.repository import _manifest_files -from kilin.source_manifest import ( - SOURCE_MANIFEST_FILE, SourceManifest, SourceRole, - _read_manifest_file, _serialize, -) -from kilin._source_manifest import parse_manifest from kilin.workspace import SOURCE_MANIFEST_VERSION, _read_records from ._filesystem import is_incidental_metadata from ._plugin_provenance import plugin_observations -from ._semantic_replay import PREFIX, validate_semantic_history +from ._semantic_replay import validate_semantic_history from .timeline import TimelineOperation, build_timeline, one from .traces import ( Recording, TraceEvent, ValidationIssue, read_json, safe_path, @@ -1487,131 +1482,6 @@ def _environment_warnings(recording: Recording) -> list[ValidationIssue]: for message in sorted(differences)] -def _default_only_organization(manifest: SourceManifest) -> bool: - """Test whether source organization has no semantic choices to replay. - - Parameters - ---------- - manifest: SourceManifest - Validated saved or recorded semantic state. - - Returns - ------- - bool - Only untouched default assignments, without semantic graph edits. - - """ - return not (manifest.relations or manifest.suppressed_automatic - or manifest.unresolved or any( - item.origin != "default" or item.role != - manifest.organization.declaration.default_role - for item in manifest.files - )) - - -def _check_source_organization(recording: Recording) -> None: - """Validate additive default-only histories from pre-PR14 recordings. - - Parameters - ---------- - recording: Recording - Closed reference workspace and ordered decoded events. - - Notes - ----- - Lifecycle-only default additions are redundant with the validated - physical creation/import history. Verify their exact revision chain; - do not infer an unrecorded edit, detector adoption or relationship. - Nontrivial histories without correlated commands remain unsupported. - - """ - lifecycle = [] - initial = None - for event in recording.events: - if event.event_type == "source_organization.committed": - recording.issue( - "source.organization.unsupported", - "Semantic source mutations lack correlated replay commands.", - event.path, event.sequence, - ) - elif event.event_type == "source_organization.reconciled": - lifecycle.append(event) - elif (initial is None and not lifecycle and event.event_type in - ("index.check.completed", "index.empty")): - initial = event.details.get("source_manifest") - try: - path = safe_path(recording.root, SOURCE_MANIFEST_FILE) - except (ValueError, OSError) as error: - recording.issue("source.organization.invalid", str(error), - SOURCE_MANIFEST_FILE) - return - try: - if not path.exists() and not path.is_symlink(): - if lifecycle: - raise ValueError("Recorded source organization is missing.") - return - try: - snapshot = _read_manifest_file(path) - except (ValueError, OSError) as error: - recording.issue("source.organization.invalid", str(error), - SOURCE_MANIFEST_FILE) - return - manifest = snapshot.manifest - if not _default_only_organization(manifest): - raise ValueError("Edited source organization is not replayable.") - if not lifecycle and manifest.revision == 0: - return - if not lifecycle or initial is None: - raise ValueError("Source organization history is incomplete.") - first = parse_manifest(lifecycle[0].details["source_organization"]) - default = first.organization.declaration.default_role - previous = replace(first, revision=0, files=tuple( - SourceRole(name, default, "default") - for name in sorted(_manifest_files(initial)) - )) - if not _default_only_organization(previous): - raise ValueError("Nondefault initial organization is unsupported.") - indexed_names = set(_manifest_files(initial)) - for event in recording.events: - if event.event_type in ("index.check.completed", "index.empty"): - indexed_names = set(_manifest_files( - event.details.get("source_manifest") - )) - if indexed_names != {item.path for item in previous.files}: - raise ValueError( - "Source organization differs from indexed selection." - ) - if event.event_type != "source_organization.reconciled": - continue - data = event.details - state = parse_manifest(data["source_organization"]) - old_digest = sha256(_serialize(previous).encode("utf-8")) - new_digest = sha256(_serialize(state).encode("utf-8")) - if ( - not _default_only_organization(state) - or state.organization != previous.organization - or state.source_root != previous.source_root - or not set(previous.files) < set(state.files) - or state.revision != previous.revision + 1 - or data.get("previous_revision") != previous.revision - or data.get("revision") != state.revision - or data.get("previous_sha256") != old_digest.hexdigest() - or data.get("sha256") != new_digest.hexdigest() - ): - raise ValueError("Nonadditive source organization history.") - previous = state - if indexed_names != {item.path for item in previous.files}: - raise ValueError( - "Source organization has no final physical index checkpoint." - ) - if (manifest != previous or - snapshot.sha256 != lifecycle[-1].details.get("sha256")): - raise ValueError("Saved organization differs from its history.") - except (ValueError, OSError, KeyError, TypeError) as error: - recording.issue("source.organization.unsupported", str(error), - SOURCE_MANIFEST_FILE) - - def validate_recording(recording: Recording) -> ValidationReport: """Collect structural, chronological and durable-state inconsistencies. @@ -1629,12 +1499,7 @@ def validate_recording(recording: Recording) -> ValidationReport: """ _sequence_checks(recording) operations = build_timeline(recording) - if any(event.event_type.startswith(PREFIX) or - "source_organization_revision" in event.details - for event in recording.events): - validate_semantic_history(recording, operations) - else: - _check_source_organization(recording) + validate_semantic_history(recording, operations) creations = [op for op in operations if op.kind == "create_project"] if (len(creations) != 1 or not operations or operations[0].kind != "create_project"): @@ -1693,13 +1558,6 @@ def validate_recording(recording: Recording) -> ValidationReport: "workspace. Unrecorded actions and edits restored before observation " "cannot always be detected. Model availability is not checked." )] - warnings.extend(ValidationIssue( - "relocation.inferred", - "Historical sibling rename inferred from independent trace paths; " - "explicit rename markers were not recorded.", - sequence=op.start_sequence, - ) for op in operations if op.request.get("relocation", {}).get( - "provenance") == "inferred") warnings.extend(_environment_warnings(recording)) return ValidationReport(recording.root, tuple(recording.issues), tuple(warnings), len(recording.events), diff --git a/kilin/tools/__init__.py b/kilin/tools/__init__.py index b4b836ba..3764dd68 100644 --- a/kilin/tools/__init__.py +++ b/kilin/tools/__init__.py @@ -13,9 +13,8 @@ modules, and templates. Every registered executable tool is a package. This package exposes the public tool API and planning vocabulary without -constructing the registry. Catalog queries and legacy convenience exports -load their definitions on demand. The plugin API version is independent -of the application version. +constructing the registry. Catalog queries load definitions on demand. +The plugin API version is independent of the application version. Key Features ------------ @@ -151,14 +150,10 @@ - ``TOOL_BATCH_CLASSIFY``, ``TOOL_BATCH_REVIEW``, ``TOOL_GENERATE_PAPER_SUMMARY``, ``TOOL_PROJECT_INVENTORY``, - ``TOOL_SCAN_AND_LIST``, ``TOOL_CHOICES``, and ``ToolName`` + ``TOOL_SCAN_AND_LIST`` and ``ToolName`` Registered tool names (from ``_registry``). -- ``TOOL_REGISTRY`` - - Map from each tool name to its registered tool. - - ``Tool`` and ``ToolUse`` One registered tool, and an intent's tool with validated settings. @@ -167,38 +162,10 @@ Validate an intent's ``tool`` object, and run it. -- ``CANDIDATES_MENTIONS``, ``CANDIDATE_CHOICES``, and ``CandidateSource`` - - How ``batch_classify`` collects the items it labels. - -- ``ClassifySettings`` - - Settings of ``batch_classify`` in a project type. - -- ``UNCLEAR`` and ``Label`` - - The always-offered category, and the category given to one mention. - -- ``MAX_TERMS`` - - Most terms ``scan_and_list`` scans for in one question. - -- ``ScanSettings`` - - Settings of ``scan_and_list`` in a project type. - -- ``Mention`` and ``MentionScan`` - - One occurrence of a term, and all mentions found. - -- ``scan_mentions`` - - Find every occurrence of the terms in the indexed text. - Examples -------- ->>> from kilin.tools import TOOL_REGISTRY, TOOL_SCAN_AND_LIST ->>> print(TOOL_REGISTRY[TOOL_SCAN_AND_LIST].summary) +>>> from kilin.tools import registered_tools, TOOL_SCAN_AND_LIST +>>> print(registered_tools()[TOOL_SCAN_AND_LIST].summary) List and count every exact mention of the question's terms. """ @@ -284,7 +251,6 @@ TOOL_GENERATE_PAPER_SUMMARY, TOOL_PROJECT_INVENTORY, TOOL_SCAN_AND_LIST, - _tool_registry, parse_tool, registered_tools, run_tool, @@ -338,34 +304,22 @@ "save_output_file", "reject_unknown", "tool_choices", - "CANDIDATES_MENTIONS", - "CANDIDATE_CHOICES", "CONFIRMATION_ALWAYS", "CONFIRMATION_CHOICES", "CONFIRMATION_NEVER", "CONFIRMATION_WHEN_LARGE", - "MAX_TERMS", "PLAN_CHOICE_CANCEL", "PLAN_CHOICE_CHOICES", "PLAN_CHOICE_CONTINUE", "PLAN_CHOICE_QUICK", "TOOL_BATCH_CLASSIFY", "TOOL_BATCH_REVIEW", - "TOOL_CHOICES", "TOOL_GENERATE_PAPER_SUMMARY", "TOOL_PROJECT_INVENTORY", - "TOOL_REGISTRY", "TOOL_SCAN_AND_LIST", - "UNCLEAR", - "CandidateSource", - "ClassifySettings", "ConfirmationPolicy", "EarlierTurn", - "Label", - "Mention", - "MentionScan", "PlanChoice", - "ScanSettings", "Tool", "ToolContext", "ToolSourceServices", @@ -380,24 +334,11 @@ "needs_confirmation", "parse_tool", "run_tool", - "scan_mentions", ] -# Preserve convenience imports without importing either tool during API import. -_LEGACY_TOOL_EXPORTS = { - "batch_classify": ( - "CANDIDATE_CHOICES", "CANDIDATES_MENTIONS", "UNCLEAR", - "CandidateSource", "ClassifySettings", "Label", - ), - "scan_and_list": ( - "MAX_TERMS", "Mention", "MentionScan", "ScanSettings", "scan_mentions", - ), -} - - def __getattr__(name: str) -> object: - """Resolve catalog and executable-tool exports only on demand. + """Resolve shared public helpers only on demand. Parameters ---------- @@ -422,11 +363,4 @@ def __getattr__(name: str) -> object: return getattr( import_module("kilin.tools._shared.outputs"), name ) - if name == "TOOL_REGISTRY": - return _tool_registry() - if name == "TOOL_CHOICES": - return tool_choices() - for module, names in _LEGACY_TOOL_EXPORTS.items(): - if name in names: - return getattr(import_module(f"kilin.tools.{module}"), name) raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/kilin/tools/_contract.py b/kilin/tools/_contract.py index 25b89bf3..03e4ce99 100644 --- a/kilin/tools/_contract.py +++ b/kilin/tools/_contract.py @@ -383,6 +383,7 @@ class ToolContext: source_files: Callable[[], dict[pathlib.Path, int]] Every selected source file (as in the source manifest) with its size in bytes. This is intentionally the full physical inventory. + Required callback; returns an empty mapping without selected files. ask_router: Callable[[str, str, int], str] Asks the router model ``(system, prompt, max_new_tokens)`` with thinking off and greedy decoding; the conversation is untouched. @@ -435,7 +436,7 @@ class ToolContext: source_root: pathlib.Path | None, optional Saved project source directory. The selected-source reader rejects this path when it is outside the project workspace. Defaults to - ``None`` for legacy test contexts. + ``None`` when no source directory is supplied. model_attempt_count: Callable[[], int] | None, optional Cumulative number of internal answering-model generation attempts, including incomplete attempts and bounded recovery, for this tool diff --git a/kilin/tools/_registry.py b/kilin/tools/_registry.py index 717df3dc..4b363881 100644 --- a/kilin/tools/_registry.py +++ b/kilin/tools/_registry.py @@ -2,9 +2,10 @@ The registry is the controlled boundary between configuration and code. A project type names a tool (``"tool": {"name": "scan_and_list", ...}``); the -name must be in ``TOOL_REGISTRY``, and the tool's own ``parse_settings`` -checks the rest. Configuration never imports arbitrary Python paths, so a -project type file can choose among these tools but cannot add code. +name must be in ``registered_tools()``, and the tool's own +``parse_settings`` checks the rest. Configuration never imports arbitrary +Python paths, so a project type file can choose among these tools but +cannot add code. The registry is constructed on first access, not during module import. A tool may also declare resources to install in newly created projects; the core resolves and copies them, not the GUI. @@ -48,10 +49,6 @@ Canonical string values of the registered tool names. -- ``TOOL_CHOICES`` - - Ordered collection of the registered tool names. - - ``ToolName`` Type alias for the registered tool names. @@ -68,10 +65,6 @@ Explicit accessors for the lazily constructed runtime registry. -- ``TOOL_REGISTRY`` - - Deferred legacy export of the same registry. - - ``parse_tool`` Validate an intent's ``tool`` object. @@ -124,7 +117,6 @@ "TOOL_ASSISTANT_GUIDE", "TOOL_BATCH_CLASSIFY", "TOOL_BATCH_REVIEW", - "TOOL_CHOICES", "TOOL_FILTER_RESULTS", "TOOL_FIND_FACT", "TOOL_FIND_PASSAGES", @@ -133,7 +125,6 @@ "TOOL_PROJECT_INVENTORY", "TOOL_PROJECT_SUMMARY", "TOOL_REFERENCE_CHECK", - "TOOL_REGISTRY", "TOOL_SCAN_AND_LIST", "TOOL_SHOW_SOURCE", "TOOL_SUGGEST_REFERENCE", @@ -628,33 +619,6 @@ def tool_choices() -> tuple[ToolName, ...]: ) -def __getattr__(name: str) -> object: - """Resolve legacy registry exports without initializing on import. - - Parameters - ---------- - name: str - Requested module attribute. - - Returns - ------- - object - The requested deferred export. - - Raises - ------ - AttributeError - If the module does not provide the requested attribute. - - """ - - if name == "TOOL_REGISTRY": - return _tool_registry() - if name == "TOOL_CHOICES": - return tool_choices() - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - - def parse_tool(where: str, data: object) -> ToolUse: """Validate an intent's ``tool`` object. diff --git a/kilin/tools/_shared/source_access.py b/kilin/tools/_shared/source_access.py index df063095..253f637f 100644 --- a/kilin/tools/_shared/source_access.py +++ b/kilin/tools/_shared/source_access.py @@ -60,8 +60,8 @@ def selected_paths(context: ToolContext) -> frozenset[Path]: Parameters ---------- context: ToolContext - Tool services and selected source inventory. Legacy mock contexts - without ``source_files`` use their indexed paths. + Tool services with the required ``source_files`` inventory callback. + Scoped consumers use bound source services instead. Returns ------- @@ -69,12 +69,19 @@ def selected_paths(context: ToolContext) -> frozenset[Path]: Names authorized for the current project. An available but empty inventory remains empty and is not replaced by stale index data. + Raises + ------ + RuntimeError + If the host does not provide a callable source inventory. + """ inventory = getattr(context, "source_files", None) - if callable(inventory): - return frozenset(inventory()) - return frozenset(chunk.path for chunk in context.chunks) + if not callable(inventory): + raise RuntimeError( + "Source inventory requires ToolContext.source_files." + ) + return frozenset(inventory()) def optional_source_bytes( diff --git a/kilin/tools/project_summary/_documents.py b/kilin/tools/project_summary/_documents.py index 48517499..87a7b49a 100644 --- a/kilin/tools/project_summary/_documents.py +++ b/kilin/tools/project_summary/_documents.py @@ -36,10 +36,10 @@ The project's documents, optionally limited to some paths. -- ``document_excerpt`` +- ``prepare_excerpt`` - The text read from one physical document; ``prepare_excerpt`` also - retains the actual original passages of a logical group. + Bounded excerpt text and its original physical passages, for both + individual documents and logical groups. Examples -------- @@ -70,7 +70,6 @@ "group_documents", "physical_citations", "prepare_excerpt", - "document_excerpt", "project_documents", "query_words", ] @@ -404,21 +403,3 @@ def score(chunk: Chunk) -> int: parts.append(label + chunk.text.strip()) return DocumentExcerpt("\n\n".join(part for part in parts if part), tuple(chosen)) - - -def document_excerpt( - document: ProjectDocument, words: set[str], tokens: int, -) -> str: - """Return the legacy physical-document excerpt text. - - Parameters - ---------- - document: ProjectDocument - A physical document. - words: set[str] - Template topic words. - tokens: int - Approximate excerpt token budget. - - """ - return prepare_excerpt(document, words, tokens).text diff --git a/kilin/tools/project_summary/_mapping.py b/kilin/tools/project_summary/_mapping.py index e9c7cd69..420e312d 100644 --- a/kilin/tools/project_summary/_mapping.py +++ b/kilin/tools/project_summary/_mapping.py @@ -263,7 +263,7 @@ def map_prompt( document: ProjectDocument The document. excerpt: str - What is read from it (``document_excerpt``). + Text read from it (``prepare_excerpt(...).text``). Returns ------- diff --git a/kilin/trace_logging.py b/kilin/trace_logging.py index ac039a24..5c2cf305 100644 --- a/kilin/trace_logging.py +++ b/kilin/trace_logging.py @@ -144,12 +144,18 @@ import warnings from kilin.atomic_writes import atomic_write_text +from kilin._trace_json import trace_json_dumps from kilin._trace_configuration import CONFIGURATION_EVENT +from kilin._trace_snapshots import ( + SEMANTIC_SNAPSHOT_WRITERS, SOURCE_SNAPSHOT_FIELDS, +) from kilin._trace_project import ( TRACE_FORMAT_VERSION, ProjectTracePublisher, ProjectTraceSequence, compact_project_configuration, + compact_project_semantic_snapshot, + compact_project_source_snapshot, project_trace_directory, project_trace_publication, write_project_trace, @@ -558,8 +564,6 @@ def __init__( "trace.started", component="trace", data={ - # Historical fixed marker, not a configurable setting. - "mode": "forensic", "scope": self.scope, "output_path": str(self.output_path), "include_embedding_vectors": ( @@ -694,8 +698,8 @@ def emit( retains all supplied event types, including token diagnostics. Event sequencing is serialized within this logger. Progress and activity updates can be throttled; other events trigger a refresh. Effective - project configuration observations may reference an unchanged - persisted full snapshot. Arbitrary payload content is not + project configuration and source observations may reference unchanged + persisted snapshot fields. Arbitrary payload content is not automatically redacted. """ @@ -713,12 +717,14 @@ def emit( return if span_id is None: span_id = self._active_span_id.get() - # Only configuration observations need publication ordering - # in addition to the ordinary project-wide allocation order. + # Snapshot references must follow publication order as well as + # project-wide allocation order. publication = ( project_trace_publication(self.readable_path) if self.scope == "project" - and normalized_event_type == CONFIGURATION_EVENT + and (normalized_event_type == CONFIGURATION_EVENT + or normalized_event_type in SOURCE_SNAPSHOT_FIELDS + or normalized_event_type in SEMANTIC_SNAPSHOT_WRITERS) and turn_id is None else nullcontext(({}, None)) ) @@ -756,9 +762,21 @@ def emit( event["data"] = _json_value(dict(data or {})) if publish is not None: if status == "completed": - event["data"] = compact_project_configuration( - previous, event["data"], self._sequence - ) + if normalized_event_type == CONFIGURATION_EVENT: + event["data"] = compact_project_configuration( + previous, event["data"], self._sequence + ) + elif started_elapsed_ms is None: + compact = ( + compact_project_semantic_snapshot + if normalized_event_type in + SEMANTIC_SNAPSHOT_WRITERS else + compact_project_source_snapshot + ) + event["data"] = compact( + previous, normalized_event_type, + event["data"], self._sequence, + ) self._write_event(event, publish_project=publish) else: self._write_event(event) @@ -1203,7 +1221,7 @@ def _write_event( Structured event dictionary used for storage or readable projection. publish_project: ProjectTracePublisher or None, optional - Publisher for a configuration observation under an already held + Publisher for a snapshot observation under an already held project lease. Otherwise the ordinary write path is used. Notes @@ -1241,7 +1259,7 @@ def _write_readable_trace( Parameters ---------- publish_project: ProjectTracePublisher or None, optional - Publisher for a configuration observation whose project lease is + Publisher for a snapshot observation whose project lease is already held. Ordinary project writes acquire their own lease. Notes @@ -1343,7 +1361,7 @@ def _write_readable_trace( ) ) payload = {**metadata, "sessions": sessions} - content = json.dumps(payload, indent=2, ensure_ascii=False) + "\n" + content = trace_json_dumps(payload) + "\n" atomic_write_text(self.readable_path, content) self._pending_events = False @@ -1401,45 +1419,28 @@ def _readable_event( return readable def _artifact_content(self, reference: object) -> object: - """Resolve an inline or supported legacy file artifact. + """Return exact inline content without reading artifact files. Parameters ---------- reference: object - Inline artifact reference, or a legacy artifact-file reference - constrained to the output directory. + Inline artifact payload produced by ``artifact()``. Returns ------- object - Artifact content, or None for an unsupported, missing, unreadable, - or invalid legacy reference. + Inline content, or None when no inline content is available. Notes ----- - Inline content takes precedence. Legacy paths must resolve inside the - trace output directory. This is a compatibility read, not arbitrary - remote artifact retrieval. + Path-only payloads are not exact artifacts in the current format. + Never consult the filesystem to reconstruct historical content. """ if not isinstance(reference, Mapping): return None - if "inline_content" in reference: - return reference["inline_content"] - relative = reference.get("path") - if not isinstance(relative, str): - return None - try: - root = self.output_path.parent.resolve() - path = (root / relative).resolve(strict=True) - if not path.is_relative_to(root) or not path.is_file(): - return None - if reference.get("format") == "json": - return json.loads(path.read_text(encoding="utf-8")) - return path.read_text(encoding="utf-8") - except (OSError, ValueError, json.JSONDecodeError): - return None + return reference.get("inline_content") def _handle_io_failure(self, error: OSError) -> None: """Apply the configured policy after trace storage fails. diff --git a/kilin/workspace.py b/kilin/workspace.py index 3af2a379..23a4ebe7 100644 --- a/kilin/workspace.py +++ b/kilin/workspace.py @@ -114,7 +114,7 @@ -------- >>> import kilin >>> project = kilin.prepare_sources_workspace( -... ["/path/to/source_repository"], kilin.PROJECT_TYPE_IDS[0], +... ["/path/to/source_repository"], kilin.project_type_ids()[0], ... "/path/to/new_workspace", ... ) diff --git a/tests/kilin/gui/test__attachments_frontend.py b/tests/kilin/gui/test__attachments_frontend.py index ce68289b..386ae1fe 100644 --- a/tests/kilin/gui/test__attachments_frontend.py +++ b/tests/kilin/gui/test__attachments_frontend.py @@ -160,15 +160,11 @@ def test_attachments_flow_and_chips(self): assert.deepEqual(calls.map(([name]) => name), ["askQuestion"]); assert.equal(error.hidden, true); -// Splitting saved questions, also from older chats. +// Splitting saved questions uses only the current attachment grammar. assert.deepEqual(splitAttached("Plain?"), { question: "Plain?", files: [] }); assert.deepEqual(splitAttached(text).files, ["sources/CITATION.cff", "sources/old.pdf", "sources/data/"]); -assert.deepEqual( - splitAttached("Old?\n\nAttached paths to consider:\n- /Users/me/a.pdf"), - { question: "Old?", files: ["/Users/me/a.pdf"] }); - -// Chips: sources/ files are buttons that reveal; old paths only a name. +// Chips: managed sources are buttons that reveal their workspace entries. const bubble = element("div"); fillQuestion(bubble, `${text}`); assert.equal(bubble.children[0], "What does it cite?"); @@ -179,12 +175,33 @@ def test_attachments_flow_and_chips(self): assert.ok(chips.every((chip) => chip.tag === "button")); chips[0].listeners.click(); assert.deepEqual(revealed, ["sources/CITATION.cff"]); -const old = element("div"); -fillQuestion(old, "Old?\n\nAttached paths to consider:\n- /Users/me/a.pdf"); -const [chip] = old.children[1].children; -assert.equal(chip.tag, "span"); -assert.equal(chip.textContent, "a.pdf"); -assert.equal(chip.title, "/Users/me/a.pdf"); +// A valid path is retained exactly and its name is set as text. +const special = "sources/nested/ & file.pdf"; +const escaped = element("div"); +fillQuestion(escaped, `Q?\n\nAttached files:\n- ${special}\n`); +const [chip] = escaped.children[1].children; +assert.equal(chip.tag, "button"); +assert.equal(chip.textContent, " & file.pdf"); +chip.listeners.click(); +assert.deepEqual(revealed, ["sources/CITATION.cff", special]); + +// Historical and malformed lists remain entirely literal, not actions. +for (const literal of [ + "Old?\n\nAttached paths to consider:\n- /Users/me/.pdf", + "Old?\n\nAttached paths to consider:\n- sources/a.pdf", + "Q?\n\nAttached files:\n- /Users/me/a.pdf", + "Q?\n\nAttached files:\n- sources/../a.pdf", + "Q?\n\nAttached files:\n- sources/..\\a.pdf", + "Q?\n\nAttached files:\n- sources//a.pdf", + "Q?\n\nAttached files:\n- sources/", + "Q?\n\nAttached files:\n- sources/a.pdf\n- /outside/b.pdf", +]) { + assert.deepEqual(splitAttached(literal), { question: literal, files: [] }); + const plain = element("div"); + fillQuestion(plain, literal); + assert.deepEqual(plain.children, [literal]); +} +assert.deepEqual(revealed, ["sources/CITATION.cff", special]); console.log("attachments passed"); """ result = run_node(script) diff --git a/tests/kilin/gui/test__paths__storage_transition.py b/tests/kilin/gui/test__paths__storage_transition.py index 56180fdb..ecc3fd7b 100644 --- a/tests/kilin/gui/test__paths__storage_transition.py +++ b/tests/kilin/gui/test__paths__storage_transition.py @@ -1,4 +1,4 @@ -"""Verify platform Documents defaults and previous-project discovery. +"""Verify platform Documents defaults and explicit project selection. The tests emulate installed KíLín on each operating system, without creating a GUI or changing the actual user's project files. @@ -22,8 +22,8 @@ from kilin.gui.engine import ChatEngine -class TestInstalledStorageTransition(unittest.TestCase): - """Keep defaults visible without losing previously stored projects.""" +class TestInstalledWorkspacePaths(unittest.TestCase): + """Resolve current defaults without searching former project folders.""" def setUp(self) -> None: """Isolate filesystem paths and environment for each test.""" @@ -47,31 +47,29 @@ def setUp(self) -> None: self.checkout_patch.start() self.addCleanup(self.checkout_patch.stop) - def _legacy(self, platform: str) -> Path: - """Create a pre-transition project with a valid saved profile. + def _existing_project(self, root: Path) -> Path: + """Create a project fixture in an explicitly supplied directory. Parameters ---------- - platform: str - Platform whose old installed-workspace directory is needed. + root: pathlib.Path + Projects directory to populate. Returns ------- pathlib.Path - Previously used workspace directory. + The created project profile. """ - with patch.object(_paths.sys, "platform", platform): - root = _paths._previous_installed_workspace_directory() - assert root is not None project = root / "existing" (project / "sources").mkdir(parents=True) - (project / "profile.ini").write_text( + profile = project / "profile.ini" + profile.write_text( "[project]\ntype_id = code\nsource = sources\n", encoding="utf-8", ) - return root + return profile def test_linux_localized_documents_uses_xdg_user_dirs(self) -> None: """Use a configured Documents directory, not its English name.""" @@ -142,33 +140,49 @@ def test_windows_redirected_documents_uses_shell_folder(self) -> None: self.home / "Documents/KíLín", ) - def test_legacy_candidate_is_found_on_all_platforms(self) -> None: - """Detect the old platform data directory without migrating it.""" + def test_former_defaults_are_not_scanned_or_modified(self) -> None: + """Use current Documents paths without discovering old projects.""" - for platform in ("darwin", "win32", "linux"): + former = { + "darwin": self.home / "Library/Application Support/kilin", + "win32": self.home / "AppData/Local/kilin", + "linux": self.home / ".local/share/kilin", + } + expected = self.home / "Documents/KíLín" + for platform, base in former.items(): with self.subTest(platform=platform): - root = self._legacy(platform) - contents = (root / "existing/profile.ini").read_bytes() - with patch.object(_paths.sys, "platform", platform): + profile = self._existing_project(base / "workspaces") + contents = profile.read_bytes() + with ( + patch.object(_paths.sys, "platform", platform), + patch.dict(sys.modules, {"winreg": None}), + patch.object(Path, "iterdir", side_effect=AssertionError( + "Project folders must not be scanned by resolution." + )), + ): self.assertEqual( - _paths.available_legacy_workspace_directory(), root + _paths.standard_workspace_directory(), expected ) - self.assertNotEqual( - _paths.standard_workspace_directory(), root + self.assertEqual( + _paths.default_workspace_directory(), expected ) - self.assertEqual( - (root / "existing/profile.ini").read_bytes(), contents - ) - self.assertFalse((root / "new-project").exists()) + self.assertEqual(profile.read_bytes(), contents) + self.assertFalse(expected.exists()) - def test_legacy_folder_reuse_discovers_existing_projects(self) -> None: - """Selecting the previous root preserves engine project discovery.""" + def test_explicit_previous_folder_remains_usable(self) -> None: + """A chosen former location is an ordinary saved projects folder.""" - root = self._legacy("darwin") + root = self.home / "Library/Application Support/kilin/workspaces" + profile = self._existing_project(root) + contents = profile.read_bytes() + with ( + patch.object(_paths.sys, "platform", "darwin"), + patch.object(_paths, "saved_workspace_folder", + return_value=str(root)), + ): + selected = _paths.default_workspace_directory() + self.assertEqual(selected, root) events: list[dict[str, object]] = [] - with patch.object(_paths.sys, "platform", "darwin"): - selected = _paths.available_legacy_workspace_directory() - self.assertIsNotNone(selected) engine = ChatEngine(selected, events.append) engine.list_saved_projects("") self.assertEqual(events[-1]["event"], "projects") @@ -176,65 +190,7 @@ def test_legacy_folder_reuse_discovers_existing_projects(self) -> None: [item["name"] for item in events[-1]["projects"]], ["existing"], ) - self.assertTrue((root / "existing/profile.ini").is_file()) - - def test_legacy_scan_ignores_symlinks_and_invalid_entries(self) -> None: - """Do not follow project symlinks or report unrelated directories.""" - - with patch.object(_paths.sys, "platform", "darwin"): - root = _paths._previous_installed_workspace_directory() - assert root is not None - root.mkdir(parents=True) - (root / "notes").mkdir() - self.assertIsNone( - _paths.available_legacy_workspace_directory() - ) - actual = self.root / "outside" - actual.mkdir() - (actual / "profile.ini").write_text("opaque", encoding="utf-8") - (root / "linked").symlink_to(actual, target_is_directory=True) - self.assertIsNone( - _paths.available_legacy_workspace_directory() - ) - old_root = root.rename(self.root / "moved") - root.symlink_to(old_root, target_is_directory=True) - self.assertIsNone( - _paths.available_legacy_workspace_directory() - ) - - def test_explicit_override_and_checkout_skip_legacy(self) -> None: - """Never override deliberate workspace selection or a checkout.""" - - root = self._legacy("darwin") - with patch.object(_paths.sys, "platform", "darwin"): - with patch.dict( - os.environ, - {"KILIN_WORKSPACES_DIR": str(self.root / "chosen")}, - ): - self.assertIsNone( - _paths.available_legacy_workspace_directory() - ) - with patch.object( - _paths, "_development_checkout", return_value=self.root - ): - self.assertIsNone( - _paths.available_legacy_workspace_directory() - ) - with patch.object( - _paths, "saved_workspace_folder", return_value=str(root) - ): - self.assertEqual(_paths.default_workspace_directory(), root) - - def test_legacy_directory_not_created_by_discovery(self) -> None: - """Read-only inspection does not construct directories or profiles.""" - - with patch.object(_paths.sys, "platform", "darwin"): - root = _paths._previous_installed_workspace_directory() - self.assertIsNotNone(root) - self.assertIsNone( - _paths.available_legacy_workspace_directory() - ) - self.assertFalse(root.exists()) + self.assertEqual(profile.read_bytes(), contents) if __name__ == "__main__": diff --git a/tests/kilin/gui/test__projects_folder_frontend.py b/tests/kilin/gui/test__projects_folder_frontend.py index cc37fef8..25689f70 100644 --- a/tests/kilin/gui/test__projects_folder_frontend.py +++ b/tests/kilin/gui/test__projects_folder_frontend.py @@ -39,13 +39,14 @@ def test_projects_folder_field_holds_the_projects(self): 'id="browse-workspace"', 'id="default-workspace"', 'id="workspace-note"', - 'id="use-legacy-workspace"', - 'id="legacy-workspace-note"', ): self.assertIn(part, project) self.assertNotIn("projects-folder", page) + self.assertNotIn("legacy-workspace", page) source = (_WEB / "app.js").read_text(encoding="utf-8") self.assertIn("bridge.requestProjectsFolder();", source) + self.assertNotIn("legacy-workspace", source) + self.assertNotIn("useLegacyProjectsFolder", source) # The open project's own path comes from the engine, not the field. self.assertNotIn('byId("workspace-path").value = data.project', source) self.assertIn( @@ -172,7 +173,6 @@ def test_folder_is_shown_and_switched_only_on_the_start_screen(self): "showProjectSettings", "projectName", "changeProjectsFolder", - "useLegacyProjectsFolder", "finishProjectsFolderSwitch", "projectPath", ): @@ -196,30 +196,26 @@ def test_folder_is_shown_and_switched_only_on_the_start_screen(self): "/Cloud/Projects is not available, so KíLín uses the default folder."); assert.ok(shown("workspace-note")); -// The previous project directory is offered but never chosen automatically. +// A saved folder is displayed normally, including a former location. calls.length = 0; showProjectsFolder({ - folder: "/repo/sandbox", saved: "", missing: false, - legacy: "/older/workspaces", + folder: "/older/workspaces", saved: "/older/workspaces", + standard: "/repo/sandbox", missing: false, }); -assert.ok(shown("legacy-workspace-choice")); -assert.match(byId("legacy-workspace-note").textContent, - /No project files will be moved/); +assert.equal(byId("workspace-path").value, "/older/workspaces"); +assert.equal(byId("default-workspace").disabled, false); +assert.ok(!shown("workspace-note")); assert.deepEqual(calls, []); -useLegacyProjectsFolder(); -assert.deepEqual(calls, ["useLegacyProjectsFolder"]); + +// Failed changes restore the controls and permit a manual retry. +changeProjectsFolder(true); +assert.deepEqual(calls, ["useDefaultProjectsFolder"]); assert.equal(busy, true); finishProjectsFolderSwitch("Could not save folder"); assert.equal(busy, false); assert.equal(switchingProjectsFolder, false); assert.equal(error.textContent, "Could not save folder"); calls.length = 0; -showProjectsFolder({ - folder: "/older/workspaces", saved: "/older/workspaces", - legacy: "/older/workspaces", missing: false, -}); -assert.ok(!shown("legacy-workspace-choice")); -showProjectsFolder({ folder: "/repo/sandbox", saved: "", missing: false }); // Use default on the start screen: Qt saves and restarts the engine. changeProjectsFolder(true); assert.deepEqual(calls, ["useDefaultProjectsFolder"]); @@ -235,6 +231,10 @@ def test_folder_is_shown_and_switched_only_on_the_start_screen(self): changeProjectsFolder(false); assert.deepEqual(calls, ["chooseProjectsFolder"]); assert.equal(busy, false); +assert.equal(switchingProjectsFolder, true); +finishProjectsFolderSwitch(); +assert.equal(switchingProjectsFolder, false); +assert.equal(busy, false); // With a project open the folder is read-only: the buttons stay but are // disabled, saying where to change it; a switch is refused with a notice. @@ -244,7 +244,6 @@ def test_folder_is_shown_and_switched_only_on_the_start_screen(self): showProjectSettings(); assert.equal(byId("browse-workspace").disabled, true); assert.equal(byId("default-workspace").disabled, true); -assert.equal(byId("use-legacy-workspace").disabled, true); assert.equal(byId("browse-workspace").title, "Change it from the start screen."); changeProjectsFolder(true); diff --git a/tests/kilin/gui/test__protocol.py b/tests/kilin/gui/test__protocol.py index 1e5bb553..84e4baec 100644 --- a/tests/kilin/gui/test__protocol.py +++ b/tests/kilin/gui/test__protocol.py @@ -1177,14 +1177,12 @@ def test_projects_folder_is_reported_and_chosen(self) -> None: return_value=Path("/sandbox"), ), patch.object( window, "saved_workspace_folder", return_value="/Gone/Projects", - ), patch.object( - window, "available_legacy_workspace_directory", return_value=None, ): self.bridge.requestProjectsFolder() self.assertEqual(json.loads(self.events[-1]), { "event": "projects_folder", "folder": str(Path("/sandbox")), "standard": str(Path("/sandbox")), "saved": "/Gone/Projects", - "legacy": "", "missing": True, + "missing": True, }) with patch.object( window, "standard_workspace_directory", @@ -1194,36 +1192,22 @@ def test_projects_folder_is_reported_and_chosen(self) -> None: self.assertEqual(chosen, [str(Path("/sandbox"))]) self.assertEqual(self.commands, []) - def test_previous_projects_choice_is_explicit_and_revalidated( - self, - ) -> None: - """Only a real legacy candidate can be passed to folder selection.""" + def test_browse_accepts_an_explicit_existing_folder(self) -> None: + """Browse can select any directory without a discovery feature.""" window = importlib.import_module("kilin.gui.window") - old = Path("/previous/kilin/workspaces") chosen: list[str] = [] self.bridge.projectsFolderChosen.connect(chosen.append) - with patch.object( - window, "available_legacy_workspace_directory", - return_value=old, - ): - self.bridge.requestProjectsFolder() - self.bridge.useLegacyProjectsFolder() - self.assertEqual( - json.loads(self.events[-1])["legacy"], str(old) - ) - self.assertEqual(chosen, [str(old)]) + with TemporaryDirectory() as temporary: + folder = Path(temporary).resolve() / "previous/workspaces" + folder.mkdir(parents=True) + with patch.object(window, "QFileDialog") as picker: + picker.getExistingDirectory.return_value = str(folder) + self.bridge.chooseProjectsFolder() + self.assertEqual(chosen, [str(folder)]) + self.assertEqual(list(folder.iterdir()), []) self.assertEqual(self.commands, []) - with patch.object( - window, "available_legacy_workspace_directory", - return_value=None, - ): - self.bridge.useLegacyProjectsFolder() - self.assertEqual(chosen, [str(old)]) - self.assertEqual( - json.loads(self.events[-1])["event"], - "projects_folder_failed", - ) + self.assertEqual(self.events, []) def test_cancelled_projects_folder_dialog_emits_its_own_event( self, diff --git a/tests/kilin/gui/test_engine__models.py b/tests/kilin/gui/test_engine__models.py index 6632f4f1..00a07ee3 100644 --- a/tests/kilin/gui/test_engine__models.py +++ b/tests/kilin/gui/test_engine__models.py @@ -23,6 +23,7 @@ from kilin.gui.preferences import default_effort_levels from kilin.project import open_project from kilin.project_files import list_project_files +from kilin.system_testing.traces import read_recording from kilin.workspace import prepare_sources_workspace @@ -203,7 +204,10 @@ def details(event): self.assertEqual(len(details("gui.project.closed")), 2) self.assertEqual(details("workspace.sync.file")[0]["path"], "sources/library/two.txt") - manifests = details("index.check.completed") + recording = read_recording(root) + self.assertFalse(recording.issues, recording.issues) + manifests = [event.details for event in recording.events + if event.event_type == "index.check.completed"] self.assertEqual(set(manifests[0]["source_manifest"]["files"]), {"library/one.txt"}) self.assertEqual( diff --git a/tests/kilin/gui/test_engine__recording.py b/tests/kilin/gui/test_engine__recording.py index 13e04f6c..e2362abf 100644 --- a/tests/kilin/gui/test_engine__recording.py +++ b/tests/kilin/gui/test_engine__recording.py @@ -27,6 +27,7 @@ from kilin.gui.engine import ChatEngine from kilin.project import open_project from kilin.project_type import RETRIEVAL_MODE_NONE +from kilin.system_testing.traces import read_recording from kilin.tools import ToolResult, ToolUse from kilin.tools._shared.planning import ( CONFIRMATION_ALWAYS, @@ -204,7 +205,11 @@ def test_semantic_commands_and_question_identity_are_recorded(self): self.assertEqual(started["preview_command_id"], proposed["command_id"]) self.assertEqual(started["command_id"], done["command_id"]) self.assertEqual(done["sha256"], committed["sha256"]) - self.assertEqual(done["source_organization"], + recording = read_recording(self.workspace) + self.assertFalse(recording.issues, recording.issues) + resolved = next(event.details for event in recording.events + if event.event_type == prefix + "apply.completed") + self.assertEqual(resolved["source_organization"], committed["source_organization"]) self.assertTrue(failed["conflict"]) observation = self.project_details(prefix + "observed") diff --git a/tests/kilin/gui/test_model_settings.py b/tests/kilin/gui/test_model_settings.py new file mode 100644 index 00000000..fc62805e --- /dev/null +++ b/tests/kilin/gui/test_model_settings.py @@ -0,0 +1,171 @@ +"""Verify current project model settings and obsolete-file isolation. + +Exercise real core-created projects and application preferences without +loading models, invoking Qt, or mutating packaged defaults. + +""" + +# 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 +import unittest +from unittest.mock import patch + +from kilin.gui import model_settings, preferences +from kilin.project import initialize_project, open_project +from kilin.runtime import BACKEND_MLX, BACKEND_TORCH + + +class TestProjectModelSettings(unittest.TestCase): + """Protect current initialization and saved-setting precedence.""" + + def setUp(self) -> None: + """Isolate preferences and projects from the user's filesystem.""" + + temporary = TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + override = patch.dict("os.environ", { + "KILIN_DEFAULTS_FILE": str(self.root / "preferences.json"), + }) + override.start() + self.addCleanup(override.stop) + + def test_initialize_current_settings_without_touching_sidecars(self): + """Ignore all obsolete input forms before and after initialization.""" + + backends = (BACKEND_MLX, BACKEND_TORCH) + levels = preferences.default_effort_levels(BACKEND_MLX) + levels[0] = {"name": "Preferred", "model": "example/preferred"} + prefs = preferences.write_defaults({ + "effort_levels": {BACKEND_MLX: levels}, + "search_depth": [1, 2, 3, 4, 5], + "router_models": {BACKEND_MLX: "example/router"}, + }) + old_levels = [ + {"name": "Old", "model": "example/old", "retrieval": i + 6} + for i in range(5) + ] + for name, old_effort in ( + ("explicit_depth", json.dumps({ + BACKEND_MLX: old_levels, "search_depth": [11] * 5, + "router": {BACKEND_MLX: "example/old-router"}, + })), + ("inferred_depth", json.dumps({BACKEND_MLX: old_levels})), + ("malformed", "{invalid"), + ): + with self.subTest(sidecar=name): + project = self.root / name + project.mkdir() + original = initialize_project(project, "code") + sidecars = { + project / "effort_levels.json": old_effort, + project / "model_choices.json": ( + "{invalid" if name == "malformed" else json.dumps({ + prefs["effort_levels"][BACKEND_TORCH][0]["model"]: + "example/old-replacement", + }) + ), + } + for path, contents in sidecars.items(): + path.write_text(contents, encoding="utf-8") + saved_files = {path: path.read_bytes() for path in sidecars} + profile_path = project / "profile.ini" + before = profile_path.read_bytes() + for backend in backends: + self.assertEqual( + model_settings.read_effort_levels(project, backend), + prefs["effort_levels"][backend], + ) + self.assertEqual(model_settings.read_search_depth(project), + prefs["search_depth"]) + self.assertEqual(profile_path.read_bytes(), before) + self.assertTrue(model_settings.save_project_settings(project)) + self.assertEqual(open_project(project).profile, + original.profile) + self._assert_saved_settings(project, prefs) + after = profile_path.read_bytes() + self.assertFalse(model_settings.save_project_settings(project)) + self.assertEqual(profile_path.read_bytes(), after) + self.assertEqual( + {path: path.read_bytes() for path in sidecars}, + saved_files, + ) + + def test_saved_settings_precede_defaults_and_partial_initialization(self): + """Initialize missing settings without replacing explicit choices.""" + + project = self.root / "partial" + project.mkdir() + initialize_project(project, "code") + levels = preferences.default_effort_levels(BACKEND_MLX) + levels[0] = {"name": "Saved", "model": "example/saved"} + model_settings.write_effort_levels(project, BACKEND_MLX, levels) + model_settings.write_router_model(project, BACKEND_TORCH, + "example/saved-router") + model_settings.write_search_depth(project, [6, 7, 8, 9, 10]) + effective = preferences.write_defaults({ + "search_depth": [1] * 5, + "router_models": {BACKEND_MLX: "example/initial-router"}, + }) + effective["effort_levels"][BACKEND_MLX] = levels + effective["router_models"][BACKEND_TORCH] = "example/saved-router" + effective["search_depth"] = [6, 7, 8, 9, 10] + self.assertTrue(model_settings.save_project_settings(project)) + self._assert_saved_settings(project, effective) + before = (project / "profile.ini").read_bytes() + new_levels = preferences.default_effort_levels(BACKEND_MLX) + new_levels[0] = {"name": "New", "model": "example/new"} + preferences.write_defaults({ + "search_depth": [2] * 5, + "router_models": {BACKEND_MLX: "example/new-router"}, + "effort_levels": {BACKEND_MLX: new_levels}, + }) + self.assertFalse(model_settings.save_project_settings(project)) + self._assert_saved_settings(project, effective) + self.assertEqual((project / "profile.ini").read_bytes(), before) + + def test_invalid_saved_settings_do_not_initialize_other_fields(self): + """Reject malformed present values before writing missing values.""" + + for index, section in enumerate(( + "[effort.torch]\nlevel1 = Broken | example/model\n", + "[router]\ntorch =\n", + "[search]\ndepth = 1, 2, 3, 4, 0\n", + )): + with self.subTest(section=section): + project = self.root / str(index) + project.mkdir() + initialize_project(project, "code") + path = project / "profile.ini" + with path.open("a", encoding="utf-8") as stream: + stream.write("\n" + section) + before = path.read_bytes() + with self.assertRaises(ValueError): + model_settings.save_project_settings(project) + self.assertEqual(path.read_bytes(), before) + + def _assert_saved_settings(self, project, expected): + """Compare the saved model and search configuration to its owner.""" + + for backend in (BACKEND_MLX, BACKEND_TORCH): + self.assertEqual( + model_settings.read_effort_levels(project, backend), + expected["effort_levels"][backend], + ) + self.assertEqual( + model_settings.read_router_model(project, backend), + expected["router_models"][backend], + ) + self.assertEqual(model_settings.read_search_depth(project), + expected["search_depth"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/gui/test_preferences.py b/tests/kilin/gui/test_preferences.py index 16fb3609..5fb5432e 100644 --- a/tests/kilin/gui/test_preferences.py +++ b/tests/kilin/gui/test_preferences.py @@ -128,7 +128,10 @@ def test_preferences_can_override_one_backend(self) -> None: def test_invalid_preferences_are_not_silently_replaced(self) -> None: """Preserve malformed data and identify the offending setting.""" + old_levels = preferences.default_effort_levels("mlx") + old_levels[0]["retrieval"] = 5 invalid = ( + json.dumps({"effort_levels": {"mlx": old_levels}}), "not JSON", "[]", '{"unrecognized": true}', @@ -160,6 +163,20 @@ def test_invalid_update_does_not_create_or_mutate_file(self) -> None: with self.assertRaises(ValueError): preferences.write_defaults({"router_models": {"bad": "id"}}) self.assertEqual(self.path.read_bytes(), original) + # A current preference update must not silently discard extra keys. + levels = preferences.default_effort_levels("mlx") + for record in ( + {"name": "Light"}, + dict(levels[0], retrieval=5), + dict(levels[0], unknown=True), + dict(levels[0], name="Light | deep"), + ): + with self.subTest(record=record): + with self.assertRaises(ValueError): + preferences.write_defaults({ + "effort_levels": {"mlx": [record, *levels[1:]]}, + }) + self.assertEqual(self.path.read_bytes(), original) def test_packaged_file_and_alias_cannot_be_write_targets(self) -> None: """Prevent direct and symbolic-link writes to shipped resources.""" diff --git a/tests/kilin/system_testing/test__batch_diagnostics.py b/tests/kilin/system_testing/test__batch_diagnostics.py index 67bb0bfd..246b8169 100644 --- a/tests/kilin/system_testing/test__batch_diagnostics.py +++ b/tests/kilin/system_testing/test__batch_diagnostics.py @@ -8,7 +8,8 @@ import unittest from kilin.system_testing.analysis import ( - batch_overview, event_inventory, question_explorer, + batch_overview, event_inventory, event_inventory_html, + question_explorer, _release_agreement_rows, _release_totals, ) from kilin.system_testing.batch import ( @@ -96,6 +97,39 @@ def test_outcome_transition_not_obscured_by_publication_hint(self): group = next(g for g in groups if g["code"] == "capability.changed") self.assertEqual(group["question_number"], 1) + def test_missing_independent_counts_are_not_reconstructed(self): + data = report() + # The old reconstruction would accept these reconciled stage counts. + for side in ("original", "replayed"): + del data[side]["event_counts"] + data[side]["outside_commands"] = {"event_counts": {"close": 1}} + data["operations"] = [{"original_sequence": 1, "stages": [{ + "event_type": "ask", "original": {"count": 1}, + "replayed": {"count": 1}}]}] + before = deepcopy(data) + inventory = event_inventory(data) + self.assertFalse(inventory["complete"]) + self.assertEqual(inventory["counts"], {"original": {}, "replayed": {}}) + self.assertEqual(inventory["differences"], []) + self.assertIn("Regenerate", event_inventory_html(data)) + self.assertIn("events.coverage", [i["code"] for i in + collect_issues(data, {})]) + self.assertEqual(data, before) + + def test_independent_inventory_requires_valid_counts_and_totals(self): + for counts, total in ((None, 2), ({"ask": True}, 1), + ({"ask": -1}, -1), ({"ask": 2.0}, 2), + ({1: 2}, 2), ({"ask": 2}, 1), + ({"ask": 2}, 2.0), ({"ask": 1}, True)): + with self.subTest(counts=counts, total=total): + data = report() + data["replayed"].update(event_counts=counts, + event_count=total) + inventory = event_inventory(data) + self.assertFalse(inventory["complete"]) + self.assertEqual(inventory["counts"]["original"], {"ask": 2}) + self.assertEqual(inventory["differences"], []) + def test_event_attribution_with_cancelling_counts(self): data = report() data["operations"] = [{"original_sequence": seq, "stages": [{ diff --git a/tests/kilin/system_testing/test__comparison_diagnostics.py b/tests/kilin/system_testing/test__comparison_diagnostics.py index 000648cb..c97e502d 100644 --- a/tests/kilin/system_testing/test__comparison_diagnostics.py +++ b/tests/kilin/system_testing/test__comparison_diagnostics.py @@ -70,15 +70,13 @@ def test_history_final_selection_is_separate(self): self.assertIsNone(row["original"]) self.assertTrue(row["issues"]) - def _prompt(self, record, *, text=" Saved text", stamp=None): - """Create the producer's memory header and selection record.""" - origins = ", ".join(f"{o['conversation_id']} turn {o['turn_number']}" - for o in record["origins"]) - timestamp = stamp or "2026-11-01T09:00:00+00:00" + def _prompt(self, record, *, text=" Saved text", header=None): + """Create the current memory header and selection record.""" + if header is None: + header = f"Memory {record['label']} | {record['role']} | Turn T1" content = ("Question: What?\n\nCONVERSATION MEMORY (previous " "discussion, NOT source evidence):\n\n" - f"Memory M1 | user | UUID {record['turn_uuid']} | " - f"{timestamp} | {origins}\n{text}") + f"{header}\n{text}") event = _event(2, "llm.call.input", {}, exact={ "01_structured_messages": {"value": [ {"role": "user", "content": content}]}}) @@ -88,18 +86,21 @@ def _prompt(self, record, *, text=" Saved text", stamp=None): def test_prompt_only_normalizes_corroborated_metadata(self): a, before = self._prompt(self.old) - b, after = self._prompt(self.new, stamp="2026-11-02T09:00:00+00:00") + b, after = self._prompt(self.new) left = structured_prompt(a, before, {"a": "a"}, {"old": "old", "branch": "branch"}) right = structured_prompt(b, after, {"b": "a"}, {"new": "old", "fork": "branch"}) - self.assertNotEqual(left["raw"], right["raw"]) + self.assertEqual(left["raw"], right["raw"]) + self.assertIsNotNone(left["normalized"]) self.assertEqual(left["normalized"], right["normalized"]) + self.assertEqual(left["headers"], 1) b, after = self._prompt(self.new, text=" Changed content") right = structured_prompt(b, after, {"b": "a"}, {"new": "old", "fork": "branch"}) + self.assertNotEqual(left["raw"], right["raw"]) self.assertNotEqual(left["normalized"], right["normalized"]) - b, after = self._prompt(self.new, stamp="invalid") + b, after = self._prompt(self.new, header="invalid header") right = structured_prompt(b, after, {"b": "a"}, {"new": "old", "fork": "branch"}) self.assertIsNone(right["normalized"]) @@ -107,29 +108,44 @@ def test_prompt_only_normalizes_corroborated_metadata(self): self.assertIsNone(structured_prompt( a, _op("old", a), {"a": "a"}, {"old": "old"})["normalized"]) - def test_local_memory_header_and_legacy_header_normalize_equally(self): + def test_legacy_memory_header_is_not_normalized(self): a, before = self._prompt(self.old) - b, after = self._prompt(self.new) - messages = b.exact_content["01_structured_messages"]["value"] - text = messages[0]["content"] - start = text.index("Memory M1 |") - end = text.index("\n", start) - messages[0]["content"] = ( - text[:start] + "Memory M1 | user | Turn T1" + text[end:] - ) + origins = ", ".join(f"{o['conversation_id']} turn {o['turn_number']}" + for o in self.new["origins"]) + header = (f"Memory M1 | user | UUID {self.new['turn_uuid']} | " + f"2026-11-02T09:00:00+00:00 | {origins}") + b, after = self._prompt(self.new, header=header) + original = deepcopy(b.exact_content) left = structured_prompt(a, before, {"a": "a"}, {"old": "old", "branch": "branch"}) right = structured_prompt(b, after, {"b": "a"}, {"new": "old", "fork": "branch"}) - self.assertEqual(left["normalized"], right["normalized"]) + self.assertIsNotNone(left["normalized"]) + self.assertIsNone(right["normalized"]) + self.assertIn("recorded format", right["issue"]) + self.assertIn(header, right["raw"]) self.assertNotEqual(left["raw"], right["raw"]) - messages[0]["content"] = messages[0]["content"].replace( - "Turn T1", "Turn T2" - ) - bad = structured_prompt(b, after, {"b": "a"}, - {"new": "old", "fork": "branch"}) - self.assertIsNone(bad["normalized"]) - self.assertTrue(bad["issue"]) + self.assertEqual(original, b.exact_content) + for header in ("Memory M1 | user | Turn T2", + "Memory M2 | user | Turn T1", + "Memory M1 | assistant | Turn T1"): + with self.subTest(header=header): + b, after = self._prompt(self.new, header=header) + bad = structured_prompt(b, after, {"b": "a"}, + {"new": "old", "fork": "branch"}) + self.assertIsNone(bad["normalized"]) + self.assertTrue(bad["issue"]) + + def test_equal_local_headers_do_not_erase_distinct_memory_identities(self): + a, before = self._prompt(self.old) + b, after = self._prompt(self.new) + left = structured_prompt(a, before, {"a": "a"}, + {"old": "old", "branch": "branch"}) + right = structured_prompt(b, after, {"b": "other"}, + {"new": "old", "fork": "branch"}) + self.assertEqual(left["raw"], right["raw"]) + self.assertIsNotNone(right["normalized"]) + self.assertNotEqual(left["normalized"], right["normalized"]) def test_timing_only_and_equal_failure(self): a = {"name": "summary", "status": "incomplete", "valid": False, diff --git a/tests/kilin/system_testing/test__plugin_provenance.py b/tests/kilin/system_testing/test__plugin_provenance.py index 8d35f1f2..6e994050 100644 --- a/tests/kilin/system_testing/test__plugin_provenance.py +++ b/tests/kilin/system_testing/test__plugin_provenance.py @@ -306,10 +306,12 @@ def test_unknown_invalid_and_one_sided_observations(self): known = _operation(_event("tool.run.started", { "name": _TOOL, "plugin": identity, }), kind="ask") - old = _operation(_event("tool.run.started", {"name": _TOOL}), - kind="ask") - self.assertEqual(compare_plugins(old, known)[0]["status"], "unknown") - self.assertEqual(_plugin_differences((old,), (known,)), []) + unknown = _operation(_event("tool.run.started", { + "name": _TOOL, "plugin": None, + }), kind="ask") + self.assertEqual(compare_plugins(unknown, known)[0]["status"], + "unknown") + self.assertEqual(_plugin_differences((unknown,), (known,)), []) self.assertEqual(compare_plugins(known, known)[0]["status"], "equal") self.assertEqual(compare_plugins(known, _operation(kind="ask"))[0][ "status"], "one_sided") @@ -321,9 +323,10 @@ def test_unknown_invalid_and_one_sided_observations(self): observation["identity"]["version"] = "changed" self.assertEqual(identity["version"], "1.0.0") - def test_legacy_activation_preserves_unknown_requirements(self): + def test_activation_preserves_explicitly_unknown_requirements(self): operation = _operation(_event("gui.project.configuration.effective", { "profile": {"type_id": _TYPE}, "tools": [{"name": _TOOL}], + "plugins": {"project_type": None, "tools": {_TOOL: None}}, })) items = plugin_observations(operation.events) self.assertEqual([x["name"] for x in items], [_TYPE, _TOOL]) @@ -338,3 +341,45 @@ def test_legacy_activation_preserves_unknown_requirements(self): return_value=()): with self.assertRaisesRegex(ValueError, _TOOL): preflight_plugins((operation,)) + + def test_missing_required_plugin_metadata_is_invalid(self): + cases = ( + ("gui.project.configuration.effective", { + "profile": {"type_id": _TYPE}, "tools": [{"name": _TOOL}], + }), + ("gui.project.configuration.effective", { + "profile": {"type_id": _TYPE}, "tools": [{"name": _TOOL}], + "plugins": {"project_type": None, "tools": {}}, + }), + ("gui.project.configuration.effective", { + "profile": {}, "tools": [], + "plugins": {"project_type": None, "tools": {}}, + }), + ("gui.project.configuration.effective", { + "profile": {"type_id": _TYPE}, "tools": [None], + "plugins": {"project_type": None, "tools": {}}, + }), + ("turn.settings.snapshot", {"project_type_plugin": None}), + ("tool.run.started", {"name": _TOOL}), + ("tool.run.started", {"plugin": None}), + ("tool.run.started", {"name": [], "plugin": None}), + ) + for kind, details in cases: + with self.subTest(kind=kind, details=details): + items = plugin_observations((_event(kind, details),)) + self.assertEqual(len(items), 1) + self.assertEqual(items[0]["status"], "invalid") + self.assertIsNone(items[0]["identity"]) + self.assertTrue(items[0]["error"]) + + def test_unavailable_turn_identity_remains_unknown(self): + # Current turn producers omit an unavailable project-type identity. + for data in ({"project_type_id": _TYPE}, { + "project_type_id": _TYPE, "project_type_plugin": None}): + with self.subTest(data=data): + items = plugin_observations(( + _event("turn.settings.snapshot", data), + )) + self.assertEqual(len(items), 1) + self.assertEqual(items[0]["status"], "unknown") + self.assertEqual(items[0]["name"], _TYPE) diff --git a/tests/kilin/system_testing/test_analysis__traces.py b/tests/kilin/system_testing/test_analysis__traces.py new file mode 100644 index 00000000..af1b47c6 --- /dev/null +++ b/tests/kilin/system_testing/test_analysis__traces.py @@ -0,0 +1,258 @@ +"""Keep local trace inspection consistent with verified recording readers.""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from copy import deepcopy +from hashlib import sha256 +import json +import unittest +from unittest.mock import patch + +from kilin._trace_configuration import ( + CONFIGURATION_EVENT, CONFIGURATION_CONTENT_REFERENCE, +) +from kilin.system_testing import analysis +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.test__batch_diagnostics import report + + +class TestLocalTraceInspection(unittest.TestCase): + """Exercise real writer output and corrupted copies without model calls.""" + + def setUp(self): + fixture = sources.TestSourceSnapshotRecording() + self.addCleanup(fixture.doCleanups) + fixture.setUp() + self.fixture = fixture + self.root = fixture.root + self.path = fixture.path + self.config = configurations._configuration(self.root) + logger = fixture._logger() + for _ in range(2): + logger.emit(CONFIGURATION_EVENT, component="fixture", + data=self.config) + for kind in sources.SOURCE_SNAPSHOT_FIELDS: + fixture._emit(logger, kind, sources.observation(kind)) + logger.close() + + def _write(self, payload): + self.path.write_text(json.dumps(payload), encoding="utf-8") + + def _model(self, name="conversation_a.json", text="Exact KíLín prompt"): + logger = self.fixture._logger(scope="conversation", name=name) + logger.emit("llm.call.input", component="fixture", data={ + "rendered_prompt_artifact": logger.artifact("prompt", text, + text=True), + }) + logger.close() + relative = logger.readable_path.relative_to(self.root).as_posix() + event = next(event for event in read_recording(self.root).events + if event.path == relative + and event.event_type == "llm.call.input") + row = {"input_sequence": event.sequence, + "prompt_sha256": sha256(text.encode("utf-8")).hexdigest()} + return relative, row, text + + def test_configuration_and_source_details_are_verified_and_read_only(self): + kinds = {CONFIGURATION_EVENT, *sources.SOURCE_SNAPSHOT_FIELDS} + before = {p: p.read_bytes() for p in self.root.rglob("*") + if p.is_file()} + recording = read_recording(self.root) + local = analysis._local_events(self.root, kinds) + self.assertEqual(local["errors"], []) + expected = [event for event in recording.events + if event.event_type in kinds] + self.assertEqual(len(local["events"]), 8) + for row, event in zip(local["events"], expected): + with self.subTest(sequence=event.sequence): + self.assertEqual(row, { + "path": event.path, "location": event.location, + "metadata": event.metadata, "details": event.details, + "exact_content": event.exact_content, + }) + raw = list(analysis._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() + for p in self.root.rglob("*") + if p.is_file()}) + + def test_failed_reference_is_labelled_unverified_and_never_repaired(self): + payload = self.fixture._raw() + node = sources.observations(payload, sources.SCAN)[-1] + node["details"][sources.REFERENCE]["sha256"] = "0" * 64 + self._write(payload) + # Current workspace content cannot repair historical observations. + (self.root / "source_manifest.json").write_text( + '{"new": "unrelated current manifest"}', encoding="utf-8", + ) + before = self.path.read_bytes() + local = analysis._local_events(self.root, {sources.SCAN}) + self.assertEqual(len(local["events"]), 2) + self.assertTrue(any("source_snapshot.reference" in issue + for issue in local["errors"])) + invalid = local["events"][-1] + self.assertIsNone(invalid["details"]) + self.assertEqual(invalid["unverified_details"], node["details"]) + self.assertEqual(invalid["metadata"], node["event"]) + self.assertEqual(self.path.read_bytes(), before) + + def test_partial_decoding_is_not_labelled_as_raw_or_verified(self): + payload = self.fixture._raw() + node = sources.observations(payload, sources.SCAN)[-1] + # Configuration validation rejects this reserved marker on a scan; + # the independent source decoder can still resolve the valid group. + node["details"][CONFIGURATION_CONTENT_REFERENCE] = { + "sequence": 1, "sha256": "0" * 64, + } + self._write(payload) + before = self.path.read_bytes() + local = analysis._local_events(self.root, {sources.SCAN}) + invalid = local["events"][-1] + self.assertIsNone(invalid["details"]) + self.assertNotIn("stored_details", invalid) + self.assertNotEqual(invalid["unverified_details"], node["details"]) + self.assertIn("selected_files", invalid["unverified_details"]) + self.assertTrue(any("configuration.reference" in error + for error in local["errors"])) + self.assertEqual(self.path.read_bytes(), before) + + def test_merged_completion_preserves_result_and_start_metadata(self): + logger = self.fixture._logger() + logger.emit("fixture.work.started", component="fixture", + status="started", span_id="span_fixture", + started_elapsed_ms=1.0, + data={"input": [1, 2]}) + logger.emit("fixture.work.completed", component="fixture", + span_id="span_fixture", started_elapsed_ms=1.0, + data={"result": "preserved"}) + logger.close() + local = analysis._local_events(self.root, { + "fixture.work.started", "fixture.work.completed", + }) + self.assertEqual(local["errors"], []) + first, last = local["events"] + self.assertEqual(first["metadata"]["status"], "started") + self.assertEqual(first["details"], {"input": [1, 2]}) + self.assertEqual(last["details"], {"result": "preserved"}) + self.assertTrue(last["location"].endswith("/completion")) + + def test_one_recording_load_serves_multiple_conversations_and_hashes(self): + relative, row, text = self._model() + other, other_row, other_text = self._model("conversation_b.json", + "Other exact prompt") + cache = {} + with patch.object(analysis, "read_recording", wraps=read_recording) \ + as reader: + first = analysis._trace_index(self.root, relative, cache) + second = analysis._trace_index(self.root, other, cache) + self.assertIs(first, analysis._trace_index(self.root, relative, + cache)) + self.assertEqual(reader.call_count, 1) + self.assertEqual(analysis._exact_model_text(row, "prompt", first), + (text, "Verified against report SHA-256.")) + self.assertEqual(analysis._exact_model_text(other_row, "prompt", + second)[0], other_text) + self.assertIsNone(analysis._exact_model_text(other_row, "prompt", + first)[0]) + changed = dict(row, prompt_sha256="0" * 64) + self.assertEqual(analysis._exact_model_text(changed, "prompt", first), + (None, "Local trace content differs from the " + "report hash.")) + config_event = next(event for event in read_recording(self.root).events + if event.event_type == CONFIGURATION_EVENT) + self.assertEqual(first["events"][config_event.sequence][0]["details"], + self.config) + + def test_sequence_ambiguity_in_another_conversation_is_not_hidden(self): + relative, row, _ = self._model() + 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) + if node["event"]["event_type"] == "llm.call.input") + node["event"]["sequence"] = row["input_sequence"] + path.write_text(json.dumps(payload), encoding="utf-8") + index = analysis._trace_index(self.root, relative, {}) + self.assertEqual(analysis._exact_model_text(row, "prompt", index), + (None, "Local trace event missing or ambiguous.")) + + def test_partial_recording_retains_text_and_visible_issues(self): + relative, row, text = self._model() + self.path.unlink() + (self.path.parent / ".sequence.json").unlink() + before = (self.root / relative).read_bytes() + index = analysis._trace_index(self.root, relative, {}) + self.assertTrue(any("counter.invalid" in error + for error in index["errors"])) + self.assertTrue(any("trace.missing" in error + for error in index["errors"])) + self.assertEqual(analysis._exact_model_text(row, "prompt", index)[0], + text) + op = {"question": {"original_trace": relative}, "model_calls": [ + {"original": row}, + ]} + html = analysis._model_calls(op, {"original": self.root}, {}, True) + self.assertIn("Local trace decoding issues", html) + self.assertIn("counter.invalid", html) + self.assertIn(text, html) + self.assertEqual((self.root / relative).read_bytes(), before) + + def test_nonhierarchy_event_traps_are_not_semantic_events(self): + payload = self.fixture._raw() + source = deepcopy(sources.observations(payload, sources.SCAN)[0]) + source["event"]["event_type"] = "fixture.fake" + session = next(iter(payload["sessions"].values())) + session["unrecognized"] = {"nested": source} + source_node = sources.observations(payload, sources.SCAN)[0] + source_node["details"]["untrusted_content"] = deepcopy(source) + self._write(payload) + local = analysis._local_events(self.root, {"fixture.fake"}) + self.assertEqual(local["events"], []) + + def test_malformed_trace_errors_are_not_silently_discarded(self): + # Use a portable filename while exercising HTML escaping of both + # the path and the JSON decoder's error message. + invalid = self.path.parent / "broken&trace.json" + invalid.write_text('{"": 1, "": 2}', "utf-8") + local = analysis._local_events(self.root, {sources.SCAN}) + self.assertEqual(len(local["events"]), 2) + self.assertTrue(any("trace.invalid" in error + for error in local["errors"])) + data = report() + data["original"].update(event_count=2, + event_counts={sources.SCAN: 2}) + data["replayed"].update(event_count=1, + event_counts={sources.SCAN: 1}) + before = deepcopy(data) + html = analysis.event_inventory_html(data, original=self.root, + include_details=True) + self.assertIn("trace.invalid", html) + self.assertIn("broken&trace.json", html) + self.assertNotIn("broken&trace.json", html) + self.assertIn("<duplicate>", html) + self.assertNotIn("", html) + self.assertEqual(data, before) + + def test_linked_root_or_trace_is_rejected_with_visible_issue(self): + link = self.root / "linked_workspace" + link.symlink_to(self.root, target_is_directory=True) + with patch.object(analysis, "read_recording") as reader: + local = analysis._local_events(link, {sources.SCAN}) + self.assertTrue(local["errors"]) + self.assertEqual(local["events"], []) + reader.assert_not_called() + linked_trace = self.path.parent / "linked.json" + linked_trace.symlink_to(self.path) + local = analysis._local_events(self.root, {sources.SCAN}) + self.assertTrue(any("Linked workspace path" in issue + for issue in local["errors"])) + self.assertEqual(len(local["events"]), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/system_testing/test_experiment.py b/tests/kilin/system_testing/test_experiment.py index 05dfef3c..c2b5d27c 100644 --- a/tests/kilin/system_testing/test_experiment.py +++ b/tests/kilin/system_testing/test_experiment.py @@ -15,6 +15,7 @@ import unittest from unittest.mock import patch +from kilin._trace_configuration import CONFIGURATION_CONTENT_REFERENCE from kilin.project import open_project from kilin.source_manifest import ( RoleEdit, apply_source_manifest, preview_source_manifest, @@ -280,6 +281,130 @@ def test_lifecycle_addition_requires_final_physical_checkpoint(self): for issue in report.issues )) + def test_default_only_history_requires_semantic_creation(self): + """Reject complete physical traces without semantic observations.""" + self.engine.close() + for name, sources in (("legacy_empty", []), ("legacy_default", [ + str(self.fixture.root / "source.txt")])): + with self.subTest(name=name): + root = self.fixture.root / name + with patch.object(self.engine, "_record_source_organization"): + self.engine.open_project(sources, "writing", str(root)) + self.assertEqual(self.fixture.events[-1]["event"], + "opened") + self.engine.close() + experiment = Experiment(root) + before = _snapshot(root) + report = self.assertInvalid( + "source.organization.unsupported", experiment + ) + self.assertFalse(any(e.event_type.startswith( + "gui.source_organization.") for e in report.events)) + self.assertEqual({issue.code for issue in report.issues}, + {"source.organization.unsupported"}) + self.assertEqual(before, _snapshot(root)) + # Even without the saved manifest, missing history is an + # error rather than an accepted pre-organization recording. + (root / "source_manifest.json").unlink() + self.assertInvalid("source.organization.unsupported", + experiment) + + def test_additive_history_requires_semantic_creation(self): + """Core reconciliations alone cannot establish a creation state.""" + self.engine.close() + root = self.fixture.root / "legacy_additive" + source = self.fixture.root / "extra.txt" + source.write_text("Additional source", encoding="utf-8") + with patch.object(self.engine, "_record_source_organization"): + self.engine.open_project([str(self.fixture.root / "source.txt")], + "writing", str(root)) + self.engine.add_project_sources([str(source)]) + self.engine.close() + experiment = Experiment(root) + before = _snapshot(root) + report = self.assertInvalid("source.organization.unsupported", + experiment) + self.assertTrue(any(e.event_type == "source_organization.reconciled" + for e in report.events)) + self.assertEqual({issue.code for issue in report.issues}, + {"source.organization.unsupported"}) + target = root.with_name("legacy_additive_replay") + with self.assertRaises(InvalidRecordingError): + experiment.replay(target) + self.assertFalse(target.exists()) + self.assertEqual(before, _snapshot(root)) + + def test_missing_saved_semantic_manifest_is_rejected(self): + """A complete event history still requires the durable manifest.""" + self.engine.close() + self.assertValid() + (self.root / "source_manifest.json").unlink() + self.assertInvalid("source.organization.unsupported") + + def test_missing_reopen_semantic_observation_is_rejected(self): + """Do not borrow a previous opening's semantic observation.""" + self.engine.close() + self.assertValid() + with patch.object(self.engine, "_record_source_organization"): + self.engine.resume_project(str(self.root)) + self.engine.close() + report = self.assertInvalid("source.organization.unsupported") + self.assertTrue(any("Missing semantic opening observation" in + issue.message for issue in report.issues)) + + def test_missing_question_semantic_identity_is_rejected(self): + """Require an explicit semantic identity at every question.""" + self.fixture._ask("Inspect the source") + self.engine.close() + report = self.assertValid() + ask = next(op for op in report.operations if op.kind == "ask") + + def remove_identity(node): + node["details"].pop("source_organization_revision") + node["details"].pop("source_organization_sha256") + + self._change(self.root / ask.events[0].path, + "gui.question.request.started", remove_identity) + self.assertInvalid("source.organization.unsupported") + + def test_missing_opening_plugin_snapshot_blocks_replay(self): + self.engine.close() + self.assertValid() + path = self.root / "logs/traces/project.json" + self._change(path, "gui.project.configuration.effective", lambda node: + node["details"].pop("plugins")) + before = _snapshot(self.root) + report = self.assertInvalid("plugin.provenance") + self.assertTrue(any("plugin snapshot" in issue.message + for issue in report.issues)) + target = self.root.with_name("missing_plugin_snapshot_replay") + with self.assertRaises(InvalidRecordingError): + self.experiment.replay(target) + self.assertFalse(target.exists()) + self.assertEqual(before, _snapshot(self.root)) + + def test_missing_tool_identity_field_blocks_replay(self): + self.fixture.commands.extend([ + {"action": "plan_choice", "choice": "quick"}, + {"action": "plan_choice", "choice": "option:0"}, + ]) + self.fixture._ask("Inspect the source", tool=True) + self.engine.close() + report = self.assertValid() + event = next(event for event in report.events + if event.event_type == "tool.run.started") + self._change(self.root / event.path, event.event_type, lambda node: + node["details"].pop("plugin")) + before = _snapshot(self.root) + report = self.assertInvalid("plugin.provenance") + self.assertTrue(any("Missing plugin identity field" in issue.message + for issue in report.issues)) + target = self.root.with_name("missing_tool_identity_replay") + with self.assertRaises(InvalidRecordingError): + self.experiment.replay(target) + self.assertFalse(target.exists()) + self.assertEqual(before, _snapshot(self.root)) + def test_blank_reference(self): self.engine.close() root = self.fixture.root / "blank" @@ -346,40 +471,50 @@ def test_recorded_consecutive_renames(self): self.assertEqual([m["destination_directory"] for m in moves], [str(middle), str(self.root)]) self.assertNotEqual(moves[0]["rename_id"], moves[1]["rename_id"]) - self.assertNotIn("relocation.inferred", {w.code for w in - report.warnings}) + for terminal in ("requested", "completed"): + self.assertEqual(sum(e.event_type == "gui.project.rename." + + terminal for e in report.events), 2) self.assertEqual(before, _snapshot(self.root)) - def _rename_without_markers(self, *, completion_only=False): - """Simulate an older producer or a missing completion marker.""" + def _rename_without_markers(self, *, missing=("requested", "completed")): + """Simulate a recording missing one or both explicit markers.""" emit = TraceLogger.emit - def legacy(logger, event_type, **options): - if event_type == "gui.project.rename.completed" or ( - not completion_only and - event_type == "gui.project.rename.requested"): + def omit(logger, event_type, **options): + if event_type in {"gui.project.rename." + suffix + for suffix in missing}: return None return emit(logger, event_type, **options) - with patch.object(TraceLogger, "emit", legacy): + with patch.object(TraceLogger, "emit", omit): self._rename("renamed") self.engine.close() - def test_legacy_rename_is_inferred_with_warning(self): - """Accept an already-recorded move only with independent paths.""" - self.fixture._ask("Before legacy rename") + def test_rename_without_markers_is_rejected(self): + """Independent paths cannot replace an explicit rename command.""" + self.fixture._ask("Before rename") self._rename_without_markers() - report = self.assertValid() + before = _snapshot(self.root) + report = self.assertInvalid("relocation.history") reopening = next(op for op in report.operations if op.kind == "open_project") - self.assertEqual(reopening.request["relocation"]["provenance"], - "inferred") - self.assertIn("relocation.inferred", {w.code for w in report.warnings}) + self.assertNotIn("relocation", reopening.request) self.assertFalse(any(e.event_type.startswith("gui.project.rename.") for e in report.events)) + self.assertEqual({issue.code for issue in report.issues}, + {"relocation.history"}) + target = self.root.with_name("renamed_replay") + with self.assertRaises(InvalidRecordingError): + self.experiment.replay(target) + self.assertFalse(target.exists()) + self.assertEqual(before, _snapshot(self.root)) + + def test_missing_rename_completion_is_rejected(self): + self._rename_without_markers(missing=("completed",)) + self.assertInvalid("relocation.history") - def test_incomplete_rename_markers_do_not_use_legacy_fallback(self): - self._rename_without_markers(completion_only=True) + def test_missing_rename_request_is_rejected(self): + self._rename_without_markers(missing=("requested",)) self.assertInvalid("relocation.history") def test_mismatched_rename_markers(self): @@ -390,13 +525,27 @@ def test_mismatched_rename_markers(self): "details"].update(rename_id="different")) self.assertInvalid("relocation.history") - def test_legacy_rename_requires_independent_path_corroboration(self): - self._rename_without_markers() + def test_rename_requires_independent_path_corroboration(self): + self._rename("renamed") + self.engine.close() + self.assertValid() + + def change_project(node): + """Corrupt the same historical path in either representation.""" + + details = node["details"] + value = str(self.root.with_name("other")) + if "behavior" in details: + details["behavior"]["project"] = value + else: + self.assertIn(CONFIGURATION_CONTENT_REFERENCE, details) + details["project"] = value + self._change(self.root / "logs/traces/project.json", - "gui.project.configuration.effective", lambda node: node[ - "details"]["behavior"].update( - project=str(self.root.with_name("other")))) - self.assertInvalid("relocation.history") + "gui.project.configuration.effective", change_project) + report = self.assertInvalid("relocation.history") + self.assertTrue(any("Relocation trace identity differs" in + issue.message for issue in report.issues)) def test_unrelated_same_directory_internal_reopen_is_rejected(self): active = self.engine.active_conversation.conversation_id diff --git a/tests/kilin/system_testing/test_traces__configuration.py b/tests/kilin/system_testing/test_traces__configuration.py index 1a1823e9..d2f0a520 100644 --- a/tests/kilin/system_testing/test_traces__configuration.py +++ b/tests/kilin/system_testing/test_traces__configuration.py @@ -5,6 +5,7 @@ # pylint: disable=C0103:invalid-name from copy import deepcopy +from hashlib import sha256 import json import os from pathlib import Path @@ -14,14 +15,16 @@ from kilin import rag from kilin._trace_configuration import ( + CONFIGURATION_CONTENT_REFERENCE, CONFIGURATION_EVENT, - CONFIGURATION_REFERENCE, - configuration_bytes, - configuration_reference, + configuration_content_bytes, + configuration_content_reference, ) +from kilin._trace_snapshots import snapshot_bytes from kilin.gui.engine import ChatEngine from kilin.gui.preferences import DEFAULTS_ENVIRONMENT from kilin.system_testing import Experiment, InvalidRecordingError +from kilin.system_testing.reference import _prefix_digest from kilin.system_testing.traces import read_recording from tests.kilin import test_trace_logging__configuration as writer_tests @@ -119,13 +122,14 @@ def _raw(self): def _write(self, payload): self.path.write_text(json.dumps(payload, ensure_ascii=False), "utf-8") - def test_compact_and_legacy_full_observations_are_equivalent(self): + def test_compact_and_full_observations_are_equivalent(self): payload = self._raw() nodes = _nodes(payload) self.assertEqual(len(nodes), 3) full = nodes[0]["details"] - expected = configuration_reference( - nodes[0]["event"]["sequence"], configuration_bytes(full) + expected = configuration_content_reference( + nodes[0]["event"]["sequence"], + configuration_content_bytes(full), full["behavior"]["project"], ) self.assertEqual([node["details"] for node in nodes[1:]], [expected, expected]) @@ -144,11 +148,11 @@ def test_compact_and_legacy_full_observations_are_equivalent(self): for node in nodes[1:]: node["details"] = deepcopy(full) self._write(payload) - legacy_before = _snapshot(self.workspace) - legacy = self.experiment.validate() - self.assertTrue(legacy.valid, legacy.issues) - self.assertEqual(report, legacy) - self.assertEqual(legacy_before, _snapshot(self.workspace)) + full_before = _snapshot(self.workspace) + expanded = self.experiment.validate() + self.assertTrue(expanded.valid, expanded.issues) + self.assertEqual(report, expanded) + self.assertEqual(full_before, _snapshot(self.workspace)) def test_workspace_replay_preserves_openings(self): before = _snapshot(self.workspace) @@ -186,7 +190,7 @@ def test_replay_with_real_source_and_index_reuse(self): self.assertEqual(replayed.operation_count, len(report.operations)) self.assertEqual(before, _snapshot(original)) - def test_rename_remains_full_and_replays_with_fixed_directory(self): + def test_rename_reuses_content_and_replays_with_fixed_directory(self): self._resume() renamed = self.workspace.with_name("renamed") self.engine.rename_project(renamed.name) @@ -197,21 +201,74 @@ def test_rename_remains_full_and_replays_with_fixed_directory(self): self._resume() self.engine.close() rows = _nodes(self._raw()) - self.assertEqual(rows[-2]["details"]["behavior"]["project"], - str(renamed)) - self.assertEqual(rows[-1]["details"], configuration_reference( - rows[-2]["event"]["sequence"], - configuration_bytes(rows[-2]["details"]), - )) + first = rows[0] + expected = configuration_content_reference( + first["event"]["sequence"], + configuration_content_bytes(first["details"]), str(renamed), + ) + self.assertEqual(rows[-2]["details"], expected) + self.assertEqual(rows[-1]["details"], expected) experiment = Experiment(renamed) before = _snapshot(renamed) report = experiment.validate() self.assertTrue(report.valid, report.issues) + configurations = [event.details for event in report.events + if event.event_type == CONFIGURATION_EVENT] + self.assertEqual(configurations[-2]["behavior"]["project"], + str(renamed)) + self.assertEqual(configurations[-1]["behavior"]["project"], + str(renamed)) replayed = experiment.replay(self.target) self.assertTrue(replayed.validation.valid, replayed.validation.issues) self.assertEqual(replayed.operation_count, len(report.operations)) self.assertEqual(before, _snapshot(renamed)) + def test_relocated_references_and_full_payloads_have_same_receipt(self): + self._resume() + self.engine.rename_project("relocated") + self.engine.close() + self.workspace = self.workspace.with_name("relocated") + self.path = self.workspace / "logs" / "traces" / "project.json" + experiment = Experiment(self.workspace) + compact = experiment.validate() + self.assertTrue(compact.valid, compact.issues) + digest = _prefix_digest(compact.events, compact.events[-1].sequence) + payload = self._raw() + configurations = {event.sequence: event.details + for event in compact.events + if event.event_type == CONFIGURATION_EVENT} + for node in _nodes(payload): + node["details"] = configurations[node["event"]["sequence"]] + self._write(payload) + full = experiment.validate() + self.assertTrue(full.valid, full.issues) + self.assertEqual(compact, full) + self.assertEqual(digest, _prefix_digest(full.events, + full.events[-1].sequence)) + + def test_corrupted_relocation_blocks_validation_and_replay(self): + self._resume() + self.engine.rename_project("relocated") + self.engine.close() + self.workspace = self.workspace.with_name("relocated") + self.path = self.workspace / "logs" / "traces" / "project.json" + payload = self._raw() + last = _nodes(payload)[-1]["details"] + last[CONFIGURATION_CONTENT_REFERENCE]["sha256"] = "0" * 64 + self._write(payload) + before = _snapshot(self.workspace) + experiment = Experiment(self.workspace) + report = experiment.validate() + self.assertFalse(report.valid) + self.assertIn("configuration.reference", + {issue.code for issue in report.issues}) + with self.assertRaises(InvalidRecordingError): + experiment.timeline() + with self.assertRaises(InvalidRecordingError): + experiment.replay(self.target) + self.assertFalse(self.target.exists()) + self.assertEqual(before, _snapshot(self.workspace)) + def test_corrupted_references_block_validation_and_replay(self): original = self._raw() for case in ("missing", "forward", "self", "reference", "digest", @@ -221,7 +278,7 @@ def test_corrupted_references_block_validation_and_replay(self): with self.subTest(case=case): payload = deepcopy(original) first, second, third = _nodes(payload) - reference = third["details"][CONFIGURATION_REFERENCE] + reference = third["details"][CONFIGURATION_CONTENT_REFERENCE] if case == "missing": reference["sequence"] = 0 elif case == "forward": @@ -237,7 +294,9 @@ def test_corrupted_references_block_validation_and_replay(self): elif case == "bool": reference["sequence"] = True elif case == "wrong_type": - third["details"][CONFIGURATION_REFERENCE] = "invalid" + third["details"][CONFIGURATION_CONTENT_REFERENCE] = ( + "invalid" + ) elif case == "wrong_event": reference["sequence"] = first["event"]["sequence"] - 1 elif case == "superseded": @@ -269,12 +328,30 @@ def test_corrupted_references_block_validation_and_replay(self): self.assertFalse(self.target.exists()) self.assertEqual(before, _snapshot(self.workspace)) + def test_obsolete_reference_blocks_validation_and_replay(self): + payload = self._raw() + first, second, _ = _nodes(payload) + second["details"] = {"configuration_reference": { + "sequence": first["event"]["sequence"], + "sha256": sha256(snapshot_bytes(first["details"])).hexdigest(), + }} + self._write(payload) + before = _snapshot(self.workspace) + report = self.experiment.validate() + self.assertFalse(report.valid) + self.assertIn("configuration.reference", + {issue.code for issue in report.issues}) + with self.assertRaises(InvalidRecordingError): + self.experiment.replay(self.target) + self.assertFalse(self.target.exists()) + self.assertEqual(before, _snapshot(self.workspace)) + def test_missing_target_does_not_use_current_settings(self): payload = self._raw() first, _, _ = _nodes(payload) - first["details"] = {CONFIGURATION_REFERENCE: { + first["details"] = {CONFIGURATION_CONTENT_REFERENCE: { "sequence": 1, "sha256": "0" * 64, - }} + }, "project": str(self.workspace)} self._write(payload) recording = read_recording(self.workspace) self.assertEqual(sum(issue.code == "configuration.reference" @@ -318,5 +395,100 @@ def test_resolve_concurrent_process_observations(self): self._assert_resolved(self.fixture._record_processes()) +class TestConfigurationContentResolution(unittest.TestCase): + """Reject malformed relocation references without altering originals.""" + + def setUp(self): + fixture = writer_tests.TestConfigurationRecording() + self.addCleanup(fixture.doCleanups) + fixture.setUp() + self.fixture = fixture + logger = fixture._logger() + fixture._emit(logger) + relocated = deepcopy(fixture.config) + relocated["behavior"]["project"] = "../KíLín relocated" + fixture._emit(logger, relocated) + fixture._emit(logger, relocated) + logger.close() + self.path = fixture.path + self.original = json.loads(self.path.read_text("utf-8")) + + def test_relocated_reference_corruption_is_blocking(self): + cases = ("missing", "self", "forward", "chain", "digest", + "boolean", "extra_key", "nonmapping", "mixed", + "superseded", "failed_target", "failed_reference", + "changed_target", "duplicate_target", "duplicate_current", + "incomplete_target", "no_target", "unsupported_event", + "wrong_turn", "missing_path", "mixed_references") + for case in cases: + with self.subTest(case=case): + payload = deepcopy(self.original) + first, second, third = _nodes(payload) + reference = third["details"][CONFIGURATION_CONTENT_REFERENCE] + if case == "missing": + reference["sequence"] = 0 + elif case == "self": + reference["sequence"] = third["event"]["sequence"] + elif case == "forward": + reference["sequence"] = third["event"]["sequence"] + 1 + elif case == "chain": + reference["sequence"] = second["event"]["sequence"] + elif case == "digest": + reference["sha256"] = "0" * 64 + elif case == "boolean": + reference["sequence"] = True + elif case == "extra_key": + reference["extra"] = True + elif case == "nonmapping": + third["details"][CONFIGURATION_CONTENT_REFERENCE] = "bad" + elif case == "mixed": + third["details"]["profile"] = {} + elif case == "superseded": + second["details"] = deepcopy(first["details"]) + elif case == "failed_target": + first["event"]["status"] = "failed" + elif case == "failed_reference": + third["event"]["status"] = "failed" + elif case == "changed_target": + first["details"]["behavior"]["prompt"] += " changed" + elif case == "duplicate_target": + second["event"]["sequence"] = first["event"]["sequence"] + elif case == "duplicate_current": + second["event"]["sequence"] = third["event"]["sequence"] + elif case == "incomplete_target": + first["details"]["behavior"].pop("project") + elif case == "no_target": + first["details"] = deepcopy(second["details"]) + elif case == "unsupported_event": + third["event"]["event_type"] = "fixture.observed" + elif case == "wrong_turn": + first["event"]["turn_id"] = "turn_fixture" + elif case == "missing_path": + third["details"].pop("project") + elif case == "mixed_references": + third["details"]["configuration_reference"] = reference + self.path.write_text(json.dumps(payload), encoding="utf-8") + before = self.path.read_bytes() + recording = read_recording(self.fixture.root) + self.assertIn("configuration.reference", + {issue.code for issue in recording.issues}) + self.assertEqual(before, self.path.read_bytes()) + + def test_conversation_reference_cannot_reuse_project_snapshot(self): + logger = self.fixture._logger(name="conversation_a.json", + scope="conversation") + self.fixture._emit(logger) + logger.close() + payload = json.loads(logger.readable_path.read_text("utf-8")) + node, = _nodes(payload) + node["details"] = deepcopy(_nodes(self.original)[-1]["details"]) + logger.readable_path.write_text(json.dumps(payload), encoding="utf-8") + before = _snapshot(self.fixture.root) + recording = read_recording(self.fixture.root) + self.assertIn("configuration.reference", + {issue.code for issue in recording.issues}) + self.assertEqual(before, _snapshot(self.fixture.root)) + + 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 new file mode 100644 index 00000000..6293c028 --- /dev/null +++ b/tests/kilin/system_testing/test_traces__semantics.py @@ -0,0 +1,265 @@ +"""Verify exact semantic reconstruction, integrity checks and real replay.""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from copy import deepcopy +import json +import unittest + +from kilin._trace_snapshots import SOURCE_SNAPSHOT_REFERENCE +from kilin.system_testing import Experiment, InvalidRecordingError +from kilin.system_testing.reference import ( + _prefix_digest, inspect_receipt, publish_receipt, +) +from kilin.system_testing.traces import read_recording +from tests.kilin import test_trace_logging__semantics as writer +from tests.kilin.system_testing import test_experiment, test_replay + + +class TestSemanticReferenceResolution(unittest.TestCase): + """Reject malformed references rather than guessing historical state.""" + + def setUp(self): + fixture = writer.TestSemanticSnapshotRecording() + self.addCleanup(fixture.doCleanups) + fixture.setUp() + self.fixture = fixture + logger = fixture.fixture._logger() + for kind in (writer.COMMITTED, writer.APPLIED, writer.RECONCILED): + fixture._emit(logger, kind) + logger.close() + self.path = fixture.fixture.path + self.original = json.loads(self.path.read_text("utf-8")) + + def _assert_invalid(self, payload, code="semantic_snapshot.reference"): + self.path.write_text(json.dumps(payload), "utf-8") + before = self.path.read_bytes() + recording = read_recording(self.fixture.fixture.root) + self.assertIn(code, {issue.code for issue in recording.issues}) + self.assertEqual(before, self.path.read_bytes()) + + def test_invalid_reference_shapes_targets_and_scopes_are_blocking(self): + cases = ( + "missing", "self", "forward", "chain", "digest", "boolean", + "extra_key", "nonmapping", "mixed", "mixed_source_reference", + "superseded", "failed_target", "failed_reference", + "changed_target", "duplicate_target", "duplicate_current", + "missing_manifest", "null_manifest", "invalid_target", + "unknown_event", "observed_reference", "wrong_turn", + "target_turn", "reference_error", "target_trace_error", + ) + for case in cases: + with self.subTest(case=case): + payload = deepcopy(self.original) + first, second, third = writer.semantic_nodes(payload) + reference = third["details"][writer.REFERENCE] + if case == "missing": + reference["sequence"] = 999999 + elif case == "self": + reference["sequence"] = third["event"]["sequence"] + elif case == "forward": + reference["sequence"] = third["event"]["sequence"] + 1 + elif case == "chain": + reference["sequence"] = second["event"]["sequence"] + elif case == "digest": + reference["sha256"] = "0" * 64 + elif case == "boolean": + reference["sequence"] = True + elif case == "extra_key": + reference["extra"] = True + elif case == "nonmapping": + third["details"][writer.REFERENCE] = "invalid" + elif case == "mixed": + third["details"]["source_organization"] = {} + elif case == "mixed_source_reference": + third["details"][SOURCE_SNAPSHOT_REFERENCE] = {} + elif case == "superseded": + second["details"] = deepcopy(first["details"]) + elif case == "failed_target": + first["event"]["status"] = "failed" + elif case == "failed_reference": + third["event"]["status"] = "failed" + elif case == "changed_target": + first["details"]["source_organization"]["changed"] = True + elif case == "duplicate_target": + second["event"]["sequence"] = first["event"]["sequence"] + elif case == "duplicate_current": + second["event"]["sequence"] = third["event"]["sequence"] + elif case == "missing_manifest": + first["details"].pop("source_organization") + elif case == "null_manifest": + first["details"]["source_organization"] = None + elif case == "invalid_target": + first["event"]["event_type"] = "unrelated.event" + elif case == "unknown_event": + third["event"]["event_type"] = "unrelated.event" + elif case == "observed_reference": + third["event"]["event_type"] = writer.OBSERVED + elif case == "wrong_turn": + third["event"]["turn_id"] = "turn_fixture" + elif case == "target_turn": + first["event"]["turn_id"] = "turn_fixture" + elif case == "reference_error": + third["details"]["error"] = "failed" + elif case == "target_trace_error": + first["details"]["trace_error"] = "failed" + # A turn-correlated node outside a turn is rejected by the + # structural decoder before reference resolution is reached. + code = ("hierarchy.invalid" if case == "wrong_turn" else + "semantic_snapshot.reference") + self._assert_invalid(payload, code) + + def test_conversation_reference_cannot_use_a_project_manifest(self): + fixture = self.fixture.fixture + logger = fixture._logger(scope="conversation", + name="conversation_a.json") + self.fixture._emit(logger, writer.APPLIED) + logger.close() + payload = json.loads(logger.readable_path.read_text("utf-8")) + node, = writer.semantic_nodes(payload) + compact = writer.semantic_nodes(self.original)[1] + node["details"] = deepcopy(compact["details"]) + logger.readable_path.write_text(json.dumps(payload), "utf-8") + recording = read_recording(fixture.root) + self.assertIn("semantic_snapshot.reference", + {issue.code for issue in recording.issues}) + + def test_group_reference_cannot_be_an_indirect_manifest_target(self): + fixture = self.fixture.fixture + logger = fixture._logger() + for kind in (writer.OBSERVED, writer.OBSERVED, writer.APPLIED): + self.fixture._emit(logger, kind) + logger.close() + payload = json.loads(self.path.read_text("utf-8")) + first, compact, applied = writer.semantic_nodes(payload)[-3:] + self.assertNotIn(SOURCE_SNAPSHOT_REFERENCE, first["details"]) + self.assertIn(SOURCE_SNAPSHOT_REFERENCE, compact["details"]) + applied["details"][writer.REFERENCE]["sequence"] = ( + compact["event"]["sequence"]) + self._assert_invalid(payload) + + def test_span_completion_cannot_contain_a_semantic_reference(self): + logger = self.fixture.fixture._logger() + with logger.span("gui.source_organization.apply", component="test"): + pass + logger.close() + payload = json.loads(self.path.read_text("utf-8")) + compact = writer.semantic_nodes(self.original)[1]["details"] + completions = [node for session in payload["sessions"].values() + for node in session.get("operations", {}).values() + if node.get("completion", {}).get("event_type") == + writer.APPLIED] + self.assertEqual(len(completions), 1) + completions[0]["result"] = deepcopy(compact) + self._assert_invalid(payload) + + +class TestSemanticSnapshotInspection(unittest.TestCase): + """Compare full and compact real engine histories before replay.""" + + def setUp(self): + fixture = test_replay.TestReplay() + self.addCleanup(fixture.doCleanups) + fixture.setUp() + self.fixture = fixture + self.workspace = fixture.experiment.workspace.with_name( + "semantic_original") + fixture.engine.rename_project(self.workspace.name) + self.assertEqual(fixture.engine.session.project.root, self.workspace) + fixture.fixture.workspace = self.workspace + fixture.original.root = self.workspace + fixture.experiment = Experiment(self.workspace) + fixture.original.experiment = fixture.experiment + self.path = self.workspace / "logs/traces/project.json" + self.report = fixture.original._record_semantic_edit() + + def test_semantic_receipt_replay_and_full_recording_equivalence(self): + fixture = self.fixture + payload = json.loads(self.path.read_text("utf-8")) + nodes = writer.semantic_nodes(payload) + compact = [node for node in nodes + if writer.REFERENCE in node["details"]] + self.assertTrue(compact) + self.assertTrue(any(node["event"]["event_type"] == writer.APPLIED + for node in compact)) + published = publish_receipt(self.workspace, self.report, []) + receipt_before = published.read_bytes() + status = inspect_receipt(self.workspace, self.report)["status"] + original = test_experiment._snapshot(self.workspace) + with fixture._model(): + replay = fixture.experiment.replay(fixture.target) + self.assertTrue(replay.validation.valid, replay.validation.issues) + self.assertEqual(replay.operation_count, len(self.report.operations)) + self.assertEqual(original, test_experiment._snapshot(self.workspace)) + self.assertEqual( + (self.workspace / "source_manifest.json").read_bytes(), + (fixture.target / "source_manifest.json").read_bytes(), + ) + comparison = fixture.experiment.compare(fixture.target) + self.assertTrue(comparison.complete, comparison.data["alignment"]) + full = deepcopy(payload) + by_sequence = {event.sequence: event for event in self.report.events} + for node in writer.semantic_nodes(full): + node["details"] = deepcopy( + by_sequence[node["event"]["sequence"]].details) + self.assertLess(len(json.dumps(payload)), len(json.dumps(full))) + self.path.write_text(json.dumps(full), "utf-8") + expanded = fixture.experiment.validate() + self.assertEqual(expanded, self.report) + self.assertEqual(_prefix_digest(expanded.events, len(expanded.events)), + _prefix_digest(self.report.events, + len(self.report.events))) + self.assertEqual(inspect_receipt(self.workspace, expanded)["status"], + status) + self.assertEqual(published.read_bytes(), receipt_before) + + def test_noop_apply_preserves_full_gui_result_and_current_inspection(self): + fixture = self.fixture + fixture.engine.resume_project(str(self.workspace)) + preview = fixture._semantic("preview") + self.assertFalse(preview["changed"]) + response = fixture._semantic("apply", preview_id=preview["preview_id"]) + self.assertFalse(response["changed"]) + self.assertNotIn(writer.REFERENCE, response) + self.assertIn("source_organization", response) + fixture.engine.close() + report = fixture.experiment.validate() + self.assertTrue(report.valid, report.issues) + applied = [event for event in report.events + if event.event_type == writer.APPLIED][-1] + for field in ("source_organization", "inspection", "changed", + "revision", "sha256", "trace_error"): + self.assertEqual(applied.details[field], response[field], field) + payload = json.loads(self.path.read_text("utf-8")) + raw = [node for node in writer.semantic_nodes(payload) + if node["event"]["event_type"] == writer.APPLIED][-1] + self.assertIn(writer.REFERENCE, raw["details"]) + self.assertEqual(report.events[:len(self.report.events)], + self.report.events) + + 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): + if writer.REFERENCE in node["details"]: + node["details"][writer.REFERENCE]["sha256"] = "0" * 64 + break + else: + self.fail("Real producer did not compact its semantic result.") + self.path.write_text(json.dumps(payload), "utf-8") + before = test_experiment._snapshot(self.workspace) + report = self.fixture.experiment.validate() + self.assertFalse(report.valid) + self.assertIn("semantic_snapshot.reference", + {issue.code for issue in report.issues}) + with self.assertRaises(InvalidRecordingError): + self.fixture.experiment.timeline() + with self.assertRaises(InvalidRecordingError): + self.fixture.experiment.replay(self.fixture.target) + self.assertFalse(self.fixture.target.exists()) + self.assertEqual(test_experiment._snapshot(self.workspace), before) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/system_testing/test_traces__sources.py b/tests/kilin/system_testing/test_traces__sources.py new file mode 100644 index 00000000..3d5d4adc --- /dev/null +++ b/tests/kilin/system_testing/test_traces__sources.py @@ -0,0 +1,282 @@ +"""Verify source snapshot references in recorded workspace histories.""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from copy import deepcopy +import json +import os +from pathlib import Path +from tempfile import TemporaryDirectory +import unittest +from unittest.mock import patch + +from kilin import rag +from kilin._trace_snapshots import SOURCE_SNAPSHOT_FIELDS +from kilin.gui.engine import ChatEngine +from kilin.gui.preferences import DEFAULTS_ENVIRONMENT +from kilin.system_testing import Experiment, InvalidRecordingError +from kilin.system_testing.reference import inspect_receipt, publish_receipt +from kilin.system_testing.traces import read_recording +from tests.kilin import test_trace_logging__sources as writer_tests +from tests.kilin.system_testing import test_traces__configuration as models + +REFERENCE = writer_tests.REFERENCE +SCAN = writer_tests.SCAN +INDEX = writer_tests.INDEX +SEMANTIC = writer_tests.SEMANTIC + + +class TestSourceReferenceResolution(unittest.TestCase): + """Reject invalid source references without repairing the trace.""" + + def setUp(self): + fixture = writer_tests.TestSourceSnapshotRecording() + self.addCleanup(fixture.doCleanups) + fixture.setUp() + self.fixture = fixture + logger = fixture._logger() + fixture._emit(logger, INDEX, writer_tests.observation(INDEX)) + for _ in range(3): + fixture._emit(logger, SCAN, writer_tests.observation(SCAN)) + logger.close() + self.original = fixture._raw() + self.path = fixture.path + + def _write(self, payload): + self.path.write_text(json.dumps(payload), encoding="utf-8") + + def _assert_invalid(self): + before = self.path.read_bytes() + recording = read_recording(self.fixture.root) + self.assertIn("source_snapshot.reference", + {issue.code for issue in recording.issues}) + self.assertEqual(before, self.path.read_bytes()) + + def test_reference_corruption_is_blocking(self): + cases = ("missing", "self", "forward", "chain", "wrong_kind", + "digest", "boolean", "extra_key", "nonmapping", "mixed", + "superseded", "failed_target", "failed_reference", + "changed_target", "duplicate_target", "duplicate_current", + "incomplete_target", "incomplete_reference", "no_target", + "unsupported_event", "wrong_turn") + for case in cases: + with self.subTest(case=case): + payload = deepcopy(self.original) + first, second, third = writer_tests.observations(payload, + SCAN) + other, = writer_tests.observations(payload, INDEX) + reference = third["details"][REFERENCE] + if case == "missing": + reference["sequence"] = 1 + elif case == "self": + reference["sequence"] = third["event"]["sequence"] + elif case == "forward": + reference["sequence"] = third["event"]["sequence"] + 1 + elif case == "chain": + reference["sequence"] = second["event"]["sequence"] + elif case == "wrong_kind": + reference["sequence"] = other["event"]["sequence"] + elif case == "digest": + reference["sha256"] = "0" * 64 + elif case == "boolean": + reference["sequence"] = True + elif case == "extra_key": + reference["extra"] = True + elif case == "nonmapping": + third["details"][REFERENCE] = "invalid" + elif case == "mixed": + third["details"]["entries"] = [] + elif case == "superseded": + second["details"] = deepcopy(first["details"]) + elif case == "failed_target": + first["event"]["status"] = "failed" + elif case == "failed_reference": + third["event"]["status"] = "failed" + elif case == "changed_target": + first["details"]["entries"][0]["size_bytes"] += 1 + elif case == "duplicate_target": + other["event"]["sequence"] = first["event"]["sequence"] + elif case == "duplicate_current": + other["event"]["sequence"] = third["event"]["sequence"] + elif case == "incomplete_target": + first["details"]["complete"] = False + elif case == "incomplete_reference": + third["details"]["complete"] = False + elif case == "no_target": + first["details"] = deepcopy(second["details"]) + elif case == "unsupported_event": + third["event"]["event_type"] = "index.empty" + elif case == "wrong_turn": + # A turn-correlated operation at project level is itself + # malformed. The missing target must also block later + # references to the same full observation. + first["event"]["turn_id"] = "turn_fixture" + self._write(payload) + self._assert_invalid() + + def test_conversation_reference_cannot_use_project_target(self): + logger = self.fixture._logger(scope="conversation", + name="conversation_a.json") + full = writer_tests.observation(SCAN) + self.fixture._emit(logger, SCAN, full) + logger.close() + payload = json.loads(logger.readable_path.read_text("utf-8")) + node, = writer_tests.observations(payload, SCAN) + first = writer_tests.observations(self.original, SCAN)[0] + for field in SOURCE_SNAPSHOT_FIELDS[SCAN]: + node["details"].pop(field) + node["details"][REFERENCE] = writer_tests.reference_for(first) + logger.readable_path.write_text(json.dumps(payload), "utf-8") + self._assert_invalid() + + +class TestSourceSnapshotInspection(unittest.TestCase): + """Validate real engine openings, replay and publication fingerprints.""" + + def setUp(self): + temporary = TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.workspace = self.root / "sources_original" + self.target = self.root / "sources_replay" + self.path = self.workspace / "logs" / "traces" / "project.json" + self.events = [] + for patcher in ( + patch.dict(os.environ, { + DEFAULTS_ENVIRONMENT: str(self.root / "preferences.json"), + }), + patch.object(rag, "choose_backend", return_value="mlx"), + patch.object(rag, "ChatSession", side_effect=models._chat_model), + patch.object(rag, "EmbeddingSession", + side_effect=models._embedding_model), + ): + patcher.start() + self.addCleanup(patcher.stop) + self.engine = ChatEngine(self.root, self.events.append, + trace_enabled=True) + self.addCleanup(self.engine.close) + folder = self.root / "library" + folder.mkdir() + for i in range(12): + (folder / f"source_{i:02d}.txt").write_text( + f"Synthetic source {i} reports a calibration result.\n", + encoding="utf-8", + ) + self.engine.open_project([str(folder)], "writing", + str(self.workspace)) + self.assertEqual(self.events[-1]["event"], "opened", self.events) + self.engine.close() + self.experiment = Experiment(self.workspace) + + def _resume(self): + self.engine.resume_project(str(self.workspace)) + self.assertEqual(self.events[-1]["event"], "opened", self.events) + self.engine.close() + + def _raw(self): + return json.loads(self.path.read_text("utf-8")) + + def _report(self): + report = self.experiment.validate() + self.assertTrue(report.valid, report.issues) + return report + + def _full_payload(self, payload, report): + """Expand an in-memory copy to the equivalent legacy raw format.""" + by_sequence = {event.sequence: event for event in report.events} + full = deepcopy(payload) + for node in writer_tests.observations(full): + sequence = node["event"]["sequence"] + node["details"] = deepcopy(by_sequence[sequence].details) + return full + + def test_opening_receipt_replay_and_full_snapshot_equivalence(self): + published = self._report() + receipt = publish_receipt(self.workspace, published, []) + receipt_before = receipt.read_bytes() + first = self._raw() + self._resume() + self._resume() + payload = self._raw() + # Appending diagnostics never rewrites the published event nodes. + for node in writer_tests.observations(first): + self.assertIn(node, writer_tests.observations(payload)) + for kind in SOURCE_SNAPSHOT_FIELDS: + rows = writer_tests.observations(payload, kind) + self.assertIn(REFERENCE, rows[-1]["details"], kind) + self.assertNotIn(REFERENCE, rows[0]["details"], kind) + before = models._snapshot(self.workspace) + report = self._report() + self.assertEqual(inspect_receipt(self.workspace, report)["status"], + "inspection_only") + self.assertEqual(receipt_before, receipt.read_bytes()) + self.assertEqual(models._snapshot(self.workspace), before) + replay = self.experiment.replay(self.target) + self.assertTrue(replay.validation.valid, replay.validation.issues) + self.assertEqual(replay.operation_count, len(report.operations)) + self.assertEqual(replay.differences, ()) + comparison = self.experiment.compare(self.target) + self.assertTrue(comparison.complete, comparison.data["alignment"]) + self.assertEqual(models._snapshot(self.workspace), before) + full = self._full_payload(payload, report) + compact_bytes = len(json.dumps(payload, indent=2, ensure_ascii=False) + .encode("utf-8")) + full_bytes = len(json.dumps(full, indent=2, ensure_ascii=False) + .encode("utf-8")) + self.assertLess(compact_bytes, full_bytes) + self.path.write_text(json.dumps(full), encoding="utf-8") + legacy = self._report() + self.assertEqual(legacy, report) + self.assertEqual(inspect_receipt(self.workspace, legacy)["status"], + "inspection_only") + self.assertEqual(receipt_before, receipt.read_bytes()) + + def test_source_change_creates_new_snapshots(self): + self._resume() + previous = self._report() + source = self.root / "extra.txt" + source.write_text("Additional synthetic evidence.\n", "utf-8") + self.engine.resume_project(str(self.workspace)) + self.engine.add_project_sources([str(source)]) + self.engine.close() + self._resume() + report = self._report() + scan = [event.details for event in report.events + if event.event_type == SCAN] + self.assertNotIn("extra.txt", scan[0]["selected_files"]) + self.assertIn("extra.txt", scan[-1]["selected_files"]) + self.assertEqual(report.events[:len(previous.events)], + previous.events) + rows = writer_tests.observations(self._raw(), SCAN) + self.assertNotIn(REFERENCE, rows[-2]["details"]) + self.assertEqual(rows[-1]["details"][REFERENCE], + writer_tests.reference_for(rows[-2])) + self.assertTrue(self.experiment.replay(self.target).validation.valid) + + def test_bad_reference_blocks_validation_timeline_and_replay(self): + self._resume() + self._resume() + original = self._raw() + for kind in SOURCE_SNAPSHOT_FIELDS: + with self.subTest(kind=kind): + payload = deepcopy(original) + rows = writer_tests.observations(payload, kind) + rows[-1]["details"][REFERENCE]["sha256"] = "0" * 64 + self.path.write_text(json.dumps(payload), "utf-8") + before = models._snapshot(self.workspace) + report = self.experiment.validate() + self.assertFalse(report.valid) + self.assertIn("source_snapshot.reference", + {issue.code for issue in report.issues}) + with self.assertRaises(InvalidRecordingError): + self.experiment.timeline() + with self.assertRaises(InvalidRecordingError): + self.experiment.replay(self.target) + self.assertFalse(self.target.exists()) + self.assertEqual(models._snapshot(self.workspace), before) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/test__format_versions.py b/tests/kilin/test__format_versions.py index 145d494b..8f246515 100644 --- a/tests/kilin/test__format_versions.py +++ b/tests/kilin/test__format_versions.py @@ -171,18 +171,47 @@ def test_comparison_report_loader_uses_own_generation(self): "summary", "original", "replayed", "files", "final_state", "embedding_evaluation", )} + self.assertEqual(comparison.COMPARISON_FORMAT_VERSION, 2) payload.update(format_version=comparison.COMPARISON_FORMAT_VERSION, alignment={"status": "complete"}, operations=[], report_issues=[]) + for side in ("original", "replayed"): + payload[side].update(event_count=0, event_counts={}) path.write_text(json.dumps(payload), encoding="utf-8") self.assertEqual(analysis.load_report(path), payload) - for invalid in _INVALID_VERSIONS: + # Comparison reports have an independent format generation. + for invalid in (True, False, 1, 1.0, 2.0, "1", "2", None, 0, 3, + "missing"): with self.subTest(version=invalid): - path.write_text(json.dumps(dict(payload, - format_version=invalid)), - encoding="utf-8") - with self.assertRaisesRegex(ValueError, "format version"): + data = dict(payload, format_version=invalid) + if invalid == "missing": + del data["format_version"] + path.write_text(json.dumps(data), encoding="utf-8") + before = path.read_bytes() + with self.assertRaisesRegex( + ValueError, "format version; regenerate"): analysis.load_report(path) + self.assertEqual(path.read_bytes(), before) + # Exercise the same loader with a nonempty independent inventory. + for side in ("original", "replayed"): + payload[side].update(event_count=2, event_counts={"ask": 2}) + path.write_text(json.dumps(payload), encoding="utf-8") + self.assertEqual(analysis.load_report(path), payload) + for side in ("original", "replayed"): + for missing in (True, False): + with self.subTest(side=side, missing_counts=missing): + data = deepcopy(payload) + if missing: + del data[side]["event_counts"] + else: + data[side]["event_counts"] = {"ask": 3} + path.write_text(json.dumps(data), encoding="utf-8") + before = path.read_bytes() + with self.assertRaisesRegex( + ValueError, + "independent event counts; regenerate"): + analysis.load_report(path) + self.assertEqual(path.read_bytes(), before) def test_receipts_validate_independent_generations(self): original = self.root / "example_original" diff --git a/tests/kilin/test__project_type_contract.py b/tests/kilin/test__project_type_contract.py index ea2329d7..ff0effc1 100644 --- a/tests/kilin/test__project_type_contract.py +++ b/tests/kilin/test__project_type_contract.py @@ -43,12 +43,12 @@ def test_public_names_and_dataclass_fields(self) -> None: for owner in (kilin, project): self.assertIs(owner.ProjectTypeId, str) for name in ( - "ProjectTypeId", "PROJECT_TYPE_IDS", + "ProjectTypeId", "project_type_ids", ): self.assertIn(name, owner.__all__) for old in ( "ProjectKind", "PROJECT_KIND_CODE", "PROJECT_KIND_CHOICES", - "PROJECT_KIND_LITERATURE", + "PROJECT_KIND_LITERATURE", "PROJECT_TYPE_IDS", ): self.assertFalse(hasattr(owner, old)) self.assertNotIn(old, owner.__all__) @@ -64,10 +64,14 @@ def test_public_names_and_dataclass_fields(self) -> None: for name in owner.__all__ ) ) - self.assertEqual(kilin.PROJECT_TYPE_IDS, tuple(load_project_types())) + current = tuple(load_project_types()) + self.assertTrue(current) + self.assertEqual(kilin.project_type_ids(), current) + self.assertEqual(project.project_type_ids(), current) + self.assertFalse(hasattr(project, "_check_built_in_kinds")) self.assertIn("id", {field.name for field in fields(ProjectType)}) self.assertNotIn("kind", {field.name for field in fields(ProjectType)}) - profile = project.default_project_profile(kilin.PROJECT_TYPE_IDS[0]) + profile = project.default_project_profile(current[0]) self.assertIn("type_id", asdict(profile)) self.assertNotIn("kind", asdict(profile)) self.assertFalse(hasattr(profile, "kind")) @@ -148,7 +152,7 @@ def test_isolated_distribution_with_only_custom_types(self) -> None: from kilin.rag import RAGSession from kilin.runtime import BACKEND_TORCH -assert kilin.PROJECT_TYPE_IDS == ("alpha", "zeta") +assert kilin.project_type_ids() == ("alpha", "zeta") assert not any( name.startswith("PROJECT_TYPE_ID_") for name in vars(kilin) ) @@ -210,7 +214,7 @@ def test_isolated_distribution_with_only_custom_types(self) -> None: ] assert all("kind" not in item for item in settings["project_types"]) engine.close() -print(json.dumps({"type_ids": kilin.PROJECT_TYPE_IDS, "ok": True})) +print(json.dumps({"type_ids": kilin.project_type_ids(), "ok": True})) ''' result = subprocess.run( [sys.executable, "-c", script], cwd=root, diff --git a/tests/kilin/test__trace_configuration.py b/tests/kilin/test__trace_configuration.py new file mode 100644 index 00000000..10f01ee7 --- /dev/null +++ b/tests/kilin/test__trace_configuration.py @@ -0,0 +1,95 @@ +"""Preserve exact configuration content when its observed path changes.""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from copy import deepcopy +import json +import unittest + +from kilin._trace_configuration import ( + CONFIGURATION_CONTENT_REFERENCE, + configuration_content_bytes, + configuration_content_reference, + resolve_configuration_reference, +) +from kilin._trace_snapshots import snapshot_bytes +from tests.kilin.test_trace_logging__configuration import _configuration + + +class TestConfigurationContent(unittest.TestCase): + """Check exact path reconstruction and narrow content extraction.""" + + def test_only_behavior_project_is_excluded(self): + original = _configuration("C:\\workspace\\old") + original["extra"] = {"project": "separate", "unknown": [1, True, 1.0]} + before = deepcopy(original) + encoded = configuration_content_bytes(original) + expected = deepcopy(original) + expected["behavior"].pop("project") + self.assertEqual(json.loads(encoded), expected) + moved = deepcopy(original) + moved["behavior"]["project"] = "../KíLín new" + self.assertEqual(encoded, configuration_content_bytes(moved)) + self.assertNotEqual(snapshot_bytes(original), + snapshot_bytes(moved)) + moved["extra"]["project"] = "changed" + self.assertNotEqual(encoded, configuration_content_bytes(moved)) + self.assertEqual(original, before) + + def test_current_path_value_and_json_types_round_trip(self): + full = _configuration("original") + before = deepcopy(full) + encoded = configuration_content_bytes(full) + paths = (None, "", "../KíLín/../copy", "C:\\work\\copy", + 1, 1.0, True, {"unknown": [None, False, 1.0]}) + for project in paths: + with self.subTest(project=project): + reference = configuration_content_reference(2, encoded, + project) + result = resolve_configuration_reference(reference, 3, + (2, full)) + expected = deepcopy(full) + expected["behavior"]["project"] = project + self.assertEqual(snapshot_bytes(result), + snapshot_bytes(expected)) + self.assertIsNot(result["behavior"], full["behavior"]) + if isinstance(project, dict): + self.assertIsNot(reference["project"], project) + self.assertIsNot(result["behavior"]["project"], + reference["project"]) + self.assertEqual(full, before) + + def test_obsolete_reference_cannot_be_resolved(self): + full = _configuration("original") + reference = {"configuration_reference": { + "sequence": 1, "sha256": "0" * 64, + }} + with self.assertRaises(ValueError): + resolve_configuration_reference(reference, 2, (1, full)) + with self.assertRaises(ValueError): + configuration_content_bytes(reference) + + def test_missing_or_incomplete_content_is_rejected(self): + full = _configuration("original") + missing = deepcopy(full) + missing["behavior"].pop("project") + wrong_type = deepcopy(full) + wrong_type["behavior"] = [] + incomplete = deepcopy(full) + incomplete.pop("tools") + compact = configuration_content_reference( + 1, configuration_content_bytes(full), "moved", + ) + mixed = {**full, **compact} + for data in (missing, wrong_type, incomplete, compact, mixed): + with self.subTest(data=data): + with self.assertRaises(ValueError): + configuration_content_bytes(data) + self.assertEqual(set(compact), + {CONFIGURATION_CONTENT_REFERENCE, "project"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/test__trace_json.py b/tests/kilin/test__trace_json.py new file mode 100644 index 00000000..e80cd2c3 --- /dev/null +++ b/tests/kilin/test__trace_json.py @@ -0,0 +1,226 @@ +"""Verify lossless trace formatting and ordinary writer integration.""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from copy import deepcopy +import json +from pathlib import Path +import random +from tempfile import TemporaryDirectory +import unittest + +from kilin._trace_json import trace_json_dumps +from kilin.system_testing.reference import _prefix_digest +from kilin.system_testing.traces import read_recording +from kilin.trace_logging import ( + TRACE_EVENT_LLM_CALL_INPUT, + TraceConfig, + TraceLogger, +) + + +class TestTraceJSON(unittest.TestCase): + """Retain exact JSON values while grouping only long integer arrays.""" + + def test_integer_rows_and_threshold(self): + for count in (0, 1, 15, 16, 17, 31, 32, 33, 1025): + for nested in (False, True): + with self.subTest(count=count, nested=nested): + integers = list(range(-(count // 2), count - count // 2)) + payload = {"tokens": integers} if nested else integers + encoded = trace_json_dumps(payload) + self.assertEqual(json.loads(encoded), payload) + ordinary = json.dumps(payload, indent=2, + ensure_ascii=False) + if len(integers) < 16: + self.assertEqual(encoded, ordinary) + else: + self.assertLess(len(encoded), len(ordinary)) + rows = [line.strip().rstrip(",").split(", ") + for line in encoded.splitlines() + if line.strip()[:1] in "-0123456789"] + self.assertEqual( + [len(row) for row in rows[:-1]], + [16] * (len(rows) - 1), + ) + self.assertLessEqual(len(rows[-1]), 16) + + def test_other_arrays_keep_standard_format(self): + arrays = ( + [True] * 20, + [False] * 20, + list(range(20)) + [True], + [1.0] * 20, + list(range(20)) + [-0.0], + ["12"] * 20, + [None] * 20, + [[1, 2]] * 20, + list(range(20)) + [{"nested": []}], + ) + for values in arrays: + with self.subTest(values=values): + payload = {"values": values} + self.assertEqual( + trace_json_dumps(payload), + json.dumps(payload, indent=2, ensure_ascii=False), + ) + + def test_strings_cannot_be_interpreted_as_arrays(self): + literal = json.dumps(list(range(32)), indent=2) + texts = [ + literal, repr(literal), json.dumps(literal), + 'quoted "array": ' + literal, + "\\\"\\\\\n\r\t\b\f" + literal, + "KíLín — 中文 🙂 \u2028\u2029" + literal, + ] + payload = {text: text for text in texts} + payload["actual_array"] = list(range(33)) + encoded = trace_json_dumps(payload) + self.assertEqual(json.loads(encoded), payload) + for text in texts: + self.assertIn(json.dumps(text, ensure_ascii=False), encoded) + + def test_scalar_types_lexemes_and_mapping_order_are_preserved(self): + payload = { + "last": [0, -10**100, 10**100] * 8, + "first": [None, True, False, 0, 1.0, -0.0, 1e-100, 1e100], + "unicode": "KíLín\n中文", + "empty": {}, + } + decoded = json.loads(trace_json_dumps(payload)) + self.assertEqual(list(decoded), list(payload)) + self.assertEqual( + json.dumps(decoded, ensure_ascii=False), + json.dumps(payload, ensure_ascii=False), + ) + self.assertEqual([type(value) for value in decoded["first"]], + [type(value) for value in payload["first"]]) + + def test_payload_is_not_mutated(self): + values = list(range(100)) + payload = {"first": values, "second": {"same": values}} + before = deepcopy(payload) + trace_json_dumps(payload) + self.assertEqual(payload, before) + self.assertIs(payload["first"], values) + self.assertIs(payload["second"]["same"], values) + + def test_standard_encoder_failures_are_unchanged(self): + circular_list = [] + circular_list.append(circular_list) + circular_mapping = {} + circular_mapping["self"] = circular_mapping + for payload in (b"bytes", {1, 2}, {(): 1}, + circular_list, circular_mapping): + with self.subTest(type=type(payload).__name__): + try: + json.dumps(payload, indent=2, ensure_ascii=False) + except (TypeError, ValueError) as error: + expected_type = type(error) + expected_message = str(error) + else: + self.fail("Fixture must be rejected by json.dumps.") + with self.assertRaises(expected_type) as raised: + trace_json_dumps(payload) + self.assertEqual(str(raised.exception), expected_message) + + def test_standard_nonfinite_serialization_is_not_reinterpreted(self): + # Diagnostic normalization and strict readers own their existing + # nonfinite-value policies; changing whitespace must not alter them. + payload = {"numbers": [float("nan"), float("inf"), -float("inf")]} + self.assertEqual(trace_json_dumps(payload), + json.dumps(payload, indent=2, ensure_ascii=False)) + + def test_varied_nested_json_round_trips_exactly(self): + generator = random.Random(1729) + for case in range(40): + payload = { + "integers": [generator.randrange(-10**30, 10**30) + for _ in range(generator.randrange(100))], + "mixed": [generator.choice((None, True, False, 3, 3.0, + "[1, 2]", "\n", "中文")) + for _ in range(40)], + "nested": [{"ids": list(range(case + 1))} for _ in range(3)], + } + with self.subTest(case=case): + self.assertEqual( + json.dumps(json.loads(trace_json_dumps(payload))), + json.dumps(payload), + ) + + +class TestTraceJSONWriters(unittest.TestCase): + """Verify actual traces and integrity hashes across formatting changes.""" + + def test_both_writers_retain_decoded_events_and_receipt_digest(self): + with TemporaryDirectory() as temporary: + root = Path(temporary).resolve() + directory = root / "logs" / "traces" + directory.mkdir(parents=True) + (root / "profile.ini").touch() + tokens = list(range(65)) + [2**80, -(2**80)] + for scope, name in (("project", "project.json"), + ("conversation", "conversation_a.json")): + logger = TraceLogger( + TraceConfig(enabled=True, output_path=directory / name, + failure_policy="raise"), + default_directory=directory, project_directory=root, + scope=scope, + ) + 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, + }) + logger.emit( + TRACE_EVENT_LLM_CALL_INPUT, + component="fixture", + data={ + "input_token_ids_artifact": logger.artifact( + "ids", tokens, + ), + "rendered_prompt_artifact": logger.artifact( + "prompt", "KíLín\n[0, 1]", text=True, + ), + }, + ) + logger.close() + + compact = read_recording(root) + self.assertEqual(compact.issues, []) + inputs = [event for event in compact.events + if event.event_type == TRACE_EVENT_LLM_CALL_INPUT] + self.assertEqual(len(inputs), 2) + for event in inputs: + self.assertEqual(event.exact_content["03_input_token_ids"][ + "value"], tokens) + self.assertEqual(event.exact_content["02_rendered_prompt"][ + "value"], "KíLín\n[0, 1]") + digest = _prefix_digest(tuple(compact.events), + len(compact.events)) + for name in ("project.json", "conversation_a.json"): + path = directory / name + encoded = path.read_text(encoding="utf-8") + ordinary = json.dumps(json.loads(encoded), indent=2, + ensure_ascii=False) + "\n" + self.assertLess(len(encoded), len(ordinary)) + path.write_text(ordinary, encoding="utf-8") + full = read_recording(root) + self.assertEqual(full.events, compact.events) + self.assertEqual(full.states, compact.states) + self.assertEqual(full.issues, compact.issues) + self.assertEqual(_prefix_digest(tuple(full.events), + len(full.events)), digest) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/test_model_settings.py b/tests/kilin/test_model_settings.py index b0ec7e5e..d15010df 100644 --- a/tests/kilin/test_model_settings.py +++ b/tests/kilin/test_model_settings.py @@ -1,7 +1,7 @@ """Verify core-owned router configuration without GUI or loaded models. -Use temporary project settings to exercise precedence, legacy input, -validation, and atomic persistence independently of desktop preferences. +Use temporary project settings to exercise precedence, obsolete-file +isolation, validation, and atomic persistence independently of the GUI. """ @@ -61,55 +61,35 @@ def test_core_defaults_match_shipped_gui_defaults(self) -> None: ) self.assertNotIn("[router]", self.profile.read_text()) - def test_saved_router_precedes_override_default_and_legacy(self) -> None: - """Saved router IDs are authoritative for core and GUI users.""" + def test_saved_router_precedes_override_default(self) -> None: + """Use initial choices only for backends without a saved router.""" - (self.root / "effort_levels.json").write_text( - json.dumps({"router": {BACKEND_MLX: "example/legacy"}}), - encoding="utf-8", - ) - self.assertEqual( - model_settings.read_router_model(self.root, BACKEND_MLX), - "example/legacy", - ) - model_settings.write_router_model( - self.root, BACKEND_MLX, " example/saved " - ) - for reader in (model_settings.read_router_model, - gui_settings.read_router_model, - kilin.read_router_model): - self.assertEqual( - reader( - self.root, BACKEND_MLX, - default_model="example/application", - ), - "example/saved", - ) - self.assertEqual( - model_settings.read_router_model(self.root, BACKEND_TORCH), - model_settings.default_router_model(BACKEND_TORCH), - ) - - def test_gui_preference_initializes_missing_saved_router(self) -> None: - """An initial preference does not override a saved model.""" - - self.assertEqual( - model_settings.read_router_model( - self.root, BACKEND_TORCH, - default_model="example/gui-preference", - ), - "example/gui-preference", - ) - model_settings.write_router_model( - self.root, BACKEND_TORCH, "example/project" - ) - self.assertEqual( - model_settings.read_router_model( - self.root, BACKEND_TORCH, - default_model="example/gui-preference", - ), - "example/project", - ) + for backend in (BACKEND_MLX, BACKEND_TORCH): + with self.subTest(backend=backend): + self.assertEqual( + model_settings.read_router_model(self.root, backend), + model_settings.default_router_model(backend), + ) + self.assertEqual( + model_settings.read_router_model( + self.root, backend, + default_model="example/application", + ), + "example/application", + ) + model_settings.write_router_model( + self.root, backend, " example/saved " + ) + for reader in (model_settings.read_router_model, + gui_settings.read_router_model, + kilin.read_router_model): + self.assertEqual( + reader( + self.root, backend, + default_model="example/application", + ), + "example/saved", + ) def test_atomic_write_preserves_unrelated_options(self) -> None: """Editing the router must not change other project options.""" @@ -157,24 +137,38 @@ def test_invalid_configuration_is_rejected_without_writes(self) -> None: with self.assertRaises(ValueError): model_settings.read_router_model(self.root, BACKEND_MLX) - def test_legacy_configuration_does_not_modify_project(self) -> None: - """Read legacy router settings without performing migration.""" + def test_obsolete_router_file_is_ignored_without_writes(self) -> None: + """Ignore valid and malformed sidecars, including saved routers.""" old = self.root / "effort_levels.json" - old.write_text( + for contents in ( json.dumps({"router": {BACKEND_TORCH: "example/old"}}), - encoding="utf-8", + "{invalid", + ): + with self.subTest(contents=contents): + old.write_text(contents, encoding="utf-8") + before = self.profile.read_bytes() + old_before = old.read_bytes() + self.assertEqual( + model_settings.read_router_model(self.root, BACKEND_TORCH), + model_settings.default_router_model(BACKEND_TORCH), + ) + self.assertEqual( + model_settings.read_router_model( + self.root, BACKEND_TORCH, + default_model="example/application", + ), + "example/application", + ) + self.assertEqual(self.profile.read_bytes(), before) + self.assertEqual(old.read_bytes(), old_before) + model_settings.write_router_model( + self.root, BACKEND_TORCH, "example/saved" ) - profile_before = self.profile.read_bytes() self.assertEqual( model_settings.read_router_model(self.root, BACKEND_TORCH), - "example/old", + "example/saved", ) - self.assertEqual(self.profile.read_bytes(), profile_before) - self.assertTrue(old.exists()) - old.write_text("{invalid", encoding="utf-8") - with self.assertRaises(json.JSONDecodeError): - model_settings.read_router_model(self.root, BACKEND_TORCH) if __name__ == "__main__": diff --git a/tests/kilin/test_project.py b/tests/kilin/test_project.py index e2339f3b..b5020413 100644 --- a/tests/kilin/test_project.py +++ b/tests/kilin/test_project.py @@ -159,17 +159,6 @@ def _write(self, directory: Path, relative: str, content: str) -> Path: class TestProjectTypeIds(ProjectFixture): """Check the mapping from type definitions to project defaults.""" - def test_registry_identifiers_are_not_a_builtin_allowlist(self) -> None: - """Expose configured types without type-specific Python constants.""" - - current = load_project_types() - self.assertEqual(project.PROJECT_TYPE_IDS, tuple(current)) - self.assertTrue(project.PROJECT_TYPE_IDS) - self.assertFalse(hasattr(project, "_check_built_in_kinds")) - self.assertFalse( - any(name.startswith("PROJECT_TYPE_ID_") for name in vars(project)) - ) - def test_default_profiles_match_loaded_packaged_definitions(self) -> None: """File filters and size limits follow data, not hard-coded values.""" @@ -194,7 +183,7 @@ def test_default_profiles_match_loaded_packaged_definitions(self) -> None: def test_default_profiles_use_canonical_model_defaults(self) -> None: """Resolve chat and embedding settings for each selected backend.""" - for type_id in project.PROJECT_TYPE_IDS: + for type_id in project.project_type_ids(): with self.subTest(type_id=type_id): item = project.default_project_profile(type_id) self.assertEqual(item.chat_mlx, DEFAULT_CHAT_MODEL_MLX) @@ -233,7 +222,7 @@ def test_initialize_all_types_without_modifying_source_files( ) -> None: """Initialize every packaged type and preserve existing data.""" - for type_id in project.PROJECT_TYPE_IDS: + for type_id in project.project_type_ids(): with self.subTest(type_id=type_id): directory = self._folder(type_id) original = self._write( @@ -300,7 +289,7 @@ def test_every_creation_path_uses_sources(self) -> None: original = self._folder("original") self._write(original, "notes.md", "text") - for type_id in project.PROJECT_TYPE_IDS: + for type_id in project.project_type_ids(): with self.subTest(type_id=type_id): created = ( project.initialize_project( @@ -417,7 +406,7 @@ class TestProjectProfileValidation(ProjectFixture): def test_default_template_round_trip(self) -> None: """Parse the canonical INI format without changing its contents.""" - for type_id in project.PROJECT_TYPE_IDS: + for type_id in project.project_type_ids(): with self.subTest(type_id=type_id): root = self._profile(f"roundtrip-{type_id}", type_id=type_id) parsed = project.open_project(root) diff --git a/tests/kilin/test_project__creation.py b/tests/kilin/test_project__creation.py index 50470edf..97180592 100644 --- a/tests/kilin/test_project__creation.py +++ b/tests/kilin/test_project__creation.py @@ -104,7 +104,7 @@ def test_initialize_cannot_bypass_existing_project_guard(self): """Enforce ownership through the lower-level public initializer.""" project = self.create() before = self.snapshot(project.root) - for type_id in kilin.PROJECT_TYPE_IDS: + for type_id in kilin.project_type_ids(): with self.subTest(type_id=type_id): with self.assertRaises(kilin.ProjectAlreadyExistsError): kilin.initialize_project(project.root, type_id) diff --git a/tests/kilin/test_project_layout.py b/tests/kilin/test_project_layout.py index c6f18276..2b908db0 100644 --- a/tests/kilin/test_project_layout.py +++ b/tests/kilin/test_project_layout.py @@ -40,7 +40,8 @@ workspace_resources, SHIPPED_TEMPLATES_DIR, ) -from kilin.tools._registry import TOOL_REGISTRY, ToolUse +from kilin.tools import ToolUse, registered_tools +from kilin.tools import _registry from kilin.tools.project_summary import ( SHIPPED_TEMPLATES_DIR as PROJECT_TEMPLATES_DIR, ) @@ -102,7 +103,7 @@ def _fake_plan( """ tool = replace( - TOOL_REGISTRY["generate_paper_summary"], + registered_tools()["generate_paper_summary"], workspace_resources=lambda _: resources, ) definition = SimpleNamespace( @@ -115,9 +116,9 @@ def _fake_plan( with patch( "kilin.project_layout.project_type", return_value=definition ): - with patch.dict( - TOOL_REGISTRY, {"generate_paper_summary": tool} - ): + entries = dict(registered_tools()) + entries["generate_paper_summary"] = tool + with patch.object(_registry, "_registry", entries): return plan_project_layout("synthetic") def test_code_project_has_empty_templates_directory(self) -> None: diff --git a/tests/kilin/test_project_type.py b/tests/kilin/test_project_type.py index dbff47bb..27c2c075 100644 --- a/tests/kilin/test_project_type.py +++ b/tests/kilin/test_project_type.py @@ -219,7 +219,7 @@ def test_builtin_types_load_as_independent_json_files(self) -> None: self.assertIn("code", types) self.assertIn("literature", types) self.assertEqual( - project.PROJECT_TYPE_IDS, tuple(types) + project.project_type_ids(), tuple(types) ) for path in paths: with self.subTest(type_id=path.stem): diff --git a/tests/kilin/test_rag__answering.py b/tests/kilin/test_rag__answering.py index 6aa7be67..fbc7a87d 100644 --- a/tests/kilin/test_rag__answering.py +++ b/tests/kilin/test_rag__answering.py @@ -27,8 +27,7 @@ project_type, ) from kilin.retrievals import DocumentSelection -from kilin.tools import ToolResult, ToolUse -from kilin.tools._registry import TOOL_REGISTRY +from kilin.tools import ToolResult, ToolUse, registered_tools from kilin.trace_logging import NullTraceLogger, TraceConfig, TraceLogger from tests.kilin.retrievals._support import chunk, ranked @@ -1369,9 +1368,8 @@ def test_tool_runs_with_project_settings_and_is_traced(self) -> None: session._earlier_turns = Mock(return_value=()) trace = MagicMock() session.trace = trace - settings = TOOL_REGISTRY["project_inventory"].parse_settings( - {}, "test" - ) + descriptor = registered_tools()["project_inventory"] + settings = descriptor.parse_settings({}, "test") use = ToolUse("project_inventory", settings) result = ToolResult("result", (), {"ok": True}) with patch.object(rag, "run_tool", return_value=result) as runner: @@ -1387,9 +1385,9 @@ def test_tool_runs_with_project_settings_and_is_traced(self) -> None: ) self.assertEqual(identity["name"], "project_inventory") self.assertEqual(identity["origin"], "distribution") - self.assertEqual(identity["version"], TOOL_REGISTRY[use.name].version) - self.assertEqual(identity["api_version"], - TOOL_REGISTRY[use.name].api_version) + descriptor = registered_tools()[use.name] + self.assertEqual(identity["version"], descriptor.version) + self.assertEqual(identity["api_version"], descriptor.api_version) self.assertRegex(identity["sha256"], r"^[0-9a-f]{64}$") trace.span.assert_any_call( "tool.run", diff --git a/tests/kilin/test_rag__tool_budgets.py b/tests/kilin/test_rag__tool_budgets.py index 1b92a285..cdddb436 100644 --- a/tests/kilin/test_rag__tool_budgets.py +++ b/tests/kilin/test_rag__tool_budgets.py @@ -16,7 +16,7 @@ from kilin import rag from kilin.project_type import RETRIEVAL_MODE_NONE -from kilin.tools import TOOL_REGISTRY, ToolResult, ToolUse +from kilin.tools import ToolResult, ToolUse, registered_tools from tests.kilin._rag_support import _answer_patches, _intent, _session from tests.kilin.test_rag__tool_thinking import _run from tests.kilin.test_answering import _FakeChat @@ -31,7 +31,7 @@ def test_all_tool_adapters_inherit_user_ceiling(self) -> None: "find_passages", "generate_paper_summary", "writing_check", "project_summary", } - for name in TOOL_REGISTRY: + for name in registered_tools(): for thinking in (True, False): for ceiling in (128, 2048, 16384): with self.subTest(tool=name, thinking=thinking, diff --git a/tests/kilin/test_settings_info.py b/tests/kilin/test_settings_info.py index 84404459..d9dadde2 100644 --- a/tests/kilin/test_settings_info.py +++ b/tests/kilin/test_settings_info.py @@ -32,7 +32,7 @@ get_settings_info, get_tool_settings_info, ) -from kilin.tools._registry import TOOL_CHOICES +from kilin.tools import tool_choices class TestSettingsInfo(unittest.TestCase): @@ -123,7 +123,7 @@ def test_every_tool_declared_setting_is_described(self): from importlib.resources import files catalog = get_settings_info()["settings"] - for name in TOOL_CHOICES: + for name in tool_choices(): with self.subTest(tool=name): root = files(f"kilin.tools.{name}") data = json.loads(root.joinpath("defaults.json") @@ -195,10 +195,10 @@ def test_invalid_metadata_does_not_affect_core_operations(self): with patch("kilin.settings_info._load_resource", side_effect=ValueError("Bad metadata")): from kilin.project_type import project_type - from kilin.tools._registry import TOOL_REGISTRY + from kilin.tools import registered_tools self.assertEqual(project_type("literature").id, "literature") - self.assertIn("reference_check", TOOL_REGISTRY) + self.assertIn("reference_check", registered_tools()) if __name__ == "__main__": diff --git a/tests/kilin/test_trace_logging.py b/tests/kilin/test_trace_logging.py index 849f80f3..7d065644 100644 --- a/tests/kilin/test_trace_logging.py +++ b/tests/kilin/test_trace_logging.py @@ -190,10 +190,8 @@ def test_startup_and_close_have_one_ordered_lifecycle(self) -> None: [1, 3], ) self.assertEqual(runtime["01_custom_ready"]["event"]["sequence"], 2) - self.assertEqual( - trace_events["01_trace_started"]["details"]["mode"], - "forensic", - ) + self.assertNotIn("mode", + trace_events["01_trace_started"]["details"]) def test_event_validation_precedes_mutation(self) -> None: """Reject blank names without consuming sequence numbers.""" @@ -497,7 +495,7 @@ def test_explicit_parent_and_exception_event(self) -> None: class TestTraceArtifacts(unittest.TestCase): - """Check inline content, conversion, and controlled legacy resolution.""" + """Check inline content, conversion, and unsupported file payloads.""" def setUp(self) -> None: """Initialize full diagnostic tracing in a disposable directory.""" @@ -589,35 +587,32 @@ class Sample: with self.assertRaises(ValueError): self.logger.artifact("...", 12) - def test_legacy_artifact_stays_inside_output_directory(self) -> None: - """Reject traversal and accept readable old local artifact files.""" + def test_path_only_artifacts_are_not_read(self) -> None: + """Ignore path-only payloads without consulting the filesystem.""" (self.root / "payload.json").write_text( '[1, 2]', encoding="utf-8" ) outside = self.root.parent / "outside.json" - with patch.object( - self.logger, "_artifact_content", - wraps=self.logger._artifact_content, - ) as content: - self.assertEqual(content({ - "path": "payload.json", "format": "json" - }), [1, 2]) - self.assertIsNone(content({ - "path": "../outside.json", "format": "json" - })) - self.assertIsNone(content({ - "path": str(outside), "format": "json" - })) - self.assertIsNone(content({"path": "missing.json"})) - self.assertEqual(content({ + with patch.object(Path, "read_text") as read: + for reference in ( + {"path": "payload.json", "format": "json"}, + {"path": "../outside.json", "format": "json"}, + {"path": str(outside), "format": "json"}, + {"path": "missing.json"}, + ): + with self.subTest(reference=reference): + self.assertIsNone(self.logger._artifact_content( + reference + )) + self.assertEqual(self.logger._artifact_content({ "inline_content": "preferred", "path": "missing.json" }), "preferred") + read.assert_not_called() - - def test_legacy_symlink_artifact_cannot_escape_trace_directory( + def test_linked_artifact_is_not_read( self, ) -> None: - """Reject an in-directory link pointing outside the trace tree.""" + """Do not load content through a path to a symbolic link.""" with TemporaryDirectory() as other_directory: outside = Path(other_directory) / "secret.json" outside.write_text('["private"]', encoding="utf-8") @@ -631,23 +626,41 @@ def test_legacy_symlink_artifact_cannot_escape_trace_directory( })) + def test_file_reference_is_not_projected_as_exact_content(self) -> None: + """Keep unsupported payloads without inventing exact artifacts.""" + artifact = self.root / "prompt.txt" + artifact.write_text("unrecorded prompt", encoding="utf-8") + reference = {"path": artifact.name, "format": "text"} + with patch.object(Path, "read_text") as read: + self.logger.emit( + TRACE_EVENT_LLM_CALL_INPUT, component="chat", + data={"rendered_prompt_artifact": reference}, + ) + read.assert_not_called() + operations = _operations(_payload(self.path), "runtime") + inputs = operations["01_llm_call_input"] + self.assertNotIn("exact_content", inputs) + self.assertEqual(inputs["details"]["rendered_prompt_artifact"], + reference) + self.assertEqual(artifact.read_text(encoding="utf-8"), + "unrecorded prompt") + def test_artifact_is_unavailable_after_logger_closes(self) -> None: """Avoid producing untracked content after the trace is closed.""" self.assertIsNotNone(self.logger.artifact("before", "content")) self.logger.close() self.assertIsNone(self.logger.artifact("after", "content")) - def test_legacy_text_and_invalid_json_artifacts(self) -> None: - """Read legacy text files while ignoring malformed JSON assets.""" + def test_file_artifact_types_are_ignored(self) -> None: + """Ignore file artifacts regardless of content or declared format.""" (self.root / "output.txt").write_text( "legacy text", encoding="utf-8" ) (self.root / "broken.json").write_text( "not json", encoding="utf-8" ) - self.assertEqual( - self.logger._artifact_content({"path": "output.txt"}), - "legacy text", + self.assertIsNone( + self.logger._artifact_content({"path": "output.txt"}) ) self.assertIsNone(self.logger._artifact_content({ "path": "broken.json", "format": "json" @@ -740,16 +753,16 @@ def test_reopen_appends_new_readable_turns_and_retains_state(self) -> None: ) self.assertEqual(payload["event_count"], 3) - def test_legacy_standard_trace_remains_readable_and_complete( + def test_reopen_preserves_prior_metadata_without_emitting_mode( self, ) -> None: - """Retain legacy mode metadata without filtering later events.""" + """Keep prior event metadata without emitting obsolete modes.""" first = self._open() first.emit("custom.earlier", component="test") first.close() prior = _payload(self.path) - legacy_start = _operations(prior, "trace")["01_trace_started"] - legacy_start["details"]["mode"] = "standard" + earlier_start = _operations(prior, "trace")["01_trace_started"] + earlier_start["details"]["mode"] = "standard" self.path.write_text(json.dumps(prior), encoding="utf-8") later = self._open() @@ -761,10 +774,14 @@ def test_legacy_standard_trace_remains_readable_and_complete( later.close() updated = _payload(self.path) self.assertEqual( - _operations(updated, "trace")["01_trace_started"]["details"] - ["mode"], - "standard", + _operations(updated, "trace")["01_trace_started"], earlier_start ) + starts = [node for session in updated["sessions"].values() + for node in session.get("operations", {}).values() + if (node["event"]["event_type"] == "trace.started" + and node["event"]["trace_id"] == later.trace_id)] + self.assertEqual(len(starts), 1) + self.assertNotIn("mode", starts[0]["details"]) self.assertIn("custom_earlier", self.path.read_text(encoding="utf-8")) self.assertIn( "llm_call_output_tokens", self.path.read_text(encoding="utf-8") diff --git a/tests/kilin/test_trace_logging__configuration.py b/tests/kilin/test_trace_logging__configuration.py index 49f7c0e9..84134615 100644 --- a/tests/kilin/test_trace_logging__configuration.py +++ b/tests/kilin/test_trace_logging__configuration.py @@ -18,11 +18,12 @@ from kilin import _trace_project from kilin._trace_configuration import ( + CONFIGURATION_CONTENT_REFERENCE, CONFIGURATION_EVENT, - CONFIGURATION_REFERENCE, - configuration_bytes, - configuration_reference, + configuration_content_bytes, + configuration_content_reference, ) +from kilin.system_testing.traces import read_recording from kilin.trace_logging import NullTraceLogger, TraceConfig, TraceLogger @@ -117,9 +118,10 @@ def test_change_and_restore_across_logger_runs(self): ): self.assertEqual(rows[full]["details"], expected) self.assertEqual(rows[reference]["details"], - configuration_reference( + configuration_content_reference( rows[full]["event"]["sequence"], - configuration_bytes(expected), + configuration_content_bytes(expected), + expected["behavior"]["project"], )) self.assertNotEqual(rows[0]["event"]["trace_id"], rows[1]["event"]["trace_id"]) @@ -132,7 +134,8 @@ def test_json_order_and_type_sensitive_comparison(self): reordered = dict(reversed(list(self.config.items()))) reordered["profile"] = {"thinking": False, "temperature": 0.0} self._emit(logger, reordered) - self.assertIn(CONFIGURATION_REFERENCE, self._nodes()[-1]["details"]) + self.assertIn(CONFIGURATION_CONTENT_REFERENCE, + self._nodes()[-1]["details"]) for value in (1.0, True, 1): changed = _configuration(self.root, value) self._emit(logger, changed) @@ -155,7 +158,146 @@ def test_all_setting_groups_and_historical_path_are_significant(self): else: changed[key]["extra"] = "changed" self._emit(logger, changed) + if key == "behavior": + node = self._nodes()[-1] + self.assertIn(CONFIGURATION_CONTENT_REFERENCE, + node["details"]) + self.assertEqual(node["details"]["project"], + changed["behavior"]["project"]) + recording = read_recording(self.root) + self.assertFalse(recording.issues, recording.issues) + self.assertEqual(recording.events[-1].details, changed) + else: + self.assertEqual(self._nodes()[-1]["details"], changed) + + def test_relocated_paths_reuse_one_complete_snapshot_across_runs(self): + expected = [] + for project in (str(self.root), "../KíLín moved", None, + "C:\\workspace\\copy", str(self.root)): + logger = self._logger() + data = deepcopy(self.config) + data["behavior"]["project"] = project + self._emit(logger, data) + expected.append(data) + logger.close() + rows = self._nodes() + first = rows[0] + encoded = configuration_content_bytes(expected[0]) + self.assertEqual(first["details"], expected[0]) + for row, data in zip(rows[1:], expected[1:]): + self.assertEqual(row["details"], configuration_content_reference( + first["event"]["sequence"], encoded, + data["behavior"]["project"], + )) + recording = read_recording(self.root) + self.assertFalse(recording.issues, recording.issues) + observations = [event for event in recording.events + if event.event_type == CONFIGURATION_EVENT] + self.assertEqual([event.details for event in observations], expected) + self.assertEqual([event.metadata for event in observations], + [node["event"] for node in rows]) + self._assert_recording_identity() + + def test_missing_path_and_other_settings_are_not_relocated(self): + logger = self._logger() + incomplete = deepcopy(self.config) + del incomplete["behavior"]["project"] + self._emit(logger, incomplete) + explicit_null = deepcopy(self.config) + explicit_null["behavior"]["project"] = None + self._emit(logger, explicit_null) + self.assertEqual(self._nodes()[-1]["details"], explicit_null) + self._emit(logger, incomplete) + self.assertEqual(self._nodes()[-1]["details"], incomplete) + for key, value in (("prompt", "changed"), ("extra", "new")): + with self.subTest(key=key): + self._emit(logger) + changed = deepcopy(self.config) + changed["behavior"]["project"] = "renamed" + changed["behavior"][key] = value + self._emit(logger, changed) self.assertEqual(self._nodes()[-1]["details"], changed) + self._emit(logger) + changed = deepcopy(self.config) + changed["behavior"]["project"] = "renamed" + changed["extra"] = {"project": "independent path"} + self._emit(logger, changed) + self.assertEqual(self._nodes()[-1]["details"], changed) + + def test_relocated_reference_uses_one_project_read_and_write(self): + logger = self._logger() + self._emit(logger) + changed = deepcopy(self.config) + changed["behavior"]["project"] = "relocated" + with ( + patch.object(_trace_project, "_read_object", + wraps=_trace_project._read_object) as read, + patch.object(_trace_project, "atomic_write_text", + wraps=_trace_project.atomic_write_text) as write, + ): + self._emit(logger, changed) + self.assertIn(CONFIGURATION_CONTENT_REFERENCE, + self._nodes()[-1]["details"]) + self.assertEqual(sum(call.args[0] == self.path + for call in read.call_args_list), 1) + self.assertEqual(sum(call.args[0] == self.path + for call in write.call_args_list), 1) + self.assertEqual(read.call_count, 2) + self.assertEqual(write.call_count, 2) + + def test_small_relocated_payload_remains_full(self): + logger = self._logger() + minimal = {key: {} for key in self.config} + minimal["behavior"]["project"] = "a" + self._emit(logger, minimal) + minimal["behavior"]["project"] = "b" + self._emit(logger, minimal) + self.assertEqual(self._nodes()[-1]["details"], minimal) + + def test_small_unchanged_payload_remains_full(self): + logger = self._logger() + minimal = {key: {} for key in self.config} + minimal["behavior"]["project"] = "a" + self._emit(logger, minimal) + self._emit(logger, minimal) + self.assertEqual(self._nodes()[-1]["details"], minimal) + + def test_concurrent_relocation_references_keep_each_observed_path(self): + first, second = self._logger(), self._logger() + self._emit(first) + barrier = Barrier(2) + + def run(logger, prefix): + for number in range(3): + data = deepcopy(self.config) + data["behavior"]["project"] = f"{prefix}/{number}" + barrier.wait(timeout=10) + self._emit(logger, data) + + with ThreadPoolExecutor(max_workers=2) as pool: + tasks = [pool.submit(run, logger, prefix) + for logger, prefix in ((first, "first"), + (second, "second"))] + for task in tasks: + task.result(timeout=30) + first.close() + second.close() + rows = self._nodes() + target = rows[0]["event"]["sequence"] + for node in rows[1:]: + self.assertEqual(node["details"][CONFIGURATION_CONTENT_REFERENCE] + ["sequence"], target) + recording = read_recording(self.root) + self.assertFalse(recording.issues, recording.issues) + for logger, paths in ((first, [str(self.root)] + + [f"first/{i}" for i in range(3)]), + (second, [f"second/{i}" for i in range(3)])): + actual = [event.details["behavior"]["project"] + for event in recording.events + if event.event_type == CONFIGURATION_EVENT + and event.metadata["trace_id"] == logger.trace_id] + self.assertEqual(actual, paths) + self._assert_recording_identity() def test_separate_workspaces_and_conversation_traces(self): logger = self._logger() @@ -265,11 +407,14 @@ def _assert_ordered_observations(self, expected): expected[trace_id][position]) positions[trace_id] += 1 sequence = event["sequence"] - encoded = configuration_bytes(configuration) + encoded = configuration_content_bytes(configuration) if latest is not None and latest[1] == encoded: - self.assertEqual(row["details"], configuration_reference( - latest[0], encoded - )) + self.assertEqual( + row["details"], configuration_content_reference( + latest[0], encoded, + configuration["behavior"]["project"] + ) + ) else: self.assertEqual(row["details"], configuration) latest = (sequence, encoded) @@ -365,7 +510,7 @@ def fail(path, content): next_logger = self._logger() self._emit(next_logger) next_logger.close() - self.assertIn(CONFIGURATION_REFERENCE, + self.assertIn(CONFIGURATION_CONTENT_REFERENCE, self._nodes()[-1]["details"]) def test_disabled_trace_performs_no_configuration_io(self): diff --git a/tests/kilin/test_trace_logging__semantics.py b/tests/kilin/test_trace_logging__semantics.py new file mode 100644 index 00000000..5ed636db --- /dev/null +++ b/tests/kilin/test_trace_logging__semantics.py @@ -0,0 +1,284 @@ +"""Verify shared semantic manifests without changing recorded operations.""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from concurrent.futures import ThreadPoolExecutor +import json +from threading import Barrier +import unittest +from unittest.mock import patch +import warnings + +from kilin import _trace_project +from kilin._trace_snapshots import ( + SEMANTIC_SNAPSHOT_EVENTS, SEMANTIC_SNAPSHOT_REFERENCE, + SOURCE_SNAPSHOT_REFERENCE, +) +from kilin.system_testing.traces import read_recording +from tests.kilin import test_trace_logging__sources as sources + +REFERENCE = SEMANTIC_SNAPSHOT_REFERENCE +OBSERVED = sources.SEMANTIC +COMMITTED = "source_organization.committed" +RECONCILED = "source_organization.reconciled" +APPLIED = "gui.source_organization.apply.completed" + + +def semantic_details(kind, value=1): + """Supply exact shared state with deliberately independent outcomes.""" + + observed = sources.observation(OBSERVED, value) + if kind == OBSERVED: + return observed + return { + "source_organization": observed["source_organization"], + "revision": value, + "previous_revision": value - 1, + "sha256": "b" * 64, + "command_id": kind, + "extra": {"kind": kind, "text": "KíLín", "null": None}, + } + + +def semantic_nodes(payload): + """Read only semantic operation nodes in their allocation order.""" + + return sorted([ + node for session in payload["sessions"].values() + for node in session.get("operations", {}).values() + if node["event"]["event_type"] in SEMANTIC_SNAPSHOT_EVENTS + ], key=lambda node: node["event"]["sequence"]) + + +class TestSemanticSnapshotRecording(unittest.TestCase): + """Exercise normal, concurrent and failed publications through loggers.""" + + def setUp(self): + fixture = sources.TestSourceSnapshotRecording() + self.addCleanup(fixture.doCleanups) + fixture.setUp() + self.fixture = fixture + + def _emit(self, logger, kind, value=1, **kwargs): + data = semantic_details(kind, value) + logger.emit(kind, component="semantic_fixture", data=data, **kwargs) + return data + + def _nodes(self): + return semantic_nodes(self.fixture._raw()) + + def _assert_decoded(self, expected): + before = self.fixture.path.read_bytes() + recording = read_recording(self.fixture.root) + self.assertFalse(recording.issues, recording.issues) + events = [event for event in recording.events + if event.event_type in SEMANTIC_SNAPSHOT_EVENTS] + self.assertEqual([event.details for event in events], expected) + self.assertEqual([event.metadata for event in events], + [node["event"] for node in self._nodes()]) + self.assertEqual(before, self.fixture.path.read_bytes()) + return events + + def test_cross_event_reuse_preserves_opening_group_and_context(self): + expected = [] + for kinds in ((OBSERVED, COMMITTED), + (APPLIED, RECONCILED, OBSERVED)): + logger = self.fixture._logger() + with logger.span("semantic_command", component="fixture"): + for kind in kinds: + expected.append(self._emit(logger, kind)) + logger.close() + rows = self._nodes() + first = rows[0] + for row in rows[1:4]: + reference = row["details"][REFERENCE] + self.assertEqual(reference["sequence"], + first["event"]["sequence"]) + self.assertNotIn("source_organization", row["details"]) + self.assertIn("span_id", row["event"]) + self.assertIn(SOURCE_SNAPSHOT_REFERENCE, rows[-1]["details"]) + self.assertNotIn(REFERENCE, rows[-1]["details"]) + events = self._assert_decoded(expected) + self.assertIsNot(events[0].details["source_organization"], + events[1].details["source_organization"]) + + def test_changes_and_restoration_keep_direct_latest_full_targets(self): + logger = self.fixture._logger() + expected = [] + for value, kind in ((1, COMMITTED), (1, APPLIED), + (2, RECONCILED), (2, APPLIED), + (1, COMMITTED), (1, APPLIED)): + expected.append(self._emit(logger, kind, value)) + logger.close() + rows = self._nodes() + for first, second in zip(rows[::2], rows[1::2]): + self.assertNotIn(REFERENCE, first["details"]) + self.assertEqual(second["details"][REFERENCE]["sequence"], + first["event"]["sequence"]) + self._assert_decoded(expected) + + def test_compact_opening_never_becomes_semantic_reference_target(self): + logger = self.fixture._logger() + expected = [self._emit(logger, kind) for kind in + (OBSERVED, OBSERVED, COMMITTED, APPLIED)] + logger.close() + rows = self._nodes() + self.assertIn(SOURCE_SNAPSHOT_REFERENCE, rows[1]["details"]) + self.assertEqual(rows[2]["details"][REFERENCE]["sequence"], + rows[0]["event"]["sequence"]) + self.assertEqual(rows[3]["details"][REFERENCE]["sequence"], + rows[0]["event"]["sequence"]) + self._assert_decoded(expected) + + def test_manifest_types_order_and_unknown_fields_remain_significant(self): + logger = self.fixture._logger() + expected = [] + for value in (1, 1.0, True, [1, 2], [2, 1], None, "KíLín"): + data = semantic_details(COMMITTED) + data["source_organization"]["future_field"] = value + logger.emit(COMMITTED, component="fixture", data=data) + expected.append(data) + self.assertEqual(self._nodes()[-1]["details"], data) + reordered = dict(reversed(list(data.items()))) + reordered["source_organization"] = dict(reversed(list( + data["source_organization"].items()))) + logger.emit(APPLIED, component="fixture", data=reordered) + expected.append(reordered) + self.assertIn(REFERENCE, self._nodes()[-1]["details"]) + logger.close() + self._assert_decoded(expected) + + def test_old_opening_reference_does_not_replace_newer_full_state(self): + logger = self.fixture._logger() + expected = [self._emit(logger, kind, value) for kind, value in ( + (OBSERVED, 1), (COMMITTED, 2), (OBSERVED, 1), (APPLIED, 1), + )] + logger.close() + rows = self._nodes() + self.assertIn(SOURCE_SNAPSHOT_REFERENCE, rows[2]["details"]) + self.assertNotIn(REFERENCE, rows[3]["details"]) + self._assert_decoded(expected) + + def test_failed_and_incomplete_full_states_reset_the_candidate(self): + logger = self.fixture._logger() + expected = [] + for problem in ("failed", "missing", "null", "error", "trace_error"): + with self.subTest(problem=problem): + expected.append(self._emit(logger, COMMITTED)) + data = semantic_details(RECONCILED) + status = "completed" + if problem == "failed": + status = "failed" + elif problem == "missing": + data.pop("source_organization") + elif problem == "null": + data["source_organization"] = None + else: + data[problem] = "incomplete" + logger.emit(RECONCILED, component="fixture", data=data, + status=status) + expected.append(data) + expected.append(self._emit(logger, APPLIED)) + self.assertNotIn(REFERENCE, self._nodes()[-1]["details"]) + logger.close() + self._assert_decoded(expected) + + def test_tiny_turn_and_conversation_snapshots_stay_inline(self): + logger = self.fixture._logger() + tiny = {"source_organization": {}} + for kind in (COMMITTED, APPLIED): + logger.emit(kind, component="fixture", data=tiny) + self.assertEqual(self._nodes()[-1]["details"], tiny) + self._emit(logger, COMMITTED) + self._emit(logger, APPLIED, turn_id="turn_fixture") + self.assertNotIn(REFERENCE, self._nodes()[-1]["details"]) + conversation = self.fixture._logger( + scope="conversation", name="conversation_a.json") + for kind in (COMMITTED, APPLIED): + self._emit(conversation, kind) + conversation.close() + payload = json.loads(conversation.readable_path.read_text("utf-8")) + for node in semantic_nodes(payload): + self.assertNotIn(REFERENCE, node["details"]) + + def test_compaction_adds_no_project_read_or_write(self): + logger = self.fixture._logger() + self._emit(logger, COMMITTED) + with ( + patch.object(_trace_project, "_read_object", + wraps=_trace_project._read_object) as read, + patch.object(_trace_project, "atomic_write_text", + wraps=_trace_project.atomic_write_text) as write, + ): + self._emit(logger, APPLIED) + self.assertEqual(read.call_count, 2) + self.assertEqual(write.call_count, 2) + self.assertEqual(sum(call.args[0] == self.fixture.path + for call in read.call_args_list), 1) + self.assertEqual(sum(call.args[0] == self.fixture.path + for call in write.call_args_list), 1) + + def test_concurrent_writers_preserve_every_original_payload(self): + first, second = self.fixture._logger(), self.fixture._logger() + submitted = {first.trace_id: (1, 2, 1, 1), + second.trace_id: (1, 1, 2, 2)} + barrier = Barrier(2) + + def run(logger): + for value in submitted[logger.trace_id]: + barrier.wait(timeout=10) + self._emit(logger, APPLIED, value) + + with ThreadPoolExecutor(max_workers=2) as pool: + tasks = [pool.submit(run, logger) for logger in (first, second)] + for task in tasks: + task.result(timeout=30) + first.close() + second.close() + positions = dict.fromkeys(submitted, 0) + expected = [] + for node in self._nodes(): + trace_id = node["event"]["trace_id"] + value = submitted[trace_id][positions[trace_id]] + positions[trace_id] += 1 + expected.append(semantic_details(APPLIED, value)) + self.assertEqual(positions, {key: 4 for key in submitted}) + self._assert_decoded(expected) + + def test_failed_publication_preserves_history_and_releases_lease(self): + for policy in ("warn", "raise"): + with self.subTest(policy=policy): + logger = self.fixture._logger(policy=policy) + self._emit(logger, COMMITTED) + before = self.fixture.path.read_bytes() + original = _trace_project.atomic_write_text + + def fail(path, content): + if path == self.fixture.path: + raise OSError("semantic publication failure") + original(path, content) + + with patch.object(_trace_project, "atomic_write_text", + side_effect=fail): + if policy == "raise": + with self.assertRaisesRegex(RuntimeError, + "semantic publication"): + self._emit(logger, APPLIED) + else: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + self._emit(logger, APPLIED) + self.assertTrue(caught) + self.assertEqual(before, self.fixture.path.read_bytes()) + logger.close() + fresh = self.fixture._logger() + self._emit(fresh, APPLIED) + fresh.close() + counter = self.fixture.directory / ".sequence.json" + self.assertTrue(json.loads(counter.read_text())["incomplete"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/test_trace_logging__sources.py b/tests/kilin/test_trace_logging__sources.py new file mode 100644 index 00000000..ab0dac0c --- /dev/null +++ b/tests/kilin/test_trace_logging__sources.py @@ -0,0 +1,409 @@ +"""Exercise source snapshot compaction and exact historical reconstruction.""" + +# pylint: disable=C0115:missing-class-docstring +# pylint: disable=C0116:missing-function-docstring +# pylint: disable=C0103:invalid-name + +from concurrent.futures import ThreadPoolExecutor +from copy import deepcopy +from hashlib import sha256 +import json +from pathlib import Path +import subprocess +import sys +from tempfile import TemporaryDirectory +from threading import Barrier +import unittest +from unittest.mock import patch +import warnings + +from kilin import _trace_project +from kilin._trace_snapshots import ( + SOURCE_SNAPSHOT_FIELDS, + SOURCE_SNAPSHOT_REFERENCE, +) +from kilin.system_testing.traces import read_recording +from kilin.trace_logging import NullTraceLogger, TraceConfig, TraceLogger + +SCAN = "source.scan.completed" +INDEX = "index.check.completed" +SEMANTIC = "gui.source_organization.observed" +REFERENCE = SOURCE_SNAPSHOT_REFERENCE + + +def observation(kind, value=1, reason="open"): + """Supply large stable groups with independent operation-specific data.""" + files = {f"source_{i}.txt": {"size_bytes": value, "sha256": "a" * 64} + for i in range(6)} + if kind == SCAN: + return {"repository": reason, "complete": True, + "selected_file_count": len(files), + "selected_files": list(files), + "entries": [{"path": name, **data} + for name, data in files.items()]} + if kind == INDEX: + return {"index_path": reason, "source_manifest": {"files": files}, + "expected_metadata": {"embedding_model": "model"}, + "saved_metadata": {"embedding_model": "model"}, + "changes": {"matches": reason == "open"}, + "reusable": reason == "open"} + return {"project": reason, "reason": reason, "revision": value, + "sha256": "b" * 64, "source_organization": {"files": files}, + "selected": list(files), "pending": [], "pending_roles": [], + "retained_versions": [], "binding_matches": True, + "changed": reason != "open", "error": None} + + +def observations(payload, kind=None): + """Locate only top-level source observation operation nodes.""" + return sorted([ + node for session in payload["sessions"].values() + for node in session.get("operations", {}).values() + if node["event"]["event_type"] in SOURCE_SNAPSHOT_FIELDS + and (kind is None or node["event"]["event_type"] == kind) + ], key=lambda node: node["event"]["sequence"]) + + +def reference_for(node): + """Compute the required digest independently of production helpers.""" + fields = SOURCE_SNAPSHOT_FIELDS[node["event"]["event_type"]] + data = {field: node["details"][field] for field in fields} + encoded = json.dumps(data, sort_keys=True, separators=(",", ":"), + ensure_ascii=False, allow_nan=False).encode("utf-8") + return {"sequence": node["event"]["sequence"], + "sha256": sha256(encoded).hexdigest()} + + +class TestSourceSnapshotRecording(unittest.TestCase): + """Check writer/reader equivalence without downloading model weights.""" + + def setUp(self): + temporary = TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.directory = self.root / "logs" / "traces" + self.directory.mkdir(parents=True) + (self.root / "profile.ini").touch() + self.path = self.directory / "project.json" + + def _logger(self, policy="raise", scope="project", name="project.json"): + logger = TraceLogger( + TraceConfig(enabled=True, output_path=self.directory / name, + failure_policy=policy), + default_directory=self.directory, project_directory=self.root, + scope=scope, + ) + self.addCleanup(logger.close) + return logger + + def _emit(self, logger, kind, data, **kwargs): + logger.emit(kind, component="fixture", data=data, **kwargs) + + def _raw(self): + return json.loads(self.path.read_text(encoding="utf-8")) + + def _rows(self, kind=None): + return observations(self._raw(), kind) + + def _assert_resolved(self, expected): + before = self.path.read_bytes() + recording = read_recording(self.root) + self.assertFalse(recording.issues, recording.issues) + events = [event for event in recording.events + if event.event_type in SOURCE_SNAPSHOT_FIELDS] + self.assertEqual([event.details for event in events], expected) + self.assertEqual([event.metadata for event in events], + [node["event"] for node in self._rows()]) + self.assertEqual(before, self.path.read_bytes()) + self.assertEqual([event.sequence for event in recording.events], + list(range(1, recording.last_sequence + 1))) + self.assertEqual(len({event.metadata["event_id"] + for event in recording.events}), + len(recording.events)) + return events + + def test_compact_groups_preserve_inline_fields_across_runs(self): + expected = [] + for reason in ("open", "relocated", "resume"): + logger = self._logger() + with logger.span("gui.project.open", component="fixture"): + for kind in SOURCE_SNAPSHOT_FIELDS: + data = observation(kind, reason=reason) + data["extra"] = {"reason": reason, "text": "KíLín"} + self._emit(logger, kind, data) + expected.append(data) + logger.close() + for kind, fields in SOURCE_SNAPSHOT_FIELDS.items(): + with self.subTest(kind=kind): + first, second, third = self._rows(kind) + self.assertNotIn(REFERENCE, first["details"]) + for row, reason in ((second, "relocated"), + (third, "resume")): + expected_data = observation(kind, reason=reason) + expected_data["extra"] = {"reason": reason, + "text": "KíLín"} + compact = {key: value for key, value in + expected_data.items() if key not in fields} + compact[REFERENCE] = reference_for(first) + self.assertEqual(row["details"], compact) + self.assertNotEqual(row["event"]["trace_id"], + first["event"]["trace_id"]) + self.assertIn("span_id", row["event"]) + events = self._assert_resolved(expected) + for i, kind in enumerate(SOURCE_SNAPSHOT_FIELDS): + for field in SOURCE_SNAPSHOT_FIELDS[kind]: + value = events[i].details[field] + if isinstance(value, (dict, list)): + self.assertIsNot(value, events[i + 3].details[field]) + + def test_changes_restoration_and_json_order(self): + logger = self._logger() + expected = [] + for kind in SOURCE_SNAPSHOT_FIELDS: + data = observation(kind) + changed = observation(kind, 2) + reordered = dict(reversed(list(data.items()))) + for value in (data, reordered, changed, changed, data, data): + self._emit(logger, kind, value) + expected.append(value) + rows = self._rows(kind) + for full, compact in zip(rows[::2], rows[1::2]): + self.assertNotIn(REFERENCE, full["details"]) + self.assertEqual(compact["details"][REFERENCE], + reference_for(full)) + logger.close() + self._assert_resolved(expected) + + def test_every_snapshot_field_affects_equality(self): + logger = self._logger() + for kind, fields in SOURCE_SNAPSHOT_FIELDS.items(): + for field in fields: + with self.subTest(kind=kind, field=field): + full = observation(kind) + self._emit(logger, kind, full) + changed = deepcopy(full) + if isinstance(changed[field], list): + changed[field].append("new") + else: + changed[field]["new"] = True + self._emit(logger, kind, changed) + self.assertEqual(self._rows(kind)[-1]["details"], changed) + + def test_array_order_and_scalar_types_remain_significant(self): + logger = self._logger() + full = observation(SCAN) + for field, value in (("size_bytes", 1.0), ("size_bytes", True)): + self._emit(logger, SCAN, full) + changed = deepcopy(full) + changed["entries"][0][field] = value + self._emit(logger, SCAN, changed) + self.assertNotIn(REFERENCE, self._rows(SCAN)[-1]["details"]) + self._emit(logger, SCAN, full) + changed = deepcopy(full) + changed["selected_files"].reverse() + self._emit(logger, SCAN, changed) + self.assertNotIn(REFERENCE, self._rows(SCAN)[-1]["details"]) + + def test_failed_or_incomplete_observation_requires_new_full_target(self): + logger = self._logger() + expected = [] + for kind in SOURCE_SNAPSHOT_FIELDS: + full = observation(kind) + incomplete = deepcopy(full) + if kind == SCAN: + incomplete["complete"] = False + elif kind == SEMANTIC: + incomplete["error"] = "inspection failed" + else: + incomplete.pop("source_manifest") + for data, status in ((full, "completed"), + (full, "failed"), + (full, "completed"), + (incomplete, "completed"), + (full, "completed"), + (full, "completed")): + self._emit(logger, kind, data, status=status) + expected.append(data) + rows = self._rows(kind) + self.assertTrue(all(REFERENCE not in row["details"] + for row in rows[:-1])) + self.assertEqual(rows[-1]["details"][REFERENCE], + reference_for(rows[-2])) + logger.close() + self._assert_resolved(expected) + + def test_small_observation_and_unrelated_event_stay_full(self): + logger = self._logger() + scan = {"complete": True, "selected_files": [], "entries": []} + for _ in range(2): + self._emit(logger, SCAN, scan) + self._emit(logger, "index.empty", observation(INDEX)) + self.assertEqual([row["details"] for row in self._rows(SCAN)], + [scan, scan]) + recording = read_recording(self.root) + self.assertEqual([event.details for event in recording.events + if event.event_type == "index.empty"], + [observation(INDEX)] * 2) + + def test_conversation_observations_are_not_compacted(self): + logger = self._logger() + self._emit(logger, SCAN, observation(SCAN)) + conversation = self._logger(scope="conversation", + name="conversation_a.json") + for _ in range(2): + self._emit(conversation, SCAN, observation(SCAN)) + conversation.close() + rows = observations(json.loads( + conversation.readable_path.read_text(encoding="utf-8"))) + self.assertEqual([row["details"] for row in rows], + [observation(SCAN)] * 2) + + def test_no_additional_project_read_or_write(self): + logger = self._logger() + for kind in SOURCE_SNAPSHOT_FIELDS: + data = observation(kind) + self._emit(logger, kind, data) + with ( + patch.object(_trace_project, "_read_object", + wraps=_trace_project._read_object) as read, + patch.object(_trace_project, "atomic_write_text", + wraps=_trace_project.atomic_write_text) as write, + ): + self._emit(logger, kind, data) + self.assertEqual(sum(call.args[0] == self.path + for call in read.call_args_list), 1) + self.assertEqual(sum(call.args[0] == self.path + for call in write.call_args_list), 1) + self.assertEqual(read.call_count, 2) + self.assertEqual(write.call_count, 2) + + def test_disabled_trace_does_not_read_or_write(self): + with ( + patch.object(_trace_project, "_read_object") as read, + patch.object(_trace_project, "atomic_write_text") as write, + ): + self._emit(NullTraceLogger(), SCAN, observation(SCAN)) + read.assert_not_called() + write.assert_not_called() + + def _assert_concurrent_history(self, submitted): + """Verify each persisted target in true allocation order.""" + latest = None + positions = dict.fromkeys(submitted, 0) + expected = [] + for node in self._rows(SCAN): + trace_id = node["event"]["trace_id"] + value = submitted[trace_id][positions[trace_id]] + positions[trace_id] += 1 + data = observation(SCAN, value) + expected.append(data) + if latest is not None and latest[0] == value: + self.assertEqual(node["details"][REFERENCE], + reference_for(latest[1])) + else: + self.assertEqual(node["details"], data) + latest = (value, node) + self.assertEqual(positions, {key: len(values) + for key, values in submitted.items()}) + self._assert_resolved(expected) + + def test_concurrent_threads(self): + first, second = self._logger(), self._logger() + submitted = {first.trace_id: (1, 2, 1, 1), + second.trace_id: (1, 1, 2, 2)} + barrier = Barrier(2) + + def run(logger): + for value in submitted[logger.trace_id]: + barrier.wait(timeout=10) + self._emit(logger, SCAN, observation(SCAN, value)) + + with ThreadPoolExecutor(max_workers=2) as pool: + tasks = [pool.submit(run, logger) for logger in (first, second)] + for task in tasks: + task.result(timeout=30) + first.close() + second.close() + self._assert_concurrent_history(submitted) + + def test_independent_processes(self): + code = """ +import json, sys +from pathlib import Path +from kilin.trace_logging import TraceConfig, TraceLogger +from tests.kilin.test_trace_logging__sources import observation, SCAN +root = Path(sys.argv[1]) +path = root / 'logs' / 'traces' / 'project.json' +logger = TraceLogger(TraceConfig(enabled=True, output_path=path, + failure_policy='raise'), + default_directory=path.parent, project_directory=root, + scope='project') +try: + for value in json.loads(sys.argv[2]): + logger.emit(SCAN, component='fixture', data=observation(SCAN, value)) +finally: + logger.close() +print(logger.trace_id) +""" + processes = [] + submitted = {} + try: + for values in ((1, 1, 2, 1), (1, 2, 2, 1)): + process = subprocess.Popen( + [sys.executable, "-c", code, str(self.root), + json.dumps(values)], stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, + ) + processes.append((process, values)) + for process, values in processes: + stdout, stderr = process.communicate(timeout=45) + self.assertEqual(process.returncode, 0, stderr) + submitted[stdout.strip()] = values + finally: + for process, _ in processes: + if process.poll() is None: + process.kill() + process.communicate() + self._assert_concurrent_history(submitted) + + def test_publication_failure_preserves_old_events_and_releases_lease(self): + for policy in ("warn", "raise"): + with self.subTest(policy=policy): + logger = self._logger(policy=policy) + data = observation(SCAN) + self._emit(logger, SCAN, data) + before = self.path.read_bytes() + counter = self.directory / ".sequence.json" + high = json.loads(counter.read_text("utf-8"))["last_sequence"] + original = _trace_project.atomic_write_text + + def fail(path, content): + if path == self.path: + raise OSError("publication failure") + original(path, content) + + with patch.object(_trace_project, "atomic_write_text", + side_effect=fail): + if policy == "raise": + with self.assertRaisesRegex(RuntimeError, + "publication failure"): + self._emit(logger, SCAN, data) + else: + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always", RuntimeWarning) + self._emit(logger, SCAN, data) + self.assertTrue(any("publication failure" in + str(w.message) for w in seen)) + self.assertEqual(self.path.read_bytes(), before) + state = json.loads(counter.read_text("utf-8")) + self.assertTrue(state["incomplete"]) + self.assertEqual(state["last_sequence"], high + 1) + logger.close() + next_logger = self._logger() + self._emit(next_logger, SCAN, data) + next_logger.close() + self.assertIn(REFERENCE, self._rows(SCAN)[-1]["details"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/kilin/tools/_contract_support.py b/tests/kilin/tools/_contract_support.py index dad5616d..8f65112c 100644 --- a/tests/kilin/tools/_contract_support.py +++ b/tests/kilin/tools/_contract_support.py @@ -14,7 +14,7 @@ from types import ModuleType import unittest -from kilin.tools._registry import TOOL_REGISTRY +from kilin.tools import registered_tools def assert_registry_entry( @@ -39,7 +39,7 @@ def assert_registry_entry( """ - entry = TOOL_REGISTRY[name] + entry = registered_tools()[name] case.assertIs(entry.parse_settings, tool.parse_settings) case.assertIs(entry.run, tool.run) case.assertIsNone(entry.workspace_resources) diff --git a/tests/kilin/tools/_shared/test__source_access.py b/tests/kilin/tools/_shared/test__source_access.py index 1f6f4471..c4f2b28e 100644 --- a/tests/kilin/tools/_shared/test__source_access.py +++ b/tests/kilin/tools/_shared/test__source_access.py @@ -27,15 +27,21 @@ class TestSelectedSourceAccess(unittest.TestCase): """Test selected-file authorization and containment.""" def test_manifest_is_authoritative_even_when_empty(self) -> None: - indexed = SimpleNamespace(path=Path("paper.tex")) - context = SimpleNamespace( - chunks=[indexed], source_files=lambda: {}, - ) - self.assertEqual(selected_paths(context), frozenset()) - del context.source_files - self.assertEqual( - selected_paths(context), frozenset({Path("paper.tex")}) - ) + indexed = SimpleNamespace(path=Path("stale.tex")) + context = SimpleNamespace(chunks=[indexed]) + for inventory in ({}, {Path("unindexed.tex"): 12}): + with self.subTest(inventory=inventory): + context.source_files = lambda: inventory + self.assertEqual(selected_paths(context), frozenset(inventory)) + + def test_source_inventory_is_required(self) -> None: + indexed = SimpleNamespace(path=Path("stale.tex")) + for fields in ({}, {"source_files": None}, {"source_files": {}}): + with self.subTest(fields=fields): + context = SimpleNamespace(chunks=[indexed], **fields) + with self.assertRaisesRegex(RuntimeError, + "ToolContext.source_files"): + selected_paths(context) def test_only_selected_regular_workspace_files(self) -> None: with TemporaryDirectory() as temporary: diff --git a/tests/kilin/tools/generate_paper_summary/test_tool.py b/tests/kilin/tools/generate_paper_summary/test_tool.py index 554f6c0a..c6bc2400 100644 --- a/tests/kilin/tools/generate_paper_summary/test_tool.py +++ b/tests/kilin/tools/generate_paper_summary/test_tool.py @@ -22,7 +22,7 @@ from kilin.chunking import Chunk from kilin.project_type import project_type from kilin.tools._contract import ToolRequest -from kilin.tools._registry import TOOL_GENERATE_PAPER_SUMMARY, TOOL_REGISTRY +from kilin.tools import TOOL_GENERATE_PAPER_SUMMARY, registered_tools from kilin.tools._shared.references import ReferenceLayout from kilin.tools.generate_paper_summary import ( REFERENCE_LAYOUT, @@ -64,7 +64,7 @@ def test_tool_registry_points_to_package(self) -> None: """ - tool = TOOL_REGISTRY[TOOL_GENERATE_PAPER_SUMMARY] + tool = registered_tools()[TOOL_GENERATE_PAPER_SUMMARY] self.assertIs(tool.parse_settings, parse_settings) self.assertIs(tool.run, run) self.assertIs(tool.workspace_resources, workspace_resources) diff --git a/tests/kilin/tools/project_summary/test__mapping.py b/tests/kilin/tools/project_summary/test__mapping.py index 6d58bae1..95ffe3dc 100644 --- a/tests/kilin/tools/project_summary/test__mapping.py +++ b/tests/kilin/tools/project_summary/test__mapping.py @@ -20,7 +20,7 @@ parse_template, ) from kilin.tools.project_summary._documents import ( - document_excerpt, + prepare_excerpt, project_documents, query_words, ) @@ -109,9 +109,10 @@ def test_notebook_cells_are_ordered_before_cell_local_lines( [item.text for item in document.passages], [item.text for item in passages], ) - excerpt = document_excerpt(document, {"opening"}, 1000) - self.assertLess(excerpt.index("Cell one end"), - excerpt.index("Cell two opening")) + excerpt = prepare_excerpt(document, {"opening"}, 1000) + self.assertLess(excerpt.text.index("Cell one end"), + excerpt.text.index("Cell two opening")) + self.assertEqual(excerpt.passages, tuple(passages)) def test_pdf_pages_are_ordered_before_page_local_lines(self) -> None: first = Chunk("p1", Path("paper.pdf"), "Page one conclusion", 40, @@ -120,27 +121,30 @@ def test_pdf_pages_are_ordered_before_page_local_lines(self) -> None: 1, "pdf", None, "Page 2") document = project_documents([first, second], None)[0] self.assertEqual(document.passages, (first, second)) - excerpt = document_excerpt(document, set(), 1000) - self.assertLess(excerpt.index("Page one conclusion"), - excerpt.index("Page two opening")) + excerpt = prepare_excerpt(document, set(), 1000) + self.assertLess(excerpt.text.index("Page one conclusion"), + excerpt.text.index("Page two opening")) + self.assertEqual(excerpt.passages, (first, second)) def test_excerpt(self) -> None: def card(path): return {"title": "Study B", "aim": "Segment nuclei."} document = project_documents(self.chunks, card)[1] words = query_words(["Datasets", "the public dataset used"]) - excerpt = document_excerpt(document, words, 1000) - self.assertTrue(excerpt.startswith( + excerpt = prepare_excerpt(document, words, 1000) + self.assertTrue(excerpt.text.startswith( "From the document's card:\nTitle: Study B\nAim: Segment " "nuclei." )) - self.assertIn("Title B. Abstract.", excerpt) - self.assertIn("the public BBBC dataset", excerpt) - self.assertNotIn("Acknowledgements", excerpt) + self.assertIn("Title B. Abstract.", excerpt.text) + self.assertIn("the public BBBC dataset", excerpt.text) + self.assertNotIn("Acknowledgements", excerpt.text) + self.assertEqual(excerpt.passages, document.passages[:3]) # The opening comes first even when the budget is small. - small = document_excerpt(document, words, 20) - self.assertIn("Title B. Abstract.", small) - self.assertNotIn("Datasets: we used", small) + small = prepare_excerpt(document, words, 20) + self.assertIn("Title B. Abstract.", small.text) + self.assertNotIn("Datasets: we used", small.text) + self.assertEqual(small.passages, document.passages[:1]) class TestMapping(unittest.TestCase): diff --git a/tests/kilin/tools/project_summary/test_tool.py b/tests/kilin/tools/project_summary/test_tool.py index 2e7dd470..1e739931 100644 --- a/tests/kilin/tools/project_summary/test_tool.py +++ b/tests/kilin/tools/project_summary/test_tool.py @@ -25,7 +25,7 @@ from kilin.tools.project_summary import _configuration as _config from kilin.project_type import project_type, with_project_routing from kilin.tools._contract import ToolRequest -from kilin.tools._registry import TOOL_REGISTRY +from kilin.tools import registered_tools from kilin.tools.project_summary import ( SHIPPED_TEMPLATES_DIR, TEMPLATE_CHOOSE, @@ -812,7 +812,7 @@ def test_settings_and_registry(self) -> None: {"unknown": 1}): with self.subTest(bad=bad), self.assertRaises(ValueError): parse_settings(bad, "x") - self.assertIn("project_summary", TOOL_REGISTRY) + self.assertIn("project_summary", registered_tools()) shipped = {r.destination for r in workspace_resources( ProjectSummarySettings())} self.assertEqual(shipped, { diff --git a/tests/kilin/tools/test__architecture.py b/tests/kilin/tools/test__architecture.py index 164d6845..d1d41369 100644 --- a/tests/kilin/tools/test__architecture.py +++ b/tests/kilin/tools/test__architecture.py @@ -16,10 +16,10 @@ from pathlib import Path import unittest -from kilin.tools._registry import TOOL_REGISTRY +from kilin.tools import registered_tools _ROOT = Path(__file__).resolve().parents[3] / "kilin" / "tools" -_REGISTERED = frozenset(TOOL_REGISTRY) +_REGISTERED = frozenset(registered_tools()) class TestToolPackageArchitecture(unittest.TestCase): diff --git a/tests/kilin/tools/test__contract_support.py b/tests/kilin/tools/test__contract_support.py index 828c564e..b66dd087 100644 --- a/tests/kilin/tools/test__contract_support.py +++ b/tests/kilin/tools/test__contract_support.py @@ -21,7 +21,7 @@ import unittest from unittest.mock import patch -from kilin.tools._registry import TOOL_REGISTRY +from kilin.tools import _registry, registered_tools from tests.kilin.tools._contract_support import ( assert_packaged_defaults, assert_registry_entry, @@ -49,7 +49,9 @@ def test_registry_detects_wrong_parser_and_followup_policy(self) -> None: workspace_resources=None, follows_up=False, ) - with patch.dict(TOOL_REGISTRY, {"test_only": entry}): + original = registered_tools() + entries = {**original, "test_only": entry} + with patch.object(_registry, "_registry", entries): assert_registry_entry( self, "test_only", package, non_followup=True ) @@ -63,6 +65,9 @@ def test_registry_detects_wrong_parser_and_followup_policy(self) -> None: self, "test_only", package, non_followup=True ) + self.assertNotIn("test_only", original) + self.assertEqual(registered_tools(), original) + def test_packaged_defaults_detect_value_drift(self) -> None: with TemporaryDirectory() as folder: root = Path(folder) diff --git a/tests/kilin/tools/test__generation_budgets.py b/tests/kilin/tools/test__generation_budgets.py index 4ba0f188..65dec767 100644 --- a/tests/kilin/tools/test__generation_budgets.py +++ b/tests/kilin/tools/test__generation_budgets.py @@ -16,7 +16,7 @@ from unittest.mock import Mock, patch from kilin.tools._contract import EarlierTurn, ToolRequest -from kilin.tools._registry import TOOL_REGISTRY +from kilin.tools import registered_tools from kilin.tools.find_passages import tool as passages from kilin.tools.generate_paper_summary import tool as summary from kilin.tools.paper_overview import tool as overview @@ -42,7 +42,7 @@ def test_obsolete_caps_are_rejected_not_silently_ignored(self) -> None: for value in (None, 128, 8192): with self.subTest(tool=name, key=key, value=value): with self.assertRaises(ValueError): - TOOL_REGISTRY[name].parse_settings( + registered_tools()[name].parse_settings( {key: value}, "custom" ) diff --git a/tests/kilin/tools/test__model_calls.py b/tests/kilin/tools/test__model_calls.py index f17d1c46..054c61f5 100644 --- a/tests/kilin/tools/test__model_calls.py +++ b/tests/kilin/tools/test__model_calls.py @@ -17,7 +17,7 @@ from tempfile import TemporaryDirectory import unittest -from kilin.tools import TOOL_REGISTRY +from kilin.tools import registered_tools from kilin.tools._model_calls import ( ModelCallSettings, load_model_call_settings, @@ -95,8 +95,8 @@ def test_all_shipped_policies_match_owned_configuration(self) -> None: "find_passages", "generate_paper_summary", "writing_check", "project_summary", } - self.assertEqual(len(TOOL_REGISTRY), 15) - for name, tool in TOOL_REGISTRY.items(): + self.assertEqual(len(registered_tools()), 15) + for name, tool in registered_tools().items(): with self.subTest(tool=name): config = importlib.import_module( f"kilin.tools.{name}._configuration" diff --git a/tests/kilin/tools/test__resources.py b/tests/kilin/tools/test__resources.py index 3865315c..bdb1a0a6 100644 --- a/tests/kilin/tools/test__resources.py +++ b/tests/kilin/tools/test__resources.py @@ -20,7 +20,7 @@ from kilin.project import initialize_project from kilin.project_layout import plan_project_layout from kilin.project_type import load_project_types, project_type -from kilin.tools._registry import TOOL_REGISTRY +from kilin.tools import registered_tools from kilin.tools.generate_paper_summary import SHIPPED_TEMPLATES_DIR from kilin.tools.project_summary import ( SHIPPED_TEMPLATES_DIR as PROJECT_TEMPLATES_DIR, @@ -41,7 +41,7 @@ def test_project_types_only_declare_assets_their_tools_own(self) -> None: use = intent.tool if use is None: continue - declaration = TOOL_REGISTRY[use.name].workspace_resources + declaration = registered_tools()[use.name].workspace_resources if declaration is None: continue package = Path(files(f"kilin.tools.{use.name}")).resolve() diff --git a/tests/test__plugin_api.py b/tests/test__plugin_api.py index 35e62d0c..ba707390 100644 --- a/tests/test__plugin_api.py +++ b/tests/test__plugin_api.py @@ -106,8 +106,8 @@ def audit(event, args): + "\n" + assertions ) - def test_one_registry_with_legacy_accessors(self) -> None: - """Resolve the same bundled entries from all public access paths.""" + def test_one_registry_with_canonical_accessors(self) -> None: + """Resolve one read-only registry and preserve tool choice order.""" self._fresh(''' import sys @@ -119,34 +119,61 @@ def test_one_registry_with_legacy_accessors(self) -> None: from kilin.project import project_type_ids assert ToolName is str assert _registry._registry is None +import importlib +from kilin import tools, project +for owner, names in ( + (kilin, ("PROJECT_TYPE_IDS", "TOOL_CHOICES")), + (project, ("PROJECT_TYPE_IDS",)), + (_registry, ("TOOL_REGISTRY", "TOOL_CHOICES")), + (tools, ("TOOL_REGISTRY", "TOOL_CHOICES", "CANDIDATE_CHOICES", + "CANDIDATES_MENTIONS", "UNCLEAR", "CandidateSource", + "ClassifySettings", "Label", "MAX_TERMS", "Mention", + "MentionScan", "ScanSettings", "scan_mentions")), +): + for name in names: + assert name not in owner.__all__, (owner, name) + assert not hasattr(owner, name), (owner, name) +assert _registry._registry is None +assert importlib.import_module( + "kilin.project_type").load_project_types.cache_info().currsize == 0 +assert "kilin.tools.batch_classify" not in sys.modules +assert "kilin.tools.scan_and_list" not in sys.modules with patch.object(_registry, "_build_tool_registry", wraps=_registry._build_tool_registry) as build: with ThreadPoolExecutor(max_workers=8) as pool: catalogs = list(pool.map(lambda _: registered_tools(), range(16))) assert build.call_count == 1 -from kilin.tools import TOOL_REGISTRY, TOOL_CHOICES -from kilin.tools._registry import TOOL_REGISTRY as old_registry -assert TOOL_REGISTRY is old_registry -assert len(TOOL_REGISTRY) == 15 -assert TOOL_CHOICES == tool_choices() == kilin.TOOL_CHOICES -assert set(TOOL_CHOICES) == set(TOOL_REGISTRY) -assert all(catalog == TOOL_REGISTRY for catalog in catalogs) -assert all(catalogs[0][name] is tool - for name, tool in TOOL_REGISTRY.items()) +catalog = registered_tools() +assert len(catalog) == 15 +assert tool_choices() == kilin.tool_choices() == ( + "project_inventory", "scan_and_list", "batch_classify", "batch_review", + "filter_results", "find_fact", "find_passages", "generate_paper_summary", + "paper_overview", "reference_check", "show_source", "suggest_reference", + "writing_check", "project_summary", "assistant_guide", +) +assert set(tool_choices()) == set(catalog) +assert all(view == catalog for view in catalogs) +assert all(view[name] is tool for view in catalogs + for name, tool in catalog.items()) try: catalogs[0]["new"] = None except TypeError: pass else: raise AssertionError("Catalog view accepted a write") -assert kilin.PROJECT_TYPE_IDS == project_type_ids() == ( +assert kilin.project_type_ids() == project_type_ids() == ( "code", "creative_brainstorming", "grounded_brainstorming", "literature", "reviewing", "writing", ) -from kilin.tools import ClassifySettings, ScanSettings -from kilin.tools.batch_classify import ClassifySettings as Classify -from kilin.tools.scan_and_list import ScanSettings as Scan -assert ClassifySettings is Classify and ScanSettings is Scan +for module, names in ( + ("batch_classify", ("CANDIDATE_CHOICES", "CANDIDATES_MENTIONS", "UNCLEAR", + "CandidateSource", "ClassifySettings", "Label")), + ("scan_and_list", ("MAX_TERMS", "Mention", "MentionScan", "ScanSettings", + "scan_mentions")), +): + owner = importlib.import_module("kilin.tools." + module) + for name in names: + assert name in owner.__all__ and hasattr(owner, name), (owner, name) ''') def test_incompatible_api_does_not_publish_registry(self) -> None: diff --git a/tutorials/140_project_chat.ipynb b/tutorials/140_project_chat.ipynb index a5d01886..e5315ead 100644 --- a/tutorials/140_project_chat.ipynb +++ b/tutorials/140_project_chat.ipynb @@ -100,7 +100,7 @@ "\n", "Choose a registered project type and an explicit local source folder:\n", "\n", - "- `PROJECT_TYPE_ID` selects a configured type from `kilin.PROJECT_TYPE_IDS`;\n", + "- `PROJECT_TYPE_ID` selects a configured type from `kilin.project_type_ids()`;\n", "- `PROJECT_DIRECTORY` selects an existing source directory; the default is bundled KíLín retrieval code;\n", "- `ENABLE_TRACE` controls whether the session records diagnostics.\n", "\n", @@ -129,9 +129,9 @@ "metadata": {}, "outputs": [], "source": [ - "if PROJECT_TYPE_ID not in kilin.PROJECT_TYPE_IDS:\n", + "if PROJECT_TYPE_ID not in kilin.project_type_ids():\n", " raise ValueError(\n", - " f\"PROJECT_TYPE_ID must be one of {kilin.PROJECT_TYPE_IDS}.\"\n", + " f\"PROJECT_TYPE_ID must be one of {kilin.project_type_ids()}.\"\n", " )\n" ] },