session-watcher
llms.txt8 starsChanged 4 months agoMITView on GitHub
A local monitor that estimates when carrying an existing agent context becomes more expensive than rebuilding it, for Claude Code and DeepSeek Harness (DSH). Session Watcher provides restart-cost metrics and handoff tooling for long-running coding sessions, and shows the readings in a dashboard and a statusline under Claude Code and in a tab and a composer dock under DSH. It installs as a Claude Code plugin or as a DSH plugin. Demo: https://nomadop.github.io/session-watcher/demo Core quantities and interpretation for the Session…
In this repository4 other files it gives its agents.
- llms.txtllms.txt
- sw-explainSkill
- sw-handoffSkill
- sw-loadSkill
The file
We split this llms-full.txt into the rules it gives an agent
9 rules. About 0 are common, 8 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈8
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 31
Validity: Always non-negative. Zero before the first model interaction in a segment, or on a true cold-start where no cached context exists …
- Distinctive: line 55
When every tracked resource is scored N, B_default equals the system overhead floor.
- Distinctive: line 115
Validity: Always positive (floored).
- Distinctive: line 299
All conclusions depend on the accuracy of the cache-pricing model (cRatio) for the current provider.
- Distinctive: line 488
When Claude Code restarts within a grace window, the hook sends the new session-id.
- Very specific: line 496
When a session ends, the agent can package its working context for the next session.
- Distinctive: line 539
Folding: When multiple snapshots share the same primary key, only the revision with the highest total token count is retained.
- Distinctive: line 648
Add the package to a DSH profile:
- Distinctive: line 664
If a session's watcher fails, it stops measuring that session and keeps the diagnostic that made it fail.
≈ “Common” is an estimate: at least 1 in 5 of the 4,067 llms.txt files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
# Session Watcher
> A local monitor that estimates when carrying an existing agent context becomes more expensive than rebuilding it, for Claude Code and DeepSeek Harness (DSH).
Session Watcher provides restart-cost metrics and handoff tooling for long-running coding sessions, and shows the readings in a dashboard and a statusline under Claude Code and in a tab and a composer dock under DSH. It installs as a Claude Code plugin or as a DSH plugin.
Demo: https://nomadop.github.io/session-watcher/demo
---
## Concepts
Core quantities and interpretation for the Session Watcher measurement system.
This page defines the user-visible metrics and cost-model quantities. Each entry lists the canonical name, its API field, units, a plain-language definition, and validity conditions; a threshold entry lists the constant and where it lives instead of a field. For stable behavioral guarantees, see the Guarantees page.
---
### Position Axis
Quantities that locate the session on the token-position number line.
#### L (Effective Context Length)
**API field.** `L`
**Units.** tokens
**Definition.** The authoritative size of the context the model is currently reading. Normally equals the cache-read token count from the latest API response. When a cache miss is detected (cache eviction mid-session), L is reconstructed as the whole context stock — input, cache-read and cache-creation — so the metrics see a continuous value rather than a cliff.
**Validity.** Always non-negative. Zero before the first model interaction in a segment, or on a true cold-start where no cached context exists yet.
#### B (Baseline)
The baseline measures how many tokens the model would need to re-ingest if the session restarted now.
##### B_full
**API field.** (internal — drives all decision math)
**Units.** tokens
**Definition.** The complete rebuild cost: the system overhead floor plus the sum of all tracked file contributions. B_full is the system's unfiltered belief about what a restart would cost.
**Validity.** Non-negative. Positive from the first step with a positive context stock on, because the system overhead floor and the tracked contributions together are then at least that stock. Content a tool result tracked before that step can make it positive earlier.
##### B_default
**API field.** `bDefault` (also exposed as `B` in the top-level status, display-capped)
**Units.** tokens
**Definition.** The subset of B_full that a restart would rebuild: the system overhead floor plus what each tracked resource contributes at its score. A file is scored N (nothing), R (its first and last lines), S (the symbols its lines fall in) or A (every line it holds); a skill is scored N or A. A file counts at most what the session holds of it. Until scored, a file counts at A and a skill at N. This is the value used as the position denominator throughout the cost model.
When every tracked resource is scored N, B_default equals the system overhead floor. While B_default is zero, the baseline validity gate withholds every position quantity except the position ratio, which reports its fallback.
The public API field `B` is a display-capped version of B_full that ensures the physical invariant B ≤ totalStock holds during transient cache-creation lag. The cap self-releases once the provider's cache catches up.
**Validity.** `0 ≤ B_default ≤ B_full`. Positive once the system overhead floor is positive or the baseline holds content its scores count. It stays zero when the first stock was wholly covered by tracked content that the scores leave out, since the floor is then zero.
#### System Overhead (Floor)
**API field.** (internal component of B)
**Units.** tokens
**Definition.** The context a restart rebuilds beyond the content tracked per file, skill and tool: system prompt, tool definitions, conversation scaffolding and, after a compact, the summary the harness carried over. Anchored once per segment by the first step with a positive context stock (input, cache-read and cache-creation together), less the content already tracked as resident per file, skill and tool when that step arrived, and floored at zero, so content the call carries and a tracked resource can re-read counts once, in its own row. The whole of that first stock is kept apart as the session floor, which the handoff's estimate of the rebuilt size adds to the kept paths.
**Validity.** Set once per segment. Zero before the first positive stock, and zero after it when the whole stock was already tracked as resident.
#### x (Position Ratio)
**API field.** `x`
**Units.** dimensionless ratio
**Definition.** How far the session has travelled past its baseline: `x = L / B_default`. At x=1 you are at baseline (no growth above the carry). At x=2 the context has doubled beyond baseline. The entire cost model is parameterized in terms of x.
**Validity.** Meaningful when baseline is valid (B_default > 0 and cRatio > 0). Falls back to 1 otherwise.
#### u (Normalized Position)
**API field.** `u`
**Units.** dimensionless (restart intervals)
**Definition.** How far along its own cost cycle the session has actually travelled, counted in restart intervals. Each API call adds the fraction of a restart interval that the baseline in force and the realized mean growth of the context outside that baseline imply at that moment, so the count only ever moves forward and is never re-valued: a baseline that grows later changes how fast the count advances from then on, not the distance already covered. One completed interval is the sweet spot; less is the early side, more is the late side. This is the authoritative position — the lamp, the verdict and every landmark read it.
**Validity.** Zero until the segment has realized growth over a settled interval, positive afterwards. Null when the baseline is invalid.
#### reference (Reference Skeleton)
**API field.** `rateLamp.reference`
**Definition.** The straight-line relation between position ratio and normalized position, fitted across the whole path the segment has travelled. Every landmark on the position axis — the sweet spot, the warning boundary on each arm and the critical boundary — is read off this line, so they move together as the fit sharpens. While the session is still short of the sweet spot the fit is reported as provisional.
**Validity.** Present once the segment's stamped points span more than a single normalized position and the fit rises; absent otherwise, and when it is absent every position landmark is absent with it.
---
### Rate Axis
Quantities measuring how fast context is growing.
#### g (Growth Rate)
**API field.** `g`
**Units.** tokens/call (smoothed)
**Definition.** The effective growth rate of unexplained context accumulation per API call. Computed as a single-exponential level filter with a per-call step cap over the per-call residual — the growth of total context stock that known file operations do not account for. Floored at a minimum value to prevent cold-start artifacts. The position (u) is not read from it: the position fold prices each interval at the realized mean growth of the context outside the scenario's baseline, so a file the baseline leaves out counts as growth rather than disappearing from both sides.
**Intuition.** "How fast is new context arriving each turn?" A high g means content is accumulating rapidly; the cost model responds by widening the optimal zone (recommending longer cycles before restart).
**Validity.** Always positive (floored). Reflects the smoothed level once several interactions have occurred.
#### residual
**API field.** (internal — feeds g)
**Units.** tokens
**Definition.** The per-interaction growth of total context stock, net of the growth known file operations account for. This is the "unexplained growth" that feeds the growth-rate smoother: reasoning tokens, tool output framing, conversation structure, and any content the system cannot trace to a specific file.
**Validity.** Non-negative. It is read from total stock rather than from L: content parks in cache creation before cache reads advance, and total stock carries no such lag, so a file read cannot surface as a residual spike while its tokens are still in transit.
---
### Cost Axis
Quantities from the EOQ (Economic Order Quantity) cost model that drive the restart recommendation.
#### dhat (Nucleus)
**API field.** `dhat`
**Units.** dimensionless
**Definition.** The characteristic scale of the cost model, derived from an inventory-theory analogy. Computed from the restart cost ratio, the rate the position fold runs on, and the baseline that rate is measured against, at the latest reading. A larger dhat means restarts can be delayed longer before cost rises significantly.
Note: the landmarks on the position axis are not placed from dhat — they are read off the reference skeleton, which is fitted to the path the session travelled rather than derived from the latest reading. dhat is reported as a diagnostic beside the raw position ratio, and nothing in the lamp, the verdict or the reminder reads it.
**Validity.** Positive when the baseline is valid and the segment has realized growth over a settled interval; zero before that. Null when the baseline is invalid.
#### xSweet (Sweet Spot)
**API field.** `xSweet`
**Units.** dimensionless (position ratio)
**Definition.** The position ratio at which the bill premium is minimized: the reference skeleton read off at one completed restart interval. It is where the sweet spot sits on the position-ratio axis, which is what a chart needs to draw it; which arm the session is on is decided by normalized position rather than by comparing x to this value.
**Validity.** Defined whenever the reference skeleton is. It is that skeleton evaluated at `u = 1`, and the skeleton's slope is only required to be positive and finite, so an early fit can place it at or below `x = 1`.
#### pp (Position Penalty)
**API field.** `pp`
**Units.** dimensionless (0 to unbounded)
**Definition.** The timing-penalty shape on its own, before any scaling by how much of the bill timing can move. It is zero at the sweet spot and rises on both sides, gently on the early side and without bound on the late side. Bill premium is this quantity multiplied by the movable fraction.
**Validity.** Non-negative when defined. Null while the position is still zero — until the segment has realized growth over a settled interval — and when the baseline is invalid.
#### br (Bill Premium)
**API field.** `br`
**Units.** dimensionless (0 to unbounded)
**Definition.** The excess cost relative to optimal timing at the normalized position the session has actually reached. Measures how much more expensive the path travelled is compared to stopping at the sweet spot.
bp combines two factors: (1) the position penalty, which grows as the session moves away from the sweet spot in either direction, and (2) the movable fraction that scales this penalty by how much of the total cost is actually timing-sensitive. bp=0 at the sweet spot.
**Lamp behavior.** Which arm the session is on is decided by normalized position, never by the position ratio against xSweet. On the right arm the lamp is green below `BR_AMBER`, amber above it, red above `BR_RED`. On the left arm the lamp shows white until the position reaches the mirror image of the amber boundary and green from there to the sweet spot; the warning and critical colours are right-arm states only, because the mathematical penalty at cold start is operationally meaningless. The reminder is a separate mechanism and reads accumulated rent rather than bp, so it is not conditioned on the arm.
**Validity.** Non-negative when defined. Null while the position penalty is null and when the baseline is invalid.
#### mf (Movable Fraction)
**API field.** `mf`
**Units.** dimensionless fraction (0 to 1)
**Definition.** The proportion of total session cost that is timing-sensitive — could theoretically be avoided by optimal restart timing. The remainder is unavoidable overhead (system floor, irreducible growth cost) that no restart strategy can eliminate.
If mf is small, even bad timing costs little. If mf is large, timing matters significantly. mf scales the bill premium so that sessions where restarts matter get earlier alerts. It is path-weighted over the segment's travelled intervals; the reminder clock instead converts each interval's rent at that interval's own fraction.
**Validity.** In range `[0, 1]` when the baseline is valid — exactly zero until the segment has realized any growth — and null on the segment's first measured call or when the baseline is invalid. The AM-GM inequality bounds it at `1/(1+√2)`, except on DSH after an inner compaction: there a request whose calls only read earlier events back or are repeat reads DSH blocked is priced at its own bill and adds no cost that restart timing cannot reach, so the bound is `1`.
#### cRatio (Cost Ratio)
**API field.** `cRatio`
**Units.** dimensionless ratio
**Definition.** The ratio of cache-write price to cache-read price for the current model (C_write / C_read). Determined from a model lookup table — keyed by the model and, where the provider prices cache lifetimes apart, by the prompt-cache lifetime the host declares — or from a user override. "How many reads does one write cost?" A higher cRatio means restarts are more expensive, pushing the sweet spot further out.
**Validity.** Always positive.
#### wallP (Rate Wall Position)
**API field.** `rateLamp.wallP`
**Units.** dimensionless (position ratio)
**Definition.** The x-position at which one more call's avoidable rent equals a complete rebuild: `wallP = 1 + cRatio`. At this point the session is consuming cache-read budget as fast as one restart cycle can replenish it.
Note: wallP is NOT guaranteed to exceed xSweet. The fitted sweet spot can land beyond the rate wall, so wallP is the rate-saturation marker, not an unconditional "past optimal" signal.
**Validity.** Computed whenever baseline is valid. Always greater than 1.
---
### Operations Axis
Quantities that drive the restart reminder and display indicators.
#### backstopInterval
**API field.** `rateLamp.rentMeter.backstopInterval`, with the fill in `rateLamp.rentMeter.depthProgress`
**Units.** bill cycles (dimensionless)
**Definition.** How much accumulated rent one reminder is worth, measured in rebuild-equivalent bill cycles: it is half the bill a session would run up travelling from a fresh start to the amber premium, so on an idealized static cycle from a fresh start the second reminder lap lands at that premium. The reminder bar fills with the same per-call rent increment that drives the bill cycle, divided by this interval; the call whose increment fills the bar raises a reminder stamped with the lap count reached and wraps the bar, so a call large enough to fill it more than once is announced by that stamp rather than by a reminder per lap. The interval is set by the exchange fraction in force for the interval being converted: a higher fraction (more at stake) shortens it; a lower one lengthens it, so loading a large file slows the clock from then on without rewinding it. Because the unit is accumulated rent rather than wall time, the reminder arrives sooner in expensive sessions and later in cheap ones — and because the reminder reads accumulated rent alone, nothing about the measured position can retract a reminder already raised.
**Validity.** A finite positive number of bill cycles while the current interval's exchange fraction is positive. The wire carries `null` whenever it is not — including before the segment has realized any growth — and while it does, the wallet clock holds where it stands and raises no reminder.
#### BR_AMBER
**Constant.** `BR_AMBER` in `lib/bill-regret.js`
**Definition.** The bill-premium threshold at which the session enters the warning zone. It also sets the reminder's scale: the reminder interval is half the accumulated bill between a fresh start and this premium.
#### BR_RED
**Constant.** `BR_RED` in `lib/bill-regret.js`
**Definition.** The higher bill-premium threshold for the red/critical zone. Used for lamp color only; the reminder's scale comes from `BR_AMBER`.
#### Lamp States
The statusline lamp is a visual indicator synthesized from bp and normalized position:
| State | Condition |
|-------|-----------|
| White | bp is not computable, OR left arm below the mirrored amber boundary |
| Green | Right arm with bp < `BR_AMBER`; OR left arm past the mirrored amber boundary |
| Amber | bp ≥ `BR_AMBER` and bp < `BR_RED` (right arm only) |
| Red | bp ≥ `BR_RED` (right arm only) |
The arm is read from normalized position, so a session that has not yet reached the sweet spot is never treated as "overstaying" however large its numerical bp.
---
### Structure Axis
Quantities describing the per-path token map and its maintenance.
#### pathTotal
**API field.** `tokens` (in bucket data)
**Units.** tokens
**Definition.** Each tracked file's contribution to B: the sum of the token counts of the lines it holds in context, minus any calibration correction, floored at zero. Summed across all paths (plus the system overhead floor) to produce B_full.
**Validity.** Non-negative.
#### scenario (Position Preview)
**API field.** `scenario`, the answer of `POST /api/preview`
**Definition.** The session's whole position history re-folded under a candidate batch of resource scores, so the dashboard can show where the session would sit if those scores were applied. It carries the candidate path, its landmarks and its premium. Asking for one applies nothing and tells nothing else: the position already on screen stays where it was, and applying the same scores afterwards produces the same numbers. A transcript replay refuses the request, because the preview would be folded from the replay's context while the apply would land on the live one.
**Validity.** Reported when measurement is reliable; otherwise the answer says only that it is unavailable.
#### Bucket Types
The system tracks different categories of content:
| Type | Description |
|------|-------------|
| **File path** | A file whose lines a tool call's text holds, recognized by matching the text against the file on disk whichever tool or command printed or wrote it (Read, Write, Edit, grep, a shell command, an MCP tool) |
| **Skill** | Skill/instruction content loaded into context (counted in B_default only when scored A; defaults to N, so it is not counted) |
| **Bash/MCP residual** | The part of a tool call's text that holds no file line, grouped under the tool or command that made the call (contributes to residual growth, not B) |
File paths are canonicalized so that different representations of the same file (`./a.js`, `/cwd/a.js`) map to a single entry, preventing baseline inflation from path fragmentation.
---
## Cookbook
This page collects operational scenarios and guidance for interpreting Session Watcher output. For formal definitions of all terms below, see the Concepts page. For behavioral guarantees, see the Guarantees page.
### Scope and Limits
- Session Watcher is a **cost-timing guardrail**, not a quality evaluator. A metric says you are overpaying — it cannot say the model is degraded or the output is worse.
- All conclusions depend on the accuracy of the cache-pricing model (cRatio) for the current provider. If pricing changes, the sweet spot and bp shift accordingly.
- B, g, and all derived quantities (dhat, xSweet, bp, mf) are measured estimates with defined invalid states. When baseline is invalid the system reports fallback values, not guesses.
- The tool does not decide or execute restarts. It surfaces cost position; the human decides whether to continue, hand off, or restart.
### Lamp / bp Interpretation
**Scenario: bp stuck at red or amber for many turns.**
The session has been running beyond the efficient operating zone for an extended period. bp is read from the path the session actually travelled, not from a snapshot of the current L and B: the normalized position behind it only moves forward, so loading more files no longer pulls the session back toward the sweet spot. What can still lower bp is the movable fraction shrinking as the carry grows, or a change of resource scores or provider, which re-folds the whole segment under the new economics. If bp stays elevated for many turns, the session is persistently in an inefficient region. Consider preparing a handoff and restarting. If the task is nearly complete, finishing may cost less than the overhead of a fresh context rebuild.
**Scenario: White lamp displays throughout the session.**
White indicates one of three states. (1) `no_transcript` — the watcher cannot locate or open the transcript file; verify the path configuration. (2) `insufficient_data` — the transcript exists but no usage rows have been ingested yet (the first API call has not been folded). The system overhead floor is anchored by the first usage row with a positive context stock, so this state resolves on the first model interaction — no file reads are required — unless that whole stock was already tracked as resident content the scores leave out. (3) Healthy low-pressure zone — measurement is reliable, but the normalized position is still short of the sweet spot and below the mirrored amber boundary, which is the pair of conditions the lamp whitens on. This is a normal, efficient state (the session has not yet grown enough for the penalty function to engage). To distinguish these causes, check the reason or reliability field in the status output rather than interpreting white solely as a data-quality problem.
**Scenario: mf seems low.**
The movable fraction is the share of the context bill that restart timing can reach. A low value means most of the cost is fixed overhead — timing optimization has limited leverage. Handoff value is reduced but not zero: the reminder still comes, only at a longer interval, because the wallet clock's unit grows as mf shrinks. A persistently low mf means the session is carry-heavy (large B relative to growth), which is normal for sessions that loaded many files early.
**Scenario: Understanding the two progress bars.**
The dashboard shows two bars. The **cycle bar** shows how far through the current billing cycle you are. It fills with the per-call rent increment; when full it wraps to zero and increments the cycle count. A fast-filling bar means rent is accruing quickly. It is purely diagnostic — it does not trigger anything.
The **reminder bar** is the decision reminder, and it is the only bar the statusline carries. It fills with the same rent increment, divided by the reminder interval (which adapts to mf — shorter when restart value is high). It is running from the first measured call rather than waiting for a threshold: the call whose increment fills the bar raises a reminder stamped with the lap count reached and wraps the bar, and the magazine beside it spends one tick per completed lap up to its visible slots and then counts the rest in an overflow label — so a call that fills the bar more than once leaves the laps ahead of the reminders raised. The reminder bar tells you "you have paid enough carry rent to be worth a decision," and because it reads accumulated rent alone, adjusting the baseline or the scores cannot take back a reminder already given.
**Scenario: bp seems wrong for what you are doing.**
bp is only as good as B_default. If B_default does not reflect the files you actually need for the current task, bp will be miscalibrated. Common cases: (1) the session loaded many large files early that are no longer relevant — B_default is inflated, bp appears lower than reality. (2) Critical working files or skills are scored N (a skill counts nothing until scored A) — B_default understates the real carry, bp appears higher than warranted. Before trusting an amber/red signal (or an unexpectedly green one), sanity-check the bucket panel: does B_default match what you would actually carry into a new session? If not, adjust the scores first.
**Scenario: Provider switch causes a bp jump.**
Switching models mid-session changes cRatio (the cache-write-to-cache-read price ratio). Since bp depends on cRatio through mf and dhat, a ratio change recalculates the cost geometry instantly. The jump is not an error — it reflects genuine repricing of the session under new economics. If the new model has a lower cache-write/cache-read ratio, the sweet spot moves inward and the session may enter amber sooner; if higher, the session gets more room before penalty engages.
### When to Restart
**Scenario: bp crosses amber (the first threshold).**
Amber signals that the timing-sensitive cost premium at the position travelled has reached a noticeable level. This is a suggestion, not a command. If a natural stopping point exists (task boundary, topic shift), this is a good time to prepare a handoff. If mid-task, weigh the cost of context rebuilding against the ongoing overspend.
**Scenario: bp crosses red (the higher threshold).**
Red means the overspend fraction is substantially higher. However, red does not mean "restart immediately." If the current task will complete in a few more turns, finishing is usually cheaper than the disruption cost of a handoff plus the tokens spent rebuilding context in a new session. Red is most actionable at natural task boundaries.
**Scenario: Mid-task bp is red but work is nearly done.**
Finish the task. The marginal cost of a few more turns at elevated bp is typically less than the fixed cost of preparing a handoff, starting a new session, loading context, and re-orienting. Use bp red as a signal to avoid starting additional unrelated tasks in this session.
**Scenario: The session sits in a flat valley just past sweet.**
When u (the normalized position) is only moderately above 1, the overspend grows slowly. The cost function is quadratic near the sweet spot, so a 2x deviation in u from sweet costs only about 25% additional bill on the timing-sensitive fraction. Flat valleys are efficient enough to continue working through.
**Scenario: Applying a fixed token policy ("restart at 200k tokens").**
Fixed-token restart policies ignore the session's actual economics. A session with high g (rapid growth) reaches amber at a higher L than one with low g — higher g increases dhat (the characteristic scale), which pushes the sweet spot and amber threshold further out, giving more room before the premium engages. A session with low mf (mostly dead weight) may never benefit from restart regardless of total size. Use bp directly — it already integrates L, B, g, and cRatio into a single actionable signal.
### Measurement Bias and Conservative Assumptions
**Scenario: B_default leaves out resources the session works with.**
B_default counts each resource at its score: a file scored N, or a skill left at its default N, contributes nothing. If your session heavily relies on such resources, B_default understates the true required carry. The session will appear to have a higher premium than it actually deserves. Score the critical ones at the tier the continuation needs, in the bucket panel or with `apply_scores`, so the measurement accounts for them.
**Scenario: Residual is large — is it all waste?**
The residual bucket (context stock minus B) captures everything not attributed to tracked file paths: reasoning history, tool output, conversation structure, and ephemeral working memory. (System prompts and tool definitions are part of the system overhead floor, which is already included in B — they do not appear in the residual.) Much of this is productive context, not waste. A large residual is normal for tool-heavy sessions. The metric does not judge the value of residual content — only that it exists and contributes to cost.
**Scenario: g is climbing but the session feels productive.**
The growth rate g measures how fast new content arrives relative to the baseline. It does not distinguish productive growth (new files being explored, code being written) from thrashing (repeated failed attempts generating tool output). A high g means cost is accumulating quickly regardless of cause. If the growth is productive, the session is efficiently using expensive context; bp still applies as the cost signal.
**Scenario: mf seems capped below 50%.**
The movable fraction has a theoretical ceiling of `1/(1+√2)` (the AM-GM bound). This is by construction: timing optimization can affect at most this fraction of total bill. The one exception is DSH after an inner compaction, where a request whose calls only read earlier events back or are repeat reads DSH blocked is priced at its own bill and adds no cost that restart timing cannot reach, so the ceiling there is `1`. However, bp itself is NOT bounded by this ceiling. Since bp equals mf multiplied by the positional penalty pp, and pp is unbounded (it grows without limit as u deviates from 1), bp can exceed any fixed value in a sufficiently extended session. The mf bound limits only the movable-fraction component, not the overall bill premium.
**Scenario: Detected cache miss during the session.**
When a cache miss is detected (cacheRead falls below a fixed fraction of the previous step's L), L is reconstructed as the whole context stock — it does not drop to near zero. The miss classifier recognizes this pattern and applies that reconstruction, so the metrics see a continuous L rather than a transient cliff. Segmentation is a separate question with a single answer: a topology change (a root UUID that is not the file's first, which is what /compact and /continue produce). A cache miss is not one, a falling token total is not one, and new files entering the B bucket are not one. Undetected misses (patterns that do not match the miss classifier) are not explicitly handled, but are rare in practice.
**Scenario: "Metric says amber but the session feels fine" / "Metric says green but output quality dropped."**
Session Watcher measures cost geometry, not output quality. Amber/red means you are paying more than optimal timing would require — the model may still be performing well. Conversely, green means cost is efficient — but the model could be producing poor output due to task difficulty, prompt issues, or capability limits. Never use lamp state as a quality proxy.
### Handoff Operations
Shortest path: `/sw-handoff` → `/clear` → `/sw-load`.
**Scenario: Verifying carry quality after loading a handoff.**
After `load_handoff` on Claude Code, the agent receives the handoff package: a list of kept paths (each a path with the line ranges to read; an entry without line ranges is skipped and listed) and a summary. The response does NOT include actual file content — the agent must read kept paths itself. On DSH the `/sw-load` command delivers the package and reads the kept paths for the model, which receives the results with the payload. To verify carry quality, read the kept paths and confirm they still exist and contain the expected content. Hash validation exists internally (the server stamps content hashes at load time for telemetry) but is not exposed in the agent-visible response. B_default recovery depends on which kept files are still readable when the agent accesses them in the new session.
**Scenario: Handoff completed but new session B is lower than expected.**
`load_handoff` retrieves the handoff package but does not validate file existence or fail on missing files. Files that have been deleted, renamed, or moved since prepare time will still appear in the returned paths list — the shortfall surfaces only when the agent (or the fold stream) attempts to read those files and finds them absent. On DSH `/sw-load` makes that attempt itself and names the paths it could not read in its follow-up. This is expected: B reflects actual current file state, not the historical snapshot from prepare time. To diagnose, compare the paths in the loaded package against what exists on disk.
**Scenario: Choosing which paths to keep during prepare.**
A handoff keeps what the resource tiers keep. Score the files central to the next task with `apply_scores` — A for what the continuation edits, S or R for what it needs in part — and set the rest to N before `prepare_handoff`, with `others: "N"` in the same `apply_scores` call; a skill is kept only at A. Carrying too much inflates B without proportional value; carrying too little means the new session must rediscover context. Aim for the minimal set that lets the next session avoid re-reading core files.
**Scenario: Understanding the load token.**
The load token is a human-readable semantic identifier (two content words plus a random suffix, e.g., `refactor-baseline-elk`) generated from the handoff's next_task field. Use it to retrieve a specific handoff with `load_handoff` on Claude Code or `/sw-load <token>` on DSH. Tokens are unique within a project's handoff store. If you lose the token, the Claude Code tool's free-text `query` parameter searches by summary content. On DSH the Web composer has a read-only lookup: choosing `/sw-load` from the slash menu, or pressing Enter on a bare `/sw-load` with no attachment, opens a picker over the handoffs the project still retains, delivered ones and this session's own included, searchable by token or task text; selecting a row only fills the composer with `/sw-load <token>`, and nothing loads until you submit it. A bare `/sw-load` that still reaches the command, such as a command claim submitted with no arguments, is a load, not a listing. With one eligible handoff it delivers it at once, binding it to the session and waking the model; with several it lists them with their tokens and loads none; with none it answers that nothing was found. Only handoffs other sessions of the project prepared and nobody has delivered are eligible, within the recent candidate window ([Commands](https://nomadop.github.io/session-watcher/docs/dsh/#commands) has the rule), so a handoff already delivered or prepared by this session is never among them. Save the token when `prepare_handoff` returns it; a token is not a guarantee that an expired or purged handoff can still be loaded.
### Configuration and Operations
**Scenario: Reading the statusline fields.**
The statusline displays (left to right): lamp emoji (white/green/yellow/red), the reminder bar as a bar and a percentage (progress toward the next reminder, wrapping on each one), bp percentage, u value (normalized position), delta (growth rate g), L/B ratio, and model tag. When the rate lamp is not yet reliable, a neutral "measuring..." line appears instead; when measurement is reliable but no ledger has been matched to the segment, the bar is drawn empty with its percentage slot blank rather than showing a stale value. A reminder appears as a second line.
**Scenario: Scoring specific files.**
Resource scores control how much of each resource counts toward B_default. Scoring a file N removes it from the baseline denominator — the session appears to be carrying less, and bp may increase (same L, lower B). Raising a resource to a higher tier, such as a skill from N to A, adds to the baseline — bp may decrease. R and S count only part of a file.
**Scenario: How long until metrics become reliable after session start.**
Metrics become reliable once `B_default` and `cRatio` are both positive. The system overhead floor is anchored by the first usage row with a positive context stock — the whole stock, less the content already tracked as resident per file, skill and tool, never below zero — and is itself part of B_default, so B_default becomes positive on the first model interaction, no file reads required, unless that whole stock was already tracked as resident and the scores leave it out. The transition from white (measuring) to a computed lamp can therefore happen on the very first usage row. Before that first usage, the system shows white with reason `insufficient_data`. Sessions with no transcript at all show white with reason `no_transcript`.
**Scenario: Dashboard vs statusline — same data source?**
Yes. Both the browser dashboard (served via the built-in HTTP server) and the CLI statusline (rendered by the hook into the terminal status area) read from the same `getStatus()` output on the watcher instance. The dashboard uses SSE for event notification (`tick` and `scan` messages), then fetches full snapshots via REST (`/api/status`, `/api/history`, `/api/buckets`) on each `scan` event; polling is the fallback trigger when SSE is unavailable. The statusline formats a compact single-line summary of the same fields. They always reflect the same underlying state, though the dashboard may show historical chart data that the statusline cannot.
---
## How It Works
Session Watcher is a real-time instrumentation layer for Claude Code sessions. It observes the transcript as it grows, derives position and cost metrics per API call, and delivers them to a browser dashboard. This page describes the logical pipeline, the session lifecycle, and why each stage produces correct results.
### Pipeline
A single API call flows through these stages:
```
Claude Code session
│
▼ writes usage rows into a local transcript
┌──────────────────────────────────────────────┐
│ Incremental read │
│ Only new bytes since last poll are consumed │
└──────────────────────────────────────────────┘
│
▼ parse, build branch topology, find active path
┌──────────────────────────────────────────────┐
│ Fold │
│ Deduplicate by message ID (idempotent), │
│ detect segment boundaries │
└──────────────────────────────────────────────┘
│
▼ one valid usage snapshot per API call
┌──────────────────────────────────────────────┐
│ Measurement │
│ ├─ Baseline (B): per-path token accounting │
│ ├─ Position (L): effective context length │
│ ├─ Growth (g): smoothed residual rate │
│ ├─ Settlement: absorb cache-timing noise │
│ └─ Position fold: u, pp, mf, bp per call │
└──────────────────────────────────────────────┘
│
▼ assembled status snapshot
┌──────────────────────────────────────────────┐
│ Rate lamp │
│ Integrate the stamped rent increment into │
│ two clocks; a wallet rollover reminds │
└──────────────────────────────────────────────┘
│
▼ push to connected clients
┌──────────────────────────────────────────────┐
│ Dashboard │
│ Browser fetches status on each data event, │
│ renders gauges and history chart │
└──────────────────────────────────────────────┘
```
**Why this works:**
- **Incremental read** ensures no data is missed or double-counted regardless of how fast the transcript grows.
- **Idempotent folding** means streaming revisions of the same call never create duplicate entries — only the final snapshot survives.
- **Segment scoping** resets metrics on each context boundary so stale history from a previous context never contaminates current measurements.
- **Settlement** absorbs the timing gap between cache-creation and cache-read: B is credited ahead of L during the lag, and the deferred ledger holds that credit until L confirms it. Any ledger balance un-retired at segment end is treated as estimation error and corrected out of the buckets.
- **Growth smoothing (g)** is a single-exponential level filter with a per-call step cap on the residual (total-stock growth net of the growth known file operations account for), floored so the cold-start diagnostic never divides by zero. It drives the growth readout and the projection slope. The position fold does not read it: each interval is priced at the realized mean growth so far of the context outside the scenario's baseline, which carries no smoothing constant and cannot lag behind what the segment has actually accumulated.
- **Cost chain** maps the session to an EOQ inventory cycle: the fixed restart cost is cRatio × baseline (analogous to the order cost per batch), the per-token cache-read price is the holding cost, growth rate g is the demand rate, and session length in calls is the order quantity. The sweet spot is where amortized restart cost equals accumulated holding cost. This mapping produces a single dimensionless premium (bp) that is comparable across models and session sizes.
- **Causal position** is what bp is read at, and it is accumulated rather than recomputed. Each call adds the fraction of a restart interval that the baseline in force and the realized mean growth outside that baseline imply for that call, so the position is a property of the path the session actually travelled. Re-pricing the whole history against today's baseline — which is what a ratio of current values would do — would let a session that loads a large file appear to have travelled backwards, and would move a reminder that was already earned. Because each interval is priced once, at the state that held while it was being traversed, later growth changes only how fast the position advances from then on. Landmarks on the position axis are placed by fitting a straight line across the travelled path, so they sit on the same evidence rather than on a formula applied to the latest reading.
- **Rate lamp integration** accumulates the same per-call rent increment into two counters: a bill cycle for display, and a reminder interval whose rollover raises the reminder, each increment converted at the exchange fraction in force for its own interval. Reading accumulated rent rather than the momentary premium means reminders follow sustained cost, and nothing about a later position revision can retract one.
### Session Lifecycle
#### 1. Hook (session-start)
Claude Code fires a hook on startup, resume, clear, or compact. The hook discovers the running server, hands it the transcript path, and injects any pending handoff tokens into the session context.
#### 2. Server bootstrap
The MCP entrypoint starts a watcher instance, an HTTP server on a loopback port, and writes a discovery file so that hooks and the statusline can locate it. The server lifecycle is tied to the Claude Code process.
On resume (or any fresh process start with an existing transcript), the watcher reconstructs its state by re-reading the transcript from byte zero — rebuilding the full call history, measurement state, and segment boundaries from the file and from the file attribution stored when each call was first observed, through the same interpretation the live path uses. This is how per-call time series data survives a process restart without a stored copy of the series itself.
#### 3. Polling
A timer drives the pipeline at regular intervals:
1. **Late resolution** — if the transcript did not exist at startup, retry each tick.
2. **Idle gate** — skip ticks when no clients are connected and nothing changed recently.
3. **Poll** — run the full pipeline (read → fold → measure).
4. **Rate-lamp advance** — integrate new samples into the rent ledger and raise any reminder they complete.
5. **Broadcast** — notify connected browsers that fresh data is available.
#### 4. Segmentation
A segment is a contiguous stretch of context between resets. Boundaries come from transcript topology alone — a root UUID that is not the file's first, which is what `/compact` and `/continue` produce. No token total starts a boundary, however steeply it falls: a reset replaces the whole conversation prefix, and only topology states that a prefix was replaced. A compact whose new branch keeps its parent in the file is therefore not seen as a boundary.
On boundary: finalize settlement, archive the segment for history, and reset all metrics to initial state. This ensures the cost model always reflects the current context, not a mixture of old and new.
#### 5. Session rotation
When Claude Code restarts within a grace window, the hook sends the new session-id. The server archives the current segment, switches to the new transcript, and updates its discovery file.
#### 6. Shutdown
On termination or idle timeout: stop timers, close connections, archive the final segment, and remove the discovery file. Segment archival persists profile summaries to SQLite — enough to reconstruct cross-segment trends but not the full per-call time series, which lives only in the current process memory.
### Handoff
When a session ends, the agent can package its working context for the next session. The handoff mechanism bridges the gap between `/clear` (which destroys in-memory context) and the new session (which starts empty).
1. The agent scores what the next task needs — each file at a tier that decides how much of it the handoff keeps, each skill kept or not — guided by the per-path token weights from B. It writes a structured summary (current state and intent, not history) and submits the package, which keeps what those scores give. The server persists this package on its own; nothing about the conversation is selected automatically.
2. On `/clear`, the session-start hook fires for the new session. The hook queries persistent storage, finds the undelivered handoff for this project, and injects a reminder into the session context containing the load token, age, and task preview. The load skill reads this reminder and initiates the restore flow.
3. The load skill extracts the token from the injected reminder, retrieves the handoff package, and reads the kept paths range by range: each entry is a path with the line ranges its tier selected, and an entry without line ranges is skipped and listed so the agent reads it only when a step needs it. As these files are read, they flow through the normal pipeline — fold processes them, and the lines each result holds, matched against the file on disk, are added to B — so the baseline naturally rebuilds to reflect the carried context. The response also carries a page of the history turns behind the handoff — the newest ones that fit a fixed budget, each a user request carrying the note written for it where the turn had one — plus a cursor for the next page, whose presence proves more history remains while its absence does not prove none does. Beside that page it carries the lineage itself: the headlines of the newest lineage members behind the handoff within a fixed budget, the older ones collapsed into runs marked `omitted`, so a successor sees the chain it inherits and not only the session immediately before it. Three read tools go further into that same history: page deeper, search a literal that occurs verbatim, or locate the turn ranges that mention a remembered term; a fourth, `lineage_headlines`, reads the headlines of an omitted run. Each resolves the lineage from the handoff this session loaded, so none of them takes a lineage identifier.
**Why this works**
- **B recovers from disk state, not snapshots.** The handoff carries path references, not cached token counts. If a file was deleted or changed since prepare, B reflects reality — stale entries do not inflate the baseline.
- **Hook injection eliminates manual token passing.** The user does not need to remember or copy a token. The hook discovers and injects it; the agent picks it up on the first interaction.
- **Turn notes preserve trajectory without bulk.** Rather than predicting which turns will matter later, the system records every history turn at the moment the handoff is prepared — each with the note written for it, and a turn with no assistant work of its own recorded without one — then delivers the newest of them as a page under a fixed token budget. What does not fit stays reachable through the read tools instead of being guessed at up front, so the handoff package stays small without discarding the trail that led to it.
---
## Guarantees
Stable externally-observable behavior of the measurement system. Implementation may change; these guarantees hold across versions.
---
### Input Contract
The measurement system requires a stream of structured events. The implementation consumes Claude Code JSONL transcripts and DeepSeek Harness session event logs; the input schema below describes the logical contract both fulfill and any further adapter would.
**Usage snapshot:** Each API interaction produces a snapshot containing:
- A token breakdown with at minimum: input, output, cache-read, and cache-write counts (additional categories such as reasoning may be present depending on the provider)
- An optional primary key (for dedup); when absent, a fallback key may be used; when both are absent the snapshot is treated as unique
- An optional sidechain flag (marks sub-agent or parallel work that should not count toward main-context measurement)
- A timestamp and model identifier
**Context-reset signal:** A structural indicator that the context window has been cleared or compacted. It comes from transcript topology alone — a drop in reported token totals is not one, however steep. The measurement system uses it to trigger segment boundaries.
**Tool-event stream:** Each tool call's input and result text. To compute per-path token contributions to B, the system reads the files the call names and matches the call's text against their lines, whichever tool or command printed or wrote them. A line that matches counts toward its file, at the line where the file holds it; every other character, and the text of a file that is missing, unreadable or binary, counts toward the residual.
---
### Measurement Invariants
Given correct input, the measurement layer guarantees:
**Folding:** When multiple snapshots share the same primary key, only the revision with the highest total token count is retained. Earlier or partial revisions are silently replaced. A fold revision never triggers a segment boundary.
**Segment isolation:** On context-reset, the accumulated cost state resets: B rebuilds from zero, g returns to floor, the deferred ledger clears, the model a segment's reads resolve against is cleared for the next call to fix, and the rate lamp starts a fresh billing cycle. What survives is the turn count and an unconsumed turn boundary, so a user turn already announced still opens its turn on the far side of the reset. Cross-segment history is preserved for visualization but does not contaminate current measurements.
**Token-at-Ingestion:** Per-path token estimates are computed once at write time using a model-specific conversion ratio. Values are never retroactively recomputed — changes in calibration or file content only affect future observations.
**Settlement:** When B grows faster than L (cache-creation credited before cache-read materializes), the surplus is banked in a deferred ledger as credit L has yet to confirm, and retires as L catches up. Any balance un-retired at segment end is treated as estimation error and corrected out of the path totals.
**Sidechain exclusion:** A row marked as sidechain is a self-contained sub-agent context and is dropped before interpretation, so it yields no evidence of any kind: it contributes to L, g, segmentation triggers, turn counting and path attribution alike not at all, and its identifiers never reach topology.
---
### Output Semantics
The system publishes a status snapshot after each measurement cycle. Consumers can rely on:
**Position constraint:** The public field `B` never exceeds `totalStock`. This cap is a transient display guard during cache-creation lag; it self-releases once the provider's cache catches up. Internal decision math uses B_default (the filtered subset) as its position basis.
**Baseline validity gate:** The system requires a positive position basis (B_default) AND `cRatio > 0` to produce meaningful cost metrics. When either condition fails:
- `x` = 1 (fallback, not null)
- `u`, `pp`, `mf`, `br`, `dhat`, `xSweet` = null, and the reference skeleton is absent, which withdraws every position landmark with it
- `g` returns at least the floor value (independent of baseline)
- Lamp state reports `no_transcript` or `insufficient_data`
The system overhead floor is anchored by the first usage snapshot with a positive context stock, as that stock less the content already tracked as resident per file, skill and tool, never below zero, and is part of B_default. B_default is therefore positive from that snapshot on without any file operation, except when the whole stock was already tracked as resident and the scores count none of it.
**Left-arm silence:** Which arm the session is on is decided by normalized position, never by the position ratio against xSweet. Before the sweet spot the lamp shows white until the position reaches the mirror image of the amber boundary and green from there on; the warning and critical zones are right-arm states only, so a session that has not reached the sweet spot is never coloured as "overstaying."
**Restart reminder:** The reminder is raised by the rent ledger and by nothing else. Each measured call adds its rent increment to a wallet phase scaled by the reminder interval, and a call whose increment carries that phase across a lap boundary raises a reminder stamped with the lap count reached and wraps the phase, so a call that crosses several boundaries is announced by that stamp rather than by a reminder per lap. Rent already accumulated is settled: a revaluation — by a baseline change, a change of resource scores, or a price change — withdraws no reminder already raised and rewinds no phase already advanced.
**Rate-lamp integration:** One rent increment per measured call, formed by trapezoidal accumulation across the call's interval, feeds two counters: a bill cycle, which is display only and triggers nothing, and the wallet phase, whose lap boundary is what raises the reminder. Reminders therefore follow accumulated cost rather than an instantaneous bp spike. The reminder interval adapts to mf — higher stakes shorten it; lower stakes lengthen it.
---
### Persistence Boundary
**Segment profiles:** On each segment boundary and at shutdown, a summary profile is archived to persistent storage. This includes exit metrics (B, L peak, g, br, mf, turns, duration) — enough to reconstruct cross-segment trends.
**Per-call time series:** The full call-by-call history lives only in process memory. On resume, the system reconstructs it by re-reading the transcript from byte zero — the same interpretation the live path applies, with each call's file attribution taken from the record stored when the call was first observed, so the rebuilt series is the one live observation produced. A call with no stored record is matched against the files as they are at that moment. If the transcript file is lost, per-call history is unrecoverable; only the archived segment profiles remain.
**Attribution records:** For each tool call observed live, the files and line numbers its text was attributed to are stored with the session, together with each line's character count and a hash of it, and the name of the tool or command that made the call (for a shell command, also its main argument), but no file content; they are deleted with the session.
**Resource scores:** The tiers you score files and skills at are stored with the session while its context epoch is the open one, so a restart, reopening the session or switching back to it restores them, for the resources the epoch still holds, once its transcript is read again. A write the database cannot take is refused and leaves the tiers and readings as they were; a read it cannot answer leaves the session at the default tiers. A new context epoch, a new session or a fork starts without them, and they are deleted with the session when it ages out. Transcript playback, the standalone dashboard and the telemetry backfill neither keep nor restore them.
**Rate-lamp ledger:** The billing ledger is persisted independently via periodic checkpoints. An unclean exit may lose recent state. On restart, the system loads the last valid checkpoint; if none is usable, it starts a fresh ledger.
---
### Hook Behavior
The session-start hook fires on `startup`, `resume`, `clear`, and `compact`. Its observable effects:
**Handoff discovery:** On `startup` and `clear`, the hook queries persistent storage for undelivered handoffs belonging to the current project. When found, it injects a reminder into the session context containing the load token, age, and task preview. On `resume`, handoff discovery is skipped — the session already has context.
**Server rotation:** When the hook detects a session-id mismatch (new session connecting to a running server), it issues a rotation request. The server archives the current segment and switches to the new transcript. If rotation fails, a fallback context is injected instructing the agent to call `rotate_session` manually.
**Bounded best-effort:** The hook always exits zero and its execution is capped by the host's command timeout. Any failure (database unavailable, server unreachable, parse error) is silently absorbed — the session starts with or without measurement context.
---
### MCP Tools
Stable commands exposed to the agent. The Claude Code plugin and the DSH plugin register the same tools, except where the table says otherwise.
| Tool | Purpose |
|------|---------|
| `watcher_status` | Report whether the watcher is running and one session's current reading: lamp, wallet-clock phase, `br`, `u`, `gEma`, `L`, `B`, model and alert, the quantities the statusline shows; while the session is still measuring, `reliable` is false and `lamp`, `phase`, `br`, `u`, `gEma` and `alert` are null, with `model`, `L` and `B` still reported. The Claude Code reply reads its own session and also carries the dashboard URL. The DSH reply carries no URL, since DSH serves no dashboard, and an optional `sessionId` names the session to read: any session the host has run or persisted, a settled one rebuilt first. It also carries `reuse` beside `reading`: `bucketTokens`, the attributed size of all held files and skills regardless of tier, and `continueAtShare`, with an entry for each share in `REUSE_SHARES`. An entry is true when the old session's next-call rent is strictly below the fresh session's minimum EOQ average cost. The fresh session rebuilds the system overhead floor plus the share, capped at `L`; its setup includes a cold write and a linear read ramp over `REUSE_WARMUP_CALLS`. The quote uses the unscored growth estimate and the epoch's cache-write to cache-read price ratio; it does not depend on resource scores or the availability of the scored position. A subagent is read by its agent id, the share the next task needs estimated from `get_bucket_summary`, and continued where that share is `true`; a minor fix may continue it either way. `reuse` is null for an empty bucket or unusable quote inputs, including stock below the overhead floor |
| `get_score_candidates` | List the resources the session holds and the tier each counts at |
| `apply_scores` | Set the tier each resource counts at toward the context a restart rebuilds, which is also what a handoff keeps of it: N nothing, R its attributed lines clipped to a head and tail, S the symbols they fall in, A all of them. A skill takes N or A. The optional `others` (`N` or `A`) sets every resource `scores` leaves out; without it they keep their tier. An invalid entry refuses the whole batch |
| `get_bucket_summary` | The files and skills the current context holds, each with its token size, beside the session id and the segment. The DSH tool takes an optional `sessionId` naming the session to read: any session the host has run or persisted, a settled one rebuilt first |
| `get_turn_skeleton` | Write the current context epoch's turn skeleton and a notes file whose `## NOTE[T]` headings are the slots a note fills; returns both paths, the snapshot id to submit against and the protocol for filling them |
| `submit_turn_notes` | Commit the notes file the latest skeleton wrote. All-or-nothing: every `NOTE` slot must be covered, by a section of the file or by a note the store already holds, and the snapshot must still be current |
| `prepare_handoff` | Persist a summary, an optional next task and what the resource tiers keep (`apply_scores`) as a handoff package; a call with only the token of an undelivered handoff takes the files and skills afresh from the tiers; returns a load token |
| `load_handoff` | Claude Code only: retrieve a handoff package by token, free-text search or auto-match for the project. Delivering a package binds it to the loading session and records the load, so the tool writes. A delivered package carries the newest lineage headlines within a budget, the older sessions collapsed into runs marked `omitted`, and the newest page of turns |
| `rotate_session` | Claude Code only: switch the watcher to a new session and transcript |
| `turn_page` | Read a page of the history turns carried by the loaded handoff, newest first |
| `turn_search` | Find a literal that occurs verbatim in the transcripts behind the loaded handoff |
| `turn_locate` | Find which turn ranges mention a remembered term, when the source wording is unknown |
| `lineage_headlines` | Read the headlines of chosen sessions of the loaded handoff's lineage, such as an omitted run of the load reply's lineage, by their positions `k` (`S2-S5` is `2-5`) |
On DSH, when **Calibrate measurement periodically** is enabled, including through [Automatic handoff](dsh.md#automatic-handoff-experimental), `get_score_candidates` and `apply_scores` return tool errors instructing the agent to skip scoring without retrying. The bucket panel can still read and change tiers.
The three history tools and `lineage_headlines` resolve their own lineage from the handoff delivered into the calling session, so none of them accepts a lineage identifier: a session that has loaded nothing is told so rather than offered a guess. Paging is deterministic and needs no query; the two query tools are distinguished by what the caller actually remembers. Every search or locate result names what to do with it — follow a hit, narrow a truncated match set, or switch tools on a miss — while a page that was built simply arrives.
On DSH the model has no `load_handoff` tool; the human command `/sw-load`, described on the [DSH page](https://nomadop.github.io/session-watcher/docs/dsh/#commands), delivers the handoff, records the load and renames the loading session after the package's next task. The human command `/sw-continue` takes no arguments and clears the session in place: it shadows the session's history behind a checkpoint that opens a new epoch, then loads the session's newest handoff itself, delivering and reading it as `/sw-load` does, and hands the model the result. The follow-up has the model continue the task from its next step in the same turn, where the follow-up of `/sw-load` has it present the loaded state and wait for confirmation, and has the model ask any question, approval or permission the task left open and wait for the user. It leaves the session untouched and says why when the session has prepared no handoff, when its newest handoff was prepared before the latest context reset, or while the agent is busy. When the clear succeeds and the load fails, the clear stands and the answer carries the reason and the token to load by hand with `/sw-load <token>`. The session's earlier epochs stay readable as their own lineage entries, each with the turns up to the handoff it produced.
---
### Degradation
**Transcript missing:** The system reports white lamp with reason `no_transcript`. Cost-model outputs fall back to their defined invalid-state defaults. Measurement resumes automatically when the transcript becomes available.
**Transcript corrupt or unparseable:** Partially readable content is processed up to the last valid entry. Corrupt trailing bytes are skipped. Metrics reflect only the successfully parsed portion.
**Database unavailable:** Persistence failures during operation (handoff discovery, segment archival, turn-record writes) degrade independently — each fails open without stopping measurement.
**Interpretation fails outright:** An error the system cannot classify as an unreadable or malformed source is treated as a defect rather than absorbed: measurement stops, the owner reports the error, releases what it holds without archiving the open segment, and exits nonzero. The transcript is left untouched, so a fresh owner rebuilds from it.
**Server unreachable during rotation:** The hook injects fallback context instructing the agent to call `rotate_session` manually.
---
## DSH Plugin
`@nomadop/session-watcher-dsh` runs Session Watcher inside DeepSeek Harness (DSH). The plugin loads into the DSH host process, watches the sessions of that host, and shows the readings in a tab and a composer dock of the DSH Web UI. The measurement, the store, the handoff and the turn history are the ones the Claude Code plugin uses. What is specific to DSH is the harness layer that reads DSH's session event log and the host wiring around it.
### Install
Add the package to a DSH profile:
```bash
dsh plugin --profile <name> add @nomadop/session-watcher-dsh
```
`<name>` is the profile you run; the tab appears in the Web UI, whose profile `dsh web` boots as `web`. The plugin needs DSH 0.2.2-rc.1 or later.
The plugin adds its own `sw_event_read` tool, which reads one event of a session in the caller's directory back as the verbatim text of its messages, tool calls and tool results, a message's reasoning blocks included as recorded, in their original position and without replay data, and for any other event type only its identity; the `before` and `after` neighbors are the raw events around it, each as a short semantic summary that leaves out reasoning blocks, except that a handoff payload and its file excerpts, an inner-seal carrier and a compaction checkpoint show their identity alone, and reading one of them as the target returns its body verbatim; no other tool bundle is needed for it, and DSH's Session search can be switched on or off freely. DSH's built-in optional `session_event_read`, which comes with that Session search, is the one that reads the raw event record in full, such as a system prompt, the dynamic tool set, a todo write, a turn end or another diagnostic payload.
### What gets watched
Each session the host lists, creates or appends to gets its own watcher, subagent sessions included. A session the plugin first meets is read in full from the host's session log, then followed event by event. While that first read is in progress, the tools wait for it, and the tab and the dock show that the session is being read.
A session that is not running, because it has settled or has not run again since the host restarted, has no watcher until the tab, the dock, `watcher_status` or `get_bucket_summary` first asks for it. The host then looks the session up among the sessions it has persisted and builds its watcher the same way, so an old session reads in the tab and the dock. A session the host has not persisted stays unobserved.
If a session's watcher fails, it stops measuring that session and keeps the diagnostic that made it fail. The tab, the dock and the tools report that diagnostic, and other sessions are not affected.
The plugin shares the store under `~/.session-watcher` with the Claude Code plugin: the archived segments, the Rate Lamp ledger, the handoffs and turn records, and the pricing overrides. A pricing override saved from the tab reprices at once every session of the host that runs that model.
The host measures a model call under the `name` its `llm` model catalog gives the call's provider and model id, and under the id where the catalog has none. The model-keyed state follows that name: a pricing override is saved and looked up under it, so one saved under an id has to be saved again under the name, and a name that lacks the model family prices under the defaults.
### The Session Watcher tab
The tab sits in the conversation view strip, labelled **SW Meter**, and shows the session open in that conversation. It mounts the dashboard's own elements:
- the hero chart and its position verdict
- the depth bar
- the cycle and reminder bars
- the history chart and the history drawer
- the bucket panel, with the same tier selection and position preview, and its file rows' drawer of the lines the session holds
- the pricing chip
The DSH Web UI provides the page chrome and the theme. The dashboard's chrome bar, theme chip and glossary are not mounted. The tab paints a light palette under a light host theme.
#### Refresh
The tab refreshes from a change signal. The host sends a signal naming a session on an event stream whenever that session's watcher goes live, applies new events, fails or is removed, and after a pricing write changes its readings or a score batch applies to it. A page holds one stream while it is visible. A signal makes that session's tab and dock pull the session's readings over the plugin's `/session-watcher` RPC channel. A stream that closes reopens after a growing wait, and a reopened stream makes every open session pull once. A failed pull is not retried; the next signal pulls again.
#### The badge
The tab keeps its panel on screen under every state, with the elements at their idle paint while there is no reading. A badge in its top row names the state. The signal stream's state shows while it is not live; otherwise the badge shows the state of the last read.
| Badge | When |
|-------|------|
| `live` | The stream is open and the last read returned a reading |
| `connecting` | The page is opening the stream, or the browser is retrying one that dropped, which is how a stopped DSH host first shows |
| `disconnected` | The stream closed and the page waits to reopen it; the panel keeps its last reading |
| `reading` | The first read of the session has not finished |
| `unobserved` | The host has no watcher for the session and has not persisted it |
| `failed` | The session's watcher failed; the badge's hover text carries its diagnostic |
| `unreachable` | A read failed while the stream is open: it timed out, or the RPC channel rejected the call or answered with an error; the badge's hover text carries the message |
### The composer dock
The dock is a pill below the composer.
With a reading, the pill shows a lamp ring with the bill premium beside it. The ring's core is the lamp's zone and its arc the progress of the alert clock, the dock's label for the reminder bar's meter. An arrow names the arm the session is on, falling on the left arm, where the bill premium falls as the session goes on, and rising on the right arm, where it rises. A badge at the pill's corner counts the alert clock's laps once there is one. The bill premium printed on the pill is capped to keep the pill short; the pill's hover text and its accessible name carry the real figure, the arm, the clock and the lap count.
Without a reading, the pill is a white ring and one word: `Calibrating` while the lamp has not enough data, otherwise the state of the read: reading, unobserved, failed or unreachable.
Clicking the pill opens a popover above it. Its header names the lamp's zone. Below it, with a reading:
- the bill premium and the normalized position
- the position track, once there are landmarks to draw: the four zone bands lit up to where the session stands on the dashboard's axis, with the sweet spot marked
- the context stock, split into the rebuild baseline and the effective context above it, with the growth per call
- the alert clock, and under it the latest alert while the clock's laps have reached that alert's bill count
Without a reading, the popover holds one line: the state of the read, or that there is not enough data yet. Escape or a click outside closes it.
The **SW Events** tab lists recorded alerts from the Dock's alert clock under **All** and **Warnings only**. Each row shows the segment and the readings from the call that triggered the alert. The alert number counts recorded alerts within that segment, not wallet laps. The row stays available when the session is reopened; earlier alerts that were not recorded are not reconstructed.
The tab's toolbar also opens **Current segment files**: the files and skills the segment's context holds now, each at its current tier, with the lines the current scores select to restore context highlighted among the file's attributed lines. It reads the segment as it is when opened, not as it was when an alert or a scoring ran.
### Supported surface
The tab and the dock are supported on `dsh web`. Whether a page's `EventSource` reaches the host's events route in the DSH Desktop shell has not been verified.
### Tools
The agent gets the tool set tabled under MCP Tools on the [Guarantees page](https://nomadop.github.io/session-watcher/docs/guarantees/#mcp-tools), without `rotate_session` and `load_handoff`, which are Claude Code only. DSH delivers handoffs through the host, either by [command](#commands) or by [automatic handoff](#automatic-handoff-experimental). Each tool answers for the session of the agent that calls it, except that `watcher_status` and `get_bucket_summary` can name another session and `sw_event_read` another session of the caller's directory. On DSH, a turn address `S{k}:{T}` names a session and an event `seq`, and the turn tools' replies tell the agent to read that event with `sw_event_read(session_id, seq)`.
### Skills
The package ships the `sw-handoff` and `sw-explain` skills, the same files the Claude Code plugin ships, and registers them with the host. Neither handoff load nor automatic handoff adds a skill to that list.
### Commands
The plugin registers the human commands below, typed in the Web composer.
`/sw-load [token]` loads a handoff into the session. With a token it loads that handoff. Choosing `/sw-load` from the slash menu, or pressing Enter on a bare `/sw-load` with no attachment, opens a picker instead: it lists the handoffs the project still retains, the undelivered group before the delivered one and each newest first, with the token, the age and the task, and its search matches the token or the task text. Selecting a row replaces the composer's draft with `/sw-load <token>` and loads nothing; the load runs when you submit that line. Enter on a bare `/sw-load` with an attachment is refused, and a bare `/sw-load` that still reaches the command, such as a command claim submitted with no arguments, loads the one handoff pending for the project, which is one that another session of the project prepared, nobody has delivered, and that falls in the recent candidate window; when several are pending it lists them, each with its token, age and task preview, loads none and waits for a run with one token. It runs only while the agent is idle.
The command does the loading itself: it delivers the handoff, which binds it to the session, records the load and renames the session after the handoff's next task, then shows the kept paths' text from the files on disk, in the shape of the host's `read` tool, and records each file it shows as read by the session so the model can edit it when the host maps the file's path and states its version; a file shown without that record needs a `read` before the model can edit it. The model gets two harness-owned messages, one holding the delivery's payload and, when any kept text was shown, one holding that text, and a follow-up that names any path skipped or not read to the end of its range, tells the model to take the payload as the task's established current state, to invoke the kept skills and to present that state, as the summary states it, for the user to confirm or correct before work resumes, and points to `turn_page` and `lineage_headlines` for a detail the payload leaves out. For a manual load, use the Web composer: the model has no load tool or skill to take the command's place where a typed line is not claimed as a command.
`/sw-continue` clears the session in place and resumes it from its newest handoff: after the clear it loads that handoff itself, as `/sw-load` does, and hands the model the result. The follow-up has the model continue the task from its next step in the same turn, where the follow-up of `/sw-load` has it present the loaded state for you to confirm first, and has the model ask any question, approval or permission the task left open and wait for you. Its behavior is stated under MCP Tools on the [Guarantees page](https://nomadop.github.io/session-watcher/docs/guarantees/#mcp-tools).
### Automatic handoff (experimental)
Automatic handoff lets a DSH session hand itself off: after a wallet reminder its model decides whether to restart, prepares the handoff, and the session clears its context and carries on in place, with no command from you. It does what `sw-handoff` followed by `/sw-continue` does by hand, except that the host starts each step and the handoff keeps what the tiers in force keep, after the host first tries a resource calibration of them; the model's own `apply_scores` is an error while scoring is on. The result is an ordinary handoff: another session can load it by its token with `/sw-load`. The Claude Code plugin has no counterpart.
Turn on **Automatic handoff** in Settings → Session Watcher → Experimental, then save. It is off by default and applies without a restart. It does not depend on Inner Mode and works with it on or off. While it is on, [**Calibrate measurement periodically**](#scoring-resources-at-checkpoints-opt-in) counts as on without changing your saved choice for it.
#### The check
After a wallet reminder, the session's own model is asked whether the end of the current line of work is in view: it decides to continue when the stage at hand is the last of the line and only its closing steps are left, and to hand off otherwise. This is a separate, billable model request over the session's history. At each step that qualifies, the check takes the most recent reminder of the current context that no decision has consumed, and starts nothing while a handoff is under way. A decision consumes its reminder; a check that fails or is cancelled leaves it pending, and a newer reminder takes its place.
With Inner Mode on, the check waits until a seal would run. A decision to continue lets the seal run as usual; a decision to hand off takes the summary of the whole unsealed source without replacing it, so nothing is sealed. With Inner Mode off, the check runs at the next step the host lets in and a handoff needs no seal summary.
After a decision to hand off, the host tries one more calibration of the session's resource tiers before the summary and the handoff instructions, so that the tiers the handoff keeps follow the work as it stands; where the session holds resources this is a further billable model request. A calibration that scores nothing, is refused or fails leaves the tiers in force as they are. The check, that calibration and, under Inner Mode, the summary are the extra requests; the preparation and the continuation are ordinary model steps.
#### The handoff
The host gives the model handoff instructions. The capture includes the last working turn up to those instructions and excludes the handoff steps. The model prepares the handoff using the resource tiers already in force. Once the session's own preparation is ready, the host runs the turn as usual: it sends the ready result to the model like any other result, and that request on the old context is billed like any model request.
Loading begins only at a normal stop point where the setting is on and the context still owns the ready handoff, after any work the host had already queued has run; before one, nothing is loaded. There it loads the handoff with the load `/sw-continue` uses, then clears the old context in place and has the turn that reached that stop point go on, which is not necessarily the turn that prepared the handoff, telling the model to resume without asking you to confirm the loaded state. The new context's workspace instructions and skill list are read afresh for the first request after the clear. Any approval or question left open still needs your answer. If the model goes on with tools, the continuation waits for the turn's stop point. If the turn fails or is cancelled, or the context changes, before that stop point, no load begins; the handoff stays ready while it still belongs to the context, and a later qualifying stop point continues it. A host that provides no working directory service loads and clears nothing, and the ready handoff stays. The same path applies to local subagents.
#### In SW Events
A wallet reminder is an **Alert** row, shown under **All**. Each check is a **Handoff check** row under **All** and **Handoffs**, which ends as Continue session, Proceed with handoff, Failed or Cancelled; the detail of a check that reached a decision names the alert it answers, and **Warnings only** keeps failed checks, not cancellations. The calibration before a handoff is a **Calibration** row under the **All** and **Calibration** filters. Open either to see its outcome and the same request, response, usage and timing views; the request shows the recorded route and tail, not the full history. A decision to hand off is not a completed handoff: the handoff is a **Handoff** row of type Continue, as one made by `/sw-continue` is, and it appears once the handoff has loaded after the clear.
#### When it stops
Turning the setting off stops new automatic actions without undoing what already succeeded. A failed or cancelled check, summary or load ends the current turn, whereas a calibration that fails is reported as a diagnostic and the handoff goes on with the tiers in force; what to do next depends on whether a checkpoint was committed.
- **No checkpoint committed.** Only here can you go on in the original session and send again a message that did not reach the conversation. While the original context still owns the ready handoff, the next qualifying stop point loads it again from the start; a load that had begun and then failed, was cancelled or found the setting off may already have delivered the handoff and read its files. To continue by hand instead, run `/sw-load` in a new session of the same workspace with the token the preparation returned, which is not a checkpoint's token, as none was written; from the moment you choose that new session, do not wake the original one, including while the new session is still loading.
- **Checkpoint committed, work not continued** (a refused `compaction/end` included). The clear stays: it is not rolled back, and nothing loads or clears again automatically; sending the old message again does not recover it. Run `/sw-load <token>` with the token in the checkpoint in a new session of the same workspace, without looking through the old queue first; from the moment you choose that new session, do not wake the original one, including while the new session is still loading. This is advice, not a guarantee of the host: if the original session's queue still holds a batch, the host may claim it at that session's next normal wake, which is not Session Watcher sending it again and is not certain to happen.
### Inner compaction (experimental)
Inner compaction is an experimental mode in which Session Watcher replaces the work a session has accumulated with a summary while the session runs. It is off unless you turn it on.
#### Turning it on
A new session shows an **Enable compaction** switch among the options of the New Session view only while **Show compaction option** is on in Settings → Session Watcher, which it is not by default. Every independent new session starts with the switch off, and there is no default preference. Hiding the switch changes only whether it is shown: a mode already chosen stands, and the header mark and the monitor, the **SW Events** tab in the conversation view strip, are unaffected. The choice is open only until the session's first turn starts: after that the recorded mode stays locked, including when that first turn was rejected or cancelled. A started session that has the mode on shows a read-only **Enable compaction** mark in its header, hidden when the header is narrow, as the agent preset's label beside it is. Neither shows while the page's read of the mode fails; that hides the entries and does not by itself stop the host from sealing. A recorded mode that does not read as a mode shows neither entry, and that session seals nothing and writes a diagnostic.
Settings → Session Watcher holds the controls of inner compaction. Each applies as soon as it is saved, with no restart: Save writes the staged changes, and Cancel, like leaving the page, drops them. Under Experimental, **Show compaction option** is the setting above. Under Compaction, **Compaction policy** sets how readily a seal runs, from Most aggressive through Aggressive, Balanced (the default), Conservative and Most conservative. **Backup summary model**, none by default, is the model a content-filtered summary is last asked on, chosen among the models the host's providers offer, and **Subagents inherit compaction state**, off by default, decides whether a plain subagent is given its parent's mode.
A resumed session keeps the mode it recorded, and a session with no record stays off. A fork inherits the mode with the history it forks from. A plain subagent, one that is not a fork, is given its parent's mode as its own only while **Subagents inherit compaction state** is on, read as the subagent is created: with it off a plain subagent stays off, and no subagent already created changes. With it on, a parent whose mode is unknown or invalid leaves the subagent off and a diagnostic says so.
#### What a seal does
With the mode on, once enough completed model steps have accumulated in the unsealed source, Session Watcher estimates before each main step what a seal would save, and the chosen **Compaction policy** decides whether a seal runs before that step: a more aggressive policy seals earlier and a more conservative one waits longer. The number of steps is fixed and cannot be configured; it only starts the estimate. A saved policy applies from the next estimate, and an estimate already under way, with the summary requests that follow it, keeps the policy it began with. A call to the session's current model selection summarizes the unsealed source, user and harness items outside any model step included, and the main step waits for it. A seal on the first step of a new turn leaves the previous turn's final answer, a reply with text and no tool call that ends the source, in the active context right behind the carrier: it is neither counted nor summarized, and the next seal takes it. A reply that is not the expected notes, whether text that finishes normally or a tool call, is asked again over the same request, a fixed small number of requests in all. A summary the provider's content filter cuts off is asked again on the session's model, then on the **Backup summary model** when one is set; with none set, no other model is used. Each request is its own attempt, from its dispatch until it commits, fails or is cancelled, or ends as the one summary of a held-back seal described next; the monitor lists every attempt, the failed ones beside the one that seals. A seal is held back while a `get_turn_skeleton` call, which starts a handoff, sits in the unsealed source with no handoff load after it; the call returning does not release it. If the unsealed source has not already been summarized, the paused step takes one summary of the whole of it without an estimate or replacement. The load page shows what that summary says of the turns after the last seal.
The seal replaces the source it summarized in the active context with one carrier message, written as a system reminder: a closing tag in its text is escaped, `<\/system-reminder>`. The user's own messages and answers are the exception: each stands inside the reminder as an anchor, `seq N user: [below]`, and the text itself, whole and unescaped, follows the reminder's closing tag in the same message as the line `seq N user: <text>`. A reminder with such lines ends with a sentence saying that each line after an anchor came after its message, so that the last carrier line is not taken for the latest word of the user. The carrier has up to three parts:
- One summary line for each model step or each item outside a model step, opening with the addresses of the events it replaces, each followed by what the event is: `user`, `assistant`, the name of the tool a result answers, or `harness` for any other message. Files attached to those events move into the carrier as their stored attachments; an image is saved as a file the model can open with `read_image`, behind a note that the image is no longer in the context. Beside the line of a step that asked the user with `ask_user_question`, the carrier holds each question the user answered, as the model wrote it, and the user's answer to it, the labels they selected and their own text, both whole and marked `question:` and `user:`, whether or not the summary retells them; the answer's text is the one that follows the reminder, under the address of the event that holds it. The options and their descriptions are left out, and a question with no answer text, an error result or a call that cannot be read this way adds nothing.
- The files and skills the session held, entered as the changes against what the earlier carriers, and any kept file text still in context from a handoff load, already carry. A file's held lines are its text on the disk as it stands at seal time. A skill's text is the result the session's log recorded for it, which no disk read changes. A held file the disk cannot give is carried as an unreadable entry with its reason and a hint to read it directly; that is a state of the file, not a failure of the seal.
- The session state at seal time, as a block headed by the session seq it was read at: the working directory, the subagents that are running and the background jobs that are running, each with its label, and the todo list, each on a line of its own that names the tool which would show it (`working_directory`, `list_agents`, `job_list`, `todo_write`), then the git state of the working directory: the output of `git status --short --branch` and `git log -1 --oneline` on the lines under a line that names the two commands, the status lines past a fixed number replaced by one line saying how many are left. An item is read only when the session's tools include its tool; the git state needs none, and is left out where the working directory is no repository (a repository with no commit yet shows its status alone). An item that is empty and has never been shown is left out. Every other item is shown every time: an empty one reads `(empty)`; any other one is shown in full when it differs from the value the nearest earlier carrier still in the context showed for it, and otherwise marked unchanged since it was last shown. When no item is shown the block is left out. If an item cannot be read, the seal goes on without it and writes a diagnostic.
A seal does not summarize the earlier prefix again: the opening prefix of the session, its system prompt, the original task and the context the harness admitted before the first model request, and the earlier carriers stay as they were. A session that starts with `/sw-load`, or resumes after a manual or automatic handoff clear, has the same kind of prefix: the load's payload, its read result and the follow-up are admitted before the first model request after the start or the clear, so they stay with the context the harness admitted there, and the first seal carries only the kept lines that differ from what the load showed. The events it replaces stay in the session log. The stock compaction of the session keeps its own configuration, and the seal runs before it, so it sees the sealed context.
A seal is not an outer compaction and does not extend the model's window. Its summary is not lossless, and the active context is not guaranteed to get shorter or to stay bounded.
#### Re-reading lines the context holds
With the mode on, a `read` whose every returned line the session's context already holds, at the same line number and with the same text, is answered with an error saying so instead of the text. The read itself has run, so an edit of the file may follow it without another read. Lines a carrier left out of its body or withdrew, a line with the closing tag of a system reminder, which a carrier writes escaped, a file whose result DSH's own pruner has cut, and anything the check cannot establish let the read return its text as usual. A blocked read is recorded in the session log with its turn, step, call and lines, never the file text.
#### The restart reminder under the mode
With the mode on, the restart reminder's budget counts only the calls the session's source keeps standing: the first calls of its context and the first call behind each seal, each once the step it is in has ended, since the step's later events can still show what its request is. The calls since the last seal wait, since the next seal may replace them, and a seal rebuilds the budget from the calls that stand instead of adding to it, so the reminder does not run ahead of calls a seal has replaced. Until a seal has run the budget does not move, and while seals stop the budget stops with them. The position, the bill premium and the context stock read the whole path as they do without the mode.
#### Recalling what a seal replaced
The model reads the addresses in the carrier with `sw_event_read`. The file handles in a carrier are stored attachments, those moved from the replaced events and the image files the seal saved, not a restoration of arbitrary earlier file contents; a saved image is read with `read_image`, and a held file's current content by reading the file itself. Whether the model notices a gap and reads is its own decision. A read of an event its context already holds whole, a carrier or a handoff payload of the open epoch, the read message and follow-up of that handoff's load, or a source a carrier of that epoch quotes word for word, is refused with an answer saying so, whatever window it asks for.
#### When a seal fails
A summary call that fails, whose reply still is not the expected notes at the last request, or that the content filter cuts off again on the last model it is asked on, a thrown failure while reading held files or saving an attachment or image, a failure assembling the carrier, and a commit the seal or the session refuses each end the turn with an error. The mode does not change, no other failure is retried, and the next message tries again. A message the failed step had just claimed may not have been admitted to the history; send it again. If the failures persist, `/compact` is a manual way out while the agent is idle and compaction is mounted: when it finds a range to summarize and the summary, commit and flush succeed, the session continues from its checkpoint. A provider or storage outage can still stop it.
#### Marking the last carrier for the provider's cache (opt-in)
An optional pi-ai adapter entry, `@nomadop/session-watcher-dsh/pi-ai`, adds one cache point at the end of the last carrier in each request, beside the points the adapter already writes. The official bundle package (below) ships the same adapter file as its own `/pi-ai` entry. The host entry never loads it, and a profile that does not mount it sends the requests it always did. The entry is the Harness's `llm-pi-ai` plugin, vendored with that one change (see `dsh/vendor/dsh-llm-pi-ai/UPSTREAM.md` in the repository), and it is a temporary replacement: it does not follow the installed Harness's own `llm-pi-ai` when that changes.
The point goes where the request's own serializer already places cache points, so a route that caches nothing gets none:
- Anthropic Messages (`cache_control` on the carrier's final content block), Bedrock Converse (a standalone `cachePoint` block after the carrier) and Chat Completions gateways whose profile states `compat.cacheControlFormat: anthropic` (`cache_control` on the final text part) take the lifetime of the route's own points.
- OpenAI Responses takes `prompt_cache_breakpoint: {mode: explicit}` on the carrier's final `input_text` block only while the owner's Responses breakpoint switch is on (see below), which it is not until chosen, and then whatever the route's model declares about `supportsExplicitPromptCacheMode`, an explicit `false` included. Only a request that gets the breakpoint is changed, and it is sent the cache options pi-ai writes for a route that declares the capability: on a route kept for long that request carries `prompt_cache_options: {ttl: 30m}` in place of the 24-hour `prompt_cache_retention`, while the route's other requests keep the retention. A request with no carrier, one whose carrier is its last input item and every request of a route whose profile turns caching off are sent as pi-ai writes them. With the switch off no Responses route gets a breakpoint, a catalog model that declares the capability and a profile's `compat.supportsExplicitPromptCacheMode: true` included, and the request is as pi-ai writes it. Only the `openai-responses` protocol is covered: Azure and Codex routes and a request under ChatGPT sign-in get none. An endpoint may reject a request that carries the breakpoint or those options.
- Routes of the DeepSeek adapters, any other protocol, a route with `cacheRetention: none` and an endpoint that is not stated to take the markers get no point and are sent as the adapter sends them.
A route's point limit counts the marker positions one request carries at once, not the cached token volume, the number of carriers or the calls added up over a session. Only the latest carrier takes the extra point, and the tools do not each take one: a route that marks its tools marks the last one. A request that is already full before the carrier point cannot take it; a request that only reaches its limit once the carrier point is added still takes it. The positions below are the native layouts of the pi-ai serializers checked when this was written, structural facts and not measured rates, and a newer serializer may lay its points out differently:
| Route | Native marker positions | With the carrier point |
| --- | --- | --- |
| Bedrock Converse, a Claude model that supports caching | the system prompt and the tail of the last user message | room for the carrier point |
| Anthropic Messages with an API key | the system prompt, the last tool when the model's capabilities allow `cache_control` on tools, and the message tail | the carrier point can be added, up to the limit |
| Anthropic Messages under OAuth sign-in | the identity prompt and the system instructions, each marked, the last tool and the message tail | with ordinary system instructions, cacheable tools and a message tail, the request is already full and the carrier point is not added |
| Chat Completions gateway of the Anthropic format | the system message, the last tool and the last conversation message | the carrier point can be added, up to the limit |
| OpenAI Responses with the switch on | the latest message's implicit breakpoint | room for the explicit carrier point |
A row holds while caching is on for the route, the route's protocol, the Responses switch and sign-in are ones the list above supports, the request has the system prompt, tools or tail the row names, and the carrier does not already end at the native tail marker. A request that lacks a position its row names has more room than the row says.
The adapter's own point already ends a carrier that is the request's last message, and that request is left alone. A request that is full before the carrier point, as the Anthropic OAuth row is, is sent with its original markers and without the extra point, and one warning names the route; the carrier optimization does not apply to that request. The limit is a request-shape limit: the entry does not claim to prevent every provider rejection. A message that opens with the carrier's opening text, the system reminder's opening and then the address sentence, is taken for a carrier whoever wrote it, which changes only where the marker sits.
The entry does not detect an expired cache, rewarm one or choose a lifetime, and no provider's reuse of the prefix, latency or cost has been measured with it: the request shapes are checked against loopback endpoints, not against a provider's cache.
To use it from this package, replace the adapter in a bundle's or the profile's patch layer; the profile has to hold this package, whose entry the row names. The Loader's `name` only asserts a row's package, so the original row stays, turned off, and the replacement is a new row under its own id with no configuration of its own:
```yaml
- id: llm-pi-ai
name: '@deepseek-ai/dsh-llm-pi-ai'
disabled: true
- insert:
- id: llm-pi-ai-carrier-cache
name: '@nomadop/session-watcher-dsh/pi-ai'
```
The provider dictionary stays where it is, under the `llm-pi-ai` row's `config.providers` in whichever layer sets it. The replacement reads that row as the Loader composes it, once, when it starts: an edit of the dictionary takes effect at the next start, not while the host runs, and the profile holds no second copy. The original row has to be off, and a `!!js` expression inside the dictionary is not evaluated for it, which makes the dictionary unusable to the replacement. The lifetime Session Watcher prices a route under is the one this dictionary declares for it.
When the replacement cannot use that row, it serves no route and Session Watcher's Settings page shows what happened, what it can cost and how to recover. The causes are that the Loader has no readable `llm-pi-ai` row, that the row is still on (the original adapter then serves its routes), and that its configuration is not a usable provider dictionary. With the replacement's routes unavailable, a session may find its route missing; where routing still works, turning on compaction can mean the earlier prompt cache is not reused after a compaction, which adds latency and cost, and no session content is lost. Check the `llm-pi-ai` configuration on the host and reload, or disable the replacement's bundle to restore the original routing. A replacement that does not mount at all, because its package cannot be loaded or its registration conflicts with the original's, reports nothing there: the Loader's log holds the error.
The Models page does not follow the row: its pi-ai editor and its hand-declared provider card are bound to the settings namespace `llm-pi-ai`, which is the turned-off original's, and the replacement has no settings entry to write. While the replacement is on, the editor's submit is unavailable for its routes and a hand-declared provider cannot be created there. Manage the routes in the `llm-pi-ai` row's `config.providers` in the patch layer and restart. Turning the original row on again and removing the replacement row returns to the stock adapter and the page.
##### Switching it from Settings
A profile with a plugin manager gets a **Compaction cache point** switch on Session Watcher's Settings page, in a row only the owner of the host is shown. It acts on one of two bundles that hold the activation above and nothing else, the disabled `llm-pi-ai` row and the replacement row with no configuration: the official `@nomadop/session-watcher-dsh-carrier-cache`, packed beside this package from `dsh/carrier-cache/`, and a local `@local/sw-carrier-cache-web` that the owner installed. Whichever of them the manager lists, readable, is used as it is. Both at once, one the manager lists but cannot read and an inventory it cannot read leave the row unavailable, say which, and install nothing. The switch selects or deselects the bundle through the profile's plugin manager. The host decides who may use it, not the page: a call whose peer is not the owner is refused before the manager is read, and no request can name another bundle.
The official bundle carries the adapter itself and does not depend on the Session Watcher package: its replacement row names its own `@nomadop/session-watcher-dsh-carrier-cache/pi-ai`, so the profile needs no Session Watcher package for the route to be served, and the host packages the adapter imports are its peers, which the Harness provides. The carrier point itself needs the Session Watcher host entry: each time pi-ai serializes a request the adapter asks it what a carrier opens with, and a request made while no host is mounted, or one made while the host that is mounted does not answer, is sent without a point and without a warning; a host whose answer is no text, or that fails to answer, gets a warning. A bundle from before the adapter asked the host tells a carrier by a text of its own, which the carriers of a newer host do not open with, and a newer bundle asks an older host, which does not answer; either pair silently gives no carrier a point, and only once both are updated does a carrier get one, whichever is updated first. The adapter is the file this package ships as `/pi-ai`. The bundle is versioned on its own, apart from the Session Watcher packages, and a change of the adapter's file calls for a new version of the bundle. The local bundle's row, as in the recipe above, names this package's entry.
##### Installing the official bundle
Where the manager lists neither bundle, the row offers the install: switching on opens a confirmation naming the package and its version, and nothing is installed until the owner confirms it. The package is fixed in the host's code and its version is the exact one of the bundle's own package, which the plugin gives the host; the page cannot name a package, a spec or a registry, and a request that does not carry the owner's literal confirmation is answered with the need for it and changes nothing. The install is the plugin manager's own, with its pnpm, saved at that exact version and switched off, with no registry of its own and no package script approved by the switch.
The installed package is read back from the manager's inventory before anything selects it: it has to be the fixed name at that version, readable and not selected. It then goes through the selection, the takeover check and the rollback below like any other bundle. A step that fails after the install leaves the package installed and switched off, which the answer says; the switch never uninstalls anything. A package that comes out as another name or version is not selected either, and is likewise left where it is. The check against an external manager is the manager's own: if another one installs the same package between the switch's read and its install, the manager refuses the second install and the next request reuses what is there; no deduplication is promised beyond that.
The version binding is checked when the package is installed and not when one already installed is reused.
The row shows on only when the running composition confirms the takeover: the original `llm-pi-ai` row is off with no mounted fiber, and the replacement itself reports a nonempty set of routes the llm registry accepted from it, equal to the dictionary's. A manager that reports the change applied, a replacement that reports no failure, or a mounted fiber is not enough alone, and the check is made again at each reading, so an edit of the dictionary the replacement did not follow, or the original row switched on again beside it, ends the on. A selection that fails or is not confirmed is undone by deselecting the bundle, and the answer says what that rollback verified: the replacement withdrawn and the original adapter mounted serving every route of its dictionary (rolled back), the replacement withdrawn with the original's return to service not proven (withdrawn, restoration unconfirmed), or the rollback not finishing, the saved selection or the replacement still in place (rollback failed). A route a third adapter took when the original let it go is the withdrawn case, since the route list names the route but the original is not mounted.
A manager that reports the change waits for a restart is not a success either, and the switch does not leave it for the next start: the selection it saved is withdrawn and the answer names the restart as the reason. A profile without hot reload therefore cannot be switched on from Settings; select the bundle on the Plugins page and restart, and the row shows what that start confirmed.
Deselecting reports the original as restored only on the same proof as a rollback. Where the deselection is saved and waits for a restart, the replacement keeps serving the routes until then, so the answer says so and the row shows pending, not off. The row shows off only with the bundle not selected and the replacement not mounted, and pending for every other reading it cannot confirm, such as a selected bundle whose replacement failed to start.
One change runs at a time; a second request meanwhile is answered busy, and nothing is queued. Requests are not migrated and no promise is made about those in flight: one sent while the routes change goes to whichever adapter serves them when it is dispatched, and may be interrupted.
The OpenAI Responses breakpoint has a switch of its own under that row. It is a setting of Session Watcher, `carrierResponsesBreakpoint`, off until it is saved on, and the page writes it as it writes its other settings, so DSH decides who may, and the row is shown to the owner alone. It acts at once without Save and changes nothing else: it can be turned off on its own, and the **Compaction cache point** switch stays as it is. It is usable only while that switch is on and confirmed; while the point is off, unavailable or not confirmed the control is held off and keeps showing the saved choice, which applies again when the point does. The page says that the endpoint may reject requests that carry the breakpoint or its cache options, and a route whose requests then fail is a reason to switch it off. The host hands the saved value to the replacement at each request, so a change reaches the next request without a restart; a replacement still mounted while the control is held off, as when a switch-off waits for a restart, goes on using the saved value until it leaves. A host that cannot give the replacement the value leaves the switch off for it.
##### Updating an installed bundle
An installed bundle is not updated with Session Watcher: update both on the Plugins page, and a carrier gets its cache point once both are updated, whichever is updated first; until then the requests are sent without a point and without a warning. One order is required for an official bundle at a version before it carried the adapter: its row names this package's `/pi-ai` entry, and under hot reload updating Session Watcher first can withdraw that entry, which leaves the route unavailable and stops the upgrade, so that bundle is updated first. After the bundle's update the row names the bundle's own package, and the Session Watcher update leaves the route as it is. Where the bundle was never installed, the Settings install offers the version this package names.
##### What the call drawer shows
The inner compaction monitor's call overview lists, for each summary request, what the replacement's wrapped payload hook did each time pi-ai serialized that request, in order, from the hook's own result: **Carrier cache point added** (the entry's point was added), **Native point at the same position reused** (the route's own point already ends the carrier), **Checked, none added** with its reason (no carrier in the request, the route writes no point of its own, the route's point limit is met, the Responses breakpoint switch is off, or the protocol or route is not supported), and **Not observed** where nothing was observed: the original adapter served the request, the replacement did not mount, or the record is from before the evidence existed. The list is bounded and counts what it leaves out. A request the seal asks again after a format failure or a content filter is its own request with its own list. The record holds these closed results and no request body, prompt or credential, and it claims nothing of the endpoint: not that a retransmission of an HTTP request reuses the serialized parameters, that the provider accepted the point, or that a later request hit the cache.
### Scoring resources at checkpoints (opt-in)
Settings → Session Watcher → Measurement holds **Calibrate measurement periodically**. It applies on save, does not depend on Inner Mode, and defaults to off. While [Automatic handoff](#automatic-handoff-experimental) is on, scoring shows as on and cannot be changed; turning automatic handoff off restores the saved choice. With it on, the host scores a session's files and skills by the user's current goal and writes the result as the formal score, as a score in the bucket panel would. See [scoring tool availability](guarantees.md#mcp-tools).
- **When.** Each session, a subagent's included, counts its own main calls of the open context epoch, with or without a usage, and a seal does not reset the count. Once `BUCKET_SCORE_INTERVAL_CALLS` calls have passed since the session's last attempt, the next step is scored before its model request is sent. A session the host first sees with the setting on, after a restart or when read from its log, counts from the calls it already has, and a new context epoch counts from zero. The counts are kept in the host process only, and the calls of a cycle that was missed are not made up.
- **What is asked.** The session's own model, on the route the step captured, is sent the session's active history as it stands, without the user message that starts the step, and the full list of its files and skills with their tiers. It is asked for the tier that keeps what the user's current line of work will still read of each resource, its remaining stages included: a request reported done stays part of that work until the user turns to other work, and a wait for a report or a verification is not a goal of its own. No lowest tier is promised. The request is no main call and no seal's cost and adds nothing to the conversation. Each request that is sent is one row of the SW Events list, under the Calibration filter, with its request, its response, its usage and the tiers it changed. The host also reports outcomes other than `applied` as `bucket_score` diagnostics on stderr, with usage when available. A session whose bucket holds nothing is not asked.
- **What is applied.** The reply must be a JSON object of `scores` and `"others": "N"` and nothing else: the keys it names take their tiers and every other resource is set to N, so an empty `scores` sets the whole bucket to N. A reply of `null` changes nothing. A batch with an unknown key or an invalid tier, text that is no such reply, a tool call and a stream that ends without a normal finish are refused whole.
- **When it fails.** A failed call or save is not retried. A reply from a previous context epoch is not applied.
Each scoring is one extra model request, billed by the provider.
#### Stop during an auxiliary request
Stop prevents the next main request, any new auxiliary request or retry, and any new automatic handoff action in that turn. An already dispatched summary, scoring request, or handoff check over committed history can still settle before the turn ends. A handoff check that included messages not yet admitted to the conversation is cancelled instead, leaving its reminder pending. The same rules apply to any cancellation the host reports as a user stop. Session Watcher sets no total deadline; the adapter's own timeouts still apply. If the adapter does not finish, the turn can keep waiting.
### Handoff across sessions
Both hosts store handoffs in the same place. If a lineage crosses from one host to the other, each host reads the other host's sessions in it as unverified turn records: the summary, the lineage headlines and the turn notes are all there, but those turns have no `S{k}:{T}` address and `turn_search` and `turn_locate` find nothing in them.
### Turn Notes
`get_turn_skeleton` puts the skeleton and the notes file under `session-watcher/turn-notes` in the system temp directory, which DSH's `workspace-write` file policy admits, so the agent writes the notes file with its own file tool without an approval. The Claude Code plugin keeps its Turn Notes under `~/.session-watcher`.
### Replaying a session log
`session-watcher replay <path>` plays back a DSH session log on the dashboard it plays a Claude Code transcript on: the host's `session.v4.jsonl.zstd` or a plaintext `session.v4.jsonl`.
```bash
npx -y @nomadop/session-watcher replay <path>
```
The command decides from the file's first line whether it is a DSH session log, so the same command takes either kind of file. It reads the file itself and needs neither a running DSH host nor the plugin.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

