You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by wu...@apache.org on 2026/10/18 14:00:45 UTC

(skywalking-ai-sessionizer) 01/01: Fix five findings of the 0.6.0 review in collection, metrics and the plugin

This is an automated email from the ASF dual-hosted git repository.

wu-sheng pushed a commit to branch fix/claude-code-review
in repository https://gitbox.apache.org/repos/asf/skywalking-ai-sessionizer.git

commit f92752d33d12ea278ddf6bcb50cc855d9fdfb98b
Author: Wu Sheng <wu...@foxmail.com>
AuthorDate: Sun Oct 18 20:01:42 2026 +0800

    Fix five findings of the 0.6.0 review in collection, metrics and the plugin
    
    The plugin removes an output file it has not written to for retention.ttl,
    and writes a new one at the same path when the session goes on. The changes
    adapter read the new file against the old cursor. That was a truncation or
    digest conflict, and the conflict is kept, so nothing more from the path was
    collected, its change records and MCP execution records included. The cursor
    of a plugin file now records head_sha256, the digest of the file's first
    line, read on every pass. A file that begins with another line is a later
    file, read from its start behind a cursor named for the path and the earlier
    first line, also when it has the old inode and the old length. A file
    rewritten behind its cursor still begins with its first line and is still a
    conflict. A cursor that read lines before 0.6.0 has no head and is given
    none.
    
    A later file, and the same path under a second recorder root, lands under a
    src of its own: the path, #, and the start of its first line's digest, and
    its cursor's source names it. asz verify checked a stream's changes or
    execution files as one source against <kind>.cursor alone, so a second
    source read as lines landed twice and as byte gaps, and a lost file of it
    was not found. It now checks each src apart against its own cursor, through
    skeletons too. The cursor names live in storage beside the second source's:
    LaterCursorName for a later file, MarkedSource and SourcePath for the mark.
    asz repack writes a relative origin again for the new root and renames the
    cursors named for it; it now renames a later file's cursor too, and reads a
    marked cursor's path without its mark, or collection into the new root read
    those files from their start.
    
    The token metric read on into the next landed file only until the first
    record of no call, such as a tool result. A call's own tool results sit
    between its fragments, so a main-stream call cut at a file boundary counted
    in an earlier fragment's minute, and at the look-back edge it could be left
    out. A record of no call no longer stops the reading, a fragment of another
    call does, and the file's last call is read on also when the file ends with
    a tool result. Under a watching collector such a file waits the grace for
    its next file, as a file that ends at a fragment does.
    
    A tool result whose content held a text block and an image, with no
    toolUseResult object, landed only the text. Content that holds anything but
    text blocks now also travels whole as the part's data.
    
    The plugin's scan suppressed a read error and recorded every file under a
    directory it could not read, or a file it could not read, as deleted, with
    the record's coverage complete. Restoring access recorded them as created.
    Such a path now keeps what the scan before saw, the step names it, and the
    record says coverage partial with a gap that names it. The stat cache also
    compares the change time, which chmod moves, so a file made unreadable is
    read again and found so.
    
    The plugin internals page named the plugin asz-changes and its data
    directory, run from a checkout, asz-changes-inline. The manifest names it
    file-changes, so the directory is file-changes-inline.
---
 docs/en/adapters/claude-code-plugin.md             |  19 +-
 docs/en/adapters/claude-code.md                    |  14 +-
 docs/en/changes/changes.md                         |  47 ++-
 docs/en/formats/otlp.md                            |  31 +-
 docs/en/formats/session-data.md                    |   9 +-
 docs/en/formats/storage-root.md                    |  47 ++-
 internal/adapters/claudecode/convert.go            |  30 +-
 internal/adapters/claudecode/result_test.go        | 147 +++++++
 internal/adapters/claudecodechanges/collect.go     | 126 +++++-
 .../adapters/claudecodechanges/collect_test.go     | 452 +++++++++++++++++++--
 internal/metrics/completion_test.go                | 133 ++++++
 internal/metrics/metrics.go                        |  53 ++-
 internal/metrics/metrics_test.go                   |  21 +-
 internal/repack/repack.go                          |  58 ++-
 internal/storage/cursor.go                         |  43 ++
 internal/storage/cursorname_test.go                |  67 +++
 internal/verify/session.go                         |  50 ++-
 internal/verify/verify.go                          | 149 ++++++-
 plugins/claude-code/internal/capture/capture.go    |  26 ++
 plugins/claude-code/internal/scan/ctime_darwin.go  |  33 ++
 plugins/claude-code/internal/scan/ctime_linux.go   |  33 ++
 plugins/claude-code/internal/scan/ctime_other.go   |  27 ++
 plugins/claude-code/internal/scan/scan.go          |  63 ++-
 plugins/claude-code/internal/scan/scan_test.go     |  67 +++
 plugins/claude-code/main_test.go                   |  55 +++
 tests/chain/repack_test.go                         | 110 ++++-
 26 files changed, 1757 insertions(+), 153 deletions(-)

diff --git a/docs/en/adapters/claude-code-plugin.md b/docs/en/adapters/claude-code-plugin.md
index 2fe4198..ebe94e9 100644
--- a/docs/en/adapters/claude-code-plugin.md
+++ b/docs/en/adapters/claude-code-plugin.md
@@ -1,8 +1,9 @@
 # Claude Code Plugin Internals
 
 How the [Claude Code plugin](../setup/claude-code-plugin.md) decides what to record, what it writes,
-and what was verified. The plugin is named `asz-changes`. Its code is under `plugins/claude-code/`,
-and what Claude Code installs, the manifest and the hooks, is under `plugins/claude-code/plugin/`.
+and what was verified. The plugin is named `file-changes`, and the program its hooks run is
+`asz-changes`. Its code is under `plugins/claude-code/`, and what Claude Code installs, the manifest
+and the hooks, is under `plugins/claude-code/plugin/`.
 
 ## What is recorded, and by whom
 
@@ -226,11 +227,19 @@ runs them now.
 ## What a scan is
 
 A scan walks the root under the exclusion rules and hashes what it finds. A file whose size,
-modification time and inode are as the last scan saw them keeps its hash, unless its
+modification time, inode and change time are as the last scan saw them keeps its hash, unless its
 modification time falls within the last scan's own second, when it is hashed again because the
-clock cannot tell. Every scan appends a step to the root's chain: which paths changed and from
+clock cannot tell. `chmod` changes a file's change time and none of the others, so a file made
+unreadable is read again and found so. On Windows the plugin reads no change time, so there a file
+whose access was taken away is found only once its size or its modification time changes. Every scan appends a step to the root's chain: which paths changed and from
 what hash to what. A window is the span of steps between its two scans.
 
+A path the scan finds gone is deleted. A directory or a file that is there and that the scan cannot
+read, as after a command ran `chmod 000` on it, is not observed. The step names it, the manifest
+keeps what the scan before saw under it, and the record of each window whose scans could not read
+it says `coverage: partial`, with a gap that names the path. Its files are not recorded as deleted
+when it becomes unreadable, nor as created when it can be read again.
+
 Two tools open at once on one root, two subagents say, see each other. A file changed in a step
 only one window spans is that window's alone; one changed in a step both span is `shared`, and
 each record names the other under `overlaps`. Nothing claims who wrote a byte: a person or an
@@ -299,7 +308,7 @@ first on `PATH` and load the plugin's directory for one session:
 PATH="$PWD/bin:$PATH" claude --plugin-dir plugins/claude-code/plugin
 ```
 
-Its data directory is `asz-changes-inline`.
+Its data directory is `file-changes-inline`.
 
 `asz-changes status`, with `CLAUDE_PLUGIN_DATA` set, prints the settings in force and the
 exclusion rules they expand to.
diff --git a/docs/en/adapters/claude-code.md b/docs/en/adapters/claude-code.md
index 3fbe6b6..aaa5c85 100644
--- a/docs/en/adapters/claude-code.md
+++ b/docs/en/adapters/claude-code.md
@@ -704,14 +704,16 @@ signatures are 13.3% of the bytes and wrap 0.1 MB of reasoning text.
 **A tool result's content is not always a string.** Over 20,000 `tool_result` records: string 19,707,
 list of image 124, list of text 104, list of `tool_reference` 92. `tool_reference` is an undocumented
 block, `{"type":"tool_reference","tool_name":"Monitor"}`, 194 in the corpus. A `result` takes its
-`text` from the string, or from the text blocks joined. When there is no text, the part keeps the raw
-content as `data`, because the source can be pruned and the landed copy may be the only one. A
-reader that treats the content as a string loses the image and reference results.
+`text` from the string, or from the text blocks joined. When there is no text, or the list holds a
+block that is not text, such as an image beside a caption, the part keeps the raw content as `data`
+too, because the source can be pruned and the landed copy may be the only one. A reader that treats
+the content as a string loses the image and reference results.
 
 **A Claude Code result carries `text` and `data` together.** When the record carries a
-`toolUseResult` object, the whole object becomes the result part's `data`, beside the text. Both are
-kept on purpose. `toolUseResult` has a different shape for each tool, 49 distinct key sets across the
-corpus, which flattening would lose, and it has detail the block lacks: stdout and stderr apart, a
+`toolUseResult` object, the whole object becomes the result part's `data`, beside the text, in place
+of any raw content. Both are kept on purpose. `toolUseResult` has a different shape for each tool,
+49 distinct key sets across the corpus, which flattening would lose, and it has detail the block
+lacks: stdout and stderr apart, a
 patch, a status. It is also the only full copy of long output. Among 516 records whose output spilled
 to a file, the content block was shorter than `toolUseResult.stdout` by about 28 KB where it had been
 cut. The cost is the `toolUseResult` copy in the table above, 7.6% of the bytes. An `Edit` or
diff --git a/docs/en/changes/changes.md b/docs/en/changes/changes.md
index 9aa49ad..9d26540 100644
--- a/docs/en/changes/changes.md
+++ b/docs/en/changes/changes.md
@@ -160,6 +160,20 @@
   [Claude Code Provider Bodies](../adapters/claude-code-provider-bodies.md). A body landed before
   this carries no list.
 
+- A tool result that holds an image beside its text keeps the image. The text blocks became the
+  result's text, and when the record had no `toolUseResult` object the rest of the content was
+  dropped with nothing saying so. Content that holds anything but text blocks now travels whole as
+  the result's `data`, beside the text, as content with no text did. A session collected before
+  this keeps the loss, because landed records are never rewritten.
+
+- The Claude Code plugin records a directory or a file it cannot read as not observed. After a
+  command ran `chmod 000` on a directory, the next scan recorded every file under it as deleted,
+  with the record's coverage complete, and making it readable again recorded them as created. The
+  scan now keeps what it saw there before, and the record says `coverage: partial`, with a gap that
+  names the path. A file the scan had seen unchanged is read again when its change time moved, as
+  `chmod` moves it, so a file made unreadable is found too; on Windows the plugin reads no change
+  time. See [What a scan is](../adapters/claude-code-plugin.md#what-a-scan-is).
+
 ## MCP calls
 
 - A call to an MCP server names its server and its tool. Claude Code calls an MCP tool
@@ -351,12 +365,29 @@
   Only `<kind>.cursor` was carried, so collection into the new root read the other sources again
   from their start and landed their records again. Each cursor's `last_seq` now names the new file
   holding the last record its own source landed. A recorder inside the storage root writes its
-  cursors' `origin` relative to it; a repack writes that origin, and the name of a cursor made from
-  it, as a collector into the new root computes them, or that recorder was read from its start.
+  cursors' `origin` relative to it; a repack writes that origin, and the name of each cursor made
+  from it, a second source's or a later file's the plugin wrote at a path, as a collector into the
+  new root computes them, or that recorder was read from its start.
 - `asz repack` cuts the records of two files into one only when the files are next to each other in
   their directory and their headers are the same apart from `seq` and `at`. A file took the header
   of the first file its records came from, so records of another source or another adapter version
   landed under the wrong header.
+- A plugin file the plugin removed and wrote again is collected. The plugin removes an output file
+  it has not written to for `retention.ttl`, and writes a new one at the same path when the session
+  goes on. Read against the old file's cursor, the new file was a conflict, and nothing more from
+  that path was collected, its workspace changes and calls to MCP servers included. The cursor of a
+  plugin file now records the digest of the file's first line, read on every pass, and a file that
+  begins with another line is read from its start behind a cursor of its own, even one of the same
+  length over the inode the old file had. It lands under a `src` of its own, the path followed by
+  `#` and the start of that digest, and so does the same path under a second recorder root. A file
+  rewritten behind its cursor still begins with its first line, and is still a conflict. A cursor
+  that read lines before this has no such digest, so for it a file written again is still a
+  conflict. See [Pruned sources](../formats/storage-root.md#pruned-sources).
+- `asz verify` checks each source of the plugin's kinds apart. It checked a stream's `changes` or
+  `execution` files as one source, from line 1, against `<kind>.cursor` alone. A second source,
+  which numbers its lines from 1 again, read as lines landed twice and as gaps in bytes, and a lost
+  file of it was not found. Each `src` is now checked from line 1 against the cursor whose `source`
+  names it, through skeletons too. See [Session Data](../formats/session-data.md#header).
 
 ## Retention
 
@@ -496,6 +527,14 @@
   the tokens from asz. A configuration that still names the adapter loads, and an enabled entry is
   skipped with a line that says so. The spool holds only derived requests, and `spool.state` is no
   longer written.
+- A model call counts in the minute of its last fragment when a landed file boundary falls among
+  its fragments and its own tool results. Reading on into the next file stopped at the first record
+  of no call, such as a tool result. On a main transcript every fragment carries the final usage and
+  a stop reason, so the call counted in an earlier fragment's minute, and at the edge of the first
+  derivation's look-back it could be left out. A tool result no longer stops the reading, any other
+  record does, such as a fragment of another call or a person's prompt, and the file's last call is
+  read on also when the file ends with a tool result. Under a watching collector, such a file waits the grace for its next file, as a file
+  that ends at a fragment does. See [OpenTelemetry export](../formats/otlp.md).
 
 ## Development
 
@@ -705,3 +744,7 @@
 - The Claude Code adapter page said the system prompt and the tool schemas are absent from
   transcripts. That holds for the versions it was measured on, 2.1.220 to 2.1.251, and the page now
   says so. Later versions write them in two attachments, which the adapter names.
+- The [Claude Code plugin internals](../adapters/claude-code-plugin.md) page named the plugin
+  `asz-changes`, and its data directory, when run from a checkout, `asz-changes-inline`. The plugin
+  is `file-changes`, as its manifest says, so the directory is `file-changes-inline`. `asz-changes`
+  is the program its hooks run.
diff --git a/docs/en/formats/otlp.md b/docs/en/formats/otlp.md
index a0ef3c7..5b311b3 100644
--- a/docs/en/formats/otlp.md
+++ b/docs/en/formats/otlp.md
@@ -208,22 +208,27 @@ calls in a corpus of 2,970 files and 365,825 records written by Claude Code 2.1.
 is 14.5% of the calls on child streams and 0.02% of those on main transcripts, as [Provider
 calls](../adapters/claude-code.md#provider-calls) reports.
 
-A call cut at a landed file boundary is read through following transcript files of its stream
-when the file's last record is a fragment of that call. There is no one-file limit. Metadata,
-change and execution files do not interrupt the reading; the first unrelated transcript record
-does. A tool
-result carries no call id, and in the same corpus a call's own tool results sit between its
-fragments on 24% of multi-fragment calls. Such a result ends the read-ahead. An unfinished child
+A call cut at a landed file boundary is read through following transcript files of its stream.
+The call read ahead is the file's last call, whether the file ends with a fragment of it or with
+records of no call after it. There is no one-file limit. Metadata, change and execution files do
+not interrupt the reading, and neither do tool results. A tool result carries no call id, and in
+the same corpus a call's own tool results sit between its fragments on 24% of multi-fragment calls.
+Any other transcript record ends the reading: a fragment of another call, or a record of no call
+that is not a tool result, such as a person's next prompt. That is where reading the next file
+alone ends the call too, so a file never waits for a call the next file has counted. An unfinished child
 call remains eligible when its final fragment arrives later. On a main transcript every fragment
 repeats the final usage, so the call counts in full, in the minute of the last fragment read.
 
-Under a watching collector, a file whose last record is a fragment of a call not yet counted waits
-a short grace for the next file of its stream, then is derived with what it has. When a continuation
-is found, its last file starts the grace. A deferred session is retried even while other sessions
-keep changing. An unfinished call is not marked counted when the grace expires. A file that ends
-with a tool result does not wait. A single pass, the backfill over history that already exists,
-derives with what is there and never waits. A call is never counted twice, however many files its
-records reach, and a record the runtime re-emitted before a context reset is the same call again.
+Under a watching collector, a file whose last call is not counted yet waits a short grace for the
+next file of its stream when the file ends at a fragment of that call, or at tool results after
+one, since the call may go on there. Then it is derived with what it has. When a continuation is
+found, its last file starts the grace. A file whose last call is followed by any other record does
+not wait: the call is over. A deferred session is retried even while other sessions keep changing.
+An unfinished call is not marked counted when the grace expires, and a fragment of a finished call
+that lands after the grace no longer moves it. A single pass, the backfill over history that
+already exists, derives with what is there and never waits. A call is never
+counted twice, however many files its records reach, and a record the runtime re-emitted before a
+context reset is the same call again.
 
 ### Calls to MCP servers
 
diff --git a/docs/en/formats/session-data.md b/docs/en/formats/session-data.md
index 7464252..fa9c3bb 100644
--- a/docs/en/formats/session-data.md
+++ b/docs/en/formats/session-data.md
@@ -44,7 +44,7 @@ stops at the first longer line.
 | `kind` | what it was collected from: `transcript`, `agent_meta`, `journal`, `workflow_manifest`, `workflow_script`, `changes`, `execution` or `provider_body`. `otlp_log` and `otlp_span` are reserved for a push transport, and no adapter writes either. |
 | `adapter` | how the records were acquired, with its contract version |
 | `dialect` | whose schema they were read as. A push receiver and a local reader for one runtime share a dialect and nothing else. |
-| `src` | the source, relative to the adapter's source root, with forward slashes on every platform |
+| `src` | the source, relative to the adapter's source root, with forward slashes on every platform. In the `changes` and `execution` kinds, a source other than the first at its path, a later file the plugin wrote there or the same path under a second recorder root, is the path, `#`, and the first 12 hexadecimal characters of the SHA-256 of the file's first line, so each source has a `src` of its own |
 | `session`, `stream`, `batch` | the session, the execution stream (`main` or an agent id), and the group of children a workflow run started. A `provider_body` file names neither a stream nor a batch |
 
 A reader refuses a header unless `h` is `1`, `schema` is `sd/1`, and `kind`, `session`, `src` and
@@ -63,7 +63,8 @@ session under its id and puts every child stream flat under `streams/`, keyed by
 project directory a source file sits in, and the workflow directory a child's transcript sits in.
 `src` is the only place both survive. It uses forward slashes on every platform, so a root reads
 the same on the machine that collected it and on any other. With a record's `off` and `sha`, it
-lets a reader check the record against its source for as long as the source exists.
+lets a reader check the record against its source for as long as the source exists. A `src` with
+the mark described above names its file by the part before its last `#`.
 
 ## File kinds
 
@@ -130,7 +131,9 @@ document at `ord` 1 and `off` 0, so for it `asz verify` rebuilds the body instea
 files of one kind, `ord` must run 1, 2, 3 with no gap, starting at 1. The first record must start
 at byte 0, and each record after it at the byte after the previous record's line ends. Where the
 stream has an append cursor, the records must reach the line and the byte the cursor names (see
-[Append cursors](storage-root.md#append-cursors)). A skipped line, or a lost file of a source that
+[Append cursors](storage-root.md#append-cursors)). In the `changes` and `execution` kinds, a stream
+can hold more than one source, each numbering its lines from 1, so these checks apply to the files
+of each `src` apart, and each `src` is held to the cursor whose `source` names it. A skipped line, or a lost file of a source that
 is a stream of lines, would otherwise show only as a shorter conversation. The Claude Code
 adapter's `agent_meta`, `workflow_manifest` and `workflow_script` files are each one document with
 a snapshot cursor, so a lost one is found only by the round chain (see
diff --git a/docs/en/formats/storage-root.md b/docs/en/formats/storage-root.md
index b4e86b5..aeaaab2 100644
--- a/docs/en/formats/storage-root.md
+++ b/docs/en/formats/storage-root.md
@@ -156,7 +156,12 @@ came from, `at` included, and the files are numbered in the order their records
 
 Each source has one cursor, beside the files it tracks, named `<kind>.cursor`. The dot matters.
 Landed files are named `<kind>-<collected-at>-<seq>.sd`, so a cursor named with a hyphen would share
-their prefix, and a scan for one kind's files would take the cursor for data.
+their prefix, and a scan for one kind's files would take the cursor for data. A stream can hold more
+than one source of the plugin's kinds: the same session in a second plugin directory or recorder
+root, or a file the plugin wrote again at the same path (see [Pruned sources](#pruned-sources)). The
+first source keeps the plain name. Each other one has a cursor named
+`<kind>-<12 hexadecimal characters>.cursor`, which a scan for landed files passes over by its
+extension.
 
 A cursor belongs to one source rather than to the session, because a session can hold hundreds of
 sources. Measured on 2026-09-11 on one machine's storage root of 60 Claude Code sessions, the
@@ -190,13 +195,14 @@ state         active
 
 | Field | What it is for |
 | --- | --- |
-| `source` | the source path, relative to the adapter's root, with forward slashes |
-| `origin` | the adapter's root the source is under, with forward slashes: relative to the storage root when the source root lies inside it, so a root copied whole keeps its cursors, and absolute otherwise. `asz repack` writes a relative origin again for its new root, which the source root is outside, and renames the cursor named for it to match. Written since 0.5.0 by an adapter that reads more than one root, since two roots can hold one relative path. A cursor without it was written be [...]
+| `source` | the source path, relative to the adapter's root, with forward slashes. For a source of the plugin's that lands under a `src` of its own, that `src`, see [Pruned sources](#pruned-sources) |
+| `origin` | the adapter's root the source is under, with forward slashes: relative to the storage root when the source root lies inside it, so a root copied whole keeps its cursors, and absolute otherwise. `asz repack` writes a relative origin again for its new root, which the source root is outside, and renames each cursor named for it to match: a second source's, and a later file's. Written since 0.5.0 by an adapter that reads more than one root, since two roots can hold one relative  [...]
 | `dev`, `ino` | the device and the inode the file had when it was read, or on Windows its volume serial number and file index. Resuming a cursor compares `ino` alone, and it is what this page calls the file's identity: a change means the file was replaced, or is being reached another way, and the bytes decide which, see below. Claiming a cursor that carries no `origin` compares both, since that decides whether the cursor was read from this file at all and not from another with the same  [...]
 | `offset` | the bytes consumed, always at the end of a line, and where the next read starts. Compared with the file's size, it says whether anything is new. A size below it means the file was cut short. |
 | `ord` | the last source line consumed, so line numbers continue without counting again from byte 0 |
 | `last_uuid` | the id of the last record that had one. For diagnosis only: many lines carry no id, and nothing compares it. |
 | `tail_sha256` | the SHA-256 of the 1 MiB before `offset`. A mismatch means bytes already read were rewritten. |
+| `head_sha256` | the SHA-256 of the file's first line, without its newline, taken from the bytes the first read landed. Written for the plugin's files, which the plugin can remove and write again at the same path, on every cursor that has read a line since 0.6.0, see [Pruned sources](#pruned-sources). A file that does not begin with this line is another file. A cursor that read lines before 0.6.0 has none and is never given one, so the file at its path is taken to be its file, and a fil [...]
 | `size`, `mtime` | the size and modification time last seen. Recorded, never compared. |
 | `last_seq` | the sequence of the last file this source landed |
 | `state` | `active`, `source_gone` or `conflict` |
@@ -316,6 +322,41 @@ by default (see [Retention](../adapters/claude-code-plugin.md#retention)). Their
 `source_gone` only on a file that goes while a pass reads it, so the cursor of a file the plugin
 removed is left as it was.
 
+When the session goes on after that, the plugin writes a new file at the same path. Its bytes are
+not the ones the old cursor read, so read against that cursor it would be a `conflict`, and nothing
+more from the path would be collected. So the cursor of a plugin file records `head_sha256`, and a
+pass finds a file's cursor before it reads the file:
+
+1. It starts at the path's cursor, `<kind>.cursor` or the one of a second source.
+2. A cursor with no `head_sha256` takes the file. It has read nothing yet, or it was written before
+   0.6.0.
+3. Otherwise the pass reads the file's first line. When its SHA-256 is `head_sha256`, the file is
+   the cursor's file. The line is read on every pass, even when the file has the `ino` the cursor
+   recorded and a size equal to its `offset`: a file system can give a new file the inode of the
+   one removed before it, and a new file of the same length would otherwise never be read.
+4. Otherwise the file is a later one. The next cursor is `<kind>-<12 hexadecimal characters>.cursor`,
+   the first 12 hexadecimal characters of the SHA-256 of the adapter's root as `origin` writes it,
+   the source path and that `head_sha256`, joined by newlines. The pass goes back to step 2 with it.
+   A file that holds no complete line yet begins with no line, so it comes to a cursor that has read
+   nothing, and waits there for its first line.
+
+A later file is read from its start, its lines numbered from 1, behind a cursor that has read
+nothing. Nothing of the file before it is landed again: that file is gone, and the plugin writes
+each record once, so two files it writes never begin with the same line. A file rewritten behind
+its cursor still begins with the line it began with, so it stays with its cursor and is a
+`conflict` there, as [Append cursors](#append-cursors) says. A file whose first line was rewritten
+is taken for a later file.
+
+A source with a cursor other than `<kind>.cursor`, a later file at the path or the same path under
+a second recorder root, lands under a `src` of its own: the source path, `#`, and the first 12
+hexadecimal characters of its `head_sha256`. Its cursor's `source` is that `src`. Its lines number
+from 1 again, so a reader of the landed files alone tells it from the other sources of the stream,
+and `asz verify` checks each `src` of the plugin's kinds apart, as
+[Session Data](session-data.md#header) says. A skeleton keeps its file's header, and `asz repack`
+cuts the records of two files into one only when their headers are the same, so both keep it. A
+cursor that read lines before 0.6.0
+has no `head_sha256`, and its files land under the source path, as they did.
+
 A session a scenario build marked is the one case where asz deletes a source itself. Once all of
 the session is sent, a pipeline removes its source first and then the whole session directory, as
 [Retention](#retention) describes.
diff --git a/internal/adapters/claudecode/convert.go b/internal/adapters/claudecode/convert.go
index 7aaa401..bbfbbe6 100644
--- a/internal/adapters/claudecode/convert.go
+++ b/internal/adapters/claudecode/convert.go
@@ -254,11 +254,13 @@ func partOf(raw json.RawMessage, tur *toolResult, hasTUR bool) (sessiondata.Part
 		if b.IsError != nil {
 			p.Failed = b.IsError
 		}
-		// A result whose content is neither a string nor text blocks - an image,
-		// a reference to another tool's output - reads as empty otherwise. The
-		// raw content travels instead of being described, because the source it
-		// came from can be pruned and this would be the only copy.
-		if p.Text == "" && len(b.Content) > 0 {
+		// A result whose content is more than a string or text blocks - an
+		// image, a reference to another tool's output, alone or beside text -
+		// reads as its text alone otherwise, and a screenshot's image was lost
+		// that way. The raw content travels instead of being described,
+		// because the source it came from can be pruned and this would be the
+		// only copy.
+		if len(b.Content) > 0 && (p.Text == "" || !textOnly(b.Content)) {
 			p.Data = b.Content
 			p.Bytes = len(b.Content)
 		}
@@ -309,6 +311,24 @@ func resultText(content json.RawMessage) (string, int) {
 	return "", len(content)
 }
 
+// textOnly reports whether a tool result's content is text and nothing else:
+// a string, or a list of text blocks, which resultText holds whole.
+func textOnly(content json.RawMessage) bool {
+	if len(content) > 0 && content[0] == '"' {
+		return true
+	}
+	var blocks []blockOf
+	if err := json.Unmarshal(content, &blocks); err != nil {
+		return false
+	}
+	for _, b := range blocks {
+		if b.Type != "text" {
+			return false
+		}
+	}
+	return true
+}
+
 // attachmentContent returns an attachment's prose, or its whole object when it
 // has none.
 //
diff --git a/internal/adapters/claudecode/result_test.go b/internal/adapters/claudecode/result_test.go
new file mode 100644
index 0000000..cc35400
--- /dev/null
+++ b/internal/adapters/claudecode/result_test.go
@@ -0,0 +1,147 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package claudecode_test
+
+import (
+	"bytes"
+	"encoding/json"
+	"errors"
+	"io"
+	"path/filepath"
+	"strings"
+	"testing"
+
+	"github.com/apache/skywalking-ai-sessionizer/internal/adapters/claudecode"
+	"github.com/apache/skywalking-ai-sessionizer/internal/parse"
+	"github.com/apache/skywalking-ai-sessionizer/internal/storage"
+	"github.com/apache/skywalking-ai-sessionizer/pkg/sessiondata"
+)
+
+// A tool result's content is a string or a list of blocks. The text of the
+// text blocks is the part's text. Content that is more than text keeps its
+// blocks whole as the part's data, since the source can be pruned and the
+// landed copy may be the only one. A list of a text and an image, as a tool
+// that takes a screenshot returns, kept only the text: the image was in no
+// part and named in no drop.
+func TestAToolResultKeepsWhatIsNotText(t *testing.T) {
+	const image = `{"type":"image","source":{"type":"base64","media_type":"image/png","data":"iVBORw0KGgo="}}`
+	const caption = `{"type":"text","text":"Took a screenshot"}`
+	cases := []struct {
+		name, content, toolUseResult string
+		text                         string
+		data                         string // the part's data, or empty for none
+	}{
+		{"text and an image", `[` + caption + `,` + image + `]`, ``, "Took a screenshot", `[` + caption + `,` + image + `]`},
+		{"text and an image, with a list beside them", `[` + caption + `,` + image + `]`, `,"toolUseResult":[` + caption + `,` + image + `]`, "Took a screenshot", `[` + caption + `,` + image + `]`},
+		{"an image alone", `[` + image + `]`, ``, "", `[` + image + `]`},
+		{"text blocks alone", `[` + caption + `,{"type":"text","text":"and more"}]`, ``, "Took a screenshot\nand more", ``},
+		{"a string", `"Took a screenshot"`, ``, "Took a screenshot", ``},
+	}
+	var transcript strings.Builder
+	for i, tc := range cases {
+		transcript.WriteString(`{"type":"user","uuid":"u` + string(rune('1'+i)) + `","sessionId":"` + tSess + `","timestamp":"2026-09-08T10:00:01.000Z",` +
+			`"message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_s","content":` + tc.content + `}]}` +
+			tc.toolUseResult + "}\n")
+	}
+	src, root := t.TempDir(), t.TempDir()
+	mk(t, filepath.Join(src, "-proj-a", tSess+".jsonl"), transcript.String())
+	zone := storage.NewZone(root)
+	col := claudecode.New(src, zone, 0)
+	for i, want := range []int{len(cases), 0} {
+		st, err := col.CollectAll(nil)
+		if err != nil || !st.Complete() || st.Records != want {
+			t.Fatalf("pass %d: %+v err=%v; want %d records", i+1, st, err, want)
+		}
+	}
+	for i := 0; i < 2; i++ {
+		r, err := parse.Session(zone, parse.Options{Conversation: tSess, Session: tSess})
+		if err != nil {
+			t.Fatal(err)
+		}
+		if i == 1 && r.Number != 0 {
+			t.Fatalf("a second parse wrote round %d; nothing changed", r.Number)
+		}
+	}
+	landed := map[string]*sessiondata.Record{}
+	files, err := storage.LandedFiles(zone, tSess)
+	if err != nil {
+		t.Fatal(err)
+	}
+	for _, lf := range files {
+		for _, rec := range readLanded(t, lf.Path) {
+			landed[rec.ID] = rec
+		}
+	}
+	for i, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			rec := landed["u"+string(rune('1'+i))]
+			if rec == nil || len(rec.Parts) != 1 || rec.Parts[0].Kind != sessiondata.PartResult {
+				t.Fatalf("the landed record: %+v", rec)
+			}
+			p := rec.Parts[0]
+			if p.Text != tc.text {
+				t.Errorf("text %q, want %q", p.Text, tc.text)
+			}
+			if tc.data == "" {
+				if len(p.Data) != 0 {
+					t.Errorf("data %s, want none: the text is all the content holds", p.Data)
+				}
+				return
+			}
+			var want bytes.Buffer
+			if err := json.Compact(&want, []byte(tc.data)); err != nil {
+				t.Fatal(err)
+			}
+			if !bytes.Equal(p.Data, want.Bytes()) {
+				t.Errorf("data %s, want the content whole: %s", p.Data, want.Bytes())
+			}
+			if p.Bytes != len(tc.content) {
+				t.Errorf("bytes %d, want the size of the content, %d", p.Bytes, len(tc.content))
+			}
+			if len(rec.Dropped) != 0 {
+				t.Errorf("dropped %+v; nothing was left out", rec.Dropped)
+			}
+		})
+	}
+}
+
+// readLanded reads every record of a landed file, as a reader of the format
+// would.
+func readLanded(t *testing.T, path string) []*sessiondata.Record {
+	t.Helper()
+	f, err := sessiondata.Open(path)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer f.Close()
+	r, err := sessiondata.NewReader(f)
+	if err != nil {
+		t.Fatal(err)
+	}
+	var out []*sessiondata.Record
+	for {
+		rec, err := r.Next()
+		if errors.Is(err, io.EOF) {
+			return out
+		}
+		if err != nil {
+			t.Fatal(err)
+		}
+		out = append(out, rec)
+	}
+}
diff --git a/internal/adapters/claudecodechanges/collect.go b/internal/adapters/claudecodechanges/collect.go
index 4c3dc90..ef1cf5c 100644
--- a/internal/adapters/claudecodechanges/collect.go
+++ b/internal/adapters/claudecodechanges/collect.go
@@ -18,6 +18,9 @@
 package claudecodechanges
 
 import (
+	"bytes"
+	"crypto/sha256"
+	"encoding/hex"
 	"errors"
 	"fmt"
 	"io"
@@ -228,22 +231,127 @@ func (c *Collector) collectSession(s Session, st *Stats) error {
 // its offset. A root whose file is another takes a cursor of its own
 // rather than reading its file against another's position, which is the
 // conflict that stopped both for good.
+//
+// One path can also hold one file after another. The plugin removes a file
+// once it was not written to for retention.ttl, and writes a new one at the
+// same path when the session goes on. Read against the old cursor, the new
+// file was a conflict, and nothing more from that path was collected. So
+// each file at a path has a cursor of its own: see followFiles.
 func cursorFor(dir, root string, src Source) (string, error) {
 	// A landed file's name prefix is its kind, and so is its cursor's, so
 	// a stream's change file and execution file keep separate places.
 	prefix := string(src.Kind)
-	plain := filepath.Join(dir, prefix+".cursor")
-	held, err := storage.LoadCursor(plain, storage.CursorAppend, src.Rel)
+	path := filepath.Join(dir, prefix+".cursor")
+	held, err := storage.LoadCursor(path, storage.CursorAppend, src.Rel)
 	if err != nil {
 		return "", err
 	}
 	switch {
 	case held.Source == "", held.Source == src.Rel && held.Origin == root:
-		return plain, nil
 	case held.Source == src.Rel && held.Origin == "" && describes(held, src.Path):
-		return plain, nil
+	default:
+		path = filepath.Join(dir, storage.SourceCursorName(prefix, root, src.Rel))
+		if held, err = storage.LoadCursor(path, storage.CursorAppend, src.Rel); err != nil {
+			return "", err
+		}
 	}
-	return filepath.Join(dir, storage.SourceCursorName(prefix, root, src.Rel)), nil
+	return followFiles(dir, prefix, root, src, path, held)
+}
+
+// followFiles follows the cursors of one path, from the first file the path
+// held to the file it holds now. A cursor records the digest of its file's
+// first line. A file that does not begin with that line is a later file, and
+// its cursor is named for the path and that line, so it is the same name on
+// every pass. The plugin never writes a line twice, so two files it writes
+// never begin with the same line. A file rewritten behind its cursor still
+// begins with its first line, so it stays with that cursor, and is still a
+// conflict there.
+//
+// The first line is read on every pass, even when the file has the inode the
+// cursor recorded and the size it read to: a file system can give a new file
+// the inode of the one removed before it, and a new file of the same length
+// was taken for the old one and never read. A file that holds no complete
+// line yet is not the file of a cursor that read one, so it goes to a cursor
+// of its own, which waits for that line.
+func followFiles(dir, prefix, root string, src Source, path string, cur *storage.Cursor) (string, error) {
+	var head string
+	read := false
+	seen := map[string]bool{}
+	for cur.HeadSHA256 != "" {
+		if !read {
+			h, err := firstLine(src.Path)
+			if errors.Is(err, os.ErrNotExist) {
+				// The file went after discovery listed it. TailAppend says
+				// so, behind the cursor it had.
+				return path, nil
+			}
+			if err != nil {
+				return "", err
+			}
+			head, read = h, true
+		}
+		if head == cur.HeadSHA256 {
+			return path, nil
+		}
+		seen[path] = true
+		path = filepath.Join(dir, storage.LaterCursorName(prefix, root, src.Rel, cur.HeadSHA256))
+		if seen[path] {
+			return "", fmt.Errorf("claudecodechanges: the cursors of %s name each other in a loop at %s", src.Rel, path)
+		}
+		var err error
+		if cur, err = storage.LoadCursor(path, storage.CursorAppend, src.Rel); err != nil {
+			return "", err
+		}
+	}
+	return path, nil
+}
+
+// landedSrc is the src a source's files land with. The first source at a
+// path lands under the path. A later file at the path, or the same path under
+// a second recorder root, has a cursor of its own, and lands under the path
+// marked with its first line, see storage.MarkedSource. Its records number
+// their lines from 1 again, so without its own src a reader of the landed
+// files took them for lines landed twice. A cursor with no first line has
+// read nothing yet, or read before 0.6.0, when its files landed under the
+// path.
+func landedSrc(src Source, cursorPath string, cur *storage.Cursor) string {
+	if filepath.Base(cursorPath) == string(src.Kind)+".cursor" || cur.HeadSHA256 == "" {
+		return src.Rel
+	}
+	return storage.MarkedSource(src.Rel, cur.HeadSHA256)
+}
+
+// firstLine is the digest of a file's first line without its newline, or ""
+// when the file holds no complete line yet. It is read in pieces, since one
+// line can be several megabytes.
+func firstLine(path string) (string, error) {
+	f, err := os.Open(path)
+	if err != nil {
+		return "", err
+	}
+	defer f.Close()
+	h := sha256.New()
+	buf := make([]byte, 64<<10)
+	for {
+		n, err := f.Read(buf)
+		if i := bytes.IndexByte(buf[:n], '\n'); i >= 0 {
+			h.Write(buf[:i])
+			return hex.EncodeToString(h.Sum(nil)), nil
+		}
+		h.Write(buf[:n])
+		if errors.Is(err, io.EOF) {
+			return "", nil
+		}
+		if err != nil {
+			return "", err
+		}
+	}
+}
+
+// lineDigest is the digest firstLine gives for a file that begins with b.
+func lineDigest(b []byte) string {
+	sum := sha256.Sum256(b)
+	return hex.EncodeToString(sum[:])
 }
 
 // describes reports whether a cursor that names no root was read from this
@@ -329,12 +437,17 @@ func (c *Collector) collectSource(src Source, ix *index.Index, state *storage.Se
 		return false, false, nil
 	}
 
+	// The first line is taken from the bytes read, not from the file now,
+	// which may already be a later one.
+	if cur.HeadSHA256 == "" && chunk.Lines[0].Off == 0 {
+		cur.HeadSHA256 = lineDigest(chunk.Lines[0].Bytes)
+	}
 	seq := state.Take()
 	name := storage.LandedName(string(src.Kind), storage.Stamp(now), seq)
 	hdr := &sessiondata.Header{
 		H: 1, Seq: seq, At: now.UTC().Format(time.RFC3339Nano),
 		Kind: src.Kind, Adapter: Name + "/" + Version, Dialect: Dialect,
-		Src: src.Rel, Session: src.Session, Stream: src.Stream,
+		Src: landedSrc(src, cursorPath, cur), Session: src.Session, Stream: src.Stream,
 	}
 	// A record is larger than its line, so the file ends where the converted
 	// records reach the budget, and the cursor stops before the first line
@@ -388,6 +501,7 @@ func (c *Collector) collectSource(src Source, ix *index.Index, state *storage.Se
 	if err != nil && !os.IsNotExist(err) {
 		return true, false, err
 	}
+	cur.Source = hdr.Src
 	cur.Dev, cur.Ino = chunk.Dev, chunk.Ino
 	cur.Offset, cur.Ord = chunk.NewOffset, chunk.NewOrd
 	cur.LastUUID, cur.TailSHA256 = chunk.LastUUID, digest
diff --git a/internal/adapters/claudecodechanges/collect_test.go b/internal/adapters/claudecodechanges/collect_test.go
index 33486ca..7b58ed0 100644
--- a/internal/adapters/claudecodechanges/collect_test.go
+++ b/internal/adapters/claudecodechanges/collect_test.go
@@ -23,6 +23,8 @@ import (
 	"io"
 	"os"
 	"path/filepath"
+	"reflect"
+	"slices"
 	"sort"
 	"strings"
 	"testing"
@@ -31,8 +33,13 @@ import (
 	"github.com/apache/skywalking-ai-sessionizer/internal/adapters/claudecode"
 	"github.com/apache/skywalking-ai-sessionizer/internal/adapters/claudecodechanges"
 	"github.com/apache/skywalking-ai-sessionizer/internal/index"
+	"github.com/apache/skywalking-ai-sessionizer/internal/parse"
+	"github.com/apache/skywalking-ai-sessionizer/internal/repack"
+	"github.com/apache/skywalking-ai-sessionizer/internal/retention"
 	"github.com/apache/skywalking-ai-sessionizer/internal/storage"
+	"github.com/apache/skywalking-ai-sessionizer/internal/verify"
 	"github.com/apache/skywalking-ai-sessionizer/pkg/changes"
+	"github.com/apache/skywalking-ai-sessionizer/pkg/execution"
 	"github.com/apache/skywalking-ai-sessionizer/pkg/sessiondata"
 )
 
@@ -339,21 +346,9 @@ func TestALegacyCursorBelongsToTheRootWhoseFileItDescribes(t *testing.T) {
 	if st, err := a.CollectAll(all); err != nil || st.Records != 1 {
 		t.Fatalf("a: %+v err=%v", st, err)
 	}
-	// The cursor as 0.4.0 wrote it: no origin.
+	// The cursor as 0.4.0 wrote it: no origin, and no head.
 	cursor := filepath.Join(zone.StreamDir(session, "main"), "changes.cursor")
-	raw, err := os.ReadFile(cursor)
-	if err != nil {
-		t.Fatal(err)
-	}
-	var kept []string
-	for _, l := range strings.Split(string(raw), "\n") {
-		if !strings.HasPrefix(l, "origin") {
-			kept = append(kept, l)
-		}
-	}
-	if err := os.WriteFile(cursor, []byte(strings.Join(kept, "\n")), 0o644); err != nil {
-		t.Fatal(err)
-	}
+	dropKeys(t, cursor, "origin", "head_sha256")
 	// The other root reads the same relative path first. The cursor does
 	// not describe its file, so it takes one of its own and lands whole.
 	b := claudecodechanges.New(rootB, zone, 0)
@@ -411,24 +406,16 @@ func TestALegacyCursorIsNotClaimedOnASharedTailAlone(t *testing.T) {
 			break
 		}
 	}
+	// The cursor as 0.4.0 wrote it: no origin, and no head. With a head,
+	// the other root's first line alone would send it to another cursor,
+	// and the test would pass whatever the claim decided.
 	cursor := filepath.Join(zone.StreamDir(session, "main"), "changes.cursor")
-	raw, err := os.ReadFile(cursor)
+	dropKeys(t, cursor, "origin", "head_sha256")
+	held, err := storage.LoadCursor(cursor, storage.CursorAppend, "")
 	if err != nil {
 		t.Fatal(err)
 	}
-	var kept []string
-	var offset int64
-	for _, l := range strings.Split(string(raw), "\n") {
-		if strings.HasPrefix(l, "offset") {
-			fmt.Sscanf(strings.TrimSpace(strings.TrimPrefix(l, "offset")), "%d", &offset)
-		}
-		if !strings.HasPrefix(l, "origin") {
-			kept = append(kept, l)
-		}
-	}
-	if err := os.WriteFile(cursor, []byte(strings.Join(kept, "\n")), 0o644); err != nil {
-		t.Fatal(err)
-	}
+	offset := int64(held.Offset)
 	// The precondition: at a's offset, the bytes before it digest the same
 	// in both files, so the bytes alone cannot tell the two apart.
 	da, errA := claudecode.TailDigestAt(fileA, offset)
@@ -518,3 +505,412 @@ func TestALargeChangeRecordKeepsItsIdentity(t *testing.T) {
 		t.Fatalf("the index counts %d added lines, want 2002", adds)
 	}
 }
+
+// executionLine is one execution record the plugin writes after a call to an
+// MCP server.
+func executionLine(id string) string {
+	ms := int64(12)
+	r := &execution.Record{Schema: execution.Schema, ID: id + "/" + execution.BoundaryClientHook,
+		ObservedBy: execution.ObservedByASZPlugin, Boundary: execution.BoundaryClientHook,
+		Session: session, Stream: "main", Tool: "toolu_" + id, ToolName: "mcp__docs__read", Protocol: execution.ProtocolMCP,
+		Server: &execution.Server{Name: "docs", Source: "user"}, Time: "2026-09-08T02:00:04Z",
+		DurationMS: &ms, Outcome: execution.OutcomeReturned}
+	b, _ := r.Marshal()
+	return string(b) + "\n"
+}
+
+// The plugin removes an output file once it was not written to for
+// retention.ttl, and writes a new one at the same path when the session goes
+// on. The old cursor's position means nothing in the new file: a shorter file
+// read against it was a truncation conflict, a longer one a digest conflict,
+// and either stopped the path for good. A file that does not begin with the
+// line its cursor's file began with is another file. It is read from its
+// start behind a cursor of its own, and nothing of the file before it is
+// landed again.
+func TestAFileThePluginWritesAgainIsCollectedFromItsStart(t *testing.T) {
+	for _, tc := range []struct {
+		kind sessiondata.Kind
+		file string
+	}{
+		{sessiondata.KindChanges, "main.jsonl"},
+		{sessiondata.KindExecution, "main.execution.jsonl"},
+	} {
+		t.Run(string(tc.kind), func(t *testing.T) {
+			src := t.TempDir()
+			rel := "file-changes-inline/output/" + session + "/" + tc.file
+			path := filepath.Join(src, filepath.FromSlash(rel))
+			zone := storage.NewZone(t.TempDir())
+			c := claudecodechanges.New(src, zone, 0)
+			rec := func(ids ...string) string {
+				var out string
+				for _, id := range ids {
+					if tc.kind == sessiondata.KindExecution {
+						out += executionLine(id)
+					} else {
+						out += line(id, "main", "toolu_"+id, "/w")
+					}
+				}
+				return out
+			}
+			pass := func(what string, want int) {
+				t.Helper()
+				st, err := c.CollectAll(nil)
+				if err != nil || !st.Complete() || st.Records != want {
+					t.Fatalf("%s: %+v err=%v; want %d records and a complete pass", what, st, err, want)
+				}
+				if st, err := c.CollectAll(nil); err != nil || !st.Complete() || st.Records != 0 {
+					t.Fatalf("%s, again: %+v err=%v; want nothing", what, st, err)
+				}
+			}
+			// As the plugin's retention does: the file, then its session's
+			// directory, which holds nothing else.
+			again := func(ids ...string) {
+				t.Helper()
+				if err := os.Remove(path); err != nil {
+					t.Fatal(err)
+				}
+				if err := os.Remove(filepath.Dir(path)); err != nil {
+					t.Fatal(err)
+				}
+				appendTo(t, path, rec(ids...))
+			}
+			appendTo(t, path, rec("a1", "a2", "a3"))
+			pass("the first file", 3)
+			// The same length over the same inode, as a file system that
+			// gives a new file the number the removed one had: only the
+			// first line tells the two apart.
+			if err := os.WriteFile(path, []byte(rec("d1", "d2", "d3")), 0o644); err != nil {
+				t.Fatal(err)
+			}
+			pass("a file of the same length over the same inode", 3)
+			again("b1")
+			pass("a shorter file at the same path", 1)
+			appendTo(t, path, rec("b2"))
+			pass("the third file's next line", 1)
+			again("c1", "c2", "c3", "c4")
+			pass("a longer file at the same path", 4)
+
+			s := claudecodechanges.Session{ID: session, Sources: []claudecodechanges.Source{{
+				Path: path, Rel: rel, Session: session, Stream: "main", Kind: tc.kind}}}
+			if ok, reason, err := c.Covered(s); err != nil || !ok {
+				t.Fatalf("the fourth file is landed to its end, but Covered says %v %q %v", ok, reason, err)
+			}
+			var ids []string
+			srcs := map[string]bool{}
+			for _, f := range landedFiles(t, zone) {
+				hdr, recs := readAll(t, f.Path)
+				srcs[hdr.Src] = true
+				if hdr.Src != rel && !strings.HasPrefix(hdr.Src, rel+"#") {
+					t.Fatalf("a file lands with src %q; want %q, or it with a mark", hdr.Src, rel)
+				}
+				for _, r := range recs {
+					ids = append(ids, strings.TrimSuffix(r.ID, "/"+execution.BoundaryClientHook))
+				}
+			}
+			if got := strings.Join(ids, " "); got != "a1 a2 a3 d1 d2 d3 b1 b2 c1 c2 c3 c4" {
+				t.Fatalf("landed %s; want every record once, in the order written", got)
+			}
+			if len(srcs) != 4 || !srcs[rel] {
+				t.Fatalf("the files land with the sources %v; want four, the first file's under its path", srcs)
+			}
+			cursorsName(t, zone.StreamDir(session, "main"), srcs)
+			parseTwice(t, zone)
+			verified(t, zone, "as landed", 4)
+			ix := rebuiltIndex(t, zone)
+			collected, ok, err := index.Load(zone.IndexDir(session), session)
+			if err != nil || !ok || !reflect.DeepEqual(collected.Entries, ix.Entries) || !reflect.DeepEqual(collected.Blocks, ix.Blocks) {
+				t.Fatalf("the index rebuilt from the landed files differs from the one collection wrote (ok=%v err=%v)", ok, err)
+			}
+
+			// Retention keeps only the metadata. A skeleton keeps its file's
+			// header, so each source is still told from the others.
+			res := (&retention.Remover{Zone: zone, MetadataOnlyAfter: time.Hour,
+				Now: func() time.Time { return time.Now().Add(24 * time.Hour) }}).Pass(retention.Input{})
+			if len(res.Errors) > 0 || res.Files == 0 {
+				t.Fatalf("retention: %+v; the test needs files removed", res)
+			}
+			verified(t, zone, "after the files were removed", 4)
+			if after := rebuiltIndex(t, zone); !reflect.DeepEqual(after, ix) {
+				t.Fatal("the index rebuilt from the skeletons differs from the one rebuilt from the files")
+			}
+		})
+	}
+}
+
+// asz verify read only <kind>.cursor, the first file's, so a lost landed file
+// of a later file at the path was not found. Each source is held to its own
+// cursor.
+func TestALostFileOfALaterFileIsFound(t *testing.T) {
+	src := t.TempDir()
+	path := filepath.Join(src, "file-changes-inline", "output", session, "main.jsonl")
+	zone := storage.NewZone(t.TempDir())
+	c := claudecodechanges.New(src, zone, 0)
+	collect := func(want int) {
+		t.Helper()
+		if st, err := c.CollectAll(nil); err != nil || !st.Complete() || st.Records != want {
+			t.Fatalf("%+v err=%v; want %d records", st, err, want)
+		}
+	}
+	appendTo(t, path, line("a1", "main", "toolu_a1", "/w")+line("a2", "main", "toolu_a2", "/w"))
+	collect(2)
+	if err := os.Remove(path); err != nil {
+		t.Fatal(err)
+	}
+	appendTo(t, path, line("b1", "main", "toolu_b1", "/w"))
+	collect(1)
+	appendTo(t, path, line("b2", "main", "toolu_b2", "/w"))
+	collect(1)
+	parseTwice(t, zone)
+	verified(t, zone, "as landed", 2)
+	files := landedFiles(t, zone)
+	if err := os.Remove(files[len(files)-1].Path); err != nil {
+		t.Fatal(err)
+	}
+	rep, err := verify.Session(zone, session)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if rep.EndGaps != 1 || rep.Problems != 1 || !strings.Contains(strings.Join(rep.Details(), " "), "changes-") {
+		t.Fatalf("verify finds %v; want the later file's cursor ahead of its landed records", rep.Details())
+	}
+}
+
+// landedFiles lists the session's landed files, in sequence order.
+func landedFiles(t *testing.T, zone *storage.Zone) []storage.LandedFile {
+	t.Helper()
+	files, err := storage.LandedFiles(zone, session)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return files
+}
+
+// parseTwice parses the session twice. The second parse has nothing new to
+// read, so it writes no round.
+func parseTwice(t *testing.T, zone *storage.Zone) {
+	t.Helper()
+	for i := 0; i < 2; i++ {
+		r, err := parse.Session(zone, parse.Options{Conversation: session, Session: session})
+		if err != nil {
+			t.Fatal(err)
+		}
+		if i == 1 && r.Number != 0 {
+			t.Fatalf("a second parse wrote round %d; nothing changed", r.Number)
+		}
+	}
+}
+
+// verified checks the session with asz verify: no problem, no record counted
+// as landed again, and one report for each source of the plugin's kind.
+func verified(t *testing.T, zone *storage.Zone, when string, sources int) {
+	t.Helper()
+	rep, err := verify.Session(zone, session)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if !rep.OK() || rep.Relanded != 0 || len(rep.Streams) != sources {
+		t.Fatalf("%s: verify finds %v, %d records landed again and %d sources; want none, none and %d",
+			when, rep.Details(), rep.Relanded, len(rep.Streams), sources)
+	}
+}
+
+// rebuiltIndex builds the session's index again from its landed files.
+func rebuiltIndex(t *testing.T, zone *storage.Zone) *index.Index {
+	t.Helper()
+	ix := index.New(session)
+	if _, err := index.Rebuild(zone, session, ix, 0); err != nil {
+		t.Fatal(err)
+	}
+	return ix
+}
+
+// cursorsName checks that every cursor that read a line, 0.6.0 being what
+// wrote it, records the file's first line, and names the src its files land
+// with: each source has its own.
+func cursorsName(t *testing.T, dir string, srcs map[string]bool) {
+	t.Helper()
+	items, err := os.ReadDir(dir)
+	if err != nil {
+		t.Fatal(err)
+	}
+	named := map[string]bool{}
+	for _, it := range items {
+		if !strings.HasSuffix(it.Name(), ".cursor") {
+			continue
+		}
+		cur, err := storage.LoadCursor(filepath.Join(dir, it.Name()), storage.CursorAppend, "")
+		if err != nil {
+			t.Fatal(err)
+		}
+		if cur.Offset == 0 {
+			continue
+		}
+		if cur.HeadSHA256 == "" {
+			t.Fatalf("the cursor %s read to %d and records no first line", it.Name(), cur.Offset)
+		}
+		if !srcs[cur.Source] || named[cur.Source] {
+			t.Fatalf("the cursor %s names %q; want one cursor for each of %v", it.Name(), cur.Source, srcs)
+		}
+		named[cur.Source] = true
+	}
+	if len(named) != len(srcs) {
+		t.Fatalf("the cursors name %v; want %v", named, srcs)
+	}
+}
+
+// A cursor 0.5.0 wrote names its root and records no first line. It goes on
+// as it did: lines appended to its file land, and nothing is landed twice.
+// It is not given a first line afterwards, so a file the plugin writes again
+// at its path is still a conflict, as the storage root page says.
+func TestACursorWithoutAFirstLineGoesOnAsBefore(t *testing.T) {
+	src := t.TempDir()
+	path := filepath.Join(src, "file-changes-inline", "output", session, "main.jsonl")
+	zone := storage.NewZone(t.TempDir())
+	c := claudecodechanges.New(src, zone, 0)
+	appendTo(t, path, line("a1", "main", "toolu_a1", "/w")+line("a2", "main", "toolu_a2", "/w"))
+	if st, err := c.CollectAll(nil); err != nil || !st.Complete() || st.Records != 2 {
+		t.Fatalf("the first pass: %+v err=%v", st, err)
+	}
+	cursor := filepath.Join(zone.StreamDir(session, "main"), "changes.cursor")
+	dropKeys(t, cursor, "head_sha256")
+	appendTo(t, path, line("a3", "main", "toolu_a3", "/w"))
+	for i, want := range []int{1, 0} {
+		if st, err := c.CollectAll(nil); err != nil || !st.Complete() || st.Records != want {
+			t.Fatalf("pass %d after the cursor of 0.5.0: %+v err=%v; want %d records", i+1, st, err, want)
+		}
+	}
+	parseTwice(t, zone)
+	if held, err := storage.LoadCursor(cursor, storage.CursorAppend, ""); err != nil || held.HeadSHA256 != "" || held.Origin == "" {
+		t.Fatalf("the cursor: %+v %v; want its root and still no first line", held, err)
+	}
+	if err := os.Remove(path); err != nil {
+		t.Fatal(err)
+	}
+	appendTo(t, path, line("b1", "main", "toolu_b1", "/w"))
+	if st, _ := c.CollectAll(nil); st == nil || st.Conflicts != 1 || st.Records != 0 {
+		t.Fatalf("a file written again behind the cursor of 0.5.0: %+v; want the conflict the page states", st)
+	}
+}
+
+// dropKeys rewrites a cursor without the keys given, as an older asz wrote it.
+func dropKeys(t *testing.T, path string, keys ...string) {
+	t.Helper()
+	raw, err := os.ReadFile(path)
+	if err != nil {
+		t.Fatal(err)
+	}
+	var kept []string
+	for _, l := range strings.Split(string(raw), "\n") {
+		key, _, _ := strings.Cut(l, " ")
+		if !slices.Contains(keys, key) {
+			kept = append(kept, l)
+		}
+	}
+	if err := os.WriteFile(path, []byte(strings.Join(kept, "\n")), 0o644); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// A repacked root goes on from where the old one stopped. Only the plain
+// cursor was carried over, so a collector pointed at the new root read a
+// later file at the same path from its start and landed all of it again.
+// And a new file never mixes two sources: its header names one src.
+func TestARepackCarriesTheCursorOfALaterFile(t *testing.T) {
+	src := t.TempDir()
+	path := filepath.Join(src, "file-changes-inline", "output", session, "main.jsonl")
+	zone := storage.NewZone(t.TempDir())
+	appendTo(t, path, line("a1", "main", "toolu_a1", "/w")+line("a2", "main", "toolu_a2", "/w"))
+	if st, err := claudecodechanges.New(src, zone, 0).CollectAll(nil); err != nil || !st.Complete() || st.Records != 2 {
+		t.Fatalf("the first file: %+v err=%v", st, err)
+	}
+	if err := os.Remove(path); err != nil {
+		t.Fatal(err)
+	}
+	appendTo(t, path, line("b1", "main", "toolu_b1", "/w"))
+	if st, err := claudecodechanges.New(src, zone, 0).CollectAll(nil); err != nil || !st.Complete() || st.Records != 1 {
+		t.Fatalf("the later file: %+v err=%v", st, err)
+	}
+	for _, budget := range []int64{1, 2 << 20} {
+		dst := storage.NewZone(t.TempDir())
+		if _, err := repack.Session(zone, dst, session, budget, time.Date(2026, 9, 9, 0, 0, 0, 0, time.UTC)); err != nil {
+			t.Fatal(err)
+		}
+		for i := 0; i < 2; i++ {
+			if st, err := claudecodechanges.New(src, dst, 0).CollectAll(nil); err != nil || !st.Complete() || st.Records != 0 {
+				t.Fatalf("budget %d, pass %d over the repacked root: %+v err=%v; want nothing landed again", budget, i+1, st, err)
+			}
+		}
+		parseTwice(t, dst)
+		verified(t, dst, fmt.Sprintf("repacked under a budget of %d", budget), 2)
+		// The first file's two records land in the second new file under a
+		// budget of one byte, and in the first under the large one.
+		want := map[int64]string{1: "last_seq      2\n", 2 << 20: "last_seq      1\n"}[budget]
+		if raw, err := os.ReadFile(filepath.Join(dst.StreamDir(session, "main"), "changes.cursor")); err != nil || !strings.Contains(string(raw), want) {
+			t.Fatalf("budget %d: the first file's cursor must name the new file of its own last record, %q: %v\n%s", budget, want, err, raw)
+		}
+	}
+}
+
+// The rule that tells a later file from the one a cursor read must not hide a
+// file rewritten behind its cursor. Such a file still begins with its first
+// line, so it is the cursor's file, and it is a conflict that stays.
+func TestAFileRewrittenBehindItsCursorIsStillAConflict(t *testing.T) {
+	first := line("a1", "main", "toolu_1", "/w")
+	for name, rewrite := range map[string]string{
+		"cut short":      first,
+		"a line changed": first + line("a2", "main", "toolu_9", "/w") + line("a3", "main", "toolu_3", "/w") + line("a4", "main", "toolu_4", "/w"),
+	} {
+		t.Run(name, func(t *testing.T) {
+			src := t.TempDir()
+			path := filepath.Join(src, "file-changes-inline", "output", session, "main.jsonl")
+			zone := storage.NewZone(t.TempDir())
+			c := claudecodechanges.New(src, zone, 0)
+			appendTo(t, path, first+line("a2", "main", "toolu_2", "/w")+line("a3", "main", "toolu_3", "/w"))
+			if st, err := c.CollectAll(nil); err != nil || !st.Complete() || st.Records != 3 {
+				t.Fatalf("first pass: %+v err=%v", st, err)
+			}
+			if err := os.WriteFile(path, []byte(rewrite), 0o644); err != nil {
+				t.Fatal(err)
+			}
+			for i := 0; i < 2; i++ {
+				if st, _ := c.CollectAll(nil); st == nil || st.Conflicts != 1 || st.Records != 0 {
+					t.Fatalf("pass %d over the rewritten file: %+v; want one conflict and nothing landed", i+1, st)
+				}
+			}
+			parseTwice(t, zone)
+			verified(t, zone, "after the conflict", 1)
+		})
+	}
+}
+
+// A file the plugin is creating holds no complete line for a moment. It is not
+// the file a cursor read, which had one, and nothing in it can land yet, so
+// the pass waits for the line rather than calling the path a conflict.
+func TestAFileStillWritingItsFirstLineWaits(t *testing.T) {
+	src := t.TempDir()
+	path := filepath.Join(src, "file-changes-inline", "output", session, "main.jsonl")
+	zone := storage.NewZone(t.TempDir())
+	c := claudecodechanges.New(src, zone, 0)
+	appendTo(t, path, line("a1", "main", "toolu_1", "/w")+line("a2", "main", "toolu_2", "/w"))
+	if st, err := c.CollectAll(nil); err != nil || !st.Complete() || st.Records != 2 {
+		t.Fatalf("first pass: %+v err=%v", st, err)
+	}
+	next := line("b1", "main", "toolu_5", "/w")
+	for _, part := range []string{"", next[:20]} {
+		if err := os.WriteFile(path, []byte(part), 0o644); err != nil {
+			t.Fatal(err)
+		}
+		if st, err := c.CollectAll(nil); err != nil || !st.Complete() || st.Records != 0 {
+			t.Fatalf("a first line of %d bytes, not ended: %+v err=%v; want nothing and no conflict", len(part), st, err)
+		}
+	}
+	appendTo(t, path, next[20:])
+	if st, err := c.CollectAll(nil); err != nil || !st.Complete() || st.Records != 1 {
+		t.Fatalf("the first line, ended: %+v err=%v; want it landed", st, err)
+	}
+	if st, err := c.CollectAll(nil); err != nil || !st.Complete() || st.Records != 0 {
+		t.Fatalf("again: %+v err=%v; want nothing", st, err)
+	}
+	parseTwice(t, zone)
+	verified(t, zone, "after the later file landed", 2)
+}
diff --git a/internal/metrics/completion_test.go b/internal/metrics/completion_test.go
index b689f3d..a7979ca 100644
--- a/internal/metrics/completion_test.go
+++ b/internal/metrics/completion_test.go
@@ -27,6 +27,7 @@ import (
 
 	"github.com/apache/skywalking-ai-sessionizer/internal/metrics"
 	"github.com/apache/skywalking-ai-sessionizer/internal/storage"
+	"github.com/apache/skywalking-ai-sessionizer/pkg/sessiondata"
 )
 
 func TestFinishedCallAcrossThreeLandedFiles(t *testing.T) {
@@ -104,6 +105,138 @@ func TestMainCallUsesTheFinalFragmentAcrossFiles(t *testing.T) {
 	}
 }
 
+// toolResult is the result of a call's first tool, which the runtime writes
+// between that call's fragments. It belongs to no call.
+func toolResult(ord uint64) *sessiondata.Record {
+	return &sessiondata.Record{Ord: ord, Sha: "x", Bytes: 1, Tool: "toolu_1", From: sessiondata.FromExternal,
+		Time:  base.Add(time.Minute - 150*time.Millisecond).Format(time.RFC3339Nano),
+		Parts: []sessiondata.Part{{Kind: sessiondata.PartResult, Of: "toolu_1", Text: "ok", State: "available", Bytes: 2}}}
+}
+
+// A call's own tool results sit between its fragments on 24% of the calls
+// with more than one fragment. A landed file can end at a fragment while the
+// next begins with such a result. The call goes on past the result, so its
+// last fragment in line order is after it, and the call counts in that
+// fragment's minute. Stopping at the result put it in the minute before.
+func TestMainCallReadsPastItsOwnToolResultAcrossFiles(t *testing.T) {
+	z := storage.NewZone(t.TempDir())
+	cut := call{id: "interleaved", model: "m", at: base.Add(time.Minute - 200*time.Millisecond), frags: 3, in: 4, out: 60}
+	first, rest := cut, cut
+	first.only = 1
+	rest.skip = 1
+	ord := uint64(1)
+	landRecords(t, z, "s1", "main", 1, records(first, true, &ord), "claude-code/1")
+	ord = 2
+	landRecords(t, z, "s1", "main", 2, append([]*sessiondata.Record{toolResult(1)}, records(rest, true, &ord)...), "claude-code/1")
+	d := deriver(z, base.Add(time.Hour), metrics.Options{})
+	st, err := d.Pass(nil)
+	if err != nil || len(st.Errors) > 0 {
+		t.Fatal(err, st)
+	}
+	got, _ := points(t, z)
+	ps := got["main/output/m#s1"]
+	if len(ps) != 1 || total(ps) != 60 || !ps[0].start.Equal(base.Add(time.Minute)) {
+		t.Fatalf("the call must count once, in its last fragment's minute %s: %+v", base.Add(time.Minute), ps)
+	}
+}
+
+// The boundary can also fall after the result. The file's last call is read
+// ahead all the same when the next file is there, and counts in its last
+// fragment's minute. Under a watching collector the next file lands on a
+// later pass, so a file that ends with its last call's tool results waits
+// the grace for it, as a file that ends at a fragment does. Counting the call
+// at once put it in the earlier minute for good. A file whose last call is
+// followed by anything else does not wait: the call is over.
+func TestACallGoesOnAfterAFileThatEndsWithItsToolResult(t *testing.T) {
+	cut := call{id: "interleaved", model: "m", at: base.Add(time.Minute - 200*time.Millisecond), frags: 3, in: 4, out: 60}
+	first, rest := cut, cut
+	first.only = 1
+	rest.skip = 1
+	firstFile := func(z *storage.Zone) string {
+		ord := uint64(1)
+		recs := records(first, true, &ord)
+		return landRecords(t, z, "s1", "main", 1, append(recs, toolResult(ord)), "claude-code/1")
+	}
+
+	z := storage.NewZone(t.TempDir())
+	firstFile(z)
+	ord := uint64(1)
+	landRecords(t, z, "s1", "main", 2, records(rest, true, &ord), "claude-code/1")
+	if st, err := deriver(z, base.Add(time.Hour), metrics.Options{}).Pass(nil); err != nil || len(st.Errors) > 0 {
+		t.Fatal(err, st)
+	}
+	got, _ := points(t, z)
+	if ps := got["main/output/m#s1"]; len(ps) != 1 || total(ps) != 60 || !ps[0].start.Equal(base.Add(time.Minute)) {
+		t.Fatalf("the call must count once, in its last fragment's minute %s: %+v", base.Add(time.Minute), ps)
+	}
+
+	z = storage.NewZone(t.TempDir())
+	aged(t, firstFile(z), base)
+	st, err := deriver(z, base.Add(30*time.Second), metrics.Options{}).Pass(nil)
+	if err != nil || len(st.Errors) > 0 || st.Deferred != 1 || st.Files != 0 {
+		t.Fatalf("a file that ends with its call's tool result must wait for the call's next fragment: %v %+v", err, st)
+	}
+	ord = 1
+	aged(t, landRecords(t, z, "s1", "main", 2, records(rest, true, &ord), "claude-code/1"), base.Add(40*time.Second))
+	if st, err := deriver(z, base.Add(time.Hour), metrics.Options{}).Pass(nil); err != nil || len(st.Errors) > 0 || st.Files != 2 {
+		t.Fatalf("the continuation landed during the grace: %v %+v", err, st)
+	}
+	got, _ = points(t, z)
+	if ps := got["main/output/m#s1"]; len(ps) != 1 || total(ps) != 60 || !ps[0].start.Equal(base.Add(time.Minute)) {
+		t.Fatalf("a continuation that landed during the grace: the call must count once, in its last fragment's minute %s: %+v", base.Add(time.Minute), ps)
+	}
+
+	z = storage.NewZone(t.TempDir())
+	ord = 1
+	recs := records(call{id: "over", model: "m", at: base, frags: 1, in: 1, out: 5}, true, &ord)
+	recs = append(recs, prompt(ord, base.Add(time.Second)))
+	aged(t, landRecords(t, z, "s1", "main", 1, recs, "claude-code/1"), base)
+	if st, err := deriver(z, base.Add(30*time.Second), metrics.Options{}).Pass(nil); err != nil || len(st.Errors) > 0 || st.Deferred != 0 || st.Files != 1 {
+		t.Fatalf("a file whose last call is followed by a prompt must not wait: %v %+v", err, st)
+	}
+}
+
+// prompt is a person's next question, which belongs to no call and ends the
+// call before it.
+func prompt(ord uint64, at time.Time) *sessiondata.Record {
+	return &sessiondata.Record{Ord: ord, Sha: "x", Bytes: 1, From: sessiondata.FromExternal,
+		Time:  at.Format(time.RFC3339Nano),
+		Parts: []sessiondata.Part{{Kind: sessiondata.PartText, Text: "next question", State: "available", Bytes: 13}}}
+}
+
+// Reading on into the next file ends a call where reading that file alone
+// does. It read past a prompt, so a file whose last call had ended in the
+// next file waited the grace, while the next file, read alone, counted the
+// call at once. The waiting file then counted its own earlier call after
+// that one, and the earlier call's window followed the later call's: 10:03
+// instead of 10:00.
+func TestReadingOnEndsACallWhereReadingAloneDoes(t *testing.T) {
+	z := storage.NewZone(t.TempDir())
+	done := call{id: "a", model: "m", at: base, frags: 1, in: 1, out: 5}
+	cut := call{id: "b", model: "m", at: base.Add(2*time.Minute - 100*time.Millisecond), frags: 2, in: 2, out: 7}
+	first, rest := cut, cut
+	first.only = 1
+	rest.skip = 1
+	ord := uint64(1)
+	recs := records(done, true, &ord)
+	recs = append(recs, records(first, true, &ord)...)
+	aged(t, landRecords(t, z, "s1", "main", 1, recs, "claude-code/1"), base.Add(2*time.Minute))
+	ord = 1
+	recs = records(rest, true, &ord)
+	recs = append(recs, prompt(ord, base.Add(2*time.Minute+time.Second)))
+	aged(t, landRecords(t, z, "s1", "main", 2, recs, "claude-code/1"), base.Add(2*time.Minute))
+	for _, now := range []time.Duration{2*time.Minute + 30*time.Second, time.Hour} {
+		if st, err := deriver(z, base.Add(now), metrics.Options{}).Pass(nil); err != nil || len(st.Errors) > 0 {
+			t.Fatal(err, st)
+		}
+	}
+	got, _ := points(t, z)
+	ps := got["main/output/m#s1"]
+	if len(ps) != 2 || !ps[0].start.Equal(base) || ps[0].value != 5 || !ps[1].start.Equal(base.Add(2*time.Minute)) || ps[1].value != 7 {
+		t.Fatalf("the first call must count at %s and the second at %s, once each: %+v", base, base.Add(2*time.Minute), ps)
+	}
+}
+
 // A later fragment restarts the grace. The first file can already be old
 // while the last file is still being followed by more fragments.
 func TestContinuationWaitsForTheLatestFilesGrace(t *testing.T) {
diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go
index b85daf6..692953c 100644
--- a/internal/metrics/metrics.go
+++ b/internal/metrics/metrics.go
@@ -434,9 +434,9 @@ type result struct {
 }
 
 // deriveFile reads one landed file's calls and turns the ones that finished
-// into points. A call whose last fragment is the file's last record may go
-// on across several files of the stream. Their leading fragments are read
-// until another transcript record ends the call, and it is counted once.
+// into points. The file's last call may go on across several files of the
+// stream. Their leading records are read until a record that is neither a
+// fragment of it nor a tool result ends it, and it is counted once.
 // Points take the minute the call's last fragment falls in, and a window
 // that never overlaps the series' last: a minute already passed by an
 // earlier point follows that point instead.
@@ -477,7 +477,9 @@ func deriveFile(lf storage.LandedFile, following []storage.LandedFile, since tim
 	calls := map[string]*call{}
 	var order []string
 	var last *call
-	var tail bool
+	// open says the file ends at a fragment of its last call, or at tool
+	// results after one.
+	var open bool
 	for {
 		rec, err := rd.Next()
 		if errors.Is(err, io.EOF) {
@@ -490,8 +492,11 @@ func deriveFile(lf storage.LandedFile, following []storage.LandedFile, since tim
 		if ok && t.After(res.latest) {
 			res.latest = t
 		}
-		tail = false
-		if hdr.Kind != sessiondata.KindTranscript || rec.Call == "" {
+		if hdr.Kind != sessiondata.KindTranscript {
+			continue
+		}
+		if rec.Call == "" {
+			open = open && isResult(rec)
 			continue
 		}
 		c := calls[rec.Call]
@@ -501,15 +506,25 @@ func deriveFile(lf storage.LandedFile, following []storage.LandedFile, since tim
 			order = append(order, rec.Call)
 		}
 		c.take(rec, t, ok)
-		last, tail = c, true
+		last, open = c, true
 	}
 	// Drain what the reader did not consume, so the digest is the file's.
 	if _, err := io.Copy(io.Discard, f); err != nil {
 		return nil, err
 	}
 	res.digest = fileDigest(&hdr, h)
-	if tail && last != nil && !ss.Calls[last.id] {
-		res.openTail = lf.Path
+	// The file's last call may go on in the next file: its own tool results
+	// sit between its fragments. It is read ahead whatever follows it here.
+	// A file that ends at a fragment of it, or at tool results after one,
+	// waits for the next file, as one does whose call was found to go on.
+	// Under a watching collector the next file lands on a later pass, and a
+	// call counted before it was counted in an earlier fragment's minute for
+	// good. A file whose last call is followed by anything else does not
+	// wait: the call is over.
+	if last != nil && !ss.Calls[last.id] {
+		if open {
+			res.openTail = lf.Path
+		}
 		for _, next := range following {
 			if next.Stream != lf.Stream {
 				continue
@@ -621,9 +636,24 @@ func (c *call) take(rec *sessiondata.Record, t time.Time, ok bool) {
 	}
 }
 
+// isResult reports whether a record carries a tool's result.
+func isResult(rec *sessiondata.Record) bool {
+	for _, p := range rec.Parts {
+		if p.Kind == sessiondata.PartResult {
+			return true
+		}
+	}
+	return false
+}
+
 // continueIn reads the leading fragments of a call. more says the call
 // may continue in another file; matched says this file held a fragment.
-// Metadata and workspace changes do not interrupt a transcript's call.
+// Metadata and workspace changes do not interrupt a transcript's call, and
+// neither do tool results, which sit between its fragments. Any other
+// record, such as a person's next prompt or a fragment of another call, ends
+// it. That is the rule deriveFile reads a file by: read on past a prompt, a
+// file waited the grace for a call its next file, read alone, counted at
+// once, and the waiting file's earlier calls then took windows after it.
 func continueIn(path string, c *call) (more, matched bool, err error) {
 	f, err := sessiondata.Open(path)
 	if err != nil {
@@ -645,6 +675,9 @@ func continueIn(path string, c *call) (more, matched bool, err error) {
 		if err != nil {
 			return false, matched, err
 		}
+		if rec.Call == "" && isResult(rec) {
+			continue
+		}
 		if rec.Call != c.id {
 			return false, matched, nil
 		}
diff --git a/internal/metrics/metrics_test.go b/internal/metrics/metrics_test.go
index a74bf8c..0f3e13d 100644
--- a/internal/metrics/metrics_test.go
+++ b/internal/metrics/metrics_test.go
@@ -91,6 +91,18 @@ func land(t *testing.T, z *storage.Zone, session, stream string, seq uint64, cal
 // Claude Code's transcripts, so every fixture is one unless a test says
 // otherwise.
 func landAs(t *testing.T, z *storage.Zone, session, stream string, seq uint64, calls []call, dialect string) string {
+	t.Helper()
+	var recs []*sessiondata.Record
+	ord := uint64(1)
+	for _, c := range calls {
+		recs = append(recs, records(c, stream == "main", &ord)...)
+	}
+	return landRecords(t, z, session, stream, seq, recs, dialect)
+}
+
+// landRecords lands a transcript of the records given, for a test that needs
+// records the call fixture does not write.
+func landRecords(t *testing.T, z *storage.Zone, session, stream string, seq uint64, recs []*sessiondata.Record, dialect string) string {
 	t.Helper()
 	path := filepath.Join(z.StreamDir(session, stream), storage.LandedName("transcript", storage.Stamp(time.Unix(int64(seq), 0)), seq))
 	err := storage.WriteAtomic(path, storage.PermLanded, func(w io.Writer) error {
@@ -100,12 +112,9 @@ func landAs(t *testing.T, z *storage.Zone, session, stream string, seq uint64, c
 		if err != nil {
 			return err
 		}
-		ord := uint64(1)
-		for _, c := range calls {
-			for _, rec := range records(c, stream == "main", &ord) {
-				if err := sw.Write(rec); err != nil {
-					return err
-				}
+		for _, rec := range recs {
+			if err := sw.Write(rec); err != nil {
+				return err
 			}
 		}
 		return sw.Close()
diff --git a/internal/repack/repack.go b/internal/repack/repack.go
index bba0579..4ec18c0 100644
--- a/internal/repack/repack.go
+++ b/internal/repack/repack.go
@@ -482,19 +482,29 @@ func closeOut(o *out) (err error) {
 // carryCursors copies every cursor of the session into the new root, so a
 // collector pointed at the new root continues each source from where the old
 // one stopped instead of landing it again. A directory holds one cursor per
-// source: <prefix>.cursor for the first, and <prefix>-<hash>.cursor for each
-// other source of the same files, such as a second recorder directory. Each
-// names the new file holding the last record of the file its source landed
-// last.
+// source: <prefix>.cursor for the first, <prefix>-<hash>.cursor for each
+// other source of the same files, such as a second recorder directory, and
+// <prefix>-<hash>.cursor for each later file the plugin wrote at a source's
+// path. Each names the new file holding the last record of the file its
+// source landed last.
 //
 // An origin relative to the storage root names a source root inside it. A
 // collector into the new root writes that root as it writes any root
-// outside, and names the source's own cursor by it, so the origin and that
-// name are written again as it computes them. Left as they were, the
+// outside, and names the source's own cursors by it, so the origin and those
+// names are written again as it computes them. Left as they were, the
 // collector found no cursor of its own and read the source from its start.
 func carryCursors(src, dst *storage.Zone, session string, landedIn map[uint64]*output, now time.Time) error {
 	srcDir, dstDir := src.SessionDir(session), dst.SessionDir(session)
-	return filepath.WalkDir(srcDir, func(path string, d fs.DirEntry, err error) error {
+	type held struct {
+		path, rel string
+		cur       *storage.Cursor
+	}
+	var all []held
+	// A later file's cursor is named for the first line of the file before
+	// it, which only that file's cursor records: by directory, each name a
+	// cursor's successor has under the old origin, and the head it is for.
+	successor := map[string]string{}
+	err := filepath.WalkDir(srcDir, func(path string, d fs.DirEntry, err error) error {
 		if err != nil || d.IsDir() || !strings.HasSuffix(d.Name(), ".cursor") {
 			return err
 		}
@@ -506,20 +516,42 @@ func carryCursors(src, dst *storage.Zone, session string, landedIn map[uint64]*o
 		if err != nil {
 			return err
 		}
+		all = append(all, held{path, rel, cur})
+		if cur.HeadSHA256 != "" {
+			name := storage.LaterCursorName(prefixOf(d.Name()), cur.Origin, storage.SourcePath(cur.Source), cur.HeadSHA256)
+			successor[filepath.Join(rel, name)] = cur.HeadSHA256
+		}
+		return nil
+	})
+	if err != nil {
+		return err
+	}
+	for _, h := range all {
+		cur := h.cur
 		var last uint64
 		if o := landedIn[cur.LastSeq]; o != nil {
 			last = o.seq
 		}
-		name, origin := d.Name(), cur.Origin
+		name, origin := filepath.Base(h.path), cur.Origin
 		if origin != "" && !filepath.IsAbs(filepath.FromSlash(origin)) {
 			origin = storage.CursorOrigin(dst.Root(), filepath.Join(src.Root(), filepath.FromSlash(cur.Origin)))
-			prefix := strings.SplitN(strings.TrimSuffix(name, ".cursor"), "-", 2)[0]
-			if name == storage.SourceCursorName(prefix, cur.Origin, cur.Source) {
-				name = storage.SourceCursorName(prefix, origin, cur.Source)
+			prefix, source := prefixOf(name), storage.SourcePath(cur.Source)
+			if name == storage.SourceCursorName(prefix, cur.Origin, source) {
+				name = storage.SourceCursorName(prefix, origin, source)
+			} else if head, ok := successor[filepath.Join(h.rel, name)]; ok {
+				name = storage.LaterCursorName(prefix, origin, source, head)
 			}
 		}
-		return carryCursor(path, filepath.Join(dstDir, rel, name), last, origin, now)
-	})
+		if err := carryCursor(h.path, filepath.Join(dstDir, h.rel, name), last, origin, now); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// prefixOf is the kind a cursor's name starts with.
+func prefixOf(name string) string {
+	return strings.SplitN(strings.TrimSuffix(name, ".cursor"), "-", 2)[0]
 }
 
 // carryCursor copies one cursor with its last landed sequence, its origin
diff --git a/internal/storage/cursor.go b/internal/storage/cursor.go
index 09bb25c..1f9a057 100644
--- a/internal/storage/cursor.go
+++ b/internal/storage/cursor.go
@@ -93,6 +93,12 @@ type Cursor struct {
 	Ord        uint64 // source line consumed through; the next batch starts at Ord+1
 	LastUUID   string // last uuid seen - diagnostic only, since many lines carry none
 	TailSHA256 string
+	// HeadSHA256 is the digest of the file's first line, for a source that
+	// can be removed and written again at the same path, as the plugin's
+	// output is: a file that does not begin with this line is another file.
+	// Empty until the first line is read, and on a source that is never
+	// written again.
+	HeadSHA256 string
 
 	// Snapshot fields.
 	ContentSHA256 string
@@ -154,6 +160,8 @@ func LoadCursor(path string, kind CursorKind, source string) (*Cursor, error) {
 			c.LastUUID = val
 		case "tail_sha256":
 			c.TailSHA256 = val
+		case "head_sha256":
+			c.HeadSHA256 = val
 		case "content_sha256":
 			c.ContentSHA256 = val
 		case "size":
@@ -196,6 +204,9 @@ func (c *Cursor) Save(path string, now time.Time) error {
 			if c.TailSHA256 != "" {
 				fmt.Fprintf(bw, "tail_sha256   %s\n", c.TailSHA256)
 			}
+			if c.HeadSHA256 != "" {
+				fmt.Fprintf(bw, "head_sha256   %s\n", c.HeadSHA256)
+			}
 		} else {
 			fmt.Fprintf(bw, "content_sha256 %s\n", c.ContentSHA256)
 		}
@@ -229,3 +240,35 @@ func SourceCursorName(prefix, origin, source string) string {
 	sum := sha256.Sum256([]byte(origin + "\n" + source))
 	return prefix + "-" + hex.EncodeToString(sum[:])[:12] + ".cursor"
 }
+
+// LaterCursorName is the name of the cursor of a later file at a source's
+// path: one the plugin wrote there after removing another, whose cursor
+// recorded previousHead, the digest of that file's first line. It is named
+// for the source's origin, its path and that digest, so it is the same on
+// every pass, and each file at the path has a cursor of its own.
+func LaterCursorName(prefix, origin, source, previousHead string) string {
+	sum := sha256.Sum256([]byte(origin + "\n" + source + "\n" + previousHead))
+	return prefix + "-" + hex.EncodeToString(sum[:])[:12] + ".cursor"
+}
+
+// markLen is how many hexadecimal characters of a file's first line digest
+// mark its source.
+const markLen = 12
+
+// MarkedSource is the src a source lands under, and its cursor's source,
+// when it is not the first at its path: the path, a #, and the first 12
+// hexadecimal characters of head, the digest of its file's first line.
+func MarkedSource(path, head string) string { return path + "#" + head[:markLen] }
+
+// SourcePath is the path a src or a cursor's source names: the part before
+// the mark MarkedSource adds, or the whole of one without it.
+func SourcePath(src string) string {
+	i := strings.LastIndexByte(src, '#')
+	if i < 0 || len(src)-i-1 != markLen {
+		return src
+	}
+	if _, err := hex.DecodeString(src[i+1:]); err != nil {
+		return src
+	}
+	return src[:i]
+}
diff --git a/internal/storage/cursorname_test.go b/internal/storage/cursorname_test.go
new file mode 100644
index 0000000..52cf688
--- /dev/null
+++ b/internal/storage/cursorname_test.go
@@ -0,0 +1,67 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package storage_test
+
+import (
+	"path/filepath"
+	"strings"
+	"testing"
+
+	"github.com/apache/skywalking-ai-sessionizer/internal/storage"
+)
+
+// A source that is not the first at its path lands under the path and a mark
+// of its first line. The path is read back from the mark, and a path that
+// only looks like one, a # not followed by 12 hexadecimal characters, is a
+// path whole. Repack reads a cursor's path this way to name the cursor again
+// for a new root.
+func TestASourceMarkIsReadBack(t *testing.T) {
+	const path = "file-changes-x/output/s/main.jsonl"
+	head := strings.Repeat("0123456789abcdef", 4)
+	marked := storage.MarkedSource(path, head)
+	if marked != path+"#0123456789ab" {
+		t.Fatalf("marked %q", marked)
+	}
+	for src, want := range map[string]string{
+		marked:                 path,
+		path:                   path,
+		path + "#notahex00000": path + "#notahex00000",
+		path + "#0123456789a":  path + "#0123456789a",
+		"a#b/" + path:          "a#b/" + path,
+	} {
+		if got := storage.SourcePath(src); got != want {
+			t.Errorf("SourcePath(%q) = %q, want %q", src, got, want)
+		}
+	}
+	// Each name differs by what it is for.
+	names := map[string]bool{
+		storage.SourceCursorName("changes", "_recorder", path):              true,
+		storage.SourceCursorName("changes", "/other", path):                 true,
+		storage.LaterCursorName("changes", "_recorder", path, head):         true,
+		storage.LaterCursorName("changes", "_recorder", path, head[1:]+"0"): true,
+		storage.LaterCursorName("execution", "_recorder", path, head):       true,
+	}
+	if len(names) != 5 {
+		t.Fatalf("two cursors share a name: %v", names)
+	}
+	for name := range names {
+		if filepath.Ext(name) != ".cursor" || !strings.Contains(name, "-") {
+			t.Fatalf("name %q", name)
+		}
+	}
+}
diff --git a/internal/verify/session.go b/internal/verify/session.go
index 132edf9..24bc222 100644
--- a/internal/verify/session.go
+++ b/internal/verify/session.go
@@ -23,6 +23,7 @@ import (
 	"path/filepath"
 
 	"github.com/apache/skywalking-ai-sessionizer/internal/storage"
+	"github.com/apache/skywalking-ai-sessionizer/pkg/sessiondata"
 )
 
 // SessionReport aggregates every stream and run in one session.
@@ -65,24 +66,39 @@ func Session(z *storage.Zone, session string) (*SessionReport, error) {
 
 	check := func(dir string, kinds ...string) error {
 		for _, k := range kinds {
-			sr, err := Stream(dir, k)
-			if err != nil {
-				return err
+			var reports []*StreamReport
+			// The plugin's kinds are checked one source at a time: a stream
+			// can hold more than one, each numbering its lines from 1.
+			if k == string(sessiondata.KindChanges) || k == string(sessiondata.KindExecution) {
+				srs, err := Sources(dir, k)
+				if err != nil {
+					return err
+				}
+				reports = srs
+			} else {
+				sr, err := Stream(dir, k)
+				if err != nil {
+					return err
+				}
+				reports = []*StreamReport{sr}
 			}
-			// A stream with no landed file of this kind is still checked when
-			// its cursor says something was read: every file of it is lost.
-			if sr.Files == 0 && sr.End == nil {
-				continue
-			}
-			rep.Streams = append(rep.Streams, sr)
-			rep.Records += sr.Records
-			rep.Relanded += sr.Relanded
-			rep.TooLarge += sr.TooLarge
-			rep.Removed = append(rep.Removed, sr.Removed...)
-			rep.Problems += len(sr.OrdGaps) + len(sr.ByteGaps)
-			if sr.End != nil {
-				rep.Problems++
-				rep.EndGaps++
+			for _, sr := range reports {
+				// A stream with no landed file of this kind is still checked
+				// when its cursor says something was read: every file of it
+				// is lost.
+				if sr.Files == 0 && sr.End == nil {
+					continue
+				}
+				rep.Streams = append(rep.Streams, sr)
+				rep.Records += sr.Records
+				rep.Relanded += sr.Relanded
+				rep.TooLarge += sr.TooLarge
+				rep.Removed = append(rep.Removed, sr.Removed...)
+				rep.Problems += len(sr.OrdGaps) + len(sr.ByteGaps)
+				if sr.End != nil {
+					rep.Problems++
+					rep.EndGaps++
+				}
 			}
 		}
 		return nil
diff --git a/internal/verify/verify.go b/internal/verify/verify.go
index e6cdf73..c1f022f 100644
--- a/internal/verify/verify.go
+++ b/internal/verify/verify.go
@@ -77,7 +77,11 @@ func (g EndGap) String() string {
 
 // StreamReport is the result of checking one stream or run directory.
 type StreamReport struct {
-	Dir     string
+	Dir string
+	// Src is the source checked, for a kind whose sources are checked apart;
+	// see Sources. Empty when the directory's files of the kind are checked
+	// as one.
+	Src     string
 	Files   int
 	Records int
 
@@ -166,15 +170,99 @@ func Stream(dir, kind string) (*StreamReport, error) {
 	if err != nil {
 		return nil, err
 	}
-	rep := &StreamReport{Dir: dir, Files: len(files)}
+	reps, err := walk(dir, files, false)
+	if err != nil {
+		return nil, err
+	}
+	rep := &StreamReport{Dir: dir}
+	if len(reps) > 0 {
+		rep = reps[0]
+	}
+	endCheck(rep, cur, cursorPath)
+	return rep, nil
+}
 
+// Sources checks one stream directory for one of the plugin's kinds, changes
+// or execution, one source at a time, by the files' src. The same path can
+// hold one file after another, the plugin writing a new one after its
+// retention removed the old, and the same session can be in two recorder
+// directories. Each lands under a src of its own and numbers its lines from
+// 1, so checked as one they read as lines landed twice and as gaps. Each
+// source is held to the cursor whose source names it. When more than one
+// cursor names a src, as cursors written before 0.6.0 can, the files cannot be
+// told apart, and only the first, <kind>.cursor where it is one, is checked.
+func Sources(dir, kind string) ([]*StreamReport, error) {
+	// The cursors are read before the files are listed, as Stream reads its.
+	type held struct {
+		path string
+		cur  *storage.Cursor
+	}
+	var cursors []held
+	items, err := os.ReadDir(dir)
+	if err != nil && !os.IsNotExist(err) {
+		return nil, err
+	}
+	for _, it := range items {
+		name := it.Name()
+		if it.IsDir() || !strings.HasSuffix(name, ".cursor") {
+			continue
+		}
+		if name != kind+".cursor" && !strings.HasPrefix(name, kind+"-") {
+			continue
+		}
+		cur, err := storage.LoadCursor(filepath.Join(dir, name), storage.CursorAppend, "")
+		if err != nil {
+			return nil, err
+		}
+		cursors = append(cursors, held{filepath.Join(dir, name), cur})
+	}
+	sort.SliceStable(cursors, func(i, j int) bool {
+		return filepath.Base(cursors[i].path) == kind+".cursor" && filepath.Base(cursors[j].path) != kind+".cursor"
+	})
+	files, err := landedFiles(dir, kind)
+	if err != nil {
+		return nil, err
+	}
+	reps, err := walk(dir, files, true)
+	if err != nil {
+		return nil, err
+	}
+	bySrc := map[string]*StreamReport{}
+	for _, rep := range reps {
+		bySrc[rep.Src] = rep
+	}
+	checked := map[string]bool{}
+	for _, c := range cursors {
+		if checked[c.cur.Source] {
+			continue
+		}
+		checked[c.cur.Source] = true
+		rep := bySrc[c.cur.Source]
+		if rep == nil {
+			rep = &StreamReport{Dir: dir, Src: c.cur.Source}
+			bySrc[rep.Src] = rep
+			reps = append(reps, rep)
+		}
+		endCheck(rep, c.cur, c.path)
+	}
+	return reps, nil
+}
+
+// walk reads a directory's landed files of one kind and checks their lines:
+// as one source, or one source for each src when bySrc is set. The reports
+// are in the order their first file landed.
+func walk(dir string, files []string, bySrc bool) ([]*StreamReport, error) {
 	// Every source starts at line 1 and byte 0, so the first record is held to
 	// that position exactly as a later record is held to the end of the one
 	// before it. Starting from whatever the first record said would accept a
 	// stream whose first landed file is lost.
-	var prevOrd, prevEnd uint64
-	first := true
-
+	type source struct {
+		rep              *StreamReport
+		prevOrd, prevEnd uint64
+		first            bool
+	}
+	var order []*source
+	sources := map[string]*source{}
 	for _, path := range files {
 		f, err := storage.OpenLanded(path)
 		if err != nil {
@@ -185,6 +273,18 @@ func Stream(dir, kind string) (*StreamReport, error) {
 			f.Close()
 			return nil, fmt.Errorf("verify: %s: %w", path, err)
 		}
+		key := ""
+		if bySrc {
+			key = r.Header().Src
+		}
+		s := sources[key]
+		if s == nil {
+			s = &source{rep: &StreamReport{Dir: dir, Src: key}, first: true}
+			sources[key] = s
+			order = append(order, s)
+		}
+		rep := s.rep
+		rep.Files++
 		if rf := removedFile(path, r.Header()); rf != nil {
 			rep.Removed = append(rep.Removed, *rf)
 		}
@@ -200,47 +300,54 @@ func Stream(dir, kind string) (*StreamReport, error) {
 			rep.Records++
 			rep.TooLarge += tooLarge(rec)
 
-			if first {
+			if s.first {
 				rep.FirstOrd = rec.Ord
-				first = false
+				s.first = false
 			}
-			if rec.Ord <= prevOrd {
+			if rec.Ord <= s.prevOrd {
 				// A repeat of ground already covered. The bytes are still here;
 				// they are here twice.
 				rep.Relanded++
 			} else {
 				// A line gap and a byte gap are independent facts, and a stream can
 				// have one without the other, so both are checked.
-				if rec.Ord != prevOrd+1 {
-					rep.OrdGaps = append(rep.OrdGaps, Gap{path, row, prevOrd + 1, rec.Ord})
+				if rec.Ord != s.prevOrd+1 {
+					rep.OrdGaps = append(rep.OrdGaps, Gap{path, row, s.prevOrd + 1, rec.Ord})
 				}
-				if rec.Off != prevEnd {
-					rep.ByteGaps = append(rep.ByteGaps, Gap{path, row, prevEnd, rec.Off})
+				if rec.Off != s.prevEnd {
+					rep.ByteGaps = append(rep.ByteGaps, Gap{path, row, s.prevEnd, rec.Off})
 				}
 			}
 
 			// A repeat must not pull the watermark backwards, or every record
 			// after it would look like a gap.
-			if rec.Ord > prevOrd {
-				prevOrd = rec.Ord
+			if rec.Ord > s.prevOrd {
+				s.prevOrd = rec.Ord
 				// +1 for the newline the source carried and the record does not.
-				prevEnd = rec.Off + uint64(rec.Bytes) + 1
+				s.prevEnd = rec.Off + uint64(rec.Bytes) + 1
 				rep.LastOrd = rec.Ord
 			}
 		}
 		f.Close()
 	}
-	rep.BytesCovered = prevEnd
+	reps := make([]*StreamReport, len(order))
+	for i, s := range order {
+		s.rep.BytesCovered = s.prevEnd
+		reps[i] = s.rep
+	}
+	return reps, nil
+}
 
-	// A snapshot cursor tracks a digest, not lines, and a stream with no cursor
-	// has nothing to say where reading stopped. Only an append cursor ahead of
-	// the records is a loss. One loss at the end is one problem, whether the
-	// cursor counts lines, bytes or both.
+// endCheck holds a source's landed records to its cursor. A snapshot cursor
+// tracks a digest, not lines, and a stream with no cursor has nothing to say
+// where reading stopped. Only an append cursor ahead of the records is a
+// loss. One loss at the end is one problem, whether the cursor counts lines,
+// bytes or both.
+func endCheck(rep *StreamReport, cur *storage.Cursor, cursorPath string) {
 	if cur.Kind == storage.CursorAppend && (cur.Ord > rep.LastOrd || cur.Offset > rep.BytesCovered) {
 		rep.End = &EndGap{Cursor: cursorPath, Ord: cur.Ord, Offset: cur.Offset,
 			LastOrd: rep.LastOrd, Covered: rep.BytesCovered}
 	}
-	return rep, nil
 }
 
 // tooLarge counts a record's parts whose payload was too large to land.
diff --git a/plugins/claude-code/internal/capture/capture.go b/plugins/claude-code/internal/capture/capture.go
index 2acbf0e..5fdcca6 100644
--- a/plugins/claude-code/internal/capture/capture.go
+++ b/plugins/claude-code/internal/capture/capture.go
@@ -189,7 +189,13 @@ func Build(r *scan.Root, reg *Registry, w *Window, ctx Context, sizeCap int64) (
 	nets := map[string]*net{}
 	var order []string
 	partial := false
+	var unread []string
 	for _, s := range steps {
+		// What the BEFORE scan could not read is not observed either: the
+		// window starts there from what an older scan saw.
+		if s.N >= w.Before {
+			unread = append(unread, s.Unread...)
+		}
 		if s.N <= w.Before {
 			continue
 		}
@@ -224,6 +230,7 @@ func Build(r *scan.Root, reg *Registry, w *Window, ctx Context, sizeCap int64) (
 		rec.Coverage = changes.CoveragePartial
 		rec.Gaps = append(rec.Gaps, "a scan stopped at its time cap; paths it did not reach are not observed")
 	}
+	notObserved(rec, unread)
 	for _, other := range reg.Windows {
 		if other.Capture == w.Capture || !overlaps(&other, w) {
 			continue
@@ -280,6 +287,7 @@ func BuildGap(r *scan.Root, step *scan.Step, session, stream string, policy *cha
 	if step.Partial {
 		rec.Coverage = changes.CoveragePartial
 	}
+	notObserved(rec, step.Unread)
 	var paths []string
 	for p := range step.Changes {
 		paths = append(paths, p)
@@ -298,6 +306,24 @@ func BuildGap(r *scan.Root, step *scan.Step, session, stream string, policy *cha
 	return rec
 }
 
+// notObserved marks a record partial for each path a scan could not read,
+// and names each once. A reader must not take the files there for unchanged.
+func notObserved(rec *changes.Record, unread []string) {
+	seen := map[string]bool{}
+	sort.Strings(unread)
+	for _, p := range unread {
+		if seen[p] {
+			continue
+		}
+		seen[p] = true
+		if p == "." {
+			p = "the root"
+		}
+		rec.Coverage = changes.CoveragePartial
+		rec.Gaps = append(rec.Gaps, "a scan could not read "+p+", so what changed there is not observed")
+	}
+}
+
 // overlaps says whether two windows were open on the root at once.
 func overlaps(a, b *Window) bool {
 	aEnd, bEnd := a.After, b.After
diff --git a/plugins/claude-code/internal/scan/ctime_darwin.go b/plugins/claude-code/internal/scan/ctime_darwin.go
new file mode 100644
index 0000000..2757560
--- /dev/null
+++ b/plugins/claude-code/internal/scan/ctime_darwin.go
@@ -0,0 +1,33 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package scan
+
+import (
+	"io/fs"
+	"syscall"
+)
+
+// ctimeOf is when the file's inode last changed, in nanoseconds: its bytes,
+// and also its permissions, which neither the size nor the modification
+// time shows.
+func ctimeOf(info fs.FileInfo) int64 {
+	if st, ok := info.Sys().(*syscall.Stat_t); ok {
+		return st.Ctimespec.Nano()
+	}
+	return 0
+}
diff --git a/plugins/claude-code/internal/scan/ctime_linux.go b/plugins/claude-code/internal/scan/ctime_linux.go
new file mode 100644
index 0000000..7ca741f
--- /dev/null
+++ b/plugins/claude-code/internal/scan/ctime_linux.go
@@ -0,0 +1,33 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package scan
+
+import (
+	"io/fs"
+	"syscall"
+)
+
+// ctimeOf is when the file's inode last changed, in nanoseconds: its bytes,
+// and also its permissions, which neither the size nor the modification
+// time shows.
+func ctimeOf(info fs.FileInfo) int64 {
+	if st, ok := info.Sys().(*syscall.Stat_t); ok {
+		return st.Ctim.Nano()
+	}
+	return 0
+}
diff --git a/plugins/claude-code/internal/scan/ctime_other.go b/plugins/claude-code/internal/scan/ctime_other.go
new file mode 100644
index 0000000..7065890
--- /dev/null
+++ b/plugins/claude-code/internal/scan/ctime_other.go
@@ -0,0 +1,27 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//go:build !linux && !darwin
+
+package scan
+
+import "io/fs"
+
+// ctimeOf has no answer on this platform, Windows among them, so the size,
+// the modification time and the inode decide alone: a file whose access was
+// taken away is found only once one of them changes.
+func ctimeOf(fs.FileInfo) int64 { return 0 }
diff --git a/plugins/claude-code/internal/scan/scan.go b/plugins/claude-code/internal/scan/scan.go
index 616f292..1e5b479 100644
--- a/plugins/claude-code/internal/scan/scan.go
+++ b/plugins/claude-code/internal/scan/scan.go
@@ -21,12 +21,12 @@
 //
 // A scan walks the root under the exclusion rules and hashes what it
 // finds. A stat cache makes the second scan cheap: a file whose size,
-// modification time and inode are as the last scan saw them keeps its
-// hash, unless its modification time is within the last scan's own
-// second, when it is hashed again because the clock cannot tell. The
-// bytes of every new hash are copied into a content store, which is what
-// a diff is later made from, since a tool may have rewritten the file in
-// place by then.
+// modification time, inode and change time, where the platform keeps one,
+// are as the last scan saw them keeps its hash, unless its modification
+// time is within the last scan's own second, when it is hashed again
+// because the clock cannot tell. The bytes of every new hash are copied
+// into a content store, which is what a diff is later made from, since a
+// tool may have rewritten the file in place by then.
 //
 // Every scan appends a step to the root's chain: which paths changed and
 // from what hash to what. A window is the span of steps between its two
@@ -61,6 +61,10 @@ type Entry struct {
 	Size  int64  `json:"size"`
 	MTime int64  `json:"mtime"` // nanoseconds
 	Inode uint64 `json:"inode"`
+	// CTime is when the inode last changed, in nanoseconds, where the
+	// platform keeps it. chmod changes it and nothing else the cache
+	// compares, so a file made unreadable is read again and found so.
+	CTime int64  `json:"ctime,omitempty"`
 	Hash  string `json:"hash"`
 }
 
@@ -81,6 +85,10 @@ type Step struct {
 	// Partial says the scan stopped at its time cap; the changes above
 	// are what it saw before stopping.
 	Partial bool `json:"partial,omitempty"`
+	// Unread names the directories and files the scan could not read, "."
+	// for the root. Nothing under them is observed, so the manifest keeps
+	// what the scan before saw there.
+	Unread []string `json:"unread,omitempty"`
 }
 
 // PathChange is one path's hash before and after a step; an empty hash
@@ -181,8 +189,22 @@ func (r *Root) Scan(opt Options) (*Manifest, *Step, error) {
 
 	next := &Manifest{N: prev.N + 1, From: start.UTC().Format(time.RFC3339Nano), Files: map[string]Entry{}}
 	timedOut := false
+	// What is gone was deleted. What is there and cannot be read is only not
+	// observed: a tool that ran chmod 000 on a directory made every file
+	// under it look deleted, and restoring access made them look created.
+	var unread []string
+	notRead := func(p string, err error) {
+		if errors.Is(err, fs.ErrNotExist) {
+			return
+		}
+		rel, rerr := filepath.Rel(r.Path, p)
+		if rerr == nil {
+			unread = append(unread, filepath.ToSlash(rel))
+		}
+	}
 	walkErr := filepath.WalkDir(r.Path, func(p string, d fs.DirEntry, err error) error {
 		if err != nil {
+			notRead(p, err)
 			if d != nil && d.IsDir() {
 				return fs.SkipDir
 			}
@@ -208,15 +230,17 @@ func (r *Root) Scan(opt Options) (*Manifest, *Step, error) {
 		}
 		info, ierr := d.Info()
 		if ierr != nil {
+			notRead(p, ierr)
 			return nil
 		}
-		e := Entry{Size: info.Size(), MTime: info.ModTime().UnixNano(), Inode: inodeOf(info)}
-		if old, ok := prev.Files[rel]; ok && old.Size == e.Size && old.MTime == e.MTime && old.Inode == e.Inode && e.MTime < racy {
+		e := Entry{Size: info.Size(), MTime: info.ModTime().UnixNano(), Inode: inodeOf(info), CTime: ctimeOf(info)}
+		if old, ok := prev.Files[rel]; ok && old.Size == e.Size && old.MTime == e.MTime && old.Inode == e.Inode && old.CTime == e.CTime && e.MTime < racy {
 			e.Hash = old.Hash
 		} else {
 			h, herr := r.hashAndKeep(p, e.Size, opt.SizeCap)
 			if herr != nil {
-				return nil // unreadable now; absent from this manifest, seen again next time
+				notRead(p, herr)
+				return nil
 			}
 			e.Hash = h
 		}
@@ -227,8 +251,14 @@ func (r *Root) Scan(opt Options) (*Manifest, *Step, error) {
 		return nil, nil, walkErr
 	}
 	next.To = now().UTC().Format(time.RFC3339Nano)
+	sort.Strings(unread)
+	for p, old := range prev.Files {
+		if _, ok := next.Files[p]; !ok && under(p, unread) {
+			next.Files[p] = old
+		}
+	}
 
-	step := &Step{N: next.N, From: next.From, To: next.To, Changes: map[string]PathChange{}, Partial: timedOut}
+	step := &Step{N: next.N, From: next.From, To: next.To, Changes: map[string]PathChange{}, Partial: timedOut, Unread: unread}
 	for p, e := range next.Files {
 		if old, ok := prev.Files[p]; !ok || old.Hash != e.Hash {
 			before := ""
@@ -294,7 +324,7 @@ func (r *Root) Touch(rel string, opt Options) (*Step, error) {
 		if herr != nil {
 			return nil, herr
 		}
-		cur = &Entry{Size: info.Size(), MTime: info.ModTime().UnixNano(), Inode: inodeOf(info), Hash: h}
+		cur = &Entry{Size: info.Size(), MTime: info.ModTime().UnixNano(), Inode: inodeOf(info), CTime: ctimeOf(info), Hash: h}
 	case serr != nil && !os.IsNotExist(serr):
 		return nil, serr
 	}
@@ -323,6 +353,17 @@ func (r *Root) Touch(rel string, opt Options) (*Step, error) {
 	return step, nil
 }
 
+// under says whether a path is one of the paths given, "." for the root, or
+// lies below one.
+func under(p string, paths []string) bool {
+	for _, u := range paths {
+		if u == "." || p == u || strings.HasPrefix(p, u+"/") {
+			return true
+		}
+	}
+	return false
+}
+
 // excluded says whether a path lies under a pruned directory.
 func excluded(rel, root string, rules Rules) bool {
 	if rules == nil {
diff --git a/plugins/claude-code/internal/scan/scan_test.go b/plugins/claude-code/internal/scan/scan_test.go
index 7aacfc4..72125d5 100644
--- a/plugins/claude-code/internal/scan/scan_test.go
+++ b/plugins/claude-code/internal/scan/scan_test.go
@@ -21,6 +21,8 @@ import (
 	"errors"
 	"os"
 	"path/filepath"
+	"runtime"
+	"strings"
 	"testing"
 	"time"
 
@@ -148,6 +150,71 @@ func TestScanStopsAtItsTimeCap(t *testing.T) {
 	}
 }
 
+// A directory or a file the scan cannot read is still there. A tool that ran
+// chmod 000 on it made every file under it look deleted, with the step
+// complete, and restoring access then made them look created. What cannot be
+// read keeps what the last scan saw, and the step names it as not observed.
+func TestWhatAScanCannotReadIsNotDeleted(t *testing.T) {
+	if runtime.GOOS == "windows" || os.Geteuid() == 0 {
+		t.Skip("permission bits do not stop this reader here")
+	}
+	ws := t.TempDir()
+	write(t, filepath.Join(ws, "a.txt"), "a\n")
+	write(t, filepath.Join(ws, "sub", "b.txt"), "b\n")
+	write(t, filepath.Join(ws, "sub", "deep", "c.txt"), "c\n")
+	write(t, filepath.Join(ws, "locked.txt"), "l\n")
+	// Older than the scan before, so the scan takes its hash from what it
+	// saw: chmod changes neither the size, the modification time nor the
+	// inode it compares.
+	old := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
+	if err := os.Chtimes(filepath.Join(ws, "locked.txt"), old, old); err != nil {
+		t.Fatal(err)
+	}
+	r, err := scan.Open(t.TempDir(), ws)
+	if err != nil {
+		t.Fatal(err)
+	}
+	o := scan.Options{SizeCap: 1 << 20, Now: steady()}
+	m1, _, err := r.Scan(o)
+	if err != nil || len(m1.Files) != 4 {
+		t.Fatalf("first scan: %v %v", m1.Files, err)
+	}
+	for _, p := range []string{"sub", "locked.txt"} {
+		if err := os.Chmod(filepath.Join(ws, p), 0); err != nil {
+			t.Fatal(err)
+		}
+	}
+	t.Cleanup(func() {
+		_ = os.Chmod(filepath.Join(ws, "sub"), 0o755)
+		_ = os.Chmod(filepath.Join(ws, "locked.txt"), 0o644)
+	})
+	write(t, filepath.Join(ws, "a.txt"), "A\n")
+	m2, step, err := r.Scan(o)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(step.Changes) != 1 || step.Changes["a.txt"].After == "" {
+		t.Fatalf("the step records %v; want only the change to a.txt", step.Changes)
+	}
+	if got := strings.Join(step.Unread, " "); got != "locked.txt sub" {
+		t.Fatalf("the step names %q as not read, want the directory and the file", got)
+	}
+	for _, p := range []string{"sub/b.txt", "sub/deep/c.txt", "locked.txt"} {
+		if m2.Files[p] != m1.Files[p] {
+			t.Fatalf("%s: the manifest has %+v, want what the last scan saw, %+v", p, m2.Files[p], m1.Files[p])
+		}
+	}
+	if err := os.Chmod(filepath.Join(ws, "sub"), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	if err := os.Chmod(filepath.Join(ws, "locked.txt"), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	if _, step, err := r.Scan(o); err != nil || len(step.Changes) != 0 || len(step.Unread) != 0 {
+		t.Fatalf("access back: changes %v unread %v err %v; want nothing", step.Changes, step.Unread, err)
+	}
+}
+
 func TestPendingNotes(t *testing.T) {
 	r, _ := scan.Open(t.TempDir(), t.TempDir())
 	if err := r.PutPending(&scan.Pending{Capture: "toolu_1", Tool: "toolu_1", Before: 3, At: "2026-09-08T10:00:00Z"}); err != nil {
diff --git a/plugins/claude-code/main_test.go b/plugins/claude-code/main_test.go
index bfa14e8..ed3a3bd 100644
--- a/plugins/claude-code/main_test.go
+++ b/plugins/claude-code/main_test.go
@@ -22,6 +22,7 @@ import (
 	"fmt"
 	"os"
 	"path/filepath"
+	"runtime"
 	"strings"
 	"testing"
 	"time"
@@ -160,6 +161,60 @@ func TestAShellCommandIsObservedEndToEnd(t *testing.T) {
 	}
 }
 
+// A shell command that makes a directory unreadable deletes nothing. The
+// record said every file under it was deleted, with coverage complete. It
+// says the directory was not observed, and when access comes back, nothing
+// under it is found as created by nobody.
+func TestADirectoryMadeUnreadableIsNotObservedRatherThanDeleted(t *testing.T) {
+	if runtime.GOOS == "windows" || os.Geteuid() == 0 {
+		t.Skip("permission bits do not stop this reader here")
+	}
+	data := t.TempDir()
+	ws := t.TempDir()
+	sub := filepath.Join(ws, "secrets")
+	if err := os.MkdirAll(sub, 0o755); err != nil {
+		t.Fatal(err)
+	}
+	if err := os.WriteFile(filepath.Join(sub, "key.txt"), []byte("k\n"), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(func() { _ = os.Chmod(sub, 0o755) })
+	now := time.Date(2026, 9, 8, 10, 0, 0, 0, time.UTC)
+	const session = "11111111-2222-4333-8444-555555555555"
+	window := func(tool, cmd string, at time.Time, during func()) {
+		t.Helper()
+		runHook(strings.NewReader(hookInput("PreToolUse", session, "", "Bash", tool, cmd, "", "")), data, ws, at)
+		during()
+		runHook(strings.NewReader(hookInput("PostToolUse", session, "", "Bash", tool, cmd, `{"stdout":"","stderr":""}`, "")), data, ws, at.Add(time.Second))
+	}
+	window("toolu_1", `{"command":"chmod 000 secrets"}`, now, func() {
+		if err := os.Chmod(sub, 0); err != nil {
+			t.Fatal(err)
+		}
+	})
+	recs := readLines(t, output.Path(data, session, "main"))
+	if len(recs) != 1 {
+		t.Fatalf("records: %d", len(recs))
+	}
+	if r := recs[0]; *r.ChangedFiles != 0 || r.Coverage != changes.CoveragePartial || len(r.Gaps) != 1 || !strings.Contains(r.Gaps[0], "secrets") {
+		t.Fatalf("record: changed=%d coverage=%s gaps=%v changes=%+v; want nothing deleted and secrets not observed",
+			*r.ChangedFiles, r.Coverage, r.Gaps, r.Changes)
+	}
+	window("toolu_2", `{"command":"chmod 755 secrets"}`, now.Add(10*time.Second), func() {
+		if err := os.Chmod(sub, 0o755); err != nil {
+			t.Fatal(err)
+		}
+	})
+	recs = readLines(t, output.Path(data, session, "main"))
+	if len(recs) != 2 {
+		t.Fatalf("records: %d; a gap record says something changed between the calls", len(recs))
+	}
+	if r := recs[1]; r.Tool != "toolu_2" || *r.ChangedFiles != 0 || r.Coverage != changes.CoveragePartial {
+		t.Fatalf("record: tool=%s changed=%d coverage=%s; want nothing created, and partial since the BEFORE scan could not read secrets",
+			r.Tool, *r.ChangedFiles, r.Coverage)
+	}
+}
+
 // TestAnEditInsideASubagentComesFromTheResponse: the runtime records no
 // patch in a subagent's transcript, so the plugin takes it from the hook.
 func TestAnEditInsideASubagentComesFromTheResponse(t *testing.T) {
diff --git a/tests/chain/repack_test.go b/tests/chain/repack_test.go
index a0b9c99..12182ad 100644
--- a/tests/chain/repack_test.go
+++ b/tests/chain/repack_test.go
@@ -271,9 +271,10 @@ func TestRepackFitsEveryFileInItsBudget(t *testing.T) {
 // into the new root computes them. Each cursor names the file holding the
 // last record its own source landed. Collection into the new root goes on
 // from where each source stopped: it lands nothing, then only the records
-// appended since, and the new root parses and verifies. Records of two files
-// are cut into one only when the files' headers are the same, so every file
-// names its own source.
+// appended since, and the new root parses and verifies. Each source other than
+// the first lands under a src of its own, its path marked with its first line,
+// and records of two files are cut into one only when the files' headers are
+// the same, so every file names its own source.
 func TestRepackCarriesTheCursorOfEveryRecorderRoot(t *testing.T) {
 	const session = "11111111-2222-4333-8444-555555555555"
 	line := func(id, tool string) string {
@@ -342,7 +343,7 @@ func TestRepackCarriesTheCursorOfEveryRecorderRoot(t *testing.T) {
 				}
 				return out
 			}
-			if a, b := sources(src), sources(dst); !reflect.DeepEqual(a, b) || len(a) != 2 {
+			if a, b := sources(src), sources(dst); !reflect.DeepEqual(a, b) || len(a) != 3 {
 				t.Fatalf("the files name the sources %v; the source root's name %v", b, a)
 			}
 			before, after := cursorsIn(t, src, session), cursorsIn(t, dst, session)
@@ -380,6 +381,107 @@ func TestRepackCarriesTheCursorOfEveryRecorderRoot(t *testing.T) {
 	}
 }
 
+// TestRepackRenamesTheCursorsOfALaterFile. A recorder inside the storage root
+// writes its origin relative to it, and the plugin there removed its output
+// file and wrote it again, twice. The first file at the path keeps the
+// recorder's own cursor, named for its origin and its path. Each later file
+// has a cursor named for its origin, its path and the first line of the file
+// before it. A repack writes the origin again for the new root, and must name
+// every one of those cursors as a collector into the new root computes them:
+// a later file's cursor kept under its old name was not found, and its file
+// was read from its start and landed again.
+func TestRepackRenamesTheCursorsOfALaterFile(t *testing.T) {
+	const session = "11111111-2222-4333-8444-555555555555"
+	line := func(id string) string {
+		r := &changes.Record{Schema: changes.Schema, ID: id, CapturedBy: changes.CapturedByASZPlugin, Session: session,
+			Stream: "main", Tool: "toolu_" + id, ToolName: "Bash", Time: "2026-09-08T02:00:04Z", Basis: changes.BasisToolWindow,
+			Root: &changes.Root{Path: "/w"}, ChangedFiles: changes.Int(0)}
+		b, err := r.Marshal()
+		if err != nil {
+			t.Fatal(err)
+		}
+		return string(b) + "\n"
+	}
+	for _, budget := range []int64{1, 64 << 20} {
+		t.Run(fmt.Sprint(budget), func(t *testing.T) {
+			src := storage.NewZone(t.TempDir())
+			outside, inside := t.TempDir(), filepath.Join(src.Root(), "_recorder")
+			pathIn := func(root string) string {
+				return filepath.Join(root, "file-changes-market", "output", session, "main.jsonl")
+			}
+			add := func(root string, lines ...string) {
+				t.Helper()
+				if err := os.MkdirAll(filepath.Dir(pathIn(root)), 0o755); err != nil {
+					t.Fatal(err)
+				}
+				f, err := os.OpenFile(pathIn(root), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
+				if err != nil {
+					t.Fatal(err)
+				}
+				for _, l := range lines {
+					if _, err := f.WriteString(l); err != nil {
+						t.Fatal(err)
+					}
+				}
+				if err := f.Close(); err != nil {
+					t.Fatal(err)
+				}
+			}
+			again := func(root string, lines ...string) {
+				t.Helper()
+				if err := os.Remove(pathIn(root)); err != nil {
+					t.Fatal(err)
+				}
+				add(root, lines...)
+			}
+			collect := func(z *storage.Zone) int {
+				t.Helper()
+				records := 0
+				for _, root := range []string{outside, inside} {
+					st, err := claudecodechanges.New(root, z, 0).CollectAll(nil)
+					if err != nil || len(st.Errors) > 0 || st.Conflicts != 0 {
+						t.Fatalf("%s: %+v, %v", root, st, err)
+					}
+					records += st.Records
+				}
+				return records
+			}
+			// The outside root arrives first and keeps <kind>.cursor.
+			add(outside, line("o1"))
+			add(inside, line("a1"), line("a2"))
+			want := []int{3}
+			got := []int{collect(src)}
+			again(inside, line("b1"))
+			want, got = append(want, 1), append(got, collect(src))
+			again(inside, line("c1"), line("c2"))
+			want, got = append(want, 2), append(got, collect(src))
+			if !reflect.DeepEqual(got, want) {
+				t.Fatalf("the source root landed %v records; want %v", got, want)
+			}
+			if n := len(cursorsIn(t, src, session)); n != 4 {
+				t.Fatalf("the source root has %d cursors; want one for each of four files", n)
+			}
+			dst := storage.NewZone(t.TempDir())
+			if _, err := repack.Session(src, dst, session, budget, time.Now()); err != nil {
+				t.Fatal(err)
+			}
+			if n := collect(dst); n != 0 {
+				t.Fatalf("collection into the new root landed %d records again", n)
+			}
+			if n := len(cursorsIn(t, dst, session)); n != 4 {
+				t.Fatalf("the new root has %d cursors after a collection; want the four carried, and no new one", n)
+			}
+			parsedAndVerified(t, dst, session)
+			add(outside, line("o2"))
+			add(inside, line("c3"))
+			if n := collect(dst); n != 2 {
+				t.Fatalf("collection into the new root landed %d records; want the two appended", n)
+			}
+			parsedAndVerified(t, dst, session)
+		})
+	}
+}
+
 // cursorsIn reads every cursor of a session's main stream.
 func cursorsIn(t *testing.T, z *storage.Zone, session string) []*storage.Cursor {
 	t.Helper()