From 1089726d9ee9cebbc16ce721744046745b0ef033 Mon Sep 17 00:00:00 2001
From: Giovanni Volpe
Date: Wed, 2 Dec 2026 12:17:09 +0100
Subject: [PATCH 1/9] Polishing Traces
---
docs/module_map.md | 10 +-
docs/system_testing.md | 11 +-
docs/trace_architecture.md | 147 ++++++-
kilin/_trace_configuration.py | 114 ++++-
kilin/_trace_json.py | 95 ++++
kilin/_trace_project.py | 204 ++++++++-
kilin/_trace_snapshots.py | 306 +++++++++++++
kilin/system_testing/analysis.py | 192 ++++----
kilin/system_testing/traces.py | 137 +++++-
kilin/trace_logging.py | 42 +-
tests/kilin/gui/test_engine__models.py | 6 +-
tests/kilin/gui/test_engine__recording.py | 7 +-
.../system_testing/test_analysis__traces.py | 254 +++++++++++
tests/kilin/system_testing/test_experiment.py | 17 +-
.../test_traces__configuration.py | 166 ++++++-
.../system_testing/test_traces__semantics.py | 265 ++++++++++++
.../system_testing/test_traces__sources.py | 282 ++++++++++++
tests/kilin/test__trace_configuration.py | 89 ++++
tests/kilin/test__trace_json.py | 226 ++++++++++
.../test_trace_logging__configuration.py | 138 ++++++
tests/kilin/test_trace_logging__semantics.py | 284 ++++++++++++
tests/kilin/test_trace_logging__sources.py | 409 ++++++++++++++++++
22 files changed, 3238 insertions(+), 163 deletions(-)
create mode 100644 kilin/_trace_json.py
create mode 100644 kilin/_trace_snapshots.py
create mode 100644 tests/kilin/system_testing/test_analysis__traces.py
create mode 100644 tests/kilin/system_testing/test_traces__semantics.py
create mode 100644 tests/kilin/system_testing/test_traces__sources.py
create mode 100644 tests/kilin/test__trace_configuration.py
create mode 100644 tests/kilin/test__trace_json.py
create mode 100644 tests/kilin/test_trace_logging__semantics.py
create mode 100644 tests/kilin/test_trace_logging__sources.py
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/system_testing.md b/docs/system_testing.md
index 03759339..8bb36934 100644
--- a/docs/system_testing.md
+++ b/docs/system_testing.md
@@ -633,8 +633,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..3bfc7fd2 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
@@ -168,9 +184,9 @@ 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 seven settings groups.
+An unchanged configuration records a direct reference to the most recent
+complete observation:
```json
{
@@ -184,14 +200,39 @@ An unchanged configuration instead records a direct reference:
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.
+The complete-payload digest includes the historical workspace path in
+`behavior.project`. When only that path changes, a distinct reference shares
+all other configuration content and retains the exact current path inline:
+
+```json
+{
+ "configuration_content_reference": {
+ "sequence": 124,
+ "sha256": "<64 lowercase hexadecimal characters>"
+ },
+ "project": "/exact/recorded/workspace/path"
+}
+```
+
+This digest uses the same encoding with only `behavior.project` removed.
+Inspection restores that field from `project`, without normalizing its
+spelling or consulting the current filesystem. An explicit null path is
+preserved; an absent path is ineligible for this representation. All other
+behavior values, unknown fields, scalar types and list ordering still affect
+equality. A relocation reference is written only when it is smaller than the
+full payload. Both reference fields are reserved and cannot be mixed with
+each other or full settings groups.
+
+Changed settings require a new full observation. Restoring settings after a
+different full observation also writes a new full observation. Both kinds of
+reference point directly to the latest full snapshot; they never form chains
+or skip newer full snapshots. Ordinary exact references remain available when
+the complete payload, including the historical path, matches that 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 +242,92 @@ 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
+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. 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.
+
+### 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/kilin/_trace_configuration.py b/kilin/_trace_configuration.py
index ab62b108..daaf7ca8 100644
--- a/kilin/_trace_configuration.py
+++ b/kilin/_trace_configuration.py
@@ -3,19 +3,23 @@
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.
+Relocation references retain the exact current 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.
+- Separate path-preserving references for otherwise 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_bytes`` and ``configuration_content_bytes`` encode complete
+ snapshots and their path-independent content for comparison.
+- ``configuration_reference`` and ``configuration_content_reference``
+ construct compact references without changing the observed configuration.
- ``resolve_configuration_reference`` verifies and expands a reference.
Examples
@@ -29,20 +33,24 @@
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_CONTENT_REFERENCE",
"configuration_bytes",
+ "configuration_content_bytes",
"configuration_reference",
+ "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",
@@ -75,12 +83,45 @@ def configuration_bytes(configuration: Mapping[str, object]) -> bytes:
"""
if (CONFIGURATION_REFERENCE in configuration
+ or CONFIGURATION_CONTENT_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")
+ return snapshot_bytes(configuration)
+
+
+def configuration_content_bytes(configuration: Mapping[str, object]) -> bytes:
+ """Encode every configuration value except the observed project path.
+
+ Parameters
+ ----------
+ configuration: mapping of str to object
+ Complete JSON-ready effective configuration. The ``behavior`` mapping
+ must contain ``project``; absence never means a null or empty path.
+
+ Returns
+ -------
+ bytes
+ Canonical JSON preserving all other settings and unknown fields.
+
+ Raises
+ ------
+ ValueError
+ If the configuration is incomplete, compact, or has no project path.
+ TypeError
+ If a retained value cannot be serialized as JSON.
+
+ """
+
+ behavior = configuration.get("behavior")
+ if (CONFIGURATION_REFERENCE in configuration
+ or 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:
@@ -100,9 +141,36 @@ def configuration_reference(sequence: int, encoded: bytes) -> dict:
"""
- return {CONFIGURATION_REFERENCE: {
- "sequence": sequence, "sha256": sha256(encoded).hexdigest(),
- }}
+ return snapshot_reference(CONFIGURATION_REFERENCE, sequence, encoded)
+
+
+def configuration_content_reference(
+ sequence: int, encoded: bytes, project: object,
+) -> dict:
+ """Reference shared settings while retaining the exact observed path.
+
+ Parameters
+ ----------
+ sequence: int
+ Project-wide sequence number of the complete snapshot.
+ encoded: bytes
+ Canonical configuration content with only ``behavior.project`` absent.
+ project: object
+ Original JSON value of ``behavior.project`` in the current event.
+ Explicit null remains present and is never confused with absence.
+
+ Returns
+ -------
+ dict
+ Direct content reference and an independent copy of the current path.
+
+ """
+
+ return {
+ **snapshot_reference(CONFIGURATION_CONTENT_REFERENCE, sequence,
+ encoded),
+ "project": deepcopy(project),
+ }
def resolve_configuration_reference(
@@ -133,8 +201,12 @@ def resolve_configuration_reference(
"""
- reference = details.get(CONFIGURATION_REFERENCE)
- if (set(details) != {CONFIGURATION_REFERENCE}
+ content_reference = CONFIGURATION_CONTENT_REFERENCE in details
+ key = (CONFIGURATION_CONTENT_REFERENCE if content_reference
+ else CONFIGURATION_REFERENCE)
+ fields = {key, "project"} if content_reference else {key}
+ reference = details.get(key)
+ if (set(details) != fields
or not isinstance(reference, dict)
or set(reference) != {"sequence", "sha256"}
or type(reference["sequence"]) is not int
@@ -145,9 +217,13 @@ 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:
+ if content_reference:
+ encoded = configuration_content_bytes(latest[1])
+ else:
+ encoded = configuration_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])
+ if content_reference:
+ 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..785f3e64 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,12 +63,22 @@
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_content_bytes,
+ configuration_content_reference,
configuration_reference,
)
+from kilin._trace_snapshots import (
+ SEMANTIC_SNAPSHOT_EVENTS, SEMANTIC_SNAPSHOT_REFERENCE,
+ SEMANTIC_SNAPSHOT_WRITERS,
+ SOURCE_SNAPSHOT_REFERENCE, snapshot_bytes, snapshot_reference,
+ semantic_snapshot, source_snapshot,
+)
from kilin.conversation_ownership import (
ConversationFileLock,
ConversationLockedError,
@@ -78,6 +91,8 @@
"project_trace_directory",
"ProjectTracePublisher",
"compact_project_configuration",
+ "compact_project_source_snapshot",
+ "compact_project_semantic_snapshot",
"project_trace_publication",
"write_project_trace",
]
@@ -169,7 +184,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 +420,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.
+ equal full configuration. When only the path differs, share all other
+ content while preserving the exact current path inline. Ineligible or
+ ambiguous history is not used for compaction.
Notes
-----
@@ -443,7 +459,8 @@ def compact_project_configuration(
or "turn_id" in event):
return configuration
seen.add(number)
- if CONFIGURATION_REFERENCE in details:
+ if (CONFIGURATION_REFERENCE in details
+ or CONFIGURATION_CONTENT_REFERENCE in details):
continue
if latest is None or number > latest[0]:
latest = (number, details)
@@ -452,6 +469,13 @@ def compact_project_configuration(
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(encoded):
+ 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 +483,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 +660,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 +703,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 +715,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/system_testing/analysis.py b/kilin/system_testing/analysis.py
index 5b92c3ac..a9cf172f 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",
@@ -952,8 +954,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 +1008,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
----------
@@ -1792,47 +1824,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 +1863,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 +1872,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 +1918,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 +1933,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 +1996,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 "
No aligned model-call records.
"
diff --git a/kilin/system_testing/traces.py b/kilin/system_testing/traces.py
index b329a885..0a30cf68 100644
--- a/kilin/system_testing/traces.py
+++ b/kilin/system_testing/traces.py
@@ -5,7 +5,7 @@
- Decode only the diagnostic hierarchy, including compact span completions.
- Inspect active and archived conversations without silent discovery skips.
- Preserve raw event identity and report malformed records without repair.
-- Expand verified configuration references for downstream consumers.
+- Expand verified configuration and source references for downstream readers.
Module Structure
----------------
@@ -31,11 +31,18 @@
from pathlib import Path, PureWindowsPath
from kilin._trace_configuration import (
+ CONFIGURATION_CONTENT_REFERENCE,
CONFIGURATION_EVENT,
CONFIGURATION_REFERENCE,
resolve_configuration_reference,
)
from kilin._trace_project import TRACE_FORMAT_VERSION
+from kilin._trace_snapshots import (
+ SEMANTIC_SNAPSHOT_EVENTS, SEMANTIC_SNAPSHOT_REFERENCE,
+ SOURCE_SNAPSHOT_FIELDS, SOURCE_SNAPSHOT_REFERENCE,
+ resolve_semantic_reference, resolve_source_reference,
+ semantic_snapshot, source_snapshot,
+)
from kilin.conversation_format import conversation_state
from kilin.conversations import _validated_metadata
from kilin.conversation_memory.models import require_saved_turn_ids
@@ -80,7 +87,7 @@ class TraceEvent:
Original event metadata, not the readable span summary.
details: dict
Input, result, or sampled progress payload. Valid compact project
- configuration observations expose their full resolved payload.
+ configuration and source observations expose their resolved payload.
exact_content: dict
Separately retained artifact contents, if present.
@@ -505,7 +512,15 @@ def _resolve_configurations(recording: Recording) -> None:
latest = None
for index, event in enumerate(recording.events):
+ compact = (CONFIGURATION_REFERENCE in event.details
+ or CONFIGURATION_CONTENT_REFERENCE in event.details)
if event.event_type != CONFIGURATION_EVENT:
+ if compact:
+ recording.issue(
+ "configuration.reference",
+ "Reference is not a configuration observation.",
+ event.path, event.sequence,
+ )
continue
# A duplicate allocation cannot identify a unique reference target.
duplicate = (
@@ -515,7 +530,7 @@ def _resolve_configurations(recording: Recording) -> None:
and recording.events[index + 1].sequence == event.sequence)
)
try:
- if CONFIGURATION_REFERENCE not in event.details:
+ if not compact:
if event.path == "logs/traces/project.json":
if (not duplicate
and event.metadata.get("status") == "completed"
@@ -541,6 +556,120 @@ def _resolve_configurations(recording: Recording) -> None:
event.path, event.sequence)
+def _resolve_semantic_snapshots(recording: Recording) -> None:
+ """Resolve shared manifests using only raw full project observations.
+
+ Parameters
+ ----------
+ recording: Recording
+ Globally ordered events. Invalid references add blocking issues;
+ no source file, semantic manifest or trace is modified.
+
+ Notes
+ -----
+ Resolve before same-type source groups so a previously compact opening
+ can never become an implicit reference target. Only the exact manifest
+ is shared; revision, provenance and command outcome stay inline.
+
+ """
+
+ latest = None
+ for index, event in enumerate(recording.events):
+ kind = event.event_type
+ compact = SEMANTIC_SNAPSHOT_REFERENCE in event.details
+ if kind not in SEMANTIC_SNAPSHOT_EVENTS and not compact:
+ continue
+ duplicate = (
+ (index > 0
+ and recording.events[index - 1].sequence == event.sequence)
+ or (index + 1 < len(recording.events)
+ and recording.events[index + 1].sequence == event.sequence)
+ )
+ project = (event.path == "logs/traces/project.json"
+ and "turn_id" not in event.metadata
+ and event.location.endswith("/event"))
+ eligible = (project and not duplicate
+ and event.metadata.get("status") == "completed")
+ if not compact:
+ if project and SOURCE_SNAPSHOT_REFERENCE not in event.details:
+ latest = None
+ if eligible:
+ try:
+ semantic_snapshot(kind, event.details)
+ except ValueError:
+ pass
+ else:
+ latest = (event.sequence, kind, event.details)
+ continue
+ try:
+ if not eligible:
+ raise ValueError("Reference is not a unique project event.")
+ details = resolve_semantic_reference(
+ kind, event.details, event.sequence, latest,
+ )
+ recording.events[index] = replace(event, details=details)
+ except (ValueError, TypeError, RecursionError) as error:
+ recording.issue("semantic_snapshot.reference", str(error),
+ event.path, event.sequence)
+
+
+def _resolve_source_snapshots(recording: Recording) -> None:
+ """Expand source observations before validation and replay.
+
+ Parameters
+ ----------
+ recording: Recording
+ Events in global sequence order. Invalid references are blocking
+ issues; the original files are never changed.
+
+ Notes
+ -----
+ Candidates are independent for each supported event type. A full failed
+ or incomplete observation resets its candidate. References never become
+ candidates, and invalid references cannot use current workspace data.
+
+ """
+
+ latest = {}
+ for index, event in enumerate(recording.events):
+ kind = event.event_type
+ compact = SOURCE_SNAPSHOT_REFERENCE in event.details
+ if kind not in SOURCE_SNAPSHOT_FIELDS and not compact:
+ continue
+ duplicate = (
+ (index > 0
+ and recording.events[index - 1].sequence == event.sequence)
+ or (index + 1 < len(recording.events)
+ and recording.events[index + 1].sequence == event.sequence)
+ )
+ project = (event.path == "logs/traces/project.json"
+ and "turn_id" not in event.metadata
+ and event.location.endswith("/event"))
+ eligible = (project and not duplicate
+ and event.metadata.get("status") == "completed")
+ if not compact:
+ if project:
+ latest.pop(kind, None)
+ if eligible:
+ try:
+ source_snapshot(kind, event.details)
+ except ValueError:
+ pass
+ else:
+ latest[kind] = (event.sequence, event.details)
+ continue
+ try:
+ if not eligible:
+ raise ValueError("Reference is not a unique project event.")
+ details = resolve_source_reference(
+ kind, event.details, event.sequence, latest.get(kind),
+ )
+ recording.events[index] = replace(event, details=details)
+ except (ValueError, TypeError, RecursionError) as error:
+ recording.issue("source_snapshot.reference", str(error),
+ event.path, event.sequence)
+
+
def read_recording(root: Path) -> Recording:
"""Read the project counter and all trace documents independently.
@@ -585,4 +714,6 @@ def read_recording(root: Path) -> Recording:
recording.issue("trace.invalid", str(error), path)
recording.events.sort(key=lambda event: event.sequence)
_resolve_configurations(recording)
+ _resolve_semantic_snapshots(recording)
+ _resolve_source_snapshots(recording)
return recording
diff --git a/kilin/trace_logging.py b/kilin/trace_logging.py
index ac039a24..fe276408 100644
--- a/kilin/trace_logging.py
+++ b/kilin/trace_logging.py
@@ -144,12 +144,18 @@
import warnings
from kilin.atomic_writes import atomic_write_text
+from kilin._trace_json import trace_json_dumps
from kilin._trace_configuration import CONFIGURATION_EVENT
+from kilin._trace_snapshots import (
+ SEMANTIC_SNAPSHOT_WRITERS, SOURCE_SNAPSHOT_FIELDS,
+)
from kilin._trace_project import (
TRACE_FORMAT_VERSION,
ProjectTracePublisher,
ProjectTraceSequence,
compact_project_configuration,
+ compact_project_semantic_snapshot,
+ compact_project_source_snapshot,
project_trace_directory,
project_trace_publication,
write_project_trace,
@@ -694,8 +700,8 @@ def emit(
retains all supplied event types, including token diagnostics. Event
sequencing is serialized within this logger. Progress and activity
updates can be throttled; other events trigger a refresh. Effective
- project configuration observations may reference an unchanged
- persisted full snapshot. Arbitrary payload content is not
+ project configuration and source observations may reference unchanged
+ persisted snapshot fields. Arbitrary payload content is not
automatically redacted.
"""
@@ -713,12 +719,14 @@ def emit(
return
if span_id is None:
span_id = self._active_span_id.get()
- # Only configuration observations need publication ordering
- # in addition to the ordinary project-wide allocation order.
+ # Snapshot references must follow publication order as well as
+ # project-wide allocation order.
publication = (
project_trace_publication(self.readable_path)
if self.scope == "project"
- and normalized_event_type == CONFIGURATION_EVENT
+ and (normalized_event_type == CONFIGURATION_EVENT
+ or normalized_event_type in SOURCE_SNAPSHOT_FIELDS
+ or normalized_event_type in SEMANTIC_SNAPSHOT_WRITERS)
and turn_id is None
else nullcontext(({}, None))
)
@@ -756,9 +764,21 @@ def emit(
event["data"] = _json_value(dict(data or {}))
if publish is not None:
if status == "completed":
- event["data"] = compact_project_configuration(
- previous, event["data"], self._sequence
- )
+ if normalized_event_type == CONFIGURATION_EVENT:
+ event["data"] = compact_project_configuration(
+ previous, event["data"], self._sequence
+ )
+ elif started_elapsed_ms is None:
+ compact = (
+ compact_project_semantic_snapshot
+ if normalized_event_type in
+ SEMANTIC_SNAPSHOT_WRITERS else
+ compact_project_source_snapshot
+ )
+ event["data"] = compact(
+ previous, normalized_event_type,
+ event["data"], self._sequence,
+ )
self._write_event(event, publish_project=publish)
else:
self._write_event(event)
@@ -1203,7 +1223,7 @@ def _write_event(
Structured event dictionary used for storage or readable
projection.
publish_project: ProjectTracePublisher or None, optional
- Publisher for a configuration observation under an already held
+ Publisher for a snapshot observation under an already held
project lease. Otherwise the ordinary write path is used.
Notes
@@ -1241,7 +1261,7 @@ def _write_readable_trace(
Parameters
----------
publish_project: ProjectTracePublisher or None, optional
- Publisher for a configuration observation whose project lease is
+ Publisher for a snapshot observation whose project lease is
already held. Ordinary project writes acquire their own lease.
Notes
@@ -1343,7 +1363,7 @@ def _write_readable_trace(
)
)
payload = {**metadata, "sessions": sessions}
- content = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
+ content = trace_json_dumps(payload) + "\n"
atomic_write_text(self.readable_path, content)
self._pending_events = False
diff --git a/tests/kilin/gui/test_engine__models.py b/tests/kilin/gui/test_engine__models.py
index 6632f4f1..00a07ee3 100644
--- a/tests/kilin/gui/test_engine__models.py
+++ b/tests/kilin/gui/test_engine__models.py
@@ -23,6 +23,7 @@
from kilin.gui.preferences import default_effort_levels
from kilin.project import open_project
from kilin.project_files import list_project_files
+from kilin.system_testing.traces import read_recording
from kilin.workspace import prepare_sources_workspace
@@ -203,7 +204,10 @@ def details(event):
self.assertEqual(len(details("gui.project.closed")), 2)
self.assertEqual(details("workspace.sync.file")[0]["path"],
"sources/library/two.txt")
- manifests = details("index.check.completed")
+ recording = read_recording(root)
+ self.assertFalse(recording.issues, recording.issues)
+ manifests = [event.details for event in recording.events
+ if event.event_type == "index.check.completed"]
self.assertEqual(set(manifests[0]["source_manifest"]["files"]),
{"library/one.txt"})
self.assertEqual(
diff --git a/tests/kilin/gui/test_engine__recording.py b/tests/kilin/gui/test_engine__recording.py
index 13e04f6c..e2362abf 100644
--- a/tests/kilin/gui/test_engine__recording.py
+++ b/tests/kilin/gui/test_engine__recording.py
@@ -27,6 +27,7 @@
from kilin.gui.engine import ChatEngine
from kilin.project import open_project
from kilin.project_type import RETRIEVAL_MODE_NONE
+from kilin.system_testing.traces import read_recording
from kilin.tools import ToolResult, ToolUse
from kilin.tools._shared.planning import (
CONFIRMATION_ALWAYS,
@@ -204,7 +205,11 @@ def test_semantic_commands_and_question_identity_are_recorded(self):
self.assertEqual(started["preview_command_id"], proposed["command_id"])
self.assertEqual(started["command_id"], done["command_id"])
self.assertEqual(done["sha256"], committed["sha256"])
- self.assertEqual(done["source_organization"],
+ recording = read_recording(self.workspace)
+ self.assertFalse(recording.issues, recording.issues)
+ resolved = next(event.details for event in recording.events
+ if event.event_type == prefix + "apply.completed")
+ self.assertEqual(resolved["source_organization"],
committed["source_organization"])
self.assertTrue(failed["conflict"])
observation = self.project_details(prefix + "observed")
diff --git a/tests/kilin/system_testing/test_analysis__traces.py b/tests/kilin/system_testing/test_analysis__traces.py
new file mode 100644
index 00000000..e43ac606
--- /dev/null
+++ b/tests/kilin/system_testing/test_analysis__traces.py
@@ -0,0 +1,254 @@
+"""Keep local trace inspection consistent with verified recording readers."""
+
+# pylint: disable=C0115:missing-class-docstring
+# pylint: disable=C0116:missing-function-docstring
+# pylint: disable=C0103:invalid-name
+
+from copy import deepcopy
+from hashlib import sha256
+import json
+import unittest
+from unittest.mock import patch
+
+from kilin._trace_configuration import (
+ CONFIGURATION_EVENT, CONFIGURATION_REFERENCE,
+)
+from kilin.system_testing import analysis
+from kilin.system_testing.traces import read_recording
+from tests.kilin import test_trace_logging__configuration as configurations
+from tests.kilin import test_trace_logging__sources as sources
+from tests.kilin.system_testing.test__batch_diagnostics import report
+
+
+class TestLocalTraceInspection(unittest.TestCase):
+ """Exercise real writer output and corrupted copies without model calls."""
+
+ def setUp(self):
+ fixture = sources.TestSourceSnapshotRecording()
+ self.addCleanup(fixture.doCleanups)
+ fixture.setUp()
+ self.fixture = fixture
+ self.root = fixture.root
+ self.path = fixture.path
+ self.config = configurations._configuration(self.root)
+ logger = fixture._logger()
+ for _ in range(2):
+ logger.emit(CONFIGURATION_EVENT, component="fixture",
+ data=self.config)
+ for kind in sources.SOURCE_SNAPSHOT_FIELDS:
+ fixture._emit(logger, kind, sources.observation(kind))
+ logger.close()
+
+ def _write(self, payload):
+ self.path.write_text(json.dumps(payload), encoding="utf-8")
+
+ def _model(self, name="conversation_a.json", text="Exact KíLín prompt"):
+ logger = self.fixture._logger(scope="conversation", name=name)
+ logger.emit("llm.call.input", component="fixture", data={
+ "rendered_prompt_artifact": logger.artifact("prompt", text,
+ text=True),
+ })
+ logger.close()
+ relative = logger.readable_path.relative_to(self.root).as_posix()
+ event = next(event for event in read_recording(self.root).events
+ if event.path == relative
+ and event.event_type == "llm.call.input")
+ row = {"input_sequence": event.sequence,
+ "prompt_sha256": sha256(text.encode("utf-8")).hexdigest()}
+ return relative, row, text
+
+ def test_configuration_and_source_details_are_verified_and_read_only(self):
+ kinds = {CONFIGURATION_EVENT, *sources.SOURCE_SNAPSHOT_FIELDS}
+ before = {p: p.read_bytes() for p in self.root.rglob("*")
+ if p.is_file()}
+ recording = read_recording(self.root)
+ local = analysis._local_events(self.root, kinds)
+ self.assertEqual(local["errors"], [])
+ expected = [event for event in recording.events
+ if event.event_type in kinds]
+ self.assertEqual(len(local["events"]), 8)
+ for row, event in zip(local["events"], expected):
+ with self.subTest(sequence=event.sequence):
+ self.assertEqual(row, {
+ "path": event.path, "location": event.location,
+ "metadata": event.metadata, "details": event.details,
+ "exact_content": event.exact_content,
+ })
+ raw = list(analysis._trace_events(self.fixture._raw()))
+ self.assertTrue(any(sources.REFERENCE in node.get("details", {})
+ for node in raw))
+ self.assertEqual(before, {p: p.read_bytes()
+ for p in self.root.rglob("*")
+ if p.is_file()})
+
+ def test_failed_reference_is_labelled_unverified_and_never_repaired(self):
+ payload = self.fixture._raw()
+ node = sources.observations(payload, sources.SCAN)[-1]
+ node["details"][sources.REFERENCE]["sha256"] = "0" * 64
+ self._write(payload)
+ # Current workspace content cannot repair historical observations.
+ (self.root / "source_manifest.json").write_text(
+ '{"new": "unrelated current manifest"}', encoding="utf-8",
+ )
+ before = self.path.read_bytes()
+ local = analysis._local_events(self.root, {sources.SCAN})
+ self.assertEqual(len(local["events"]), 2)
+ self.assertTrue(any("source_snapshot.reference" in issue
+ for issue in local["errors"]))
+ invalid = local["events"][-1]
+ self.assertIsNone(invalid["details"])
+ self.assertEqual(invalid["unverified_details"], node["details"])
+ self.assertEqual(invalid["metadata"], node["event"])
+ self.assertEqual(self.path.read_bytes(), before)
+
+ def test_partial_decoding_is_not_labelled_as_raw_or_verified(self):
+ payload = self.fixture._raw()
+ node = sources.observations(payload, sources.SCAN)[-1]
+ # Configuration validation rejects this reserved marker on a scan;
+ # the independent source decoder can still resolve the valid group.
+ node["details"][CONFIGURATION_REFERENCE] = {
+ "sequence": 1, "sha256": "0" * 64,
+ }
+ self._write(payload)
+ before = self.path.read_bytes()
+ local = analysis._local_events(self.root, {sources.SCAN})
+ invalid = local["events"][-1]
+ self.assertIsNone(invalid["details"])
+ self.assertNotIn("stored_details", invalid)
+ self.assertNotEqual(invalid["unverified_details"], node["details"])
+ self.assertIn("selected_files", invalid["unverified_details"])
+ self.assertTrue(any("configuration.reference" in error
+ for error in local["errors"]))
+ self.assertEqual(self.path.read_bytes(), before)
+
+ def test_merged_completion_preserves_result_and_start_metadata(self):
+ logger = self.fixture._logger()
+ logger.emit("fixture.work.started", component="fixture",
+ status="started", span_id="span_fixture",
+ started_elapsed_ms=1.0,
+ data={"input": [1, 2]})
+ logger.emit("fixture.work.completed", component="fixture",
+ span_id="span_fixture", started_elapsed_ms=1.0,
+ data={"result": "preserved"})
+ logger.close()
+ local = analysis._local_events(self.root, {
+ "fixture.work.started", "fixture.work.completed",
+ })
+ self.assertEqual(local["errors"], [])
+ first, last = local["events"]
+ self.assertEqual(first["metadata"]["status"], "started")
+ self.assertEqual(first["details"], {"input": [1, 2]})
+ self.assertEqual(last["details"], {"result": "preserved"})
+ self.assertTrue(last["location"].endswith("/completion"))
+
+ def test_one_recording_load_serves_multiple_conversations_and_hashes(self):
+ relative, row, text = self._model()
+ other, other_row, other_text = self._model("conversation_b.json",
+ "Other exact prompt")
+ cache = {}
+ with patch.object(analysis, "read_recording", wraps=read_recording) \
+ as reader:
+ first = analysis._trace_index(self.root, relative, cache)
+ second = analysis._trace_index(self.root, other, cache)
+ self.assertIs(first, analysis._trace_index(self.root, relative,
+ cache))
+ self.assertEqual(reader.call_count, 1)
+ self.assertEqual(analysis._exact_model_text(row, "prompt", first),
+ (text, "Verified against report SHA-256."))
+ self.assertEqual(analysis._exact_model_text(other_row, "prompt",
+ second)[0], other_text)
+ self.assertIsNone(analysis._exact_model_text(other_row, "prompt",
+ first)[0])
+ changed = dict(row, prompt_sha256="0" * 64)
+ self.assertEqual(analysis._exact_model_text(changed, "prompt", first),
+ (None, "Local trace content differs from the "
+ "report hash."))
+ config_event = next(event for event in read_recording(self.root).events
+ if event.event_type == CONFIGURATION_EVENT)
+ self.assertEqual(first["events"][config_event.sequence][0]["details"],
+ self.config)
+
+ def test_sequence_ambiguity_in_another_conversation_is_not_hidden(self):
+ relative, row, _ = self._model()
+ other, _, _ = self._model("conversation_b.json")
+ path = self.root / other
+ payload = json.loads(path.read_text("utf-8"))
+ node = next(node for node in analysis._trace_events(payload)
+ if node["event"]["event_type"] == "llm.call.input")
+ node["event"]["sequence"] = row["input_sequence"]
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ index = analysis._trace_index(self.root, relative, {})
+ self.assertEqual(analysis._exact_model_text(row, "prompt", index),
+ (None, "Local trace event missing or ambiguous."))
+
+ def test_partial_recording_retains_text_and_visible_issues(self):
+ relative, row, text = self._model()
+ self.path.unlink()
+ (self.path.parent / ".sequence.json").unlink()
+ before = (self.root / relative).read_bytes()
+ index = analysis._trace_index(self.root, relative, {})
+ self.assertTrue(any("counter.invalid" in error
+ for error in index["errors"]))
+ self.assertTrue(any("trace.missing" in error
+ for error in index["errors"]))
+ self.assertEqual(analysis._exact_model_text(row, "prompt", index)[0],
+ text)
+ op = {"question": {"original_trace": relative}, "model_calls": [
+ {"original": row},
+ ]}
+ html = analysis._model_calls(op, {"original": self.root}, {}, True)
+ self.assertIn("Local trace decoding issues", html)
+ self.assertIn("counter.invalid", html)
+ self.assertIn(text, html)
+ self.assertEqual((self.root / relative).read_bytes(), before)
+
+ def test_nonhierarchy_event_traps_are_not_semantic_events(self):
+ payload = self.fixture._raw()
+ source = deepcopy(sources.observations(payload, sources.SCAN)[0])
+ source["event"]["event_type"] = "fixture.fake"
+ session = next(iter(payload["sessions"].values()))
+ session["unrecognized"] = {"nested": source}
+ source_node = sources.observations(payload, sources.SCAN)[0]
+ source_node["details"]["untrusted_content"] = deepcopy(source)
+ self._write(payload)
+ local = analysis._local_events(self.root, {"fixture.fake"})
+ self.assertEqual(local["events"], [])
+
+ def test_malformed_trace_errors_are_not_silently_discarded(self):
+ invalid = self.path.parent / ".json"
+ invalid.write_text('{"duplicate": 1, "duplicate": 2}', "utf-8")
+ local = analysis._local_events(self.root, {sources.SCAN})
+ self.assertEqual(len(local["events"]), 2)
+ self.assertTrue(any("trace.invalid" in error
+ for error in local["errors"]))
+ data = report()
+ data["original"].update(event_count=2,
+ event_counts={sources.SCAN: 2})
+ data["replayed"].update(event_count=1,
+ event_counts={sources.SCAN: 1})
+ before = deepcopy(data)
+ html = analysis.event_inventory_html(data, original=self.root,
+ include_details=True)
+ self.assertIn("trace.invalid", html)
+ self.assertIn("<broken>.json", html)
+ self.assertNotIn(".json", html)
+ self.assertEqual(data, before)
+
+ def test_linked_root_or_trace_is_rejected_with_visible_issue(self):
+ link = self.root / "linked_workspace"
+ link.symlink_to(self.root, target_is_directory=True)
+ with patch.object(analysis, "read_recording") as reader:
+ local = analysis._local_events(link, {sources.SCAN})
+ self.assertTrue(local["errors"])
+ self.assertEqual(local["events"], [])
+ reader.assert_not_called()
+ linked_trace = self.path.parent / "linked.json"
+ linked_trace.symlink_to(self.path)
+ local = analysis._local_events(self.root, {sources.SCAN})
+ self.assertTrue(any("Linked workspace path" in issue
+ for issue in local["errors"]))
+ self.assertEqual(len(local["events"]), 2)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/kilin/system_testing/test_experiment.py b/tests/kilin/system_testing/test_experiment.py
index 05dfef3c..2d1924e4 100644
--- a/tests/kilin/system_testing/test_experiment.py
+++ b/tests/kilin/system_testing/test_experiment.py
@@ -15,6 +15,7 @@
import unittest
from unittest.mock import patch
+from kilin._trace_configuration import CONFIGURATION_CONTENT_REFERENCE
from kilin.project import open_project
from kilin.source_manifest import (
RoleEdit, apply_source_manifest, preview_source_manifest,
@@ -392,10 +393,20 @@ def test_mismatched_rename_markers(self):
def test_legacy_rename_requires_independent_path_corroboration(self):
self._rename_without_markers()
+
+ def change_project(node):
+ """Corrupt the same historical path in either representation."""
+
+ details = node["details"]
+ value = str(self.root.with_name("other"))
+ if "behavior" in details:
+ details["behavior"]["project"] = value
+ else:
+ self.assertIn(CONFIGURATION_CONTENT_REFERENCE, details)
+ details["project"] = value
+
self._change(self.root / "logs/traces/project.json",
- "gui.project.configuration.effective", lambda node: node[
- "details"]["behavior"].update(
- project=str(self.root.with_name("other"))))
+ "gui.project.configuration.effective", change_project)
self.assertInvalid("relocation.history")
def test_unrelated_same_directory_internal_reopen_is_rejected(self):
diff --git a/tests/kilin/system_testing/test_traces__configuration.py b/tests/kilin/system_testing/test_traces__configuration.py
index 1a1823e9..8897af69 100644
--- a/tests/kilin/system_testing/test_traces__configuration.py
+++ b/tests/kilin/system_testing/test_traces__configuration.py
@@ -14,14 +14,18 @@
from kilin import rag
from kilin._trace_configuration import (
+ CONFIGURATION_CONTENT_REFERENCE,
CONFIGURATION_EVENT,
CONFIGURATION_REFERENCE,
configuration_bytes,
+ configuration_content_bytes,
+ configuration_content_reference,
configuration_reference,
)
from kilin.gui.engine import ChatEngine
from kilin.gui.preferences import DEFAULTS_ENVIRONMENT
from kilin.system_testing import Experiment, InvalidRecordingError
+from kilin.system_testing.reference import _prefix_digest
from kilin.system_testing.traces import read_recording
from tests.kilin import test_trace_logging__configuration as writer_tests
@@ -186,7 +190,7 @@ def test_replay_with_real_source_and_index_reuse(self):
self.assertEqual(replayed.operation_count, len(report.operations))
self.assertEqual(before, _snapshot(original))
- def test_rename_remains_full_and_replays_with_fixed_directory(self):
+ def test_rename_reuses_content_and_replays_with_fixed_directory(self):
self._resume()
renamed = self.workspace.with_name("renamed")
self.engine.rename_project(renamed.name)
@@ -197,21 +201,74 @@ def test_rename_remains_full_and_replays_with_fixed_directory(self):
self._resume()
self.engine.close()
rows = _nodes(self._raw())
- self.assertEqual(rows[-2]["details"]["behavior"]["project"],
- str(renamed))
- self.assertEqual(rows[-1]["details"], configuration_reference(
- rows[-2]["event"]["sequence"],
- configuration_bytes(rows[-2]["details"]),
- ))
+ first = rows[0]
+ expected = configuration_content_reference(
+ first["event"]["sequence"],
+ configuration_content_bytes(first["details"]), str(renamed),
+ )
+ self.assertEqual(rows[-2]["details"], expected)
+ self.assertEqual(rows[-1]["details"], expected)
experiment = Experiment(renamed)
before = _snapshot(renamed)
report = experiment.validate()
self.assertTrue(report.valid, report.issues)
+ configurations = [event.details for event in report.events
+ if event.event_type == CONFIGURATION_EVENT]
+ self.assertEqual(configurations[-2]["behavior"]["project"],
+ str(renamed))
+ self.assertEqual(configurations[-1]["behavior"]["project"],
+ str(renamed))
replayed = experiment.replay(self.target)
self.assertTrue(replayed.validation.valid, replayed.validation.issues)
self.assertEqual(replayed.operation_count, len(report.operations))
self.assertEqual(before, _snapshot(renamed))
+ def test_relocated_references_and_full_payloads_have_same_receipt(self):
+ self._resume()
+ self.engine.rename_project("relocated")
+ self.engine.close()
+ self.workspace = self.workspace.with_name("relocated")
+ self.path = self.workspace / "logs" / "traces" / "project.json"
+ experiment = Experiment(self.workspace)
+ compact = experiment.validate()
+ self.assertTrue(compact.valid, compact.issues)
+ digest = _prefix_digest(compact.events, compact.events[-1].sequence)
+ payload = self._raw()
+ configurations = {event.sequence: event.details
+ for event in compact.events
+ if event.event_type == CONFIGURATION_EVENT}
+ for node in _nodes(payload):
+ node["details"] = configurations[node["event"]["sequence"]]
+ self._write(payload)
+ full = experiment.validate()
+ self.assertTrue(full.valid, full.issues)
+ self.assertEqual(compact, full)
+ self.assertEqual(digest, _prefix_digest(full.events,
+ full.events[-1].sequence))
+
+ def test_corrupted_relocation_blocks_validation_and_replay(self):
+ self._resume()
+ self.engine.rename_project("relocated")
+ self.engine.close()
+ self.workspace = self.workspace.with_name("relocated")
+ self.path = self.workspace / "logs" / "traces" / "project.json"
+ payload = self._raw()
+ last = _nodes(payload)[-1]["details"]
+ last[CONFIGURATION_CONTENT_REFERENCE]["sha256"] = "0" * 64
+ self._write(payload)
+ before = _snapshot(self.workspace)
+ experiment = Experiment(self.workspace)
+ report = experiment.validate()
+ self.assertFalse(report.valid)
+ self.assertIn("configuration.reference",
+ {issue.code for issue in report.issues})
+ with self.assertRaises(InvalidRecordingError):
+ experiment.timeline()
+ with self.assertRaises(InvalidRecordingError):
+ experiment.replay(self.target)
+ self.assertFalse(self.target.exists())
+ self.assertEqual(before, _snapshot(self.workspace))
+
def test_corrupted_references_block_validation_and_replay(self):
original = self._raw()
for case in ("missing", "forward", "self", "reference", "digest",
@@ -318,5 +375,100 @@ def test_resolve_concurrent_process_observations(self):
self._assert_resolved(self.fixture._record_processes())
+class TestConfigurationContentResolution(unittest.TestCase):
+ """Reject malformed relocation references without altering originals."""
+
+ def setUp(self):
+ fixture = writer_tests.TestConfigurationRecording()
+ self.addCleanup(fixture.doCleanups)
+ fixture.setUp()
+ self.fixture = fixture
+ logger = fixture._logger()
+ fixture._emit(logger)
+ relocated = deepcopy(fixture.config)
+ relocated["behavior"]["project"] = "../KíLín relocated"
+ fixture._emit(logger, relocated)
+ fixture._emit(logger, relocated)
+ logger.close()
+ self.path = fixture.path
+ self.original = json.loads(self.path.read_text("utf-8"))
+
+ def test_relocated_reference_corruption_is_blocking(self):
+ cases = ("missing", "self", "forward", "chain", "digest",
+ "boolean", "extra_key", "nonmapping", "mixed",
+ "superseded", "failed_target", "failed_reference",
+ "changed_target", "duplicate_target", "duplicate_current",
+ "incomplete_target", "no_target", "unsupported_event",
+ "wrong_turn", "missing_path", "mixed_references")
+ for case in cases:
+ with self.subTest(case=case):
+ payload = deepcopy(self.original)
+ first, second, third = _nodes(payload)
+ reference = third["details"][CONFIGURATION_CONTENT_REFERENCE]
+ if case == "missing":
+ reference["sequence"] = 0
+ elif case == "self":
+ reference["sequence"] = third["event"]["sequence"]
+ elif case == "forward":
+ reference["sequence"] = third["event"]["sequence"] + 1
+ elif case == "chain":
+ reference["sequence"] = second["event"]["sequence"]
+ elif case == "digest":
+ reference["sha256"] = "0" * 64
+ elif case == "boolean":
+ reference["sequence"] = True
+ elif case == "extra_key":
+ reference["extra"] = True
+ elif case == "nonmapping":
+ third["details"][CONFIGURATION_CONTENT_REFERENCE] = "bad"
+ elif case == "mixed":
+ third["details"]["profile"] = {}
+ elif case == "superseded":
+ second["details"] = deepcopy(first["details"])
+ elif case == "failed_target":
+ first["event"]["status"] = "failed"
+ elif case == "failed_reference":
+ third["event"]["status"] = "failed"
+ elif case == "changed_target":
+ first["details"]["behavior"]["prompt"] += " changed"
+ elif case == "duplicate_target":
+ second["event"]["sequence"] = first["event"]["sequence"]
+ elif case == "duplicate_current":
+ second["event"]["sequence"] = third["event"]["sequence"]
+ elif case == "incomplete_target":
+ first["details"]["behavior"].pop("project")
+ elif case == "no_target":
+ first["details"] = deepcopy(second["details"])
+ elif case == "unsupported_event":
+ third["event"]["event_type"] = "fixture.observed"
+ elif case == "wrong_turn":
+ first["event"]["turn_id"] = "turn_fixture"
+ elif case == "missing_path":
+ third["details"].pop("project")
+ elif case == "mixed_references":
+ third["details"][CONFIGURATION_REFERENCE] = reference
+ self.path.write_text(json.dumps(payload), encoding="utf-8")
+ before = self.path.read_bytes()
+ recording = read_recording(self.fixture.root)
+ self.assertIn("configuration.reference",
+ {issue.code for issue in recording.issues})
+ self.assertEqual(before, self.path.read_bytes())
+
+ def test_conversation_reference_cannot_reuse_project_snapshot(self):
+ logger = self.fixture._logger(name="conversation_a.json",
+ scope="conversation")
+ self.fixture._emit(logger)
+ logger.close()
+ payload = json.loads(logger.readable_path.read_text("utf-8"))
+ node, = _nodes(payload)
+ node["details"] = deepcopy(_nodes(self.original)[-1]["details"])
+ logger.readable_path.write_text(json.dumps(payload), encoding="utf-8")
+ before = _snapshot(self.fixture.root)
+ recording = read_recording(self.fixture.root)
+ self.assertIn("configuration.reference",
+ {issue.code for issue in recording.issues})
+ self.assertEqual(before, _snapshot(self.fixture.root))
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/kilin/system_testing/test_traces__semantics.py b/tests/kilin/system_testing/test_traces__semantics.py
new file mode 100644
index 00000000..6293c028
--- /dev/null
+++ b/tests/kilin/system_testing/test_traces__semantics.py
@@ -0,0 +1,265 @@
+"""Verify exact semantic reconstruction, integrity checks and real replay."""
+
+# pylint: disable=C0115:missing-class-docstring
+# pylint: disable=C0116:missing-function-docstring
+# pylint: disable=C0103:invalid-name
+
+from copy import deepcopy
+import json
+import unittest
+
+from kilin._trace_snapshots import SOURCE_SNAPSHOT_REFERENCE
+from kilin.system_testing import Experiment, InvalidRecordingError
+from kilin.system_testing.reference import (
+ _prefix_digest, inspect_receipt, publish_receipt,
+)
+from kilin.system_testing.traces import read_recording
+from tests.kilin import test_trace_logging__semantics as writer
+from tests.kilin.system_testing import test_experiment, test_replay
+
+
+class TestSemanticReferenceResolution(unittest.TestCase):
+ """Reject malformed references rather than guessing historical state."""
+
+ def setUp(self):
+ fixture = writer.TestSemanticSnapshotRecording()
+ self.addCleanup(fixture.doCleanups)
+ fixture.setUp()
+ self.fixture = fixture
+ logger = fixture.fixture._logger()
+ for kind in (writer.COMMITTED, writer.APPLIED, writer.RECONCILED):
+ fixture._emit(logger, kind)
+ logger.close()
+ self.path = fixture.fixture.path
+ self.original = json.loads(self.path.read_text("utf-8"))
+
+ def _assert_invalid(self, payload, code="semantic_snapshot.reference"):
+ self.path.write_text(json.dumps(payload), "utf-8")
+ before = self.path.read_bytes()
+ recording = read_recording(self.fixture.fixture.root)
+ self.assertIn(code, {issue.code for issue in recording.issues})
+ self.assertEqual(before, self.path.read_bytes())
+
+ def test_invalid_reference_shapes_targets_and_scopes_are_blocking(self):
+ cases = (
+ "missing", "self", "forward", "chain", "digest", "boolean",
+ "extra_key", "nonmapping", "mixed", "mixed_source_reference",
+ "superseded", "failed_target", "failed_reference",
+ "changed_target", "duplicate_target", "duplicate_current",
+ "missing_manifest", "null_manifest", "invalid_target",
+ "unknown_event", "observed_reference", "wrong_turn",
+ "target_turn", "reference_error", "target_trace_error",
+ )
+ for case in cases:
+ with self.subTest(case=case):
+ payload = deepcopy(self.original)
+ first, second, third = writer.semantic_nodes(payload)
+ reference = third["details"][writer.REFERENCE]
+ if case == "missing":
+ reference["sequence"] = 999999
+ elif case == "self":
+ reference["sequence"] = third["event"]["sequence"]
+ elif case == "forward":
+ reference["sequence"] = third["event"]["sequence"] + 1
+ elif case == "chain":
+ reference["sequence"] = second["event"]["sequence"]
+ elif case == "digest":
+ reference["sha256"] = "0" * 64
+ elif case == "boolean":
+ reference["sequence"] = True
+ elif case == "extra_key":
+ reference["extra"] = True
+ elif case == "nonmapping":
+ third["details"][writer.REFERENCE] = "invalid"
+ elif case == "mixed":
+ third["details"]["source_organization"] = {}
+ elif case == "mixed_source_reference":
+ third["details"][SOURCE_SNAPSHOT_REFERENCE] = {}
+ elif case == "superseded":
+ second["details"] = deepcopy(first["details"])
+ elif case == "failed_target":
+ first["event"]["status"] = "failed"
+ elif case == "failed_reference":
+ third["event"]["status"] = "failed"
+ elif case == "changed_target":
+ first["details"]["source_organization"]["changed"] = True
+ elif case == "duplicate_target":
+ second["event"]["sequence"] = first["event"]["sequence"]
+ elif case == "duplicate_current":
+ second["event"]["sequence"] = third["event"]["sequence"]
+ elif case == "missing_manifest":
+ first["details"].pop("source_organization")
+ elif case == "null_manifest":
+ first["details"]["source_organization"] = None
+ elif case == "invalid_target":
+ first["event"]["event_type"] = "unrelated.event"
+ elif case == "unknown_event":
+ third["event"]["event_type"] = "unrelated.event"
+ elif case == "observed_reference":
+ third["event"]["event_type"] = writer.OBSERVED
+ elif case == "wrong_turn":
+ third["event"]["turn_id"] = "turn_fixture"
+ elif case == "target_turn":
+ first["event"]["turn_id"] = "turn_fixture"
+ elif case == "reference_error":
+ third["details"]["error"] = "failed"
+ elif case == "target_trace_error":
+ first["details"]["trace_error"] = "failed"
+ # A turn-correlated node outside a turn is rejected by the
+ # structural decoder before reference resolution is reached.
+ code = ("hierarchy.invalid" if case == "wrong_turn" else
+ "semantic_snapshot.reference")
+ self._assert_invalid(payload, code)
+
+ def test_conversation_reference_cannot_use_a_project_manifest(self):
+ fixture = self.fixture.fixture
+ logger = fixture._logger(scope="conversation",
+ name="conversation_a.json")
+ self.fixture._emit(logger, writer.APPLIED)
+ logger.close()
+ payload = json.loads(logger.readable_path.read_text("utf-8"))
+ node, = writer.semantic_nodes(payload)
+ compact = writer.semantic_nodes(self.original)[1]
+ node["details"] = deepcopy(compact["details"])
+ logger.readable_path.write_text(json.dumps(payload), "utf-8")
+ recording = read_recording(fixture.root)
+ self.assertIn("semantic_snapshot.reference",
+ {issue.code for issue in recording.issues})
+
+ def test_group_reference_cannot_be_an_indirect_manifest_target(self):
+ fixture = self.fixture.fixture
+ logger = fixture._logger()
+ for kind in (writer.OBSERVED, writer.OBSERVED, writer.APPLIED):
+ self.fixture._emit(logger, kind)
+ logger.close()
+ payload = json.loads(self.path.read_text("utf-8"))
+ first, compact, applied = writer.semantic_nodes(payload)[-3:]
+ self.assertNotIn(SOURCE_SNAPSHOT_REFERENCE, first["details"])
+ self.assertIn(SOURCE_SNAPSHOT_REFERENCE, compact["details"])
+ applied["details"][writer.REFERENCE]["sequence"] = (
+ compact["event"]["sequence"])
+ self._assert_invalid(payload)
+
+ def test_span_completion_cannot_contain_a_semantic_reference(self):
+ logger = self.fixture.fixture._logger()
+ with logger.span("gui.source_organization.apply", component="test"):
+ pass
+ logger.close()
+ payload = json.loads(self.path.read_text("utf-8"))
+ compact = writer.semantic_nodes(self.original)[1]["details"]
+ completions = [node for session in payload["sessions"].values()
+ for node in session.get("operations", {}).values()
+ if node.get("completion", {}).get("event_type") ==
+ writer.APPLIED]
+ self.assertEqual(len(completions), 1)
+ completions[0]["result"] = deepcopy(compact)
+ self._assert_invalid(payload)
+
+
+class TestSemanticSnapshotInspection(unittest.TestCase):
+ """Compare full and compact real engine histories before replay."""
+
+ def setUp(self):
+ fixture = test_replay.TestReplay()
+ self.addCleanup(fixture.doCleanups)
+ fixture.setUp()
+ self.fixture = fixture
+ self.workspace = fixture.experiment.workspace.with_name(
+ "semantic_original")
+ fixture.engine.rename_project(self.workspace.name)
+ self.assertEqual(fixture.engine.session.project.root, self.workspace)
+ fixture.fixture.workspace = self.workspace
+ fixture.original.root = self.workspace
+ fixture.experiment = Experiment(self.workspace)
+ fixture.original.experiment = fixture.experiment
+ self.path = self.workspace / "logs/traces/project.json"
+ self.report = fixture.original._record_semantic_edit()
+
+ def test_semantic_receipt_replay_and_full_recording_equivalence(self):
+ fixture = self.fixture
+ payload = json.loads(self.path.read_text("utf-8"))
+ nodes = writer.semantic_nodes(payload)
+ compact = [node for node in nodes
+ if writer.REFERENCE in node["details"]]
+ self.assertTrue(compact)
+ self.assertTrue(any(node["event"]["event_type"] == writer.APPLIED
+ for node in compact))
+ published = publish_receipt(self.workspace, self.report, [])
+ receipt_before = published.read_bytes()
+ status = inspect_receipt(self.workspace, self.report)["status"]
+ original = test_experiment._snapshot(self.workspace)
+ with fixture._model():
+ replay = fixture.experiment.replay(fixture.target)
+ self.assertTrue(replay.validation.valid, replay.validation.issues)
+ self.assertEqual(replay.operation_count, len(self.report.operations))
+ self.assertEqual(original, test_experiment._snapshot(self.workspace))
+ self.assertEqual(
+ (self.workspace / "source_manifest.json").read_bytes(),
+ (fixture.target / "source_manifest.json").read_bytes(),
+ )
+ comparison = fixture.experiment.compare(fixture.target)
+ self.assertTrue(comparison.complete, comparison.data["alignment"])
+ full = deepcopy(payload)
+ by_sequence = {event.sequence: event for event in self.report.events}
+ for node in writer.semantic_nodes(full):
+ node["details"] = deepcopy(
+ by_sequence[node["event"]["sequence"]].details)
+ self.assertLess(len(json.dumps(payload)), len(json.dumps(full)))
+ self.path.write_text(json.dumps(full), "utf-8")
+ expanded = fixture.experiment.validate()
+ self.assertEqual(expanded, self.report)
+ self.assertEqual(_prefix_digest(expanded.events, len(expanded.events)),
+ _prefix_digest(self.report.events,
+ len(self.report.events)))
+ self.assertEqual(inspect_receipt(self.workspace, expanded)["status"],
+ status)
+ self.assertEqual(published.read_bytes(), receipt_before)
+
+ def test_noop_apply_preserves_full_gui_result_and_current_inspection(self):
+ fixture = self.fixture
+ fixture.engine.resume_project(str(self.workspace))
+ preview = fixture._semantic("preview")
+ self.assertFalse(preview["changed"])
+ response = fixture._semantic("apply", preview_id=preview["preview_id"])
+ self.assertFalse(response["changed"])
+ self.assertNotIn(writer.REFERENCE, response)
+ self.assertIn("source_organization", response)
+ fixture.engine.close()
+ report = fixture.experiment.validate()
+ self.assertTrue(report.valid, report.issues)
+ applied = [event for event in report.events
+ if event.event_type == writer.APPLIED][-1]
+ for field in ("source_organization", "inspection", "changed",
+ "revision", "sha256", "trace_error"):
+ self.assertEqual(applied.details[field], response[field], field)
+ payload = json.loads(self.path.read_text("utf-8"))
+ raw = [node for node in writer.semantic_nodes(payload)
+ if node["event"]["event_type"] == writer.APPLIED][-1]
+ self.assertIn(writer.REFERENCE, raw["details"])
+ self.assertEqual(report.events[:len(self.report.events)],
+ self.report.events)
+
+ def test_corrupt_reference_blocks_replay_and_creates_no_destination(self):
+ payload = json.loads(self.path.read_text("utf-8"))
+ for node in writer.semantic_nodes(payload):
+ if writer.REFERENCE in node["details"]:
+ node["details"][writer.REFERENCE]["sha256"] = "0" * 64
+ break
+ else:
+ self.fail("Real producer did not compact its semantic result.")
+ self.path.write_text(json.dumps(payload), "utf-8")
+ before = test_experiment._snapshot(self.workspace)
+ report = self.fixture.experiment.validate()
+ self.assertFalse(report.valid)
+ self.assertIn("semantic_snapshot.reference",
+ {issue.code for issue in report.issues})
+ with self.assertRaises(InvalidRecordingError):
+ self.fixture.experiment.timeline()
+ with self.assertRaises(InvalidRecordingError):
+ self.fixture.experiment.replay(self.fixture.target)
+ self.assertFalse(self.fixture.target.exists())
+ self.assertEqual(test_experiment._snapshot(self.workspace), before)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/kilin/system_testing/test_traces__sources.py b/tests/kilin/system_testing/test_traces__sources.py
new file mode 100644
index 00000000..3d5d4adc
--- /dev/null
+++ b/tests/kilin/system_testing/test_traces__sources.py
@@ -0,0 +1,282 @@
+"""Verify source snapshot references in recorded workspace histories."""
+
+# pylint: disable=C0115:missing-class-docstring
+# pylint: disable=C0116:missing-function-docstring
+# pylint: disable=C0103:invalid-name
+
+from copy import deepcopy
+import json
+import os
+from pathlib import Path
+from tempfile import TemporaryDirectory
+import unittest
+from unittest.mock import patch
+
+from kilin import rag
+from kilin._trace_snapshots import SOURCE_SNAPSHOT_FIELDS
+from kilin.gui.engine import ChatEngine
+from kilin.gui.preferences import DEFAULTS_ENVIRONMENT
+from kilin.system_testing import Experiment, InvalidRecordingError
+from kilin.system_testing.reference import inspect_receipt, publish_receipt
+from kilin.system_testing.traces import read_recording
+from tests.kilin import test_trace_logging__sources as writer_tests
+from tests.kilin.system_testing import test_traces__configuration as models
+
+REFERENCE = writer_tests.REFERENCE
+SCAN = writer_tests.SCAN
+INDEX = writer_tests.INDEX
+SEMANTIC = writer_tests.SEMANTIC
+
+
+class TestSourceReferenceResolution(unittest.TestCase):
+ """Reject invalid source references without repairing the trace."""
+
+ def setUp(self):
+ fixture = writer_tests.TestSourceSnapshotRecording()
+ self.addCleanup(fixture.doCleanups)
+ fixture.setUp()
+ self.fixture = fixture
+ logger = fixture._logger()
+ fixture._emit(logger, INDEX, writer_tests.observation(INDEX))
+ for _ in range(3):
+ fixture._emit(logger, SCAN, writer_tests.observation(SCAN))
+ logger.close()
+ self.original = fixture._raw()
+ self.path = fixture.path
+
+ def _write(self, payload):
+ self.path.write_text(json.dumps(payload), encoding="utf-8")
+
+ def _assert_invalid(self):
+ before = self.path.read_bytes()
+ recording = read_recording(self.fixture.root)
+ self.assertIn("source_snapshot.reference",
+ {issue.code for issue in recording.issues})
+ self.assertEqual(before, self.path.read_bytes())
+
+ def test_reference_corruption_is_blocking(self):
+ cases = ("missing", "self", "forward", "chain", "wrong_kind",
+ "digest", "boolean", "extra_key", "nonmapping", "mixed",
+ "superseded", "failed_target", "failed_reference",
+ "changed_target", "duplicate_target", "duplicate_current",
+ "incomplete_target", "incomplete_reference", "no_target",
+ "unsupported_event", "wrong_turn")
+ for case in cases:
+ with self.subTest(case=case):
+ payload = deepcopy(self.original)
+ first, second, third = writer_tests.observations(payload,
+ SCAN)
+ other, = writer_tests.observations(payload, INDEX)
+ reference = third["details"][REFERENCE]
+ if case == "missing":
+ reference["sequence"] = 1
+ elif case == "self":
+ reference["sequence"] = third["event"]["sequence"]
+ elif case == "forward":
+ reference["sequence"] = third["event"]["sequence"] + 1
+ elif case == "chain":
+ reference["sequence"] = second["event"]["sequence"]
+ elif case == "wrong_kind":
+ reference["sequence"] = other["event"]["sequence"]
+ elif case == "digest":
+ reference["sha256"] = "0" * 64
+ elif case == "boolean":
+ reference["sequence"] = True
+ elif case == "extra_key":
+ reference["extra"] = True
+ elif case == "nonmapping":
+ third["details"][REFERENCE] = "invalid"
+ elif case == "mixed":
+ third["details"]["entries"] = []
+ elif case == "superseded":
+ second["details"] = deepcopy(first["details"])
+ elif case == "failed_target":
+ first["event"]["status"] = "failed"
+ elif case == "failed_reference":
+ third["event"]["status"] = "failed"
+ elif case == "changed_target":
+ first["details"]["entries"][0]["size_bytes"] += 1
+ elif case == "duplicate_target":
+ other["event"]["sequence"] = first["event"]["sequence"]
+ elif case == "duplicate_current":
+ other["event"]["sequence"] = third["event"]["sequence"]
+ elif case == "incomplete_target":
+ first["details"]["complete"] = False
+ elif case == "incomplete_reference":
+ third["details"]["complete"] = False
+ elif case == "no_target":
+ first["details"] = deepcopy(second["details"])
+ elif case == "unsupported_event":
+ third["event"]["event_type"] = "index.empty"
+ elif case == "wrong_turn":
+ # A turn-correlated operation at project level is itself
+ # malformed. The missing target must also block later
+ # references to the same full observation.
+ first["event"]["turn_id"] = "turn_fixture"
+ self._write(payload)
+ self._assert_invalid()
+
+ def test_conversation_reference_cannot_use_project_target(self):
+ logger = self.fixture._logger(scope="conversation",
+ name="conversation_a.json")
+ full = writer_tests.observation(SCAN)
+ self.fixture._emit(logger, SCAN, full)
+ logger.close()
+ payload = json.loads(logger.readable_path.read_text("utf-8"))
+ node, = writer_tests.observations(payload, SCAN)
+ first = writer_tests.observations(self.original, SCAN)[0]
+ for field in SOURCE_SNAPSHOT_FIELDS[SCAN]:
+ node["details"].pop(field)
+ node["details"][REFERENCE] = writer_tests.reference_for(first)
+ logger.readable_path.write_text(json.dumps(payload), "utf-8")
+ self._assert_invalid()
+
+
+class TestSourceSnapshotInspection(unittest.TestCase):
+ """Validate real engine openings, replay and publication fingerprints."""
+
+ def setUp(self):
+ temporary = TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name).resolve()
+ self.workspace = self.root / "sources_original"
+ self.target = self.root / "sources_replay"
+ self.path = self.workspace / "logs" / "traces" / "project.json"
+ self.events = []
+ for patcher in (
+ patch.dict(os.environ, {
+ DEFAULTS_ENVIRONMENT: str(self.root / "preferences.json"),
+ }),
+ patch.object(rag, "choose_backend", return_value="mlx"),
+ patch.object(rag, "ChatSession", side_effect=models._chat_model),
+ patch.object(rag, "EmbeddingSession",
+ side_effect=models._embedding_model),
+ ):
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.engine = ChatEngine(self.root, self.events.append,
+ trace_enabled=True)
+ self.addCleanup(self.engine.close)
+ folder = self.root / "library"
+ folder.mkdir()
+ for i in range(12):
+ (folder / f"source_{i:02d}.txt").write_text(
+ f"Synthetic source {i} reports a calibration result.\n",
+ encoding="utf-8",
+ )
+ self.engine.open_project([str(folder)], "writing",
+ str(self.workspace))
+ self.assertEqual(self.events[-1]["event"], "opened", self.events)
+ self.engine.close()
+ self.experiment = Experiment(self.workspace)
+
+ def _resume(self):
+ self.engine.resume_project(str(self.workspace))
+ self.assertEqual(self.events[-1]["event"], "opened", self.events)
+ self.engine.close()
+
+ def _raw(self):
+ return json.loads(self.path.read_text("utf-8"))
+
+ def _report(self):
+ report = self.experiment.validate()
+ self.assertTrue(report.valid, report.issues)
+ return report
+
+ def _full_payload(self, payload, report):
+ """Expand an in-memory copy to the equivalent legacy raw format."""
+ by_sequence = {event.sequence: event for event in report.events}
+ full = deepcopy(payload)
+ for node in writer_tests.observations(full):
+ sequence = node["event"]["sequence"]
+ node["details"] = deepcopy(by_sequence[sequence].details)
+ return full
+
+ def test_opening_receipt_replay_and_full_snapshot_equivalence(self):
+ published = self._report()
+ receipt = publish_receipt(self.workspace, published, [])
+ receipt_before = receipt.read_bytes()
+ first = self._raw()
+ self._resume()
+ self._resume()
+ payload = self._raw()
+ # Appending diagnostics never rewrites the published event nodes.
+ for node in writer_tests.observations(first):
+ self.assertIn(node, writer_tests.observations(payload))
+ for kind in SOURCE_SNAPSHOT_FIELDS:
+ rows = writer_tests.observations(payload, kind)
+ self.assertIn(REFERENCE, rows[-1]["details"], kind)
+ self.assertNotIn(REFERENCE, rows[0]["details"], kind)
+ before = models._snapshot(self.workspace)
+ report = self._report()
+ self.assertEqual(inspect_receipt(self.workspace, report)["status"],
+ "inspection_only")
+ self.assertEqual(receipt_before, receipt.read_bytes())
+ self.assertEqual(models._snapshot(self.workspace), before)
+ replay = self.experiment.replay(self.target)
+ self.assertTrue(replay.validation.valid, replay.validation.issues)
+ self.assertEqual(replay.operation_count, len(report.operations))
+ self.assertEqual(replay.differences, ())
+ comparison = self.experiment.compare(self.target)
+ self.assertTrue(comparison.complete, comparison.data["alignment"])
+ self.assertEqual(models._snapshot(self.workspace), before)
+ full = self._full_payload(payload, report)
+ compact_bytes = len(json.dumps(payload, indent=2, ensure_ascii=False)
+ .encode("utf-8"))
+ full_bytes = len(json.dumps(full, indent=2, ensure_ascii=False)
+ .encode("utf-8"))
+ self.assertLess(compact_bytes, full_bytes)
+ self.path.write_text(json.dumps(full), encoding="utf-8")
+ legacy = self._report()
+ self.assertEqual(legacy, report)
+ self.assertEqual(inspect_receipt(self.workspace, legacy)["status"],
+ "inspection_only")
+ self.assertEqual(receipt_before, receipt.read_bytes())
+
+ def test_source_change_creates_new_snapshots(self):
+ self._resume()
+ previous = self._report()
+ source = self.root / "extra.txt"
+ source.write_text("Additional synthetic evidence.\n", "utf-8")
+ self.engine.resume_project(str(self.workspace))
+ self.engine.add_project_sources([str(source)])
+ self.engine.close()
+ self._resume()
+ report = self._report()
+ scan = [event.details for event in report.events
+ if event.event_type == SCAN]
+ self.assertNotIn("extra.txt", scan[0]["selected_files"])
+ self.assertIn("extra.txt", scan[-1]["selected_files"])
+ self.assertEqual(report.events[:len(previous.events)],
+ previous.events)
+ rows = writer_tests.observations(self._raw(), SCAN)
+ self.assertNotIn(REFERENCE, rows[-2]["details"])
+ self.assertEqual(rows[-1]["details"][REFERENCE],
+ writer_tests.reference_for(rows[-2]))
+ self.assertTrue(self.experiment.replay(self.target).validation.valid)
+
+ def test_bad_reference_blocks_validation_timeline_and_replay(self):
+ self._resume()
+ self._resume()
+ original = self._raw()
+ for kind in SOURCE_SNAPSHOT_FIELDS:
+ with self.subTest(kind=kind):
+ payload = deepcopy(original)
+ rows = writer_tests.observations(payload, kind)
+ rows[-1]["details"][REFERENCE]["sha256"] = "0" * 64
+ self.path.write_text(json.dumps(payload), "utf-8")
+ before = models._snapshot(self.workspace)
+ report = self.experiment.validate()
+ self.assertFalse(report.valid)
+ self.assertIn("source_snapshot.reference",
+ {issue.code for issue in report.issues})
+ with self.assertRaises(InvalidRecordingError):
+ self.experiment.timeline()
+ with self.assertRaises(InvalidRecordingError):
+ self.experiment.replay(self.target)
+ self.assertFalse(self.target.exists())
+ self.assertEqual(models._snapshot(self.workspace), before)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/kilin/test__trace_configuration.py b/tests/kilin/test__trace_configuration.py
new file mode 100644
index 00000000..0b69e3c8
--- /dev/null
+++ b/tests/kilin/test__trace_configuration.py
@@ -0,0 +1,89 @@
+"""Preserve exact configuration content when its observed path changes."""
+
+# pylint: disable=C0115:missing-class-docstring
+# pylint: disable=C0116:missing-function-docstring
+# pylint: disable=C0103:invalid-name
+
+from copy import deepcopy
+import json
+import unittest
+
+from kilin._trace_configuration import (
+ CONFIGURATION_CONTENT_REFERENCE,
+ configuration_bytes,
+ configuration_content_bytes,
+ configuration_content_reference,
+ resolve_configuration_reference,
+)
+from tests.kilin.test_trace_logging__configuration import _configuration
+
+
+class TestConfigurationContent(unittest.TestCase):
+ """Check exact path reconstruction and narrow content extraction."""
+
+ def test_only_behavior_project_is_excluded(self):
+ original = _configuration("C:\\workspace\\old")
+ original["extra"] = {"project": "separate", "unknown": [1, True, 1.0]}
+ before = deepcopy(original)
+ encoded = configuration_content_bytes(original)
+ expected = deepcopy(original)
+ expected["behavior"].pop("project")
+ self.assertEqual(json.loads(encoded), expected)
+ moved = deepcopy(original)
+ moved["behavior"]["project"] = "../KíLín new"
+ self.assertEqual(encoded, configuration_content_bytes(moved))
+ self.assertNotEqual(configuration_bytes(original),
+ configuration_bytes(moved))
+ moved["extra"]["project"] = "changed"
+ self.assertNotEqual(encoded, configuration_content_bytes(moved))
+ self.assertEqual(original, before)
+
+ def test_current_path_value_and_json_types_round_trip(self):
+ full = _configuration("original")
+ before = deepcopy(full)
+ encoded = configuration_content_bytes(full)
+ paths = (None, "", "../KíLín/../copy", "C:\\work\\copy",
+ 1, 1.0, True, {"unknown": [None, False, 1.0]})
+ for project in paths:
+ with self.subTest(project=project):
+ reference = configuration_content_reference(2, encoded,
+ project)
+ result = resolve_configuration_reference(reference, 3,
+ (2, full))
+ expected = deepcopy(full)
+ expected["behavior"]["project"] = project
+ self.assertEqual(configuration_bytes(result),
+ configuration_bytes(expected))
+ self.assertIsNot(result["behavior"], full["behavior"])
+ if isinstance(project, dict):
+ self.assertIsNot(reference["project"], project)
+ self.assertIsNot(result["behavior"]["project"],
+ reference["project"])
+ self.assertEqual(full, before)
+
+ def test_missing_or_incomplete_content_is_rejected(self):
+ full = _configuration("original")
+ missing = deepcopy(full)
+ missing["behavior"].pop("project")
+ wrong_type = deepcopy(full)
+ wrong_type["behavior"] = []
+ incomplete = deepcopy(full)
+ incomplete.pop("tools")
+ compact = configuration_content_reference(
+ 1, configuration_content_bytes(full), "moved",
+ )
+ mixed = {**full, **compact}
+ for data in (missing, wrong_type, incomplete, compact, mixed):
+ with self.subTest(data=data):
+ with self.assertRaises(ValueError):
+ configuration_content_bytes(data)
+ for data in (compact, mixed):
+ with self.subTest(data=data):
+ with self.assertRaises(ValueError):
+ configuration_bytes(data)
+ self.assertEqual(set(compact),
+ {CONFIGURATION_CONTENT_REFERENCE, "project"})
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/kilin/test__trace_json.py b/tests/kilin/test__trace_json.py
new file mode 100644
index 00000000..e80cd2c3
--- /dev/null
+++ b/tests/kilin/test__trace_json.py
@@ -0,0 +1,226 @@
+"""Verify lossless trace formatting and ordinary writer integration."""
+
+# pylint: disable=C0115:missing-class-docstring
+# pylint: disable=C0116:missing-function-docstring
+# pylint: disable=C0103:invalid-name
+
+from copy import deepcopy
+import json
+from pathlib import Path
+import random
+from tempfile import TemporaryDirectory
+import unittest
+
+from kilin._trace_json import trace_json_dumps
+from kilin.system_testing.reference import _prefix_digest
+from kilin.system_testing.traces import read_recording
+from kilin.trace_logging import (
+ TRACE_EVENT_LLM_CALL_INPUT,
+ TraceConfig,
+ TraceLogger,
+)
+
+
+class TestTraceJSON(unittest.TestCase):
+ """Retain exact JSON values while grouping only long integer arrays."""
+
+ def test_integer_rows_and_threshold(self):
+ for count in (0, 1, 15, 16, 17, 31, 32, 33, 1025):
+ for nested in (False, True):
+ with self.subTest(count=count, nested=nested):
+ integers = list(range(-(count // 2), count - count // 2))
+ payload = {"tokens": integers} if nested else integers
+ encoded = trace_json_dumps(payload)
+ self.assertEqual(json.loads(encoded), payload)
+ ordinary = json.dumps(payload, indent=2,
+ ensure_ascii=False)
+ if len(integers) < 16:
+ self.assertEqual(encoded, ordinary)
+ else:
+ self.assertLess(len(encoded), len(ordinary))
+ rows = [line.strip().rstrip(",").split(", ")
+ for line in encoded.splitlines()
+ if line.strip()[:1] in "-0123456789"]
+ self.assertEqual(
+ [len(row) for row in rows[:-1]],
+ [16] * (len(rows) - 1),
+ )
+ self.assertLessEqual(len(rows[-1]), 16)
+
+ def test_other_arrays_keep_standard_format(self):
+ arrays = (
+ [True] * 20,
+ [False] * 20,
+ list(range(20)) + [True],
+ [1.0] * 20,
+ list(range(20)) + [-0.0],
+ ["12"] * 20,
+ [None] * 20,
+ [[1, 2]] * 20,
+ list(range(20)) + [{"nested": []}],
+ )
+ for values in arrays:
+ with self.subTest(values=values):
+ payload = {"values": values}
+ self.assertEqual(
+ trace_json_dumps(payload),
+ json.dumps(payload, indent=2, ensure_ascii=False),
+ )
+
+ def test_strings_cannot_be_interpreted_as_arrays(self):
+ literal = json.dumps(list(range(32)), indent=2)
+ texts = [
+ literal, repr(literal), json.dumps(literal),
+ 'quoted "array": ' + literal,
+ "\\\"\\\\\n\r\t\b\f" + literal,
+ "KíLín — 中文 🙂 \u2028\u2029" + literal,
+ ]
+ payload = {text: text for text in texts}
+ payload["actual_array"] = list(range(33))
+ encoded = trace_json_dumps(payload)
+ self.assertEqual(json.loads(encoded), payload)
+ for text in texts:
+ self.assertIn(json.dumps(text, ensure_ascii=False), encoded)
+
+ def test_scalar_types_lexemes_and_mapping_order_are_preserved(self):
+ payload = {
+ "last": [0, -10**100, 10**100] * 8,
+ "first": [None, True, False, 0, 1.0, -0.0, 1e-100, 1e100],
+ "unicode": "KíLín\n中文",
+ "empty": {},
+ }
+ decoded = json.loads(trace_json_dumps(payload))
+ self.assertEqual(list(decoded), list(payload))
+ self.assertEqual(
+ json.dumps(decoded, ensure_ascii=False),
+ json.dumps(payload, ensure_ascii=False),
+ )
+ self.assertEqual([type(value) for value in decoded["first"]],
+ [type(value) for value in payload["first"]])
+
+ def test_payload_is_not_mutated(self):
+ values = list(range(100))
+ payload = {"first": values, "second": {"same": values}}
+ before = deepcopy(payload)
+ trace_json_dumps(payload)
+ self.assertEqual(payload, before)
+ self.assertIs(payload["first"], values)
+ self.assertIs(payload["second"]["same"], values)
+
+ def test_standard_encoder_failures_are_unchanged(self):
+ circular_list = []
+ circular_list.append(circular_list)
+ circular_mapping = {}
+ circular_mapping["self"] = circular_mapping
+ for payload in (b"bytes", {1, 2}, {(): 1},
+ circular_list, circular_mapping):
+ with self.subTest(type=type(payload).__name__):
+ try:
+ json.dumps(payload, indent=2, ensure_ascii=False)
+ except (TypeError, ValueError) as error:
+ expected_type = type(error)
+ expected_message = str(error)
+ else:
+ self.fail("Fixture must be rejected by json.dumps.")
+ with self.assertRaises(expected_type) as raised:
+ trace_json_dumps(payload)
+ self.assertEqual(str(raised.exception), expected_message)
+
+ def test_standard_nonfinite_serialization_is_not_reinterpreted(self):
+ # Diagnostic normalization and strict readers own their existing
+ # nonfinite-value policies; changing whitespace must not alter them.
+ payload = {"numbers": [float("nan"), float("inf"), -float("inf")]}
+ self.assertEqual(trace_json_dumps(payload),
+ json.dumps(payload, indent=2, ensure_ascii=False))
+
+ def test_varied_nested_json_round_trips_exactly(self):
+ generator = random.Random(1729)
+ for case in range(40):
+ payload = {
+ "integers": [generator.randrange(-10**30, 10**30)
+ for _ in range(generator.randrange(100))],
+ "mixed": [generator.choice((None, True, False, 3, 3.0,
+ "[1, 2]", "\n", "中文"))
+ for _ in range(40)],
+ "nested": [{"ids": list(range(case + 1))} for _ in range(3)],
+ }
+ with self.subTest(case=case):
+ self.assertEqual(
+ json.dumps(json.loads(trace_json_dumps(payload))),
+ json.dumps(payload),
+ )
+
+
+class TestTraceJSONWriters(unittest.TestCase):
+ """Verify actual traces and integrity hashes across formatting changes."""
+
+ def test_both_writers_retain_decoded_events_and_receipt_digest(self):
+ with TemporaryDirectory() as temporary:
+ root = Path(temporary).resolve()
+ directory = root / "logs" / "traces"
+ directory.mkdir(parents=True)
+ (root / "profile.ini").touch()
+ tokens = list(range(65)) + [2**80, -(2**80)]
+ for scope, name in (("project", "project.json"),
+ ("conversation", "conversation_a.json")):
+ logger = TraceLogger(
+ TraceConfig(enabled=True, output_path=directory / name,
+ failure_policy="raise"),
+ default_directory=directory, project_directory=root,
+ scope=scope,
+ )
+ self.addCleanup(logger.close)
+ if scope == "conversation":
+ logger.update_conversation({
+ "conversation_id": "a",
+ "name": "Formatter fixture",
+ "parent_conversation_id": None,
+ "origin_checkpoint_id": None,
+ "created_at_utc": "2026-12-02T00:00:00Z",
+ "updated_at_utc": "2026-12-02T00:00:00Z",
+ "turns": [],
+ "token_fixture": tokens,
+ })
+ logger.emit(
+ TRACE_EVENT_LLM_CALL_INPUT,
+ component="fixture",
+ data={
+ "input_token_ids_artifact": logger.artifact(
+ "ids", tokens,
+ ),
+ "rendered_prompt_artifact": logger.artifact(
+ "prompt", "KíLín\n[0, 1]", text=True,
+ ),
+ },
+ )
+ logger.close()
+
+ compact = read_recording(root)
+ self.assertEqual(compact.issues, [])
+ inputs = [event for event in compact.events
+ if event.event_type == TRACE_EVENT_LLM_CALL_INPUT]
+ self.assertEqual(len(inputs), 2)
+ for event in inputs:
+ self.assertEqual(event.exact_content["03_input_token_ids"][
+ "value"], tokens)
+ self.assertEqual(event.exact_content["02_rendered_prompt"][
+ "value"], "KíLín\n[0, 1]")
+ digest = _prefix_digest(tuple(compact.events),
+ len(compact.events))
+ for name in ("project.json", "conversation_a.json"):
+ path = directory / name
+ encoded = path.read_text(encoding="utf-8")
+ ordinary = json.dumps(json.loads(encoded), indent=2,
+ ensure_ascii=False) + "\n"
+ self.assertLess(len(encoded), len(ordinary))
+ path.write_text(ordinary, encoding="utf-8")
+ full = read_recording(root)
+ self.assertEqual(full.events, compact.events)
+ self.assertEqual(full.states, compact.states)
+ self.assertEqual(full.issues, compact.issues)
+ self.assertEqual(_prefix_digest(tuple(full.events),
+ len(full.events)), digest)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/kilin/test_trace_logging__configuration.py b/tests/kilin/test_trace_logging__configuration.py
index 49f7c0e9..f5a1b031 100644
--- a/tests/kilin/test_trace_logging__configuration.py
+++ b/tests/kilin/test_trace_logging__configuration.py
@@ -18,11 +18,15 @@
from kilin import _trace_project
from kilin._trace_configuration import (
+ CONFIGURATION_CONTENT_REFERENCE,
CONFIGURATION_EVENT,
CONFIGURATION_REFERENCE,
configuration_bytes,
+ configuration_content_bytes,
+ configuration_content_reference,
configuration_reference,
)
+from kilin.system_testing.traces import read_recording
from kilin.trace_logging import NullTraceLogger, TraceConfig, TraceLogger
@@ -155,7 +159,141 @@ def test_all_setting_groups_and_historical_path_are_significant(self):
else:
changed[key]["extra"] = "changed"
self._emit(logger, changed)
+ if key == "behavior":
+ node = self._nodes()[-1]
+ self.assertIn(CONFIGURATION_CONTENT_REFERENCE,
+ node["details"])
+ self.assertEqual(node["details"]["project"],
+ changed["behavior"]["project"])
+ recording = read_recording(self.root)
+ self.assertFalse(recording.issues, recording.issues)
+ self.assertEqual(recording.events[-1].details, changed)
+ else:
+ self.assertEqual(self._nodes()[-1]["details"], changed)
+
+ def test_relocated_paths_reuse_one_complete_snapshot_across_runs(self):
+ expected = []
+ for project in (str(self.root), "../KíLín moved", None,
+ "C:\\workspace\\copy", str(self.root)):
+ logger = self._logger()
+ data = deepcopy(self.config)
+ data["behavior"]["project"] = project
+ self._emit(logger, data)
+ expected.append(data)
+ logger.close()
+ rows = self._nodes()
+ first = rows[0]
+ encoded = configuration_content_bytes(expected[0])
+ self.assertEqual(first["details"], expected[0])
+ for row, data in zip(rows[1:-1], expected[1:-1]):
+ self.assertEqual(row["details"], configuration_content_reference(
+ first["event"]["sequence"], encoded,
+ data["behavior"]["project"],
+ ))
+ self.assertEqual(rows[-1]["details"], configuration_reference(
+ first["event"]["sequence"], configuration_bytes(expected[0]),
+ ))
+ recording = read_recording(self.root)
+ self.assertFalse(recording.issues, recording.issues)
+ observations = [event for event in recording.events
+ if event.event_type == CONFIGURATION_EVENT]
+ self.assertEqual([event.details for event in observations], expected)
+ self.assertEqual([event.metadata for event in observations],
+ [node["event"] for node in rows])
+ self._assert_recording_identity()
+
+ def test_missing_path_and_other_settings_are_not_relocated(self):
+ logger = self._logger()
+ incomplete = deepcopy(self.config)
+ del incomplete["behavior"]["project"]
+ self._emit(logger, incomplete)
+ explicit_null = deepcopy(self.config)
+ explicit_null["behavior"]["project"] = None
+ self._emit(logger, explicit_null)
+ self.assertEqual(self._nodes()[-1]["details"], explicit_null)
+ self._emit(logger, incomplete)
+ self.assertEqual(self._nodes()[-1]["details"], incomplete)
+ for key, value in (("prompt", "changed"), ("extra", "new")):
+ with self.subTest(key=key):
+ self._emit(logger)
+ changed = deepcopy(self.config)
+ changed["behavior"]["project"] = "renamed"
+ changed["behavior"][key] = value
+ self._emit(logger, changed)
self.assertEqual(self._nodes()[-1]["details"], changed)
+ self._emit(logger)
+ changed = deepcopy(self.config)
+ changed["behavior"]["project"] = "renamed"
+ changed["extra"] = {"project": "independent path"}
+ self._emit(logger, changed)
+ self.assertEqual(self._nodes()[-1]["details"], changed)
+
+ def test_relocated_reference_uses_one_project_read_and_write(self):
+ logger = self._logger()
+ self._emit(logger)
+ changed = deepcopy(self.config)
+ changed["behavior"]["project"] = "relocated"
+ with (
+ patch.object(_trace_project, "_read_object",
+ wraps=_trace_project._read_object) as read,
+ patch.object(_trace_project, "atomic_write_text",
+ wraps=_trace_project.atomic_write_text) as write,
+ ):
+ self._emit(logger, changed)
+ self.assertIn(CONFIGURATION_CONTENT_REFERENCE,
+ self._nodes()[-1]["details"])
+ self.assertEqual(sum(call.args[0] == self.path
+ for call in read.call_args_list), 1)
+ self.assertEqual(sum(call.args[0] == self.path
+ for call in write.call_args_list), 1)
+ self.assertEqual(read.call_count, 2)
+ self.assertEqual(write.call_count, 2)
+
+ def test_small_relocated_payload_remains_full(self):
+ logger = self._logger()
+ minimal = {key: {} for key in self.config}
+ minimal["behavior"]["project"] = "a"
+ self._emit(logger, minimal)
+ minimal["behavior"]["project"] = "b"
+ self._emit(logger, minimal)
+ self.assertEqual(self._nodes()[-1]["details"], minimal)
+
+ def test_concurrent_relocation_references_keep_each_observed_path(self):
+ first, second = self._logger(), self._logger()
+ self._emit(first)
+ barrier = Barrier(2)
+
+ def run(logger, prefix):
+ for number in range(3):
+ data = deepcopy(self.config)
+ data["behavior"]["project"] = f"{prefix}/{number}"
+ barrier.wait(timeout=10)
+ self._emit(logger, data)
+
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ tasks = [pool.submit(run, logger, prefix)
+ for logger, prefix in ((first, "first"),
+ (second, "second"))]
+ for task in tasks:
+ task.result(timeout=30)
+ first.close()
+ second.close()
+ rows = self._nodes()
+ target = rows[0]["event"]["sequence"]
+ for node in rows[1:]:
+ self.assertEqual(node["details"][CONFIGURATION_CONTENT_REFERENCE]
+ ["sequence"], target)
+ recording = read_recording(self.root)
+ self.assertFalse(recording.issues, recording.issues)
+ for logger, paths in ((first, [str(self.root)] +
+ [f"first/{i}" for i in range(3)]),
+ (second, [f"second/{i}" for i in range(3)])):
+ actual = [event.details["behavior"]["project"]
+ for event in recording.events
+ if event.event_type == CONFIGURATION_EVENT
+ and event.metadata["trace_id"] == logger.trace_id]
+ self.assertEqual(actual, paths)
+ self._assert_recording_identity()
def test_separate_workspaces_and_conversation_traces(self):
logger = self._logger()
diff --git a/tests/kilin/test_trace_logging__semantics.py b/tests/kilin/test_trace_logging__semantics.py
new file mode 100644
index 00000000..5ed636db
--- /dev/null
+++ b/tests/kilin/test_trace_logging__semantics.py
@@ -0,0 +1,284 @@
+"""Verify shared semantic manifests without changing recorded operations."""
+
+# pylint: disable=C0115:missing-class-docstring
+# pylint: disable=C0116:missing-function-docstring
+# pylint: disable=C0103:invalid-name
+
+from concurrent.futures import ThreadPoolExecutor
+import json
+from threading import Barrier
+import unittest
+from unittest.mock import patch
+import warnings
+
+from kilin import _trace_project
+from kilin._trace_snapshots import (
+ SEMANTIC_SNAPSHOT_EVENTS, SEMANTIC_SNAPSHOT_REFERENCE,
+ SOURCE_SNAPSHOT_REFERENCE,
+)
+from kilin.system_testing.traces import read_recording
+from tests.kilin import test_trace_logging__sources as sources
+
+REFERENCE = SEMANTIC_SNAPSHOT_REFERENCE
+OBSERVED = sources.SEMANTIC
+COMMITTED = "source_organization.committed"
+RECONCILED = "source_organization.reconciled"
+APPLIED = "gui.source_organization.apply.completed"
+
+
+def semantic_details(kind, value=1):
+ """Supply exact shared state with deliberately independent outcomes."""
+
+ observed = sources.observation(OBSERVED, value)
+ if kind == OBSERVED:
+ return observed
+ return {
+ "source_organization": observed["source_organization"],
+ "revision": value,
+ "previous_revision": value - 1,
+ "sha256": "b" * 64,
+ "command_id": kind,
+ "extra": {"kind": kind, "text": "KíLín", "null": None},
+ }
+
+
+def semantic_nodes(payload):
+ """Read only semantic operation nodes in their allocation order."""
+
+ return sorted([
+ node for session in payload["sessions"].values()
+ for node in session.get("operations", {}).values()
+ if node["event"]["event_type"] in SEMANTIC_SNAPSHOT_EVENTS
+ ], key=lambda node: node["event"]["sequence"])
+
+
+class TestSemanticSnapshotRecording(unittest.TestCase):
+ """Exercise normal, concurrent and failed publications through loggers."""
+
+ def setUp(self):
+ fixture = sources.TestSourceSnapshotRecording()
+ self.addCleanup(fixture.doCleanups)
+ fixture.setUp()
+ self.fixture = fixture
+
+ def _emit(self, logger, kind, value=1, **kwargs):
+ data = semantic_details(kind, value)
+ logger.emit(kind, component="semantic_fixture", data=data, **kwargs)
+ return data
+
+ def _nodes(self):
+ return semantic_nodes(self.fixture._raw())
+
+ def _assert_decoded(self, expected):
+ before = self.fixture.path.read_bytes()
+ recording = read_recording(self.fixture.root)
+ self.assertFalse(recording.issues, recording.issues)
+ events = [event for event in recording.events
+ if event.event_type in SEMANTIC_SNAPSHOT_EVENTS]
+ self.assertEqual([event.details for event in events], expected)
+ self.assertEqual([event.metadata for event in events],
+ [node["event"] for node in self._nodes()])
+ self.assertEqual(before, self.fixture.path.read_bytes())
+ return events
+
+ def test_cross_event_reuse_preserves_opening_group_and_context(self):
+ expected = []
+ for kinds in ((OBSERVED, COMMITTED),
+ (APPLIED, RECONCILED, OBSERVED)):
+ logger = self.fixture._logger()
+ with logger.span("semantic_command", component="fixture"):
+ for kind in kinds:
+ expected.append(self._emit(logger, kind))
+ logger.close()
+ rows = self._nodes()
+ first = rows[0]
+ for row in rows[1:4]:
+ reference = row["details"][REFERENCE]
+ self.assertEqual(reference["sequence"],
+ first["event"]["sequence"])
+ self.assertNotIn("source_organization", row["details"])
+ self.assertIn("span_id", row["event"])
+ self.assertIn(SOURCE_SNAPSHOT_REFERENCE, rows[-1]["details"])
+ self.assertNotIn(REFERENCE, rows[-1]["details"])
+ events = self._assert_decoded(expected)
+ self.assertIsNot(events[0].details["source_organization"],
+ events[1].details["source_organization"])
+
+ def test_changes_and_restoration_keep_direct_latest_full_targets(self):
+ logger = self.fixture._logger()
+ expected = []
+ for value, kind in ((1, COMMITTED), (1, APPLIED),
+ (2, RECONCILED), (2, APPLIED),
+ (1, COMMITTED), (1, APPLIED)):
+ expected.append(self._emit(logger, kind, value))
+ logger.close()
+ rows = self._nodes()
+ for first, second in zip(rows[::2], rows[1::2]):
+ self.assertNotIn(REFERENCE, first["details"])
+ self.assertEqual(second["details"][REFERENCE]["sequence"],
+ first["event"]["sequence"])
+ self._assert_decoded(expected)
+
+ def test_compact_opening_never_becomes_semantic_reference_target(self):
+ logger = self.fixture._logger()
+ expected = [self._emit(logger, kind) for kind in
+ (OBSERVED, OBSERVED, COMMITTED, APPLIED)]
+ logger.close()
+ rows = self._nodes()
+ self.assertIn(SOURCE_SNAPSHOT_REFERENCE, rows[1]["details"])
+ self.assertEqual(rows[2]["details"][REFERENCE]["sequence"],
+ rows[0]["event"]["sequence"])
+ self.assertEqual(rows[3]["details"][REFERENCE]["sequence"],
+ rows[0]["event"]["sequence"])
+ self._assert_decoded(expected)
+
+ def test_manifest_types_order_and_unknown_fields_remain_significant(self):
+ logger = self.fixture._logger()
+ expected = []
+ for value in (1, 1.0, True, [1, 2], [2, 1], None, "KíLín"):
+ data = semantic_details(COMMITTED)
+ data["source_organization"]["future_field"] = value
+ logger.emit(COMMITTED, component="fixture", data=data)
+ expected.append(data)
+ self.assertEqual(self._nodes()[-1]["details"], data)
+ reordered = dict(reversed(list(data.items())))
+ reordered["source_organization"] = dict(reversed(list(
+ data["source_organization"].items())))
+ logger.emit(APPLIED, component="fixture", data=reordered)
+ expected.append(reordered)
+ self.assertIn(REFERENCE, self._nodes()[-1]["details"])
+ logger.close()
+ self._assert_decoded(expected)
+
+ def test_old_opening_reference_does_not_replace_newer_full_state(self):
+ logger = self.fixture._logger()
+ expected = [self._emit(logger, kind, value) for kind, value in (
+ (OBSERVED, 1), (COMMITTED, 2), (OBSERVED, 1), (APPLIED, 1),
+ )]
+ logger.close()
+ rows = self._nodes()
+ self.assertIn(SOURCE_SNAPSHOT_REFERENCE, rows[2]["details"])
+ self.assertNotIn(REFERENCE, rows[3]["details"])
+ self._assert_decoded(expected)
+
+ def test_failed_and_incomplete_full_states_reset_the_candidate(self):
+ logger = self.fixture._logger()
+ expected = []
+ for problem in ("failed", "missing", "null", "error", "trace_error"):
+ with self.subTest(problem=problem):
+ expected.append(self._emit(logger, COMMITTED))
+ data = semantic_details(RECONCILED)
+ status = "completed"
+ if problem == "failed":
+ status = "failed"
+ elif problem == "missing":
+ data.pop("source_organization")
+ elif problem == "null":
+ data["source_organization"] = None
+ else:
+ data[problem] = "incomplete"
+ logger.emit(RECONCILED, component="fixture", data=data,
+ status=status)
+ expected.append(data)
+ expected.append(self._emit(logger, APPLIED))
+ self.assertNotIn(REFERENCE, self._nodes()[-1]["details"])
+ logger.close()
+ self._assert_decoded(expected)
+
+ def test_tiny_turn_and_conversation_snapshots_stay_inline(self):
+ logger = self.fixture._logger()
+ tiny = {"source_organization": {}}
+ for kind in (COMMITTED, APPLIED):
+ logger.emit(kind, component="fixture", data=tiny)
+ self.assertEqual(self._nodes()[-1]["details"], tiny)
+ self._emit(logger, COMMITTED)
+ self._emit(logger, APPLIED, turn_id="turn_fixture")
+ self.assertNotIn(REFERENCE, self._nodes()[-1]["details"])
+ conversation = self.fixture._logger(
+ scope="conversation", name="conversation_a.json")
+ for kind in (COMMITTED, APPLIED):
+ self._emit(conversation, kind)
+ conversation.close()
+ payload = json.loads(conversation.readable_path.read_text("utf-8"))
+ for node in semantic_nodes(payload):
+ self.assertNotIn(REFERENCE, node["details"])
+
+ def test_compaction_adds_no_project_read_or_write(self):
+ logger = self.fixture._logger()
+ self._emit(logger, COMMITTED)
+ with (
+ patch.object(_trace_project, "_read_object",
+ wraps=_trace_project._read_object) as read,
+ patch.object(_trace_project, "atomic_write_text",
+ wraps=_trace_project.atomic_write_text) as write,
+ ):
+ self._emit(logger, APPLIED)
+ self.assertEqual(read.call_count, 2)
+ self.assertEqual(write.call_count, 2)
+ self.assertEqual(sum(call.args[0] == self.fixture.path
+ for call in read.call_args_list), 1)
+ self.assertEqual(sum(call.args[0] == self.fixture.path
+ for call in write.call_args_list), 1)
+
+ def test_concurrent_writers_preserve_every_original_payload(self):
+ first, second = self.fixture._logger(), self.fixture._logger()
+ submitted = {first.trace_id: (1, 2, 1, 1),
+ second.trace_id: (1, 1, 2, 2)}
+ barrier = Barrier(2)
+
+ def run(logger):
+ for value in submitted[logger.trace_id]:
+ barrier.wait(timeout=10)
+ self._emit(logger, APPLIED, value)
+
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ tasks = [pool.submit(run, logger) for logger in (first, second)]
+ for task in tasks:
+ task.result(timeout=30)
+ first.close()
+ second.close()
+ positions = dict.fromkeys(submitted, 0)
+ expected = []
+ for node in self._nodes():
+ trace_id = node["event"]["trace_id"]
+ value = submitted[trace_id][positions[trace_id]]
+ positions[trace_id] += 1
+ expected.append(semantic_details(APPLIED, value))
+ self.assertEqual(positions, {key: 4 for key in submitted})
+ self._assert_decoded(expected)
+
+ def test_failed_publication_preserves_history_and_releases_lease(self):
+ for policy in ("warn", "raise"):
+ with self.subTest(policy=policy):
+ logger = self.fixture._logger(policy=policy)
+ self._emit(logger, COMMITTED)
+ before = self.fixture.path.read_bytes()
+ original = _trace_project.atomic_write_text
+
+ def fail(path, content):
+ if path == self.fixture.path:
+ raise OSError("semantic publication failure")
+ original(path, content)
+
+ with patch.object(_trace_project, "atomic_write_text",
+ side_effect=fail):
+ if policy == "raise":
+ with self.assertRaisesRegex(RuntimeError,
+ "semantic publication"):
+ self._emit(logger, APPLIED)
+ else:
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ self._emit(logger, APPLIED)
+ self.assertTrue(caught)
+ self.assertEqual(before, self.fixture.path.read_bytes())
+ logger.close()
+ fresh = self.fixture._logger()
+ self._emit(fresh, APPLIED)
+ fresh.close()
+ counter = self.fixture.directory / ".sequence.json"
+ self.assertTrue(json.loads(counter.read_text())["incomplete"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/kilin/test_trace_logging__sources.py b/tests/kilin/test_trace_logging__sources.py
new file mode 100644
index 00000000..ab0dac0c
--- /dev/null
+++ b/tests/kilin/test_trace_logging__sources.py
@@ -0,0 +1,409 @@
+"""Exercise source snapshot compaction and exact historical reconstruction."""
+
+# pylint: disable=C0115:missing-class-docstring
+# pylint: disable=C0116:missing-function-docstring
+# pylint: disable=C0103:invalid-name
+
+from concurrent.futures import ThreadPoolExecutor
+from copy import deepcopy
+from hashlib import sha256
+import json
+from pathlib import Path
+import subprocess
+import sys
+from tempfile import TemporaryDirectory
+from threading import Barrier
+import unittest
+from unittest.mock import patch
+import warnings
+
+from kilin import _trace_project
+from kilin._trace_snapshots import (
+ SOURCE_SNAPSHOT_FIELDS,
+ SOURCE_SNAPSHOT_REFERENCE,
+)
+from kilin.system_testing.traces import read_recording
+from kilin.trace_logging import NullTraceLogger, TraceConfig, TraceLogger
+
+SCAN = "source.scan.completed"
+INDEX = "index.check.completed"
+SEMANTIC = "gui.source_organization.observed"
+REFERENCE = SOURCE_SNAPSHOT_REFERENCE
+
+
+def observation(kind, value=1, reason="open"):
+ """Supply large stable groups with independent operation-specific data."""
+ files = {f"source_{i}.txt": {"size_bytes": value, "sha256": "a" * 64}
+ for i in range(6)}
+ if kind == SCAN:
+ return {"repository": reason, "complete": True,
+ "selected_file_count": len(files),
+ "selected_files": list(files),
+ "entries": [{"path": name, **data}
+ for name, data in files.items()]}
+ if kind == INDEX:
+ return {"index_path": reason, "source_manifest": {"files": files},
+ "expected_metadata": {"embedding_model": "model"},
+ "saved_metadata": {"embedding_model": "model"},
+ "changes": {"matches": reason == "open"},
+ "reusable": reason == "open"}
+ return {"project": reason, "reason": reason, "revision": value,
+ "sha256": "b" * 64, "source_organization": {"files": files},
+ "selected": list(files), "pending": [], "pending_roles": [],
+ "retained_versions": [], "binding_matches": True,
+ "changed": reason != "open", "error": None}
+
+
+def observations(payload, kind=None):
+ """Locate only top-level source observation operation nodes."""
+ return sorted([
+ node for session in payload["sessions"].values()
+ for node in session.get("operations", {}).values()
+ if node["event"]["event_type"] in SOURCE_SNAPSHOT_FIELDS
+ and (kind is None or node["event"]["event_type"] == kind)
+ ], key=lambda node: node["event"]["sequence"])
+
+
+def reference_for(node):
+ """Compute the required digest independently of production helpers."""
+ fields = SOURCE_SNAPSHOT_FIELDS[node["event"]["event_type"]]
+ data = {field: node["details"][field] for field in fields}
+ encoded = json.dumps(data, sort_keys=True, separators=(",", ":"),
+ ensure_ascii=False, allow_nan=False).encode("utf-8")
+ return {"sequence": node["event"]["sequence"],
+ "sha256": sha256(encoded).hexdigest()}
+
+
+class TestSourceSnapshotRecording(unittest.TestCase):
+ """Check writer/reader equivalence without downloading model weights."""
+
+ def setUp(self):
+ temporary = TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name).resolve()
+ self.directory = self.root / "logs" / "traces"
+ self.directory.mkdir(parents=True)
+ (self.root / "profile.ini").touch()
+ self.path = self.directory / "project.json"
+
+ def _logger(self, policy="raise", scope="project", name="project.json"):
+ logger = TraceLogger(
+ TraceConfig(enabled=True, output_path=self.directory / name,
+ failure_policy=policy),
+ default_directory=self.directory, project_directory=self.root,
+ scope=scope,
+ )
+ self.addCleanup(logger.close)
+ return logger
+
+ def _emit(self, logger, kind, data, **kwargs):
+ logger.emit(kind, component="fixture", data=data, **kwargs)
+
+ def _raw(self):
+ return json.loads(self.path.read_text(encoding="utf-8"))
+
+ def _rows(self, kind=None):
+ return observations(self._raw(), kind)
+
+ def _assert_resolved(self, expected):
+ before = self.path.read_bytes()
+ recording = read_recording(self.root)
+ self.assertFalse(recording.issues, recording.issues)
+ events = [event for event in recording.events
+ if event.event_type in SOURCE_SNAPSHOT_FIELDS]
+ self.assertEqual([event.details for event in events], expected)
+ self.assertEqual([event.metadata for event in events],
+ [node["event"] for node in self._rows()])
+ self.assertEqual(before, self.path.read_bytes())
+ self.assertEqual([event.sequence for event in recording.events],
+ list(range(1, recording.last_sequence + 1)))
+ self.assertEqual(len({event.metadata["event_id"]
+ for event in recording.events}),
+ len(recording.events))
+ return events
+
+ def test_compact_groups_preserve_inline_fields_across_runs(self):
+ expected = []
+ for reason in ("open", "relocated", "resume"):
+ logger = self._logger()
+ with logger.span("gui.project.open", component="fixture"):
+ for kind in SOURCE_SNAPSHOT_FIELDS:
+ data = observation(kind, reason=reason)
+ data["extra"] = {"reason": reason, "text": "KíLín"}
+ self._emit(logger, kind, data)
+ expected.append(data)
+ logger.close()
+ for kind, fields in SOURCE_SNAPSHOT_FIELDS.items():
+ with self.subTest(kind=kind):
+ first, second, third = self._rows(kind)
+ self.assertNotIn(REFERENCE, first["details"])
+ for row, reason in ((second, "relocated"),
+ (third, "resume")):
+ expected_data = observation(kind, reason=reason)
+ expected_data["extra"] = {"reason": reason,
+ "text": "KíLín"}
+ compact = {key: value for key, value in
+ expected_data.items() if key not in fields}
+ compact[REFERENCE] = reference_for(first)
+ self.assertEqual(row["details"], compact)
+ self.assertNotEqual(row["event"]["trace_id"],
+ first["event"]["trace_id"])
+ self.assertIn("span_id", row["event"])
+ events = self._assert_resolved(expected)
+ for i, kind in enumerate(SOURCE_SNAPSHOT_FIELDS):
+ for field in SOURCE_SNAPSHOT_FIELDS[kind]:
+ value = events[i].details[field]
+ if isinstance(value, (dict, list)):
+ self.assertIsNot(value, events[i + 3].details[field])
+
+ def test_changes_restoration_and_json_order(self):
+ logger = self._logger()
+ expected = []
+ for kind in SOURCE_SNAPSHOT_FIELDS:
+ data = observation(kind)
+ changed = observation(kind, 2)
+ reordered = dict(reversed(list(data.items())))
+ for value in (data, reordered, changed, changed, data, data):
+ self._emit(logger, kind, value)
+ expected.append(value)
+ rows = self._rows(kind)
+ for full, compact in zip(rows[::2], rows[1::2]):
+ self.assertNotIn(REFERENCE, full["details"])
+ self.assertEqual(compact["details"][REFERENCE],
+ reference_for(full))
+ logger.close()
+ self._assert_resolved(expected)
+
+ def test_every_snapshot_field_affects_equality(self):
+ logger = self._logger()
+ for kind, fields in SOURCE_SNAPSHOT_FIELDS.items():
+ for field in fields:
+ with self.subTest(kind=kind, field=field):
+ full = observation(kind)
+ self._emit(logger, kind, full)
+ changed = deepcopy(full)
+ if isinstance(changed[field], list):
+ changed[field].append("new")
+ else:
+ changed[field]["new"] = True
+ self._emit(logger, kind, changed)
+ self.assertEqual(self._rows(kind)[-1]["details"], changed)
+
+ def test_array_order_and_scalar_types_remain_significant(self):
+ logger = self._logger()
+ full = observation(SCAN)
+ for field, value in (("size_bytes", 1.0), ("size_bytes", True)):
+ self._emit(logger, SCAN, full)
+ changed = deepcopy(full)
+ changed["entries"][0][field] = value
+ self._emit(logger, SCAN, changed)
+ self.assertNotIn(REFERENCE, self._rows(SCAN)[-1]["details"])
+ self._emit(logger, SCAN, full)
+ changed = deepcopy(full)
+ changed["selected_files"].reverse()
+ self._emit(logger, SCAN, changed)
+ self.assertNotIn(REFERENCE, self._rows(SCAN)[-1]["details"])
+
+ def test_failed_or_incomplete_observation_requires_new_full_target(self):
+ logger = self._logger()
+ expected = []
+ for kind in SOURCE_SNAPSHOT_FIELDS:
+ full = observation(kind)
+ incomplete = deepcopy(full)
+ if kind == SCAN:
+ incomplete["complete"] = False
+ elif kind == SEMANTIC:
+ incomplete["error"] = "inspection failed"
+ else:
+ incomplete.pop("source_manifest")
+ for data, status in ((full, "completed"),
+ (full, "failed"),
+ (full, "completed"),
+ (incomplete, "completed"),
+ (full, "completed"),
+ (full, "completed")):
+ self._emit(logger, kind, data, status=status)
+ expected.append(data)
+ rows = self._rows(kind)
+ self.assertTrue(all(REFERENCE not in row["details"]
+ for row in rows[:-1]))
+ self.assertEqual(rows[-1]["details"][REFERENCE],
+ reference_for(rows[-2]))
+ logger.close()
+ self._assert_resolved(expected)
+
+ def test_small_observation_and_unrelated_event_stay_full(self):
+ logger = self._logger()
+ scan = {"complete": True, "selected_files": [], "entries": []}
+ for _ in range(2):
+ self._emit(logger, SCAN, scan)
+ self._emit(logger, "index.empty", observation(INDEX))
+ self.assertEqual([row["details"] for row in self._rows(SCAN)],
+ [scan, scan])
+ recording = read_recording(self.root)
+ self.assertEqual([event.details for event in recording.events
+ if event.event_type == "index.empty"],
+ [observation(INDEX)] * 2)
+
+ def test_conversation_observations_are_not_compacted(self):
+ logger = self._logger()
+ self._emit(logger, SCAN, observation(SCAN))
+ conversation = self._logger(scope="conversation",
+ name="conversation_a.json")
+ for _ in range(2):
+ self._emit(conversation, SCAN, observation(SCAN))
+ conversation.close()
+ rows = observations(json.loads(
+ conversation.readable_path.read_text(encoding="utf-8")))
+ self.assertEqual([row["details"] for row in rows],
+ [observation(SCAN)] * 2)
+
+ def test_no_additional_project_read_or_write(self):
+ logger = self._logger()
+ for kind in SOURCE_SNAPSHOT_FIELDS:
+ data = observation(kind)
+ self._emit(logger, kind, data)
+ with (
+ patch.object(_trace_project, "_read_object",
+ wraps=_trace_project._read_object) as read,
+ patch.object(_trace_project, "atomic_write_text",
+ wraps=_trace_project.atomic_write_text) as write,
+ ):
+ self._emit(logger, kind, data)
+ self.assertEqual(sum(call.args[0] == self.path
+ for call in read.call_args_list), 1)
+ self.assertEqual(sum(call.args[0] == self.path
+ for call in write.call_args_list), 1)
+ self.assertEqual(read.call_count, 2)
+ self.assertEqual(write.call_count, 2)
+
+ def test_disabled_trace_does_not_read_or_write(self):
+ with (
+ patch.object(_trace_project, "_read_object") as read,
+ patch.object(_trace_project, "atomic_write_text") as write,
+ ):
+ self._emit(NullTraceLogger(), SCAN, observation(SCAN))
+ read.assert_not_called()
+ write.assert_not_called()
+
+ def _assert_concurrent_history(self, submitted):
+ """Verify each persisted target in true allocation order."""
+ latest = None
+ positions = dict.fromkeys(submitted, 0)
+ expected = []
+ for node in self._rows(SCAN):
+ trace_id = node["event"]["trace_id"]
+ value = submitted[trace_id][positions[trace_id]]
+ positions[trace_id] += 1
+ data = observation(SCAN, value)
+ expected.append(data)
+ if latest is not None and latest[0] == value:
+ self.assertEqual(node["details"][REFERENCE],
+ reference_for(latest[1]))
+ else:
+ self.assertEqual(node["details"], data)
+ latest = (value, node)
+ self.assertEqual(positions, {key: len(values)
+ for key, values in submitted.items()})
+ self._assert_resolved(expected)
+
+ def test_concurrent_threads(self):
+ first, second = self._logger(), self._logger()
+ submitted = {first.trace_id: (1, 2, 1, 1),
+ second.trace_id: (1, 1, 2, 2)}
+ barrier = Barrier(2)
+
+ def run(logger):
+ for value in submitted[logger.trace_id]:
+ barrier.wait(timeout=10)
+ self._emit(logger, SCAN, observation(SCAN, value))
+
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ tasks = [pool.submit(run, logger) for logger in (first, second)]
+ for task in tasks:
+ task.result(timeout=30)
+ first.close()
+ second.close()
+ self._assert_concurrent_history(submitted)
+
+ def test_independent_processes(self):
+ code = """
+import json, sys
+from pathlib import Path
+from kilin.trace_logging import TraceConfig, TraceLogger
+from tests.kilin.test_trace_logging__sources import observation, SCAN
+root = Path(sys.argv[1])
+path = root / 'logs' / 'traces' / 'project.json'
+logger = TraceLogger(TraceConfig(enabled=True, output_path=path,
+ failure_policy='raise'),
+ default_directory=path.parent, project_directory=root,
+ scope='project')
+try:
+ for value in json.loads(sys.argv[2]):
+ logger.emit(SCAN, component='fixture', data=observation(SCAN, value))
+finally:
+ logger.close()
+print(logger.trace_id)
+"""
+ processes = []
+ submitted = {}
+ try:
+ for values in ((1, 1, 2, 1), (1, 2, 2, 1)):
+ process = subprocess.Popen(
+ [sys.executable, "-c", code, str(self.root),
+ json.dumps(values)], stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, text=True,
+ )
+ processes.append((process, values))
+ for process, values in processes:
+ stdout, stderr = process.communicate(timeout=45)
+ self.assertEqual(process.returncode, 0, stderr)
+ submitted[stdout.strip()] = values
+ finally:
+ for process, _ in processes:
+ if process.poll() is None:
+ process.kill()
+ process.communicate()
+ self._assert_concurrent_history(submitted)
+
+ def test_publication_failure_preserves_old_events_and_releases_lease(self):
+ for policy in ("warn", "raise"):
+ with self.subTest(policy=policy):
+ logger = self._logger(policy=policy)
+ data = observation(SCAN)
+ self._emit(logger, SCAN, data)
+ before = self.path.read_bytes()
+ counter = self.directory / ".sequence.json"
+ high = json.loads(counter.read_text("utf-8"))["last_sequence"]
+ original = _trace_project.atomic_write_text
+
+ def fail(path, content):
+ if path == self.path:
+ raise OSError("publication failure")
+ original(path, content)
+
+ with patch.object(_trace_project, "atomic_write_text",
+ side_effect=fail):
+ if policy == "raise":
+ with self.assertRaisesRegex(RuntimeError,
+ "publication failure"):
+ self._emit(logger, SCAN, data)
+ else:
+ with warnings.catch_warnings(record=True) as seen:
+ warnings.simplefilter("always", RuntimeWarning)
+ self._emit(logger, SCAN, data)
+ self.assertTrue(any("publication failure" in
+ str(w.message) for w in seen))
+ self.assertEqual(self.path.read_bytes(), before)
+ state = json.loads(counter.read_text("utf-8"))
+ self.assertTrue(state["incomplete"])
+ self.assertEqual(state["last_sequence"], high + 1)
+ logger.close()
+ next_logger = self._logger()
+ self._emit(next_logger, SCAN, data)
+ next_logger.close()
+ self.assertIn(REFERENCE, self._rows(SCAN)[-1]["details"])
+
+
+if __name__ == "__main__":
+ unittest.main()
From ecb1e1d3258400b98eecd1b9e437c2761b8c63bb Mon Sep 17 00:00:00 2001
From: Giovanni Volpe
Date: Wed, 2 Dec 2026 13:14:08 +0100
Subject: [PATCH 2/9] Update test_analysis__traces.py
---
tests/kilin/system_testing/test_analysis__traces.py | 12 ++++++++----
1 file changed, 8 insertions(+), 4 deletions(-)
diff --git a/tests/kilin/system_testing/test_analysis__traces.py b/tests/kilin/system_testing/test_analysis__traces.py
index e43ac606..edf4aea5 100644
--- a/tests/kilin/system_testing/test_analysis__traces.py
+++ b/tests/kilin/system_testing/test_analysis__traces.py
@@ -215,8 +215,10 @@ def test_nonhierarchy_event_traps_are_not_semantic_events(self):
self.assertEqual(local["events"], [])
def test_malformed_trace_errors_are_not_silently_discarded(self):
- invalid = self.path.parent / ".json"
- invalid.write_text('{"duplicate": 1, "duplicate": 2}', "utf-8")
+ # Use a portable filename while exercising HTML escaping of both
+ # the path and the JSON decoder's error message.
+ invalid = self.path.parent / "broken&trace.json"
+ invalid.write_text('{"": 1, "": 2}', "utf-8")
local = analysis._local_events(self.root, {sources.SCAN})
self.assertEqual(len(local["events"]), 2)
self.assertTrue(any("trace.invalid" in error
@@ -230,8 +232,10 @@ def test_malformed_trace_errors_are_not_silently_discarded(self):
html = analysis.event_inventory_html(data, original=self.root,
include_details=True)
self.assertIn("trace.invalid", html)
- self.assertIn("<broken>.json", html)
- self.assertNotIn(".json", html)
+ self.assertIn("broken&trace.json", html)
+ self.assertNotIn("broken&trace.json", html)
+ self.assertIn("<duplicate>", html)
+ self.assertNotIn("", html)
self.assertEqual(data, before)
def test_linked_root_or_trace_is_rejected_with_visible_issue(self):
From 76b2acc7e8ffca6d02871e63d54e778a79140e82 Mon Sep 17 00:00:00 2001
From: Giovanni Volpe
Date: Wed, 2 Dec 2026 14:28:18 +0100
Subject: [PATCH 3/9] Canonical trace representation
Canonicalize trace representations and remove legacy artifact handling
- Consolidate configuration references into a single content-based representation, preserving the observed project path.
- Retain exact snapshot reconstruction, digest verification, and chronological reference validation.
- Remove obsolete configuration-reference decoding and external file-artifact resolution.
- Remove the historical fixed forensic-mode marker from newly recorded traces.
- Update trace readers, documentation, and regression tests to enforce the canonical representation.
---
docs/trace_architecture.md | 55 ++++-------
docs/trace_recording.md | 12 ++-
kilin/_trace_configuration.py | 97 +++----------------
kilin/_trace_project.py | 19 ++--
kilin/system_testing/traces.py | 11 ++-
kilin/trace_logging.py | 31 ++----
.../system_testing/test_analysis__traces.py | 4 +-
.../test_traces__configuration.py | 52 +++++++---
tests/kilin/test__trace_configuration.py | 24 +++--
tests/kilin/test_trace_logging.py | 91 ++++++++++-------
.../test_trace_logging__configuration.py | 37 ++++---
11 files changed, 193 insertions(+), 240 deletions(-)
diff --git a/docs/trace_architecture.md b/docs/trace_architecture.md
index 3bfc7fd2..26412c9f 100644
--- a/docs/trace_architecture.md
+++ b/docs/trace_architecture.md
@@ -184,25 +184,9 @@ A failed diagnostic snapshot is recorded explicitly. Subsequent saved profile,
model, tool, behavior and card settings changes are traced in the project.
Each activation retains its own configuration event and global sequence
-number. The first complete configuration retains all seven settings groups.
-An unchanged configuration records a direct reference to the most recent
-complete observation:
-
-```json
-{
- "configuration_reference": {
- "sequence": 124,
- "sha256": "<64 lowercase hexadecimal characters>"
- }
-}
-```
-
-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 complete-payload digest includes the historical workspace path in
-`behavior.project`. When only that path changes, a distinct reference shares
-all other configuration content and retains the exact current path inline:
+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
{
@@ -214,20 +198,22 @@ all other configuration content and retains the exact current path inline:
}
```
-This digest uses the same encoding with only `behavior.project` removed.
-Inspection restores that field from `project`, without normalizing its
-spelling or consulting the current filesystem. An explicit null path is
-preserved; an absent path is ineligible for this representation. All other
-behavior values, unknown fields, scalar types and list ordering still affect
-equality. A relocation reference is written only when it is smaller than the
-full payload. Both reference fields are reserved and cannot be mixed with
-each other or full settings groups.
+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. Both kinds of
-reference point directly to the latest full snapshot; they never form chains
-or skip newer full snapshots. Ordinary exact references remain available when
-the complete payload, including the historical path, matches that snapshot.
+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
@@ -245,9 +231,10 @@ copies of the complete payload to validation, timeline reconstruction, replay
and comparison. Publication receipts fingerprint these decoded payloads, so a
full configuration and its compact representation have the same trace-prefix
digest. Invalid references are blocking recording issues. Original
-files are not rewritten. 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.
+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
diff --git a/docs/trace_recording.md b/docs/trace_recording.md
index bb91032b..4a228701 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
diff --git a/kilin/_trace_configuration.py b/kilin/_trace_configuration.py
index daaf7ca8..0b566665 100644
--- a/kilin/_trace_configuration.py
+++ b/kilin/_trace_configuration.py
@@ -3,30 +3,29 @@
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.
-Relocation references retain the exact current project path inline while
-sharing all other configuration content with the latest complete snapshot.
+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.
-- Separate path-preserving references for otherwise identical settings.
+- 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`` and ``configuration_content_bytes`` encode complete
- snapshots and their path-independent content for comparison.
-- ``configuration_reference`` and ``configuration_content_reference``
- construct compact references without changing the observed configuration.
+- ``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
"""
@@ -39,17 +38,13 @@
__all__ = [
"CONFIGURATION_EVENT",
- "CONFIGURATION_REFERENCE",
"CONFIGURATION_CONTENT_REFERENCE",
- "configuration_bytes",
"configuration_content_bytes",
- "configuration_reference",
"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",
@@ -57,38 +52,6 @@
})
-def configuration_bytes(configuration: Mapping[str, object]) -> bytes:
- """Encode a complete JSON-ready configuration for exact comparison.
-
- Parameters
- ----------
- configuration: mapping of str to object
- Complete effective configuration, already converted to trace JSON
- values. Extra fields are retained and included in equality.
-
- Returns
- -------
- bytes
- UTF-8 JSON with ordered object keys and compact separators. List
- ordering and JSON scalar representations remain significant.
-
- Raises
- ------
- ValueError
- If required fields are missing, the payload is a reference, or a
- nonfinite number cannot be represented in standard JSON.
- TypeError
- If a value cannot be serialized as JSON.
-
- """
-
- if (CONFIGURATION_REFERENCE in configuration
- or CONFIGURATION_CONTENT_REFERENCE in configuration
- or not _CONFIGURATION_FIELDS <= configuration.keys()):
- raise ValueError("Expected a complete effective configuration.")
- return snapshot_bytes(configuration)
-
-
def configuration_content_bytes(configuration: Mapping[str, object]) -> bytes:
"""Encode every configuration value except the observed project path.
@@ -113,8 +76,7 @@ def configuration_content_bytes(configuration: Mapping[str, object]) -> bytes:
"""
behavior = configuration.get("behavior")
- if (CONFIGURATION_REFERENCE in configuration
- or CONFIGURATION_CONTENT_REFERENCE in configuration
+ 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.")
@@ -124,26 +86,6 @@ def configuration_content_bytes(configuration: Mapping[str, object]) -> bytes:
return snapshot_bytes(content)
-def configuration_reference(sequence: int, encoded: bytes) -> dict:
- """Construct the compact payload for an already published snapshot.
-
- Parameters
- ----------
- sequence: int
- Project-wide sequence number of the complete snapshot.
- encoded: bytes
- Canonical JSON of the complete snapshot.
-
- Returns
- -------
- dict
- Reference containing the sequence number and lowercase SHA-256 digest.
-
- """
-
- return snapshot_reference(CONFIGURATION_REFERENCE, sequence, encoded)
-
-
def configuration_content_reference(
sequence: int, encoded: bytes, project: object,
) -> dict:
@@ -201,12 +143,9 @@ def resolve_configuration_reference(
"""
- content_reference = CONFIGURATION_CONTENT_REFERENCE in details
- key = (CONFIGURATION_CONTENT_REFERENCE if content_reference
- else CONFIGURATION_REFERENCE)
- fields = {key, "project"} if content_reference else {key}
+ key = CONFIGURATION_CONTENT_REFERENCE
reference = details.get(key)
- if (set(details) != fields
+ if (set(details) != {key, "project"}
or not isinstance(reference, dict)
or set(reference) != {"sequence", "sha256"}
or type(reference["sequence"]) is not int
@@ -217,13 +156,9 @@ def resolve_configuration_reference(
raise ValueError(
"Configuration reference does not identify the latest snapshot."
)
- if content_reference:
- encoded = configuration_content_bytes(latest[1])
- else:
- encoded = configuration_bytes(latest[1])
+ encoded = configuration_content_bytes(latest[1])
if reference != snapshot_reference(key, latest[0], encoded)[key]:
raise ValueError("Project configuration reference digest mismatch.")
resolved = deepcopy(latest[1])
- if content_reference:
- resolved["behavior"]["project"] = deepcopy(details["project"])
+ resolved["behavior"]["project"] = deepcopy(details["project"])
return resolved
diff --git a/kilin/_trace_project.py b/kilin/_trace_project.py
index 785f3e64..d0754b56 100644
--- a/kilin/_trace_project.py
+++ b/kilin/_trace_project.py
@@ -67,11 +67,8 @@
from kilin._trace_configuration import (
CONFIGURATION_CONTENT_REFERENCE,
CONFIGURATION_EVENT,
- CONFIGURATION_REFERENCE,
- configuration_bytes,
configuration_content_bytes,
configuration_content_reference,
- configuration_reference,
)
from kilin._trace_snapshots import (
SEMANTIC_SNAPSHOT_EVENTS, SEMANTIC_SNAPSHOT_REFERENCE,
@@ -420,9 +417,9 @@ def compact_project_configuration(
-------
dict
Original full configuration or a direct reference to the latest
- equal full configuration. When only the path differs, share all other
- content while preserving the exact current path inline. 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
-----
@@ -459,22 +456,20 @@ def compact_project_configuration(
or "turn_id" in event):
return configuration
seen.add(number)
- if (CONFIGURATION_REFERENCE in details
- or CONFIGURATION_CONTENT_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(encoded):
+ if len(snapshot_bytes(compact)) < len(
+ snapshot_bytes(configuration)
+ ):
return compact
except (ValueError, TypeError, RecursionError):
# Keep full evidence rather than guessing when a configuration
diff --git a/kilin/system_testing/traces.py b/kilin/system_testing/traces.py
index 0a30cf68..73743e70 100644
--- a/kilin/system_testing/traces.py
+++ b/kilin/system_testing/traces.py
@@ -33,7 +33,7 @@
from kilin._trace_configuration import (
CONFIGURATION_CONTENT_REFERENCE,
CONFIGURATION_EVENT,
- CONFIGURATION_REFERENCE,
+ configuration_content_bytes,
resolve_configuration_reference,
)
from kilin._trace_project import TRACE_FORMAT_VERSION
@@ -503,7 +503,7 @@ def _resolve_configurations(recording: Recording) -> None:
Notes
-----
Track the most recent full project configuration, not the most recent
- reference. Legacy full observations pass through unchanged. A reference
+ reference. Complete full observations pass through unchanged. A reference
must belong to the same project trace and cannot target a later event,
a different event type, an earlier superseded snapshot, or another
reference.
@@ -512,8 +512,7 @@ def _resolve_configurations(recording: Recording) -> None:
latest = None
for index, event in enumerate(recording.events):
- compact = (CONFIGURATION_REFERENCE in event.details
- or CONFIGURATION_CONTENT_REFERENCE in event.details)
+ compact = CONFIGURATION_CONTENT_REFERENCE in event.details
if event.event_type != CONFIGURATION_EVENT:
if compact:
recording.issue(
@@ -535,6 +534,10 @@ def _resolve_configurations(recording: Recording) -> None:
if (not duplicate
and event.metadata.get("status") == "completed"
and "turn_id" not in event.metadata):
+ # An invalid full observation (including obsolete
+ # compact payloads) cannot supply historical state.
+ latest = None
+ configuration_content_bytes(event.details)
latest = (event.sequence, event.details)
else:
latest = None
diff --git a/kilin/trace_logging.py b/kilin/trace_logging.py
index fe276408..5c2cf305 100644
--- a/kilin/trace_logging.py
+++ b/kilin/trace_logging.py
@@ -564,8 +564,6 @@ def __init__(
"trace.started",
component="trace",
data={
- # Historical fixed marker, not a configurable setting.
- "mode": "forensic",
"scope": self.scope,
"output_path": str(self.output_path),
"include_embedding_vectors": (
@@ -1421,45 +1419,28 @@ def _readable_event(
return readable
def _artifact_content(self, reference: object) -> object:
- """Resolve an inline or supported legacy file artifact.
+ """Return exact inline content without reading artifact files.
Parameters
----------
reference: object
- Inline artifact reference, or a legacy artifact-file reference
- constrained to the output directory.
+ Inline artifact payload produced by ``artifact()``.
Returns
-------
object
- Artifact content, or None for an unsupported, missing, unreadable,
- or invalid legacy reference.
+ Inline content, or None when no inline content is available.
Notes
-----
- Inline content takes precedence. Legacy paths must resolve inside the
- trace output directory. This is a compatibility read, not arbitrary
- remote artifact retrieval.
+ Path-only payloads are not exact artifacts in the current format.
+ Never consult the filesystem to reconstruct historical content.
"""
if not isinstance(reference, Mapping):
return None
- if "inline_content" in reference:
- return reference["inline_content"]
- relative = reference.get("path")
- if not isinstance(relative, str):
- return None
- try:
- root = self.output_path.parent.resolve()
- path = (root / relative).resolve(strict=True)
- if not path.is_relative_to(root) or not path.is_file():
- return None
- if reference.get("format") == "json":
- return json.loads(path.read_text(encoding="utf-8"))
- return path.read_text(encoding="utf-8")
- except (OSError, ValueError, json.JSONDecodeError):
- return None
+ return reference.get("inline_content")
def _handle_io_failure(self, error: OSError) -> None:
"""Apply the configured policy after trace storage fails.
diff --git a/tests/kilin/system_testing/test_analysis__traces.py b/tests/kilin/system_testing/test_analysis__traces.py
index edf4aea5..af1b47c6 100644
--- a/tests/kilin/system_testing/test_analysis__traces.py
+++ b/tests/kilin/system_testing/test_analysis__traces.py
@@ -11,7 +11,7 @@
from unittest.mock import patch
from kilin._trace_configuration import (
- CONFIGURATION_EVENT, CONFIGURATION_REFERENCE,
+ CONFIGURATION_EVENT, CONFIGURATION_CONTENT_REFERENCE,
)
from kilin.system_testing import analysis
from kilin.system_testing.traces import read_recording
@@ -106,7 +106,7 @@ def test_partial_decoding_is_not_labelled_as_raw_or_verified(self):
node = sources.observations(payload, sources.SCAN)[-1]
# Configuration validation rejects this reserved marker on a scan;
# the independent source decoder can still resolve the valid group.
- node["details"][CONFIGURATION_REFERENCE] = {
+ node["details"][CONFIGURATION_CONTENT_REFERENCE] = {
"sequence": 1, "sha256": "0" * 64,
}
self._write(payload)
diff --git a/tests/kilin/system_testing/test_traces__configuration.py b/tests/kilin/system_testing/test_traces__configuration.py
index 8897af69..d2f0a520 100644
--- a/tests/kilin/system_testing/test_traces__configuration.py
+++ b/tests/kilin/system_testing/test_traces__configuration.py
@@ -5,6 +5,7 @@
# pylint: disable=C0103:invalid-name
from copy import deepcopy
+from hashlib import sha256
import json
import os
from pathlib import Path
@@ -16,12 +17,10 @@
from kilin._trace_configuration import (
CONFIGURATION_CONTENT_REFERENCE,
CONFIGURATION_EVENT,
- CONFIGURATION_REFERENCE,
- configuration_bytes,
configuration_content_bytes,
configuration_content_reference,
- configuration_reference,
)
+from kilin._trace_snapshots import snapshot_bytes
from kilin.gui.engine import ChatEngine
from kilin.gui.preferences import DEFAULTS_ENVIRONMENT
from kilin.system_testing import Experiment, InvalidRecordingError
@@ -123,13 +122,14 @@ def _raw(self):
def _write(self, payload):
self.path.write_text(json.dumps(payload, ensure_ascii=False), "utf-8")
- def test_compact_and_legacy_full_observations_are_equivalent(self):
+ def test_compact_and_full_observations_are_equivalent(self):
payload = self._raw()
nodes = _nodes(payload)
self.assertEqual(len(nodes), 3)
full = nodes[0]["details"]
- expected = configuration_reference(
- nodes[0]["event"]["sequence"], configuration_bytes(full)
+ expected = configuration_content_reference(
+ nodes[0]["event"]["sequence"],
+ configuration_content_bytes(full), full["behavior"]["project"],
)
self.assertEqual([node["details"] for node in nodes[1:]],
[expected, expected])
@@ -148,11 +148,11 @@ def test_compact_and_legacy_full_observations_are_equivalent(self):
for node in nodes[1:]:
node["details"] = deepcopy(full)
self._write(payload)
- legacy_before = _snapshot(self.workspace)
- legacy = self.experiment.validate()
- self.assertTrue(legacy.valid, legacy.issues)
- self.assertEqual(report, legacy)
- self.assertEqual(legacy_before, _snapshot(self.workspace))
+ full_before = _snapshot(self.workspace)
+ expanded = self.experiment.validate()
+ self.assertTrue(expanded.valid, expanded.issues)
+ self.assertEqual(report, expanded)
+ self.assertEqual(full_before, _snapshot(self.workspace))
def test_workspace_replay_preserves_openings(self):
before = _snapshot(self.workspace)
@@ -278,7 +278,7 @@ def test_corrupted_references_block_validation_and_replay(self):
with self.subTest(case=case):
payload = deepcopy(original)
first, second, third = _nodes(payload)
- reference = third["details"][CONFIGURATION_REFERENCE]
+ reference = third["details"][CONFIGURATION_CONTENT_REFERENCE]
if case == "missing":
reference["sequence"] = 0
elif case == "forward":
@@ -294,7 +294,9 @@ def test_corrupted_references_block_validation_and_replay(self):
elif case == "bool":
reference["sequence"] = True
elif case == "wrong_type":
- third["details"][CONFIGURATION_REFERENCE] = "invalid"
+ third["details"][CONFIGURATION_CONTENT_REFERENCE] = (
+ "invalid"
+ )
elif case == "wrong_event":
reference["sequence"] = first["event"]["sequence"] - 1
elif case == "superseded":
@@ -326,12 +328,30 @@ def test_corrupted_references_block_validation_and_replay(self):
self.assertFalse(self.target.exists())
self.assertEqual(before, _snapshot(self.workspace))
+ def test_obsolete_reference_blocks_validation_and_replay(self):
+ payload = self._raw()
+ first, second, _ = _nodes(payload)
+ second["details"] = {"configuration_reference": {
+ "sequence": first["event"]["sequence"],
+ "sha256": sha256(snapshot_bytes(first["details"])).hexdigest(),
+ }}
+ self._write(payload)
+ before = _snapshot(self.workspace)
+ report = self.experiment.validate()
+ self.assertFalse(report.valid)
+ self.assertIn("configuration.reference",
+ {issue.code for issue in report.issues})
+ with self.assertRaises(InvalidRecordingError):
+ self.experiment.replay(self.target)
+ self.assertFalse(self.target.exists())
+ self.assertEqual(before, _snapshot(self.workspace))
+
def test_missing_target_does_not_use_current_settings(self):
payload = self._raw()
first, _, _ = _nodes(payload)
- first["details"] = {CONFIGURATION_REFERENCE: {
+ first["details"] = {CONFIGURATION_CONTENT_REFERENCE: {
"sequence": 1, "sha256": "0" * 64,
- }}
+ }, "project": str(self.workspace)}
self._write(payload)
recording = read_recording(self.workspace)
self.assertEqual(sum(issue.code == "configuration.reference"
@@ -446,7 +466,7 @@ def test_relocated_reference_corruption_is_blocking(self):
elif case == "missing_path":
third["details"].pop("project")
elif case == "mixed_references":
- third["details"][CONFIGURATION_REFERENCE] = reference
+ third["details"]["configuration_reference"] = reference
self.path.write_text(json.dumps(payload), encoding="utf-8")
before = self.path.read_bytes()
recording = read_recording(self.fixture.root)
diff --git a/tests/kilin/test__trace_configuration.py b/tests/kilin/test__trace_configuration.py
index 0b69e3c8..10f01ee7 100644
--- a/tests/kilin/test__trace_configuration.py
+++ b/tests/kilin/test__trace_configuration.py
@@ -10,11 +10,11 @@
from kilin._trace_configuration import (
CONFIGURATION_CONTENT_REFERENCE,
- configuration_bytes,
configuration_content_bytes,
configuration_content_reference,
resolve_configuration_reference,
)
+from kilin._trace_snapshots import snapshot_bytes
from tests.kilin.test_trace_logging__configuration import _configuration
@@ -32,8 +32,8 @@ def test_only_behavior_project_is_excluded(self):
moved = deepcopy(original)
moved["behavior"]["project"] = "../KíLín new"
self.assertEqual(encoded, configuration_content_bytes(moved))
- self.assertNotEqual(configuration_bytes(original),
- configuration_bytes(moved))
+ self.assertNotEqual(snapshot_bytes(original),
+ snapshot_bytes(moved))
moved["extra"]["project"] = "changed"
self.assertNotEqual(encoded, configuration_content_bytes(moved))
self.assertEqual(original, before)
@@ -52,8 +52,8 @@ def test_current_path_value_and_json_types_round_trip(self):
(2, full))
expected = deepcopy(full)
expected["behavior"]["project"] = project
- self.assertEqual(configuration_bytes(result),
- configuration_bytes(expected))
+ self.assertEqual(snapshot_bytes(result),
+ snapshot_bytes(expected))
self.assertIsNot(result["behavior"], full["behavior"])
if isinstance(project, dict):
self.assertIsNot(reference["project"], project)
@@ -61,6 +61,16 @@ def test_current_path_value_and_json_types_round_trip(self):
reference["project"])
self.assertEqual(full, before)
+ def test_obsolete_reference_cannot_be_resolved(self):
+ full = _configuration("original")
+ reference = {"configuration_reference": {
+ "sequence": 1, "sha256": "0" * 64,
+ }}
+ with self.assertRaises(ValueError):
+ resolve_configuration_reference(reference, 2, (1, full))
+ with self.assertRaises(ValueError):
+ configuration_content_bytes(reference)
+
def test_missing_or_incomplete_content_is_rejected(self):
full = _configuration("original")
missing = deepcopy(full)
@@ -77,10 +87,6 @@ def test_missing_or_incomplete_content_is_rejected(self):
with self.subTest(data=data):
with self.assertRaises(ValueError):
configuration_content_bytes(data)
- for data in (compact, mixed):
- with self.subTest(data=data):
- with self.assertRaises(ValueError):
- configuration_bytes(data)
self.assertEqual(set(compact),
{CONFIGURATION_CONTENT_REFERENCE, "project"})
diff --git a/tests/kilin/test_trace_logging.py b/tests/kilin/test_trace_logging.py
index 849f80f3..7d065644 100644
--- a/tests/kilin/test_trace_logging.py
+++ b/tests/kilin/test_trace_logging.py
@@ -190,10 +190,8 @@ def test_startup_and_close_have_one_ordered_lifecycle(self) -> None:
[1, 3],
)
self.assertEqual(runtime["01_custom_ready"]["event"]["sequence"], 2)
- self.assertEqual(
- trace_events["01_trace_started"]["details"]["mode"],
- "forensic",
- )
+ self.assertNotIn("mode",
+ trace_events["01_trace_started"]["details"])
def test_event_validation_precedes_mutation(self) -> None:
"""Reject blank names without consuming sequence numbers."""
@@ -497,7 +495,7 @@ def test_explicit_parent_and_exception_event(self) -> None:
class TestTraceArtifacts(unittest.TestCase):
- """Check inline content, conversion, and controlled legacy resolution."""
+ """Check inline content, conversion, and unsupported file payloads."""
def setUp(self) -> None:
"""Initialize full diagnostic tracing in a disposable directory."""
@@ -589,35 +587,32 @@ class Sample:
with self.assertRaises(ValueError):
self.logger.artifact("...", 12)
- def test_legacy_artifact_stays_inside_output_directory(self) -> None:
- """Reject traversal and accept readable old local artifact files."""
+ def test_path_only_artifacts_are_not_read(self) -> None:
+ """Ignore path-only payloads without consulting the filesystem."""
(self.root / "payload.json").write_text(
'[1, 2]', encoding="utf-8"
)
outside = self.root.parent / "outside.json"
- with patch.object(
- self.logger, "_artifact_content",
- wraps=self.logger._artifact_content,
- ) as content:
- self.assertEqual(content({
- "path": "payload.json", "format": "json"
- }), [1, 2])
- self.assertIsNone(content({
- "path": "../outside.json", "format": "json"
- }))
- self.assertIsNone(content({
- "path": str(outside), "format": "json"
- }))
- self.assertIsNone(content({"path": "missing.json"}))
- self.assertEqual(content({
+ with patch.object(Path, "read_text") as read:
+ for reference in (
+ {"path": "payload.json", "format": "json"},
+ {"path": "../outside.json", "format": "json"},
+ {"path": str(outside), "format": "json"},
+ {"path": "missing.json"},
+ ):
+ with self.subTest(reference=reference):
+ self.assertIsNone(self.logger._artifact_content(
+ reference
+ ))
+ self.assertEqual(self.logger._artifact_content({
"inline_content": "preferred", "path": "missing.json"
}), "preferred")
+ read.assert_not_called()
-
- def test_legacy_symlink_artifact_cannot_escape_trace_directory(
+ def test_linked_artifact_is_not_read(
self,
) -> None:
- """Reject an in-directory link pointing outside the trace tree."""
+ """Do not load content through a path to a symbolic link."""
with TemporaryDirectory() as other_directory:
outside = Path(other_directory) / "secret.json"
outside.write_text('["private"]', encoding="utf-8")
@@ -631,23 +626,41 @@ def test_legacy_symlink_artifact_cannot_escape_trace_directory(
}))
+ def test_file_reference_is_not_projected_as_exact_content(self) -> None:
+ """Keep unsupported payloads without inventing exact artifacts."""
+ artifact = self.root / "prompt.txt"
+ artifact.write_text("unrecorded prompt", encoding="utf-8")
+ reference = {"path": artifact.name, "format": "text"}
+ with patch.object(Path, "read_text") as read:
+ self.logger.emit(
+ TRACE_EVENT_LLM_CALL_INPUT, component="chat",
+ data={"rendered_prompt_artifact": reference},
+ )
+ read.assert_not_called()
+ operations = _operations(_payload(self.path), "runtime")
+ inputs = operations["01_llm_call_input"]
+ self.assertNotIn("exact_content", inputs)
+ self.assertEqual(inputs["details"]["rendered_prompt_artifact"],
+ reference)
+ self.assertEqual(artifact.read_text(encoding="utf-8"),
+ "unrecorded prompt")
+
def test_artifact_is_unavailable_after_logger_closes(self) -> None:
"""Avoid producing untracked content after the trace is closed."""
self.assertIsNotNone(self.logger.artifact("before", "content"))
self.logger.close()
self.assertIsNone(self.logger.artifact("after", "content"))
- def test_legacy_text_and_invalid_json_artifacts(self) -> None:
- """Read legacy text files while ignoring malformed JSON assets."""
+ def test_file_artifact_types_are_ignored(self) -> None:
+ """Ignore file artifacts regardless of content or declared format."""
(self.root / "output.txt").write_text(
"legacy text", encoding="utf-8"
)
(self.root / "broken.json").write_text(
"not json", encoding="utf-8"
)
- self.assertEqual(
- self.logger._artifact_content({"path": "output.txt"}),
- "legacy text",
+ self.assertIsNone(
+ self.logger._artifact_content({"path": "output.txt"})
)
self.assertIsNone(self.logger._artifact_content({
"path": "broken.json", "format": "json"
@@ -740,16 +753,16 @@ def test_reopen_appends_new_readable_turns_and_retains_state(self) -> None:
)
self.assertEqual(payload["event_count"], 3)
- def test_legacy_standard_trace_remains_readable_and_complete(
+ def test_reopen_preserves_prior_metadata_without_emitting_mode(
self,
) -> None:
- """Retain legacy mode metadata without filtering later events."""
+ """Keep prior event metadata without emitting obsolete modes."""
first = self._open()
first.emit("custom.earlier", component="test")
first.close()
prior = _payload(self.path)
- legacy_start = _operations(prior, "trace")["01_trace_started"]
- legacy_start["details"]["mode"] = "standard"
+ earlier_start = _operations(prior, "trace")["01_trace_started"]
+ earlier_start["details"]["mode"] = "standard"
self.path.write_text(json.dumps(prior), encoding="utf-8")
later = self._open()
@@ -761,10 +774,14 @@ def test_legacy_standard_trace_remains_readable_and_complete(
later.close()
updated = _payload(self.path)
self.assertEqual(
- _operations(updated, "trace")["01_trace_started"]["details"]
- ["mode"],
- "standard",
+ _operations(updated, "trace")["01_trace_started"], earlier_start
)
+ starts = [node for session in updated["sessions"].values()
+ for node in session.get("operations", {}).values()
+ if (node["event"]["event_type"] == "trace.started"
+ and node["event"]["trace_id"] == later.trace_id)]
+ self.assertEqual(len(starts), 1)
+ self.assertNotIn("mode", starts[0]["details"])
self.assertIn("custom_earlier", self.path.read_text(encoding="utf-8"))
self.assertIn(
"llm_call_output_tokens", self.path.read_text(encoding="utf-8")
diff --git a/tests/kilin/test_trace_logging__configuration.py b/tests/kilin/test_trace_logging__configuration.py
index f5a1b031..84134615 100644
--- a/tests/kilin/test_trace_logging__configuration.py
+++ b/tests/kilin/test_trace_logging__configuration.py
@@ -20,11 +20,8 @@
from kilin._trace_configuration import (
CONFIGURATION_CONTENT_REFERENCE,
CONFIGURATION_EVENT,
- CONFIGURATION_REFERENCE,
- configuration_bytes,
configuration_content_bytes,
configuration_content_reference,
- configuration_reference,
)
from kilin.system_testing.traces import read_recording
from kilin.trace_logging import NullTraceLogger, TraceConfig, TraceLogger
@@ -121,9 +118,10 @@ def test_change_and_restore_across_logger_runs(self):
):
self.assertEqual(rows[full]["details"], expected)
self.assertEqual(rows[reference]["details"],
- configuration_reference(
+ configuration_content_reference(
rows[full]["event"]["sequence"],
- configuration_bytes(expected),
+ configuration_content_bytes(expected),
+ expected["behavior"]["project"],
))
self.assertNotEqual(rows[0]["event"]["trace_id"],
rows[1]["event"]["trace_id"])
@@ -136,7 +134,8 @@ def test_json_order_and_type_sensitive_comparison(self):
reordered = dict(reversed(list(self.config.items())))
reordered["profile"] = {"thinking": False, "temperature": 0.0}
self._emit(logger, reordered)
- self.assertIn(CONFIGURATION_REFERENCE, self._nodes()[-1]["details"])
+ self.assertIn(CONFIGURATION_CONTENT_REFERENCE,
+ self._nodes()[-1]["details"])
for value in (1.0, True, 1):
changed = _configuration(self.root, value)
self._emit(logger, changed)
@@ -185,14 +184,11 @@ def test_relocated_paths_reuse_one_complete_snapshot_across_runs(self):
first = rows[0]
encoded = configuration_content_bytes(expected[0])
self.assertEqual(first["details"], expected[0])
- for row, data in zip(rows[1:-1], expected[1:-1]):
+ for row, data in zip(rows[1:], expected[1:]):
self.assertEqual(row["details"], configuration_content_reference(
first["event"]["sequence"], encoded,
data["behavior"]["project"],
))
- self.assertEqual(rows[-1]["details"], configuration_reference(
- first["event"]["sequence"], configuration_bytes(expected[0]),
- ))
recording = read_recording(self.root)
self.assertFalse(recording.issues, recording.issues)
observations = [event for event in recording.events
@@ -258,6 +254,14 @@ def test_small_relocated_payload_remains_full(self):
self._emit(logger, minimal)
self.assertEqual(self._nodes()[-1]["details"], minimal)
+ def test_small_unchanged_payload_remains_full(self):
+ logger = self._logger()
+ minimal = {key: {} for key in self.config}
+ minimal["behavior"]["project"] = "a"
+ self._emit(logger, minimal)
+ self._emit(logger, minimal)
+ self.assertEqual(self._nodes()[-1]["details"], minimal)
+
def test_concurrent_relocation_references_keep_each_observed_path(self):
first, second = self._logger(), self._logger()
self._emit(first)
@@ -403,11 +407,14 @@ def _assert_ordered_observations(self, expected):
expected[trace_id][position])
positions[trace_id] += 1
sequence = event["sequence"]
- encoded = configuration_bytes(configuration)
+ encoded = configuration_content_bytes(configuration)
if latest is not None and latest[1] == encoded:
- self.assertEqual(row["details"], configuration_reference(
- latest[0], encoded
- ))
+ self.assertEqual(
+ row["details"], configuration_content_reference(
+ latest[0], encoded,
+ configuration["behavior"]["project"]
+ )
+ )
else:
self.assertEqual(row["details"], configuration)
latest = (sequence, encoded)
@@ -503,7 +510,7 @@ def fail(path, content):
next_logger = self._logger()
self._emit(next_logger)
next_logger.close()
- self.assertIn(CONFIGURATION_REFERENCE,
+ self.assertIn(CONFIGURATION_CONTENT_REFERENCE,
self._nodes()[-1]["details"])
def test_disabled_trace_performs_no_configuration_io(self):
From ff55703e6205ac63b1a8863d8862691ee3f20d94 Mon Sep 17 00:00:00 2001
From: Giovanni Volpe
Date: Wed, 2 Dec 2026 14:34:49 +0100
Subject: [PATCH 4/9] Strict recording protocol
Enforce the current system-testing recording protocol
- Require complete chronological source-organization histories, including projects with only default source assignments.
- Remove historical reconstruction of incomplete semantic observations.
- Require explicit, correlated project rename events instead of inferring relocation from recorded paths.
- Preserve physical source-history validation and independent identity corroboration.
- Reject incomplete recordings before replay without modifying the original workspace.
- Update system-testing documentation and regression tests.
---
docs/source_manifest.md | 13 +-
docs/system_testing.md | 35 ++---
docs/trace_architecture.md | 6 +-
docs/trace_recording.md | 4 +-
kilin/system_testing/_inspection.py | 5 +-
kilin/system_testing/_semantic_replay.py | 9 +-
kilin/system_testing/batch.py | 3 +-
kilin/system_testing/timeline.py | 51 +++---
kilin/system_testing/validation.py | 148 +-----------------
tests/kilin/system_testing/test_experiment.py | 142 ++++++++++++++---
10 files changed, 187 insertions(+), 229 deletions(-)
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 8bb36934..656d3118 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
diff --git a/docs/trace_architecture.md b/docs/trace_architecture.md
index 26412c9f..8cbf6114 100644
--- a/docs/trace_architecture.md
+++ b/docs/trace_architecture.md
@@ -127,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
diff --git a/docs/trace_recording.md b/docs/trace_recording.md
index 4a228701..d40451b7 100644
--- a/docs/trace_recording.md
+++ b/docs/trace_recording.md
@@ -272,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/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/_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/batch.py b/kilin/system_testing/batch.py
index cd9be20f..828f08ee 100644
--- a/kilin/system_testing/batch.py
+++ b/kilin/system_testing/batch.py
@@ -555,8 +555,7 @@ def add(level, code, message, sequence=None, *, side=None):
("validation_warnings", "review")):
for issue in workspace.get(field, []):
severity = ("info" if issue.get("code") in (
- "recording.limit", "relocation.inferred",
- "environment.difference") else level)
+ "recording.limit", "environment.difference") else level)
add(severity, f'{side}.{issue.get("code")}',
issue.get("message"), issue.get("sequence"), side=side)
for issue in data.get("report_issues", []):
diff --git a/kilin/system_testing/timeline.py b/kilin/system_testing/timeline.py
index 70ef37bc..72be9d12 100644
--- a/kilin/system_testing/timeline.py
+++ b/kilin/system_testing/timeline.py
@@ -198,12 +198,11 @@ def _relocations(recording: Recording,
Notes
-----
- New recordings require matching rename markers when either marker is
- present. Older recordings can establish a sibling rename through the
- preceding and following opening configurations and independently
- recorded trace paths, a complete close/open boundary, and unchanged
- conversation identity. Persistent settings and source manifests are
- checked separately by validation. Historical paths are never opened.
+ Require a matching request and completion for every internal reopen.
+ Corroborate their paths and conversation identity with independent
+ opening configurations, trace paths and close/open boundaries.
+ Persistent settings and source manifests are checked separately by
+ validation. Historical paths are never opened.
"""
events = recording.events
@@ -267,29 +266,27 @@ def _relocations(recording: Recording,
or (e.event_type ==
"gui.project.rename.completed"
and op.end_sequence < e.sequence < upper))]
+ request = one(relevant, "gui.project.rename.requested")
+ result = one(relevant, "gui.project.rename.completed")
+ identity = request.details.get("rename_id")
+ if (not isinstance(identity, str) or not identity or
+ identity in identities or
+ request.path != _PROJECT or result.path != _PROJECT or
+ not lower < request.sequence < close.start_sequence <
+ op.start_sequence <= op.end_sequence <
+ result.sequence < upper or
+ request.details != result.details or
+ request.details.get("conversation_id") != active or
+ _historical_directory(request.details.get(
+ "source_directory")) != source or
+ _historical_directory(request.details.get(
+ "destination_directory")) != destination):
+ raise ValueError("Uncorrelated project rename markers.")
+ consumed.update((request.sequence, result.sequence))
+ identities.add(identity)
relocation = {"source_directory": str(source),
"destination_directory": str(destination),
- "provenance": "inferred"}
- if relevant:
- request = one(relevant, "gui.project.rename.requested")
- result = one(relevant, "gui.project.rename.completed")
- identity = request.details.get("rename_id")
- if (not isinstance(identity, str) or not identity or
- identity in identities or len(relevant) != 2 or
- request.path != _PROJECT or result.path != _PROJECT or
- not lower < request.sequence < close.start_sequence <
- op.start_sequence <= op.end_sequence <
- result.sequence < upper or
- request.details != result.details or
- request.details.get("conversation_id") != active or
- _historical_directory(request.details.get(
- "source_directory")) != source or
- _historical_directory(request.details.get(
- "destination_directory")) != destination):
- raise ValueError("Uncorrelated project rename markers.")
- consumed.update((request.sequence, result.sequence))
- identities.add(identity)
- relocation.update(provenance="recorded", rename_id=identity)
+ "provenance": "recorded", "rename_id": identity}
operations[i] = replace(op, request={
**op.request, "requested_conversation_id": active,
"relocation": relocation,
diff --git a/kilin/system_testing/validation.py b/kilin/system_testing/validation.py
index 4b4e341c..635edcf8 100644
--- a/kilin/system_testing/validation.py
+++ b/kilin/system_testing/validation.py
@@ -23,7 +23,7 @@
from __future__ import annotations
from configparser import ConfigParser, Error as ConfigError
-from dataclasses import asdict, dataclass, field, replace
+from dataclasses import asdict, dataclass, field
from hashlib import sha256
import json
import os
@@ -41,16 +41,11 @@
)
from kilin.project import _read_project
from kilin.repository import _manifest_files
-from kilin.source_manifest import (
- SOURCE_MANIFEST_FILE, SourceManifest, SourceRole,
- _read_manifest_file, _serialize,
-)
-from kilin._source_manifest import parse_manifest
from kilin.workspace import SOURCE_MANIFEST_VERSION, _read_records
from ._filesystem import is_incidental_metadata
from ._plugin_provenance import plugin_observations
-from ._semantic_replay import PREFIX, validate_semantic_history
+from ._semantic_replay import validate_semantic_history
from .timeline import TimelineOperation, build_timeline, one
from .traces import (
Recording, TraceEvent, ValidationIssue, read_json, safe_path,
@@ -1487,131 +1482,6 @@ def _environment_warnings(recording: Recording) -> list[ValidationIssue]:
for message in sorted(differences)]
-def _default_only_organization(manifest: SourceManifest) -> bool:
- """Test whether source organization has no semantic choices to replay.
-
- Parameters
- ----------
- manifest: SourceManifest
- Validated saved or recorded semantic state.
-
- Returns
- -------
- bool
- Only untouched default assignments, without semantic graph edits.
-
- """
- return not (manifest.relations or manifest.suppressed_automatic
- or manifest.unresolved or any(
- item.origin != "default" or item.role !=
- manifest.organization.declaration.default_role
- for item in manifest.files
- ))
-
-
-def _check_source_organization(recording: Recording) -> None:
- """Validate additive default-only histories from pre-PR14 recordings.
-
- Parameters
- ----------
- recording: Recording
- Closed reference workspace and ordered decoded events.
-
- Notes
- -----
- Lifecycle-only default additions are redundant with the validated
- physical creation/import history. Verify their exact revision chain;
- do not infer an unrecorded edit, detector adoption or relationship.
- Nontrivial histories without correlated commands remain unsupported.
-
- """
- lifecycle = []
- initial = None
- for event in recording.events:
- if event.event_type == "source_organization.committed":
- recording.issue(
- "source.organization.unsupported",
- "Semantic source mutations lack correlated replay commands.",
- event.path, event.sequence,
- )
- elif event.event_type == "source_organization.reconciled":
- lifecycle.append(event)
- elif (initial is None and not lifecycle and event.event_type in
- ("index.check.completed", "index.empty")):
- initial = event.details.get("source_manifest")
- try:
- path = safe_path(recording.root, SOURCE_MANIFEST_FILE)
- except (ValueError, OSError) as error:
- recording.issue("source.organization.invalid", str(error),
- SOURCE_MANIFEST_FILE)
- return
- try:
- if not path.exists() and not path.is_symlink():
- if lifecycle:
- raise ValueError("Recorded source organization is missing.")
- return
- try:
- snapshot = _read_manifest_file(path)
- except (ValueError, OSError) as error:
- recording.issue("source.organization.invalid", str(error),
- SOURCE_MANIFEST_FILE)
- return
- manifest = snapshot.manifest
- if not _default_only_organization(manifest):
- raise ValueError("Edited source organization is not replayable.")
- if not lifecycle and manifest.revision == 0:
- return
- if not lifecycle or initial is None:
- raise ValueError("Source organization history is incomplete.")
- first = parse_manifest(lifecycle[0].details["source_organization"])
- default = first.organization.declaration.default_role
- previous = replace(first, revision=0, files=tuple(
- SourceRole(name, default, "default")
- for name in sorted(_manifest_files(initial))
- ))
- if not _default_only_organization(previous):
- raise ValueError("Nondefault initial organization is unsupported.")
- indexed_names = set(_manifest_files(initial))
- for event in recording.events:
- if event.event_type in ("index.check.completed", "index.empty"):
- indexed_names = set(_manifest_files(
- event.details.get("source_manifest")
- ))
- if indexed_names != {item.path for item in previous.files}:
- raise ValueError(
- "Source organization differs from indexed selection."
- )
- if event.event_type != "source_organization.reconciled":
- continue
- data = event.details
- state = parse_manifest(data["source_organization"])
- old_digest = sha256(_serialize(previous).encode("utf-8"))
- new_digest = sha256(_serialize(state).encode("utf-8"))
- if (
- not _default_only_organization(state)
- or state.organization != previous.organization
- or state.source_root != previous.source_root
- or not set(previous.files) < set(state.files)
- or state.revision != previous.revision + 1
- or data.get("previous_revision") != previous.revision
- or data.get("revision") != state.revision
- or data.get("previous_sha256") != old_digest.hexdigest()
- or data.get("sha256") != new_digest.hexdigest()
- ):
- raise ValueError("Nonadditive source organization history.")
- previous = state
- if indexed_names != {item.path for item in previous.files}:
- raise ValueError(
- "Source organization has no final physical index checkpoint."
- )
- if (manifest != previous or
- snapshot.sha256 != lifecycle[-1].details.get("sha256")):
- raise ValueError("Saved organization differs from its history.")
- except (ValueError, OSError, KeyError, TypeError) as error:
- recording.issue("source.organization.unsupported", str(error),
- SOURCE_MANIFEST_FILE)
-
-
def validate_recording(recording: Recording) -> ValidationReport:
"""Collect structural, chronological and durable-state inconsistencies.
@@ -1629,12 +1499,7 @@ def validate_recording(recording: Recording) -> ValidationReport:
"""
_sequence_checks(recording)
operations = build_timeline(recording)
- if any(event.event_type.startswith(PREFIX) or
- "source_organization_revision" in event.details
- for event in recording.events):
- validate_semantic_history(recording, operations)
- else:
- _check_source_organization(recording)
+ validate_semantic_history(recording, operations)
creations = [op for op in operations if op.kind == "create_project"]
if (len(creations) != 1 or not operations
or operations[0].kind != "create_project"):
@@ -1693,13 +1558,6 @@ def validate_recording(recording: Recording) -> ValidationReport:
"workspace. Unrecorded actions and edits restored before observation "
"cannot always be detected. Model availability is not checked."
)]
- warnings.extend(ValidationIssue(
- "relocation.inferred",
- "Historical sibling rename inferred from independent trace paths; "
- "explicit rename markers were not recorded.",
- sequence=op.start_sequence,
- ) for op in operations if op.request.get("relocation", {}).get(
- "provenance") == "inferred")
warnings.extend(_environment_warnings(recording))
return ValidationReport(recording.root, tuple(recording.issues),
tuple(warnings), len(recording.events),
diff --git a/tests/kilin/system_testing/test_experiment.py b/tests/kilin/system_testing/test_experiment.py
index 2d1924e4..a257fd31 100644
--- a/tests/kilin/system_testing/test_experiment.py
+++ b/tests/kilin/system_testing/test_experiment.py
@@ -281,6 +281,92 @@ def test_lifecycle_addition_requires_final_physical_checkpoint(self):
for issue in report.issues
))
+ def test_default_only_history_requires_semantic_creation(self):
+ """Reject complete physical traces without semantic observations."""
+ self.engine.close()
+ for name, sources in (("legacy_empty", []), ("legacy_default", [
+ str(self.fixture.root / "source.txt")])):
+ with self.subTest(name=name):
+ root = self.fixture.root / name
+ with patch.object(self.engine, "_record_source_organization"):
+ self.engine.open_project(sources, "writing", str(root))
+ self.assertEqual(self.fixture.events[-1]["event"],
+ "opened")
+ self.engine.close()
+ experiment = Experiment(root)
+ before = _snapshot(root)
+ report = self.assertInvalid(
+ "source.organization.unsupported", experiment
+ )
+ self.assertFalse(any(e.event_type.startswith(
+ "gui.source_organization.") for e in report.events))
+ self.assertEqual({issue.code for issue in report.issues},
+ {"source.organization.unsupported"})
+ self.assertEqual(before, _snapshot(root))
+ # Even without the saved manifest, missing history is an
+ # error rather than an accepted pre-organization recording.
+ (root / "source_manifest.json").unlink()
+ self.assertInvalid("source.organization.unsupported",
+ experiment)
+
+ def test_additive_history_requires_semantic_creation(self):
+ """Core reconciliations alone cannot establish a creation state."""
+ self.engine.close()
+ root = self.fixture.root / "legacy_additive"
+ source = self.fixture.root / "extra.txt"
+ source.write_text("Additional source", encoding="utf-8")
+ with patch.object(self.engine, "_record_source_organization"):
+ self.engine.open_project([str(self.fixture.root / "source.txt")],
+ "writing", str(root))
+ self.engine.add_project_sources([str(source)])
+ self.engine.close()
+ experiment = Experiment(root)
+ before = _snapshot(root)
+ report = self.assertInvalid("source.organization.unsupported",
+ experiment)
+ self.assertTrue(any(e.event_type == "source_organization.reconciled"
+ for e in report.events))
+ self.assertEqual({issue.code for issue in report.issues},
+ {"source.organization.unsupported"})
+ target = root.with_name("legacy_additive_replay")
+ with self.assertRaises(InvalidRecordingError):
+ experiment.replay(target)
+ self.assertFalse(target.exists())
+ self.assertEqual(before, _snapshot(root))
+
+ def test_missing_saved_semantic_manifest_is_rejected(self):
+ """A complete event history still requires the durable manifest."""
+ self.engine.close()
+ self.assertValid()
+ (self.root / "source_manifest.json").unlink()
+ self.assertInvalid("source.organization.unsupported")
+
+ def test_missing_reopen_semantic_observation_is_rejected(self):
+ """Do not borrow a previous opening's semantic observation."""
+ self.engine.close()
+ self.assertValid()
+ with patch.object(self.engine, "_record_source_organization"):
+ self.engine.resume_project(str(self.root))
+ self.engine.close()
+ report = self.assertInvalid("source.organization.unsupported")
+ self.assertTrue(any("Missing semantic opening observation" in
+ issue.message for issue in report.issues))
+
+ def test_missing_question_semantic_identity_is_rejected(self):
+ """Require an explicit semantic identity at every question."""
+ self.fixture._ask("Inspect the source")
+ self.engine.close()
+ report = self.assertValid()
+ ask = next(op for op in report.operations if op.kind == "ask")
+
+ def remove_identity(node):
+ node["details"].pop("source_organization_revision")
+ node["details"].pop("source_organization_sha256")
+
+ self._change(self.root / ask.events[0].path,
+ "gui.question.request.started", remove_identity)
+ self.assertInvalid("source.organization.unsupported")
+
def test_blank_reference(self):
self.engine.close()
root = self.fixture.root / "blank"
@@ -347,40 +433,50 @@ def test_recorded_consecutive_renames(self):
self.assertEqual([m["destination_directory"] for m in moves],
[str(middle), str(self.root)])
self.assertNotEqual(moves[0]["rename_id"], moves[1]["rename_id"])
- self.assertNotIn("relocation.inferred", {w.code for w in
- report.warnings})
+ for terminal in ("requested", "completed"):
+ self.assertEqual(sum(e.event_type == "gui.project.rename." +
+ terminal for e in report.events), 2)
self.assertEqual(before, _snapshot(self.root))
- def _rename_without_markers(self, *, completion_only=False):
- """Simulate an older producer or a missing completion marker."""
+ def _rename_without_markers(self, *, missing=("requested", "completed")):
+ """Simulate a recording missing one or both explicit markers."""
emit = TraceLogger.emit
- def legacy(logger, event_type, **options):
- if event_type == "gui.project.rename.completed" or (
- not completion_only and
- event_type == "gui.project.rename.requested"):
+ def omit(logger, event_type, **options):
+ if event_type in {"gui.project.rename." + suffix
+ for suffix in missing}:
return None
return emit(logger, event_type, **options)
- with patch.object(TraceLogger, "emit", legacy):
+ with patch.object(TraceLogger, "emit", omit):
self._rename("renamed")
self.engine.close()
- def test_legacy_rename_is_inferred_with_warning(self):
- """Accept an already-recorded move only with independent paths."""
- self.fixture._ask("Before legacy rename")
+ def test_rename_without_markers_is_rejected(self):
+ """Independent paths cannot replace an explicit rename command."""
+ self.fixture._ask("Before rename")
self._rename_without_markers()
- report = self.assertValid()
+ before = _snapshot(self.root)
+ report = self.assertInvalid("relocation.history")
reopening = next(op for op in report.operations
if op.kind == "open_project")
- self.assertEqual(reopening.request["relocation"]["provenance"],
- "inferred")
- self.assertIn("relocation.inferred", {w.code for w in report.warnings})
+ self.assertNotIn("relocation", reopening.request)
self.assertFalse(any(e.event_type.startswith("gui.project.rename.")
for e in report.events))
+ self.assertEqual({issue.code for issue in report.issues},
+ {"relocation.history"})
+ target = self.root.with_name("renamed_replay")
+ with self.assertRaises(InvalidRecordingError):
+ self.experiment.replay(target)
+ self.assertFalse(target.exists())
+ self.assertEqual(before, _snapshot(self.root))
- def test_incomplete_rename_markers_do_not_use_legacy_fallback(self):
- self._rename_without_markers(completion_only=True)
+ def test_missing_rename_completion_is_rejected(self):
+ self._rename_without_markers(missing=("completed",))
+ self.assertInvalid("relocation.history")
+
+ def test_missing_rename_request_is_rejected(self):
+ self._rename_without_markers(missing=("requested",))
self.assertInvalid("relocation.history")
def test_mismatched_rename_markers(self):
@@ -391,8 +487,10 @@ def test_mismatched_rename_markers(self):
"details"].update(rename_id="different"))
self.assertInvalid("relocation.history")
- def test_legacy_rename_requires_independent_path_corroboration(self):
- self._rename_without_markers()
+ def test_rename_requires_independent_path_corroboration(self):
+ self._rename("renamed")
+ self.engine.close()
+ self.assertValid()
def change_project(node):
"""Corrupt the same historical path in either representation."""
@@ -407,7 +505,9 @@ def change_project(node):
self._change(self.root / "logs/traces/project.json",
"gui.project.configuration.effective", change_project)
- self.assertInvalid("relocation.history")
+ report = self.assertInvalid("relocation.history")
+ self.assertTrue(any("Relocation trace identity differs" in
+ issue.message for issue in report.issues))
def test_unrelated_same_directory_internal_reopen_is_rejected(self):
active = self.engine.active_conversation.conversation_id
From a86bc79b6f63ef10d063c704eb659e02c700683b Mon Sep 17 00:00:00 2001
From: Giovanni Volpe
Date: Wed, 2 Dec 2026 14:45:20 +0100
Subject: [PATCH 5/9] Current comparison format
Enforce the current comparison and plugin-provenance contracts
- Require independent event inventories reconciled with recorded event totals.
- Remove legacy event-count reconstruction from aligned operations.
- Restrict memory-header normalization to the current prompt-local representation.
- Require explicit plugin-provenance metadata while preserving legitimately unknown identities.
- Increment the independent comparison report format generation to 2 and reject incompatible reports with regeneration instructions.
- Consolidate overlapping report-loader tests while preserving validation and replay-boundary coverage.
- Update comparison, versioning, and system-testing regression coverage and documentation.
---
docs/PLUGIN_API.md | 21 +++---
docs/system_testing.md | 44 ++++++-----
.../system_testing/_comparison_diagnostics.py | 36 ++-------
kilin/system_testing/_plugin_provenance.py | 74 +++++++++++--------
kilin/system_testing/analysis.py | 68 +++++++----------
kilin/system_testing/comparison.py | 2 +-
kilin/system_testing/replay.py | 2 +-
.../system_testing/test__batch_diagnostics.py | 36 ++++++++-
.../test__comparison_diagnostics.py | 70 +++++++++++-------
.../system_testing/test__plugin_provenance.py | 55 ++++++++++++--
tests/kilin/system_testing/test_experiment.py | 38 ++++++++++
tests/kilin/test__format_versions.py | 39 ++++++++--
12 files changed, 314 insertions(+), 171 deletions(-)
diff --git a/docs/PLUGIN_API.md b/docs/PLUGIN_API.md
index 036d695a..1ed4c8ce 100644
--- a/docs/PLUGIN_API.md
+++ b/docs/PLUGIN_API.md
@@ -678,12 +678,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 +700,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 +720,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/system_testing.md b/docs/system_testing.md
index 656d3118..d16d4612 100644
--- a/docs/system_testing.md
+++ b/docs/system_testing.md
@@ -325,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
@@ -391,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
@@ -406,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
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/_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/analysis.py b/kilin/system_testing/analysis.py
index a9cf172f..5761249c 100644
--- a/kilin/system_testing/analysis.py
+++ b/kilin/system_testing/analysis.py
@@ -585,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.
@@ -596,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):
@@ -609,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
@@ -886,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
----------
@@ -899,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:
@@ -1066,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"), [
@@ -1118,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
-------
@@ -2474,7 +2455,8 @@ def analysis_markdown(data: dict, name: str = "Workspace") -> str:
sum(events["counts"][side].values())) for side in SIDES])
if not events["complete"]:
lines += ["Complete inventory unavailable; partial counts are not "
- "interpreted as differences.", ""]
+ "interpreted as differences. Regenerate the comparison "
+ "report.", ""]
elif events["differences"]:
lines += _md_table(("Event type", "Original", "Replay", "Delta"), [
(r["event_type"], r["original"], r["replayed"], r["delta"])
diff --git a/kilin/system_testing/comparison.py b/kilin/system_testing/comparison.py
index 426c32d8..a58871a3 100644
--- a/kilin/system_testing/comparison.py
+++ b/kilin/system_testing/comparison.py
@@ -61,7 +61,7 @@
__all__ = ["Comparison", "compare", "COMPARISON_FORMAT_VERSION"]
-COMPARISON_FORMAT_VERSION: Final[int] = 1
+COMPARISON_FORMAT_VERSION: Final[int] = 2
@dataclass(frozen=True, slots=True)
diff --git a/kilin/system_testing/replay.py b/kilin/system_testing/replay.py
index 656d049e..259b6101 100644
--- a/kilin/system_testing/replay.py
+++ b/kilin/system_testing/replay.py
@@ -344,7 +344,7 @@ def _plugin_differences(
Returns
-------
list[ReplayDifference]
- Known differences in the common command prefix. Missing historical
+ Known differences in the common command prefix. Unavailable
identities are not inferred differences; comparison reports retain
their explicit unknown status.
diff --git a/tests/kilin/system_testing/test__batch_diagnostics.py b/tests/kilin/system_testing/test__batch_diagnostics.py
index 67bb0bfd..246b8169 100644
--- a/tests/kilin/system_testing/test__batch_diagnostics.py
+++ b/tests/kilin/system_testing/test__batch_diagnostics.py
@@ -8,7 +8,8 @@
import unittest
from kilin.system_testing.analysis import (
- batch_overview, event_inventory, question_explorer,
+ batch_overview, event_inventory, event_inventory_html,
+ question_explorer,
_release_agreement_rows, _release_totals,
)
from kilin.system_testing.batch import (
@@ -96,6 +97,39 @@ def test_outcome_transition_not_obscured_by_publication_hint(self):
group = next(g for g in groups if g["code"] == "capability.changed")
self.assertEqual(group["question_number"], 1)
+ def test_missing_independent_counts_are_not_reconstructed(self):
+ data = report()
+ # The old reconstruction would accept these reconciled stage counts.
+ for side in ("original", "replayed"):
+ del data[side]["event_counts"]
+ data[side]["outside_commands"] = {"event_counts": {"close": 1}}
+ data["operations"] = [{"original_sequence": 1, "stages": [{
+ "event_type": "ask", "original": {"count": 1},
+ "replayed": {"count": 1}}]}]
+ before = deepcopy(data)
+ inventory = event_inventory(data)
+ self.assertFalse(inventory["complete"])
+ self.assertEqual(inventory["counts"], {"original": {}, "replayed": {}})
+ self.assertEqual(inventory["differences"], [])
+ self.assertIn("Regenerate", event_inventory_html(data))
+ self.assertIn("events.coverage", [i["code"] for i in
+ collect_issues(data, {})])
+ self.assertEqual(data, before)
+
+ def test_independent_inventory_requires_valid_counts_and_totals(self):
+ for counts, total in ((None, 2), ({"ask": True}, 1),
+ ({"ask": -1}, -1), ({"ask": 2.0}, 2),
+ ({1: 2}, 2), ({"ask": 2}, 1),
+ ({"ask": 2}, 2.0), ({"ask": 1}, True)):
+ with self.subTest(counts=counts, total=total):
+ data = report()
+ data["replayed"].update(event_counts=counts,
+ event_count=total)
+ inventory = event_inventory(data)
+ self.assertFalse(inventory["complete"])
+ self.assertEqual(inventory["counts"]["original"], {"ask": 2})
+ self.assertEqual(inventory["differences"], [])
+
def test_event_attribution_with_cancelling_counts(self):
data = report()
data["operations"] = [{"original_sequence": seq, "stages": [{
diff --git a/tests/kilin/system_testing/test__comparison_diagnostics.py b/tests/kilin/system_testing/test__comparison_diagnostics.py
index 000648cb..c97e502d 100644
--- a/tests/kilin/system_testing/test__comparison_diagnostics.py
+++ b/tests/kilin/system_testing/test__comparison_diagnostics.py
@@ -70,15 +70,13 @@ def test_history_final_selection_is_separate(self):
self.assertIsNone(row["original"])
self.assertTrue(row["issues"])
- def _prompt(self, record, *, text=" Saved text", stamp=None):
- """Create the producer's memory header and selection record."""
- origins = ", ".join(f"{o['conversation_id']} turn {o['turn_number']}"
- for o in record["origins"])
- timestamp = stamp or "2026-11-01T09:00:00+00:00"
+ def _prompt(self, record, *, text=" Saved text", header=None):
+ """Create the current memory header and selection record."""
+ if header is None:
+ header = f"Memory {record['label']} | {record['role']} | Turn T1"
content = ("Question: What?\n\nCONVERSATION MEMORY (previous "
"discussion, NOT source evidence):\n\n"
- f"Memory M1 | user | UUID {record['turn_uuid']} | "
- f"{timestamp} | {origins}\n{text}")
+ f"{header}\n{text}")
event = _event(2, "llm.call.input", {}, exact={
"01_structured_messages": {"value": [
{"role": "user", "content": content}]}})
@@ -88,18 +86,21 @@ def _prompt(self, record, *, text=" Saved text", stamp=None):
def test_prompt_only_normalizes_corroborated_metadata(self):
a, before = self._prompt(self.old)
- b, after = self._prompt(self.new, stamp="2026-11-02T09:00:00+00:00")
+ b, after = self._prompt(self.new)
left = structured_prompt(a, before, {"a": "a"},
{"old": "old", "branch": "branch"})
right = structured_prompt(b, after, {"b": "a"},
{"new": "old", "fork": "branch"})
- self.assertNotEqual(left["raw"], right["raw"])
+ self.assertEqual(left["raw"], right["raw"])
+ self.assertIsNotNone(left["normalized"])
self.assertEqual(left["normalized"], right["normalized"])
+ self.assertEqual(left["headers"], 1)
b, after = self._prompt(self.new, text=" Changed content")
right = structured_prompt(b, after, {"b": "a"},
{"new": "old", "fork": "branch"})
+ self.assertNotEqual(left["raw"], right["raw"])
self.assertNotEqual(left["normalized"], right["normalized"])
- b, after = self._prompt(self.new, stamp="invalid")
+ b, after = self._prompt(self.new, header="invalid header")
right = structured_prompt(b, after, {"b": "a"},
{"new": "old", "fork": "branch"})
self.assertIsNone(right["normalized"])
@@ -107,29 +108,44 @@ def test_prompt_only_normalizes_corroborated_metadata(self):
self.assertIsNone(structured_prompt(
a, _op("old", a), {"a": "a"}, {"old": "old"})["normalized"])
- def test_local_memory_header_and_legacy_header_normalize_equally(self):
+ def test_legacy_memory_header_is_not_normalized(self):
a, before = self._prompt(self.old)
- b, after = self._prompt(self.new)
- messages = b.exact_content["01_structured_messages"]["value"]
- text = messages[0]["content"]
- start = text.index("Memory M1 |")
- end = text.index("\n", start)
- messages[0]["content"] = (
- text[:start] + "Memory M1 | user | Turn T1" + text[end:]
- )
+ origins = ", ".join(f"{o['conversation_id']} turn {o['turn_number']}"
+ for o in self.new["origins"])
+ header = (f"Memory M1 | user | UUID {self.new['turn_uuid']} | "
+ f"2026-11-02T09:00:00+00:00 | {origins}")
+ b, after = self._prompt(self.new, header=header)
+ original = deepcopy(b.exact_content)
left = structured_prompt(a, before, {"a": "a"},
{"old": "old", "branch": "branch"})
right = structured_prompt(b, after, {"b": "a"},
{"new": "old", "fork": "branch"})
- self.assertEqual(left["normalized"], right["normalized"])
+ self.assertIsNotNone(left["normalized"])
+ self.assertIsNone(right["normalized"])
+ self.assertIn("recorded format", right["issue"])
+ self.assertIn(header, right["raw"])
self.assertNotEqual(left["raw"], right["raw"])
- messages[0]["content"] = messages[0]["content"].replace(
- "Turn T1", "Turn T2"
- )
- bad = structured_prompt(b, after, {"b": "a"},
- {"new": "old", "fork": "branch"})
- self.assertIsNone(bad["normalized"])
- self.assertTrue(bad["issue"])
+ self.assertEqual(original, b.exact_content)
+ for header in ("Memory M1 | user | Turn T2",
+ "Memory M2 | user | Turn T1",
+ "Memory M1 | assistant | Turn T1"):
+ with self.subTest(header=header):
+ b, after = self._prompt(self.new, header=header)
+ bad = structured_prompt(b, after, {"b": "a"},
+ {"new": "old", "fork": "branch"})
+ self.assertIsNone(bad["normalized"])
+ self.assertTrue(bad["issue"])
+
+ def test_equal_local_headers_do_not_erase_distinct_memory_identities(self):
+ a, before = self._prompt(self.old)
+ b, after = self._prompt(self.new)
+ left = structured_prompt(a, before, {"a": "a"},
+ {"old": "old", "branch": "branch"})
+ right = structured_prompt(b, after, {"b": "other"},
+ {"new": "old", "fork": "branch"})
+ self.assertEqual(left["raw"], right["raw"])
+ self.assertIsNotNone(right["normalized"])
+ self.assertNotEqual(left["normalized"], right["normalized"])
def test_timing_only_and_equal_failure(self):
a = {"name": "summary", "status": "incomplete", "valid": False,
diff --git a/tests/kilin/system_testing/test__plugin_provenance.py b/tests/kilin/system_testing/test__plugin_provenance.py
index 8d35f1f2..6e994050 100644
--- a/tests/kilin/system_testing/test__plugin_provenance.py
+++ b/tests/kilin/system_testing/test__plugin_provenance.py
@@ -306,10 +306,12 @@ def test_unknown_invalid_and_one_sided_observations(self):
known = _operation(_event("tool.run.started", {
"name": _TOOL, "plugin": identity,
}), kind="ask")
- old = _operation(_event("tool.run.started", {"name": _TOOL}),
- kind="ask")
- self.assertEqual(compare_plugins(old, known)[0]["status"], "unknown")
- self.assertEqual(_plugin_differences((old,), (known,)), [])
+ unknown = _operation(_event("tool.run.started", {
+ "name": _TOOL, "plugin": None,
+ }), kind="ask")
+ self.assertEqual(compare_plugins(unknown, known)[0]["status"],
+ "unknown")
+ self.assertEqual(_plugin_differences((unknown,), (known,)), [])
self.assertEqual(compare_plugins(known, known)[0]["status"], "equal")
self.assertEqual(compare_plugins(known, _operation(kind="ask"))[0][
"status"], "one_sided")
@@ -321,9 +323,10 @@ def test_unknown_invalid_and_one_sided_observations(self):
observation["identity"]["version"] = "changed"
self.assertEqual(identity["version"], "1.0.0")
- def test_legacy_activation_preserves_unknown_requirements(self):
+ def test_activation_preserves_explicitly_unknown_requirements(self):
operation = _operation(_event("gui.project.configuration.effective", {
"profile": {"type_id": _TYPE}, "tools": [{"name": _TOOL}],
+ "plugins": {"project_type": None, "tools": {_TOOL: None}},
}))
items = plugin_observations(operation.events)
self.assertEqual([x["name"] for x in items], [_TYPE, _TOOL])
@@ -338,3 +341,45 @@ def test_legacy_activation_preserves_unknown_requirements(self):
return_value=()):
with self.assertRaisesRegex(ValueError, _TOOL):
preflight_plugins((operation,))
+
+ def test_missing_required_plugin_metadata_is_invalid(self):
+ cases = (
+ ("gui.project.configuration.effective", {
+ "profile": {"type_id": _TYPE}, "tools": [{"name": _TOOL}],
+ }),
+ ("gui.project.configuration.effective", {
+ "profile": {"type_id": _TYPE}, "tools": [{"name": _TOOL}],
+ "plugins": {"project_type": None, "tools": {}},
+ }),
+ ("gui.project.configuration.effective", {
+ "profile": {}, "tools": [],
+ "plugins": {"project_type": None, "tools": {}},
+ }),
+ ("gui.project.configuration.effective", {
+ "profile": {"type_id": _TYPE}, "tools": [None],
+ "plugins": {"project_type": None, "tools": {}},
+ }),
+ ("turn.settings.snapshot", {"project_type_plugin": None}),
+ ("tool.run.started", {"name": _TOOL}),
+ ("tool.run.started", {"plugin": None}),
+ ("tool.run.started", {"name": [], "plugin": None}),
+ )
+ for kind, details in cases:
+ with self.subTest(kind=kind, details=details):
+ items = plugin_observations((_event(kind, details),))
+ self.assertEqual(len(items), 1)
+ self.assertEqual(items[0]["status"], "invalid")
+ self.assertIsNone(items[0]["identity"])
+ self.assertTrue(items[0]["error"])
+
+ def test_unavailable_turn_identity_remains_unknown(self):
+ # Current turn producers omit an unavailable project-type identity.
+ for data in ({"project_type_id": _TYPE}, {
+ "project_type_id": _TYPE, "project_type_plugin": None}):
+ with self.subTest(data=data):
+ items = plugin_observations((
+ _event("turn.settings.snapshot", data),
+ ))
+ self.assertEqual(len(items), 1)
+ self.assertEqual(items[0]["status"], "unknown")
+ self.assertEqual(items[0]["name"], _TYPE)
diff --git a/tests/kilin/system_testing/test_experiment.py b/tests/kilin/system_testing/test_experiment.py
index a257fd31..c2b5d27c 100644
--- a/tests/kilin/system_testing/test_experiment.py
+++ b/tests/kilin/system_testing/test_experiment.py
@@ -367,6 +367,44 @@ def remove_identity(node):
"gui.question.request.started", remove_identity)
self.assertInvalid("source.organization.unsupported")
+ def test_missing_opening_plugin_snapshot_blocks_replay(self):
+ self.engine.close()
+ self.assertValid()
+ path = self.root / "logs/traces/project.json"
+ self._change(path, "gui.project.configuration.effective", lambda node:
+ node["details"].pop("plugins"))
+ before = _snapshot(self.root)
+ report = self.assertInvalid("plugin.provenance")
+ self.assertTrue(any("plugin snapshot" in issue.message
+ for issue in report.issues))
+ target = self.root.with_name("missing_plugin_snapshot_replay")
+ with self.assertRaises(InvalidRecordingError):
+ self.experiment.replay(target)
+ self.assertFalse(target.exists())
+ self.assertEqual(before, _snapshot(self.root))
+
+ def test_missing_tool_identity_field_blocks_replay(self):
+ self.fixture.commands.extend([
+ {"action": "plan_choice", "choice": "quick"},
+ {"action": "plan_choice", "choice": "option:0"},
+ ])
+ self.fixture._ask("Inspect the source", tool=True)
+ self.engine.close()
+ report = self.assertValid()
+ event = next(event for event in report.events
+ if event.event_type == "tool.run.started")
+ self._change(self.root / event.path, event.event_type, lambda node:
+ node["details"].pop("plugin"))
+ before = _snapshot(self.root)
+ report = self.assertInvalid("plugin.provenance")
+ self.assertTrue(any("Missing plugin identity field" in issue.message
+ for issue in report.issues))
+ target = self.root.with_name("missing_tool_identity_replay")
+ with self.assertRaises(InvalidRecordingError):
+ self.experiment.replay(target)
+ self.assertFalse(target.exists())
+ self.assertEqual(before, _snapshot(self.root))
+
def test_blank_reference(self):
self.engine.close()
root = self.fixture.root / "blank"
diff --git a/tests/kilin/test__format_versions.py b/tests/kilin/test__format_versions.py
index 145d494b..8f246515 100644
--- a/tests/kilin/test__format_versions.py
+++ b/tests/kilin/test__format_versions.py
@@ -171,18 +171,47 @@ def test_comparison_report_loader_uses_own_generation(self):
"summary", "original", "replayed", "files", "final_state",
"embedding_evaluation",
)}
+ self.assertEqual(comparison.COMPARISON_FORMAT_VERSION, 2)
payload.update(format_version=comparison.COMPARISON_FORMAT_VERSION,
alignment={"status": "complete"}, operations=[],
report_issues=[])
+ for side in ("original", "replayed"):
+ payload[side].update(event_count=0, event_counts={})
path.write_text(json.dumps(payload), encoding="utf-8")
self.assertEqual(analysis.load_report(path), payload)
- for invalid in _INVALID_VERSIONS:
+ # Comparison reports have an independent format generation.
+ for invalid in (True, False, 1, 1.0, 2.0, "1", "2", None, 0, 3,
+ "missing"):
with self.subTest(version=invalid):
- path.write_text(json.dumps(dict(payload,
- format_version=invalid)),
- encoding="utf-8")
- with self.assertRaisesRegex(ValueError, "format version"):
+ data = dict(payload, format_version=invalid)
+ if invalid == "missing":
+ del data["format_version"]
+ path.write_text(json.dumps(data), encoding="utf-8")
+ before = path.read_bytes()
+ with self.assertRaisesRegex(
+ ValueError, "format version; regenerate"):
analysis.load_report(path)
+ self.assertEqual(path.read_bytes(), before)
+ # Exercise the same loader with a nonempty independent inventory.
+ for side in ("original", "replayed"):
+ payload[side].update(event_count=2, event_counts={"ask": 2})
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ self.assertEqual(analysis.load_report(path), payload)
+ for side in ("original", "replayed"):
+ for missing in (True, False):
+ with self.subTest(side=side, missing_counts=missing):
+ data = deepcopy(payload)
+ if missing:
+ del data[side]["event_counts"]
+ else:
+ data[side]["event_counts"] = {"ask": 3}
+ path.write_text(json.dumps(data), encoding="utf-8")
+ before = path.read_bytes()
+ with self.assertRaisesRegex(
+ ValueError,
+ "independent event counts; regenerate"):
+ analysis.load_report(path)
+ self.assertEqual(path.read_bytes(), before)
def test_receipts_validate_independent_generations(self):
original = self.root / "example_original"
From 2745fe07340ac64ccbe802cebc88ba201fcba553 Mon Sep 17 00:00:00 2001
From: Giovanni Volpe
Date: Wed, 2 Dec 2026 14:51:53 +0100
Subject: [PATCH 6/9] Canonical model settings
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
PR08 — Canonical model settings
Remove historical model-settings migration and enforce the current configuration contract.
- Remove legacy effort-level, model-choice, router, and retrieval-depth sidecar readers.
- Ignore and preserve obsolete settings files without automatic migration or deletion.
- Establish profile.ini as the sole authority for saved project model and search settings.
- Preserve explicit model overrides, application preferences, and packaged defaults.
- Retain initialization of genuinely missing settings in core-created projects.
- Validate current settings before initialization and reject unsupported effort-level fields.
- Consolidate redundant router-precedence tests and add regression coverage for obsolete-file isolation, current validation, and saved-setting preservation.
- Update model-management and configuration documentation.
---
docs/configuration.md | 11 +-
docs/gui_architecture.md | 5 +-
docs/model_management.md | 4 +-
docs/package_defaults.md | 4 +-
kilin/gui/README.md | 12 +-
kilin/gui/model_settings.py | 186 +++++++------------------
kilin/gui/preferences.py | 22 +--
kilin/model_settings.py | 29 ++--
tests/kilin/gui/test_model_settings.py | 171 +++++++++++++++++++++++
tests/kilin/gui/test_preferences.py | 17 +++
tests/kilin/test_model_settings.py | 116 ++++++++-------
11 files changed, 334 insertions(+), 243 deletions(-)
create mode 100644 tests/kilin/gui/test_model_settings.py
diff --git a/docs/configuration.md b/docs/configuration.md
index d0bcb184..1413c3f1 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
diff --git a/docs/gui_architecture.md b/docs/gui_architecture.md
index f5a61ad5..ce168d0f 100644
--- a/docs/gui_architecture.md
+++ b/docs/gui_architecture.md
@@ -161,8 +161,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/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/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/kilin/gui/README.md b/kilin/gui/README.md
index 606fc592..964a6f21 100644
--- a/kilin/gui/README.md
+++ b/kilin/gui/README.md
@@ -574,13 +574,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/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/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/tests/kilin/gui/test_model_settings.py b/tests/kilin/gui/test_model_settings.py
new file mode 100644
index 00000000..fc62805e
--- /dev/null
+++ b/tests/kilin/gui/test_model_settings.py
@@ -0,0 +1,171 @@
+"""Verify current project model settings and obsolete-file isolation.
+
+Exercise real core-created projects and application preferences without
+loading models, invoking Qt, or mutating packaged defaults.
+
+"""
+
+# pylint: disable=C0115:missing-class-docstring
+# pylint: disable=C0116:missing-function-docstring
+# pylint: disable=C0103:invalid-name
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from tempfile import TemporaryDirectory
+import unittest
+from unittest.mock import patch
+
+from kilin.gui import model_settings, preferences
+from kilin.project import initialize_project, open_project
+from kilin.runtime import BACKEND_MLX, BACKEND_TORCH
+
+
+class TestProjectModelSettings(unittest.TestCase):
+ """Protect current initialization and saved-setting precedence."""
+
+ def setUp(self) -> None:
+ """Isolate preferences and projects from the user's filesystem."""
+
+ temporary = TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ override = patch.dict("os.environ", {
+ "KILIN_DEFAULTS_FILE": str(self.root / "preferences.json"),
+ })
+ override.start()
+ self.addCleanup(override.stop)
+
+ def test_initialize_current_settings_without_touching_sidecars(self):
+ """Ignore all obsolete input forms before and after initialization."""
+
+ backends = (BACKEND_MLX, BACKEND_TORCH)
+ levels = preferences.default_effort_levels(BACKEND_MLX)
+ levels[0] = {"name": "Preferred", "model": "example/preferred"}
+ prefs = preferences.write_defaults({
+ "effort_levels": {BACKEND_MLX: levels},
+ "search_depth": [1, 2, 3, 4, 5],
+ "router_models": {BACKEND_MLX: "example/router"},
+ })
+ old_levels = [
+ {"name": "Old", "model": "example/old", "retrieval": i + 6}
+ for i in range(5)
+ ]
+ for name, old_effort in (
+ ("explicit_depth", json.dumps({
+ BACKEND_MLX: old_levels, "search_depth": [11] * 5,
+ "router": {BACKEND_MLX: "example/old-router"},
+ })),
+ ("inferred_depth", json.dumps({BACKEND_MLX: old_levels})),
+ ("malformed", "{invalid"),
+ ):
+ with self.subTest(sidecar=name):
+ project = self.root / name
+ project.mkdir()
+ original = initialize_project(project, "code")
+ sidecars = {
+ project / "effort_levels.json": old_effort,
+ project / "model_choices.json": (
+ "{invalid" if name == "malformed" else json.dumps({
+ prefs["effort_levels"][BACKEND_TORCH][0]["model"]:
+ "example/old-replacement",
+ })
+ ),
+ }
+ for path, contents in sidecars.items():
+ path.write_text(contents, encoding="utf-8")
+ saved_files = {path: path.read_bytes() for path in sidecars}
+ profile_path = project / "profile.ini"
+ before = profile_path.read_bytes()
+ for backend in backends:
+ self.assertEqual(
+ model_settings.read_effort_levels(project, backend),
+ prefs["effort_levels"][backend],
+ )
+ self.assertEqual(model_settings.read_search_depth(project),
+ prefs["search_depth"])
+ self.assertEqual(profile_path.read_bytes(), before)
+ self.assertTrue(model_settings.save_project_settings(project))
+ self.assertEqual(open_project(project).profile,
+ original.profile)
+ self._assert_saved_settings(project, prefs)
+ after = profile_path.read_bytes()
+ self.assertFalse(model_settings.save_project_settings(project))
+ self.assertEqual(profile_path.read_bytes(), after)
+ self.assertEqual(
+ {path: path.read_bytes() for path in sidecars},
+ saved_files,
+ )
+
+ def test_saved_settings_precede_defaults_and_partial_initialization(self):
+ """Initialize missing settings without replacing explicit choices."""
+
+ project = self.root / "partial"
+ project.mkdir()
+ initialize_project(project, "code")
+ levels = preferences.default_effort_levels(BACKEND_MLX)
+ levels[0] = {"name": "Saved", "model": "example/saved"}
+ model_settings.write_effort_levels(project, BACKEND_MLX, levels)
+ model_settings.write_router_model(project, BACKEND_TORCH,
+ "example/saved-router")
+ model_settings.write_search_depth(project, [6, 7, 8, 9, 10])
+ effective = preferences.write_defaults({
+ "search_depth": [1] * 5,
+ "router_models": {BACKEND_MLX: "example/initial-router"},
+ })
+ effective["effort_levels"][BACKEND_MLX] = levels
+ effective["router_models"][BACKEND_TORCH] = "example/saved-router"
+ effective["search_depth"] = [6, 7, 8, 9, 10]
+ self.assertTrue(model_settings.save_project_settings(project))
+ self._assert_saved_settings(project, effective)
+ before = (project / "profile.ini").read_bytes()
+ new_levels = preferences.default_effort_levels(BACKEND_MLX)
+ new_levels[0] = {"name": "New", "model": "example/new"}
+ preferences.write_defaults({
+ "search_depth": [2] * 5,
+ "router_models": {BACKEND_MLX: "example/new-router"},
+ "effort_levels": {BACKEND_MLX: new_levels},
+ })
+ self.assertFalse(model_settings.save_project_settings(project))
+ self._assert_saved_settings(project, effective)
+ self.assertEqual((project / "profile.ini").read_bytes(), before)
+
+ def test_invalid_saved_settings_do_not_initialize_other_fields(self):
+ """Reject malformed present values before writing missing values."""
+
+ for index, section in enumerate((
+ "[effort.torch]\nlevel1 = Broken | example/model\n",
+ "[router]\ntorch =\n",
+ "[search]\ndepth = 1, 2, 3, 4, 0\n",
+ )):
+ with self.subTest(section=section):
+ project = self.root / str(index)
+ project.mkdir()
+ initialize_project(project, "code")
+ path = project / "profile.ini"
+ with path.open("a", encoding="utf-8") as stream:
+ stream.write("\n" + section)
+ before = path.read_bytes()
+ with self.assertRaises(ValueError):
+ model_settings.save_project_settings(project)
+ self.assertEqual(path.read_bytes(), before)
+
+ def _assert_saved_settings(self, project, expected):
+ """Compare the saved model and search configuration to its owner."""
+
+ for backend in (BACKEND_MLX, BACKEND_TORCH):
+ self.assertEqual(
+ model_settings.read_effort_levels(project, backend),
+ expected["effort_levels"][backend],
+ )
+ self.assertEqual(
+ model_settings.read_router_model(project, backend),
+ expected["router_models"][backend],
+ )
+ self.assertEqual(model_settings.read_search_depth(project),
+ expected["search_depth"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/kilin/gui/test_preferences.py b/tests/kilin/gui/test_preferences.py
index 16fb3609..5fb5432e 100644
--- a/tests/kilin/gui/test_preferences.py
+++ b/tests/kilin/gui/test_preferences.py
@@ -128,7 +128,10 @@ def test_preferences_can_override_one_backend(self) -> None:
def test_invalid_preferences_are_not_silently_replaced(self) -> None:
"""Preserve malformed data and identify the offending setting."""
+ old_levels = preferences.default_effort_levels("mlx")
+ old_levels[0]["retrieval"] = 5
invalid = (
+ json.dumps({"effort_levels": {"mlx": old_levels}}),
"not JSON",
"[]",
'{"unrecognized": true}',
@@ -160,6 +163,20 @@ def test_invalid_update_does_not_create_or_mutate_file(self) -> None:
with self.assertRaises(ValueError):
preferences.write_defaults({"router_models": {"bad": "id"}})
self.assertEqual(self.path.read_bytes(), original)
+ # A current preference update must not silently discard extra keys.
+ levels = preferences.default_effort_levels("mlx")
+ for record in (
+ {"name": "Light"},
+ dict(levels[0], retrieval=5),
+ dict(levels[0], unknown=True),
+ dict(levels[0], name="Light | deep"),
+ ):
+ with self.subTest(record=record):
+ with self.assertRaises(ValueError):
+ preferences.write_defaults({
+ "effort_levels": {"mlx": [record, *levels[1:]]},
+ })
+ self.assertEqual(self.path.read_bytes(), original)
def test_packaged_file_and_alias_cannot_be_write_targets(self) -> None:
"""Prevent direct and symbolic-link writes to shipped resources."""
diff --git a/tests/kilin/test_model_settings.py b/tests/kilin/test_model_settings.py
index b0ec7e5e..d15010df 100644
--- a/tests/kilin/test_model_settings.py
+++ b/tests/kilin/test_model_settings.py
@@ -1,7 +1,7 @@
"""Verify core-owned router configuration without GUI or loaded models.
-Use temporary project settings to exercise precedence, legacy input,
-validation, and atomic persistence independently of desktop preferences.
+Use temporary project settings to exercise precedence, obsolete-file
+isolation, validation, and atomic persistence independently of the GUI.
"""
@@ -61,55 +61,35 @@ def test_core_defaults_match_shipped_gui_defaults(self) -> None:
)
self.assertNotIn("[router]", self.profile.read_text())
- def test_saved_router_precedes_override_default_and_legacy(self) -> None:
- """Saved router IDs are authoritative for core and GUI users."""
+ def test_saved_router_precedes_override_default(self) -> None:
+ """Use initial choices only for backends without a saved router."""
- (self.root / "effort_levels.json").write_text(
- json.dumps({"router": {BACKEND_MLX: "example/legacy"}}),
- encoding="utf-8",
- )
- self.assertEqual(
- model_settings.read_router_model(self.root, BACKEND_MLX),
- "example/legacy",
- )
- model_settings.write_router_model(
- self.root, BACKEND_MLX, " example/saved "
- )
- for reader in (model_settings.read_router_model,
- gui_settings.read_router_model,
- kilin.read_router_model):
- self.assertEqual(
- reader(
- self.root, BACKEND_MLX,
- default_model="example/application",
- ),
- "example/saved",
- )
- self.assertEqual(
- model_settings.read_router_model(self.root, BACKEND_TORCH),
- model_settings.default_router_model(BACKEND_TORCH),
- )
-
- def test_gui_preference_initializes_missing_saved_router(self) -> None:
- """An initial preference does not override a saved model."""
-
- self.assertEqual(
- model_settings.read_router_model(
- self.root, BACKEND_TORCH,
- default_model="example/gui-preference",
- ),
- "example/gui-preference",
- )
- model_settings.write_router_model(
- self.root, BACKEND_TORCH, "example/project"
- )
- self.assertEqual(
- model_settings.read_router_model(
- self.root, BACKEND_TORCH,
- default_model="example/gui-preference",
- ),
- "example/project",
- )
+ for backend in (BACKEND_MLX, BACKEND_TORCH):
+ with self.subTest(backend=backend):
+ self.assertEqual(
+ model_settings.read_router_model(self.root, backend),
+ model_settings.default_router_model(backend),
+ )
+ self.assertEqual(
+ model_settings.read_router_model(
+ self.root, backend,
+ default_model="example/application",
+ ),
+ "example/application",
+ )
+ model_settings.write_router_model(
+ self.root, backend, " example/saved "
+ )
+ for reader in (model_settings.read_router_model,
+ gui_settings.read_router_model,
+ kilin.read_router_model):
+ self.assertEqual(
+ reader(
+ self.root, backend,
+ default_model="example/application",
+ ),
+ "example/saved",
+ )
def test_atomic_write_preserves_unrelated_options(self) -> None:
"""Editing the router must not change other project options."""
@@ -157,24 +137,38 @@ def test_invalid_configuration_is_rejected_without_writes(self) -> None:
with self.assertRaises(ValueError):
model_settings.read_router_model(self.root, BACKEND_MLX)
- def test_legacy_configuration_does_not_modify_project(self) -> None:
- """Read legacy router settings without performing migration."""
+ def test_obsolete_router_file_is_ignored_without_writes(self) -> None:
+ """Ignore valid and malformed sidecars, including saved routers."""
old = self.root / "effort_levels.json"
- old.write_text(
+ for contents in (
json.dumps({"router": {BACKEND_TORCH: "example/old"}}),
- encoding="utf-8",
+ "{invalid",
+ ):
+ with self.subTest(contents=contents):
+ old.write_text(contents, encoding="utf-8")
+ before = self.profile.read_bytes()
+ old_before = old.read_bytes()
+ self.assertEqual(
+ model_settings.read_router_model(self.root, BACKEND_TORCH),
+ model_settings.default_router_model(BACKEND_TORCH),
+ )
+ self.assertEqual(
+ model_settings.read_router_model(
+ self.root, BACKEND_TORCH,
+ default_model="example/application",
+ ),
+ "example/application",
+ )
+ self.assertEqual(self.profile.read_bytes(), before)
+ self.assertEqual(old.read_bytes(), old_before)
+ model_settings.write_router_model(
+ self.root, BACKEND_TORCH, "example/saved"
)
- profile_before = self.profile.read_bytes()
self.assertEqual(
model_settings.read_router_model(self.root, BACKEND_TORCH),
- "example/old",
+ "example/saved",
)
- self.assertEqual(self.profile.read_bytes(), profile_before)
- self.assertTrue(old.exists())
- old.write_text("{invalid", encoding="utf-8")
- with self.assertRaises(json.JSONDecodeError):
- model_settings.read_router_model(self.root, BACKEND_TORCH)
if __name__ == "__main__":
From 8c39da4c70720c496e752f35c3abfc4ecae5fec8 Mon Sep 17 00:00:00 2001
From: Giovanni Volpe
Date: Wed, 2 Dec 2026 15:05:35 +0100
Subject: [PATCH 7/9] Current workspace selection and attachment UI
Remove obsolete workspace discovery and historical attachment compatibility.
- Remove discovery of former installed-application workspace directories.
- Remove the legacy projects-folder bridge action, event field, and frontend controls.
- Preserve explicit folder selection, saved preferences, environment overrides, platform defaults, and missing-folder recovery.
- Preserve existing project files without automatic movement, migration, or deletion.
- Recognize only the current managed-source attachment grammar.
- Display historical and malformed attachment lists literally, without creating workspace actions.
- Consolidate obsolete discovery tests while retaining current workspace-selection, attachment, and protocol coverage.
- Update configuration, GUI architecture, protocol, and user documentation.
---
docs/configuration.md | 11 +-
docs/gui_architecture.md | 3 +
docs/gui_protocol.md | 2 +-
kilin/gui/README.md | 18 +--
kilin/gui/_paths.py | 73 ---------
kilin/gui/web/app.js | 67 +++------
kilin/gui/web/index.html | 4 -
kilin/gui/window.py | 31 +---
tests/kilin/gui/test__attachments_frontend.py | 41 ++++--
.../gui/test__paths__storage_transition.py | 138 ++++++------------
.../gui/test__projects_folder_frontend.py | 35 +++--
tests/kilin/gui/test__protocol.py | 40 ++---
12 files changed, 142 insertions(+), 321 deletions(-)
diff --git a/docs/configuration.md b/docs/configuration.md
index 1413c3f1..d19843d9 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -608,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 ce168d0f..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
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/kilin/gui/README.md b/kilin/gui/README.md
index 964a6f21..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.
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/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.