Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
5e3bc2c
docs: Change Lens contract and shared client types (#397)
byronwall Nov 21, 2026
e1df04c
feat(server): Change Lens engine, API and srcly changes (#397)
byronwall Nov 21, 2026
044585e
fix(server): Change Lens shallow-window note and worktree flag
byronwall Nov 21, 2026
437ef77
docs: Change Lens contract follows the engine (#397)
byronwall Nov 21, 2026
5117950
test: Change Lens fixture payloads and model parity check (#397)
byronwall Nov 21, 2026
395f765
fix(server): Change Lens time window leaves out upstream merge changes
byronwall Nov 21, 2026
1f9b5ca
fix(server): Change Lens counts PR merges on the default branch
byronwall Nov 21, 2026
7ed0eec
fix(server): Change Lens pairs same-named scopes by body, skips anony…
byronwall Nov 21, 2026
6535504
fix(server): Change Lens keeps two files apart when one reuses the ot…
byronwall Nov 21, 2026
29db7c7
fix(server): Change Lens gives a method its doc comment and decorators
byronwall Nov 21, 2026
4b196b0
fix(server): Change Lens hunk diff of a scope leaves out nested chunk…
byronwall Nov 21, 2026
7fdbc0c
fix(server): Change Lens ends a line at a newline only
byronwall Nov 21, 2026
f3e8293
fix(server): Change Lens pairs a renamed Markdown heading with its se…
byronwall Nov 21, 2026
9167e0c
fix(server): Change Lens says so when a file has a syntax error
byronwall Nov 21, 2026
3abd33c
fix(server): Change Lens edge cases in windows, hunks and the parse c…
byronwall Nov 21, 2026
e591e77
fix(server): Change Lens moved chunk counts its own lines; no CR in d…
byronwall Nov 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,116 changes: 1,116 additions & 0 deletions client/src/changelens/fixture.json

Large diffs are not rendered by default.

909 changes: 909 additions & 0 deletions client/src/changelens/fixture.net.json

Large diffs are not rendered by default.

193 changes: 193 additions & 0 deletions client/src/changelens/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
// Change Lens payload contract. The server builds it in
// server/app/services/changelens/; docs/intent/change-lens/contract.md explains each field.
// Field names are camelCase on the wire.

export type LensWindow = "branch" | "24h" | "7d" | "custom";
/** touched: union of chunks changed by the window's commits. net: base snapshot against head snapshot. */
export type LensMode = "touched" | "net";

/** The literal head and commit id of uncommitted work. */
export const WORKTREE = "WORKTREE";

export interface LensEndpoint {
/** What the user or preset named: a branch, `merge-base(main, HEAD)`, a sha, `WORKTREE`. */
ref: string;
/** Null only for the working tree. */
sha: string | null;
/** Short text for the UI, e.g. `main @ e17633f` or `Working tree`. */
label: string;
/** ISO 8601 committer time; null for the working tree. */
date: string | null;
}

export interface LensSelection {
window: LensWindow;
mode: LensMode;
/** The branch or revision whose first-parent history was read. */
ref: string;
base: LensEndpoint;
head: LensEndpoint;
/** Time limits of a time window (ISO 8601); null for `branch` and for ref-only custom ranges. */
since: string | null;
until: string | null;
/** IANA name the server used to print times. */
timezone: string;
/** True when staged and unstaged edits are part of the result. Then `head` is the working tree. */
includesWorktree: boolean;
/** Plain sentences the UI shows as is: shallow history, clipped commit list, how merges were walked. */
notes: string[];
/** Absolute path of the git repo. Every `path` in the payload is relative to it. */
repoRoot: string;
}

export interface LensCommit {
/** Full sha, or `WORKTREE` for the uncommitted entry (always last, when present). */
sha: string;
short: string;
subject: string;
author: string;
/** ISO 8601 committer time; null for `WORKTREE`. */
date: string | null;
files: number;
added: number;
deleted: number;
/** Chunks this commit touched. */
chunkIds: string[];
}

export type ChunkKind =
| "function" // an executable scope the analyzer named (function, method, component, arrow const)
| "class" // a display scope: class, type, object literal
| "heading" // a Markdown heading section
| "file" // hunks outside any symbol; or a whole file: added, deleted, renamed with no edit, generated
| "range"; // nearby hunks in a file the analyzers can't read (YAML, CSS), grouped by line range

export type ChunkStatus =
| "modified"
| "added" // not in base
| "deleted" // not in head; lines are base lines
| "moved" // same symbol in another file, a renamed file, or another place in its file; body unchanged or changed
| "reverted"; // touched in the window, identical at base and head (touched mode only)

/** How the chunk at head was paired with base. */
export type ChunkMatch =
| "exact" // same path, same qualified name
| "renamed-file" // git reports the file as renamed; same qualified name
| "moved" // same name and near-identical body in another file or scope
| "uncertain" // best guess; the UI labels it
| "none"; // added or deleted: nothing to pair

export interface LensHunk {
/** Commit that made the hunk; `WORKTREE` for uncommitted; null in net mode (base → head). */
sha: string | null;
/** Line ranges as git prints them (`-oldStart,oldLines +newStart,newLines`). */
oldStart: number;
oldLines: number;
newStart: number;
newLines: number;
}

export interface LensTouch {
sha: string;
added: number;
deleted: number;
}

/** null on a side means that side has no value: absent, or not measured. */
export interface BeforeAfter {
before: number | null;
after: number | null;
}

export type ReviewBucket = "complex-and-changed" | "new-hotspot";

export interface LensChunk {
/** Stable for one selection: `<path>::<qualifiedName>` or `<path>::L<start>-<end>` or `<path>`. */
id: string;
/** Repo-relative path at head (at base for deleted chunks). */
path: string;
/** Path at base when it differs. */
oldPath?: string;
kind: ChunkKind;
/** Display name: `retryJob`, `## Install`, `lines 40–62`, or the file name. */
name: string;
/** Lines at head (at base for deleted chunks), 1-based, inclusive. */
startLine: number;
endLine: number;
/** Lines at base when the chunk exists there. */
baseStartLine?: number;
baseEndLine?: number;
status: ChunkStatus;
match: ChunkMatch;
/** Sum over every touch (churn = added + deleted). In net mode, the same as netAdded and netDeleted. */
added: number;
deleted: number;
/** Lines that differ between base and head for this chunk. 0 for reverted. */
netAdded: number;
netDeleted: number;
/** One per commit that touched the chunk, oldest first. Empty in net mode. */
touches: LensTouch[];
/** ISO 8601 times of the first and last touch; null when only the working tree touched it. */
firstTouched: string | null;
lastTouched: string | null;
/** Catalog metric id → before/after. Only metrics the chunk's language measures at its scope. */
metrics: Record<string, BeforeAfter>;
/** False when no analyzer reads this chunk: the UI says "not measured", never 0. */
measured: boolean;
/** Why not, when `measured` is false or a side failed. */
naReason?: string;
buckets: ReviewBucket[];
/** code | test | docs | style | config | fixture | generated | vendor … from file_classes.py */
fileClass: string;
hunks: LensHunk[];
}

export interface LensFile {
path: string;
oldPath?: string;
status: "added" | "deleted" | "modified" | "renamed";
/** Touched mode: lines summed over the window's commits. Net mode: base against head. */
added: number;
deleted: number;
/** Lines of code at head; null for deleted files. Area of the file in Show in repo. */
loc: number | null;
fileClass: string;
chunkIds: string[];
/** Generated or vendored: listed, drawn muted, left out of buckets. */
outOfScope: boolean;
}

export interface LensSummary {
filesEdited: number;
/** Files in the repo at head (tracked, after srcly's ignore rules). */
filesTotal: number;
chunks: number;
churnLines: number;
netLines: number;
reverted: number;
}

export interface ChangeLensPayload {
selection: LensSelection;
/** First-parent commits in the window, oldest first; capped (see `selection.notes`). */
commits: LensCommit[];
chunks: LensChunk[];
files: LensFile[];
summary: LensSummary;
/** Catalog ids of the metrics that have a before/after on at least one chunk. */
metricIds: string[];
}

/** `GET /api/change-lens/hunk`: the diff text behind one chunk. */
export interface LensHunkDiff {
chunkId: string;
path: string;
oldPath?: string;
/** Revisions the diff runs between, as labels. */
from: string;
to: string;
/** Unified diff (3 lines of context) limited to the chunk's lines; "" when the sides are equal. */
diff: string;
/** Set when the diff was clipped. */
truncated: boolean;
}
99 changes: 99 additions & 0 deletions docs/intent/change-lens/contract.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Change Lens: contract

Source: [#397](https://github.com/byronwall/srcly/issues/397). This file is temporary. The last PR of the stack moves its lasting facts into `docs/CODE_MAP.md` and the site docs, and removes this folder.

Change Lens answers three questions after a coding session: where the work happened, what changed in the shape of the code, and what to review first. A window changes which code is visible.

The payload types are in `client/src/changelens/types.ts`. That file is the contract. The server's Pydantic models mirror it with camelCase aliases.

## Endpoints

### `GET /api/change-lens`

| Param | Values | Default |
| --- | --- | --- |
| `path` | Absolute path of the analyzed folder (the scan root) | required |
| `window` | `branch`, `24h`, `7d`, `custom` | `branch` |
| `mode` | `touched`, `net` | `touched` |
| `ref` | Branch or revision whose history is read | `HEAD` |
| `base`, `head` | Revisions, for `custom` | none |
| `since`, `until` | ISO 8601 times, for `custom` | none |
| `worktree` | `1` or `0`: include staged and unstaged edits | `1` when `ref` is `HEAD` |

Returns `ChangeLensPayload`. A folder that is not a git repo returns 409 with a reason. An empty window returns 200 with empty lists and a note.

Every `path` in the payload is relative to `selection.repoRoot`. When `path` is a folder inside the repo, only files below it are read, and a note says so.

### `GET /api/change-lens/hunk`

`path`, the same selection params, `chunk` (a chunk id), and an optional `commit` (a sha or `WORKTREE`). Returns `LensHunkDiff`. Without `commit`, the diff runs from the selection's base to its head. With `commit`, it runs from that commit's first parent to the commit.

The diff holds only the chunk's own lines. A symbol's diff compares its body on the two sides, so a moved symbol shows only what changed in it. It leaves out the changed lines of the named scopes nested in it: those are in the nested chunks' diffs. A `file` chunk's diff leaves out the lines inside named scopes. An unknown chunk id returns 404. So does a `commit` that is not in the selection; a sha of fewer than 7 characters returns 400.

### `srcly changes [path]`

Prints the same result as Markdown: the resolved selection, the review buckets, then the chunks grouped by folder, with `before → after` complexity. Flags: `--window`, `--mode`, `--ref`, `--base`, `--head`, `--since`, `--until`, `--no-worktree`, `--json`.

## Time rules

1. **One history.** Read `git log --first-parent <ref>`. A merge commit counts once, as its diff against its first parent. Activity from other branches never mixes in. Say this in `selection.notes` when the window holds a merge. A merge of the default branch into a feature branch is listed, but its diff is not read: those are upstream changes. A note names it. A merge that is itself on the default branch (a merged PR) is never an upstream merge. When the base is older than such a merge (a time window), "before" is the base with the merge's own diff applied, so neither mode counts what the merge brought in. If that diff overlaps the branch's own edits and cannot be applied, the base stays as it is and a note says so.
2. **Branch window.** Base is the merge-base of `ref` and the default branch, found the way `compare/git_refs.py` (`resolve_auto_base`) finds it. Head is `ref`. On the default branch itself, the base is the upstream tip (`origin/<default>`); when that equals head, the window is empty and a note says so.
3. **Time windows.** Commits whose committer date is inside `[since, until]`. Base is the first parent of the oldest commit in the window. Head is the newest. `24h` and `7d` count back from now. A `since` later than `until` returns 400. A time window reads the newest 5,000 commits of the ref; a note says so when that limit cuts the window.
4. **Working tree.** Staged and unstaged edits are one entry, `WORKTREE`, after the last commit. It has no time. Untracked files count as added, unless srcly's ignore rules skip them. The entry exists only when the tree holds edits; then `selection.head` is the working tree.
5. **Touched against net.** Touched is the union of chunks that any commit in the window changed. Net compares the base snapshot with the head snapshot (the working tree, when included). A chunk that was changed and then put back has status `reverted` in touched mode and is absent in net mode.
6. **Shallow or incomplete history.** State it in `selection.notes`. Never guess a base. A window never reads past the oldest commit a shallow clone holds.
7. **Long windows.** A window keeps its newest 200 commits. The base moves to the parent of the oldest one kept, and a note says so.
8. **Files left out.** Binary files and files that srcly's ignore rules skip (lockfiles, `.json`, images) are not in the payload. A note gives their count.

## Chunk rules

1. Parse each changed file once per side (base and head) with the analyzer the scan uses for it. Parse the blob (`git show <sha>:<path>`), not a checkout. Do not scan whole snapshots. A line ends at a newline only, as git counts lines: a lone CR, a form feed or U+2028 is content.
2. A hunk belongs to the innermost named scope that holds its lines: on the new side for added and changed lines, on the old side for deleted lines. Executable scopes win over display scopes. A callback or an object literal with no name belongs to the named scope around it, and so does an object under a key of such a literal. A nested named scope has a qualified name (`Outer.inner`, `Class.method`). Comment and decorator lines right above a scope belong to it, also when a class around the scope holds those lines.
3. Hunks outside every scope form one `file` chunk for that file. In Markdown, a hunk belongs to its nearest heading section (`heading`). In a file no analyzer reads (YAML, CSS, shell), hunks within 10 lines of each other form one `range` chunk; when such a file is added or deleted, it is one `file` chunk. An empty file that is added or deleted is one `file` chunk too, in both modes. A generated or vendored file is one `file` chunk and is not analyzed.
4. Never invent a symbol. A chunk with no analyzer has `measured: false`, an empty `metrics`, and a `naReason`. So do `heading` chunks and `file` chunks: no code metric applies to them. A file whose base or head does not parse (a syntax error at that end) gets no symbols: its hunks form `range` chunks (one `file` chunk when the file is added or deleted) with the `naReason` "Syntax error at head" or "at base", and a note names the file.
5. Pair head and base chunks by path and qualified name (`exact`). When one file holds a qualified name more than once (overloads, a getter and its setter), the scopes pair by body: identical bodies first, then the closest. Position in the file never decides, and the chunk has the key of its scope at head (`load`, `load#2`). When git reports a rename, pair by qualified name across the two paths (`renamed-file`). A symbol that left one file and appeared in another with a near-identical body is `moved` (same name, 90% of body lines equal). A line-number overlap alone is never a match. A weaker guess is `uncertain`: the same name with 60% to 90% equal, or a new name on an unchanged body in the same file (a renamed function, or a Markdown heading reworded above the same text). Unpaired chunks are `added` or `deleted`.
6. A file is followed through its renames. A file that a commit of the window added has no base, and a file that one deleted has no head, even when another file holds its path at that end. `files` lists each path once: a deleted file whose path a renamed file took shares that file's entry. A pure rename with an unchanged body has equal `before` and `after`. It is not an improvement or a regression. A file renamed with no edit is one `file` chunk with status `moved`, no changed lines, and file-level metrics (`loc`, max `complexity`) that are equal on both sides.
7. Deleted chunks stay in touched mode, with their base lines. A symbol added and removed inside the window is `reverted`, with no metrics.
8. Touches come from mapping each commit's hunks to the chunk through the file's symbols at that commit. `touches.length` is the number of commits that changed the chunk.
9. Use one analysis version for both sides.

## Review buckets

Buckets are plain rules. There is no single score.

- `complex-and-changed`: the chunk existed at base with cyclomatic complexity of 10 or more, and its body changed.
- `new-hotspot`: the chunk is `added`, or its complexity rose, and its complexity at head is 10 or more.

Test, docs, generated and vendor files get no bucket. The thresholds are constants in one place.

## Client view

Change Lens is the fourth view: `?view=changes`, beside Treemap, Graph and 2x2. Its code is in `client/src/changelens/`. URL params: `cw` (window), `cm` (mode), `cl` (layout: `edits` or `repo`), `cc` (selected commit), `cs` (selected chunk id), `cbase`, `chead`, `csince`, `cuntil`.

- **Window bar** (in the view toolbar slot): the four presets, the Touched/Net switch, the Only edits/Show in repo switch. Below it, one status line shows the resolved base and head, the time limits and time zone, and each note.
- **Only edits:** a packed treemap of chunks grouped by folder, then file. Area is changed lines (`added + deleted`), with a floor so each chunk can be clicked. Folder labels read like `5 edited / 43 files · mostly tests`. Breadcrumbs and collapsible groups stay.
- **Show in repo:** the file map with area by file LOC. Untouched files are muted. Edited chunks keep an outline.
- **Lenses:** the color picker gains "Complexity delta" (a diverging scale) beside the current metrics. Added, deleted, moved, reverted and not-measured each have their own state, never a zero. A color change never changes the layout or the selection.
- **Panel** (`client/src/changelens/panel/`): `ReviewBuckets`, `ChunkInspector` (before → after for each metric, the touch strip, churn against net), `HunkDiff`, `CommitRail`.

Panel components take data through props only. They do not fetch, and they do not read the navigation store. The view owns state and passes it in:

```ts
// client/src/changelens/panel/index.ts
ReviewBuckets(props: { payload: ChangeLensPayload; selected: string | null; onSelect: (chunkId: string) => void })
ChunkInspector(props: { payload: ChangeLensPayload; chunk: LensChunk | null; onOpenHunk: (chunkId: string, commit?: string) => void; onOpenCode: (chunk: LensChunk) => void })
HunkDiff(props: { diff: LensHunkDiff | null; loading: boolean; error?: string; onClose: () => void })
CommitRail(props: { commits: LensCommit[]; selected: string | null; onSelect: (sha: string | null) => void; highlightChunk?: string | null })
```

## Acceptance fixture

`server/tests/fixtures/change_lens_repo.py` builds a small git repo in a temp folder, with fixed commit dates. Its branch holds: one edit to one function in a large file; three edits to the same function; a change that a later commit reverts; a pure file rename; a deleted function; a config hunk and a Markdown hunk; a new function with high complexity; and an uncommitted edit.

The tests and the browser proof check that:

- Only edits hides untouched chunks, keeps breadcrumbs, and opens the right diff.
- Reverted work shows in Touched and not in Net. The pure rename reports no complexity change.
- A color change keeps layout and selection. A switch to Show in repo keeps the selection.
- Before → after values come from the same analysis inputs. Unsupported metrics and unresolved matches say so.
- The UI never names an agent as the author of a read or an edit.
3 changes: 2 additions & 1 deletion server/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import signal
import threading

from app.routers import analysis, compare, dataflow, files, metrics, scans, symbols
from app.routers import analysis, changelens, compare, dataflow, files, metrics, scans, symbols
from app.services.dataflow import engine as dataflow_engine
from app.services.scan_workers import cancel_all_scans

Expand Down Expand Up @@ -82,6 +82,7 @@ async def lifespan(_app: FastAPI):
app.include_router(files.router)
app.include_router(scans.router)
app.include_router(compare.router)
app.include_router(changelens.router)
app.include_router(metrics.router)
app.include_router(dataflow.router)
app.include_router(symbols.router)
Expand Down
Loading
Loading