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.
This is where KíLín keeps your projects. Confirm it, or choose another folder with Browse.
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'
'
+ if value is not None else "")
+ panes.append(pane)
panel += _section("Exact " + field, _pair(*panes))
body += _section(title, panel)
return body or "