Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(lens): add Lens, a Claude Code mod that shows Repowise's view of the repo while Claude works (#3022)
Raghav Chamadiyafc7343d69223
diff --git a/.gitattributes b/.gitattributesindex ae98b9e32..bebfabceb 100644--- a/.gitattributes+++ b/.gitattributes@@ -11,3 +11,7 @@ packages/types/src/generated/*.ts text eol=lf# The UI copy of core-owned data, written by scripts/generate_biomarker_labels.py.packages/ui/src/health/generated/*.ts text eol=lf++# The Lens mod bundle, written by packages/claude-mod/build.mjs and checked+# byte for byte by `build:mod -- --check`.+plugins/claude-code/hooks/lens/*.js text eol=lfdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 167563bde..ea72a4d18 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -228,6 +228,15 @@ jobs:- name: Test uirun: npm run test --workspace @repowise-dev/ui+ - name: Type check claude-mod+ run: npm run type-check --workspace @repowise-dev/claude-mod++ - name: Test claude-mod+ run: npm run test --workspace @repowise-dev/claude-mod++ - name: Check the committed Lens bundle is current+ run: npm run build:mod --workspace @repowise-dev/claude-mod -- --check+# ---------------------------------------------------------------------------# VS Code extension — type check, bundle-size gate, and Electron smoke test# ---------------------------------------------------------------------------diff --git a/.gitignore b/.gitignoreindex 99138aa72..e8d92e9b6 100644--- a/.gitignore+++ b/.gitignore@@ -121,3 +121,7 @@ ehthumbs.db# Claude Code.claude/++# Written by Claude Code into a plugin dir it loads a mod from+plugins/claude-code/.claude-plugin/types/+plugins/claude-code/tsconfig.jsondiff --git a/package-lock.json b/package-lock.jsonindex 5684995cf..c0e2be7df 100644--- a/package-lock.json+++ b/package-lock.json@@ -12,7 +12,8 @@"packages/ui","packages/api-client","packages/web",- "packages/vscode"+ "packages/vscode",+ "packages/claude-mod"],"engines": {"node": ">=20.0.0"@@ -3315,6 +3316,10 @@"resolved": "packages/api-client","link": true},+ "node_modules/@repowise-dev/claude-mod": {+ "resolved": "packages/claude-mod",+ "link": true+ },"node_modules/@repowise-dev/types": {"resolved": "packages/types","link": true@@ -5650,6 +5655,47 @@"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"}},+ "node_modules/@vitest/coverage-v8": {+ "version": "4.1.10",+ "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.10.tgz",+ "integrity": "sha512-IM49HmthevbgAO4anp1hwtoT9wYe59w0LR00gr+eagHE+ZJ5lK4sLPeO0ubgoJcwLk6dehU3R24N+FbEEKDc8g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@bcoe/v8-coverage": "^1.0.2",+ "@vitest/utils": "4.1.10",+ "ast-v8-to-istanbul": "^1.0.0",+ "istanbul-lib-coverage": "^3.2.2",+ "istanbul-lib-report": "^3.0.1",+ "istanbul-reports": "^3.2.0",+ "magicast": "^0.5.2",+ "obug": "^2.1.1",+ "std-env": "^4.0.0-rc.1",+ "tinyrainbow": "^3.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "@vitest/browser": "4.1.10",+ "vitest": "4.1.10"+ },+ "peerDependenciesMeta": {+ "@vitest/browser": {+ "optional": true+ }+ }+ },+ "node_modules/@vitest/coverage-v8/node_modules/@bcoe/v8-coverage": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz",+ "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },"node_modules/@vitest/expect": {"version": "4.1.10","resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.10.tgz",@@ -6468,6 +6514,25 @@"dev": true,"license": "MIT"},+ "node_modules/ast-v8-to-istanbul": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.7.tgz",+ "integrity": "sha512-kFL68AG6ajd8fg248zwM9GQrUWEp79gsmjum34OEXjs4yHuUMZfYKwOLW9GMmB4oNvVrj+EAGxsP7ye2UR9UlA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/trace-mapping": "^0.3.31",+ "estree-walker": "^3.0.3",+ "js-tokens": "^10.0.0"+ }+ },+ "node_modules/ast-v8-to-istanbul/node_modules/js-tokens": {+ "version": "10.0.0",+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz",+ "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==",+ "dev": true,+ "license": "MIT"+ },"node_modules/astral-regex": {"version": "2.0.0","resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz",@@ -11741,6 +11806,7 @@"os": ["android"],+ "peer": true,"engines": {"node": ">= 12.0.0"},@@ -11762,6 +11828,7 @@"os": ["darwin"],+ "peer": true,"engines": {"node": ">= 12.0.0"},@@ -11783,6 +11850,7 @@"os": ["darwin"],+ "peer": true,"engines": {"node": ">= 12.0.0"},@@ -11804,6 +11872,7 @@"os": ["freebsd"],+ "peer": true,"engines": {"node": ">= 12.0.0"},@@ -11825,6 +11894,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">= 12.0.0"},@@ -11846,6 +11916,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">= 12.0.0"},@@ -11867,6 +11938,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">= 12.0.0"},@@ -11888,6 +11960,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">= 12.0.0"},@@ -11909,6 +11982,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">= 12.0.0"},@@ -11930,6 +12004,7 @@"os": ["win32"],+ "peer": true,"engines": {"node": ">= 12.0.0"},@@ -11951,6 +12026,7 @@"os": ["win32"],+ "peer": true,"engines": {"node": ">= 12.0.0"},@@ -12156,6 +12232,18 @@"@jridgewell/sourcemap-codec": "^1.5.5"}},+ "node_modules/magicast": {+ "version": "0.5.5",+ "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz",+ "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/parser": "^7.29.7",+ "@babel/types": "^7.29.7",+ "source-map-js": "^1.2.1"+ }+ },"node_modules/make-dir": {"version": "4.0.0","resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",@@ -18607,6 +18695,21 @@"vitest": "^4.1.5"}},+ "packages/claude-mod": {+ "name": "@repowise-dev/claude-mod",+ "version": "0.1.0",+ "devDependencies": {+ "@repowise-dev/api-client": "*",+ "@repowise-dev/types": "*",+ "@repowise-dev/ui": "*",+ "@types/node": "^26.1.0",+ "@vitest/coverage-v8": "4.1.10",+ "d3-hierarchy": "^3.1.2",+ "esbuild": "^0.28.1",+ "typescript": "^5.6.0",+ "vitest": "^4.1.5"+ }+ },"packages/types": {"name": "@repowise-dev/types","version": "0.0.1",diff --git a/package.json b/package.jsonindex 6835f6137..2138c793c 100644--- a/package.json+++ b/package.json@@ -8,7 +8,8 @@"packages/ui","packages/api-client","packages/web",- "packages/vscode"+ "packages/vscode",+ "packages/claude-mod"],"scripts": {"dev": "cd packages/web && npm run dev",diff --git a/packages/claude-mod/build.mjs b/packages/claude-mod/build.mjsnew file mode 100644index 000000000..2ec10f4a7--- /dev/null+++ b/packages/claude-mod/build.mjs@@ -0,0 +1,56 @@+// Bundles src/register.ts into the plugin's hooks module.+//+// node build.mjs write plugins/claude-code/hooks/lens/lens.js+// node build.mjs --check exit 1 when the committed bundle has drifted+//+// The mod runtime loads only files inside the plugin dir, so the shared+// packages are inlined. Never minified: the engine's static check reads `$`+// calls by name. Output is deterministic (relative paths, no legal comments,+// LF) so a rebuild on any OS matches the committed file.++import { readFile, writeFile, mkdir } from "node:fs/promises";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { build } from "esbuild";++const here = dirname(fileURLToPath(import.meta.url));+const repoRoot = resolve(here, "../..");+const outFile = resolve(repoRoot, "plugins/claude-code/hooks/lens/lens.js");+const check = process.argv.includes("--check");++const result = await build({+ entryPoints: [resolve(here, "src/register.ts")],+ absWorkingDir: here,+ bundle: true,+ format: "esm",+ platform: "neutral",+ mainFields: ["module", "main"],+ keepNames: true,+ minify: false,+ legalComments: "none",+ charset: "utf8",+ write: false,+ logLevel: "warning",+});++const banner = "// Generated by packages/claude-mod (npm run build:mod). Do not edit.\n";+const output = banner + result.outputFiles[0].text.replace(/\r\n/g, "\n");++if (check) {+ let current = "";+ try {+ current = (await readFile(outFile, "utf8")).replace(/\r\n/g, "\n");+ } catch (err) {+ // A missing bundle is drift, reported below; any other read error fails loudly.+ if (err?.code !== "ENOENT") throw new Error(`cannot read ${outFile}`, { cause: err });+ }+ if (current !== output) {+ console.error(`${outFile} is out of date. Run: npm run build:mod -w @repowise-dev/claude-mod`);+ process.exit(1);+ }+ console.log("lens.js is up to date");+} else {+ await mkdir(dirname(outFile), { recursive: true });+ await writeFile(outFile, output);+ console.log(`wrote ${outFile} (${Buffer.byteLength(output)} bytes)`);+}diff --git a/packages/claude-mod/mod-test/lens-map.test.ts b/packages/claude-mod/mod-test/lens-map.test.tsnew file mode 100644index 000000000..05d26db0e--- /dev/null+++ b/packages/claude-mod/mod-test/lens-map.test.ts@@ -0,0 +1,141 @@+// Runs under `claude plugin test` against the built bundle (npm run test:mod).+// django-feed.ts is generated by scripts/mod-test.mjs from the recorded+// fixtures in test/fixtures, so the map draws real Django data.+import { expect, test } from 'claude-code/testing'+import { BLAST_RADIUS, HEALTH_MAP } from './django-feed'++const ROOT = 'C:\\work\\django'+const SHA = 'e78991410b78391bc07a4b5010b273dfec814ff6'+const LOCK = { pid: 4242, host: '127.0.0.1', port: 7411, url: 'http://127.0.0.1:7411', ui_port: null, server_version: '0.54.0', started_at: '2026-10-03T09:00:00Z' }+const PANE = {+ plugin: 'repowise',+ component: 'Pane',+ surface: 'terminal',+ requestId: 'lens',+ viewport: { columns: 240, rows: 60 },+ props: { title: 'Lens', isFocused: false, bodyColumns: 180, placement: 'dock', scroll: { offset: 0, bodyRows: 55 }, view: {} },+} as const++const ok = (body: unknown) => ({ value: { status: 200, ok: true, headers: {}, text: JSON.stringify(body) } })+const run = (stdout: string) => ({ value: { exitCode: 0, stdout, stderr: '' } })++/** The local server's answers by path suffix, recorded from Django. */+const ROUTES: [RegExp, unknown][] = [+ [/\/health$/, { status: 'healthy' }],+ [/\/api\/repos$/, [{ id: 'dj', name: 'django', local_path: ROOT, updated_at: null }]],+ [/\/health\/map/, HEALTH_MAP],+ [/\/blast-radius$/, BLAST_RADIUS],+]++/** Files under the repo's .repowise folder. */+const FILES: [RegExp, string][] = [+ [/state\.json$/, JSON.stringify({ last_sync_commit: SHA })],+ [/serve\.lock\.json$/, JSON.stringify(LOCK)],+]++function answer(url: string) {+ const route = ROUTES.find(([pattern]) => pattern.test(url))+ return route ? ok(route[1]) : { value: { status: 404, ok: false, headers: {}, text: '{}' } }+}++function readFile(path: string) {+ const file = FILES.find(([pattern]) => pattern.test(path))+ return file ? { value: file[1] } : { deny: 'ENOENT' }+}++/** tasklist sees the server's pid; git says HEAD is the indexed commit. */+function processRun(argv: readonly string[]) {+ if (argv[0] === 'tasklist') return run('"python.exe","4242","Console"\r\n')+ return run(argv.includes('HEAD') ? `${SHA}\n` : 'true\n')+}++/** An indexed Django copy whose local server is up, answering from the recorded payloads. */+function fullStubs(on: any, seen: { urls: string[]; blits: any[]; opened: any[] }): void {+ on('session.start', () => ({ cwd: ROOT }))+ on('session.cwd', () => ({ value: ROOT }))+ on('fs.exists', (_$: any, e: any) => ({ value: FILES.some(([pattern]) => pattern.test(e.path)) }))+ on('fs.read', (_$: any, e: any) => readFile(e.path))+ on('process.run', (_$: any, e: any) => processRun(e.argv))+ on('http.fetch', (_$: any, e: any) => (seen.urls.push(e.url), answer(e.url)))+ on('settings.read', () => ({ value: {} }))+ on('ui.open', (_$: any, e: any) => (seen.opened.push(e), { value: { isPlaced: true } }))+ on('ui.blit', (_$: any, e: any) => (seen.blits.push(e), { value: {} }))+ on('tool.call', () => ({ result: {} }))+}++async function waitFor(check: () => boolean | Promise<boolean>): Promise<boolean> {+ for (let i = 0; i < 80; i++) {+ if (await check()) return true+ await new Promise((resolve) => setTimeout(resolve, 25))+ }+ return false+}++async function openMap($: any, on: any) {+ const seen = { urls: [] as string[], blits: [] as any[], opened: [] as any[] }+ fullStubs(on, seen)+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: ROOT })+ expect(await waitFor(() => seen.urls.some((u) => u.endsWith('/api/repos')))).toBe(true)+ await $.command.run({ command: 'lens' })+ const ui = await $.ui.mount(PANE)+ expect(await waitFor(async () => (await ui.find({ key: 'lens-map' })) !== undefined)).toBe(true)+ return { seen, ui }+}++test('/lens draws the Django health map with its legend', async ($: any, on: any) => {+ const { seen, ui } = await openMap($, on)+ expect(seen.opened).toEqual([{ id: 'lens', title: 'Lens', rows: 29, focus: true }])+ expect(seen.urls.filter((u) => u.includes('/health/map?cap=4000'))).toHaveLength(1)+ const map = await ui.find({ key: 'lens-map' })+ expect(map?.type).toBe('Raster')+ expect(map?.props.columns).toBe(180)+ expect(map?.props.rows).toBe(48)+ expect(String(map?.props.cells).length).toBe(180 * 48 * 16)+ expect(await ui.find({ type: 'Text', text: /^1,\d{3} of 2,970 files drawn at this size/ })).toBeDefined()+ expect(await ui.find({ type: 'Text', text: ' Needs work' })).toBeDefined()+ expect(await ui.find({ type: 'Text', text: ' Claude read' })).toBeDefined()+ await ui.unmount()+})++test('an edit ripples to the importers the server returned, by blit', async ($: any, on: any) => {+ const { seen, ui } = await openMap($, on)+ await $.tool.call({ tool: 'Edit', file_path: `${ROOT}\\django\\db\\models\\query.py`, old_string: 'a', new_string: 'b' })+ expect(await waitFor(() => seen.blits.length >= 2)).toBe(true)+ expect(seen.blits[0]).toMatchObject({ requestId: 'lens', key: 'lens-map', columns: 180, rows: 48 })+ const fetched = BLAST_RADIUS.transitive_affected.length+ const line = await ui.find({ type: 'Text', text: /^edited query\.py/ })+ expect(line?.text).toMatch(new RegExp(`^edited query\\.py · ${fetched} files import it \\(from imports, not calls\\)`))+ await ui.unmount()+})++test('without the local server the pane says what to run', async ($: any, on: any) => {+ on('session.start', () => ({ cwd: '/work' }))+ on('session.cwd', () => ({ value: '/work' }))+ on('fs.exists', (_$: any, e: any) => ({ value: e.path.endsWith('state.json') }))+ on('fs.read', () => ({ deny: 'ENOENT' }))+ on('process.run', () => run('true\n'))+ on('mcp.connect', () => ({ value: { isConnected: true, server: 'plugin:repowise:repowise' } }))+ on('settings.read', () => ({ value: {} }))+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })+ const hint = 'Lens map needs the local server: repowise serve --no-ui'+ expect(+ await waitFor(async () => {+ const ui = await $.ui.mount(PANE)+ const found = await ui.find({ type: 'Text', text: hint })+ await ui.unmount()+ return found !== undefined+ }),+ ).toBe(true)+})++test('the desktop app draws the same Django map as SVG, under the element limit', async ($: any, on: any) => {+ const { ui } = await openMap($, on)+ await ui.unmount()+ const desktop = await $.ui.mount({ ...PANE, surface: 'desktop' })+ const drawing = await desktop.find({ type: 'Svg' })+ const source = String(drawing?.props?.source ?? '')+ expect(source.startsWith('<svg ')).toBe(true)+ expect(source.length).toBeLessThan(131072)+ expect(await desktop.find({ type: 'Text', text: / of 2,970 files drawn at this size/ })).toBeDefined()+ await desktop.unmount()+})diff --git a/packages/claude-mod/mod-test/lens-pane.test.ts b/packages/claude-mod/mod-test/lens-pane.test.tsnew file mode 100644index 000000000..d1e5cc44f--- /dev/null+++ b/packages/claude-mod/mod-test/lens-pane.test.ts@@ -0,0 +1,104 @@+// Runs under `claude plugin test` against the built bundle (npm run test:mod):+// the /lens pane's tabs, the Ask field through the engine's own `ui.input`+// chain, and the brief offered after a compaction. MCP is the test's stub.+import { expect, test } from 'claude-code/testing'++const PANE = {+ plugin: 'repowise',+ component: 'Pane',+ surface: 'terminal',+ requestId: 'lens',+ viewport: { columns: 160, rows: 50 },+ props: { title: 'Lens', isFocused: true, bodyColumns: 140, placement: 'dock', scroll: { offset: 0, bodyRows: 40 }, view: {} },+} as const++const BAND = {+ plugin: 'repowise',+ component: 'AbovePrompt',+ surface: 'terminal',+ viewport: { columns: 100, rows: 30 },+ props: { hasSurvey: false, isWorking: false, maxRows: 10, bodyColumns: 100, scroll: { offset: 0, bodyRows: 10 }, view: {} },+} as const++// A get_answer reply recorded on an indexed Django copy (test/fixtures/ask/django-answer-filter.json).+const ANSWER = {+ answer:+ 'Synthesis is unavailable (no-llm-provider). Source rationale in django/utils/tree.py: A class for storing a tree graph. Primarily used for filter constructs in the ORM.',+ citations: ['django/utils/tree.py', 'django/db/models/sql/constants.py'],+ confidence: 'low',+ retrieval_quality: 'weak',+ degraded: 'no-llm-provider',+}++/** A git work tree with an index and no local server; the MCP server connects and answers get_answer. */+function stubs(on: any, seen: { mcp: string[]; prompts: string[]; opened: any[] }): void {+ on('session.start', () => ({ cwd: '/work' }))+ on('session.cwd', () => ({ value: '/work' }))+ on('fs.exists', (_$: any, e: any) => ({ value: /work[\\/]\.repowise[\\/]state\.json$/.test(e.path) }))+ on('fs.read', () => ({ value: '{}' }))+ on('process.run', () => ({ value: { exitCode: 0, stdout: 'true\n', stderr: '' } }))+ on('settings.read', () => ({ value: {} }))+ on('mcp.connect', () => ({ value: { isConnected: true, server: 'plugin:repowise:repowise' } }))+ on('mcp.call', (_$: any, e: any) => {+ seen.mcp.push(`${e.tool} ${JSON.stringify(e.args)}`)+ return { value: { content: [{ type: 'text', text: JSON.stringify({ result: ANSWER }) }], isError: false } }+ })+ on('ui.open', (_$: any, e: any) => (seen.opened.push(e), { value: { isPlaced: true } }))+ on('prompt.submit', (_$: any, e: any) => (seen.prompts.push(e.text), { text: e.text }))+ on('tool.call', () => ({ result: { type: 'create' } }))+ on('classic.PostCompact', () => ({}))+ on('ui.render', () => ({ type: 'Text', props: {}, children: ['drawn by Claude Code'] }))+ on('ui.log', () => ({}))+}++async function begin($: any, on: any) {+ const seen = { mcp: [] as string[], prompts: [] as string[], opened: [] as any[] }+ stubs(on, seen)+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })+ // The server name resolves in the background.+ await new Promise((resolve) => setTimeout(resolve, 300))+ return seen+}++test('/lens recap opens the pane with focus on the recap, and the tabs switch it', async ($: any, on: any) => {+ const seen = await begin($, on)+ await $.command.run({ command: 'lens', args: 'recap' })+ expect(seen.opened).toEqual([{ id: 'lens', title: 'Lens', rows: 29, focus: true }])+ const ui = await $.ui.mount(PANE)+ expect(await ui.find({ key: 'lens-recap' })).toBeDefined()+ expect(await ui.find({ type: 'Text', text: 'Lens made no model calls. Every figure here is read from the local index.' })).toBeDefined()+ await ui.press({ key: 'lens-tab-ask' })+ await ui.unmount()+ const again = await $.ui.mount(PANE)+ expect(await again.find({ key: 'lens-ask' })).toBeDefined()+ await again.unmount()+ expect(seen.mcp).toEqual([])+})++test('Enter in the Ask field asks get_answer and shows the reply with its evidence and confidence', async ($: any, on: any) => {+ const seen = await begin($, on)+ await $.command.run({ command: 'lens', args: 'ask' })+ const ui = await $.ui.mount(PANE)+ await ui.input({ key: 'lens-ask', text: 'how does filter() build SQL?' })+ expect(seen.mcp).toEqual(['get_answer {"question":"how does filter() build SQL?"}'])+ await ui.unmount()+ const after = await $.ui.mount(PANE)+ const md = await after.find({ type: 'Markdown' })+ expect(md?.props?.text ?? md?.text).toMatch(/\*\*Built from the index\*\* · confidence low · retrieval weak/)+ expect(md?.props?.text ?? md?.text).toMatch(/evidence: `django\/utils\/tree\.py`/)+ await after.unmount()+})++test('after a compaction the band offers the brief; only the press submits it', async ($: any, on: any) => {+ const seen = await begin($, on)+ await $.tool.call({ tool: 'Write', file_path: '/work/src/new.py', content: 'x = 1\n' } as any)+ await $.classic.PostCompact({ trigger: 'manual', compact_summary: 'summary' } as any)+ const ui = await $.ui.mount(BAND)+ expect(await ui.find({ type: 'Text', text: 'context compacted' })).toBeDefined()+ expect(seen.prompts).toEqual([])+ await ui.press({ key: 'lens-brief' })+ await ui.unmount()+ expect(seen.prompts).toHaveLength(1)+ expect(seen.prompts[0]).toMatch(/^The context was compacted\. This brief is built from the Repowise index and this session's edits:/)+ expect(seen.prompts[0]).toMatch(/Files edited: src\/new\.py$/)+})diff --git a/packages/claude-mod/mod-test/lens.test.ts b/packages/claude-mod/mod-test/lens.test.tsnew file mode 100644index 000000000..5a5643bcb--- /dev/null+++ b/packages/claude-mod/mod-test/lens.test.ts@@ -0,0 +1,350 @@+// Runs under `claude plugin test` against the built bundle, from a temporary+// copy of plugins/claude-code (npm run test:mod). Not shipped in the plugin.+import { expect, test } from 'claude-code/testing'++const BAND = {+ plugin: 'repowise',+ component: 'AbovePrompt',+ surface: 'terminal',+ viewport: { columns: 100, rows: 30 },+ props: {+ hasSurvey: false,+ isWorking: false,+ maxRows: 10,+ bodyColumns: 100,+ scroll: { offset: 0, bodyRows: 10 },+ view: {},+ },+} as const++const ENGINE_DRAWING = { type: 'Text', props: {}, children: ['drawn by Claude Code'] }+const HINT = 'index this repo for Lens: repowise init --no-prose --yes'++/** A git work tree with no index: the walk finds no state file, the MCP server connects. */+function noIndexStubs(on: any, inWorkTree = true): void {+ on('session.start', () => ({ cwd: '/work' }))+ on('session.cwd', () => ({ value: '/work' }))+ on('fs.exists', () => ({ value: false }))+ on('process.run', () => ({+ value: inWorkTree+ ? { exitCode: 0, stdout: 'true\n', stderr: '' }+ : { exitCode: 128, stdout: '', stderr: 'fatal: not a git repository' },+ }))+ on('mcp.connect', () => ({ value: { isConnected: true, server: 'plugin:repowise:repowise' } }))+ on('ui.render', () => ENGINE_DRAWING)+ // Core resolves turn.complete to the answer's own text.+ on('turn.complete', (_$: any, e: any) => ({ text: e.answer }))+}++async function waitFor(check: () => Promise<boolean>): Promise<boolean> {+ for (let i = 0; i < 40; i++) {+ if (await check()) return true+ await new Promise((resolve) => setTimeout(resolve, 25))+ }+ return false+}++/** Lens's row in the band, and whether the drawing beneath it survived. */+async function band($: any): Promise<{ lens: string | undefined; engineKept: boolean }> {+ const ui = await $.ui.mount(BAND)+ const found = await ui.find({ type: 'Text', text: /repowise|Lens|index/ })+ const engine = await ui.find({ type: 'Text', text: 'drawn by Claude Code' })+ await ui.unmount()+ return { lens: found?.children?.join(''), engineKept: engine !== undefined }+}++test('registers and draws nothing in the band at rest', async ($, on) => {+ on('ui.render', () => ENGINE_DRAWING)+ const ui = await $.ui.mount(BAND)+ expect(await ui.find({ type: 'Text', text: 'drawn by Claude Code' })).toBeDefined()+ expect(await ui.find({ key: 'lens-band' })).toBeUndefined()+ await ui.unmount()+})++test('the no-index hint shows once per session, above what the band already held', async ($, on) => {+ noIndexStubs(on)+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })+ expect(await waitFor(async () => (await band($)).lens === HINT)).toBe(true)+ expect((await band($)).engineKept).toBe(true)++ // The hint retires after the first turn ends, and a re-discovery does not bring it back.+ await $.turn.complete({ turnId: 't1', answer: 'ok', durationMs: 1, isAborted: false, usage: null })+ expect((await band($)).lens).toBeUndefined()+ await $.turn.complete({ turnId: 't2', answer: 'ok', durationMs: 1, isAborted: false, usage: null })+ await new Promise((resolve) => setTimeout(resolve, 200))+ expect(await band($)).toEqual({ lens: undefined, engineKept: true })+})++test('a subagent turn does not retire the hint', async ($, on) => {+ noIndexStubs(on)+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })+ expect(await waitFor(async () => (await band($)).lens !== undefined)).toBe(true)+ await $.turn.complete({ turnId: 't1', agentId: 'sub-1', answer: 'ok', durationMs: 1, isAborted: false, usage: null })+ expect((await band($)).lens).toBe(HINT)+})++test('outside a git work tree the band stays empty', async ($, on) => {+ noIndexStubs(on, false)+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })+ await new Promise((resolve) => setTimeout(resolve, 200))+ expect(await band($)).toEqual({ lens: undefined, engineKept: true })+})++const OWN_TOOL = 'mcp__plugin_repowise_repowise__get_context'+const CORE = { decision: 'ask', reason: 'core' }++/** Stands in for another plugin that asks about Lens's tool. */+const foreign = {+ name: 'foreign',+ register(on: any) {+ on('turn.start', async ($: any, e: any, next: any) => {+ const verdict = await $.tool.check({ tool: 'mcp__plugin_repowise_repowise__get_context', input: {} })+ return { ...(await next(e)), verdict }+ })+ },+}++test("Claude's own call to a Lens tool keeps the engine's verdict", async ($, on) => {+ on('tool.check', () => CORE)+ expect(await $.tool.check({ tool: OWN_TOOL, input: {}, tool_use_id: 'toolu_01abc' } as any)).toEqual(CORE)+ // A plugin-shaped id is not enough: the engine raised it, not Lens.+ expect(await $.tool.check({ tool: OWN_TOOL, input: {}, tool_use_id: 'toolu_plugin_01' } as any)).toEqual(CORE)+})++test('a tool outside the allowlist is never approved', async ($, on) => {+ on('tool.check', () => CORE)+ const tool = 'mcp__plugin_repowise_repowise__get_dead_code'+ expect(await $.tool.check({ tool, input: {}, tool_use_id: 'toolu_plugin_01' } as any)).toEqual(CORE)+ expect(await $.tool.check({ tool: 'Bash', input: { command: 'ls' }, tool_use_id: 'toolu_plugin_02' } as any)).toEqual(CORE)+})++test("another plugin's question about a Lens tool keeps the engine's verdict", { plugins: [foreign] }, async ($, on) => {+ on('tool.check', () => CORE)+ on('turn.start', () => ({ turnId: 't1' }))+ expect(await ($ as any).turn.start({ turnId: 't1', prompt: 'hi' })).toMatchObject({ verdict: CORE })+})++const SPINNER = {+ plugin: 'repowise',+ component: 'Spinner',+ surface: 'terminal',+ props: { word: 'Sauteing', message: null, suffix: '…', mode: 'tool-use' },+} as const++/** An indexed repo at /work with no local server; get_context answers for src/a.py. */+function indexedStubs(on: any, calls: string[]): void {+ on('session.start', () => ({ cwd: '/work' }))+ on('session.cwd', () => ({ value: '/work' }))+ // The engine hands paths over resolved for this OS (`C:\work\...` on Windows).+ on('fs.exists', (_$: any, e: any) => ({ value: /work[\\/]\.repowise[\\/]state\.json$/.test(e.path) }))+ on('fs.read', () => ({ value: '{}' }))+ on('process.run', () => ({ value: { exitCode: 1, stdout: '', stderr: '' } }))+ on('mcp.connect', () => ({ value: { isConnected: true, server: 'plugin:repowise:repowise' } }))+ on('mcp.call', (_$: any, e: any) => {+ calls.push(`${e.server} ${e.tool} ${JSON.stringify(e.args)}`)+ const card = { callers: [{ file: 'b.py' }, { file: 'c.py' }], callers_total: 41, ownership: { contributor_count: 3 } }+ return { value: { content: [{ type: 'text', text: JSON.stringify({ result: { targets: { 'src/a.py': card } } }) }], isError: false } }+ })+ // The engine's own spinner line: the word, then whatever suffix it is handed.+ on('ui.render', (_$: any, e: any) => ({ type: 'Text', props: {}, children: [`${e.props.word}${e.props.suffix}`] }))+}++async function spinnerText($: any): Promise<string | undefined> {+ const ui = await $.ui.mount(SPINNER)+ const found = await ui.find({ type: 'Text', text: /Sauteing/ })+ await ui.unmount()+ return found?.children?.join('')+}++test("the spinner names the file and its reach while a file tool runs, and is the engine's own line otherwise", async ($, on) => {+ const calls: string[] = []+ const seen: Array<string | undefined> = []+ indexedStubs(on, calls)+ on('tool.call', async () => {+ seen.push(await spinnerText($))+ return { result: { ok: true } }+ })+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })+ await new Promise((resolve) => setTimeout(resolve, 600))++ expect(await $.tool.call({ tool: 'Read', file_path: '/work/src/a.py' } as any)).toMatchObject({ result: { ok: true } })+ await new Promise((resolve) => setTimeout(resolve, 100))+ await $.tool.call({ tool: 'Read', file_path: '/work/src/a.py' } as any)++ // The mocked lookup lands at once, so both reads show it; it was fetched once.+ expect(calls).toEqual(['plugin:repowise:repowise get_context {"targets":["src/a.py"],"include":["callers","ownership"]}'])+ expect(seen).toEqual(['Sauteing… a.py · 41 caller files · 3 contributors', 'Sauteing… a.py · 41 caller files · 3 contributors'])+ expect(await spinnerText($)).toBe('Sauteing…')+})++// Recorded from the plugin's augment hook on a real Edit (see test/fixtures/replay).+const AUGMENT_EDIT =+ '[repowise] packages/core/src/repowise/core/analysis/dead_code/analyzer.py has a decision recorded in it, mined but not reviewed: Share one identifier shape for absence scans.\n' ++ '[repowise] packages/core/src/repowise/core/analysis/dead_code/analyzer.py has been bug-fixed 53x in the last 6 months, last today (bug magnet); mostly in _member_is_used.'++const TOOL_ROW = {+ plugin: 'repowise',+ component: 'ToolUse',+ surface: 'terminal',+ requestId: 'toolu_01edit',+ props: { tool_use_id: 'toolu_01edit', tool: 'Edit', input: {}, isRunning: false, isErrored: false, isInterrupted: false },+} as const++function rowStubs(on: any): void {+ on('ui.render', () => ({ type: 'Text', props: {}, children: ['Update(analyzer.py)'] }))+ on('classic.PostToolUse', () => ({ additionalContext: [AUGMENT_EDIT] }))+}++async function postEdit($: any, id: string, tool = 'Edit'): Promise<unknown> {+ return $.classic.PostToolUse({ tool_name: tool, tool_use_id: id, tool_input: { file_path: '/work/a.py' }, tool_response: {} })+}++test('a margin note sits under the edit the hook flagged, and the hook result reaches Claude unchanged', async ($, on) => {+ rowStubs(on)+ expect(await postEdit($, 'toolu_01edit')).toEqual({ additionalContext: [AUGMENT_EDIT] })+ const ui = await $.ui.mount(TOOL_ROW as any)+ expect(await ui.find({ type: 'Text', text: 'Update(analyzer.py)' })).toBeDefined()+ expect(await ui.find({ type: 'Text', text: /a decision found in this file, not yet reviewed: Share one identifier shape/ })).toBeDefined()+ expect(await ui.find({ type: 'Text', text: /fixed 53 times in 6 months, most recently today, mostly in _member_is_used/ })).toBeDefined()+ await ui.unmount()+})++test("no margin under another row, under a read, or under Lens's own lookups", async ($, on) => {+ rowStubs(on)+ await postEdit($, 'toolu_plugin_1')+ await postEdit($, 'toolu_01read', 'Read')+ for (const id of ['toolu_plugin_1', 'toolu_01read', 'toolu_01never']) {+ const ui = await $.ui.mount({ ...TOOL_ROW, requestId: id, props: { ...TOOL_ROW.props, tool_use_id: id } } as any)+ expect(await ui.find({ key: 'lens-margin' })).toBeUndefined()+ await ui.unmount()+ }+})++test('the margin toggle off draws no notes', { options: { lens_margin: false } }, async ($, on) => {+ rowStubs(on)+ await postEdit($, 'toolu_01edit')+ const ui = await $.ui.mount(TOOL_ROW as any)+ expect(await ui.find({ key: 'lens-margin' })).toBeUndefined()+ await ui.unmount()+})++// Real `repowise distill git log -n 300` output on the requests index, abridged+// to its first kept lines; the marker is verbatim.+const DISTILLED =+ '300 commits (showing 20 most recent; subjects only)\n' ++ '3bb56ba5 Oct 3 2026 scratch: two files\n' ++ '4ed3d1b3 Jun 24 2026 Bump actions/checkout from 6.0.2 to 7.0.0 in the actions group (#7540)\n' ++ '\n' ++ '[repowise#eed993b23bc3: 2928 lines omitted (~25947 tokens); restore: repowise expand eed993b23bc3]\n'++function bashResult(stdout: string) {+ return {+ plugin: 'repowise',+ component: 'ToolResult',+ surface: 'terminal',+ props: { tool_use_id: 'toolu_01bash', tool: 'Bash', output: { stdout, stderr: '', interrupted: false }, isErrored: false },+ } as any+}++test('a squeeze row sits under a distilled Bash result', async ($, on) => {+ on('ui.render', () => ({ type: 'Text', props: {}, children: ['engine result'] }))+ const ui = await $.ui.mount(bashResult(DISTILLED))+ expect(await ui.find({ type: 'Text', text: 'engine result' })).toBeDefined()+ expect(await ui.find({ type: 'Text', text: /2,931 lines → 3 · ~25,947 tokens omitted · repowise expand eed993b23bc3$/ })).toBeDefined()+ await ui.unmount()+})++test('the squeeze toggle off draws no row', { options: { lens_squeeze: false } }, async ($, on) => {+ on('ui.render', () => ({ type: 'Text', props: {}, children: ['engine result'] }))+ const ui = await $.ui.mount(bashResult(DISTILLED))+ expect(await ui.find({ type: 'Text', text: /repowise expand/ })).toBeUndefined()+ await ui.unmount()+})++test('no squeeze row for output distill left alone', async ($, on) => {+ on('ui.render', () => ({ type: 'Text', props: {}, children: ['engine result'] }))+ const ui = await $.ui.mount(bashResult('On branch main\nnothing to commit, working tree clean\n'))+ expect(await ui.find({ type: 'Text', text: /lines →/ })).toBeUndefined()+ await ui.unmount()+})++// A get_change_risk result recorded on an indexed copy of `requests` after a+// complex helper was added (test/fixtures/change-risk/findings.json, the+// blocks the card reads; this runtime has no fs to load the file).+const FINDINGS =+ {"directive": {"status": "review_required", "headline": "2 new findings need review, starting with nested_complexity in src/requests/_internal_utils.py.", "reasons": ["critical defect: nested_complexity in classify_headers (added_lines)", "high defect: complex_method in classify_headers (added_lines)"], "next_actions": ["Inspect src/requests/_internal_utils.py:55 (chf_7c35d63fcc13e52b)", "Inspect src/requests/_internal_utils.py:55 (chf_1d478916e70baee8)", "Run: tests/test_requests.py tests/test_utils.py"]}, "ref": "working tree", "working_tree": true, "risk_percentile": 92.0, "impacted_tests": {"status": "inferred", "basis": "inferred", "map_present": false, "tests_to_run": ["tests/test_requests.py", "tests/test_utils.py"], "tests_to_run_kind": "test_file", "total": 2, "truncated": false, "line_coverage": {"untested_changes": [], "stale_test_candidates": [], "covered": [], "no_coverage_data": []}, "summary": "2 test file(s) reach the changed files in the graph. Inferred from the dependency graph, not measured. For the line-precise answer build the map with `coverage run --contexts=test` then `repowise coverage add`."}, "health_delta": {"status": "available", "explanation": "Compared 1 changed files on both sides.", "basis": "both_sides_analyzed", "introduced": 2, "worsened": 0, "resolved": 0, "scope": {"changed": 1, "eligible": 1, "analyzed": 1, "skipped": 0, "failed": 0}, "top_findings": [{"id": "chf_7c35d63fcc13e52b", "change": "introduced", "dimension": "defect", "biomarker": "nested_complexity", "severity": "critical", "path": "src/requests/_internal_utils.py", "reason": "classify_headers nests 7 levels deep", "attribution": {"basis": "added_lines", "confidence": "high", "why": "Lines 55-85 are added or rewritten by this change."}, "inspect": "get_change_risk(finding_id='chf_7c35d63fcc13e52b')", "symbol": "classify_headers", "lines": [55, 85]}, {"id": "chf_1d478916e70baee8", "change": "introduced", "dimension": "defect", "biomarker": "complex_method", "severity": "high", "path": "src/requests/_internal_utils.py", "reason": "classify_headers has cyclomatic complexity 15", "attribution": {"basis": "added_lines", "confidence": "high", "why": "Lines 55-85 are added or rewritten by this change."}, "inspect": "get_change_risk(finding_id='chf_1d478916e70baee8')", "symbol": "classify_headers", "lines": [55, 85]}], "findings_total": 2, "findings_emitted": 2}}++/** A git work tree; get_change_risk answers with FINDINGS; records prompts and transcript lines. */+function reviewStubs(on: any, seen: { mcp: string[]; prompts: string[]; logs: string[] }): void {+ noIndexStubs(on)+ on('turn.start', () => ({ turnId: 't1' }))+ on('tool.call', () => ({ result: { type: 'create' }, text: 'File created' }))+ on('mcp.call', (_$: any, e: any) => {+ seen.mcp.push(e.tool)+ return { value: { content: [{ type: 'text', text: JSON.stringify({ result: FINDINGS }) }], isError: false } }+ })+ on('prompt.submit', (_$: any, e: any) => {+ seen.prompts.push(e.text)+ return { text: e.text }+ })+ on('ui.log', (_$: any, e: any) => {+ if (e.to === 'transcript') seen.logs.push(e.text)+ })+}++const TURN = { turnId: 't1', answer: 'Added the helper.', durationMs: 1, isAborted: false, reason: 'answer', usage: null }++test('after a turn that edited a file, the review goes beneath the answer and the band offers its buttons', async ($, on) => {+ const seen = { mcp: [] as string[], prompts: [] as string[], logs: [] as string[] }+ reviewStubs(on, seen)+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })+ await ($ as any).turn.start({ turnId: 't1', prompt: 'add a helper' })+ await $.tool.call({ tool: 'Write', file_path: '/elsewhere/x.py', content: 'x = 1\n' } as any)+ const done: any = await $.turn.complete(TURN as any)++ // Started when the edit landed and reused at the turn's end: one call.+ expect(seen.mcp).toEqual(['get_change_risk'])+ // One row: the engine stores a line break in this text as U+FFFD.+ expect(done.text).not.toContain('\n')+ expect(done.text.split(' · ').slice(0, 2)).toEqual([+ 'Change review (working tree, 1 changed file)',+ 'Health: 2 new findings need review, starting with nested_complexity in src/requests/_internal_utils.py',+ ])++ const ui = await $.ui.mount(BAND)+ expect((await ui.find({ type: 'Text', text: /review · health/ }))?.children?.join('')).toBe(+ 'review · health: 2 new findings, review required',+ )+ // Nothing reaches Claude until a button is pressed.+ expect(seen.prompts).toEqual([])+ await ui.press({ key: 'lens-review-tests' })+ await ui.press({ key: 'lens-review-details' })+ await ui.unmount()+ expect(seen.prompts).toEqual([+ 'Run the tests Repowise names for this change, inferred from the dependency graph, not measured: tests/test_requests.py tests/test_utils.py',+ ])+ expect(seen.logs.slice(0, 2)).toEqual([+ 'Change review: review required',+ '2 new findings need review, starting with nested_complexity in src/requests/_internal_utils.py.',+ ])+})++test('a turn that edited nothing gets no review and no card', async ($, on) => {+ const seen = { mcp: [] as string[], prompts: [] as string[], logs: [] as string[] }+ reviewStubs(on, seen)+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })+ await ($ as any).turn.start({ turnId: 't1', prompt: 'explain' })+ await $.tool.call({ tool: 'Read', file_path: '/elsewhere/x.py' } as any)+ expect(await $.turn.complete(TURN as any)).toMatchObject({ text: 'Added the helper.' })+ expect(seen.mcp).toEqual([])+})++test('with lens_review off, an editing turn is not reviewed', { options: { lens_review: false } }, async ($, on) => {+ const seen = { mcp: [] as string[], prompts: [] as string[], logs: [] as string[] }+ reviewStubs(on, seen)+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })+ await ($ as any).turn.start({ turnId: 't1', prompt: 'add a helper' })+ await $.tool.call({ tool: 'Write', file_path: '/elsewhere/x.py', content: 'x = 1\n' } as any)+ expect(await $.turn.complete(TURN as any)).toMatchObject({ text: 'Added the helper.' })+ expect(seen.mcp).toEqual([])+})diff --git a/packages/claude-mod/package.json b/packages/claude-mod/package.jsonnew file mode 100644index 000000000..b70aed18a--- /dev/null+++ b/packages/claude-mod/package.json@@ -0,0 +1,26 @@+{+ "name": "@repowise-dev/claude-mod",+ "version": "0.1.0",+ "private": true,+ "description": "Repowise Lens: the Claude Code mod source. build:mod writes the loadable bundle into plugins/claude-code/hooks/lens/.",+ "type": "module",+ "scripts": {+ "type-check": "tsc --noEmit",+ "test": "vitest run --coverage",+ "build:mod": "node build.mjs",+ "test:mod": "node scripts/mod-test.mjs",+ "bench:map": "node scripts/bench-map.mjs",+ "test:e2e": "node --no-warnings=ExperimentalWarning scripts/e2e.mjs"+ },+ "devDependencies": {+ "@repowise-dev/api-client": "*",+ "@repowise-dev/types": "*",+ "@repowise-dev/ui": "*",+ "@types/node": "^26.1.0",+ "@vitest/coverage-v8": "4.1.10",+ "d3-hierarchy": "^3.1.2",+ "esbuild": "^0.28.1",+ "typescript": "^5.6.0",+ "vitest": "^4.1.5"+ }+}diff --git a/packages/claude-mod/scripts/bench-map.mjs b/packages/claude-mod/scripts/bench-map.mjsnew file mode 100644index 000000000..425de8072--- /dev/null+++ b/packages/claude-mod/scripts/bench-map.mjs@@ -0,0 +1,68 @@+// Local benchmark for the map's per-frame work at 180x50 on the recorded+// Django feed: layout, a ripple frame, and the cell encoding. Budget 16 ms per+// frame; vitest guards at 5x that (test/overlay.test.ts).+//+// npm run bench:map -w @repowise-dev/claude-mod++import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { build } from "esbuild";++const BUDGET_MS = 16;+const RUNS = 50;+const pkg = resolve(dirname(fileURLToPath(import.meta.url)), "..");++// test/setup gives Node the runtime's Uint8Array.prototype.toBase64.+const bundled = await build({+ stdin: {+ contents: 'import "./test/setup"; export * from "./src/views/map"; export * from "./src/views/overlay"; export * from "./src/model/trail";',+ resolveDir: pkg,+ loader: "ts",+ },+ bundle: true,+ format: "esm",+ platform: "node",+ mainFields: ["module", "main"],+ write: false,+ logLevel: "warning",+});+const map = await import(`data:text/javascript;base64,${Buffer.from(bundled.outputFiles[0].text).toString("base64")}`);++const fixture = (name) => JSON.parse(readFileSync(resolve(pkg, "test/fixtures", name), "utf8"));+const feed = fixture("django-health-map.json");+const importers = fixture("django-blast-radius-query-depth1.json").transitive_affected.map((t) => t.path);+const root = "C:/work/django";+let trail = map.initialTrail;+for (const p of ["django/db/models/base.py", "django/db/models/manager.py"]) {+ trail = map.reduceTrail(trail, { type: "read", path: `c:/work/django/${p}` });+}+trail = map.reduceTrail(trail, { type: "edit", path: "c:/work/django/django/db/models/query.py" });+trail = map.reduceTrail(trail, { type: "callers", edits: 1, callers: { status: "ready", paths: importers } });++function time(label, work) {+ for (let i = 0; i < 5; i++) work(i);+ const samples = [];+ for (let i = 0; i < RUNS; i++) {+ const start = performance.now();+ work(i);+ samples.push(performance.now() - start);+ }+ samples.sort((a, b) => a - b);+ const median = samples[Math.floor(RUNS / 2)];+ const p95 = samples[Math.floor(RUNS * 0.95)];+ console.log(`${label.padEnd(32)} median ${median.toFixed(2)} ms p95 ${p95.toFixed(2)} ms`);+ return p95;+}++const layout = map.layoutMap(feed.files, 180, 50, true);+const overlay = map.resolveOverlay(layout, trail, root).overlay;+console.log(`Django feed: ${feed.files.length} files, ${layout.drawn.length} drawn at 180x50`);+const layoutP95 = time("layout (on resize only)", () => map.layoutMap(feed.files, 180, 50, true));+const frameP95 = time("ripple frame + encode", (i) =>+ map.frameCells(layout, map.resolveOverlay(layout, trail, root).overlay, { kind: "ripple", t: (i % 30) / 30 }),+);+time("resting frame + encode", () => map.frameCells(layout, overlay));+const ok = frameP95 <= BUDGET_MS && layoutP95 <= BUDGET_MS;+console.log(ok ? `within the ${BUDGET_MS} ms budget` : `OVER the ${BUDGET_MS} ms budget`);+process.exitCode = ok ? 0 : 1;diff --git a/packages/claude-mod/scripts/e2e.mjs b/packages/claude-mod/scripts/e2e.mjsnew file mode 100644index 000000000..7af7f3594--- /dev/null+++ b/packages/claude-mod/scripts/e2e.mjs@@ -0,0 +1,595 @@+// End-to-end check of Lens's data layer against a real local server. Local+// only: it needs the repowise CLI on PATH and an indexed repo.+//+// npm run test:e2e -w @repowise-dev/claude-mod -- <indexed-repo> [options]+//+// --file <rel> the file whose importers are checked (default: the largest+// drawn file with importers, among the 15 largest)+// --reindex re-index the temp copy first (`repowise init`, no prose)+// --map-only skip savings and the change review+// --json <path> also write the result as JSON+//+// It copies the repo to a temp dir outside any workspace (a shared git clone+// plus a copy of `.repowise`), points the copy's index at the copy, starts+// `repowise serve --no-ui` there, and drives Lens's own modules (bundled from+// src with esbuild) through a Host whose http is real fetch and whose fs and+// process are real Node. Every count Lens shows is checked against the+// server's own answer. The server, the MCP child and the copy are always+// removed, pass or fail.++import { execFile, spawn, spawnSync } from "node:child_process";+import { appendFileSync, cpSync, createWriteStream, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { createServer } from "node:net";+import { tmpdir } from "node:os";+import { basename, dirname, join, resolve } from "node:path";+import { DatabaseSync } from "node:sqlite";+import { fileURLToPath } from "node:url";+import { build } from "esbuild";++const pkg = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const WIN = process.platform === "win32";+const WIDTHS = [60, 100, 180];+const DOCK_ROWS = 40;+const CANDIDATES = 15;+const SERVER_START_MS = 180_000;++// ---------------------------------------------------------------- arguments++const argv = process.argv.slice(2);+const flag = (name) => argv.includes(name);+const option = (name) => {+ const i = argv.indexOf(name);+ return i >= 0 ? argv[i + 1] : undefined;+};+const source = argv.find((a, i) => !a.startsWith("--") && !["--file", "--json"].includes(argv[i - 1]));+if (!source) {+ console.error("usage: e2e.mjs <indexed-repo> [--file <rel>] [--reindex] [--map-only] [--json <path>]");+ process.exit(2);+}+const src = resolve(source);+if (!existsSync(join(src, ".repowise", "wiki.db"))) {+ console.error(`${src} has no .repowise/wiki.db`);+ process.exit(2);+}++// ---------------------------------------------------------------- results++const checks = [];+const timings = {};+const facts = { repo: basename(src) };++function check(name, ok, detail = "") {+ checks.push({ name, ok: Boolean(ok), detail });+ console.log(`${ok ? "ok " : "FAIL"} ${name}${detail ? `: ${detail}` : ""}`);+}++async function timed(label, work) {+ const start = performance.now();+ try {+ return await work();+ } finally {+ timings[label] = Math.round(performance.now() - start);+ }+}++const norm = (p) => (WIN ? p.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase() : p.replace(/\/+$/, ""));++// ---------------------------------------------------------------- processes++function run(cmd, args, cwd, timeoutMs = 600_000) {+ const r = spawnSync(cmd, args, { cwd, encoding: "utf8", timeout: timeoutMs, env: { ...process.env, PYTHONIOENCODING: "utf-8" } });+ if (r.status !== 0) throw new Error(`${cmd} ${args.join(" ")} failed (${r.status}): ${(r.stderr || r.stdout || "").slice(-800)}`);+ return r.stdout;+}++/** Stops a child and everything it started: the Windows CLI is a launcher over python. */+function killTree(pid) {+ if (!pid) return;+ if (WIN) spawnSync("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore" });+ else {+ try {+ process.kill(pid, "SIGTERM");+ } catch {+ // already gone+ }+ }+}++function freePort() {+ return new Promise((ok, fail) => {+ const s = createServer();+ s.once("error", fail);+ s.listen(0, "127.0.0.1", () => {+ const { port } = s.address();+ s.close(() => ok(port));+ });+ });+}++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++// ---------------------------------------------------------------- the copy++/** A shared clone at the source's HEAD (objects borrowed, nothing written back) plus its index. */+function copyRepo(dest) {+ if (existsSync(join(src, ".git"))) {+ const head = run("git", ["-C", src, "rev-parse", "HEAD"], src).trim();+ run("git", ["clone", "--shared", "--no-checkout", "-q", src, dest], dirname(dest));+ run("git", ["-C", dest, "checkout", "-q", "--detach", head], dest);+ cpSync(join(src, ".repowise"), join(dest, ".repowise"), {+ recursive: true,+ filter: (p) => !p.endsWith("serve.lock.json") && !p.endsWith(".update.lock"),+ });+ } else {+ cpSync(src, dest, { recursive: true, filter: (p) => !p.endsWith("serve.lock.json") });+ }+}++/** Points the copy's index row at the copy, so the server lists it under the copy's path. */+function patchLocalPath(dest) {+ const db = new DatabaseSync(join(dest, ".repowise", "wiki.db"));+ try {+ const rows = db.prepare("SELECT id, local_path FROM repositories").all();+ const own = rows.filter((r) => rows.length === 1 || norm(r.local_path ?? "") === norm(src) || norm(r.local_path ?? "") === norm(dest));+ if (own.length !== 1) throw new Error(`expected one repositories row for ${src}, found ${own.length} of ${rows.length}`);+ db.prepare("UPDATE repositories SET local_path = ? WHERE id = ?").run(dest, own[0].id);+ return own[0].id;+ } finally {+ db.close();+ }+}++function indexVersion(dir) {+ try {+ return JSON.parse(readFileSync(join(dir, ".repowise", "state.json"), "utf8")).written_by_version ?? "unstamped";+ } catch {+ return "unknown";+ }+}++// ---------------------------------------------------------------- the server++async function startServer(dest, logPath) {+ const port = await freePort();+ const log = createWriteStream(logPath);+ const child = spawn("repowise", ["serve", "--no-ui", "--host", "127.0.0.1", "--port", String(port)], {+ cwd: dest,+ env: { ...process.env, PYTHONIOENCODING: "utf-8" },+ stdio: ["ignore", "pipe", "pipe"],+ });+ child.stdout.pipe(log);+ child.stderr.pipe(log);+ let exited = null;+ child.once("exit", (code) => (exited = code));+ const url = `http://127.0.0.1:${port}`;+ const deadline = Date.now() + SERVER_START_MS;+ while (Date.now() < deadline) {+ if (exited !== null) throw new Error(`repowise serve exited (${exited}); see ${logPath}`);+ const up = await fetch(`${url}/health`).then((r) => r.ok).catch(() => false);+ if (up && existsSync(join(dest, ".repowise", "serve.lock.json"))) return { child, url };+ await sleep(500);+ }+ throw new Error(`repowise serve did not answer /health in ${SERVER_START_MS / 1000} s; see ${logPath}`);+}++async function getJson(url, init) {+ const r = await fetch(url, init);+ if (!r.ok) throw new Error(`${init?.method ?? "GET"} ${url}: ${r.status} ${(await r.text()).slice(0, 300)}`);+ return r.json();+}++// ---------------------------------------------------------------- MCP over stdio++/** A minimal MCP stdio client for `repowise mcp`: newline-delimited JSON-RPC. */+function mcpClient(dest) {+ let child = null;+ let ready = null;+ let nextId = 1;+ const pending = new Map();+ const send = (msg) => child.stdin.write(`${JSON.stringify(msg)}\n`);+ const request = (method, params) =>+ new Promise((ok, fail) => {+ const id = nextId++;+ pending.set(id, { ok, fail });+ send({ jsonrpc: "2.0", id, method, params });+ });+ function start() {+ child = spawn("repowise", ["mcp", dest, "--no-workspace"], {+ cwd: dest,+ env: { ...process.env, PYTHONIOENCODING: "utf-8" },+ stdio: ["pipe", "pipe", "ignore"],+ });+ let buf = "";+ child.stdout.setEncoding("utf8");+ child.stdout.on("data", (chunk) => {+ buf += chunk;+ let nl;+ while ((nl = buf.indexOf("\n")) >= 0) {+ const line = buf.slice(0, nl).trim();+ buf = buf.slice(nl + 1);+ if (!line.startsWith("{")) continue;+ const msg = JSON.parse(line);+ const waiter = pending.get(msg.id);+ if (!waiter) continue;+ pending.delete(msg.id);+ if (msg.error) waiter.fail(new Error(msg.error.message));+ else waiter.ok(msg.result);+ }+ });+ child.once("exit", (code) => {+ for (const w of pending.values()) w.fail(new Error(`repowise mcp exited (${code})`));+ pending.clear();+ });+ return request("initialize", {+ protocolVersion: "2025-06-18",+ capabilities: {},+ clientInfo: { name: "lens-e2e", version: "0" },+ }).then(() => send({ jsonrpc: "2.0", method: "notifications/initialized" }));+ }+ const connect = () => (ready ??= start().then(() => true));+ return {+ connect,+ pid: () => child?.pid,+ call: async (tool, args) => {+ await connect();+ const r = await request("tools/call", { name: tool, arguments: args });+ return { content: r.content ?? [], isError: r.isError === true };+ },+ };+}++// ---------------------------------------------------------------- Lens, bundled++async function loadLens() {+ const out = await build({+ stdin: {+ contents: [+ 'import "./test/setup";',+ 'export { discover, readFreshness, isWindowsPath } from "./src/data/discovery";',+ 'export { callTool, warmMcp } from "./src/data/mcp";',+ 'export { LensMap } from "./src/map-controller";',+ 'export { layoutMap } from "./src/views/map";',+ 'export { resolveOverlay } from "./src/views/overlay";',+ 'export { legendRows } from "./src/views/mapPane";',+ 'export { fromToolCall, absolutePath, savingsTotals, savingsSince } from "./src/model/events";',+ 'export { reduce, initialSession } from "./src/model/session";',+ 'export { testsToRun } from "./src/model/review";',+ 'export { bandView, bandRows } from "./src/views/band";',+ 'export { savingsLine } from "./src/views/copy";',+ 'export { reviewText } from "./src/views/review";',+ 'export { getSavings } from "@repowise-dev/api-client/costs";',+ ].join("\n"),+ resolveDir: pkg,+ loader: "ts",+ },+ bundle: true,+ format: "esm",+ platform: "node",+ mainFields: ["module", "main"],+ write: false,+ logLevel: "warning",+ });+ return import(`data:text/javascript;base64,${Buffer.from(out.outputFiles[0].text).toString("base64")}`);+}++function nodeHost(cwd, mcp) {+ return {+ session: { cwd: async () => cwd },+ fs: {+ read: async (p) => readFileSync(p, "utf8"),+ exists: async (p) => existsSync(p),+ },+ process: {+ run: (args, runCwd) =>+ new Promise((ok) => {+ execFile(args[0], args.slice(1), { cwd: runCwd, encoding: "utf8", timeout: 10_000 }, (err, stdout, stderr) =>+ ok({ exitCode: err ? (typeof err.code === "number" ? err.code : 1) : 0, stdout, stderr }),+ );+ }),+ },+ http: async (url, init) => {+ const r = await fetch(url, { method: init.method, headers: init.headers, body: init.body });+ const headers = {};+ r.headers.forEach((v, k) => (headers[k] = v));+ return { status: r.status, ok: r.ok, headers, text: await r.text() };+ },+ mcp: {+ connect: () => mcp.connect(),+ server: () => mcp.connect().then(() => "plugin:repowise:repowise"),+ call: (_server, tool, args) => mcp.call(tool, args),+ },+ };+}++// ---------------------------------------------------------------- tree helpers++function textsOf(node, out = []) {+ if (node.type === "Text") out.push(node.children.join(""));+ else if (node.type === "Box") for (const c of node.children) textsOf(c, out);+ return out;+}++function rasterOf(node) {+ if (node.type === "Raster") return node;+ if (node.type === "Box") for (const c of node.children) {+ const r = rasterOf(c);+ if (r) return r;+ }+ return null;+}++const num = (s) => Number(s.replace(/,/g, ""));++/** Distinct files owning at least one pixel, painted independently of the layout's own `drawn`. */+function pixelOwners(layout) {+ const grid = new Int32Array(layout.width * layout.height).fill(-1);+ let overlaps = 0;+ layout.files.forEach((f, i) => {+ for (let y = Math.max(0, f.py0); y < Math.min(layout.height, f.py1); y++)+ for (let x = Math.max(0, f.px0); x < Math.min(layout.width, f.px1); x++) {+ if (grid[y * layout.width + x] !== -1) overlaps++;+ grid[y * layout.width + x] = i;+ }+ });+ const owners = new Set();+ for (const v of grid) if (v !== -1) owners.add(v);+ return { owners: owners.size, overlaps };+}++// ---------------------------------------------------------------- the run++async function main() {+ const work = mkdtempSync(join(tmpdir(), "lens-e2e-"));+ // Under a workspace root, `repowise serve` serves the workspace's DB, not the copy's.+ for (let d = work; d !== dirname(d); d = dirname(d)) {+ if (existsSync(join(d, ".repowise-workspace.yaml"))) {+ rmSync(work, { recursive: true, force: true });+ throw new Error(`temp dir ${work} sits inside the workspace at ${d}; set TMP elsewhere`);+ }+ }+ const dest = join(work, basename(src));+ let server = null;+ const mcp = mcpClient(dest);+ try {+ await timed("copy", async () => copyRepo(dest));+ facts.indexVersion = indexVersion(src);+ if (flag("--reindex")) {+ await timed("reindex", async () =>+ run("repowise", ["init", ".", "--no-prose", "-y", "--no-editor-setup", "--no-hook", "--embedder", "mock", "--no-workspace"], dest, 1_800_000),+ );+ facts.indexVersion = `${facts.indexVersion} -> ${indexVersion(dest)} (temp copy)`;+ }+ const repoId = patchLocalPath(dest);+ server = await timed("server start", () => startServer(dest, join(work, "serve.log")));+ const api = server.url;+ const L = await loadLens();+ const host = nodeHost(dest, mcp);++ // Discovery: the lock, the pid, /health, and this repo in the server's list.+ const found = await timed("discovery", () => L.discover(host));+ facts.mode = found.mode;+ check("discovery mode is full", found.mode === "full", `${found.mode}${found.liteReason ? ` (${found.liteReason})` : ""}`);+ check("discovered repo id matches the local_path row", found.repo?.id === repoId, `${found.repo?.id} vs ${repoId}`);+ check("discovered root is the copy", norm(found.repoRoot ?? "") === norm(dest), String(found.repoRoot));+ if (found.mode !== "full" || found.repo === undefined) return;+ await timed("freshness", () => L.readFreshness(host, found.repoRoot));++ // The map, as the pane draws it.+ const root = found.repoRoot;+ const repo = { id: found.repo.id, root, updatedAt: found.repo.updatedAt, caseInsensitive: L.isWindowsPath(root) };+ let redraws = 0;+ const debug = [];+ const io = {+ redraw: () => redraws++,+ debug: (m) => debug.push(m),+ blit: async () => ({}),+ openPane: async () => ({ isPlaced: true }),+ closePane: async () => {},+ };+ const map = new L.LensMap(false);+ map.setReducedMotion(true);+ map.setRepo(io, repo);+ const pane = (columns) => map.paneTree(io, { surface: "terminal", notice: "", bodyColumns: columns, placement: "dock", bodyRows: DOCK_ROWS });+ async function until(ready, label, ms = 60_000) {+ const deadline = Date.now() + ms;+ while (!ready()) {+ if (Date.now() > deadline) throw new Error(`${label} not ready in ${ms} ms (${debug.join("; ")})`);+ await sleep(20);+ }+ }+ await timed("health map", async () => {+ await map.request(io);+ await until(() => rasterOf(pane(180)) !== null || debug.some((d) => d.startsWith("health map failed")), "health map", 60_000);+ });+ const feed = await getJson(`${api}/api/repos/${repo.id}/health/map?cap=4000`);+ facts.files = feed.repository_total;+ check("health map drew", rasterOf(pane(180)) !== null, debug.join("; "));+ check("feed shown equals its files", feed.shown === feed.files.length, `${feed.shown} vs ${feed.files.length}`);++ facts.drawn = {};+ for (const columns of WIDTHS) {+ const tree = pane(columns);+ const raster = rasterOf(tree);+ if (!raster) {+ check(`map at ${columns} columns`, false, textsOf(tree).join(" | "));+ continue;+ }+ const layout = await timed(`layout ${columns}`, async () => L.layoutMap(feed.files, raster.props.columns, raster.props.rows, repo.caseInsensitive));+ const { owners, overlaps } = pixelOwners(layout);+ const cellsBytes = Buffer.from(raster.props.cells, "base64").length;+ check(`${columns}: raster is ${raster.props.columns}x${raster.props.rows} cells`, cellsBytes === raster.props.columns * raster.props.rows * 12, `${cellsBytes} bytes`);+ check(`${columns}: no pixel owned twice`, overlaps === 0, `${overlaps} overlaps`);+ check(`${columns}: layout drawn equals pixel owners`, layout.drawn.length === owners, `${layout.drawn.length} vs ${owners}`);+ const lines = textsOf(tree);+ check(`${columns}: legend rows fit`, lines.every((l) => l.length <= columns), lines.filter((l) => l.length > columns).join(" | "));+ const all = lines.join("\n");+ const some = all.match(/([\d,]+) of ([\d,]+) files? drawn at this size/);+ const every = all.match(/([\d,]+) files?, all drawn/);+ const drawn = some ? num(some[1]) : every ? num(every[1]) : NaN;+ const total = some ? num(some[2]) : every ? num(every[1]) : NaN;+ facts.drawn[columns] = `${drawn}/${total}`;+ check(`${columns}: legend drawn equals pixel owners`, drawn === owners, `legend ${drawn}, owners ${owners}`);+ check(`${columns}: legend total equals feed repository_total`, total === feed.repository_total, `legend ${total}, feed ${feed.repository_total}`);+ if (feed.omitted.files > 0) {+ const beyond = all.match(/([\d,]+) beyond the ([\d,]+)-file cap/);+ check(`${columns}: legend beyond-cap equals feed`, beyond !== null && num(beyond[1]) === feed.omitted.files && num(beyond[2]) === feed.cap, beyond?.[0] ?? `missing from "${lines.slice(-2).join(" / ")}" (feed: ${feed.omitted.files} beyond the ${feed.cap}-file cap)`);+ }+ }++ // Importers of an edited file against the server's direct list.+ const layout180 = L.layoutMap(feed.files, 180, DOCK_ROWS - L.legendRows(180), repo.caseInsensitive);+ const direct = async (rel) => {+ const r = await getJson(`${api}/api/repos/${repo.id}/blast-radius`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ changed_files: [rel], max_depth: 1 }),+ });+ return [...new Set(r.transitive_affected.map((t) => t.path))].filter((p) => p !== rel);+ };+ let chosen = option("--file");+ let expected = chosen ? await direct(chosen) : null;+ if (!chosen) {+ // Largest first, source before tests: a test file rarely has importers.+ const isTest = (p) => /(^|\/)(tests?|__tests__|spec)\/|[._-](test|spec)\.[a-z]+$|(^|\/)test_[^/]*$/i.test(p);+ const biggest = layout180.drawn+ .map((i) => layout180.files[i])+ .sort((a, b) => isTest(a.path) - isTest(b.path) || b.nloc - a.nloc || (a.path < b.path ? -1 : 1))+ .slice(0, CANDIDATES);+ for (const f of biggest) {+ const list = await direct(f.path);+ if (chosen === undefined || (expected.length === 0 && list.length > 0)) [chosen, expected] = [f.path, list];+ if (list.length > 0) break;+ }+ }+ facts.importers = { file: chosen, api: expected.length };+ const raw = WIN ? `${root}\\${chosen.replace(/\//g, "\\")}` : `${root}/${chosen}`;+ const ctx = { cwd: root, isWindows: repo.caseInsensitive };+ const action = L.fromToolCall({ tool: "Edit", tool_use_id: "toolu_e2e_edit", file_path: raw }, {}, ctx);+ await timed("blast radius", async () => {+ map.observe(io, action, L.absolutePath(raw, ctx));+ await until(() => map.trail.callers?.status !== "loading", "importers", 60_000);+ });+ const callers = map.trail.callers;+ check("importers loaded", callers?.status === "ready", `${callers?.status} ${debug.join("; ")}`);+ if (callers?.status === "ready") {+ const got = [...callers.paths].sort();+ const want = [...expected].sort();+ check("importer paths equal the blast-radius direct list", JSON.stringify(got) === JSON.stringify(want), `${got.length} vs ${want.length}`);+ for (const columns of WIDTHS) {+ const tree = pane(columns);+ const raster = rasterOf(tree);+ if (!raster) continue;+ const layout = L.layoutMap(feed.files, raster.props.columns, raster.props.rows, repo.caseInsensitive);+ const resolved = L.resolveOverlay(layout, map.trail, root);+ const all = textsOf(tree).join("\n");+ const line = textsOf(tree).find((l) => l.startsWith("edited ")) ?? "";+ // Narrow panes use the short form: `edited x.py · 12 import it · 3 not drawn`.+ const said = line.match(/([\d,]+) (?:files? )?imports? it/);+ const notDrawn = line.match(/· ([\d,]+) not drawn/);+ const n = said ? num(said[1]) : NaN;+ const missing = notDrawn ? num(notDrawn[1]) : 0;+ const unmarked = expected.length - resolved.overlay.callers.length;+ check(`${columns}: legend importer count equals the API`, n === expected.length, `legend ${n}, api ${expected.length}`);+ check(`${columns}: overlay not-drawn importers equal the API's unmarked`, resolved.edit?.notDrawn === unmarked, `${resolved.edit?.notDrawn} vs ${unmarked}`);+ check(`${columns}: legend states the not-drawn importers`, missing === unmarked, `"${line}" (${unmarked} not drawn)`);+ const drawnPaths = resolved.overlay.callers.map((i) => layout.files[i].path);+ check(`${columns}: every marked importer is in the API list`, drawnPaths.every((p) => expected.includes(p)));+ facts.importers[`drawn${columns}`] = resolved.overlay.callers.length;+ }+ }+ facts.importers.lens = callers?.status === "ready" ? callers.paths.length : null;++ // Band rows as the session would hold them.+ let state = L.reduce(L.initialSession, { type: "discovered", mode: "full", freshness: null, repoRoot: root });++ if (!flag("--map-only")) {+ // Savings: Lens's baseline then a later read, and the raw ledger beside it.+ const first = await timed("savings", () => L.getSavings(repo.id));+ const rawLedger = await getJson(`${api}/api/repos/${repo.id}/savings`);+ const totals = L.savingsTotals(first);+ check("savings tokens equal the ledger", totals.tokens === rawLedger.saved_input_tokens, `${totals.tokens} vs ${rawLedger.saved_input_tokens}`);+ check("savings dollars equal the ledger", totals.usd === rawLedger.priced_input_savings_usd, `${totals.usd} vs ${rawLedger.priced_input_savings_usd}`);+ const delta = L.savingsSince(L.savingsTotals(await L.getSavings(repo.id)), totals);+ if (delta !== null) state = L.reduce(state, { type: "savings", delta });+ const row = state.savings === null ? null : L.savingsLine(state.savings, 180);+ const rows = L.bandRows(state, 180);+ check(+ "savings row absent or equal to the ledger delta",+ delta === null || delta.tokens === 0 ? state.savings === null && !rows.some((r) => r.includes("saved")) : rows.includes(row),+ delta === null ? "ledger shrank" : `${delta.tokens} tokens since the baseline`,+ );+ facts.savingsTokens = rawLedger.saved_input_tokens;++ // The change review through the MCP layer, headless over stdio: first+ // the clean copy (nothing to say), then after a one-line edit to the+ // chosen file (the copy only).+ try {+ L.warmMcp(host);+ await timed("mcp connect", () => host.mcp.server());+ await sleep(0);+ const review = () => L.callTool(host, "get_change_risk", {}, { timeoutMs: 120_000 });+ const clean = await timed("change risk (clean)", review);+ const quiet = L.reduce(state, { type: "reviewed", risk: clean });+ const quietBand = L.bandView(quiet, { columns: 180, hasSurvey: false });+ check(+ "clean tree: no review card and no review row",+ L.reviewText(quiet.review.outcome) === null && (quietBand === null || !textsOf(quietBand).some((l) => l.startsWith("review"))),+ L.reviewText(quiet.review.outcome) ?? "card null",+ );+ appendFileSync(join(dest, ...chosen.split("/")), "\n");+ const risk = await timed("change risk", review);+ state = L.reduce(state, { type: "reviewed", risk });+ const card = L.reviewText(state.review.outcome);+ check("edited tree: review card renders", typeof card === "string" && card.length > 0, card?.split("\n")[0] ?? "null");+ check("edited tree: card counts the one changed file", typeof card === "string" && card.includes("1 changed file"), card ?? "null");+ const tests = L.testsToRun(risk);+ if (tests !== null && risk.impacted_tests?.total !== undefined) {+ check("review test total equals the tool's", tests.total === risk.impacted_tests.total, `${tests.total}`);+ }+ facts.review = { ms: timings["change risk"], overLensTimeout: timings["change risk"] > 20_000, percentile: risk.risk_percentile ?? null };+ } catch (err) {+ check("change review ran", false, String(err));+ }+ }++ for (const columns of WIDTHS) {+ try {+ const band = L.bandView(state, { columns, hasSurvey: false });+ const lines = band === null ? [] : textsOf(band);+ check(`${columns}: band rows fit`, lines.every((l) => l.length <= columns), lines.join(" | "));+ } catch (err) {+ check(`${columns}: band renders`, false, String(err));+ }+ }+ map.dispose();+ } catch (err) {+ check("run completed", false, err instanceof Error ? err.message : String(err));+ } finally {+ killTree(mcp.pid());+ if (server) {+ killTree(server.child.pid);+ // The lock names the python process itself; stop it too if the launcher left it.+ try {+ killTree(JSON.parse(readFileSync(join(dest, ".repowise", "serve.lock.json"), "utf8")).pid);+ } catch {+ // removed by the server on exit+ }+ }+ for (let i = 0; i < 10 && existsSync(work); i++) {+ try {+ rmSync(work, { recursive: true, force: true, maxRetries: 3 });+ } catch {+ await sleep(1000);+ }+ }+ if (existsSync(work)) console.error(`could not remove ${work}`);+ }+}++await main();+const failed = checks.filter((c) => !c.ok);+const result = { ...facts, timings, checks: checks.length, failed };+console.log(JSON.stringify(result));+const out = option("--json");+if (out) writeFileSync(out, JSON.stringify(result, null, 2));+process.exitCode = failed.length === 0 ? 0 : 1;diff --git a/packages/claude-mod/scripts/mod-test.mjs b/packages/claude-mod/scripts/mod-test.mjsnew file mode 100644index 000000000..6249d5b8c--- /dev/null+++ b/packages/claude-mod/scripts/mod-test.mjs@@ -0,0 +1,39 @@+// Runs mod-test/*.test.ts under `claude plugin test` against the committed+// bundle. The tests go into a temporary copy of plugins/claude-code so they+// never ship with the plugin. Needs the `claude` CLI (>= 2.1.287) on PATH.++import { spawnSync } from "node:child_process";+import { cpSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+const pkg = resolve(here, "..");+const plugin = resolve(pkg, "../../plugins/claude-code");++const work = mkdtempSync(join(tmpdir(), "lens-mod-test-"));+const copy = join(work, "claude-code");+try {+ cpSync(plugin, copy, {+ recursive: true,+ // Claude Code writes these into a plugin dir it loads; never copy stale ones.+ filter: (src) => !src.includes(join(".claude-plugin", "types")) && !src.endsWith("tsconfig.json"),+ });+ for (const name of readdirSync(join(pkg, "mod-test"))) {+ if (name.endsWith(".test.ts")) cpSync(join(pkg, "mod-test", name), join(copy, "tests", name));+ }+ // The test `$` has no fs: the recorded Django payloads reach the map tests as a module.+ const recorded = (name) => readFileSync(join(pkg, "test", "fixtures", name), "utf8");+ writeFileSync(+ join(copy, "tests", "django-feed.ts"),+ `export const HEALTH_MAP = ${recorded("django-health-map.json")} as any+` ++ `export const BLAST_RADIUS = ${recorded("django-blast-radius-query-depth1.json")} as any+`,+ );+ const run = spawnSync("claude", ["plugin", "test", copy], { stdio: "inherit", shell: process.platform === "win32" });+ process.exitCode = run.status ?? 1;+} finally {+ rmSync(work, { recursive: true, force: true });+}diff --git a/packages/claude-mod/src/data/discovery.ts b/packages/claude-mod/src/data/discovery.tsnew file mode 100644index 000000000..11d28e377--- /dev/null+++ b/packages/claude-mod/src/data/discovery.ts@@ -0,0 +1,214 @@+/**+ * Which mode Lens runs in, and how fresh the index is. Same discovery order as+ * the VS Code extension: lock file, pid alive, /health probe. Read-only+ * throughout: nothing here starts, stops or writes anything.+ */++import { getHealth } from "@repowise-dev/api-client/health";+import { listRepos } from "@repowise-dev/api-client/repos";+import { ApiClientError } from "@repowise-dev/api-client";+import { normalizeRepoPath } from "@repowise-dev/types/repos";+import { isServeLock, type ServeLock } from "@repowise-dev/types/serve-lock";+import type { Host } from "../host";+import type { IndexFreshness, LiteReason, Mode } from "../model/session";+import { connectApiClient, withTimeout } from "./transport";++export interface Discovery {+ mode: Mode;+ liteReason?: LiteReason;+ repoRoot: string | null;+ /** In full mode: the local server's id for this repo, and when it last indexed it. */+ repo?: { id: string; updatedAt: string | null };+}++const HEALTH_TIMEOUT_MS = 800;+const LIST_TIMEOUT_MS = 3_000;+/** A little over the engine's own 30 s MCP connection timeout. */+const CONNECT_TIMEOUT_MS = 35_000;+const GIT_TIMEOUT_MS = 5_000;+const MAX_WALK = 20;+const SHA = /^[0-9a-f]{7,64}$/i;++export function isWindowsPath(p: string): boolean {+ return /^[A-Za-z]:[\\/]/.test(p) || p.startsWith("\\\\");+}++function join(dir: string, rel: string): string {+ return `${dir.replace(/[\\/]+$/, "")}/${rel}`;+}++function parentDir(p: string): string | null {+ const trimmed = p.replace(/[\\/]+$/, "");+ const cut = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));+ if (cut < 0) return null;+ if (cut === 0) return trimmed === "" ? null : "/";+ return trimmed.slice(0, cut);+}++/**+ * The nearest directory at or above `cwd` holding an index. The marker is+ * `.repowise/state.json`, not the bare directory: `~/.repowise` is the user+ * config dir and has no state file, so it never reads as an indexed repo.+ */+export async function findIndexedRoot(host: Host, cwd: string): Promise<string | null> {+ let dir: string | null = cwd;+ for (let i = 0; dir !== null && i < MAX_WALK; i++) {+ if (await host.fs.exists(join(dir, ".repowise/state.json"))) return dir;+ dir = parentDir(dir);+ }+ return null;+}++async function readJson(host: Host, path: string): Promise<unknown> {+ try {+ return JSON.parse(await host.fs.read(path)) as unknown;+ } catch {+ return null;+ }+}++/** The parsed lock, or null when missing or malformed. A stale lock still parses: gate on the pid. */+export async function readServeLock(host: Host, repoRoot: string): Promise<ServeLock | null> {+ const parsed = await readJson(host, join(repoRoot, ".repowise/serve.lock.json"));+ return isServeLock(parsed) ? parsed : null;+}++const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);++/**+ * Whether the lock points at plain http on this machine. The lock sits in the+ * repo, so a cloned repo can carry one naming any host, and a pid gate is no+ * defence (some pids are always alive). Lens probes nothing else.+ */+export function isLoopbackUrl(url: string): boolean {+ try {+ const u = new URL(url);+ return u.protocol === "http:" && LOOPBACK_HOSTS.has(u.hostname);+ } catch {+ return false;+ }+}++/**+ * Whether a process with this pid exists: true, false, or null when the probe+ * could not run (no process API on this surface). A null does not block the+ * /health probe, which still has to answer.+ */+export async function isPidAlive(host: Host, pid: number, cwd: string): Promise<boolean | null> {+ try {+ if (isWindowsPath(cwd)) {+ const out = await host.process.run(["tasklist", "/FI", `PID eq ${pid}`, "/NH", "/FO", "CSV"], cwd);+ return out.exitCode === 0 && out.stdout.includes(`"${pid}"`);+ }+ const out = await host.process.run(["ps", "-p", String(pid), "-o", "pid="], cwd);+ return out.exitCode === 0 && out.stdout.trim() === String(pid);+ } catch {+ return null;+ }+}++type ServerProbe = { kind: "ok"; repoId: string; updatedAt: string | null } | { kind: "down" } | { kind: "auth" } | { kind: "unlisted" };++/**+ * Health-probes the server the lock names, then finds this repo in its list.+ * A server can list several repos (a workspace DB), so the match is on+ * `local_path`, never the first row. Loopback needs no key; a 401 means one+ * is configured, which Lens will not read.+ */+export async function probeServer(host: Host, lock: ServeLock, repoRoot: string): Promise<ServerProbe> {+ connectApiClient(host, lock.url);+ try {+ await withTimeout(getHealth(), HEALTH_TIMEOUT_MS, "health");+ } catch {+ return { kind: "down" };+ }+ try {+ const repos = await withTimeout(listRepos(), LIST_TIMEOUT_MS, "listRepos");+ const win = isWindowsPath(repoRoot);+ const target = normalizeRepoPath(repoRoot, win);+ const match = repos.find((r) => r.local_path && normalizeRepoPath(r.local_path, win) === target);+ return match ? { kind: "ok", repoId: match.id, updatedAt: match.updated_at ?? null } : { kind: "unlisted" };+ } catch (err) {+ if (err instanceof ApiClientError && (err.status === 401 || err.status === 403)) return { kind: "auth" };+ return { kind: "down" };+ }+}++/**+ * Whether this plugin's MCP server connects. Connecting, not calling a tool:+ * a single-repo server does not list `list_repos`, and the engine's own+ * connect says outright when `repowise mcp` cannot start.+ */+export async function mcpReachable(host: Host): Promise<boolean> {+ try {+ return await withTimeout(host.mcp.connect(), CONNECT_TIMEOUT_MS, "mcp connect");+ } catch {+ return false;+ }+}++/** Mode for a directory with no index: quiet outside a git work tree, else depends on the CLI. */+async function unindexedMode(host: Host, cwd: string): Promise<Mode> {+ const inWorkTree = (await git(host, cwd, ["rev-parse", "--is-inside-work-tree"]))?.trim() === "true";+ if (!inWorkTree) return "no-repo";+ return (await mcpReachable(host)) ? "no-index" : "no-cli";+}++/** The local server's state: only a loopback lock with a pid not known dead is probed. */+async function serverState(host: Host, repoRoot: string): Promise<ServerProbe> {+ const lock = await readServeLock(host, repoRoot);+ if (!lock || !isLoopbackUrl(lock.url)) return { kind: "down" };+ if ((await isPidAlive(host, lock.pid, repoRoot)) === false) return { kind: "down" };+ return probeServer(host, lock, repoRoot);+}++export async function discover(host: Host): Promise<Discovery> {+ const cwd = await host.session.cwd();+ const repoRoot = await findIndexedRoot(host, cwd);+ if (repoRoot === null) return { mode: await unindexedMode(host, cwd), repoRoot };+ const server = await serverState(host, repoRoot);+ if (server.kind === "ok") return { mode: "full", repoRoot, repo: { id: server.repoId, updatedAt: server.updatedAt } };+ if (!(await mcpReachable(host))) return { mode: "no-cli", repoRoot };+ const liteReason: LiteReason = server.kind === "down" ? "no-server" : server.kind;+ return { mode: "lite", liteReason, repoRoot };+}++async function git(host: Host, cwd: string, args: string[]): Promise<string | null> {+ try {+ const out = await withTimeout(host.process.run(["git", ...args], cwd), GIT_TIMEOUT_MS, "git");+ return out.exitCode === 0 ? out.stdout : null;+ } catch {+ return null;+ }+}++/**+ * True while `repowise update` holds its lock with a live pid. The band stays+ * quiet then rather than asking for an update that is already running.+ * Ceiling: the post-commit hook's short-lived `.update.queued` marker is not+ * read, so the row can show for the few seconds before the update starts.+ */+async function updateRunning(host: Host, repoRoot: string): Promise<boolean> {+ const lock = await readJson(host, join(repoRoot, ".repowise/.update.lock"));+ const pid = (lock as { pid?: unknown } | null)?.pid;+ return typeof pid === "number" && (await isPidAlive(host, pid, repoRoot)) === true;+}++/**+ * Index freshness, compared the way the SessionStart hook does it: the+ * state file's `last_sync_commit` against `git rev-parse HEAD`, and the count+ * from `git diff --name-only`. Read-only git only. null means nothing to+ * say: current, unknown, or an update already running.+ */+export async function readFreshness(host: Host, repoRoot: string): Promise<IndexFreshness | null> {+ const state = await readJson(host, join(repoRoot, ".repowise/state.json"));+ const indexed = (state as { last_sync_commit?: unknown } | null)?.last_sync_commit;+ // The state file is repo content: only a bare hex sha may reach git's argv.+ if (typeof indexed !== "string" || !SHA.test(indexed)) return null;+ const head = (await git(host, repoRoot, ["rev-parse", "HEAD"]))?.trim();+ if (!head || !SHA.test(head) || head === indexed) return null;+ if (await updateRunning(host, repoRoot)) return null;+ const diff = await git(host, repoRoot, ["diff", "--name-only", indexed, head, "--"]);+ const changedFiles = diff === null ? null : diff.split("\n").filter((l) => l.trim() !== "").length;+ return { changedFiles };+}diff --git a/packages/claude-mod/src/data/mcp.ts b/packages/claude-mod/src/data/mcp.tsnew file mode 100644index 000000000..8135cbf6e--- /dev/null+++ b/packages/claude-mod/src/data/mcp.ts@@ -0,0 +1,144 @@+/**+ * Lens's own read-only calls to this plugin's repowise MCP server, and the+ * rule for approving them. The engine approves a call only when it STARTS+ * while one of Lens's hooks is live, so a caller starts the call inside its+ * hook (awaited or `void`), never from a timer or a late promise.+ */++import type { Host } from "../host";+import type { McpToolResult } from "../mod-api";+import type { FileContext } from "../model/session";+import { withTimeout } from "./transport";++/** This plugin's name, as `next.origin.plugin` reports it. */+export const PLUGIN_NAME = "repowise";++/** Only the tools a shipped Lens feature calls. All read-only. */+export const LENS_TOOLS = ["get_context", "get_change_risk", "get_why", "get_answer"] as const;+export type LensTool = (typeof LENS_TOOLS)[number];++/** Both spellings of this plugin's server seen at runtime; Lens calls and approves no other. */+const PLUGIN_SERVER_FORMS: readonly string[] = ["plugin:repowise:repowise", "plugin_repowise_repowise"];++const DEFAULT_TIMEOUT_MS = 10_000;++let resolvedServer: string | null = null;+let resolving: Promise<void> | null = null;++/** Forget the resolved server; a new session resolves again. */+export function resetMcp(): void {+ resolvedServer = null;+ resolving = null;+}++/**+ * Asks the engine, once, which name this plugin's server runs under, and+ * keeps it only when it is one of this plugin's own forms. Never awaited by a+ * caller: connecting can take seconds, and an MCP call started after its hook+ * returned is refused (REST through `$.http` from a late continuation works;+ * a late MCP call does not).+ */+export function warmMcp(host: Host): void {+ if (resolvedServer !== null || resolving !== null) return;+ const asked = host.mcp+ .server()+ .then((name) => {+ if (name !== null && PLUGIN_SERVER_FORMS.includes(name)) resolvedServer = name;+ })+ .catch(() => undefined)+ .finally(() => {+ // Unresolved: the next hook asks again.+ if (resolving === asked) resolving = null;+ });+ resolving = asked;+}++/**+ * Waits for the server name, for a hook that stays live while it waits (a+ * command): the call it then starts is still started inside that hook.+ * True once resolved; false when the server did not connect in time.+ */+export async function mcpReady(host: Host, timeoutMs = DEFAULT_TIMEOUT_MS): Promise<boolean> {+ warmMcp(host);+ const pending = resolving;+ if (resolvedServer === null && pending !== null) await withTimeout(pending, timeoutMs, "MCP connect").catch(() => undefined);+ return resolvedServer !== null;+}++/** How a server's tools are named in `tool.check` (`mcp__plugin_repowise_repowise__get_context`). */+export function toolName(serverForm: string, tool: string): string {+ return `mcp__${serverForm.replace(/[^A-Za-z0-9_-]/g, "_")}__${tool}`;+}++const OWN_TOOL_NAMES: ReadonlySet<string> = new Set(+ PLUGIN_SERVER_FORMS.flatMap((form) => LENS_TOOLS.map((tool) => toolName(form, tool))),+);++/**+ * Whether a `tool.check` is for one of Lens's own calls: a plugin-made call+ * (id `toolu_plugin_`), raised by this plugin, to an allowlisted tool on this+ * plugin's server. Anything else keeps the engine's verdict.+ */+export function isOwnLensCall(e: { tool: string; tool_use_id?: string | undefined }, originPlugin: unknown): boolean {+ if (originPlugin !== PLUGIN_NAME) return false;+ if (typeof e.tool_use_id !== "string" || !e.tool_use_id.startsWith("toolu_plugin_")) return false;+ return OWN_TOOL_NAMES.has(e.tool);+}++function parse<T>(result: McpToolResult, tool: string): T {+ const text = result.content[0]?.text;+ if (result.isError) throw new Error(`${tool} failed: ${String(text).slice(0, 200)}`);+ if (typeof text !== "string") throw new Error(`${tool} returned no text`);+ const parsed = JSON.parse(text) as { result?: T };+ // Claude Code hands the tool's structured result over as `{"result": ...}`;+ // a plain MCP client sees the bare object. Both are the same server's answer.+ return (parsed !== null && typeof parsed === "object" && "result" in parsed ? parsed.result : parsed) as T;+}++/**+ * Calls one allowlisted tool and returns the parsed `result`. The call starts+ * synchronously, so it starts while the calling hook is live (the engine+ * approves Lens's call only then); with no server name resolved yet it does+ * not start at all and rejects, and the caller tries again from a later hook.+ * Rejects on timeout or a tool error; nothing retries after the hook.+ */+export function callTool<T>(+ host: Host,+ tool: LensTool,+ args: Record<string, unknown>,+ opts: { timeoutMs?: number } = {},+): Promise<T> {+ if (resolvedServer === null) {+ warmMcp(host);+ return Promise.reject(new Error("repowise MCP server name not resolved yet"));+ }+ const call = host.mcp.call(resolvedServer, tool, args).then((r) => parse<T>(r, tool));+ return withTimeout(call, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS, tool);+}++// Typed here, not shared: the MCP server has no generated TypeScript types,+// and Lens reads three fields of a larger card.+interface ContextTarget {+ error?: string;+ callers?: unknown[];+ callers_total?: number;+ ownership?: { contributor_count?: number | null };+}++/** The file card's caller and contributor counts; null when the index does not know the file. */+export async function fetchFileContext(host: Host, path: string): Promise<FileContext | null> {+ const result = await callTool<{ targets?: Record<string, ContextTarget> }>(host, "get_context", {+ targets: [path],+ include: ["callers", "ownership"],+ });+ const target = result.targets?.[path];+ if (target === undefined || target.error !== undefined) return null;+ // The server stamps `callers_total` on every reduction of the list (its+ // construction cap and its response budget alike), so without it the list is whole.+ const callers = target.callers_total ?? target.callers?.length;+ const contributors = target.ownership?.contributor_count;+ return {+ callerFiles: typeof callers === "number" ? callers : null,+ contributors: typeof contributors === "number" ? contributors : null,+ };+}diff --git a/packages/claude-mod/src/data/transport.ts b/packages/claude-mod/src/data/transport.tsnew file mode 100644index 000000000..838ddc6f8--- /dev/null+++ b/packages/claude-mod/src/data/transport.ts@@ -0,0 +1,23 @@+import { configureApiClient, createAdapterFetch } from "@repowise-dev/api-client";+import type { Host } from "../host";++/** Points the shared api-client at a loopback server, over the host's HTTP. No token: Lens never reads an API key. */+export function connectApiClient(host: Host, baseUrl: string): void {+ configureApiClient({ baseUrl, fetch: createAdapterFetch(host.http) });+}++export class TimeoutError extends Error {+ constructor(label: string, ms: number) {+ super(`${label} timed out after ${ms} ms`);+ this.name = "TimeoutError";+ }+}++/** Rejects with TimeoutError when `work` has not settled in `ms`; the work itself is not cancelled. */+export function withTimeout<T>(work: Promise<T>, ms: number, label: string): Promise<T> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new TimeoutError(label, ms)), ms);+ });+ return Promise.race([work, timeout]).finally(() => clearTimeout(timer));+}diff --git a/packages/claude-mod/src/format.ts b/packages/claude-mod/src/format.tsnew file mode 100644index 000000000..b1a0e9f50--- /dev/null+++ b/packages/claude-mod/src/format.ts@@ -0,0 +1,16 @@+import { formatNumber } from "@repowise-dev/ui/lib/format";++/** `1 file`, `1,204 files`. */+export function countOf(n: number, singular: string, plural: string): string {+ return `${formatNumber(n)} ${n === 1 ? singular : plural}`;+}++/**+ * Cuts `text` to `columns` cells, ending in an ellipsis when cut. Counts UTF-16+ * units, which matches cells for the BMP text Lens writes.+ */+export function fit(text: string, columns: number): string {+ if (columns <= 0) return "";+ if (text.length <= columns) return text;+ return `${text.slice(0, columns - 1).trimEnd()}…`;+}diff --git a/packages/claude-mod/src/host.ts b/packages/claude-mod/src/host.tsnew file mode 100644index 000000000..2d9f9b456--- /dev/null+++ b/packages/claude-mod/src/host.ts@@ -0,0 +1,29 @@+/**+ * What Lens may do, as closures over `$`. register.ts builds one from each+ * hook's own `$`; tests build fakes. Nothing outside register.ts sees `$`.+ */++import type { MinimalFetch } from "@repowise-dev/api-client";+import type { McpToolResult, ProcessRunResult } from "./mod-api";++export interface Host {+ session: { cwd(): Promise<string> };+ fs: {+ /** Rejects when the file is missing. */+ read(path: string): Promise<string>;+ exists(path: string): Promise<boolean>;+ };+ process: {+ /** Read-only commands only (git queries, a pid probe). Rejects off the CLI. */+ run(argv: readonly string[], cwd: string): Promise<ProcessRunResult>;+ };+ http: MinimalFetch;+ /** This plugin's own repowise MCP server. */+ mcp: {+ /** Waits for the server to connect; false when it cannot (the CLI is not installed). */+ connect(): Promise<boolean>;+ /** The name `call` takes for the server, or null when it does not connect. */+ server(): Promise<string | null>;+ call(server: string, tool: string, args: Record<string, unknown>): Promise<McpToolResult>;+ };+}diff --git a/packages/claude-mod/src/map-controller.ts b/packages/claude-mod/src/map-controller.tsnew file mode 100644index 000000000..26ef5db80--- /dev/null+++ b/packages/claude-mod/src/map-controller.ts@@ -0,0 +1,341 @@+/**+ * The map's session: what Claude looked at, the feed, the importers of the+ * last edit, and the animations. One instance per session; a disposed one+ * drops every late answer, so nothing from an earlier session lands in this+ * one. It never sees `$`: register.ts hands it closures (MapIO).+ *+ * Quiet at rest: no request leaves until the person asks for the map (/lens,+ * or an auto-open that was placed).+ */++import { analyzeBlastRadius } from "@repowise-dev/api-client/blast-radius";+import { getHealthMap } from "@repowise-dev/api-client/code-health";+import type { HealthMapFeed } from "@repowise-dev/types/health";+import { formatRelativeTimeOrNull } from "@repowise-dev/ui/lib/format";+import { withTimeout } from "./data/transport";+import type { UiOpenResult } from "./mod-api";+import { relativeTo } from "./model/events";+import { initialTrail, reduceTrail, type TrailAction, type TrailState } from "./model/trail";+import { MAP_COPY, notPlacedLine, type ScopeFacts } from "./views/copy";+import type { Node } from "./views/elements";+import { layoutMap, type MapLayout } from "./views/map";+import { mapPaneView, mapSize, noticeView, type PaneSize } from "./views/mapPane";+import { desktopSize, svgPaneView } from "./views/mapSvg";+import { FLASH_MS, FRAME_MS, RIPPLE_MS, frameCells, resolveOverlay, rippleRadius, type Anim } from "./views/overlay";++/** The server's own maximum: Django's 2,347 drawable files fit in one call. */+const MAP_CAP = 4_000;+const MAP_TIMEOUT_MS = 15_000;+const CALLERS_TIMEOUT_MS = 20_000;+/** Direct importers only: 0.6 s on Django's query.py, against 2 s for three levels. */+const CALLERS_DEPTH = 1;++export interface MapIO {+ redraw(): void;+ /** Debug log only (`--debug-file`), never the user's screen. */+ debug(message: string): void;+ blit(cells: string, columns: number, rows: number): Promise<{ deny?: string }>;+ /** `focus` only when the person asked for the pane; an automatic open never takes the keyboard. */+ openPane(focus: boolean): Promise<UiOpenResult>;+ closePane(): Promise<void>;+}++/** The repo the map draws, once discovery found the local server for it. */+export interface MapRepo {+ id: string;+ root: string;+ updatedAt: string | null;+ caseInsensitive: boolean;+}++type Feed = { status: "idle" | "loading" | "failed" } | { status: "ready"; data: HealthMapFeed };++export interface PaneInput extends PaneSize {+ /** The surface drawing the pane: the terminal (cells) or the desktop app (SVG). */+ surface: string | undefined;+ /** Why there is no repo to draw, when there is none. */+ notice: string;+}++function scopeFacts(layout: MapLayout, data: HealthMapFeed, repo: MapRepo): ScopeFacts {+ return {+ drawn: layout.drawn.length,+ repositoryTotal: data.repository_total,+ indexed: formatRelativeTimeOrNull(repo.updatedAt, "") || null,+ beyondCap: data.omitted.files,+ cap: data.cap,+ };+}++/** What an animation draws on: the frame for a step, or null once nothing is on screen. */+type Screen = (step: Anim) => { cells: string; columns: number; rows: number } | null;++/**+ * Plays a flash or a ripple with blits, a frame every FRAME_MS for about a+ * second, one blit at a time. Stops on a refused blit and asks for a redraw,+ * which draws the resting frame.+ */+class Animator {+ private anim: { kind: Anim["kind"]; start: number; duration: number } | null = null;+ private timer: ReturnType<typeof setInterval> | undefined;+ private blitting = false;+ private stopped = false;++ progress(now: number): Anim | undefined {+ const a = this.anim;+ return a === null ? undefined : { kind: a.kind, t: Math.min(1, (now - a.start) / a.duration) };+ }++ play(io: MapIO, kind: Anim["kind"], screen: Screen): void {+ this.stop();+ if (this.stopped) return;+ this.anim = { kind, start: Date.now(), duration: kind === "flash" ? FLASH_MS : RIPPLE_MS };+ io.redraw();+ this.timer = setInterval(() => this.tick(io, screen), FRAME_MS);+ }++ stop(): void {+ clearInterval(this.timer);+ this.timer = undefined;+ this.anim = null;+ }++ /** For good: a disposed map plays nothing more. */+ end(): void {+ this.stopped = true;+ this.stop();+ }++ private tick(io: MapIO, screen: Screen): void {+ const step = this.progress(Date.now());+ const frame = step === undefined ? null : screen(step);+ if (step === undefined || frame === null) return this.stop();+ // One blit at a time: a slow surface drops frames rather than queueing them.+ if (this.blitting) return;+ if (step.t >= 1) this.stop();+ this.blitting = true;+ io.blit(frame.cells, frame.columns, frame.rows)+ .then((r) => r.deny === undefined || this.refused(io, r.deny))+ .catch((err: unknown) => this.refused(io, String(err)))+ .finally(() => {+ this.blitting = false;+ });+ }++ /** Resized, closed or refused under the animation: stop and let a redraw show the resting frame. */+ private refused(io: MapIO, why: string): void {+ io.debug(`blit refused: ${why}`);+ this.stop();+ if (!this.stopped) io.redraw();+ }+}++export class LensMap {+ trail: TrailState = initialTrail;+ private disposed = false;+ /** One band row the map asks for (the pane could not open), until the turn ends. */+ private band: string | null = null;+ private repo: MapRepo | null = null;+ private feed: Feed = { status: "idle" };+ private requested = false;+ private autoOpenTried = false;+ /** The latest edit's absolute path with its case, for the importers request. */+ private editPath: string | null = null;+ /** The edit whose importers were asked for, so each is asked once. */+ private callersAsked = 0;+ private drawn: { layout: MapLayout; root: string } | null = null;+ private layoutCache: { data: HealthMapFeed; columns: number; rows: number; layout: MapLayout } | null = null;+ private readonly animator = new Animator();+ private reducedMotion = false;++ private readonly autoOpenOnRead: boolean;++ constructor(autoOpenOnRead: boolean) {+ this.autoOpenOnRead = autoOpenOnRead;+ }++ /** The band row the map wants shown, if any. */+ bandLine(): string | null {+ return this.band;+ }++ /** The person's `prefersReducedMotion` setting: resting frames only. */+ setReducedMotion(on: boolean): void {+ this.reducedMotion = on;+ }++ dispose(): void {+ this.disposed = true;+ this.animator.end();+ }++ setRepo(io: MapIO, repo: MapRepo | null): void {+ this.repo = repo;+ this.fetchWanted(io);+ }++ /** One observed tool call; `editPath` is the edited file's absolute path, case kept. */+ observe(io: MapIO, action: TrailAction, editPath: string | null): void {+ if (action.type === "edit") this.editPath = editPath;+ this.apply(io, action);+ if (action.type === "edit") this.fetchWanted(io);+ if (action.type === "read") void this.autoOpen(io);+ }++ /** /lens: open the pane with focus (asked, so placed at any width) and start what it shows. */+ async request(io: MapIO): Promise<void> {+ this.requested = true;+ this.band = null;+ if (this.feed.status === "failed") this.feed = { status: "idle" };+ const opened = await io.openPane(true);+ if (!opened.isPlaced) this.band = notPlacedLine(opened.reason);+ this.fetchWanted(io);+ io.redraw();+ }++ /** A main-loop turn ended: the band row has been seen. */+ turnEnded(): void {+ this.band = null;+ }++ /** Another tab is shown: nothing of the map is on screen to animate. */+ offScreen(): void {+ this.drawn = null;+ }++ /** The pane's tree; starts the feed fetch when the map is wanted and not yet asked for. */+ paneTree(io: MapIO, pane: PaneInput): Node {+ this.drawn = null;+ const notice = this.noticeFor(io, pane);+ if (notice !== null) return noticeView(notice, pane.bodyColumns);+ const { data } = this.feed as { data: HealthMapFeed };+ const repo = this.repo as MapRepo;+ // The terminal draws cells and the desktop app SVG, with no blits: its resting frame redraws as the trail grows.+ const desktop = pane.surface === "desktop";+ const layout = this.layoutFor(data, desktop ? desktopSize(mapSize(pane)) : mapSize(pane), repo.caseInsensitive);+ const resolved = resolveOverlay(layout, this.trail, repo.root);+ const scope = scopeFacts(layout, data, repo);+ if (desktop) return svgPaneView(layout, resolved, scope);+ this.drawn = { layout, root: repo.root };+ return mapPaneView(layout, frameCells(layout, resolved.overlay, this.animator.progress(Date.now())), resolved, scope);+ }++ /** Why there is no map to draw yet (and the feed fetch started when wanted), or null once it can be drawn. */+ private noticeFor(io: MapIO, pane: PaneInput): string | null {+ if (pane.surface !== undefined && pane.surface !== "terminal" && pane.surface !== "desktop") return MAP_COPY.desktop;+ if (this.repo === null) return pane.notice;+ this.requested = true;+ this.fetchWanted(io);+ const status = this.feed.status;+ if (status === "ready") return null;+ return status === "failed" ? MAP_COPY.failed : MAP_COPY.loading;+ }++ private layoutFor(data: HealthMapFeed, size: { columns: number; rows: number }, caseInsensitive: boolean): MapLayout {+ const cached = this.cachedLayout(data, size);+ if (cached !== null) return cached;+ const layout = layoutMap(data.files, size.columns, size.rows, caseInsensitive);+ this.layoutCache = { data, columns: size.columns, rows: size.rows, layout };+ return layout;+ }++ private cachedLayout(data: HealthMapFeed, size: { columns: number; rows: number }): MapLayout | null {+ const c = this.layoutCache;+ const same = c !== null && c.data === data && c.columns === size.columns && c.rows === size.rows;+ return same ? c.layout : null;+ }++ private apply(io: MapIO, action: TrailAction): void {+ const next = reduceTrail(this.trail, action);+ if (next === this.trail) return;+ this.trail = next;+ if (action.type === "search") this.animate(io, "flash");+ else if (action.type === "callers" && action.callers.status === "ready") this.animate(io, "ripple");+ else io.redraw();+ }++ /** The feed and the latest edit's importers, once the map is wanted and the repo known. */+ private fetchWanted(io: MapIO): void {+ if (!this.requested || this.repo === null) return;+ this.loadFeed(io, this.repo);+ this.loadCallers(io, this.repo);+ }++ private loadFeed(io: MapIO, repo: MapRepo): void {+ if (this.feed.status !== "idle") return;+ this.feed = { status: "loading" };+ withTimeout(getHealthMap(repo.id, { cap: MAP_CAP }), MAP_TIMEOUT_MS, "health map")+ .then((data) => {+ this.feed = { status: "ready", data };+ })+ .catch((err: unknown) => {+ this.feed = { status: "failed" };+ io.debug(`health map failed: ${String(err)}`);+ })+ .finally(() => {+ if (!this.disposed) io.redraw();+ });+ }++ private loadCallers(io: MapIO, repo: MapRepo): void {+ const edits = this.trail.edits;+ if (this.editPath === null || this.callersAsked === edits) return;+ this.callersAsked = edits;+ const rel = relativeTo(this.editPath, repo.root, repo.caseInsensitive);+ if (rel === null) return this.apply(io, { type: "callers", edits, callers: { status: "failed" } });+ const request = { changed_files: [rel], max_depth: CALLERS_DEPTH };+ withTimeout(analyzeBlastRadius(repo.id, request), CALLERS_TIMEOUT_MS, "importers")+ .then((r) => {+ const paths = [...new Set(r.transitive_affected.map((t) => t.path))].filter((p) => p !== rel);+ if (!this.disposed) this.apply(io, { type: "callers", edits, callers: { status: "ready", paths } });+ })+ .catch((err: unknown) => {+ io.debug(`importers failed: ${String(err)}`);+ if (!this.disposed) this.apply(io, { type: "callers", edits, callers: { status: "failed" } });+ });+ }++ /** The first read opens the map when the toggle is on and the pane would be placed; never forced. */+ private async autoOpen(io: MapIO): Promise<void> {+ if (!this.mayAutoOpen()) return;+ this.autoOpenTried = true;+ const opened = await io.openPane(false);+ if (this.disposed || this.requested) return;+ if (opened.isPlaced) {+ this.requested = true;+ this.fetchWanted(io);+ return;+ }+ // Below the width an unasked pane needs: close it rather than let it pop up later.+ await io.closePane();+ this.band = MAP_COPY.waiting;+ io.redraw();+ }++ /** Once, with the toggle on, before the person asked, and only for a repo with a map. */+ private mayAutoOpen(): boolean {+ return this.autoOpenOnRead && !this.autoOpenTried && !this.requested && this.repo !== null;+ }++ /** Whether an animation would show anything: a map on screen, motion allowed, a ripple with somewhere to go. */+ private canAnimate(kind: Anim["kind"]): boolean {+ const on = this.drawn;+ if (this.reducedMotion || on === null) return false;+ return kind === "flash" || rippleRadius(on.layout, resolveOverlay(on.layout, this.trail, on.root).overlay) > 0;+ }++ /** A flash or a ripple when it would show; otherwise (reduced motion, nothing on screen) the resting frame. */+ private animate(io: MapIO, kind: Anim["kind"]): void {+ this.animator.stop();+ if (!this.canAnimate(kind)) return io.redraw();+ this.animator.play(io, kind, (step) => this.frame(step));+ }++ /** The current trail on the drawn map at one step, or null once the map is off screen. */+ private frame(step: Anim): { cells: string; columns: number; rows: number } | null {+ const on = this.drawn;+ if (on === null) return null;+ const cells = frameCells(on.layout, resolveOverlay(on.layout, this.trail, on.root).overlay, step);+ return { cells, columns: on.layout.columns, rows: on.layout.rows };+ }+}diff --git a/packages/claude-mod/src/mod-api.ts b/packages/claude-mod/src/mod-api.tsnew file mode 100644index 000000000..642965889--- /dev/null+++ b/packages/claude-mod/src/mod-api.ts@@ -0,0 +1,167 @@+/**+ * The slice of the Claude Code mods API that register.ts uses, typed locally.+ *+ * Claude Code writes the full declarations (`claude-code`) into a plugin dir+ * when it loads the mod, so they do not exist where `claude` is not installed.+ * This file names only what Lens calls. It is checked against the real+ * surface locally, by `npm run test:mod` and `claude plugin validate --strict`+ * on the built bundle; CI runs neither. Extend it with each new call.+ */++export interface ProcessRunResult {+ exitCode: number;+ stdout: string;+ stderr: string;+}++export interface HttpResponse {+ status: number;+ ok: boolean;+ headers: Record<string, string>;+ text: string;+}++export interface McpToolResult {+ content: Array<{ type: string; text?: string }>;+ isError: boolean;+}++export interface RenderEvent {+ props: { hasSurvey?: boolean; bodyColumns?: number };+}++/** A `Pane` render: the pane's id is `requestId`. */+export interface PaneRenderEvent {+ surface?: string;+ requestId: string;+ props: { bodyColumns: number; placement: "dock" | "inline"; scroll: { bodyRows: number } };+}++export type UiOpenResult = { isPlaced: true } | { isPlaced: false; reason: string };++export interface ModApi {+ session: { cwd(): Promise<string> };+ fs: {+ read(path: string): Promise<string>;+ exists(path: string): Promise<boolean>;+ };+ process: {+ run(argv: readonly string[], init: { cwd: string; timeoutMs: number }): Promise<ProcessRunResult>;+ };+ http: {+ fetch(url: string, init: { method?: string; headers?: Record<string, string>; body?: string }): Promise<HttpResponse>;+ };+ mcp: {+ connect(server: string): Promise<{ isConnected: boolean; server?: string }>;+ call(server: string, tool: string, args?: Record<string, unknown>): Promise<McpToolResult>;+ };+ prompt: {+ /** A visible prompt, run once the session is idle. */+ submit(input: { text: string }): Promise<unknown>;+ };+ ui: {+ invalidate(event: "ui.render"): void;+ /** `transcript`: a dim row of its own; `debug`: the debug log alone. */+ log(text: string, options: { to: "debug" | "transcript" }): void;+ resolve(e: { props: object }): Record<string, (props: Record<string, unknown>) => unknown>;+ /** `focus`: the pane takes the keyboard (only when the person asked for it). */+ open(pane: { id: string; title?: string; rows?: number; focus?: boolean }): Promise<UiOpenResult>;+ close(pane: { id: string }): Promise<void>;+ blit(args: { requestId: string; key: string; cells: string; columns: number; rows: number }): Promise<{ deny?: string }>;+ };+ command: {+ register(command: { name: string; description: string; argumentHint?: string; immediate?: true }): Promise<unknown>;+ };+ settings: { read(): Promise<Readonly<Record<string, unknown>>> };+}++export interface SessionStartEvent {+ cwd?: string;+}++export interface TurnCompleteEvent {+ agentId?: string;+ /** Claude's final text this turn. */+ answer?: string;+ reason?: "answer" | "aborted" | "refusal" | "error";+ isAborted?: boolean;+}++/** A tool call as `tool.call` sees it: the tool's own arguments ride beside these keys. */+export interface ToolCallEvent {+ tool: string;+ tool_use_id: string;+ agentId?: string;+ file_path?: unknown;+ /** The tool's other arguments. */+ [arg: string]: unknown;+}++export interface ToolCheckEvent {+ tool: string;+ input: unknown;+ /** Absent on a query (`$.tool.check`). */+ tool_use_id?: string;+}++/** `next` of `tool.check` also says whose call is being decided. */+export type CheckNext = ((e: ToolCheckEvent) => Promise<unknown>) & { origin: { plugin: string; tier?: string } };++export interface SpinnerEvent {+ props: { word: string; message: string | null; suffix: string; mode: string };+}++export interface ToolResultEvent {+ props: { tool_use_id: string; tool: string; output: unknown; isErrored: boolean };+}++export interface ToolUseEvent {+ props: { tool_use_id: string; tool: string; input: unknown; isRunning: boolean; isErrored: boolean };+}++export interface PostToolUseEvent {+ tool_name: string;+ tool_use_id: string;+ tool_input: unknown;+}++/** `/lens <args>`: everything after the name, as typed. */+export interface CommandRunEvent {+ args?: string;+}++/** A change of, or Enter in, an `Input` a render hook drew. */+export interface UiInputEvent {+ plugin: string;+ element: string;+ kind: "change" | "submit";+ value: string;+}++/** After the conversation was compacted; Lens reads nothing of it. */+export interface PostCompactEvent {+ trigger?: "manual" | "auto";+}++export type Hook<E> = ($: ModApi, e: E, next: (e: E) => Promise<unknown>) => Promise<unknown>;++/** The plugin's `userConfig` values, fixed for one activation. */+export type PluginOptions = Readonly<Record<string, string | number | boolean | readonly string[]>>;++export interface On {+ (event: "session.start", hook: Hook<SessionStartEvent>): unknown;+ (event: "turn.complete", hook: Hook<TurnCompleteEvent>): unknown;+ (event: "turn.start", hook: Hook<unknown>): unknown;+ (event: "ui.render", matcher: { component: "AbovePrompt" }, hook: Hook<RenderEvent>): unknown;+ (event: "tool.call", hook: Hook<ToolCallEvent>): unknown;+ (event: "tool.check", hook: ($: ModApi, e: ToolCheckEvent, next: CheckNext) => Promise<unknown>): unknown;+ (event: "ui.render", matcher: { component: "Spinner" }, hook: Hook<SpinnerEvent>): unknown;+ (event: "ui.render", matcher: { component: "ToolResult" }, hook: Hook<ToolResultEvent>): unknown;+ (event: "ui.render", matcher: { component: "ToolUse" }, hook: Hook<ToolUseEvent>): unknown;+ /** `next(e)` resolves to the settings hooks' folded result, `{ additionalContext: string[] }`. */+ (event: "classic.PostToolUse", hook: Hook<PostToolUseEvent>): unknown;+ (event: "ui.render", matcher: { component: "Pane" }, hook: Hook<PaneRenderEvent>): unknown;+ (event: "command.run", matcher: { command: string }, hook: Hook<CommandRunEvent>): unknown;+ (event: "ui.input", matcher: { plugin: string; element: string }, hook: Hook<UiInputEvent>): unknown;+ (event: "classic.PostCompact", hook: Hook<PostCompactEvent>): unknown;+}diff --git a/packages/claude-mod/src/model/ask.ts b/packages/claude-mod/src/model/ask.tsnew file mode 100644index 000000000..fc1e64033--- /dev/null+++ b/packages/claude-mod/src/model/ask.ts@@ -0,0 +1,109 @@+/**+ * The pane's Ask tab and the `/lens` arguments. Pure: a question is routed to+ * `get_why` or `get_answer`, and the reply is kept as the tool sent it.+ */++import type { DecisionsArtifactData } from "@repowise-dev/types";++export type PaneTab = "map" | "ask" | "recap";++export type AskTool = "get_why" | "get_answer";++// Typed here, not shared: the MCP server has no generated TypeScript types,+// and the shared chat types lack the evidence fields Lens shows.++export interface EvidenceRef {+ id?: string;+}++/** The fields of a `get_answer` reply the tab shows, as the server names them. */+export interface AnswerReply {+ answer?: string;+ confidence?: string;+ retrieval_quality?: string;+ citations?: string[];+ /** Why the answer is not a synthesis (`no-llm-provider`); absent when it may be one. */+ degraded?: string;+}++export interface WhyCommit {+ sha?: string;+ message?: string;+ date?: string;+ evidence_refs?: EvidenceRef[];+}++/** A decision row: the shared shape, plus the id, authority and confidence `get_why` also sends. */+export type WhyDecision = NonNullable<DecisionsArtifactData["decisions"]>[number] & {+ id?: string;+ /** `accepted` when somebody signed it, `candidate` when nobody has yet. */+ authority?: string;+ confidence?: number | null;+};++export interface WhyRationale {+ path: string;+ lines?: [number, number];+ comment: string;+ evidence_refs?: EvidenceRef[];+}++/** The fields of a `get_why` reply the tab shows, as the server names them. */+export interface WhyReply {+ reason?: string;+ answer_basis?: string;+ decisions?: WhyDecision[];+ git_archaeology?: { summary?: string; git_log?: WhyCommit[]; file_commits?: WhyCommit[] };+ code_rationale?: WhyRationale[];+ code_rationale_total?: number;+}++export type AskReply = { tool: "get_answer"; reply: AnswerReply } | { tool: "get_why"; reply: WhyReply };++export type AskState =+ | { phase: "idle" }+ /** `busy`: another question came while this one ran; it was not asked. */+ | { phase: "asking"; question: string; tool: AskTool; busy: boolean }+ | { phase: "answered"; question: string; answer: AskReply }+ | { phase: "failed"; question: string; tool: AskTool; message: string };++/** A "why" question goes to the decision records; anything else to the index's answer. */+export function askRoute(question: string): { tool: AskTool; args: Record<string, unknown> } {+ return /^\s*why\b/i.test(question)+ ? { tool: "get_why", args: { query: question } }+ : { tool: "get_answer", args: { question } };+}++export function askReply(tool: AskTool, reply: unknown): AskReply {+ const body = typeof reply === "object" && reply !== null ? reply : {};+ return tool === "get_why" ? { tool, reply: body as WhyReply } : { tool, reply: body as AnswerReply };+}++/**+ * Whether a reply may have come from the index's own model: `get_answer`+ * synthesizes with one when the repo configures it. Only an answer that says+ * `no-llm-provider` is known to have used none.+ */+export function mayHaveUsedModel(a: AskReply): boolean {+ return a.tool === "get_answer" && a.reply.degraded !== "no-llm-provider";+}++/** What `/lens <args>` asks for: a tab to show, and a question to ask. */+export function lensCommand(args: string): { tab: PaneTab | null; question: string | null } {+ const [word = "", ...rest] = args.trim().split(/\s+/);+ const question = rest.join(" ");+ switch (word.toLowerCase()) {+ case "map":+ case "recap":+ return { tab: word.toLowerCase() as PaneTab, question: null };+ case "ask":+ return { tab: "ask", question: question === "" ? null : question };+ default:+ return { tab: null, question: null };+ }+}++/** The Ask field's text after `Why` on a review: the decision that governs the edit. */+export function whyDraft(decision: string): string {+ return `why ${decision}`;+}diff --git a/packages/claude-mod/src/model/events.ts b/packages/claude-mod/src/model/events.tsnew file mode 100644index 000000000..7ba3e07d1--- /dev/null+++ b/packages/claude-mod/src/model/events.ts@@ -0,0 +1,183 @@+/**+ * Engine events to session actions. Pure.+ */++import type { Savings } from "@repowise-dev/api-client/costs";+import { normalizeRepoPath } from "@repowise-dev/types/repos";+import type { MarginNote, SavingsDelta, SessionAction } from "./session";+import type { TrailAction } from "./trail";++/** A finished turn counts only for the main loop; a subagent's carries `agentId`. */+export function fromTurnComplete(e: { agentId?: string | undefined }): SessionAction | null {+ return e.agentId === undefined ? { type: "turnCompleted" } : null;+}++/** The tools whose file Lens follows. */+export const FILE_TOOLS: ReadonlySet<string> = new Set(["Read", "Edit", "Write"]);++/**+ * The repo-relative path a file tool works on, or null when it is not a file+ * tool or the file is outside the repo. Windows paths compare without case.+ */+export function fileTarget(e: { tool: string; file_path?: unknown }, repoRoot: string | null): string | null {+ if (!FILE_TOOLS.has(e.tool) || repoRoot === null || typeof e.file_path !== "string") return null;+ const windows = /^[A-Za-z]:[\\/]|^[\\/]{2}/.test(repoRoot);+ return relativeTo(e.file_path, repoRoot, windows);+}++/** The tools whose augment notices become margin notes. */+export const EDIT_TOOLS: ReadonlySet<string> = new Set(["Edit", "Write"]);++// The two edit-time notices `repowise-augment` writes (augment_cmd/decision_inject.py).+const STANDING = /^\[repowise\] .+? is governed by a standing decision: (.+?)(?: because .*)?\.$/;+const MINED = /^\[repowise\] .+? has a decision recorded in it, mined but not reviewed: (.+?)(?: because .*)?\.$/;+const FIXES = /^\[repowise\] .+? has been bug-fixed (\d+)x in the last 6 months, last (.+?)(?: \(bug magnet\))?(?:; mostly in (.+?))?\.$/;++/** Each "(confirmed across N sessions)" tail is the hook's; the title is what Lens shows. */+function stripConfirmed(line: string): string {+ return line.replace(/ \(confirmed across \d+ sessions\)\.$/, ".");+}++/**+ * The margin notes in what the settings hooks added for one tool call+ * (`classic.PostToolUse`'s `additionalContext`, one entry per hook). Only+ * the hook's own edit-time notices count; at most one of each kind.+ */+export function notesFromAugment(additionalContext: unknown): MarginNote[] {+ if (!Array.isArray(additionalContext)) return [];+ const notes: MarginNote[] = [];+ const lines = additionalContext.filter((c): c is string => typeof c === "string").flatMap((c) => c.split(/\r?\n/));+ for (const raw of lines) {+ const line = stripConfirmed(raw.trim());+ const standing = STANDING.exec(line);+ const decision = standing ?? MINED.exec(line);+ const fixes = FIXES.exec(line);+ if (decision !== null && !notes.some((n) => n.kind === "decision")) {+ notes.push({ kind: "decision", reviewed: standing !== null, title: decision[1]! });+ } else if (fixes !== null && !notes.some((n) => n.kind === "fixes")) {+ notes.push({ kind: "fixes", count: Number(fixes[1]), age: fixes[2]!, symbol: fixes[3] ?? null });+ }+ }+ return notes;+}++/**+ * The ledger totals Lens compares: the server's own figures, read as they+ * are. Dollars are the input side only, to match the input-token count.+ */+export function savingsTotals(s: Savings): SavingsDelta {+ return {+ tokens: s.saved_input_tokens,+ inferredTokens: Math.min(s.inferred_saved_input_tokens, s.saved_input_tokens),+ usd: s.priced_input_savings_usd,+ };+}++/**+ * Growth since the snapshot, or null when any figure went down: the ledger+ * only grows, so a drop means it was rebuilt and the snapshot no longer holds.+ */+export function savingsSince(now: SavingsDelta, base: SavingsDelta): SavingsDelta | null {+ const tokens = now.tokens - base.tokens;+ const inferredTokens = now.inferredTokens - base.inferredTokens;+ const usd = now.usd - base.usd;+ if (tokens < 0 || inferredTokens < 0 || usd < 0) return null;+ return { tokens, inferredTokens: Math.min(inferredTokens, tokens), usd };+}++// Where Claude looked, for the map.++/** The tools whose calls say where Claude looked. */+export const OBSERVED_TOOLS: ReadonlySet<string> = new Set(["Read", "Edit", "Write", "Grep", "Glob"]);++/** Lens's own MCP calls fire tool events too; they are not Claude's attention. */+const OWN_CALL_PREFIX = "toolu_plugin_";++export interface PathContext {+ /** The session's working directory, which relative tool paths resolve against. */+ cwd: string;+ isWindows: boolean;+}++/** `raw` resolved against the cwd, with forward slashes on Windows; case kept. */+export function absolutePath(raw: string, ctx: PathContext): string {+ const absolute = ctx.isWindows ? /^[A-Za-z]:[\\/]|^\\\\/.test(raw) : raw.startsWith("/");+ // Ceiling: `..` segments are kept as written; the tools Lens reads report resolved paths.+ const joined = absolute ? raw : `${ctx.cwd.replace(/[\\/]+$/, "")}/${raw.replace(/^\.[\\/]/, "")}`;+ return ctx.isWindows ? joined.replace(/\\/g, "/") : joined;+}++/** Absolute and normalized: forward slashes and, on Windows, lowercase. */+export function absoluteKey(raw: string, ctx: PathContext): string {+ return normalizeRepoPath(absolutePath(raw, ctx), ctx.isWindows);+}++/** `absolute` relative to `root` with its own case kept, or null outside it. */+export function relativeTo(absolute: string, root: string, isWindows: boolean): string | null {+ const rootKey = normalizeRepoPath(root, isWindows);+ const slashed = isWindows ? absolute.replace(/\\/g, "/") : absolute;+ if (!normalizeRepoPath(slashed, isWindows).startsWith(`${rootKey}/`)) return null;+ return slashed.slice(rootKey.length + 1);+}++/** What `next(e)` resolves to for a tool call, as recorded (test/fixtures/tool-calls.json). */+interface ToolOutcome {+ isError?: boolean;+ result?: { mode?: string; filenames?: unknown } | string;+}++function filenamesOf(out: ToolOutcome): string[] {+ const names = typeof out.result === "object" ? out.result.filenames : undefined;+ return Array.isArray(names) ? names.filter((v): v is string => typeof v === "string") : [];+}++/** A Grep that printed lines (`content`) names no files: it says nothing about where the hits are. */+function isContentGrep(tool: string, out: ToolOutcome): boolean {+ return tool === "Grep" && typeof out.result === "object" && out.result.mode === "content";+}++function searchAction(out: ToolOutcome, ctx: PathContext): TrailAction {+ return { type: "search", paths: filenamesOf(out).map((f) => absoluteKey(f, ctx)) };+}++function fileAction(e: { tool: string; [arg: string]: unknown }, ctx: PathContext): TrailAction | null {+ const raw = e["file_path"];+ if (typeof raw !== "string") return null;+ const path = absoluteKey(raw, ctx);+ return e.tool === "Read" ? { type: "read", path } : { type: "edit", path };+}++/**+ * What Claude's tool call says about where it looked, from the call and what+ * `next(e)` returned: a read, a search's hits, or an edit. Subagent calls+ * count (they are Claude's attention too); MCP and other tools do not, and+ * neither do Lens's own calls, a call that failed, or a content-mode Grep.+ */+export function fromToolCall(+ e: { tool: string; tool_use_id?: string | undefined; [arg: string]: unknown },+ outcome: unknown,+ ctx: PathContext,+): TrailAction | null {+ if (!OBSERVED_TOOLS.has(e.tool) || e.tool_use_id?.startsWith(OWN_CALL_PREFIX)) return null;+ const out = (outcome ?? {}) as ToolOutcome;+ if (out.isError === true || isContentGrep(e.tool, out)) return null;+ return e.tool === "Grep" || e.tool === "Glob" ? searchAction(out, ctx) : fileAction(e, ctx);+}++/**+ * The file an edit wrote, as the recap and the brief name it: repo-relative+ * inside the repo (case kept), else absolute; null without a path.+ */+export function touchedPath(+ e: { file_path?: unknown; [arg: string]: unknown },+ cwd: string | null,+ repoRoot: string | null,+): string | null {+ const raw = typeof e.file_path === "string" ? e.file_path : e["notebook_path"];+ if (typeof raw !== "string") return null;+ const base = cwd ?? repoRoot;+ if (base === null) return raw;+ const isWindows = /^[A-Za-z]:[\/]|^[\/]{2}/.test(base);+ const abs = absolutePath(raw, { cwd: base, isWindows });+ return (repoRoot === null ? null : relativeTo(abs, repoRoot, isWindows)) ?? abs;+}diff --git a/packages/claude-mod/src/model/review.ts b/packages/claude-mod/src/model/review.tsnew file mode 100644index 000000000..3cb684342--- /dev/null+++ b/packages/claude-mod/src/model/review.ts@@ -0,0 +1,110 @@+/**+ * The change review of the last turn: whether it edited files, and what+ * `get_change_risk` said about the working tree afterwards. Pure.+ */++import type { RiskReportArtifactData } from "@repowise-dev/types";++/** The `get_change_risk` result, as the shared chat types describe it. */+export type ChangeRisk = RiskReportArtifactData;++export type ReviewOutcome =+ | { phase: "none" }+ | { phase: "reviewing" }+ | { phase: "done"; risk: ChangeRisk }+ | { phase: "failed"; reason: "error" | "timeout"; message: string };++export interface ReviewState {+ /** Claude (or a subagent) edited a file since the main turn started. */+ edited: boolean;+ outcome: ReviewOutcome;+ /** The decision the augment hook said governs a file edited this turn, as it titled it. */+ decision: string | null;+}++export type ReviewAction =+ | { type: "turnStarted" }+ | { type: "fileEdited" }+ | { type: "reviewStarted" }+ | { type: "reviewed"; risk: ChangeRisk }+ | { type: "reviewFailed"; reason: "error" | "timeout"; message: string }+ | { type: "decisionNoted"; title: string };++export const initialReview: ReviewState = { edited: false, outcome: { phase: "none" }, decision: null };++export function reduceReview(state: ReviewState, action: ReviewAction): ReviewState {+ switch (action.type) {+ case "turnStarted":+ // A new turn retires the last review and drops one still in flight.+ return state.edited || state.outcome.phase !== "none" || state.decision !== null ? initialReview : state;+ case "fileEdited":+ return state.edited ? state : { ...state, edited: true };+ case "reviewStarted":+ return { ...state, outcome: { phase: "reviewing" } };+ case "reviewed":+ return { ...state, outcome: { phase: "done", risk: action.risk } };+ case "reviewFailed":+ return { ...state, outcome: { phase: "failed", reason: action.reason, message: action.message } };+ case "decisionNoted":+ return state.decision === action.title ? state : { ...state, decision: action.title };+ }+}++/** A diff with nothing in it: the server's own status, or a scope of 0 changed files (an edit reverted). */+export function emptyDiff(risk: ChangeRisk): boolean {+ return risk.status === "nothing_to_score" || risk.health_delta?.scope?.changed === 0;+}++/** A review with something to say: no server error and a non-empty diff. */+export function reviewable(risk: ChangeRisk): boolean {+ return risk.error === undefined && !emptyDiff(risk);+}++/** Every tool that writes a file (wider than the margin's Edit and Write: any change to the tree counts). */+const WRITE_TOOLS = new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);++/**+ * A tool call wrote a file: an edit tool, answered without a deny or an error.+ * Lens's own calls (`toolu_plugin_`) never count.+ */+export function isFileEdit(e: { tool?: unknown; tool_use_id?: unknown }, result: unknown): boolean {+ if (typeof e.tool !== "string" || !WRITE_TOOLS.has(e.tool)) return false;+ if (typeof e.tool_use_id === "string" && e.tool_use_id.startsWith("toolu_plugin_")) return false;+ if (typeof result !== "object" || result === null) return false;+ const r = result as { deny?: unknown; isError?: unknown };+ return r.deny === undefined && r.isError !== true;+}++/**+ * A finished main-loop turn that edited files gets a review; an interrupted or+ * failed one may have stopped mid-change, and a subagent's turn is not the+ * user's.+ */+export function shouldReview(+ e: { agentId?: string | undefined; isAborted?: boolean | undefined; reason?: string | undefined },+ edits: number,+): boolean {+ if (e.agentId !== undefined || edits === 0) return false;+ return e.isAborted !== true && e.reason !== "aborted" && e.reason !== "error";+}++/** A failure worth one more try: anything but a timeout (a refused call, say). */+export function isRetryable(action: { type: string; reason?: string }): boolean {+ return action.type === "reviewFailed" && action.reason !== "timeout";+}++/** The tests the review names, with how it knows them; null when it names none. */+export function testsToRun(+ risk: ChangeRisk,+): { tests: string[]; total: number; truncated: boolean; files: boolean; measured: boolean } | null {+ const block = risk.impacted_tests;+ const tests = block?.tests_to_run ?? [];+ if (block === undefined || tests.length === 0) return null;+ return {+ tests,+ total: block.total ?? tests.length,+ truncated: block.truncated === true,+ files: block.tests_to_run_kind === "test_file",+ measured: block.basis === "measured",+ };+}diff --git a/packages/claude-mod/src/model/session.ts b/packages/claude-mod/src/model/session.tsnew file mode 100644index 000000000..f4310eecf--- /dev/null+++ b/packages/claude-mod/src/model/session.ts@@ -0,0 +1,217 @@+/**+ * Session state and its reducer. Pure: no I/O, no clock, no `$`.+ */++import type { AskReply, AskState, AskTool, PaneTab } from "./ask";+import { mayHaveUsedModel } from "./ask";+import { initialReview, reduceReview, reviewable, type ChangeRisk, type ReviewAction, type ReviewState } from "./review";++/** `no-repo`: not inside a git work tree, so there is nothing to index and Lens stays quiet. */+export type Mode = "full" | "lite" | "no-index" | "no-cli" | "no-repo";++/** Why a lite session has no map, when it is not simply "no server". */+export type LiteReason = "no-server" | "auth" | "unlisted";++/** One setup hint; each shows at most once per session. */+export type HintKind = "no-server" | "auth" | "unlisted" | "no-index" | "no-cli";++export interface IndexFreshness {+ /** Files changed between the indexed commit and HEAD; null when git could not count them. */+ changedFiles: number | null;+}++/** What the spinner shows for a file. null fields are unknown, not zero. */+export interface FileContext {+ /** Files that import this one or call into it (the server's file-level rollup). */+ callerFiles: number | null;+ contributors: number | null;+}++/** A Read, Edit or Write running on a file inside the indexed repo. */+export interface RunningTool {+ id: string;+ /** Repo-relative, forward slashes. */+ file: string;+}++/**+ * One exception the augment hook flagged on an edited file, as it worded it.+ * Lens reads these; the thresholds and caps are the hook's own.+ */+export type MarginNote =+ | { kind: "decision"; reviewed: boolean; title: string }+ | { kind: "fixes"; count: number; age: string; symbol: string | null };++/**+ * What the savings ledger gained since the session's first snapshot. It+ * covers every agent on this repo: savings events carry a per-connection id,+ * not Claude's session id.+ */+export interface SavingsDelta {+ /** Input tokens saved, measured and inferred together. */+ tokens: number;+ /** The inferred part of `tokens`. */+ inferredTokens: number;+ /** Priced input savings in US dollars; unpriced tokens add nothing here. */+ usd: number;+}++export interface SessionState {+ /** null until the first discovery settles. */+ mode: Mode | null;+ /** Shown while the index is behind HEAD, in full and lite mode only. */+ freshness: IndexFreshness | null;+ /** The hint on screen now. */+ hint: HintKind | null;+ /** Every hint already shown this session, so none comes back. */+ hintsShown: readonly HintKind[];+ /** The indexed repo's root, once discovered. */+ repoRoot: string | null;+ /** The file tool running now, if any. */+ running: RunningTool | null;+ /** File context fetched this session, by repo-relative path. */+ contexts: Readonly<Record<string, FileContext>>;+ /** Margin notes by the Edit or Write call they belong to. */+ notes: Readonly<Record<string, readonly MarginNote[]>>;+ /** Shown only once something was saved; full mode only. */+ savings: SavingsDelta | null;+ /** The last turn's change review. */+ review: ReviewState;+ /** The latest review that came back this session, kept past the turn for the recap and the brief. */+ lastReview: ChangeRisk | null;+ /** Files Claude (or a subagent) wrote this session, repo-relative when inside the repo, each once. */+ touched: readonly string[];+ /** The pane's tab, and the text the Ask field starts with. */+ pane: { tab: PaneTab; draft: string };+ ask: AskState;+ /** get_answer asks that may have used the repo's configured model: counted at the start, dropped when the reply says no provider. */+ modelAsks: number;+ /** The context was compacted and the brief not yet sent or passed over. */+ compacted: boolean;+}++export type SessionAction =+ | { type: "discovered"; mode: Mode; liteReason?: LiteReason; freshness: IndexFreshness | null; repoRoot?: string | null }+ | { type: "turnCompleted" }+ | { type: "toolStarted"; tool: RunningTool }+ | { type: "toolEnded"; id: string }+ | { type: "contextLoaded"; file: string; context: FileContext }+ | { type: "notesFor"; id: string; notes: readonly MarginNote[] }+ | { type: "savings"; delta: SavingsDelta }+ | { type: "touched"; path: string }+ | { type: "tab"; tab: PaneTab; draft?: string }+ | { type: "asked"; question: string; tool: AskTool }+ | { type: "answered"; question: string; answer: AskReply }+ | { type: "askFailed"; question: string; tool: AskTool; message: string }+ | { type: "askBusy" }+ | { type: "compacted" }+ | { type: "briefDone" }+ | ReviewAction;++export const initialSession: SessionState = {+ mode: null,+ freshness: null,+ hint: null,+ hintsShown: [],+ repoRoot: null,+ running: null,+ contexts: {},+ notes: {},+ savings: null,+ review: initialReview,+ lastReview: null,+ touched: [],+ pane: { tab: "map", draft: "" },+ ask: { phase: "idle" },+ modelAsks: 0,+ compacted: false,+};++export function hintFor(mode: Mode, liteReason: LiteReason | undefined): HintKind | null {+ if (mode === "full" || mode === "no-repo") return null;+ if (mode === "lite") return liteReason ?? "no-server";+ return mode;+}++export function reduce(state: SessionState, action: SessionAction): SessionState {+ switch (action.type) {+ case "discovered": {+ const kind = hintFor(action.mode, action.liteReason);+ const indexed = action.mode === "full" || action.mode === "lite";+ const freshness = indexed ? action.freshness : null;+ const repoRoot = indexed ? (action.repoRoot ?? null) : null;+ // Savings come from the local server: the row leaves with it.+ const savings = action.mode === "full" ? state.savings : null;+ if (kind !== null && !state.hintsShown.includes(kind)) {+ const hintsShown = [...state.hintsShown, kind];+ return { ...state, mode: action.mode, freshness, repoRoot, savings, hint: kind, hintsShown };+ }+ // A hint for a state that no longer holds (the server came up) leaves at once.+ const hint = state.hint === kind ? state.hint : null;+ return { ...state, mode: action.mode, freshness, repoRoot, savings, hint };+ }+ case "turnCompleted":+ // A hint stays up through the first turn that ends while it shows, then retires.+ return state.hint === null ? state : { ...state, hint: null };+ case "toolStarted":+ return { ...state, running: action.tool };+ case "toolEnded":+ // Calls overlap: only the one shown clears the slot.+ return state.running?.id === action.id ? { ...state, running: null } : state;+ case "contextLoaded":+ return { ...state, contexts: { ...state.contexts, [action.file]: action.context } };+ case "notesFor": {+ if (action.notes.length === 0) return state;+ const notes = { ...state.notes, [action.id]: action.notes };+ const decision = action.notes.find((n) => n.kind === "decision");+ const review = decision === undefined ? state.review : reduceReview(state.review, { type: "decisionNoted", title: decision.title });+ return { ...state, notes, review };+ }+ case "savings":+ return { ...state, savings: action.delta.tokens > 0 ? action.delta : null };+ case "touched":+ return state.touched.includes(action.path) ? state : { ...state, touched: [...state.touched, action.path] };+ case "tab":+ return { ...state, pane: { tab: action.tab, draft: action.draft ?? state.pane.draft } };+ case "asked": {+ // Counted when it starts (it may fail or time out after the provider saw it); the Why draft is spent.+ const modelAsks = state.modelAsks + (action.tool === "get_answer" ? 1 : 0);+ const ask: AskState = { phase: "asking", question: action.question, tool: action.tool, busy: false };+ return { ...state, modelAsks, ask, pane: { ...state.pane, draft: "" } };+ }+ case "askBusy":+ return state.ask.phase === "asking" && !state.ask.busy ? { ...state, ask: { ...state.ask, busy: true } } : state;+ case "answered": {+ // A reply that says it had no provider is known to have used no model: no longer counted.+ const modelAsks = Math.max(0, state.modelAsks - (action.answer.tool === "get_answer" && !mayHaveUsedModel(action.answer) ? 1 : 0));+ return { ...state, modelAsks, ask: { phase: "answered", question: action.question, answer: action.answer } };+ }+ case "askFailed":+ return { ...state, ask: { phase: "failed", question: action.question, tool: action.tool, message: action.message } };+ case "compacted":+ return state.compacted ? state : { ...state, compacted: true };+ case "briefDone":+ return state.compacted ? { ...state, compacted: false } : state;+ default:+ return reduceTurn(state, action);+ }+}++/** The review's actions; a new turn also retires the brief offer, and a landed review is kept for the recap. */+function reduceTurn(state: SessionState, action: ReviewAction): SessionState {+ const review = reduceReview(state.review, action);+ const compacted = action.type === "turnStarted" ? false : state.compacted;+ // Only a review with something to say is kept: an error or an empty diff leaves the last one.+ const lastReview = action.type === "reviewed" && reviewable(action.risk) ? action.risk : state.lastReview;+ if (review === state.review && compacted === state.compacted && lastReview === state.lastReview) return state;+ return { ...state, review, compacted, lastReview };+}++/** Each decision the augment hook surfaced on an edit this session, once, in the order seen. */+export function surfacedDecisions(state: SessionState): Array<{ title: string; reviewed: boolean }> {+ const seen = new Map<string, boolean>();+ for (const notes of Object.values(state.notes)) {+ for (const n of notes) if (n.kind === "decision" && !seen.has(n.title)) seen.set(n.title, n.reviewed);+ }+ return [...seen].map(([title, reviewed]) => ({ title, reviewed }));+}diff --git a/packages/claude-mod/src/model/squeeze.ts b/packages/claude-mod/src/model/squeeze.tsnew file mode 100644index 000000000..f5596716e--- /dev/null+++ b/packages/claude-mod/src/model/squeeze.ts@@ -0,0 +1,112 @@+/**+ * What a Bash result that `repowise distill` shortened says about itself:+ * read from the omission marker distill writes at the end of its output, and+ * from the test runner's own summary in what was kept. Pure; nothing fetched.+ */++/** The one marker `core/distill` renders (markers.py `_MARKER_TEMPLATE`). */+const MARKER = /^\[repowise#([0-9a-f]{12}): (\d+) lines omitted \(~(\d+) tokens\); restore: repowise expand \1\]$/;++export interface Squeeze {+ /** Lines the command printed. */+ originalLines: number;+ /** Lines Claude received, the marker aside. */+ keptLines: number;+ /** Tokens distill held back, as its marker estimates them. */+ omittedTokens: number;+ /** Failures and errors as the test runner counted them in what was kept; zero when it reported none. */+ failed: number;+ errors: number;+ /** Omission refs, in order; the first is the one to expand. */+ refs: string[];+}++interface Marker {+ ref: string;+ lines: number;+ tokens: number;+}++function markerOf(line: string): Marker | null {+ const m = MARKER.exec(line.trim());+ return m === null ? null : { ref: m[1]!, lines: Number(m[2]), tokens: Number(m[3]) };+}++const isBlank = (line: string) => line.trim() === "";++/**+ * Splits off the markers distill wrote: the trailing run of marker lines+ * (blank lines between them allowed). A marker anywhere else is text the+ * command printed, and draws nothing.+ */+function trailingMarkers(lines: string[]): { kept: string[]; markers: Marker[] } {+ let end = lines.length;+ const markers: Marker[] = [];+ while (end > 0) {+ const line = lines[end - 1]!;+ const marker = isBlank(line) ? null : markerOf(line);+ if (!isBlank(line) && marker === null) break;+ if (marker !== null) markers.unshift(marker);+ end--;+ }+ return { kept: lines.slice(0, end), markers };+}++// Runner summaries, in their own words.+const PYTEST_SUMMARY = /^=+ (.*\b(?:passed|failed|error|errors|skipped)\b.*) =+$/;+const PYTEST_FAILED = /\b(\d+) failed\b/;+const PYTEST_ERRORS = /\b(\d+) errors?\b/;+const JEST_SUMMARY = /^\s*Tests?:\s.*?\b(\d+) failed\b/;+const CARGO_SUMMARY = /^test result: \w+\. \d+ passed; (\d+) failed;/;+/** Top-level only: an indented `--- FAIL:` is a subtest of one already counted. */+const GO_FAIL = /^--- FAIL:/;++function pytestCounts(line: string): { failed: number; errors: number } | null {+ const m = PYTEST_SUMMARY.exec(line);+ if (m === null) return null;+ return { failed: Number(PYTEST_FAILED.exec(m[1]!)?.[1] ?? 0), errors: Number(PYTEST_ERRORS.exec(m[1]!)?.[1] ?? 0) };+}++/** Failures the runner itself reported in the kept text. */+export function runnerFailures(kept: string[]): { failed: number; errors: number } {+ let cargo = 0;+ let go = 0;+ for (const line of kept) {+ const pytest = pytestCounts(line);+ if (pytest !== null) return pytest;+ const jest = JEST_SUMMARY.exec(line);+ if (jest !== null) return { failed: Number(jest[1]), errors: 0 };+ cargo += Number(CARGO_SUMMARY.exec(line)?.[1] ?? 0);+ if (GO_FAIL.test(line)) go++;+ }+ return { failed: cargo + go, errors: 0 };+}++/** The squeeze a distilled output carries, or null when distill did not write a complete marker at its end. */+export function parseSqueeze(output: string): Squeeze | null {+ const { kept, markers } = trailingMarkers(output.split(/\r?\n/));+ if (markers.length === 0) return null;+ const refs = new Set<string>();+ let lines = 0;+ let tokens = 0;+ for (const m of markers) {+ if (refs.has(m.ref)) continue;+ refs.add(m.ref);+ lines += m.lines;+ tokens += m.tokens;+ }+ return {+ originalLines: kept.length + lines,+ keptLines: kept.length,+ omittedTokens: tokens,+ ...runnerFailures(kept),+ refs: [...refs],+ };+}++/** What a Bash result carries: `{stdout}` once it ran, or the text the model read when it errored. */+export function bashText(output: unknown): string | null {+ if (typeof output === "string") return output;+ const stdout = (output as { stdout?: unknown } | null)?.stdout;+ return typeof stdout === "string" ? stdout : null;+}diff --git a/packages/claude-mod/src/model/trail.ts b/packages/claude-mod/src/model/trail.tsnew file mode 100644index 000000000..d170550c3--- /dev/null+++ b/packages/claude-mod/src/model/trail.ts@@ -0,0 +1,76 @@+/**+ * Where Claude's attention went this session, and what its last edit reaches.+ * Pure. Paths are kept absolute and normalized (`normalizeRepoPath`), so+ * nothing is lost before discovery has found the repo root; the map view maps+ * them onto its cells.+ */++/**+ * Most recent reads kept for the trail. Ceiling: a session reading more keeps+ * only the newest (the legend then says `200+`); raise it if the trail ever+ * needs the whole session.+ */+const MAX_READS = 200;++export type Callers =+ | { status: "loading" }+ | { status: "ready"; paths: readonly string[] }+ | { status: "failed" };++export interface TrailState {+ /** Files read or edited, oldest first, each once (a re-read keeps its first place). */+ reads: readonly string[];+ /** True once older reads were dropped to stay under the cap. */+ readsCapped: boolean;+ /** Files the latest file-listing Grep or Glob returned. */+ hits: readonly string[];+ /** Bumped per search, so a search that returns the same files flashes again. */+ searches: number;+ /** The latest Edit or Write target. */+ edit: string | null;+ /** Bumped per edit; a callers answer for an older edit is dropped. */+ edits: number;+ /** Files that import `edit`, repo-relative as the server names them. */+ callers: Callers | null;+}++export type TrailAction =+ | { type: "read"; path: string }+ | { type: "search"; paths: readonly string[] }+ | { type: "edit"; path: string }+ | { type: "callers"; edits: number; callers: Callers };++export const initialTrail: TrailState = {+ reads: [],+ readsCapped: false,+ hits: [],+ searches: 0,+ edit: null,+ edits: 0,+ callers: null,+};++function withRead(state: TrailState, path: string): TrailState {+ if (state.reads.includes(path)) return state;+ const reads = [...state.reads, path];+ if (reads.length <= MAX_READS) return { ...state, reads };+ return { ...state, reads: reads.slice(reads.length - MAX_READS), readsCapped: true };+}++export function reduceTrail(state: TrailState, action: TrailAction): TrailState {+ switch (action.type) {+ case "read":+ return withRead(state, action.path);+ case "search":+ return { ...state, hits: action.paths, searches: state.searches + 1 };+ case "edit":+ return {+ ...withRead(state, action.path),+ edit: action.path,+ edits: state.edits + 1,+ callers: { status: "loading" },+ };+ case "callers":+ return action.edits === state.edits ? { ...state, callers: action.callers } : state;+ }+}diff --git a/packages/claude-mod/src/register.ts b/packages/claude-mod/src/register.tsnew file mode 100644index 000000000..be898c8a1--- /dev/null+++ b/packages/claude-mod/src/register.ts@@ -0,0 +1,765 @@+/**+ * The mod's entry, and the only file that touches `$`. Each hook builds a Host+ * from its own `$`, feeds events to the model, and redraws. Lens only+ * observes: every hook passes its event on unchanged.+ */++import { getSavings } from "@repowise-dev/api-client/costs";+import { discover, isWindowsPath, readFreshness, type Discovery } from "./data/discovery";+import { callTool, fetchFileContext, isOwnLensCall, mcpReady, resetMcp, warmMcp } from "./data/mcp";+import { withTimeout } from "./data/transport";+import { fit } from "./format";+import type { Host } from "./host";+import { LensMap, type MapIO, type MapRepo } from "./map-controller";+import type {+ CheckNext,+ CommandRunEvent,+ ModApi,+ On,+ PaneRenderEvent,+ PluginOptions,+ PostCompactEvent,+ PostToolUseEvent,+ RenderEvent,+ SessionStartEvent,+ SpinnerEvent,+ ToolCallEvent,+ ToolCheckEvent,+ ToolResultEvent,+ ToolUseEvent,+ TurnCompleteEvent,+ UiInputEvent,+} from "./mod-api";+import {+ EDIT_TOOLS,+ OBSERVED_TOOLS,+ absolutePath,+ fileTarget,+ fromToolCall,+ fromTurnComplete,+ notesFromAugment,+ savingsSince,+ savingsTotals,+ touchedPath,+} from "./model/events";+import { askReply, askRoute, lensCommand, whyDraft, type PaneTab } from "./model/ask";+import { hintFor, initialSession, reduce, type SavingsDelta, type SessionAction, type SessionState } from "./model/session";+import { bandView } from "./views/band";+import { materialize, type ElementTable, type Node } from "./views/elements";+import { marginView } from "./views/margin";+import { isFileEdit, isRetryable, shouldReview, type ChangeRisk } from "./model/review";+import { BRIEF_PRESS, briefText } from "./views/brief";+import { HINTS, MAP_COPY, PANE_COPY, REVIEW_TIMEOUT_S } from "./views/copy";+import { MAP_KEY } from "./views/mapPane";+import { ASK_KEY, TABS, TAB_PRESS, TAB_ROWS, askView, paneView, recapView } from "./views/pane";+import { PRESS, directiveRows, reviewText, runTestsText, withCard } from "./views/review";+import { spinnerSuffix } from "./views/spinner";+import { bashText, parseSqueeze, type Squeeze } from "./model/squeeze";+import { squeezeView } from "./views/squeeze";++const PROCESS_TIMEOUT_MS = 5_000;+/** The savings route scans transcripts: 0.24 s on a quiet store, 5-12 s on a busy one. */+const SAVINGS_TIMEOUT_MS = 30_000;+const SAVINGS_COOLDOWN_MS = 60_000;+/** The server's key in the plugin's .mcp.json. */+const MCP_SERVER_KEY = "repowise";+const PANE_ID = "lens";+/** Rows an inline pane asks for: the tabs, the tallest inline map (20) and a legend wrapped once. */+const PANE_ROWS = 29;+/** get_why took 22 s cold on Django, get_answer about 4 s. */+const ASK_TIMEOUT_MS = 30_000;++let state: SessionState = initialSession;+/** Bumped per session, so a refresh started in an earlier one never lands in this one. */+let generation = 0;+let running = false;+/** A refresh was asked for while one ran: run once more after it. */+let dirty = false;+let latest: Bound | null = null;+/**+ * Once the server has connected the CLI is known to exist; a later connect+ * can fail while the session shuts its servers down, which is not "no CLI".+ */+let mcpConnected = false;+/** The ledger at this session's first read, and whose; the band shows growth past it. */+let savingsBase: { repoId: string; totals: SavingsDelta } | null = null;+let savingsBusy = false;+let savingsAskedAt = Number.NEGATIVE_INFINITY;+/** Each Bash result's squeeze, kept once found: a row redraws on every scroll. */+const squeezes = new Map<string, Squeeze>();+/** Files whose context is being fetched, or that the index does not know. */+const contextAsked = new Set<string>();+/** The `lens_review` toggle, fixed for one activation. */+let reviewOn = true;+/** Bumped when a main turn starts, so a review still in flight for the last one is dropped. */+let reviewGeneration = 0;+/** Edits that landed since the main turn started. */+let editsThisTurn = 0;++/** A review started during this turn: how many of its edits it covers, and its outcome. */+interface StartedReview {+ gen: number;+ covers: number;+ settled: boolean;+ /** Never rejects: a failure is a `reviewFailed` action. */+ outcome: Promise<SessionAction>;+}+let started: StartedReview | null = null;+/** The `lens_pane_autoopen` toggle, fixed for one activation. */+let autoOpenOn = false;+/** The last discovery, for the map pane's notice and its repo. */+let discovery: Discovery | null = null;+/** The session's cwd, from its start event, so observing a tool call waits on nothing. */+let cwd: string | null = null;+let map = new LensMap(false);++/** Cut so an error stays one line under the answer. */+const ERROR_CELLS = 160;++/** What a background refresh needs from a hook's `$`, as closures (the engine forbids keeping `$` itself). */+interface Bound extends MapIO {+ host: Host;+}++// Built from the calling hook's own `$`. REST through `$.http` from a later+// continuation of these closures works; an MCP call works only when it starts+// while a Lens hook is live (one started later is refused), so MCP calls are+// started synchronously from inside a hook (see data/mcp.ts). A late+// `$.ui.blit` is not refused either (checked headless from a timer).+function bind($: ModApi): Bound {+ const host: Host = {+ session: { cwd: () => $.session.cwd() },+ fs: {+ read: (path) => $.fs.read(path),+ exists: (path) => $.fs.exists(path),+ },+ process: {+ run: (argv, cwd) => $.process.run(argv, { cwd, timeoutMs: PROCESS_TIMEOUT_MS }),+ },+ http: (url, init) => {+ const request: { method?: string; headers?: Record<string, string>; body?: string } = {};+ if (init.method !== undefined) request.method = init.method;+ if (init.headers !== undefined) request.headers = init.headers;+ if (init.body !== undefined) request.body = init.body;+ return $.http.fetch(url, request);+ },+ mcp: {+ connect: async () => (mcpConnected ||= (await $.mcp.connect(MCP_SERVER_KEY)).isConnected),+ server: async () => {+ const r = await $.mcp.connect(MCP_SERVER_KEY);+ return r.isConnected && typeof r.server === "string" ? r.server : null;+ },+ call: (server, tool, args) => $.mcp.call(server, tool, args),+ },+ };+ return {+ host,+ redraw: () => $.ui.invalidate("ui.render"),+ debug: (message) => $.ui.log(`lens: ${message}`, { to: "debug" }),+ blit: (cells, columns, rows) => $.ui.blit({ requestId: PANE_ID, key: MAP_KEY, cells, columns, rows }),+ // Focus only when asked (/lens, a press): an automatic open leaves the prompt the keyboard.+ openPane: (focus) =>+ $.ui.open(+ focus+ ? { id: PANE_ID, title: MAP_COPY.title, rows: PANE_ROWS, focus: true }+ : { id: PANE_ID, title: MAP_COPY.title, rows: PANE_ROWS },+ ),+ closePane: () => $.ui.close({ id: PANE_ID }),+ };+}++function mapRepo(d: Discovery): MapRepo | null {+ if (d.mode !== "full" || d.repo === undefined || d.repoRoot === null) return null;+ return { id: d.repo.id, root: d.repoRoot, updatedAt: d.repo.updatedAt, caseInsensitive: isWindowsPath(d.repoRoot) };+}++function dispatch(b: Bound, action: SessionAction): void {+ const next = reduce(state, action);+ if (next === state) return;+ state = next;+ b.redraw();+}++async function refreshOnce(b: Bound, gen: number): Promise<void> {+ const h = b.host;+ const found = await discover(h);+ const indexed = found.mode === "full" || found.mode === "lite";+ const freshness = indexed && found.repoRoot !== null ? await readFreshness(h, found.repoRoot) : null;+ if (gen !== generation) return;+ if (indexed) warmMcp(h);+ discovery = found;+ const action: SessionAction = { type: "discovered", mode: found.mode, freshness, repoRoot: found.repoRoot };+ if (found.liteReason !== undefined) action.liteReason = found.liteReason;+ dispatch(b, action);+ if (found.repo !== undefined) refreshSavings(b, found.repo.id, gen);+ map.setRepo(b, mapRepo(found));+}++/**+ * Reads the savings ledger in the background, never awaited by a hook or a+ * render. The first read of a session is the baseline; later reads, at most+ * once a minute, become the band's delta.+ * Ceiling: the baseline lands a moment after the session starts, so savings+ * made before that first read are not counted.+ */+function refreshSavings(b: Bound, repoId: string, gen: number): void {+ const now = Date.now();+ if (savingsBusy || now - savingsAskedAt < SAVINGS_COOLDOWN_MS) return;+ savingsBusy = true;+ savingsAskedAt = now;+ withTimeout(getSavings(repoId), SAVINGS_TIMEOUT_MS, "savings")+ .then((s) => {+ if (gen !== generation) return;+ const totals = savingsTotals(s);+ const delta = savingsBase?.repoId === repoId ? savingsSince(totals, savingsBase.totals) : null;+ if (delta !== null) {+ dispatch(b, { type: "savings", delta });+ return;+ }+ // First read, another repo, or a ledger that shrank: start counting again from here.+ if (savingsBase !== null) dispatch(b, { type: "savings", delta: { tokens: 0, inferredTokens: 0, usd: 0 } });+ savingsBase = { repoId, totals };+ })+ .catch((err: unknown) => b.debug(`savings failed: ${String(err)}`))+ .finally(() => (savingsBusy = false));+}++/** Re-reads mode and freshness in the background, one run at a time. */+function refresh(b: Bound): void {+ latest = b;+ if (running) {+ dirty = true;+ return;+ }+ running = true;+ dirty = false;+ refreshOnce(b, generation)+ // Keep the last good state; the next turn tries again.+ .catch((err: unknown) => b.debug(`refresh failed: ${String(err)}`))+ .finally(() => {+ running = false;+ if (dirty && latest !== null) refresh(latest);+ });+}++async function onSessionStart(+ $: ModApi,+ e: SessionStartEvent,+ next: (e: SessionStartEvent) => Promise<unknown>,+): Promise<unknown> {+ const b = bind($);+ try {+ generation++;+ cwd = typeof e.cwd === "string" ? e.cwd : null;+ map.dispose();+ map = new LensMap(autoOpenOn);+ state = initialSession;+ reviewGeneration++;+ editsThisTurn = 0;+ started = null;+ contextAsked.clear();+ squeezes.clear();+ savingsBase = null;+ savingsAskedAt = Number.NEGATIVE_INFINITY;+ resetMcp();+ warmMcp(b.host);+ refresh(b);+ await $.command.register({ name: "lens", description: PANE_COPY.command, argumentHint: PANE_COPY.argumentHint, immediate: true });+ map.setReducedMotion((await $.settings.read())["prefersReducedMotion"] === true);+ } catch (err) {+ // Lens stays quiet; the session is unaffected.+ b.debug(`session.start failed: ${String(err)}`);+ }+ return next(e);+}++// Also the first refresh when the module loaded after the session started.+async function onTurnComplete(+ $: ModApi,+ e: TurnCompleteEvent,+ next: (e: TurnCompleteEvent) => Promise<unknown>,+): Promise<unknown> {+ const b = bind($);+ noteTurnEnd(b, e);+ const result = await next(e);+ return reviewOn && shouldReview(e, editsThisTurn) ? withReview(b, e, result) : result;+}++function noteTurnEnd(b: Bound, e: TurnCompleteEvent): void {+ try {+ const action = fromTurnComplete(e);+ if (action === null) return;+ map.turnEnded();+ dispatch(b, action);+ refresh(b);+ } catch (err) {+ b.debug(`turn.complete failed: ${String(err)}`);+ }+}++/** The turn's result with the review card beneath the answer, or as it was. */+async function withReview(b: Bound, e: TurnCompleteEvent, result: unknown): Promise<unknown> {+ try {+ const card = await finishReview(b);+ return card === null ? result : withCard(result, e.answer ?? "", card);+ } catch (err) {+ b.debug(`change review failed: ${String(err)}`);+ return result;+ }+}++// callTool starts `$.mcp.call` synchronously (or rejects at once when the+// server name is not resolved yet), so the call starts inside the caller's hook.+async function fetchReview(b: Bound): Promise<SessionAction> {+ try {+ const risk = await callTool<ChangeRisk>(b.host, "get_change_risk", {}, { timeoutMs: REVIEW_TIMEOUT_S * 1000 });+ return { type: "reviewed", risk };+ } catch (err) {+ b.debug(`change review failed: ${String(err)}`);+ const message = fit((err instanceof Error ? err.message : String(err)).split("\n")[0] ?? "", ERROR_CELLS);+ return { type: "reviewFailed", reason: err instanceof Error && err.name === "TimeoutError" ? "timeout" : "error", message };+ }+}++/**+ * Starts a review of the working tree, not awaited. Only ever called while a+ * Lens hook is live (an edit's tool.call, or turn.complete), which is when the+ * engine approves the call.+ */+function startReview(b: Bound): StartedReview {+ const review: StartedReview = { gen: reviewGeneration, covers: editsThisTurn, settled: false, outcome: fetchReview(b) };+ void review.outcome.then(() => {+ review.settled = true;+ });+ started = review;+ return review;+}++/** After an edit lands: start a review, not awaited, unless one is already in flight. */+function reviewAfterEdit(b: Bound): void {+ editsThisTurn++;+ dispatch(b, { type: "fileEdited" });+ if (started !== null && started.gen === reviewGeneration && !started.settled) return;+ startReview(b);+}++/** The review started this turn, when it covers every edit so far. */+function coveringReview(): StartedReview | null {+ const s = started;+ return s !== null && s.gen === reviewGeneration && s.covers === editsThisTurn ? s : null;+}++/**+ * A review started at an edit can fail where one started here would not (the+ * server name was not resolved yet): that one is tried once more, awaited.+ */+async function outcomeOf(b: Bound, review: StartedReview, reused: boolean): Promise<SessionAction> {+ const action = await review.outcome;+ return reused && isRetryable(action) ? startReview(b).outcome : action;+}++/**+ * At the end of the turn: the started review when it covers every edit of the+ * turn (usually already landed), else one more. Null when a new turn started+ * meanwhile.+ */+async function finishReview(b: Bound): Promise<string | null> {+ const gen = reviewGeneration;+ const reused = coveringReview();+ const review = reused ?? startReview(b);+ if (!review.settled) dispatch(b, { type: "reviewStarted" });+ const action = await outcomeOf(b, review, reused !== null);+ if (gen !== reviewGeneration) return null;+ dispatch(b, action);+ return reviewText(state.review.outcome);+}++async function onTurnStart($: ModApi, e: unknown, next: (e: unknown) => Promise<unknown>): Promise<unknown> {+ try {+ // With reviews off the review state is never touched; a new turn only retires the brief offer.+ if (reviewOn) {+ reviewGeneration++;+ editsThisTurn = 0;+ started = null;+ }+ dispatch(bind($), reviewOn ? { type: "turnStarted" } : { type: "briefDone" });+ } catch (err) {+ bind($).debug(`turn.start failed: ${String(err)}`);+ }+ return next(e);+}++/** `Run tests`: a visible prompt naming the tests; nothing reaches Claude without this press. */+// A press runs after the render hook that drew the button returned, with+// that hook's `$`; the docs' own Button examples call `$` from onPress.+function pressRunTests($: ModApi): void {+ try {+ const prompt = runTestsText(state.review.outcome);+ if (prompt === null) return;+ $.prompt.submit({ text: prompt }).catch((err: unknown) => bind($).debug(`run tests failed: ${String(err)}`));+ } catch (err) {+ bind($).debug(`run tests failed: ${String(err)}`);+ }+}++/** `Why`: the pane's Ask tab, its field holding the decision that governs the edit; nothing is asked until Enter. */+function pressWhy($: ModApi): void {+ const b = bind($);+ try {+ const decision = state.review.decision;+ if (decision === null) return;+ dispatch(b, { type: "tab", tab: "ask", draft: whyDraft(decision) });+ map.request(b).catch((err: unknown) => b.debug(`why failed: ${String(err)}`));+ } catch (err) {+ b.debug(`why failed: ${String(err)}`);+ }+}++/** `Brief Claude`: the session brief as a visible prompt; the offer then retires. */+function pressBrief($: ModApi): void {+ const b = bind($);+ try {+ const brief = briefText(state);+ dispatch(b, { type: "briefDone" });+ if (brief === null) return;+ $.prompt.submit({ text: brief }).catch((err: unknown) => b.debug(`brief failed: ${String(err)}`));+ } catch (err) {+ b.debug(`brief failed: ${String(err)}`);+ }+}++// Only offers the brief: the compaction and its summary pass on untouched.+async function onPostCompact(+ $: ModApi,+ e: PostCompactEvent,+ next: (e: PostCompactEvent) => Promise<unknown>,+): Promise<unknown> {+ try {+ dispatch(bind($), { type: "compacted" });+ } catch (err) {+ bind($).debug(`PostCompact failed: ${String(err)}`);+ }+ return next(e);+}++/**+ * Asks the index, one question at a time. Only called from a live hook (the+ * Ask field's `ui.input`, or `/lens ask`): `callTool` starts the call at+ * once, which is when the engine approves Lens's own lookup.+ */+function startAsk(b: Bound, question: string): void {+ const q = question.trim();+ if (q === "") return;+ // One question at a time; the tab says this one was not asked.+ if (state.ask.phase === "asking") return dispatch(b, { type: "askBusy" });+ const { tool, args } = askRoute(q);+ dispatch(b, { type: "asked", question: q, tool });+ const gen = generation;+ callTool<unknown>(b.host, tool, args, { timeoutMs: ASK_TIMEOUT_MS })+ .then((reply) => {+ if (gen === generation) dispatch(b, { type: "answered", question: q, answer: askReply(tool, reply) });+ })+ .catch((err: unknown) => {+ b.debug(`ask failed: ${String(err)}`);+ const message = fit((err instanceof Error ? err.message : String(err)).split("\n")[0] ?? "", ERROR_CELLS);+ if (gen === generation) dispatch(b, { type: "askFailed", question: q, tool, message });+ });+}++// The Ask field's Enter. The lookup starts here, in Lens's own hook, so the+// engine approves it; the field's own closure does nothing.+async function onAskInput($: ModApi, e: UiInputEvent, next: (e: UiInputEvent) => Promise<unknown>): Promise<unknown> {+ try {+ if (e.kind === "submit" && e.element === ASK_KEY) startAsk(bind($), e.value);+ } catch (err) {+ bind($).debug(`ask failed: ${String(err)}`);+ }+ return next(e);+}++/** `Details`: the review's full directive in the transcript, one row per line, for the user only. */+function pressDetails($: ModApi): void {+ try {+ for (const row of directiveRows(state.review.outcome) ?? []) $.ui.log(row, { to: "transcript" });+ } catch (err) {+ bind($).debug(`details failed: ${String(err)}`);+ }+}++// The band is shared: a mod's tree replaces what the mods after it draw+// (docs: plugins/mods/interface, "Band above the prompt"), so Lens puts its+// rows above the tree `next(e)` returns instead of dropping it.+async function onBand($: ModApi, e: RenderEvent, next: (e: RenderEvent) => Promise<unknown>): Promise<unknown> {+ const theirs = await next(e);+ try {+ const line = map.bandLine();+ const viewport = { columns: e.props.bodyColumns ?? 80, hasSurvey: e.props.hasSurvey === true };+ const tree = bandView(state, viewport, line === null ? [] : [line]);+ if (tree === null) return theirs;+ const elements = $.ui.resolve(e);+ const ours = materialize(tree, elements, {+ [PRESS.tests]: () => pressRunTests($),+ [PRESS.why]: () => pressWhy($),+ [PRESS.details]: () => pressDetails($),+ [BRIEF_PRESS]: () => pressBrief($),+ });+ const box = elements["Box"];+ if (theirs === null || theirs === undefined || box === undefined) return ours;+ return box({ flexDirection: "column", children: [ours, theirs] });+ } catch (err) {+ bind($).debug(`band render failed: ${String(err)}`);+ return theirs;+ }+}++/**+ * Fetches a file's context once per session, started here and not awaited:+ * the engine approves Lens's call because it starts while this hook is live,+ * and the spinner shows it from the first render after it lands.+ * Ceiling: cached for the session, so an index update mid-session is not seen.+ */+function fetchContext(b: Bound, file: string): void {+ if (contextAsked.has(file)) return;+ contextAsked.add(file);+ const gen = generation;+ fetchFileContext(b.host, file)+ .then((context) => {+ if (gen !== generation || context === null) return;+ dispatch(b, { type: "contextLoaded", file, context });+ })+ .catch((err: unknown) => {+ // Asked again on the next call: the server may not have connected yet.+ contextAsked.delete(file);+ b.debug(`context for ${file} failed: ${String(err)}`);+ });+}++async function onToolCall($: ModApi, e: ToolCallEvent, next: (e: ToolCallEvent) => Promise<unknown>): Promise<unknown> {+ const b = bind($);+ const file = fileToolStarted(b, e);+ let result: unknown;+ try {+ result = await next(e);+ } finally {+ if (file !== null) dispatch(b, { type: "toolEnded", id: e.tool_use_id });+ }+ editLanded(b, e, result);+ observeTrail($, b, e, result);+ return result;+}++/** Where Claude looked, for the map: recorded from what next(e) returned, waiting on nothing. */+function observeTrail($: ModApi, b: Bound, e: ToolCallEvent, result: unknown): void {+ if (!OBSERVED_TOOLS.has(e.tool)) return;+ try {+ const here = cwd;+ // Loaded after the session started: learn the cwd for the next call, skip this one.+ if (here === null) {+ void $.session.cwd().then(+ (c) => (cwd = c),+ (err: unknown) => b.debug(`cwd failed: ${String(err)}`),+ );+ return;+ }+ const ctx = { cwd: here, isWindows: isWindowsPath(here) };+ const action = fromToolCall(e, result, ctx);+ const raw = e.file_path;+ if (action !== null) map.observe(b, action, typeof raw === "string" ? absolutePath(raw, ctx) : null);+ } catch (err) {+ b.debug(`tool.call observe failed: ${String(err)}`);+ }+}++/** A file tool starting in the repo: the spinner's file, and its context fetched. */+function fileToolStarted(b: Bound, e: ToolCallEvent): string | null {+ try {+ const file = fileTarget(e, state.repoRoot);+ if (file === null) return null;+ dispatch(b, { type: "toolStarted", tool: { id: e.tool_use_id, file } });+ fetchContext(b, file);+ return file;+ } catch (err) {+ b.debug(`tool.call failed: ${String(err)}`);+ return null;+ }+}++function editLanded(b: Bound, e: ToolCallEvent, result: unknown): void {+ try {+ if (!isFileEdit(e, result)) return;+ const path = touchedPath(e, cwd, state.repoRoot);+ if (path !== null) dispatch(b, { type: "touched", path });+ if (reviewOn) reviewAfterEdit(b);+ } catch (err) {+ b.debug(`tool.call failed: ${String(err)}`);+ }+}++// The one approval Lens gives: its own read-only lookups. Every other+// question keeps the engine's verdict, untouched.+async function onToolCheck($: ModApi, e: ToolCheckEvent, next: CheckNext): Promise<unknown> {+ try {+ if (isOwnLensCall(e, next.origin?.plugin)) {+ return { decision: "allow", reason: "Repowise Lens: its own read-only index lookup" };+ }+ } catch (err) {+ bind($).debug(`tool.check failed: ${String(err)}`);+ }+ return next(e);+}++// Rewrites only the suffix prop, so the engine keeps drawing (and animating) the line.+async function onSpinner($: ModApi, e: SpinnerEvent, next: (e: SpinnerEvent) => Promise<unknown>): Promise<unknown> {+ let line: string | null = null;+ try {+ line = spinnerSuffix(state);+ } catch (err) {+ bind($).debug(`spinner render failed: ${String(err)}`);+ }+ if (line === null) return next(e);+ const theirs = typeof e.props.suffix === "string" ? e.props.suffix : "";+ return next({ ...e, props: { ...e.props, suffix: `${theirs} ${line}` } });+}++/** Lens's rows drawn under what the engine (and the mods after Lens) drew for the site. */+function below(elements: ElementTable, theirs: unknown, tree: Node): unknown {+ const ours = materialize(tree, elements);+ const box = elements["Box"];+ if (theirs === null || theirs === undefined || box === undefined) return ours;+ return box({ flexDirection: "column", children: [theirs, ours] });+}++// A miss is not kept: an early render can come before the output is whole.+function squeezeOf(e: ToolResultEvent): Squeeze | null {+ const id = e.props.tool_use_id;+ const known = squeezes.get(id);+ if (known !== undefined || e.props.tool !== "Bash") return known ?? null;+ const out = bashText(e.props.output);+ const found = out === null ? null : parseSqueeze(out);+ if (found !== null) squeezes.set(id, found);+ return found;+}++async function onToolResult(+ $: ModApi,+ e: ToolResultEvent,+ next: (e: ToolResultEvent) => Promise<unknown>,+): Promise<unknown> {+ const theirs = await next(e);+ try {+ const s = squeezeOf(e);+ return s === null ? theirs : below($.ui.resolve(e), theirs, squeezeView(s));+ } catch (err) {+ bind($).debug(`squeeze render failed: ${String(err)}`);+ return theirs;+ }+}++// Reads what the augment hook told Claude about this edit, and passes it on untouched.+async function onPostToolUse(+ $: ModApi,+ e: PostToolUseEvent,+ next: (e: PostToolUseEvent) => Promise<unknown>,+): Promise<unknown> {+ const result = await next(e);+ try {+ // Lens's own lookups also pass through here; they are not Claude's edits.+ if (EDIT_TOOLS.has(e.tool_name) && !e.tool_use_id.startsWith("toolu_plugin_")) {+ const notes = notesFromAugment((result as { additionalContext?: unknown } | null)?.additionalContext);+ if (notes.length > 0) dispatch(bind($), { type: "notesFor", id: e.tool_use_id, notes });+ }+ } catch (err) {+ bind($).debug(`PostToolUse failed: ${String(err)}`);+ }+ return result;+}++async function onToolUse($: ModApi, e: ToolUseEvent, next: (e: ToolUseEvent) => Promise<unknown>): Promise<unknown> {+ const theirs = await next(e);+ try {+ const tree = marginView(state.notes[e.props.tool_use_id]);+ return tree === null ? theirs : below($.ui.resolve(e), theirs, tree);+ } catch (err) {+ bind($).debug(`margin render failed: ${String(err)}`);+ return theirs;+ }+}++// `/lens`, `/lens map`, `/lens recap`, `/lens ask <question>`: the pane, with+// focus, on the tab asked for (else the last one shown).+async function onLensCommand($: ModApi, e: CommandRunEvent): Promise<unknown> {+ const b = bind($);+ try {+ const asked = lensCommand(e.args ?? "");+ if (asked.tab !== null) dispatch(b, { type: "tab", tab: asked.tab });+ if (discovery === null || mapRepo(discovery) === null) refresh(b);+ await map.request(b);+ // Right after the session starts the server may not have connected yet:+ // this hook waits for it, so the lookup still starts while the hook is live.+ if (asked.question !== null) {+ await mcpReady(b.host);+ startAsk(b, asked.question);+ }+ } catch (err) {+ b.debug(`/lens failed: ${String(err)}`);+ }+ // Nothing in the transcript: the pane is the answer.+ return {};+}++function selectTab($: ModApi, tab: PaneTab): void {+ try {+ dispatch(bind($), { type: "tab", tab });+ } catch (err) {+ bind($).debug(`tab failed: ${String(err)}`);+ }+}++/** The shown tab's body; the map draws only on its own tab. */+function tabBody(b: Bound, e: PaneRenderEvent): Node {+ const { bodyColumns, placement, scroll } = e.props;+ const tab = state.pane.tab;+ if (tab !== "map") map.offScreen();+ if (tab === "ask") return askView(state, bodyColumns);+ if (tab === "recap") return recapView(state, { count: map.trail.reads.length, capped: map.trail.readsCapped }, bodyColumns);+ const d = discovery;+ const notice = d === null ? MAP_COPY.looking : HINTS[hintFor(d.mode, d.liteReason) ?? "no-index"];+ const bodyRows = scroll.bodyRows - TAB_ROWS;+ return map.paneTree(b, { surface: e.surface, notice, bodyColumns, placement, bodyRows });+}++async function onPane($: ModApi, e: PaneRenderEvent, next: (e: PaneRenderEvent) => Promise<unknown>): Promise<unknown> {+ if (e.requestId !== PANE_ID) return next(e);+ const b = bind($);+ try {+ const presses = Object.fromEntries(TABS.map((tab) => [TAB_PRESS[tab], () => selectTab($, tab)]));+ return materialize(paneView(state.pane.tab, tabBody(b, e)), $.ui.resolve(e), presses);+ } catch (err) {+ b.debug(`pane render failed: ${String(err)}`);+ return next(e);+ }+}++// `options` are the plugin's userConfig toggles; a change reloads the module.+export function register(on: On, options: PluginOptions = {}): void {+ reviewOn = options["lens_review"] !== false;+ autoOpenOn = options["lens_pane_autoopen"] === true;+ on("session.start", onSessionStart);+ on("turn.start", onTurnStart);+ on("turn.complete", onTurnComplete);+ on("ui.render", { component: "AbovePrompt" }, onBand);+ on("ui.render", { component: "Pane" }, onPane);+ on("command.run", { command: "lens" }, onLensCommand);+ // Literals, so the static check reads the matcher: this plugin's Ask field (ASK_KEY).+ on("ui.input", { plugin: "repowise", element: "lens-ask" }, onAskInput);+ // The brief is only offered: nothing here hooks `session.compact`.+ on("classic.PostCompact", onPostCompact);+ on("tool.call", onToolCall);+ on("tool.check", onToolCheck);+ on("ui.render", { component: "Spinner" }, onSpinner);+ if (options["lens_squeeze"] !== false) on("ui.render", { component: "ToolResult" }, onToolResult);+ if (options["lens_margin"] !== false) {+ on("classic.PostToolUse", onPostToolUse);+ on("ui.render", { component: "ToolUse" }, onToolUse);+ }+}diff --git a/packages/claude-mod/src/views/answer.ts b/packages/claude-mod/src/views/answer.tsnew file mode 100644index 000000000..d6118c659--- /dev/null+++ b/packages/claude-mod/src/views/answer.ts@@ -0,0 +1,86 @@+/**+ * An Ask reply as Markdown: the tool's own words, its confidence or basis,+ * and the evidence ids and paths it cites, all as the server sent them.+ */++import { fit } from "../format";+import type { AnswerReply, AskReply, EvidenceRef, WhyCommit, WhyDecision, WhyRationale, WhyReply } from "../model/ask";+import { ASK_CHARS, PANE_COPY, askCut, moreRows } from "./copy";++/** Rows of each list drawn; the rest are counted. */+const LIST_ROWS = 5;+/** Characters of one decision body or rationale comment. */+const ROW_CHARS = 300;++const code = (s: string): string => `\`${s.replace(/`/g, "'")}\``;+/** One line of the tool's prose: Markdown line breaks would split a list row. */+const line = (s: string, chars = ROW_CHARS): string => fit(s.replace(/\s+/g, " ").trim(), chars);++function ids(refs: readonly EvidenceRef[] | undefined): string {+ const found = (refs ?? []).map((r) => r.id).filter((id): id is string => typeof id === "string");+ return found.length === 0 ? "" : ` · ${found.map(code).join(" ")}`;+}++/** Up to LIST_ROWS rows under a bold head, then a count of the rest (`total` when the server stamped one). */+function list<T>(head: string, rows: readonly T[] | undefined, row: (r: T) => string, total?: number): string[] {+ if (rows === undefined || rows.length === 0) return [];+ const shown = rows.slice(0, LIST_ROWS);+ const more = Math.max(total ?? 0, rows.length) - shown.length;+ return [`**${head}**`, ...shown.map((r) => `- ${row(r)}`), ...(more > 0 ? [`- ${moreRows(more)}`] : [])];+}++/**+ * `**Built from the index** · confidence low · retrieval weak`. A reply that+ * says why it is not a synthesis (`degraded`) was built from the index; any+ * other may have been written by the repo's configured model. The reply does+ * not name the model.+ */+function answerHead(a: AnswerReply): string {+ const parts = [`**${a.degraded === undefined ? PANE_COPY.fromModel : PANE_COPY.fromIndex}**`];+ if (a.confidence !== undefined) parts.push(`confidence ${a.confidence}`);+ if (a.retrieval_quality !== undefined) parts.push(`retrieval ${a.retrieval_quality}`);+ return parts.join(" · ");+}++function answerMarkdown(a: AnswerReply): string[] {+ const cited = a.citations ?? [];+ const evidence = cited.length === 0 ? PANE_COPY.noEvidence : `evidence: ${cited.map(code).join(", ")}`;+ return [answerHead(a), a.answer ?? "", evidence];+}++const decisionRow = (d: WhyDecision): string => {+ const facts = [d.status, d.authority, d.confidence === null || d.confidence === undefined ? undefined : `confidence ${d.confidence}`]+ .filter((f): f is string => f !== undefined)+ .join(" · ");+ const id = d.id === undefined ? "" : ` · ${code(d.id)}`;+ const body = d.decision === undefined ? "" : `: ${line(d.decision)}`;+ return `**${line(d.title, 120)}**${facts === "" ? "" : ` (${facts})`}${id}${body}`;+};++const commitRow = (c: WhyCommit): string =>+ `${code(c.sha ?? "?")} ${line(c.message ?? "", 160)}${c.date === undefined ? "" : ` (${c.date.slice(0, 10)})`}${ids(c.evidence_refs)}`;++const rationaleRow = (r: WhyRationale): string =>+ `${code(r.lines === undefined ? r.path : `${r.path}:${r.lines[0]}`)} ${line(r.comment)}${ids(r.evidence_refs)}`;++function whyMarkdown(w: WhyReply): string[] {+ const from = `**${PANE_COPY.fromIndex}**`;+ const head = w.answer_basis === undefined ? from : `${from} · basis ${w.answer_basis}`;+ const commits = w.git_archaeology?.git_log ?? w.git_archaeology?.file_commits;+ return [+ head,+ ...(w.reason === undefined ? [] : [w.reason]),+ ...list("Decisions", w.decisions, decisionRow),+ ...list("Commits", commits, commitRow),+ ...list("Rationale in the code", w.code_rationale, rationaleRow, w.code_rationale_total),+ ];+}++/** The reply under the question, cut at ASK_CHARS with the cut said. */+export function replyMarkdown(question: string, a: AskReply): string {+ const body = a.tool === "get_answer" ? answerMarkdown(a.reply) : whyMarkdown(a.reply);+ const text = [`> ${line(question, 200)}`, ...body].join("\n\n");+ if (text.length <= ASK_CHARS) return text;+ const note = `\n\n_${askCut(ASK_CHARS)}_`;+ return `${text.slice(0, ASK_CHARS - note.length).trimEnd()}${note}`;+}diff --git a/packages/claude-mod/src/views/band.ts b/packages/claude-mod/src/views/band.tsnew file mode 100644index 000000000..b9cf3268a--- /dev/null+++ b/packages/claude-mod/src/views/band.ts@@ -0,0 +1,39 @@+/**+ * The band above the prompt. Empty at rest; at most two rows, each an+ * exception or a one-time hint; gives way to a survey.+ */++import { fit } from "../format";+import type { SessionState } from "../model/session";+import { HINTS, freshnessLine, savingsLine } from "./copy";+import { box, text, type Node } from "./elements";+import { briefBandRow } from "./brief";+import { reviewBandRow } from "./review";++export const MAX_BAND_ROWS = 2;++export interface BandViewport {+ columns: number;+ hasSurvey: boolean;+}++export function bandRows(state: SessionState, columns = Number.POSITIVE_INFINITY): string[] {+ const rows: string[] = [];+ if (state.hint !== null) rows.push(HINTS[state.hint]);+ if (state.freshness !== null) rows.push(freshnessLine(state.freshness));+ if (state.savings !== null) rows.push(savingsLine(state.savings, columns));+ return rows.slice(0, MAX_BAND_ROWS);+}++/** null means draw nothing: pass the site on. `extra` rows come after the session's own. */+export function bandView(state: SessionState, viewport: BandViewport, extra: readonly string[] = []): Node | null {+ if (viewport.hasSurvey) return null;+ // Rows with buttons keep their place within the cap: the review's (never+ // hidden) and the brief's, which takes hotkey 4 beside the review's 1 to 3.+ const review = reviewBandRow(state.review.outcome, viewport.columns, state.review.decision);+ const actions = [review, briefBandRow(state, viewport.columns, review !== null)].filter((n): n is Node => n !== null);+ const own = [...bandRows(state, viewport.columns), ...extra].slice(0, Math.max(0, MAX_BAND_ROWS - actions.length));+ if (own.length === 0 && actions.length === 0) return null;+ const nodes = own.map((row) => text(fit(row, viewport.columns), { dimColor: true, wrap: "truncate-end" }));+ return box({ key: "lens-band", flexDirection: "column" }, [...nodes, ...actions]);+}diff --git a/packages/claude-mod/src/views/brief.ts b/packages/claude-mod/src/views/brief.tsnew file mode 100644index 000000000..163ece0e4--- /dev/null+++ b/packages/claude-mod/src/views/brief.ts@@ -0,0 +1,76 @@+/**+ * The brief offered after a compaction: files edited, decisions in play and+ * the last review's open items, as one visible prompt under BRIEF_CHARS. It+ * reaches Claude only when the person presses `Brief Claude`.+ */++import { fit } from "../format";+import { testsToRun } from "../model/review";+import { surfacedDecisions, type SessionState } from "../model/session";+import { BRIEF_CHARS, BRIEF_COPY, briefDecision, briefTests, findingLine, overlapLine } from "./copy";+import { box, button, text, type Node } from "./elements";+import { overlap } from "./review";++export const BRIEF_PRESS = "lens-brief";+/** Characters of one listed item, so one long title cannot take the whole brief. */+const ITEM_CHARS = 240;++/**+ * `head item; item; and N more`, with as many items as fit in `room`. The+ * last resort cuts the line itself, so the result never passes `room`.+ */+export function listWithin(head: string, items: readonly string[], room: number): string {+ // One line per section: a title or a finding written over several lines is joined.+ const cut = items.map((i) => fit(i.replace(/\s+/g, " ").trim(), ITEM_CHARS));+ for (let k = cut.length; k >= 0; k--) {+ const more = cut.length - k;+ const shown = cut.slice(0, k).join("; ");+ const tail = more === 0 ? "" : `${shown === "" ? "" : "; "}and ${more} more`;+ const line = `${head} ${shown}${tail}`;+ if (line.length <= room) return line;+ }+ return fit(`${head} and ${cut.length} more`, room);+}++function reviewItems(state: SessionState): string[] {+ const risk = state.lastReview;+ if (risk === null) return [];+ const findings = (risk.health_delta?.findings_total ?? 0) > 0 ? (risk.health_delta?.top_findings ?? []).map(findingLine) : [];+ const tests = testsToRun(risk);+ const shared = overlap(risk);+ return [+ ...findings,+ ...(tests === null ? [] : [briefTests(tests)]),+ ...(shared === null ? [] : [overlapLine(shared.branches, shared.files, shared.more)]),+ ];+}++/** The brief, or null when the session has nothing to hand over. */+export function briefText(state: SessionState): string | null {+ const sections: Array<[string, string[]]> = [+ [BRIEF_COPY.files, [...state.touched]],+ [BRIEF_COPY.decisions, surfacedDecisions(state).map((d) => briefDecision(d.title, d.reviewed))],+ [BRIEF_COPY.review, reviewItems(state)],+ ];+ const filled = sections.filter(([, items]) => items.length > 0);+ if (filled.length === 0) return null;+ let brief = BRIEF_COPY.intro;+ filled.forEach(([head, items], i) => {+ // An even share of what is left; a section that needs less leaves the rest to the next.+ const room = Math.floor((BRIEF_CHARS - brief.length) / (filled.length - i)) - 1;+ brief += `\n${listWithin(head, items, Math.max(0, room))}`;+ });+ return brief;+}++/**+ * `context compacted 1: Brief Claude`, while the offer stands and there is+ * something to brief. Beside a review row (hotkeys 1 to 3) it takes 4.+ */+export function briefBandRow(state: SessionState, columns: number, besideReview = false): Node | null {+ if (!state.compacted || briefText(state) === null) return null;+ return box({ key: "lens-brief", flexDirection: "row", columnGap: 2 }, [+ text(fit(BRIEF_COPY.compacted, Math.max(1, columns - BRIEF_COPY.button.length - 5)), { dimColor: true }),+ button(BRIEF_PRESS, besideReview ? "4" : "1", BRIEF_COPY.button),+ ]);+}diff --git a/packages/claude-mod/src/views/copy.ts b/packages/claude-mod/src/views/copy.tsnew file mode 100644index 000000000..d4f9cf309--- /dev/null+++ b/packages/claude-mod/src/views/copy.ts@@ -0,0 +1,391 @@+/**+ * Every string Lens shows. Commands are written out whole so they can be+ * copied; Lens never runs them.+ */++import { formatNumber } from "@repowise-dev/ui/lib/format";+import { countOf, fit } from "../format";+import type { FileContext, HintKind, IndexFreshness, MarginNote, SavingsDelta } from "../model/session";+import type { Squeeze } from "../model/squeeze";+import type { Callers } from "../model/trail";++export const HINTS: Record<HintKind, string> = {+ "no-server": "Lens map needs the local server: repowise serve --no-ui",+ auth: "local server needs an API key; Lens does not read keys",+ unlisted: "Lens map needs a local server for this repo: repowise serve --no-ui",+ "no-index": "index this repo for Lens: repowise init --no-prose --yes",+ "no-cli": "Lens needs the Repowise CLI: pip install repowise",+};++export function freshnessLine(f: IndexFreshness): string {+ const changed = f.changedFiles === null ? "" : ` (${countOf(f.changedFiles, "file", "files")} changed)`;+ return `index behind HEAD${changed} · repowise update`;+}++/** `query.py · 41 caller files · 3 contributors`; unknown or zero counts are left out. */+export function spinnerLine(file: string, ctx: FileContext): string {+ const parts = [file.slice(file.lastIndexOf("/") + 1)];+ if (ctx.callerFiles) parts.push(countOf(ctx.callerFiles, "caller file", "caller files"));+ if (ctx.contributors) parts.push(countOf(ctx.contributors, "contributor", "contributors"));+ return parts.join(" · ");+}++/** `1,204 lines → 38 · ~9,400 tokens omitted · 4 failed · repowise expand 9c1e4b2a7f01`. */+export function squeezeLine(s: Squeeze): string {+ const parts = [`${countOf(s.originalLines, "line", "lines")} → ${s.keptLines.toLocaleString("en-US")}`];+ if (s.omittedTokens > 0) parts.push(`~${countOf(s.omittedTokens, "token", "tokens")} omitted`);+ // As the runner wrote it: pytest's `4 failed, 1 error`.+ const failures = [s.failed > 0 ? `${s.failed.toLocaleString("en-US")} failed` : "", s.errors > 0 ? countOf(s.errors, "error", "errors") : ""];+ if (s.failed + s.errors > 0) parts.push(failures.filter((f) => f !== "").join(", "));+ const more = s.refs.length > 1 ? ` (+${s.refs.length - 1} more)` : "";+ parts.push(`repowise expand ${s.refs[0]}${more}`);+ return parts.join(" · ");+}++/**+ * A margin note as help, never a label, saying only what the hook emitted.+ * The age is always said, so a run of fixes last week never reads like one+ * from last spring.+ */+export function marginLine(note: MarginNote): string {+ if (note.kind === "decision") {+ return note.reviewed+ ? `a standing decision covers this file: ${note.title}`+ : `a decision found in this file, not yet reviewed: ${note.title}`;+ }+ const where = note.symbol === null ? "" : `, mostly in ${note.symbol}`;+ return `fixed ${countOf(note.count, "time", "times")} in 6 months, most recently ${note.age}${where}`;+}++/**+ * `182,400 tokens · $2.41 saved since this session started · all agents on this repo`.+ * The scope stays on screen: a narrow band gets the short form, not a cut one.+ */+export function savingsLine(d: SavingsDelta, columns: number): string {+ const inferred = d.inferredTokens > 0 ? ` (${d.inferredTokens.toLocaleString("en-US")} inferred)` : "";+ // Input-side dollars, like the token count. Under half a cent rounds to+ // $0.00, which would read as nothing priced.+ const usd = d.usd >= 0.005 ? ` · $${d.usd.toFixed(2)}` : "";+ const head = `${countOf(d.tokens, "token", "tokens")}${inferred}${usd} saved`;+ const full = `${head} since this session started · all agents on this repo`;+ return full.length <= columns ? full : `${head} this session · all agents`;+}++// Change review. Figures carry their unit; "measured" and "inferred" are said in words.++export const REVIEWING = "Reviewing the change...";+export const REVIEW_TIMEOUT_S = 20;+export const REVIEW_TIMED_OUT = `Change review timed out after ${REVIEW_TIMEOUT_S} s`;+export const RUN_TESTS = "Run tests";+export const WHY = "Why";+export const DETAILS = "Details";+/** Branch overlap is a fact, not a health band: a neutral mark plus words. */+export const OVERLAP_MARK = "◦";++export function reviewFailed(message: string): string {+ return `Change review could not run: ${message}`;+}++/** `working tree, 2 changed files`, or the commit a clean tree fell back to. */+export function reviewScope(ref: string, workingTree: boolean, changed: number | null): string {+ const where = workingTree ? ref : `${ref} (no uncommitted changes)`;+ return changed === null ? where : `${where}, ${countOf(changed, "changed file", "changed files")}`;+}++export function noNewFindings(analyzed: number): string {+ return `no new findings in ${analyzed === 1 ? "the 1 changed file" : `all ${analyzed.toLocaleString("en-US")} changed files`}`;+}++export function healthImproved(resolved: number): string {+ return `improved, ${countOf(resolved, "finding", "findings")} resolved, none new`;+}++export const HEALTH_NOT_REPORTED = "not reported";+export const NO_NEW_FINDINGS = "no new findings";+export const PARTLY_COMPARED = "partly compared, no new findings";++export function notCompared(why: string): string {+ return why === "" ? "not compared" : `not compared: ${why}`;+}++export function improvedShort(resolved: number): string {+ return `improved, ${resolved.toLocaleString("en-US")} resolved`;+}++/** `2 new findings, review required`; low and advisory severities are worth a look, not a gate. */+export function newFindings(total: number, required: boolean): string {+ return `${countOf(total, "new finding", "new findings")}, ${required ? "review required" : "low severity"}`;+}++export function resolvedToo(resolved: number): string {+ return `${countOf(resolved, "finding", "findings")} resolved`;+}++export function findingLine(f: { severity: string; biomarker: string; reason: string; path: string; lines?: [number, number] }): string {+ const at = f.lines === undefined ? f.path : `${f.path}:${f.lines[0]}`;+ return `${f.severity} ${f.biomarker}: ${f.reason} (${at})`;+}++export function moreFindings(more: number): string {+ return `and ${more.toLocaleString("en-US")} more (Details)`;+}++export function partialScope(analyzed: number, changed: number, reasons: Record<string, number>): string {+ const why = Object.entries(reasons)+ .map(([reason, n]) => `${n.toLocaleString("en-US")} ${reason.replace(/_/g, " ")}`)+ .join(", ");+ const skipped = changed - analyzed;+ return (+ `Scope: compared ${analyzed.toLocaleString("en-US")} of ${countOf(changed, "changed file", "changed files")}; ` ++ `${skipped.toLocaleString("en-US")} not analysed${why ? ` (${why})` : ""}, so this is not a clean bill`+ );+}++export function diffShape(percentile: number | null | undefined): string {+ const where =+ percentile === null || percentile === undefined+ ? "not ranked (no recent commits to compare)"+ : `bigger than ${Math.round(percentile)}% of this repo's recent commits`;+ return `Diff shape: ${where}; size, not danger`;+}++export function testsBasis(measured: boolean): string {+ return measured ? "measured by stored coverage" : "inferred from the dependency graph, not measured";+}++export function testsLine(t: { tests: string[]; total: number; truncated: boolean; files: boolean; measured: boolean }): string {+ const count = countOf(t.total, t.files ? "test file" : "test", t.files ? "test files" : "tests");+ const shown = t.truncated ? ` (first ${t.tests.length.toLocaleString("en-US")} shown)` : "";+ return `Tests to run: ${count}, ${testsBasis(t.measured)}${shown}: ${t.tests.join(", ")}`;+}++export function overlapLine(branches: string[], files: string[], more: boolean): string {+ const who = countOf(branches.length, "other branch", "other branches") + (more ? " or more" : "");+ const what = files.length === 1 ? files[0] : countOf(files.length, "changed file", "changed files");+ const verb = branches.length === 1 && !more ? "edits" : "edit";+ return `${OVERLAP_MARK} ${who} also ${verb} ${what} (${branches.join(", ")})`;+}++export function overlapShort(branches: number): string {+ return `${OVERLAP_MARK} ${countOf(branches, "other branch edits", "other branches edit")} these files`;+}++export function directiveLines(d: { status: string; headline: string; reasons?: string[]; next_actions?: string[] }): string[] {+ const out = [`Change review: ${d.status.replace(/_/g, " ")}`, d.headline];+ if (d.reasons?.length) out.push("Reasons:", ...d.reasons.map((r) => ` ${r}`));+ if (d.next_actions?.length) out.push("Next actions:", ...d.next_actions.map((a) => ` ${a}`));+ return out;+}++/** The prompt `Run tests` submits, visible in the transcript. */+export function runTestsPrompt(t: { tests: string[]; truncated: boolean; total: number; measured: boolean }): string {+ const rest = t.truncated ? ` (the first ${t.tests.length} of ${t.total})` : "";+ return `Run the tests Repowise names for this change${rest}, ${testsBasis(t.measured)}: ${t.tests.join(" ")}`;+}++// The living map.++export const MAP_COPY = {+ title: "Lens",+ looking: "Lens map: looking for the local server",+ loading: "Lens map: loading the health map",+ failed: "Lens map could not load the health map; it tries again on /lens",+ desktop: "Lens map: not drawn on this surface (terminal and desktop app only)",+ tooLarge: "Lens map has too much detail to draw here; the terminal map shows it",+ noScore: "Not scored",+ read: "Claude read",+ edited: "edited",+ importer: "imports the edited file",+ match: "search match",+ waiting: "Lens map is ready; this pane is too narrow to open on its own. Run /lens",+} as const;++/** What the desktop map says to a reader that cannot see it. */+export function mapAlt(drawn: number): string {+ return `Code health map: ${countOf(drawn, "file", "files")} drawn, colored by health band, with the files Claude read and edited marked`;+}++/** /lens could not place the pane; the engine's reason names the width it needs. */+export function notPlacedLine(reason: string): string {+ return `Lens map needs a wider terminal: ${reason}`;+}++export interface ScopeFacts {+ drawn: number;+ repositoryTotal: number;+ /** "2h ago", or null when the server did not say. */+ indexed: string | null;+ /** Files the server left out at its cap, and the cap. */+ beyondCap: number;+ cap: number;+}++/** Scope parts a narrow legend may leave out; the counts and the cap always stay. */+export const SCOPE_REST = "rest empty or too small";+export function indexedPart(age: string): string {+ return `indexed ${age}`;+}++/** The scope, as parts the legend joins with ` · ` and wraps onto two rows when narrow. */+export function scopeParts(s: ScopeFacts): string[] {+ const parts =+ s.drawn === s.repositoryTotal+ ? [`${countOf(s.drawn, "file", "files")}, all drawn`]+ : [`${formatNumber(s.drawn)} of ${countOf(s.repositoryTotal, "file", "files")} drawn at this size`, SCOPE_REST];+ if (s.indexed !== null) parts.push(indexedPart(s.indexed));+ if (s.beyondCap > 0) parts.push(`${formatNumber(s.beyondCap)} beyond the ${formatNumber(s.cap)}-file cap`);+ return parts;+}++/**+ * Reads so far (`200+` once capped), what was not drawn, and what the last+ * search matched. Narrower than `columns`, a short form that keeps every count.+ */+export function readsLine(+ reads: { count: number; capped: boolean; notDrawn: number },+ matched: number | null,+ columns = Number.POSITIVE_INFINITY,+): string | null {+ const count = reads.capped ? `${formatNumber(reads.count)}+` : formatNumber(reads.count);+ const full: string[] = [];+ const short: string[] = [];+ if (reads.count > 0) {+ full.push(reads.capped ? `${count} files read` : countOf(reads.count, "file read", "files read"));+ short.push(`${count} read`);+ }+ if (reads.notDrawn > 0) {+ full.push(`${formatNumber(reads.notDrawn)} not drawn`);+ short.push(`${formatNumber(reads.notDrawn)} not drawn`);+ }+ if (matched !== null) {+ full.push(`last search matched ${countOf(matched, "file", "files")}`);+ short.push(`search matched ${formatNumber(matched)}`);+ }+ if (full.length === 0) return null;+ const line = full.join(" · ");+ return line.length <= columns ? line : short.join(" · ");+}++/**+ * The importers of the edited file: inferred from the import graph, not+ * observed calls. Narrower than `columns`, a short form that keeps the counts+ * and cuts the file name instead (the legend's swatch names the basis).+ */+export function callersLine(name: string, callers: Callers | null, notDrawn: number, columns = Number.POSITIVE_INFINITY): string {+ if (callers === null || callers.status === "loading") return `edited ${name} · finding the files that import it`;+ if (callers.status === "failed") return `edited ${name} · import graph unavailable`;+ const missing = notDrawn === 0 ? "" : ` · ${formatNumber(notDrawn)} not drawn`;+ const full = `edited ${name} · ${countOf(callers.paths.length, "file imports", "files import")} it (from imports, not calls)${missing}`;+ if (full.length <= columns) return full;+ const rest = ` · ${formatNumber(callers.paths.length)} import it${missing}`;+ return `edited ${fit(name, columns - "edited ".length - rest.length)}${rest}`;+}++// The pane's tabs, Ask and Recap.++export const PANE_COPY = {+ command: "Open Lens: the health map, ask the index, and the session recap",+ argumentHint: "[map | ask <question> | recap]",+ tabs: { map: "Map", ask: "Ask", recap: "Recap" },+ askLabel: "ask ",+ askPlaceholder: "why ...? asks the decision records; anything else asks the index",+ askSubmit: "ask",+ askIdle: "Ask about this repo. Answers cite the evidence they used.",+ askBusy: "still answering the last question; ask again when it lands",+ noEvidence: "no evidence cited",+ fromIndex: "Built from the index",+ fromModel: "Written by this repo's configured model, from the index",+} as const;++/** Characters of a reply the Ask tab draws; the Markdown element takes at most 10,000. */+export const ASK_CHARS = 4_000;++export function askingLine(tool: "get_why" | "get_answer"): string {+ return tool === "get_why" ? "asking the decision records..." : "asking the index...";+}++export function askFailedLine(message: string): string {+ return `Could not answer: ${message}`;+}++export function askCut(chars: number): string {+ return `reply cut at ${formatNumber(chars)} characters`;+}++export function moreRows(more: number): string {+ return `and ${formatNumber(more)} more`;+}++export const RECAP_COPY = {+ files: "Files",+ fromReview: "from the last change review",+ review: "Change review",+ health: "Code health",+ findings: "Findings",+ tests: "Tests to run",+ overlap: "Branches overlapping",+ saved: "Saved",+ decisions: "Decisions surfaced",+ noReview: "none this session",+ notCompared: "not compared",+ noTests: "none named",+ noOverlap: "none found",+ notReported: "not reported",+ noSavings: "nothing yet since this session started",+ savingsNeedServer: "needs the local server: repowise serve --no-ui",+ noDecisions: "none",+ noModel: "Lens made no model calls.",+ fromIndex: "Every figure here is read from the local index.",+} as const;++/** `4 edited of 41 files touched`, `200+` once the trail is capped. */+export function filesTouched(edited: number, touched: { count: number; capped: boolean }): string {+ const all = touched.capped ? `${formatNumber(touched.count)}+` : formatNumber(touched.count);+ return `${formatNumber(edited)} edited of ${all} ${touched.count === 1 && !touched.capped ? "file" : "files"} touched`;+}++/** `1 resolved · 3 new findings`. */+export function findingsCounts(resolved: number, total: number): string {+ return `${formatNumber(resolved)} resolved · ${countOf(total, "new finding", "new findings")}`;+}++export function testsToRunCount(t: { total: number; files: boolean; measured: boolean }): string {+ const count = countOf(t.total, t.files ? "test file" : "test", t.files ? "test files" : "tests");+ return `${count}, ${t.measured ? "measured" : "inferred"}`;+}++export function decisionsSurfaced(titles: readonly string[]): string {+ return `${formatNumber(titles.length)}: ${titles.join("; ")}`;+}++/**+ * Lens itself calls no model. `get_answer` may have its reply written by the+ * model a repo configures, which the footer then says.+ */+export function recapFooter(modelAsks: number): string {+ if (modelAsks === 0) return `${RECAP_COPY.noModel} ${RECAP_COPY.fromIndex}`;+ const asks = countOf(modelAsks, "Ask reply", "Ask replies");+ return `${RECAP_COPY.noModel} ${asks} from get_answer may have been written by this repo's configured model.`;+}++// The brief after a compaction: a visible prompt, sent only on a press.++export const BRIEF_COPY = {+ compacted: "context compacted",+ button: "Brief Claude",+ intro: "The context was compacted. This brief is built from the Repowise index and this session's edits:",+ files: "Files edited:",+ decisions: "Decisions in play:",+ review: "Open review items:",+} as const;++/** Characters the brief may take, about 300 tokens. */+export const BRIEF_CHARS = 1_200;++export function briefDecision(title: string, reviewed: boolean): string {+ return reviewed ? `${title} (standing decision)` : `${title} (found in the code, not yet reviewed)`;+}++export function briefTests(t: { tests: string[]; measured: boolean }): string {+ return `tests to run, ${testsBasis(t.measured)}: ${t.tests.join(" ")}`;+}diff --git a/packages/claude-mod/src/views/elements.ts b/packages/claude-mod/src/views/elements.tsnew file mode 100644index 000000000..1f7c238b4--- /dev/null+++ b/packages/claude-mod/src/views/elements.ts@@ -0,0 +1,129 @@+/**+ * Views build plain trees with these builders, so they stay pure and testable+ * without a surface. register.ts turns a tree into real elements with+ * `materialize` over the table `$.ui.resolve(e)` returns.+ */++export interface TextProps {+ dimColor?: boolean;+ wrap?: "truncate-end";+ /** A theme key (`success`, `warning`, `error`: the terminal's own colors for health) or a hex color. */+ color?: string;+}++export interface BoxProps {+ key?: string;+ flexDirection?: "column" | "row";+ columnGap?: number;+}++/** A pressable leaf; `key` names the action register.ts runs on a press. */+export interface ButtonProps {+ key: string;+ label: string;+ hotkey: string;+ /** Drawn as `1: label`, the way a survey's rows read. */+ plain: true;+ /** Dim at rest, full strength under the focus: a tab not shown. */+ dimColor?: boolean;+}++/** A one-line field; its submit is read by register.ts's `ui.input` hook, not a closure. */+export interface InputProps {+ key: string;+ label: string;+ placeholder: string;+ submitLabel: string;+ value?: string;+ autoFocus?: true;+}++export interface MarkdownProps {+ /** At most 10,000 characters. */+ text: string;+}++/** A drawing for the surfaces that draw SVG (the desktop app); at most 131,072 characters. */+export interface SvgProps {+ source: string;+ alt: string;+}++/** A terminal cell grid; `cells` packs `columns * rows` cells (views/map.ts). */+export interface RasterProps {+ key: string;+ columns: number;+ rows: number;+ cells: string;+}++export type Node =+ | { type: "Text"; props: TextProps; children: string[] }+ | { type: "Box"; props: BoxProps; children: Node[] }+ | { type: "Button"; props: ButtonProps }+ | { type: "Raster"; props: RasterProps }+ | { type: "Input"; props: InputProps }+ | { type: "Markdown"; props: MarkdownProps }+ | { type: "Svg"; props: SvgProps };++export function text(value: string, props: TextProps = {}): Node {+ return { type: "Text", props, children: [value] };+}++export function box(props: BoxProps, children: Node[]): Node {+ return { type: "Box", props, children };+}++export function button(key: string, hotkey: string, label: string, dimColor = false): Node {+ return { type: "Button", props: { key, label, hotkey, plain: true, ...(dimColor ? { dimColor } : {}) } };+}++export function raster(props: RasterProps): Node {+ return { type: "Raster", props };+}++export function input(props: InputProps): Node {+ return { type: "Input", props };+}++export function markdown(text: string): Node {+ return { type: "Markdown", props: { text } };+}++export function svg(source: string, alt: string): Node {+ return { type: "Svg", props: { source, alt } };+}++/** The Input's own closure: the submit is handled in the `ui.input` hook, where a lookup may start. */+const SUBMIT_IN_HOOK = (): void => undefined;++export type ElementTable = Record<string, (props: Record<string, unknown>) => unknown>;++/** What a press on each Button key runs. */+export type PressTable = Record<string, () => void>;++type Props = Record<string, unknown>;+type PropsOf = { [K in Node["type"]]: (node: Extract<Node, { type: K }>, table: ElementTable, presses: PressTable) => Props };++function pressFor(key: string, presses: PressTable): () => void {+ const onPress = presses[key];+ if (!onPress) throw new Error(`button ${key} has no action`);+ return onPress;+}++// Leaves (Raster, Markdown, Svg) pass their props alone: the element refuses a `children` prop.+const PROPS: PropsOf = {+ Text: (n) => ({ ...n.props, children: n.children }),+ Box: (n, table, presses) => ({ ...n.props, children: n.children.map((child) => materialize(child, table, presses)) }),+ Button: (n, _table, presses) => ({ ...n.props, onPress: pressFor(n.props.key, presses) }),+ Input: (n) => ({ ...n.props, onSubmit: SUBMIT_IN_HOOK }),+ Raster: (n) => ({ ...n.props }),+ Markdown: (n) => ({ ...n.props }),+ Svg: (n) => ({ ...n.props }),+};++export function materialize(node: Node, table: ElementTable, presses: PressTable = {}): unknown {+ const build = table[node.type];+ if (!build) throw new Error(`element ${node.type} is not on this surface`);+ return build((PROPS[node.type] as (n: Node, t: ElementTable, p: PressTable) => Props)(node, table, presses));+}diff --git a/packages/claude-mod/src/views/map.ts b/packages/claude-mod/src/views/map.tsnew file mode 100644index 000000000..24ae3d03a--- /dev/null+++ b/packages/claude-mod/src/views/map.ts@@ -0,0 +1,300 @@+/**+ * The living map: a squarified treemap of the health-map feed, sized by lines+ * of code and grouped by folder, rasterized into terminal cells. Each cell+ * holds two map pixels as an upper half block (top pixel the glyph, bottom+ * pixel the background), so the pixel grid is `columns x rows * 2`, near square.+ *+ * Pure: the layout, its base pixels and the cell encoding. views/overlay.ts+ * paints Claude's marks on top; register.ts blits the animated frames.+ */++import { hierarchy, treemap, treemapSquarify, type HierarchyRectangularNode } from "d3-hierarchy";+import { bandForScore, type HealthFileMetric } from "@repowise-dev/types/health";+import { BRAND, DARK, DARK_CANVAS, DARK_CANVAS_BAND } from "@repowise-dev/ui/brand";++export type MapFile = Pick<HealthFileMetric, "file_path" | "score" | "nloc">;++export interface Rect {+ x: number;+ y: number;+ w: number;+ h: number;+}++/** A file's place: float rect in pixels, and the whole pixels it owns (`px1`, `py1` exclusive). */+export interface PlacedFile {+ path: string;+ score: number | null;+ nloc: number;+ group: number;+ rect: Rect;+ px0: number;+ py0: number;+ px1: number;+ py1: number;+}++export interface MapGroup {+ key: string;+ rect: Rect;+ nloc: number;+}++export interface MapLabel {+ row: number;+ col: number;+ text: string;+}++export interface MapLayout {+ columns: number;+ rows: number;+ /** Pixel grid: `columns` across, `rows * 2` down. */+ width: number;+ height: number;+ groups: MapGroup[];+ /** Every file with lines, drawn or not. */+ files: PlacedFile[];+ /** Indices into `files` of those that own at least one pixel. */+ drawn: number[];+ /** Drawn file by repo-relative path (lowercase where paths are case-insensitive). */+ index: Map<string, number>;+ caseInsensitive: boolean;+ labels: MapLabel[];+ base: Uint32Array;+}++const UPPER_HALF = 0x2580;+const hex = (s: string): number => parseInt(s.slice(1), 16);+export const ACCENT = hex(BRAND.accent);+/** The canvas ground and gutters: painted, never the terminal's own background. */+export const GROUND = hex(DARK.bgRoot);+export const LABEL_FG = hex(DARK.textSecondary);+const NEUTRAL = hex(DARK_CANVAS.nodeNeutral);+const BLACK = 0x000000;++/** A folder holding more than this share of the lines is split into its subfolders. */+const SPLIT_SHARE = 0.25;+const MAX_SPLITS = 8;+/** Groups at least this many pixels each way get a one-pixel gutter on their right and bottom. */+const GUTTER_MIN = 6;+/** Files at least this many pixels across (or down) get a darker last column (or row), so neighbours of one band part. */+const EDGE_MIN = 3;++/** The color a file's score paints; neutral when it has none. */+export function colorForScore(score: number | null): number {+ return score === null ? NEUTRAL : hex(DARK_CANVAS_BAND[bandForScore(score)]);+}++/** Linear blend of two 0xRRGGBB colors; `amount` 1 is all `b`. */+export function mix(a: number, b: number, amount: number): number {+ const ch = (shift: number) => {+ const x = (a >> shift) & 0xff;+ const y = (b >> shift) & 0xff;+ return Math.round(x + (y - x) * amount) << shift;+ };+ return (ch(16) | ch(8) | ch(0)) >>> 0;+}++const byName = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);++function dirsOf(path: string): string[] {+ return path.split("/").slice(0, -1);+}++function keyOf(path: string, split: ReadonlySet<string>): string {+ const dirs = dirsOf(path);+ let depth = Math.min(1, dirs.length);+ while (depth < dirs.length && split.has(dirs.slice(0, depth).join("/"))) depth++;+ return dirs.slice(0, depth).join("/");+}++/** The heaviest group over the share that splitting would actually divide, or null. */+function nextSplit(files: readonly MapFile[], split: ReadonlySet<string>, limit: number): string | null {+ const weight = new Map<string, number>();+ for (const f of files) {+ const key = keyOf(f.file_path, split);+ weight.set(key, (weight.get(key) ?? 0) + f.nloc);+ }+ const heavy = [...weight].filter(([key, w]) => key !== "" && w > limit).sort((a, b) => b[1] - a[1] || byName(a[0], b[0]));+ for (const [key] of heavy) {+ const deeper = new Set([...split, key]);+ const parts = new Set(files.filter((f) => keyOf(f.file_path, split) === key).map((f) => keyOf(f.file_path, deeper)));+ if (parts.size > 1) return key;+ }+ return null;+}++/**+ * Each file's group: its top folder, or deeper where one folder would hold+ * most of the map. The server's `module` is the top folder alone, which on+ * Django puts nearly everything in `django` and `tests`; splitting here keeps+ * `django/db` and `django/contrib` apart.+ */+export function groupKeys(files: readonly MapFile[]): string[] {+ const split = new Set<string>();+ const limit = files.reduce((sum, f) => sum + f.nloc, 0) * SPLIT_SHARE;+ for (let i = 0; i < MAX_SPLITS; i++) {+ const key = nextSplit(files, split, limit);+ if (key === null) break;+ split.add(key);+ }+ return files.map((f) => keyOf(f.file_path, split));+}++interface Datum {+ name: string;+ file?: MapFile;+ children?: Datum[];+}++/** The two-level tree (groups, then files), laid out by d3's squarified treemap. */+function treemapOf(files: readonly MapFile[], width: number, height: number): HierarchyRectangularNode<Datum> {+ const keys = groupKeys(files);+ const groups = new Map<string, Datum[]>();+ files.forEach((file, i) => {+ const key = keys[i] ?? "";+ groups.set(key, [...(groups.get(key) ?? []), { name: file.file_path, file }]);+ });+ const data: Datum = { name: "", children: [...groups].map(([name, children]) => ({ name, children })) };+ const root = hierarchy(data)+ .sum((d) => d.file?.nloc ?? 0)+ .sort((a, b) => (b.value ?? 0) - (a.value ?? 0) || byName(a.data.name, b.data.name));+ return treemap<Datum>().tile(treemapSquarify).size([width, height])(root);+}++const rectOf = (n: HierarchyRectangularNode<Datum>): Rect => ({ x: n.x0, y: n.y0, w: n.x1 - n.x0, h: n.y1 - n.y0 });++/** Whole pixels whose centres fall in [from, to). */+function pixelSpan(from: number, to: number): [number, number] {+ return [Math.ceil(from - 0.5), Math.ceil(to - 0.5)];+}++/** The pixels a group's files may use: all of it, less a one-pixel gutter on inner edges of large groups. */+function groupInterior(rect: Rect, width: number, height: number): { x0: number; y0: number; x1: number; y1: number } {+ const [x0, x1] = pixelSpan(rect.x, rect.x + rect.w);+ const [y0, y1] = pixelSpan(rect.y, rect.y + rect.h);+ const gutter = x1 - x0 >= GUTTER_MIN && y1 - y0 >= GUTTER_MIN;+ return { x0, y0, x1: gutter && x1 < width ? x1 - 1 : x1, y1: gutter && y1 < height ? y1 - 1 : y1 };+}++function placeFile(leaf: HierarchyRectangularNode<Datum>, group: number, inner: ReturnType<typeof groupInterior>): PlacedFile {+ const file = leaf.data.file as MapFile;+ const rect = rectOf(leaf);+ const [x0, x1] = pixelSpan(rect.x, rect.x + rect.w);+ const [y0, y1] = pixelSpan(rect.y, rect.y + rect.h);+ return {+ path: file.file_path,+ score: file.score,+ nloc: file.nloc,+ group,+ rect,+ px0: Math.max(x0, inner.x0),+ py0: Math.max(y0, inner.y0),+ px1: Math.min(x1, inner.x1),+ py1: Math.min(y1, inner.y1),+ };+}++function paintFile(base: Uint32Array, width: number, f: PlacedFile): void {+ const fill = colorForScore(f.score);+ const edge = mix(fill, BLACK, 0.3);+ const edgeX = f.px1 - f.px0 >= EDGE_MIN ? f.px1 - 1 : -1;+ const edgeY = f.py1 - f.py0 >= EDGE_MIN ? f.py1 - 1 : -1;+ for (let y = f.py0; y < f.py1; y++) {+ base.fill(y === edgeY ? edge : fill, y * width + f.px0, y * width + f.px1);+ if (edgeX >= 0) base[y * width + edgeX] = edge;+ }+}++/** A label for a group `width` cells wide: the folder, its last two segments, or its last; printable ASCII only. */+export function labelText(key: string, width: number): string | null {+ const parts = key.split("/");+ const rungs = [key, parts.slice(-2).join("/"), parts[parts.length - 1] ?? ""];+ const text = rungs.find((r) => r.length > 0 && r.length <= width);+ return text !== undefined && /^[\x20-\x7e]+$/.test(text) ? text : null;+}++function labelFor(g: MapGroup, columns: number, rows: number): MapLabel | null {+ const col = Math.ceil(g.rect.x);+ const row = Math.ceil(g.rect.y / 2);+ const width = Math.min(columns, Math.floor(g.rect.x + g.rect.w)) - col - 1;+ const height = Math.floor((g.rect.y + g.rect.h) / 2) - row;+ if (g.key === "" || height < 2 || row >= rows) return null;+ const text = labelText(g.key, width);+ return text === null ? null : { row, col, text };+}++/** Group labels, largest groups first, where the group is wide and tall enough. */+function labelsFor(groups: readonly MapGroup[], columns: number, rows: number): MapLabel[] {+ return [...groups]+ .sort((a, b) => b.nloc - a.nloc)+ .map((g) => labelFor(g, columns, rows))+ .filter((l): l is MapLabel => l !== null);+}++/**+ * Lays the feed out on a `columns x rows` cell canvas. Deterministic: ties+ * break on path. Files too small for a whole pixel at this size are placed but+ * not drawn; the legend counts only what is drawn.+ */+export function layoutMap(feed: readonly MapFile[], columns: number, rows: number, caseInsensitive: boolean): MapLayout {+ const width = columns;+ const height = rows * 2;+ const root = treemapOf(+ feed.filter((f) => f.nloc > 0),+ width,+ height,+ );+ const groups: MapGroup[] = [];+ const files: PlacedFile[] = [];+ for (const node of root.children ?? []) {+ const group = groups.push({ key: node.data.name, rect: rectOf(node), nloc: node.value ?? 0 }) - 1;+ const inner = groupInterior(rectOf(node), width, height);+ for (const leaf of node.children ?? []) files.push(placeFile(leaf, group, inner));+ }+ const base = new Uint32Array(width * height).fill(GROUND);+ const drawn: number[] = [];+ const index = new Map<string, number>();+ files.forEach((f, i) => {+ if (f.px1 <= f.px0 || f.py1 <= f.py0) return;+ drawn.push(i);+ index.set(caseInsensitive ? f.path.toLowerCase() : f.path, i);+ paintFile(base, width, f);+ });+ return { columns, rows, width, height, groups, files, drawn, index, caseInsensitive, labels: labelsFor(groups, columns, rows), base };+}++/** True when a mark covers either pixel of any of the label's cells: then the whole label gives way. */+function labelCovered(label: MapLabel, marked: Uint8Array | undefined, width: number): boolean {+ if (marked === undefined) return false;+ for (let c = label.col; c < label.col + label.text.length; c++) {+ if (marked[2 * label.row * width + c] || marked[(2 * label.row + 1) * width + c]) return true;+ }+ return false;+}++/**+ * Packs pixels into the Raster's `cells`: base64 of little-endian u32 triplets+ * `[codePoint, fg, bg]`, two pixels per cell. Labels sit on cells no mark+ * covers. Uint32Array is little-endian on every platform Claude Code runs on.+ */+export function encodeCells(layout: MapLayout, pixels: Uint32Array, marked?: Uint8Array): string {+ const { columns, rows, width } = layout;+ const words = new Uint32Array(columns * rows * 3);+ for (let i = 0; i < columns * rows; i++) {+ const r = Math.floor(i / columns);+ const c = i % columns;+ words[i * 3] = UPPER_HALF;+ words[i * 3 + 1] = pixels[2 * r * width + c] ?? GROUND;+ words[i * 3 + 2] = pixels[(2 * r + 1) * width + c] ?? GROUND;+ }+ for (const label of layout.labels) {+ if (labelCovered(label, marked, width)) continue;+ for (let k = 0; k < label.text.length && label.col + k < columns; k++) {+ const o = (label.row * columns + label.col + k) * 3;+ words.set([label.text.charCodeAt(k), LABEL_FG, GROUND], o);+ }+ }+ return (new Uint8Array(words.buffer) as Uint8Array & { toBase64(): string }).toBase64();+}diff --git a/packages/claude-mod/src/views/mapPane.ts b/packages/claude-mod/src/views/mapPane.tsnew file mode 100644index 000000000..8e3d409bf--- /dev/null+++ b/packages/claude-mod/src/views/mapPane.ts@@ -0,0 +1,144 @@+/**+ * The map pane: the Raster and, outside it, the legend (bands with words,+ * Claude's marks, what the trail and the edit reached, and the scope).+ */++import { HEALTH_BAND_LABEL, HEALTH_BAND_ORDER } from "@repowise-dev/types/health";+import { BRAND, DARK_CANVAS, DARK_CANVAS_BAND } from "@repowise-dev/ui/brand";+import { fit } from "../format";+import { MAP_COPY, SCOPE_REST, callersLine, indexedPart, readsLine, scopeParts, type ScopeFacts } from "./copy";+import { box, raster, text, type Node } from "./elements";+import type { MapLayout } from "./map";+import { EDIT_TINT, type ResolvedOverlay } from "./overlay";++export const MAP_KEY = "lens-map";+const MAX_COLUMNS = 512;+const MAX_ROWS = 256;+const MIN_ROWS = 4;+const GAP = 2;+const SEP = " · ";+/** Rows of facts under the swatches: reads, the edit, and the scope over at most two. */+const FACT_ROWS = 4;+/** An inline pane grows with its tree, so it asks for a height that keeps the map squat. */+const INLINE_ROWS_PER_COLUMN = 1 / 6;+const INLINE_MAX_ROWS = 20;++interface Swatch {+ glyph: string;+ color: string;+ label: string;+}++const hexOf = (n: number): string => `#${n.toString(16).padStart(6, "0")}`;++const BAND_SWATCHES: readonly Swatch[] = [+ ...HEALTH_BAND_ORDER.map((band) => ({ glyph: "■", color: DARK_CANVAS_BAND[band], label: HEALTH_BAND_LABEL[band] })),+ { glyph: "■", color: DARK_CANVAS.nodeNeutral, label: MAP_COPY.noScore },+];+const READ: Swatch = { glyph: "□", color: BRAND.accent, label: MAP_COPY.read };+const EDITED: Swatch = { glyph: "◆", color: hexOf(EDIT_TINT), label: MAP_COPY.edited };+const IMPORTER: Swatch = { glyph: "·", color: BRAND.accent, label: MAP_COPY.importer };+const MATCH: Swatch = { glyph: "▪", color: BRAND.accent, label: MAP_COPY.match };++/** Greedy rows: items in order, a new row whenever the next would pass `columns`. */+export function packRows<T>(items: readonly T[], width: (item: T) => number, columns: number, gap: number): T[][] {+ const rows: T[][] = [];+ let used = Infinity;+ for (const item of items) {+ const w = width(item);+ const last = rows[rows.length - 1];+ if (last === undefined || used + gap + w > columns) {+ rows.push([item]);+ used = w;+ } else {+ last.push(item);+ used += gap + w;+ }+ }+ return rows;+}++const swatchWidth = (s: Swatch): number => s.label.length + 2;++/** Legend rows at this width, reserved whatever the marks: the map's height must not move under a blit. */+export function legendRows(columns: number): number {+ const swatchRows = (items: readonly Swatch[]) => packRows(items, swatchWidth, columns, GAP).length;+ return swatchRows(BAND_SWATCHES) + swatchRows([READ, EDITED, IMPORTER, MATCH]) + FACT_ROWS;+}++export interface PaneSize {+ bodyColumns: number;+ placement: "dock" | "inline";+ bodyRows: number;+}++/** The Raster's cell size for a pane: full width, and the height the pane gives (dock) or a squat share (inline). */+export function mapSize(pane: PaneSize): { columns: number; rows: number } {+ const columns = Math.max(1, Math.min(MAX_COLUMNS, pane.bodyColumns));+ const wanted =+ pane.placement === "dock"+ ? pane.bodyRows - legendRows(columns)+ : Math.min(INLINE_MAX_ROWS, Math.round(columns * INLINE_ROWS_PER_COLUMN));+ return { columns, rows: Math.max(MIN_ROWS, Math.min(MAX_ROWS, wanted)) };+}++function swatchRows(items: readonly Swatch[], columns: number): Node[] {+ return packRows(items, swatchWidth, columns, GAP).map((row) =>+ box(+ { flexDirection: "row", columnGap: GAP },+ row.map((s) => box({ flexDirection: "row" }, [text(s.glyph, { color: s.color }), text(` ${s.label}`, { dimColor: true })])),+ ),+ );+}++function marksOf(resolved: ResolvedOverlay): Swatch[] {+ const marks = [READ, EDITED];+ if (resolved.overlay.callers.length > 0) marks.push(IMPORTER);+ if (resolved.overlay.hits.length > 0) marks.push(MATCH);+ return marks;+}++/**+ * Scope parts joined with ` · `, wrapped onto at most two rows. When they+ * need more, the parts that do not change the reading leave first (the "rest"+ * note, then the index age), so the counts and the cap clause survive.+ */+function scopeRows(scope: ScopeFacts, columns: number): string[] {+ const rows = (parts: readonly string[]) => packRows(parts, (p) => p.length, columns, SEP.length);+ let parts = scopeParts(scope);+ for (const optional of [SCOPE_REST, scope.indexed === null ? null : indexedPart(scope.indexed)]) {+ if (rows(parts).length <= 2) break;+ parts = parts.filter((p) => p !== optional);+ }+ return rows(parts)+ .slice(0, 2)+ .map((row) => row.join(SEP));+}++function factRows(resolved: ResolvedOverlay, scope: ScopeFacts, columns: number): string[] {+ const facts: string[] = [];+ const reads = readsLine(resolved.reads, resolved.matched, columns);+ if (reads !== null) facts.push(reads);+ if (resolved.edit !== null) facts.push(callersLine(resolved.edit.name, resolved.edit.callers, resolved.edit.notDrawn, columns));+ return [...facts, ...scopeRows(scope, columns)];+}++export function legendView(resolved: ResolvedOverlay, scope: ScopeFacts, columns: number): Node[] {+ return [+ ...swatchRows(BAND_SWATCHES, columns),+ ...swatchRows(marksOf(resolved), columns),+ ...factRows(resolved, scope, columns).map((f) => text(fit(f, columns), { dimColor: true, wrap: "truncate-end" })),+ ];+}++export function mapPaneView(layout: MapLayout, cells: string, resolved: ResolvedOverlay, scope: ScopeFacts): Node {+ return box({ key: "lens-map-pane", flexDirection: "column" }, [+ raster({ key: MAP_KEY, columns: layout.columns, rows: layout.rows, cells }),+ ...legendView(resolved, scope, layout.columns),+ ]);+}++/** The pane when there is no map to draw: one line saying why. */+export function noticeView(line: string, columns: number): Node {+ return box({ key: "lens-map-pane", flexDirection: "column" }, [text(fit(line, columns), { dimColor: true, wrap: "truncate-end" })]);+}diff --git a/packages/claude-mod/src/views/mapSvg.ts b/packages/claude-mod/src/views/mapSvg.tsnew file mode 100644index 000000000..65eb91d9b--- /dev/null+++ b/packages/claude-mod/src/views/mapSvg.ts@@ -0,0 +1,68 @@+/**+ * The map for the desktop app, which draws SVG and not terminal cells: the+ * same layout and the same resting frame (bands, Claude's marks, labels),+ * one SVG unit per map pixel, each row's runs of one color drawn as a+ * stroked line. Pure. No animation: blits are terminal only.+ */++import { fit } from "../format";+import { MAP_COPY, mapAlt, type ScopeFacts } from "./copy";+import { box, svg, text, type Node } from "./elements";+import { GROUND, LABEL_FG, type MapLayout } from "./map";+import { legendView } from "./mapPane";+import { framePixels, type ResolvedOverlay } from "./overlay";++/** The Svg element's own limit. */+export const SVG_CHARS = 131_072;+/** Caps that keep a busy Django map (200 reads marked) near 80,000 characters, under the limit. */+const DESKTOP_MAX_COLUMNS = 160;+const DESKTOP_MAX_ROWS = 45;++const color = (c: number): string => `#${c.toString(16).padStart(6, "0")}`;+const escape = (s: string): string => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");++/** The Svg's cell size for a desktop pane: the terminal size, capped. */+export function desktopSize(size: { columns: number; rows: number }): { columns: number; rows: number } {+ return { columns: Math.min(DESKTOP_MAX_COLUMNS, size.columns), rows: Math.min(DESKTOP_MAX_ROWS, size.rows) };+}++/** The resting frame as SVG: per color, one path of horizontal runs (`M x y.5h n`). */+export function mapSvg(layout: MapLayout, resolved: ResolvedOverlay): string {+ const { width, height } = layout;+ const { pixels } = framePixels(layout, resolved.overlay);+ const runs = new Map<number, string[]>();+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; ) {+ const c = pixels[y * width + x] ?? GROUND;+ let end = x + 1;+ while (end < width && pixels[y * width + end] === c) end++;+ if (c !== GROUND) {+ const list = runs.get(c) ?? [];+ list.push(`M${x} ${y}.5h${end - x}`);+ runs.set(c, list);+ }+ x = end;+ }+ }+ const paths = [...runs].map(([c, d]) => `<path stroke="${color(c)}" d="${d.join("")}"/>`).join("");+ // A label sits on its cell: one unit across, two down.+ const labels = layout.labels+ .map((l) => `<text x="${l.col}" y="${2 * l.row + 1.6}">${escape(l.text)}</text>`)+ .join("");+ return (+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" shape-rendering="crispEdges">` ++ `<rect width="${width}" height="${height}" fill="${color(GROUND)}"/>` ++ `<g stroke-width="1" fill="none">${paths}</g>` ++ `<g font-family="monospace" font-size="1.7" fill="${color(LABEL_FG)}">${labels}</g></svg>`+ );+}++/** The desktop pane: the drawing and the same legend as the terminal's; a drawing over the limit says so instead. */+export function svgPaneView(layout: MapLayout, resolved: ResolvedOverlay, scope: ScopeFacts): Node {+ const source = mapSvg(layout, resolved);+ const picture =+ source.length <= SVG_CHARS+ ? svg(source, mapAlt(layout.drawn.length))+ : text(fit(MAP_COPY.tooLarge, layout.columns), { dimColor: true, wrap: "truncate-end" });+ return box({ key: "lens-map-pane", flexDirection: "column" }, [picture, ...legendView(resolved, scope, layout.columns)]);+}diff --git a/packages/claude-mod/src/views/margin.ts b/packages/claude-mod/src/views/margin.tsnew file mode 100644index 000000000..55ef98028--- /dev/null+++ b/packages/claude-mod/src/views/margin.ts@@ -0,0 +1,19 @@+/**+ * Margin notes under an Edit or Write row: at most two dim lines, only for+ * what the augment hook flagged on that call. Lens adds no thresholds.+ */++import type { MarginNote } from "../model/session";+import { marginLine } from "./copy";+import { box, text, type Node } from "./elements";++export const MAX_MARGIN_LINES = 2;++/** null means draw nothing: pass the row on. */+export function marginView(notes: readonly MarginNote[] | undefined): Node | null {+ if (notes === undefined || notes.length === 0) return null;+ return box(+ { key: "lens-margin", flexDirection: "column" },+ notes.slice(0, MAX_MARGIN_LINES).map((n) => text(` ${marginLine(n)}`, { dimColor: true, wrap: "truncate-end" })),+ );+}diff --git a/packages/claude-mod/src/views/overlay.ts b/packages/claude-mod/src/views/overlay.tsnew file mode 100644index 000000000..e8c681ed2--- /dev/null+++ b/packages/claude-mod/src/views/overlay.ts@@ -0,0 +1,223 @@+/**+ * Claude's marks on the map, as pixel layers over the base: the dotted path+ * joining reads, search matches (a flash that settles to a faint tint), read+ * outlines, the edited file, and the ripple with its importers. Pure.+ *+ * Ceiling: a mark reads as its own shape only on files of at least 3x3 pixels;+ * smaller files show a mark as a solid orange (read) or pale orange (edited) dot.+ */++import { relativeTo } from "../model/events";+import type { Callers, TrailState } from "../model/trail";+import { ACCENT, GROUND, encodeCells, mix, type MapLayout, type PlacedFile } from "./map";++/** What the trail and the ripple mark, as indices into `layout.files`. */+export interface Overlay {+ reads: number[];+ hits: number[];+ edited: number | null;+ callers: number[];+}++/** The overlay plus the counts the legend states beside it. */+export interface ResolvedOverlay {+ overlay: Overlay;+ reads: { count: number; capped: boolean; notDrawn: number };+ /** Files the latest search matched, drawn or not; null before any search. */+ matched: number | null;+ /** null while no edit has been seen. */+ edit: { name: string; callers: Callers | null; notDrawn: number } | null;+}++/** One step of an animation, `t` from 0 to 1; t = 1 is the resting frame. */+export type Anim = { kind: "flash"; t: number } | { kind: "ripple"; t: number };++export const EDIT_TINT = mix(ACCENT, 0xffffff, 0.45);+const READ_DIM = 0.4;+const PATH_AMOUNT = 0.85;+const MATCH_FLASH = 0.85;+const MATCH_REST = 0.25;+const RING_AMOUNT = 0.5;+const SMALL = 3;++/** A drawn file for a repo-relative path. */+function lookup(layout: MapLayout, rel: string): number | undefined {+ return layout.index.get(layout.caseInsensitive ? rel.toLowerCase() : rel);+}++/** A drawn file for an absolute path under `root`. */+function locate(layout: MapLayout, abs: string, root: string): number | undefined {+ const rel = relativeTo(abs, root, layout.caseInsensitive);+ return rel === null ? undefined : lookup(layout, rel);+}++function split<T>(items: readonly T[], find: (item: T) => number | undefined): { found: number[]; missing: number } {+ const found: number[] = [];+ for (const item of items) {+ const i = find(item);+ if (i !== undefined) found.push(i);+ }+ return { found, missing: items.length - found.length };+}++/**+ * Maps the trail's absolute paths onto drawn files under `repoRoot`. A path+ * outside the repo, outside the feed, or too small to draw is "not drawn".+ */+export function resolveOverlay(layout: MapLayout, trail: TrailState, repoRoot: string): ResolvedOverlay {+ const reads = split(trail.reads, (p) => locate(layout, p, repoRoot));+ const hits = split(trail.hits, (p) => locate(layout, p, repoRoot)).found;+ const callers = split(trail.callers?.status === "ready" ? trail.callers.paths : [], (p) => lookup(layout, p));+ const edited = trail.edit === null ? null : (locate(layout, trail.edit, repoRoot) ?? null);+ const edit =+ trail.edit === null+ ? null+ : { name: trail.edit.slice(trail.edit.lastIndexOf("/") + 1), callers: trail.callers, notDrawn: callers.missing };+ return {+ overlay: { reads: reads.found, hits, edited, callers: callers.found },+ reads: { count: trail.reads.length, capped: trail.readsCapped, notDrawn: reads.missing },+ matched: trail.searches === 0 ? null : trail.hits.length,+ edit,+ };+}++function center(f: PlacedFile): [number, number] {+ return [Math.floor((f.px0 + f.px1 - 1) / 2), Math.floor((f.py0 + f.py1 - 1) / 2)];+}++function distance(a: PlacedFile, b: PlacedFile): number {+ const [ax, ay] = center(a);+ const [bx, by] = center(b);+ return Math.hypot(ax - bx, ay - by);+}++/** How far the ripple travels: just past its farthest importer; 0 when there is nothing to ripple to. */+export function rippleRadius(layout: MapLayout, overlay: Overlay): number {+ const origin = overlay.edited === null ? undefined : layout.files[overlay.edited];+ if (!origin || overlay.callers.length === 0) return 0;+ return Math.max(...overlay.callers.map((i) => distance(origin, layout.files[i] as PlacedFile))) + 3;+}++interface Paint {+ layout: MapLayout;+ px: Uint32Array;+ marked: Uint8Array;+}++function inside(layout: MapLayout, x: number, y: number): boolean {+ return x >= 0 && y >= 0 && x < layout.width && y < layout.height;+}++function set(p: Paint, x: number, y: number, color: number): void {+ if (!inside(p.layout, x, y)) return;+ const width = p.layout.width;+ p.px[y * width + x] = color;+ p.marked[y * width + x] = 1;+}++function fillFile(p: Paint, f: PlacedFile, color: (current: number) => number): void {+ const w = p.layout.width;+ for (let y = f.py0; y < f.py1; y++) for (let x = f.px0; x < f.px1; x++) set(p, x, y, color(p.px[y * w + x] ?? GROUND));+}++function outlineFile(p: Paint, f: PlacedFile, color: number): void {+ for (let x = f.px0; x < f.px1; x++) {+ set(p, x, f.py0, color);+ set(p, x, f.py1 - 1, color);+ }+ for (let y = f.py0; y < f.py1; y++) {+ set(p, f.px0, y, color);+ set(p, f.px1 - 1, y, color);+ }+}++const isSmall = (f: PlacedFile): boolean => f.px1 - f.px0 < SMALL || f.py1 - f.py0 < SMALL;++/** Every third pixel along the straight line between two consecutive reads. */+function paintPath(p: Paint, overlay: Overlay): void {+ const files = p.layout.files;+ for (let k = 1; k < overlay.reads.length; k++) {+ const [ax, ay] = center(files[overlay.reads[k - 1] as number] as PlacedFile);+ const [bx, by] = center(files[overlay.reads[k] as number] as PlacedFile);+ const steps = Math.max(Math.abs(bx - ax), Math.abs(by - ay));+ for (let s = 1; s < steps; s += 3) {+ const x = Math.round(ax + ((bx - ax) * s) / steps);+ const y = Math.round(ay + ((by - ay) * s) / steps);+ set(p, x, y, mix(p.px[y * p.layout.width + x] ?? GROUND, ACCENT, PATH_AMOUNT));+ }+ }+}++function paintHits(p: Paint, overlay: Overlay, amount: number): void {+ for (const i of overlay.hits) fillFile(p, p.layout.files[i] as PlacedFile, (c) => mix(c, ACCENT, amount));+}++/** A read: its interior dimmed so the orange outline holds against warm bands. */+function paintReads(p: Paint, overlay: Overlay): void {+ for (const i of overlay.reads) {+ const f = p.layout.files[i] as PlacedFile;+ fillFile(p, f, (c) => mix(c, 0x000000, READ_DIM));+ outlineFile(p, f, ACCENT);+ }+}++/** The edited file: pale orange inside an orange outline (a small one is all pale, unlike a small read). */+function paintEdited(p: Paint, f: PlacedFile): void {+ fillFile(p, f, () => EDIT_TINT);+ if (!isSmall(f)) outlineFile(p, f, ACCENT);+}++function paintRing(p: Paint, origin: PlacedFile, reach: number): void {+ const [ox, oy] = center(origin);+ const { width, height } = p.layout;+ for (let y = Math.max(0, Math.floor(oy - reach)); y <= Math.min(height - 1, oy + reach); y++) {+ for (let x = Math.max(0, Math.floor(ox - reach)); x <= Math.min(width - 1, ox + reach); x++) {+ const d = Math.hypot(x - ox, y - oy);+ if (d <= reach && d > reach - 2) set(p, x, y, mix(p.px[y * width + x] ?? GROUND, ACCENT, RING_AMOUNT));+ }+ }+}++/** An importer: an orange pixel with a dark one beside it in the same cell, so it holds on any band. */+function paintCallers(p: Paint, overlay: Overlay, origin: PlacedFile | undefined, reach: number): void {+ for (const i of overlay.callers) {+ const f = p.layout.files[i] as PlacedFile;+ if (origin !== undefined && distance(origin, f) > reach) continue;+ const [x, y] = center(f);+ set(p, x, y, ACCENT);+ set(p, x, y ^ 1, GROUND);+ }+}++function matchAmount(anim: Anim | undefined): number {+ return anim?.kind === "flash" ? MATCH_REST + (MATCH_FLASH - MATCH_REST) * (1 - anim.t) : MATCH_REST;+}++function rippleReach(layout: MapLayout, overlay: Overlay, anim: Anim | undefined): number {+ return anim?.kind === "ripple" && anim.t < 1 ? rippleRadius(layout, overlay) * anim.t : Infinity;+}++/** Map pixels for one frame: the base map with the trail, the edit and the ripple painted on. */+export function framePixels(layout: MapLayout, overlay: Overlay, anim?: Anim): { pixels: Uint32Array; marked: Uint8Array } {+ const p: Paint = { layout, px: layout.base.slice(), marked: new Uint8Array(layout.width * layout.height) };+ const origin = overlay.edited === null ? undefined : layout.files[overlay.edited];+ const reach = rippleReach(layout, overlay, anim);+ paintPath(p, overlay);+ paintHits(p, overlay, matchAmount(anim));+ paintReads(p, overlay);+ if (origin !== undefined) paintEdited(p, origin);+ if (origin !== undefined && reach < Infinity) paintRing(p, origin, reach);+ paintCallers(p, overlay, origin, reach);+ return { pixels: p.px, marked: p.marked };+}++/** One frame's cells: the resting frame without `anim`. */+export function frameCells(layout: MapLayout, overlay: Overlay, anim?: Anim): string {+ const { pixels, marked } = framePixels(layout, overlay, anim);+ return encodeCells(layout, pixels, marked);+}++/** Animation lengths; frames go out every `FRAME_MS`, under the surface's 30 per second. */+export const FRAME_MS = 40;+export const FLASH_MS = 600;+export const RIPPLE_MS = 1_200;diff --git a/packages/claude-mod/src/views/pane.ts b/packages/claude-mod/src/views/pane.tsnew file mode 100644index 000000000..3a430cde4--- /dev/null+++ b/packages/claude-mod/src/views/pane.ts@@ -0,0 +1,144 @@+/**+ * The `/lens` pane around the map: a row of tabs (Map, Ask, Recap), the Ask+ * field with the last reply, and the session recap. Every recap figure is+ * read from the session model as it stands; nothing is re-derived.+ */++import { fit } from "../format";+import type { PaneTab } from "../model/ask";+import { testsToRun, type ChangeRisk } from "../model/review";+import { surfacedDecisions, type SessionState } from "../model/session";+import { replyMarkdown } from "./answer";+import {+ PANE_COPY,+ RECAP_COPY,+ askFailedLine,+ askingLine,+ decisionsSurfaced,+ filesTouched,+ findingsCounts,+ overlapLine,+ recapFooter,+ savingsLine,+ testsToRunCount,+} from "./copy";+import { box, button, input, markdown, text, type Node } from "./elements";+import { health, overlap } from "./review";++export const TABS: readonly PaneTab[] = ["map", "ask", "recap"];+/** Button keys of the tabs; register.ts maps each to its tab. */+export const TAB_PRESS: Record<PaneTab, string> = { map: "lens-tab-map", ask: "lens-tab-ask", recap: "lens-tab-recap" };+export const ASK_KEY = "lens-ask";+/** Rows the tab row takes above each tab's body. */+export const TAB_ROWS = 1;++/** `1: Map 2: Ask 3: Recap`, the shown one at full strength. */+export function tabsView(current: PaneTab): Node {+ return box(+ { key: "lens-tabs", flexDirection: "row", columnGap: 2 },+ TABS.map((tab, i) => button(TAB_PRESS[tab], String(i + 1), PANE_COPY.tabs[tab], tab !== current)),+ );+}++const dim = (line: string, columns: number): Node => text(fit(line, columns), { dimColor: true, wrap: "truncate-end" });++function askStatus(state: SessionState, columns: number): Node[] {+ const ask = state.ask;+ switch (ask.phase) {+ case "idle":+ return [dim(PANE_COPY.askIdle, columns)];+ case "asking":+ return [+ dim(`> ${ask.question}`, columns),+ dim(askingLine(ask.tool), columns),+ ...(ask.busy ? [dim(PANE_COPY.askBusy, columns)] : []),+ ];+ case "failed":+ return [dim(`> ${ask.question}`, columns), dim(askFailedLine(ask.message), columns)];+ case "answered":+ return [markdown(replyMarkdown(ask.question, ask.answer))];+ }+}++/**+ * The field (pre-filled when `Why` opened the tab) and the last reply. Once a+ * question is asked no value is drawn, so the field keeps what was typed and+ * a follow-up can edit the last question.+ */+export function askView(state: SessionState, columns: number): Node {+ const field = input({+ key: ASK_KEY,+ label: PANE_COPY.askLabel,+ placeholder: PANE_COPY.askPlaceholder,+ submitLabel: PANE_COPY.askSubmit,+ autoFocus: true,+ ...(state.pane.draft === "" ? {} : { value: state.pane.draft }),+ });+ return box({ key: "lens-ask-tab", flexDirection: "column" }, [field, ...askStatus(state, columns)]);+}++/** What the trail counted: files read or edited, and whether older ones were dropped. */+export interface TrailCounts {+ count: number;+ capped: boolean;+}++/** A label and its value, or a dim sub-head over the rows that follow. */+export type RecapRow = [label: string, value: string] | string;++function overlapWords(risk: ChangeRisk): string {+ const shared = overlap(risk);+ if (shared !== null) return overlapLine(shared.branches, shared.files, shared.more);+ return risk.branch_overlap === undefined ? RECAP_COPY.notReported : RECAP_COPY.noOverlap;+}++function reviewRows(state: SessionState): RecapRow[] {+ const risk = state.lastReview;+ if (risk === null) return [[RECAP_COPY.review, RECAP_COPY.noReview]];+ const hd = risk.health_delta;+ const compared = hd !== undefined && (hd.status === "available" || hd.status === "partial");+ const tests = testsToRun(risk);+ return [+ RECAP_COPY.fromReview,+ [RECAP_COPY.health, health(risk).words],+ [RECAP_COPY.findings, compared ? findingsCounts(hd.resolved, hd.findings_total) : RECAP_COPY.notCompared],+ [RECAP_COPY.tests, tests === null ? RECAP_COPY.noTests : testsToRunCount(tests)],+ [RECAP_COPY.overlap, overlapWords(risk)],+ ];+}++function savedRow(state: SessionState): string {+ if (state.savings !== null) return savingsLine(state.savings, Number.POSITIVE_INFINITY);+ return state.mode === "full" ? RECAP_COPY.noSavings : RECAP_COPY.savingsNeedServer;+}++/** The recap in the order drawn. */+export function recapRows(state: SessionState, touched: TrailCounts): RecapRow[] {+ const decisions = surfacedDecisions(state).map((d) => d.title);+ return [+ [RECAP_COPY.files, filesTouched(state.touched.length, touched)],+ ...reviewRows(state),+ [RECAP_COPY.saved, savedRow(state)],+ [RECAP_COPY.decisions, decisions.length === 0 ? RECAP_COPY.noDecisions : decisionsSurfaced(decisions)],+ ];+}++/** Labels in a dim column wide enough for the longest, values beside them. */+export function recapView(state: SessionState, touched: TrailCounts, columns: number): Node {+ const rows = recapRows(state, touched);+ const width = Math.max(...rows.map((r) => (typeof r === "string" ? 0 : r[0].length))) + 2;+ const drawn = rows.map((r) =>+ typeof r === "string"+ ? dim(r, columns)+ : box({ flexDirection: "row" }, [+ text(r[0].padEnd(width), { dimColor: true }),+ text(fit(r[1], Math.max(1, columns - width)), { wrap: "truncate-end" }),+ ]),+ );+ return box({ key: "lens-recap", flexDirection: "column" }, [...drawn, dim(recapFooter(state.modelAsks), columns)]);+}++/** The pane: the tabs, then the shown tab's body. */+export function paneView(tab: PaneTab, body: Node): Node {+ return box({ key: "lens-pane", flexDirection: "column" }, [tabsView(tab), body]);+}diff --git a/packages/claude-mod/src/views/review.ts b/packages/claude-mod/src/views/review.tsnew file mode 100644index 000000000..ef87fb3a5--- /dev/null+++ b/packages/claude-mod/src/views/review.ts@@ -0,0 +1,243 @@+/**+ * The change review: a card shown beneath Claude's answer and one band row with+ * the health word in color and the buttons. Built only from what+ * `get_change_risk` returned.+ *+ * The engine draws the text a `turn.complete` hook returns as one row (a line+ * break is stored as U+FFFD), so the card is one row of segments, plain text+ * whose words carry the meaning.+ */++import { DARK } from "@repowise-dev/ui/brand";+import { fit } from "../format";+import { emptyDiff, reviewable, testsToRun, type ChangeRisk, type ReviewOutcome } from "../model/review";+import {+ DETAILS,+ HEALTH_NOT_REPORTED,+ REVIEW_TIMED_OUT,+ REVIEWING,+ RUN_TESTS,+ WHY,+ diffShape,+ directiveLines,+ findingLine,+ healthImproved,+ improvedShort,+ newFindings,+ NO_NEW_FINDINGS,+ notCompared,+ PARTLY_COMPARED,+ moreFindings,+ noNewFindings,+ overlapLine,+ overlapShort,+ partialScope,+ resolvedToo,+ reviewFailed,+ reviewScope,+ runTestsPrompt,+ testsLine,+} from "./copy";+import { box, button, text, type Node } from "./elements";++/** Button keys; register.ts maps each to what its press runs. */+export const PRESS = { tests: "lens-review-tests", why: "lens-review-why", details: "lens-review-details" } as const;++/** Green, amber and red mean health and nothing else (dark tokens: terminals are dark). */+type HealthColor = typeof DARK.success | typeof DARK.warning | typeof DARK.error;++export interface HealthWords {+ /** The card's sentence. */+ words: string;+ /** The band's few words. */+ short: string;+ color?: HealthColor;+}++type Directive = NonNullable<ChangeRisk["directive"]>;+type Delta = NonNullable<ChangeRisk["health_delta"]>;++/** Delta statuses where both sides were compared, fully or in part. */+const COMPARED = new Set(["available", "partial"]);++const NOT_REPORTED: HealthWords = { words: HEALTH_NOT_REPORTED, short: HEALTH_NOT_REPORTED };++function notComparedWords(hd: Delta): HealthWords {+ return { words: notCompared(hd.explanation.replace(/\.$/, "")), short: notCompared("") };+}++function clearWords(hd: Delta): HealthWords {+ if (hd.resolved === 0) return { words: noNewFindings(hd.scope?.analyzed ?? 0), short: NO_NEW_FINDINGS };+ return { words: healthImproved(hd.resolved), short: improvedShort(hd.resolved), color: DARK.success };+}++/** New findings by the directive's verdict; an unknown verdict is a partial comparison. */+const FINDINGS_TONE: Record<string, { required: boolean; color: HealthColor } | undefined> = {+ review_required: { required: true, color: DARK.error },+ review_recommended: { required: false, color: DARK.warning },+};++function findingsWords(d: Directive, hd: Delta): HealthWords {+ const headline = d.headline.replace(/\.$/, "");+ const words = hd.resolved > 0 ? `${headline}; ${resolvedToo(hd.resolved)}` : headline;+ const tone = FINDINGS_TONE[d.status];+ if (tone === undefined) return { words, short: PARTLY_COMPARED };+ return { words, short: newFindings(hd.findings_total, tone.required), color: tone.color };+}++export function health(risk: ChangeRisk): HealthWords {+ const d = risk.directive;+ const hd = risk.health_delta;+ if (d === undefined || hd === undefined) return NOT_REPORTED;+ if (!COMPARED.has(hd.status)) return notComparedWords(hd);+ if (d.status === "clear_in_analyzed_scope") return clearWords(hd);+ return findingsWords(d, hd);+}++export function overlap(risk: ChangeRisk): { branches: string[]; files: string[]; more: boolean } | null {+ const block = risk.branch_overlap;+ const branches = block?.branches ?? [];+ if (branches.length === 0) return null;+ const files = [...new Set(branches.flatMap((b) => (b.files ?? []).map((f) => f.file)))];+ return { branches: branches.map((b) => b.branch), files, more: block?.truncated === true };+}++function isClear(risk: ChangeRisk): boolean {+ return risk.directive?.status === "clear_in_analyzed_scope";+}++function header(risk: ChangeRisk, changed: number | null): string {+ return `Change review (${reviewScope(risk.ref ?? "working tree", risk.working_tree !== false, changed)})`;+}++/** Each listed finding, then a count of the ones the server left out. */+function findingSegments(hd: Delta | undefined): string[] {+ const rows = hd?.top_findings ?? [];+ const segments = rows.map(findingLine);+ const more = (hd?.findings_total ?? 0) - rows.length;+ if (more > 0) segments.push(moreFindings(more));+ return segments;+}++/** The scope line, for a partial comparison only. */+function scopeSegments(hd: Delta | undefined): string[] {+ if (hd?.status !== "partial" || hd.scope === undefined) return [];+ return [partialScope(hd.scope.analyzed, hd.scope.changed, hd.skipped?.by_reason ?? {})];+}++function testSegments(risk: ChangeRisk): string[] {+ const tests = testsToRun(risk);+ return tests === null ? [] : [testsLine(tests)];+}++function overlapSegments(risk: ChangeRisk): string[] {+ const shared = overlap(risk);+ return shared === null ? [] : [`Branches: ${overlapLine(shared.branches, shared.files, shared.more)}`];+}++function cardSegments(risk: ChangeRisk): string[] {+ // Nothing to act on and nobody else in these files: the short form.+ if (isClear(risk) && overlap(risk) === null) return [header(risk, null), `health: ${health(risk).words}`];+ const hd = risk.health_delta;+ return [+ header(risk, hd?.scope?.changed ?? null),+ `Health: ${health(risk).words}`,+ ...findingSegments(hd),+ ...scopeSegments(hd),+ diffShape(risk.risk_percentile),+ ...testSegments(risk),+ ...overlapSegments(risk),+ ];+}++function doneText(risk: ChangeRisk): string | null {+ if (risk.error !== undefined) return reviewFailed(risk.error);+ // An empty diff has nothing to say (its percentile would rank a diff of nothing).+ if (emptyDiff(risk)) return null;+ return cardSegments(risk).join(" · ");+}++/** What shows beneath Claude's answer, as one row; null while there is nothing to say. */+export function reviewText(outcome: ReviewOutcome): string | null {+ switch (outcome.phase) {+ case "none":+ case "reviewing":+ return null;+ case "failed":+ return outcome.reason === "timeout" ? REVIEW_TIMED_OUT : reviewFailed(outcome.message);+ case "done":+ return doneText(outcome.risk);+ }+}++/** `1: Run tests`, `2: Why` (only when a decision governs an edited file) and `3: Details`. */+function buttons(risk: ChangeRisk, decision: string | null): Node[] {+ const out: Node[] = [];+ if (testsToRun(risk) !== null) out.push(button(PRESS.tests, "1", RUN_TESTS));+ if (decision !== null) out.push(button(PRESS.why, "2", WHY));+ if (risk.directive !== undefined) out.push(button(PRESS.details, "3", DETAILS));+ return out;+}++const GAP = 2;++/** Cells the buttons take: a plain Button draws as `1: label`, then the gap. */+function buttonCells(pressable: Node[]): number {+ return pressable.reduce((n, b) => n + (b.type === "Button" ? b.props.label.length + 3 : 0) + GAP, 0);+}++/** A review the band has nothing to add to: clear, no tests to run, nobody else in these files, no decision. */+function quietInBand(risk: ChangeRisk, decision: string | null): boolean {+ return isClear(risk) && testsToRun(risk) === null && overlap(risk) === null && decision === null;+}++/** The health word in its color, then the overlap words when they fit in `room`. */+function summaryParts(risk: ChangeRisk, room: number): Node[] {+ const h = health(risk);+ const words = fit(`review · health: ${h.short}`, room);+ const parts = [text(words, h.color === undefined ? { dimColor: true } : { color: h.color })];+ const shared = overlap(risk);+ const tail = shared === null ? "" : ` · ${overlapShort(shared.branches.length)}`;+ if (tail !== "" && room - words.length >= tail.length) parts.push(text(tail, { dimColor: true }));+ return parts;+}++function resultRow(risk: ChangeRisk, columns: number, decision: string | null): Node | null {+ if (!reviewable(risk) || quietInBand(risk, decision)) return null;+ const pressable = buttons(risk, decision);+ const room = Math.max(0, columns - buttonCells(pressable));+ return box({ key: "lens-review", flexDirection: "row", columnGap: GAP }, [+ box({ flexDirection: "row" }, summaryParts(risk, room)),+ ...pressable,+ ]);+}++/** The band's review row: a placeholder while the review runs, then the health word and the buttons. */+export function reviewBandRow(outcome: ReviewOutcome, columns: number, decision: string | null = null): Node | null {+ if (outcome.phase === "reviewing") return text(fit(REVIEWING, columns), { dimColor: true, wrap: "truncate-end" });+ return outcome.phase === "done" ? resultRow(outcome.risk, columns, decision) : null;+}++/** The full directive, as `Details` prints it, one transcript row per line; null when the result carries none. */+export function directiveRows(outcome: ReviewOutcome): string[] | null {+ if (outcome.phase !== "done" || outcome.risk.directive === undefined) return null;+ return directiveLines(outcome.risk.directive);+}++/** The prompt `Run tests` submits; null when the review names no tests. */+export function runTestsText(outcome: ReviewOutcome): string | null {+ if (outcome.phase !== "done") return null;+ const tests = testsToRun(outcome.risk);+ return tests === null ? null : runTestsPrompt(tests);+}++/**+ * What `turn.complete` returns with the card: the card beneath the answer, or+ * beneath what a hook below already put there. A result with no text passes on.+ */+export function withCard(result: unknown, answer: string, card: string): unknown {+ if (typeof result !== "object" || result === null) return result;+ const r = result as { text?: unknown };+ if (typeof r.text !== "string") return result;+ return { ...r, text: r.text === answer ? card : `${r.text} · ${card}` };+}diff --git a/packages/claude-mod/src/views/spinner.ts b/packages/claude-mod/src/views/spinner.tsnew file mode 100644index 000000000..e9bb5257c--- /dev/null+++ b/packages/claude-mod/src/views/spinner.ts@@ -0,0 +1,14 @@+/**+ * The spinner suffix: while a file tool runs on a file whose context has+ * already landed, name the file and its reach. Never waits for a fetch.+ */++import type { SessionState } from "../model/session";+import { spinnerLine } from "./copy";++/** null leaves the engine's suffix as it is. */+export function spinnerSuffix(state: SessionState): string | null {+ if (state.running === null) return null;+ const ctx = state.contexts[state.running.file];+ return ctx === undefined ? null : spinnerLine(state.running.file, ctx);+}diff --git a/packages/claude-mod/src/views/squeeze.ts b/packages/claude-mod/src/views/squeeze.tsnew file mode 100644index 000000000..f383bdc00--- /dev/null+++ b/packages/claude-mod/src/views/squeeze.ts@@ -0,0 +1,21 @@+/**+ * The squeeze row under a Bash result that `repowise distill` shortened: a+ * bar for the share kept, then the row's words. Parsing lives in+ * model/squeeze.ts.+ */++import type { Squeeze } from "../model/squeeze";+import { squeezeLine } from "./copy";+import { text, type Node } from "./elements";++export const BAR_CELLS = 12;++/** Filled cells for what was kept, at least one so a deep cut still shows a mark. */+export function squeezeBar(s: Squeeze, cells = BAR_CELLS): string {+ const filled = Math.min(cells, Math.max(1, Math.round((cells * s.keptLines) / Math.max(1, s.originalLines))));+ return `${"█".repeat(filled)}${"░".repeat(cells - filled)}`;+}++export function squeezeView(s: Squeeze): Node {+ return text(`${squeezeBar(s)} ${squeezeLine(s)}`, { dimColor: true, wrap: "truncate-end" });+}diff --git a/packages/claude-mod/test/band.test.ts b/packages/claude-mod/test/band.test.tsnew file mode 100644index 000000000..f8ec2e359--- /dev/null+++ b/packages/claude-mod/test/band.test.ts@@ -0,0 +1,193 @@+import { describe, expect, it } from "vitest";+import type { Savings } from "@repowise-dev/api-client/costs";+import { countOf, fit } from "../src/format";+import { savingsSince, savingsTotals } from "../src/model/events";+import { initialSession, reduce, type SavingsDelta, type SessionState } from "../src/model/session";+import { bandRows, bandView, MAX_BAND_ROWS } from "../src/views/band";+import { HINTS, freshnessLine, savingsLine } from "../src/views/copy";+import { box, materialize, text, type Node } from "../src/views/elements";+import { fixture } from "./fake-host";++const at = (columns: number) => ({ columns, hasSurvey: false });++function lines(node: Node | null): string[] {+ if (node === null) return [];+ if (node.type === "Text") return node.children;+ if (node.type === "Button") return [node.props.label];+ if (node.type !== "Box") return [];+ return node.children.flatMap(lines);+}++const behind: SessionState = { ...initialSession, mode: "full", freshness: { changedFiles: 14 } };+const hinted: SessionState = { ...initialSession, mode: "lite", hint: "no-server", hintsShown: ["no-server"] };+const both: SessionState = { ...hinted, freshness: { changedFiles: 1 } };++describe("band", () => {+ it("draws nothing at rest", () => {+ expect(bandView(initialSession, at(100))).toBeNull();+ expect(bandView({ ...initialSession, mode: "full" }, at(100))).toBeNull();+ });++ it("draws nothing once a hint has retired and the index is current", () => {+ expect(bandView({ ...hinted, hint: null }, at(100))).toBeNull();+ });++ it("shows the freshness exception", () => {+ expect(lines(bandView(behind, at(100)))).toEqual(["index behind HEAD (14 files changed) · repowise update"]);+ });++ it.each(Object.entries(HINTS))("shows the %s hint as copyable text", (kind, copy) => {+ const s = { ...initialSession, hint: kind, hintsShown: [kind] } as SessionState;+ expect(lines(bandView(s, at(180)))).toEqual([copy]);+ });++ it("puts the hint above freshness, never more than two rows", () => {+ expect(lines(bandView(both, at(180)))).toEqual([HINTS["no-server"], "index behind HEAD (1 file changed) · repowise update"]);+ expect(bandRows(both).length).toBeLessThanOrEqual(MAX_BAND_ROWS);+ });++ it("yields to a survey", () => {+ expect(bandView(both, { columns: 100, hasSurvey: true })).toBeNull();+ });++ it("is quiet text: dim, truncating, in one keyed column", () => {+ const node = bandView(both, at(100));+ expect(node).toMatchObject({ type: "Box", props: { key: "lens-band", flexDirection: "column" } });+ for (const row of (node as Extract<Node, { type: "Box" }>).children) {+ expect(row).toMatchObject({ type: "Text", props: { dimColor: true, wrap: "truncate-end" } });+ }+ });++ it.each([60, 100, 180])("fits every row in %i columns", (columns) => {+ for (const row of lines(bandView(both, at(columns)))) expect(row.length).toBeLessThanOrEqual(columns);+ });++ it("truncates a long row at 60 columns with an ellipsis and keeps it whole at 100 and 180", () => {+ const long: SessionState = { ...initialSession, hint: "unlisted", hintsShown: ["unlisted"] };+ const [narrow] = lines(bandView(long, at(60)));+ expect(HINTS.unlisted.length).toBeGreaterThan(60);+ expect(narrow?.length).toBeGreaterThan(55);+ expect(narrow?.length).toBeLessThanOrEqual(60);+ expect(narrow?.endsWith("…")).toBe(true);+ expect(lines(bandView(long, at(100)))).toEqual([HINTS.unlisted]);+ expect(lines(bandView(long, at(180)))).toEqual([HINTS.unlisted]);+ });++ it("uses no em dashes in any copy", () => {+ for (const copy of [...Object.values(HINTS), freshnessLine({ changedFiles: 2 })]) expect(copy).not.toContain("—");+ });+});++describe("freshness copy", () => {+ it("counts files with a unit, singular and plural, with separators", () => {+ expect(freshnessLine({ changedFiles: 1 })).toBe("index behind HEAD (1 file changed) · repowise update");+ expect(freshnessLine({ changedFiles: 1204 })).toBe("index behind HEAD (1,204 files changed) · repowise update");+ });++ it("states no number it did not measure", () => {+ expect(freshnessLine({ changedFiles: null })).toBe("index behind HEAD · repowise update");+ });+});++describe("format", () => {+ it("countOf", () => {+ expect(countOf(0, "file", "files")).toBe("0 files");+ });++ it("fit leaves short text alone and handles a zero width", () => {+ expect(fit("abc", 3)).toBe("abc");+ expect(fit("abcd", 3)).toBe("ab…");+ expect(fit("abc", 0)).toBe("");+ });+});++describe("materialize", () => {+ it("builds the tree through the surface's element table", () => {+ const table = {+ Box: (props: Record<string, unknown>) => ({ el: "Box", props }),+ Text: (props: Record<string, unknown>) => ({ el: "Text", props }),+ };+ const out = materialize(box({ key: "k" }, [text("hi", { dimColor: true })]), table);+ expect(out).toEqual({+ el: "Box",+ props: { key: "k", children: [{ el: "Text", props: { dimColor: true, children: ["hi"] } }] },+ });+ });++ it("refuses an element the surface does not have", () => {+ expect(() => materialize(text("hi"), {})).toThrow(/Text/);+ });+});++describe("savings row", () => {+ // Real ledger reads from a local server on the requests index, before and+ // after one `repowise distill git log -n 300`.+ const before = savingsTotals(JSON.parse(fixture("savings/before-distill.json")) as Savings);+ const after = savingsTotals(JSON.parse(fixture("savings/after-distill.json")) as Savings);+ const measured = savingsSince(after, before)!;+ const big: SavingsDelta = { tokens: 182_400, inferredTokens: 0, usd: 2.41 };+ const withInferred: SavingsDelta = { ...big, inferredTokens: 12_000 };+ const saving = (delta: SavingsDelta, s: SessionState = initialSession) => reduce(s, { type: "savings", delta });++ it("reads the delta from the server's own figures", () => {+ expect(before).toEqual({ tokens: 0, inferredTokens: 0, usd: 0 });+ expect(measured).toEqual({ tokens: 7099, inferredTokens: 0, usd: 0.035495 });+ // The ledger only grows: a drop means a rebuilt ledger, and the snapshot no longer holds.+ expect(savingsSince(before, after)).toBeNull();+ expect(savingsSince({ ...after, usd: 0 }, after)).toBeNull();+ expect(savingsSince({ tokens: 10, inferredTokens: 50, usd: 0 }, before)).toEqual({ tokens: 10, inferredTokens: 10, usd: 0 });+ });++ it("renders nothing at rest and nothing for a zero delta", () => {+ expect(bandView(saving({ tokens: 0, inferredTokens: 0, usd: 0 }), at(100))).toBeNull();+ // A zero delta is never a row, even after one.+ expect(saving({ tokens: 0, inferredTokens: 0, usd: 0 }, saving(big)).savings).toBeNull();+ });++ it("names the scope: since this session started, every agent on this repo", () => {+ expect(lines(bandView(saving(measured), at(100)))).toEqual([+ "7,099 tokens · $0.04 saved since this session started · all agents on this repo",+ ]);+ expect(lines(bandView(saving(big), at(180)))).toEqual([+ "182,400 tokens · $2.41 saved since this session started · all agents on this repo",+ ]);+ });++ it("says how much of it is inferred, and leaves out a dollar figure under a cent", () => {+ expect(savingsLine(withInferred, 180)).toBe(+ "182,400 tokens (12,000 inferred) · $2.41 saved since this session started · all agents on this repo",+ );+ expect(savingsLine({ tokens: 1, inferredTokens: 0, usd: 0.004 }, 180)).toBe(+ "1 token saved since this session started · all agents on this repo",+ );+ });++ it("keeps the scope at 60 columns with the short form", () => {+ expect(lines(bandView(saving(big), at(60)))).toEqual(["182,400 tokens · $2.41 saved this session · all agents"]);+ });++ it.each([60, 100, 180])("fits %i columns with every row showing", (columns) => {+ const all: SessionState = { ...saving(withInferred, both), hint: null };+ for (const row of lines(bandView(all, at(columns)))) expect(row.length).toBeLessThanOrEqual(columns);+ });++ it("comes after a hint and freshness, within two rows, and yields to a survey", () => {+ expect(bandRows(saving(big, both))).toEqual([HINTS["no-server"], "index behind HEAD (1 file changed) · repowise update"]);+ expect(bandRows(saving(big, behind))).toEqual([+ "index behind HEAD (14 files changed) · repowise update",+ "182,400 tokens · $2.41 saved since this session started · all agents on this repo",+ ]);+ expect(bandView(saving(big), { columns: 100, hasSurvey: true })).toBeNull();+ });++ it("leaves with the local server", () => {+ const full = reduce(saving(big), { type: "discovered", mode: "full", freshness: null });+ expect(full.savings).toEqual(big);+ expect(reduce(full, { type: "discovered", mode: "lite", freshness: null }).savings).toBeNull();+ });++ it("uses no em dashes", () => {+ expect(savingsLine(withInferred, 60)).not.toContain("—");+ expect(savingsLine(withInferred, 180)).not.toContain("—");+ });+});diff --git a/packages/claude-mod/test/discovery.test.ts b/packages/claude-mod/test/discovery.test.tsnew file mode 100644index 000000000..d3bc201a1--- /dev/null+++ b/packages/claude-mod/test/discovery.test.ts@@ -0,0 +1,294 @@+import { afterEach, describe, expect, it } from "vitest";+import { configureApiClient } from "@repowise-dev/api-client";+import {+ discover,+ findIndexedRoot,+ isPidAlive,+ isLoopbackUrl,+ isWindowsPath,+ mcpReachable,+ probeServer,+ readFreshness,+ readServeLock,+} from "../src/data/discovery";+import { TimeoutError, withTimeout } from "../src/data/transport";+import { failed, fakeHost, fixture, json, ok, type FakeHostOptions } from "./fake-host";++afterEach(() => configureApiClient({ baseUrl: "" }));++const ROOT = "C:\\work\\requests";+const STATE = `${ROOT}/.repowise/state.json`;+const LOCK = `${ROOT}/.repowise/serve.lock.json`;+const repos = JSON.parse(fixture("repos.json")) as unknown;+const indexedAt = "a".repeat(40);+const head = "b".repeat(40);++/** tasklist answers for pid 4242 only. */+function tasklist(argv: readonly string[]) {+ if (argv[0] === "tasklist") return argv[2] === "PID eq 4242" ? ok('"python.exe","4242","Console"\r\n') : ok("INFO: No tasks are running.\r\n");+ if (argv[0] === "git") return failed;+ throw new Error(`unexpected ${argv.join(" ")}`);+}++function server(status = 200) {+ return (url: string) => {+ if (url.endsWith("/health")) return json(200, { status: "ok", db: "ok", version: "0.54.0" });+ if (url.endsWith("/api/repos")) return status === 200 ? json(200, repos) : json(status, { detail: "Invalid API key" });+ return json(404, { detail: "not found" });+ };+}++const inWorkTree = (argv: readonly string[]) =>+ argv.join(" ") === "git rev-parse --is-inside-work-tree" ? ok("true\n") : failed;++describe("isLoopbackUrl", () => {+ it.each(["http://127.0.0.1:7411", "http://localhost:7411/", "http://[::1]:7411"])("accepts %s", (url) => {+ expect(isLoopbackUrl(url)).toBe(true);+ });++ it.each([+ "https://127.0.0.1:7411",+ "http://evil.example:7411",+ "http://127.0.0.1.evil.example",+ "http://10.0.0.5:7411",+ "file:///etc/passwd",+ "not a url",+ ])("refuses %s", (url) => {+ expect(isLoopbackUrl(url)).toBe(false);+ });+});++function host(o: FakeHostOptions = {}) {+ return fakeHost({ cwd: ROOT, files: { [STATE]: JSON.stringify({ last_sync_commit: indexedAt }) }, run: tasklist, ...o });+}++describe("lock file", () => {+ it("parses a valid lock", async () => {+ const lock = await readServeLock(host({ files: { [LOCK]: fixture("locks/valid.json") } }), ROOT);+ expect(lock).toMatchObject({ pid: 4242, url: "http://127.0.0.1:7411" });+ });++ it("returns null for a garbage lock", async () => {+ expect(await readServeLock(host({ files: { [LOCK]: fixture("locks/garbage.json") } }), ROOT)).toBeNull();+ });++ it("returns null for a missing lock", async () => {+ expect(await readServeLock(host({ files: {} }), ROOT)).toBeNull();+ });++ it("still parses a stale lock; the pid gate decides", async () => {+ const h = host({ files: { [LOCK]: fixture("locks/stale-pid.json") } });+ const lock = await readServeLock(h, ROOT);+ expect(lock?.pid).toBe(9999);+ expect(await isPidAlive(h, 9999, ROOT)).toBe(false);+ expect(await isPidAlive(h, 4242, ROOT)).toBe(true);+ });+});++describe("pid probe", () => {+ it("uses ps off Windows", async () => {+ const h = fakeHost({ run: (argv) => (argv[2] === "77" ? ok(" 77\n") : failed) });+ expect(await isPidAlive(h, 77, "/home/u/repo")).toBe(true);+ expect(await isPidAlive(h, 78, "/home/u/repo")).toBe(false);+ expect(h.calls.run[0]).toEqual(["ps", "-p", "77", "-o", "pid="]);+ });++ it("is unknown, not dead, when the process API is missing", async () => {+ expect(await isPidAlive(fakeHost(), 1, ROOT)).toBeNull();+ });+});++describe("findIndexedRoot", () => {+ it("walks up from a subdirectory to the indexed root", async () => {+ expect(await findIndexedRoot(host(), `${ROOT}\\src\\requests`)).toBe(ROOT);+ });++ it("does not take a .repowise dir without a state file (the user config dir)", async () => {+ const h = fakeHost({ files: { "C:\\Users\\me/.repowise/config.yaml": "" } });+ expect(await findIndexedRoot(h, "C:\\Users\\me\\scratch")).toBeNull();+ });++ it("works on POSIX paths up to the root", async () => {+ const h = fakeHost({ files: { "/.repowise/state.json": "{}" } });+ expect(await findIndexedRoot(h, "/srv/app")).toBe("/");+ expect(await findIndexedRoot(fakeHost(), "/srv/app")).toBeNull();+ });++ it("detects Windows paths", () => {+ expect(isWindowsPath("C:\\x")).toBe(true);+ expect(isWindowsPath("c:/x")).toBe(true);+ expect(isWindowsPath("\\\\server\\share")).toBe(true);+ expect(isWindowsPath("/home/x")).toBe(false);+ });+});++describe("probeServer", () => {+ const lock = JSON.parse(fixture("locks/valid.json"));++ it("matches this repo by local_path among several, not the first row", async () => {+ expect(await probeServer(host({ http: server() }), lock, ROOT)).toEqual({+ kind: "ok",+ repoId: "repo-requests",+ updatedAt: "2026-10-03T05:21:18.324285",+ });+ });++ it("reports a server that does not list this repo", async () => {+ expect(await probeServer(host({ http: server() }), lock, "C:\\elsewhere")).toEqual({ kind: "unlisted" });+ });++ it("reads a 401 as a configured key, never sending one", async () => {+ const seen: Record<string, string>[] = [];+ const h = host({+ http: (url, init) => {+ seen.push(init.headers ?? {});+ return server(401)(url);+ },+ });+ expect(await probeServer(h, lock, ROOT)).toEqual({ kind: "auth" });+ for (const headers of seen) expect(Object.keys(headers).map((k) => k.toLowerCase())).not.toContain("authorization");+ });++ it("is down when /health does not answer", async () => {+ expect(await probeServer(host(), lock, ROOT)).toEqual({ kind: "down" });+ });++ it("is down when the repo list fails for another reason", async () => {+ expect(await probeServer(host({ http: server(500) }), lock, ROOT)).toEqual({ kind: "down" });+ });+});++describe("discover", () => {+ it("full: live lock, healthy server, repo listed", async () => {+ const h = host({ files: { [STATE]: "{}", [LOCK]: fixture("locks/valid.json") }, http: server() });+ expect(await discover(h)).toEqual({+ mode: "full",+ repoRoot: ROOT,+ repo: { id: "repo-requests", updatedAt: "2026-10-03T05:21:18.324285" },+ });+ expect(h.calls.connect).toBe(0);+ });++ it("lite: a stale pid is never probed", async () => {+ const h = host({ files: { [STATE]: "{}", [LOCK]: fixture("locks/stale-pid.json") }, http: server() });+ expect(await discover(h)).toEqual({ mode: "lite", liteReason: "no-server", repoRoot: ROOT });+ expect(h.calls.http).toEqual([]);+ });++ it("lite: garbage or missing lock", async () => {+ for (const files of [{ [STATE]: "{}", [LOCK]: fixture("locks/garbage.json") }, { [STATE]: "{}" }]) {+ const h = host({ files });+ expect((await discover(h)).mode).toBe("lite");+ }+ });++ it("lite with a reason when the server wants a key", async () => {+ const h = host({ files: { [STATE]: "{}", [LOCK]: fixture("locks/valid.json") }, http: server(401) });+ expect(await discover(h)).toMatchObject({ mode: "lite", liteReason: "auth" });+ });++ it("probes /health when the pid cannot be checked", async () => {+ const h = host({ files: { [STATE]: "{}", [LOCK]: fixture("locks/valid.json") }, run: undefined, http: server() });+ expect((await discover(h)).mode).toBe("full");+ });++ it("no-index: a git work tree with no state file anywhere up the tree", async () => {+ const h = fakeHost({ cwd: ROOT, run: inWorkTree });+ expect(await discover(h)).toEqual({ mode: "no-index", repoRoot: null });+ expect(h.calls.run).toContainEqual(["git", "rev-parse", "--is-inside-work-tree"]);+ });++ it("no-repo: outside a git work tree Lens stays quiet and asks nothing of MCP", async () => {+ for (const run of [() => failed, undefined]) {+ const h = fakeHost({ cwd: "C:\Users\me", run });+ expect(await discover(h)).toEqual({ mode: "no-repo", repoRoot: null });+ expect(h.calls.connect).toBe(0);+ }+ });++ it("no-cli: the MCP server cannot connect", async () => {+ expect((await discover(host({ files: { [STATE]: "{}" }, connected: false }))).mode).toBe("no-cli");+ expect((await discover(fakeHost({ cwd: ROOT, run: inWorkTree, connected: false }))).mode).toBe("no-cli");+ });++ it("never probes a lock that names a host other than this machine", async () => {+ const remote = { ...JSON.parse(fixture("locks/valid.json")), url: "http://evil.example:7411", pid: 4242 };+ const h = host({ files: { [STATE]: "{}", [LOCK]: JSON.stringify(remote) }, http: server() });+ expect(await discover(h)).toEqual({ mode: "lite", liteReason: "no-server", repoRoot: ROOT });+ expect(h.calls.http).toEqual([]);+ });++ it("no-cli when the connect itself rejects", async () => {+ const h = fakeHost({ cwd: ROOT });+ h.mcp.connect = async () => {+ throw new Error("refused");+ };+ expect(await mcpReachable(h)).toBe(false);+ });+});++describe("readFreshness", () => {+ function git(diff: string | null, headSha = head) {+ return (argv: readonly string[]) => {+ if (argv[0] !== "git") return tasklist(argv);+ if (argv[1] === "rev-parse") return ok(`${headSha}\n`);+ if (argv[1] === "diff") return diff === null ? failed : ok(diff);+ return failed;+ };+ }++ it("counts files behind HEAD with read-only git", async () => {+ const h = host({ run: git("a.py\nb.py\n\nc.py\n") });+ expect(await readFreshness(h, ROOT)).toEqual({ changedFiles: 3 });+ expect(h.calls.run).toContainEqual(["git", "diff", "--name-only", indexedAt, head, "--"]);+ for (const argv of h.calls.run.filter((a) => a[0] === "git")) expect(["rev-parse", "diff"]).toContain(argv[1]);+ });++ it("never hands git a state value that is not a bare sha", async () => {+ for (const hostile of ["--output=C:/pwned.txt", "-p", "HEAD~1", "a".repeat(65), "abc"]) {+ const h = host({ files: { [STATE]: JSON.stringify({ last_sync_commit: hostile }) }, run: git("a.py\n") });+ expect(await readFreshness(h, ROOT)).toBeNull();+ expect(h.calls.run.filter((a) => a[0] === "git")).toEqual([]);+ }+ });++ it("ignores a HEAD that is not a sha", async () => {+ expect(await readFreshness(host({ run: git("a.py\n", "--output=x") }), ROOT)).toBeNull();+ });++ it("says nothing when current", async () => {+ expect(await readFreshness(host({ run: git("", indexedAt) }), ROOT)).toBeNull();+ });++ it("keeps the row but drops the number when the diff fails", async () => {+ expect(await readFreshness(host({ run: git(null) }), ROOT)).toEqual({ changedFiles: null });+ });++ it("says nothing without git or without a synced commit", async () => {+ expect(await readFreshness(host({ run: () => failed }), ROOT)).toBeNull();+ expect(await readFreshness(host({ files: { [STATE]: "{}" }, run: git("x") }), ROOT)).toBeNull();+ });++ it("stays quiet while an update holds its lock with a live pid", async () => {+ const files = {+ [STATE]: JSON.stringify({ last_sync_commit: indexedAt }),+ [`${ROOT}/.repowise/.update.lock`]: JSON.stringify({ pid: 4242, started_at: 1 }),+ };+ expect(await readFreshness(host({ files, run: git("a.py\n") }), ROOT)).toBeNull();+ });++ it("ignores an update lock whose pid is gone", async () => {+ const files = {+ [STATE]: JSON.stringify({ last_sync_commit: indexedAt }),+ [`${ROOT}/.repowise/.update.lock`]: JSON.stringify({ pid: 9999, started_at: 1 }),+ };+ expect(await readFreshness(host({ files, run: git("a.py\n") }), ROOT)).toEqual({ changedFiles: 1 });+ });+});++describe("withTimeout", () => {+ it("rejects with a TimeoutError when the work does not settle", async () => {+ await expect(withTimeout(new Promise(() => {}), 5, "probe")).rejects.toBeInstanceOf(TimeoutError);+ await expect(withTimeout(Promise.resolve(1), 50, "probe")).resolves.toBe(1);+ });+});diff --git a/packages/claude-mod/test/django.ts b/packages/claude-mod/test/django.tsnew file mode 100644index 000000000..e0590b5f7--- /dev/null+++ b/packages/claude-mod/test/django.ts@@ -0,0 +1,15 @@+// Recorded from `repowise serve` 0.54.0 on a copy of test-repos/django (commit+// e789914): GET /health/map?cap=4000 and POST /blast-radius for+// django/db/models/query.py at max_depth 1, each cut to the fields Lens reads.+import type { HealthMapFeed } from "@repowise-dev/types/health";+import { fixture } from "./fake-host";++export const feed = JSON.parse(fixture("django-health-map.json")) as HealthMapFeed;+export const importers = (+ JSON.parse(fixture("django-blast-radius-query-depth1.json")) as { transitive_affected: { path: string }[] }+).transitive_affected.map((t) => t.path);++export function decode(cells: string): Uint32Array {+ const bytes = Buffer.from(cells, "base64");+ return new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4);+}diff --git a/packages/claude-mod/test/fake-host.ts b/packages/claude-mod/test/fake-host.tsnew file mode 100644index 000000000..103372bb5--- /dev/null+++ b/packages/claude-mod/test/fake-host.ts@@ -0,0 +1,117 @@+import { readFileSync } from "node:fs";+import { resolve } from "node:path";+import type { MinimalRequestInit, MinimalResponse } from "@repowise-dev/api-client";+import type { Host } from "../src/host";+import type { McpToolResult, ProcessRunResult } from "../src/mod-api";++export function fixture(name: string): string {+ return readFileSync(resolve(__dirname, "fixtures", name), "utf8");+}++/**+ * A golden line shared with the Python tests (tests/fixtures/lens): they+ * assert the real formatters write it, these assert Lens reads it.+ */+export function golden(name: string): string {+ return readFileSync(resolve(__dirname, "../../../tests/fixtures/lens", name), "utf8");+}++type HttpRoute = (url: string, init: MinimalRequestInit) => MinimalResponse | Promise<MinimalResponse>;++export interface FakeHostOptions {+ cwd?: string;+ /** Files by path; `/` and `\` are the same separator. */+ files?: Record<string, string>;+ run?: ((argv: readonly string[], cwd: string) => ProcessRunResult | Promise<ProcessRunResult>) | undefined;+ http?: HttpRoute;+ /** Whether the MCP server connects; default true. */+ connected?: boolean;+ /** The name the server connects under; default `plugin:repowise:repowise`. */+ server?: string;+ /** Answers MCP tool calls; default: rejects. */+ mcp?: (tool: string, args: Record<string, unknown>, server: string) => McpToolResult | Promise<McpToolResult>;+}++const norm = (p: string) => p.replace(/\\/g, "/");++export interface FakeHost extends Host {+ calls: { run: string[][]; http: string[]; connect: number; mcp: Array<{ server: string; tool: string; args: Record<string, unknown> }> };+}++export function fakeHost(o: FakeHostOptions = {}): FakeHost {+ const files = new Map(Object.entries(o.files ?? {}).map(([k, v]) => [norm(k), v]));+ const calls: FakeHost["calls"] = { run: [], http: [], connect: 0, mcp: [] };+ return {+ calls,+ session: { cwd: async () => o.cwd ?? "C:\\work\\requests" },+ fs: {+ read: async (path) => {+ const hit = files.get(norm(path));+ if (hit === undefined) throw new Error(`ENOENT ${path}`);+ return hit;+ },+ exists: async (path) => files.has(norm(path)),+ },+ process: {+ run: async (argv, cwd) => {+ calls.run.push([...argv]);+ if (!o.run) throw new Error("process API unavailable");+ return o.run(argv, cwd);+ },+ },+ http: async (url, init) => {+ calls.http.push(url);+ if (!o.http) throw new Error("connection refused");+ return o.http(url, init);+ },+ mcp: {+ connect: async () => {+ calls.connect++;+ return o.connected ?? true;+ },+ server: async () => {+ calls.connect++;+ return (o.connected ?? true) ? (o.server ?? "plugin:repowise:repowise") : null;+ },+ call: async (server, tool, args) => {+ calls.mcp.push({ server, tool, args });+ if (!o.mcp) throw new Error("no connected MCP tool");+ return o.mcp(tool, args, server);+ },+ },+ };+}++export const ok = (stdout: string): ProcessRunResult => ({ exitCode: 0, stdout, stderr: "" });+export const failed: ProcessRunResult = { exitCode: 1, stdout: "", stderr: "fatal" };++export function json(status: number, body: unknown): MinimalResponse {+ return { status, ok: status >= 200 && status < 300, headers: {}, text: JSON.stringify(body) };+}++/** An MCP result carrying `result` the way the repowise server wraps it. */+export function mcpResult(result: unknown, isError = false): McpToolResult {+ return { content: [{ type: "text", text: JSON.stringify(isError ? result : { result }) }], isError };+}++/** An element as the tests' fake `$.ui.resolve` builds it. */+export type Tree = { el: string; props: Record<string, any> };++/** Every element in a drawn tree, depth first. */+export function flatten(t: unknown): Tree[] {+ const n = t as Tree;+ if (typeof n !== "object" || n === null || n.props === undefined) return [];+ const kids = Array.isArray(n.props.children) ? (n.props.children as unknown[]) : [];+ return [n, ...kids.flatMap(flatten)];+}++/** Each Text's string and each Markdown's text, in order. */+export function textOf(t: unknown): string[] {+ return flatten(t)+ .filter((n) => n.el === "Text" || n.el === "Markdown")+ .map((n) => (n.el === "Markdown" ? (n.props.text as string) : (n.props.children as string[]).join("")));+}++export function buttonsOf(t: unknown): Tree[] {+ return flatten(t).filter((n) => n.el === "Button");+}diff --git a/packages/claude-mod/test/fixtures/ask/django-answer-filter.json b/packages/claude-mod/test/fixtures/ask/django-answer-filter.jsonnew file mode 100644index 000000000..a94f62372--- /dev/null+++ b/packages/claude-mod/test/fixtures/ask/django-answer-filter.json@@ -0,0 +1,10 @@+{+ "answer": "Synthesis is unavailable (no-llm-provider). Source rationale in django/utils/tree.py: A class for storing a tree graph. Primarily used for filter constructs in the ORM.",+ "citations": [+ "django/utils/tree.py",+ "django/db/models/sql/constants.py"+ ],+ "confidence": "low",+ "retrieval_quality": "weak",+ "degraded": "no-llm-provider"+}\ No newline at end of filediff --git a/packages/claude-mod/test/fixtures/ask/django-answer-queryset.json b/packages/claude-mod/test/fixtures/ask/django-answer-queryset.jsonnew file mode 100644index 000000000..803132ac3--- /dev/null+++ b/packages/claude-mod/test/fixtures/ask/django-answer-queryset.json@@ -0,0 +1,9 @@+{+ "answer": "Synthesis is unavailable (no-llm-provider), but symbol_bodies contains live source for the named code. Use that evidence directly.",+ "citations": [+ "django/db/models/query.py"+ ],+ "confidence": "medium",+ "retrieval_quality": "high",+ "degraded": "no-llm-provider"+}\ No newline at end of filediff --git a/packages/claude-mod/test/fixtures/ask/django-why-no-record.json b/packages/claude-mod/test/fixtures/ask/django-why-no-record.jsonnew file mode 100644index 000000000..94fa63ee1--- /dev/null+++ b/packages/claude-mod/test/fixtures/ask/django-why-no-record.json@@ -0,0 +1,6 @@+{+ "mode": "search",+ "query": "why does the CSRF middleware rotate the token on login?",+ "reason": "No recorded rationale: no decision record covers this question. The store holds none carrying its terms, and the closest ones would be noise.",+ "decisions": []+}diff --git a/packages/claude-mod/test/fixtures/ask/django-why-query-path.json b/packages/claude-mod/test/fixtures/ask/django-why-query-path.jsonnew file mode 100644index 000000000..a6ac81350--- /dev/null+++ b/packages/claude-mod/test/fixtures/ask/django-why-query-path.json@@ -0,0 +1,149 @@+{+ "mode": "path",+ "path": "django/db/models/query.py",+ "answer_basis": "rationale",+ "decisions": [],+ "git_archaeology": {+ "summary": "No architectural decisions found for django/db/models/query.py, but git archaeology recovered 50 direct commit(s), 1 cross-reference(s), and 29 git log result(s). Review these to understand the intent behind this code.",+ "git_log": [+ {+ "sha": "99672c672a15",+ "message": "Refs #36593, #37187 -- Avoided spurious select_related() warning in ModelAdmin.",+ "date": "2026-06-25",+ "evidence_refs": [+ {+ "id": "ev_8bf8eb410e85f4c04c6d"+ }+ ]+ },+ {+ "sha": "ca5746b8680a",+ "message": "Fixed #37143 -- Added missing chunk_size=None check to QuerySet.aiterator().",+ "date": "2026-06-07",+ "evidence_refs": [+ {+ "id": "ev_bfe153f73c4f51cf2536"+ }+ ]+ },+ {+ "sha": "f970a98e4643",+ "message": "Fixed #37142 -- Moved django_file_prefixes() to django.utils.warnings.",+ "date": "2026-06-06",+ "evidence_refs": [+ {+ "id": "ev_55f2b2d6bde6df529dc3"+ }+ ]+ },+ {+ "sha": "fbe902d4a4b8",+ "message": "Refs #37097 -- Removed compilation-time order clearing on combined queries on Oracle.",+ "date": "2026-05-13",+ "evidence_refs": [+ {+ "id": "ev_771a4cbc951420a05e5a"+ }+ ]+ },+ {+ "sha": "f386d8ec7cbf",+ "message": "Fixed #36593 -- Deprecated QuerySet.select_related() with no arguments.",+ "date": "2025-09-05",+ "evidence_refs": [+ {+ "id": "ev_a26d850458daa53480e1"+ }+ ]+ },+ {+ "sha": "5cf9c7fde7cf",+ "message": "Refs #28586 -- Added DEFAULT_FETCH_MODE module constant.",+ "date": "2026-04-19",+ "evidence_refs": [+ {+ "id": "ev_eb6161dfad80f269cbb9"+ }+ ]+ },+ {+ "sha": "3b161e60964a",+ "message": "Fixed #37016 -- Avoided propagating invalid arguments from When() to Q().",+ "date": "2026-04-02",+ "evidence_refs": [+ {+ "id": "ev_4e797f7b925aa6066141"+ }+ ]+ }+ ]+ },+ "code_rationale": [+ {+ "path": "django/db/models/query.py",+ "lines": [+ 81,+ 88+ ],+ "comment": "__aiter__() is a *synchronous* method that has to then return an *asynchronous* iterator/generator. Thus, nest an async generator inside it. This is a generic iterable converter for now, and is going to suffer a performance penalty on large sets of items due to the cost of crossing over the sync barrier for each chunk. Custom __aiter__() methods should be added to each Iterable subclass, but that needs some work in the Compiler first.",+ "evidence_refs": [+ {+ "id": "ev_31e393e22918fcab5a3b"+ }+ ]+ },+ {+ "path": "django/db/models/query.py",+ "lines": [+ 153,+ 153+ ],+ "comment": "Avoid overwriting objects loaded by, e.g., select_related().",+ "evidence_refs": [+ {+ "id": "ev_d8f7624113dc11517dc1"+ }+ ]+ },+ {+ "path": "django/db/models/query.py",+ "lines": [+ 156,+ 157+ ],+ "comment": "Avoid fetching potentially deferred attributes that would result in unexpected queries.",+ "evidence_refs": [+ {+ "id": "ev_2625aa6ea06d5c2189bd"+ }+ ]+ },+ {+ "path": "django/db/models/query.py",+ "lines": [+ 177,+ 177+ ],+ "comment": "Cache some things for performance reasons outside the loop.",+ "evidence_refs": [+ {+ "id": "ev_0e6831ae4655faf6121b"+ }+ ]+ },+ {+ "path": "django/db/models/query.py",+ "lines": [+ 240,+ 240+ ],+ "comment": "extra(select=...) cols are always at the start of the row.",+ "evidence_refs": [+ {+ "id": "ev_eff2c2b8f0f096f509de"+ }+ ]+ }+ ],+ "code_rationale_total": 38+}diff --git a/packages/claude-mod/test/fixtures/ask/requests-why-archaeology.json b/packages/claude-mod/test/fixtures/ask/requests-why-archaeology.jsonnew file mode 100644index 000000000..6dc642b30--- /dev/null+++ b/packages/claude-mod/test/fixtures/ask/requests-why-archaeology.json@@ -0,0 +1,22 @@+{+ "mode": "search",+ "query": "why does Session merge environment settings?",+ "reason": "No decision record covers this question. The commit history below carry its terms. They are quoted from the code and its history, not a ruling: read them as evidence, not as the recorded reason.",+ "answer_basis": "archaeology",+ "decisions": [],+ "git_archaeology": {+ "summary": "No recorded rationale for this question. 1 commit(s) carry its terms: history, not a stated reason.",+ "git_log": [+ {+ "sha": "827bbe2a7e40",+ "message": "docs: correct error in 'merge_environment_settings' usage",+ "date": "2019-02-04",+ "evidence_refs": [+ {+ "id": "ev_8964f795d9001bd297ca"+ }+ ]+ }+ ]+ }+}diff --git a/packages/claude-mod/test/fixtures/change-risk/clear.json b/packages/claude-mod/test/fixtures/change-risk/clear.jsonnew file mode 100644index 000000000..19dd7d4b8--- /dev/null+++ b/packages/claude-mod/test/fixtures/change-risk/clear.json@@ -0,0 +1,136 @@+{+ "directive": {+ "status": "clear_in_analyzed_scope",+ "headline": "No supported new findings surfaced in the analyzed scope.",+ "reasons": [],+ "next_actions": [+ "Run: tests/test_requests.py tests/test_utils.py"+ ]+ },+ "health_delta": {+ "status": "available",+ "explanation": "No supported new findings surfaced in the analyzed scope.",+ "basis": "both_sides_analyzed",+ "introduced": 0,+ "worsened": 0,+ "resolved": 0,+ "by_dimension": {},+ "by_severity": {},+ "scope": {+ "changed": 1,+ "eligible": 1,+ "analyzed": 1,+ "skipped": 0,+ "failed": 0+ },+ "top_findings": [],+ "findings_total": 0,+ "findings_emitted": 0,+ "base": {+ "ref": "HEAD",+ "sha": "3bb56ba566ce783ebdc4e61929522fd1648c2527",+ "kind": "commit"+ },+ "head": {+ "ref": "WORKTREE",+ "sha": "",+ "kind": "working_tree"+ },+ "analyzer": {+ "analyzer_version": 38,+ "rules_fingerprint": "2f1b53b61c545f3ce5e44371e52b0428f710f8cee6f8d8547f8ca5c474e864fd",+ "performance_model_version": 3+ },+ "limits": [+ "Both sides are analysed over the changed files only, so cross-file detectors (duplication, cross-function performance) see no wider context."+ ]+ },+ "ref": "working tree",+ "working_tree": true,+ "fix_history": {+ "available": true,+ "density": 1.329,+ "percentile": 75.0,+ "files": [+ {+ "path": "src/requests/_internal_utils.py",+ "churn": 3,+ "fix_pressure": 1.33+ }+ ],+ "overlap": {+ "files": [+ {+ "file_path": "src/requests/_internal_utils.py",+ "fix_count": 1,+ "overlapping_lines": 0,+ "changed_lines": 2,+ "share_of_change": 1.0,+ "last_fix_days_ago": 186+ }+ ],+ "truncated": false,+ "total_fixes": 1,+ "files_with_fixes": 1,+ "changed_lines_in_fixed_files": 2,+ "line_overlap": "approximate",+ "summary": "1 past bug-fix commit(s) touched 1 of the changed file(s). Line overlap is approximate (past ranges are numbered on their own parent commit); the per-file counts are not.",+ "concentration": "src/requests/_internal_utils.py carries 100% of the changed lines and 1 past bug fix(es)."+ }+ },+ "risk_percentile": 34.0,+ "review_priority": "moderate",+ "classification": "Typical",+ "exclude_patterns": [],+ "is_fix": false,+ "impacted_tests": {+ "status": "inferred",+ "basis": "inferred",+ "map_present": false,+ "tests_to_run": [+ "tests/test_requests.py",+ "tests/test_utils.py"+ ],+ "tests_to_run_kind": "test_file",+ "total": 2,+ "truncated": false,+ "line_coverage": {+ "untested_changes": [],+ "stale_test_candidates": [],+ "covered": [],+ "no_coverage_data": []+ },+ "summary": "2 test file(s) reach the changed files in the graph. Inferred from the dependency graph, not measured. For the line-precise answer build the map with `coverage run --contexts=test` then `repowise coverage add`."+ },+ "diff_shape": "Diff shape: bigger than 34% of this repo's recent commits. Size and spread, not danger. Mechanics: get_change_risk(include=['diagnostics']).",+ "_meta": {+ "contract_version": 2,+ "timing_ms": 1054.0,+ "index_age_days": 49,+ "indexed_commit": "4ed3d1b3204c",+ "live_head": "3bb56ba566ce",+ "index_behind": true,+ "index_scope": {+ "version": 1,+ "projection": "compact",+ "run_mode": "standard",+ "content_provenance": "template",+ "git_tier": "full",+ "status": "unknown",+ "fingerprint": "118fda63ca3a",+ "full": "get_overview()"+ },+ "embedder": "mock",+ "embedder_degraded": false,+ "semantic_search": false,+ "source": "live_git",+ "response_budget": {+ "limit_chars": 24000,+ "tier": "default",+ "serialized_chars": 3111+ },+ "completeness": {+ "capped": false+ }+ }+}diff --git a/packages/claude-mod/test/fixtures/change-risk/findings.json b/packages/claude-mod/test/fixtures/change-risk/findings.jsonnew file mode 100644index 000000000..8625f5c44--- /dev/null+++ b/packages/claude-mod/test/fixtures/change-risk/findings.json@@ -0,0 +1,189 @@+{+ "directive": {+ "status": "review_required",+ "headline": "2 new findings need review, starting with nested_complexity in src/requests/_internal_utils.py.",+ "reasons": [+ "critical defect: nested_complexity in classify_headers (added_lines)",+ "high defect: complex_method in classify_headers (added_lines)"+ ],+ "next_actions": [+ "Inspect src/requests/_internal_utils.py:55 (chf_7c35d63fcc13e52b)",+ "Inspect src/requests/_internal_utils.py:55 (chf_1d478916e70baee8)",+ "Run: tests/test_requests.py tests/test_utils.py"+ ]+ },+ "health_delta": {+ "status": "available",+ "explanation": "Compared 1 changed files on both sides.",+ "basis": "both_sides_analyzed",+ "introduced": 2,+ "worsened": 0,+ "resolved": 0,+ "by_dimension": {+ "defect": 2+ },+ "by_severity": {+ "critical": 1,+ "high": 1+ },+ "scope": {+ "changed": 1,+ "eligible": 1,+ "analyzed": 1,+ "skipped": 0,+ "failed": 0+ },+ "top_findings": [+ {+ "id": "chf_7c35d63fcc13e52b",+ "change": "introduced",+ "dimension": "defect",+ "biomarker": "nested_complexity",+ "severity": "critical",+ "path": "src/requests/_internal_utils.py",+ "reason": "classify_headers nests 7 levels deep",+ "attribution": {+ "basis": "added_lines",+ "confidence": "high",+ "why": "Lines 55-85 are added or rewritten by this change."+ },+ "inspect": "get_change_risk(finding_id='chf_7c35d63fcc13e52b')",+ "symbol": "classify_headers",+ "lines": [+ 55,+ 85+ ]+ },+ {+ "id": "chf_1d478916e70baee8",+ "change": "introduced",+ "dimension": "defect",+ "biomarker": "complex_method",+ "severity": "high",+ "path": "src/requests/_internal_utils.py",+ "reason": "classify_headers has cyclomatic complexity 15",+ "attribution": {+ "basis": "added_lines",+ "confidence": "high",+ "why": "Lines 55-85 are added or rewritten by this change."+ },+ "inspect": "get_change_risk(finding_id='chf_1d478916e70baee8')",+ "symbol": "classify_headers",+ "lines": [+ 55,+ 85+ ]+ }+ ],+ "findings_total": 2,+ "findings_emitted": 2,+ "base": {+ "ref": "HEAD",+ "sha": "3bb56ba566ce783ebdc4e61929522fd1648c2527",+ "kind": "commit"+ },+ "head": {+ "ref": "WORKTREE",+ "sha": "",+ "kind": "working_tree"+ },+ "analyzer": {+ "analyzer_version": 38,+ "rules_fingerprint": "2f1b53b61c545f3ce5e44371e52b0428f710f8cee6f8d8547f8ca5c474e864fd",+ "performance_model_version": 3+ },+ "limits": [+ "Both sides are analysed over the changed files only, so cross-file detectors (duplication, cross-function performance) see no wider context."+ ]+ },+ "ref": "working tree",+ "working_tree": true,+ "fix_history": {+ "available": true,+ "density": 1.329,+ "percentile": 75.0,+ "files": [+ {+ "path": "src/requests/_internal_utils.py",+ "churn": 36,+ "fix_pressure": 1.33+ }+ ],+ "overlap": {+ "files": [+ {+ "file_path": "src/requests/_internal_utils.py",+ "fix_count": 1,+ "overlapping_lines": 0,+ "changed_lines": 35,+ "share_of_change": 1.0,+ "last_fix_days_ago": 186+ }+ ],+ "truncated": false,+ "total_fixes": 1,+ "files_with_fixes": 1,+ "changed_lines_in_fixed_files": 35,+ "line_overlap": "approximate",+ "summary": "1 past bug-fix commit(s) touched 1 of the changed file(s). Line overlap is approximate (past ranges are numbered on their own parent commit); the per-file counts are not.",+ "concentration": "src/requests/_internal_utils.py carries 100% of the changed lines and 1 past bug fix(es)."+ }+ },+ "risk_percentile": 92.0,+ "review_priority": "high",+ "classification": "Elevated",+ "exclude_patterns": [],+ "is_fix": false,+ "impacted_tests": {+ "status": "inferred",+ "basis": "inferred",+ "map_present": false,+ "tests_to_run": [+ "tests/test_requests.py",+ "tests/test_utils.py"+ ],+ "tests_to_run_kind": "test_file",+ "total": 2,+ "truncated": false,+ "line_coverage": {+ "untested_changes": [],+ "stale_test_candidates": [],+ "covered": [],+ "no_coverage_data": []+ },+ "summary": "2 test file(s) reach the changed files in the graph. Inferred from the dependency graph, not measured. For the line-precise answer build the map with `coverage run --contexts=test` then `repowise coverage add`."+ },+ "diff_shape": "Diff shape: bigger than 92% of this repo's recent commits. Size and spread, not danger. Mechanics: get_change_risk(include=['diagnostics']).",+ "_meta": {+ "contract_version": 2,+ "timing_ms": 999.7,+ "index_age_days": 49,+ "indexed_commit": "4ed3d1b3204c",+ "live_head": "3bb56ba566ce",+ "index_behind": true,+ "index_scope": {+ "version": 1,+ "projection": "compact",+ "run_mode": "standard",+ "content_provenance": "template",+ "git_tier": "full",+ "status": "unknown",+ "fingerprint": "118fda63ca3a",+ "full": "get_overview()"+ },+ "embedder": "mock",+ "embedder_degraded": false,+ "semantic_search": false,+ "source": "live_git",+ "response_budget": {+ "limit_chars": 24000,+ "tier": "default",+ "serialized_chars": 4324+ },+ "completeness": {+ "capped": false,+ "shown": 2,+ "total": 2+ }+ }+}diff --git a/packages/claude-mod/test/fixtures/change-risk/nothing-to-score.json b/packages/claude-mod/test/fixtures/change-risk/nothing-to-score.jsonnew file mode 100644index 000000000..276021ade--- /dev/null+++ b/packages/claude-mod/test/fixtures/change-risk/nothing-to-score.json@@ -0,0 +1,40 @@+{+ "ref": "HEAD",+ "status": "nothing_to_score",+ "warning": "No counted file changes in 'HEAD' (check the revspec, extensions, or exclusion filters).",+ "scored_repo": {+ "root": "C:\\work\\requests",+ "head": "3bb56ba566ce783ebdc4e61929522fd1648c2527"+ },+ "_meta": {+ "contract_version": 2,+ "timing_ms": 640.7,+ "index_age_days": 49,+ "indexed_commit": "4ed3d1b3204c",+ "live_head": "3bb56ba566ce",+ "index_behind": true,+ "stale_warning": "Index is behind live HEAD — run `repowise update`.",+ "index_scope": {+ "version": 1,+ "projection": "compact",+ "run_mode": "standard",+ "content_provenance": "template",+ "git_tier": "full",+ "status": "unknown",+ "fingerprint": "118fda63ca3a",+ "full": "get_overview()"+ },+ "embedder": "mock",+ "embedder_degraded": false,+ "semantic_search": false,+ "source": "live_git",+ "response_budget": {+ "limit_chars": 24000,+ "tier": "default",+ "serialized_chars": 893+ },+ "completeness": {+ "capped": false+ }+ }+}diff --git a/packages/claude-mod/test/fixtures/change-risk/overlap.json b/packages/claude-mod/test/fixtures/change-risk/overlap.jsonnew file mode 100644index 000000000..f28b9087c--- /dev/null+++ b/packages/claude-mod/test/fixtures/change-risk/overlap.json@@ -0,0 +1,158 @@+{+ "directive": {+ "status": "clear_in_analyzed_scope",+ "headline": "No supported new findings surfaced in the analyzed scope.",+ "reasons": [],+ "next_actions": [+ "Run: tests/test_requests.py tests/test_utils.py"+ ]+ },+ "health_delta": {+ "status": "available",+ "explanation": "No supported new findings surfaced in the analyzed scope.",+ "basis": "both_sides_analyzed",+ "introduced": 0,+ "worsened": 0,+ "resolved": 0,+ "by_dimension": {},+ "by_severity": {},+ "scope": {+ "changed": 1,+ "eligible": 1,+ "analyzed": 1,+ "skipped": 0,+ "failed": 0+ },+ "top_findings": [],+ "findings_total": 0,+ "findings_emitted": 0,+ "base": {+ "ref": "HEAD",+ "sha": "3bb56ba566ce783ebdc4e61929522fd1648c2527",+ "kind": "commit"+ },+ "head": {+ "ref": "WORKTREE",+ "sha": "",+ "kind": "working_tree"+ },+ "analyzer": {+ "analyzer_version": 38,+ "rules_fingerprint": "2f1b53b61c545f3ce5e44371e52b0428f710f8cee6f8d8547f8ca5c474e864fd",+ "performance_model_version": 3+ },+ "limits": [+ "Both sides are analysed over the changed files only, so cross-file detectors (duplication, cross-function performance) see no wider context."+ ]+ },+ "ref": "working tree",+ "working_tree": true,+ "fix_history": {+ "available": true,+ "density": 1.329,+ "percentile": 75.0,+ "files": [+ {+ "path": "src/requests/_internal_utils.py",+ "churn": 3,+ "fix_pressure": 1.33+ }+ ],+ "overlap": {+ "files": [+ {+ "file_path": "src/requests/_internal_utils.py",+ "fix_count": 1,+ "overlapping_lines": 0,+ "changed_lines": 2,+ "share_of_change": 1.0,+ "last_fix_days_ago": 186+ }+ ],+ "truncated": false,+ "total_fixes": 1,+ "files_with_fixes": 1,+ "changed_lines_in_fixed_files": 2,+ "line_overlap": "approximate",+ "summary": "1 past bug-fix commit(s) touched 1 of the changed file(s). Line overlap is approximate (past ranges are numbered on their own parent commit); the per-file counts are not.",+ "concentration": "src/requests/_internal_utils.py carries 100% of the changed lines and 1 past bug fix(es)."+ }+ },+ "risk_percentile": 34.0,+ "review_priority": "moderate",+ "classification": "Typical",+ "exclude_patterns": [],+ "is_fix": false,+ "impacted_tests": {+ "status": "inferred",+ "basis": "inferred",+ "map_present": false,+ "tests_to_run": [+ "tests/test_requests.py",+ "tests/test_utils.py"+ ],+ "tests_to_run_kind": "test_file",+ "total": 2,+ "truncated": false,+ "line_coverage": {+ "untested_changes": [],+ "stale_test_candidates": [],+ "covered": [],+ "no_coverage_data": []+ },+ "summary": "2 test file(s) reach the changed files in the graph. Inferred from the dependency graph, not measured. For the line-precise answer build the map with `coverage run --contexts=test` then `repowise coverage add`."+ },+ "branch_overlap": {+ "base": "origin/main",+ "current": "main",+ "branches": [+ {+ "branch": "fix-native-strings",+ "ahead": 1,+ "behind": 0,+ "last_commit": "2026-10-03",+ "files": [+ {+ "file": "src/requests/_internal_utils.py",+ "basis": "same file"+ }+ ]+ }+ ],+ "scanned": 6,+ "total": 6,+ "truncated": false,+ "summary": "1 of 6 open branches (6 exist) edit files this change also edits."+ },+ "diff_shape": "Diff shape: bigger than 34% of this repo's recent commits. Size and spread, not danger. Mechanics: get_change_risk(include=['diagnostics']).",+ "_meta": {+ "contract_version": 2,+ "timing_ms": 1333.0,+ "index_age_days": 49,+ "indexed_commit": "4ed3d1b3204c",+ "live_head": "3bb56ba566ce",+ "index_behind": true,+ "index_scope": {+ "version": 1,+ "projection": "compact",+ "run_mode": "standard",+ "content_provenance": "template",+ "git_tier": "full",+ "status": "unknown",+ "fingerprint": "118fda63ca3a",+ "full": "get_overview()"+ },+ "embedder": "mock",+ "embedder_degraded": false,+ "semantic_search": false,+ "source": "live_git",+ "response_budget": {+ "limit_chars": 24000,+ "tier": "default",+ "serialized_chars": 3452+ },+ "completeness": {+ "capped": false+ }+ }+}diff --git a/packages/claude-mod/test/fixtures/change-risk/partial.json b/packages/claude-mod/test/fixtures/change-risk/partial.jsonnew file mode 100644index 000000000..8d953b3c5--- /dev/null+++ b/packages/claude-mod/test/fixtures/change-risk/partial.json@@ -0,0 +1,183 @@+{+ "directive": {+ "status": "unknown",+ "headline": "Nothing new in what was compared, but part of the change was not analysed.",+ "reasons": [+ "1 changed file were not analysed, so this is not a clean bill."+ ],+ "next_actions": [+ "Run: tests/test_requests.py tests/test_utils.py",+ "Review the skipped files by hand; they were not compared."+ ]+ },+ "health_delta": {+ "status": "partial",+ "explanation": "Compared 1 of 2 changed files; 1 were not analysed.",+ "basis": "both_sides_analyzed",+ "introduced": 0,+ "worsened": 0,+ "resolved": 0,+ "by_dimension": {},+ "by_severity": {},+ "scope": {+ "changed": 2,+ "eligible": 1,+ "analyzed": 1,+ "skipped": 1,+ "failed": 0+ },+ "top_findings": [],+ "findings_total": 0,+ "findings_emitted": 0,+ "base": {+ "ref": "HEAD",+ "sha": "3bb56ba566ce783ebdc4e61929522fd1648c2527",+ "kind": "commit"+ },+ "head": {+ "ref": "WORKTREE",+ "sha": "",+ "kind": "working_tree"+ },+ "analyzer": {+ "analyzer_version": 38,+ "rules_fingerprint": "2f1b53b61c545f3ce5e44371e52b0428f710f8cee6f8d8547f8ca5c474e864fd",+ "performance_model_version": 3+ },+ "skipped": {+ "total": 1,+ "by_reason": {+ "unsupported_language": 1+ }+ },+ "limits": [+ "Both sides are analysed over the changed files only, so cross-file detectors (duplication, cross-function performance) see no wider context."+ ]+ },+ "ref": "working tree",+ "working_tree": true,+ "fix_history": {+ "available": true,+ "density": 1.14,+ "percentile": 72.5,+ "files": [+ {+ "path": "src/requests/utils.py",+ "churn": 2,+ "fix_pressure": 2.28+ },+ {+ "path": "tox.ini",+ "churn": 2,+ "fix_pressure": 0.0+ }+ ],+ "overlap": {+ "files": [+ {+ "file_path": "src/requests/utils.py",+ "fix_count": 1,+ "overlapping_lines": 0,+ "changed_lines": 1,+ "share_of_change": 0.333,+ "last_fix_days_ago": 186+ }+ ],+ "truncated": false,+ "total_fixes": 1,+ "files_with_fixes": 1,+ "changed_lines_in_fixed_files": 1,+ "line_overlap": "approximate",+ "summary": "1 past bug-fix commit(s) touched 1 of the changed file(s). Line overlap is approximate (past ranges are numbered on their own parent commit); the per-file counts are not."+ }+ },+ "risk_percentile": 40.2,+ "review_priority": "moderate",+ "classification": "Typical",+ "exclude_patterns": [],+ "is_fix": false,+ "impacted_tests": {+ "status": "inferred",+ "basis": "inferred",+ "map_present": false,+ "tests_to_run": [+ "tests/test_requests.py",+ "tests/test_utils.py"+ ],+ "tests_to_run_kind": "test_file",+ "total": 2,+ "truncated": false,+ "line_coverage": {+ "untested_changes": [],+ "stale_test_candidates": [],+ "covered": [],+ "no_coverage_data": []+ },+ "summary": "2 test file(s) reach the changed files in the graph. Inferred from the dependency graph, not measured. For the line-precise answer build the map with `coverage run --contexts=test` then `repowise coverage add`."+ },+ "branch_overlap": {+ "base": "origin/main",+ "current": "main",+ "branches": [+ {+ "branch": "origin/3.0",+ "ahead": 234,+ "behind": 1206,+ "last_commit": "2018-06-14",+ "files": [+ {+ "file": "tox.ini",+ "basis": "same file"+ }+ ]+ },+ {+ "branch": "origin/proposed/3.0.0",+ "ahead": 161,+ "behind": 1206,+ "last_commit": "2018-03-08",+ "files": [+ {+ "file": "tox.ini",+ "basis": "same file"+ }+ ]+ }+ ],+ "scanned": 6,+ "total": 6,+ "truncated": false,+ "summary": "2 of 6 open branches (6 exist) edit files this change also edits."+ },+ "diff_shape": "Diff shape: bigger than 40% of this repo's recent commits. Size and spread, not danger. Mechanics: get_change_risk(include=['diagnostics']).",+ "_meta": {+ "contract_version": 2,+ "timing_ms": 2135.0,+ "index_age_days": 49,+ "indexed_commit": "4ed3d1b3204c",+ "live_head": "3bb56ba566ce",+ "index_behind": true,+ "index_scope": {+ "version": 1,+ "projection": "compact",+ "run_mode": "standard",+ "content_provenance": "template",+ "git_tier": "full",+ "status": "unknown",+ "fingerprint": "118fda63ca3a",+ "full": "get_overview()"+ },+ "embedder": "mock",+ "embedder_degraded": false,+ "semantic_search": false,+ "source": "live_git",+ "response_budget": {+ "limit_chars": 24000,+ "tier": "default",+ "serialized_chars": 3661+ },+ "completeness": {+ "capped": false+ }+ }+}diff --git a/packages/claude-mod/test/fixtures/change-risk/resolved.json b/packages/claude-mod/test/fixtures/change-risk/resolved.jsonnew file mode 100644index 000000000..33174234f--- /dev/null+++ b/packages/claude-mod/test/fixtures/change-risk/resolved.json@@ -0,0 +1,137 @@+{+ "directive": {+ "status": "clear_in_analyzed_scope",+ "headline": "No supported new findings surfaced in the analyzed scope.",+ "reasons": [],+ "next_actions": [+ "Run: tests/test_requests.py tests/test_utils.py"+ ]+ },+ "health_delta": {+ "status": "available",+ "explanation": "No supported new findings surfaced in the analyzed scope.",+ "basis": "both_sides_analyzed",+ "introduced": 0,+ "worsened": 0,+ "resolved": 2,+ "by_dimension": {},+ "by_severity": {},+ "scope": {+ "changed": 1,+ "eligible": 1,+ "analyzed": 1,+ "skipped": 0,+ "failed": 0+ },+ "top_findings": [],+ "findings_total": 0,+ "findings_emitted": 0,+ "base": {+ "ref": "HEAD",+ "sha": "99025b48982b9261cdf574e08e1338d8ca84f8a8",+ "kind": "commit"+ },+ "head": {+ "ref": "WORKTREE",+ "sha": "",+ "kind": "working_tree"+ },+ "analyzer": {+ "analyzer_version": 38,+ "rules_fingerprint": "2f1b53b61c545f3ce5e44371e52b0428f710f8cee6f8d8547f8ca5c474e864fd",+ "performance_model_version": 3+ },+ "limits": [+ "Both sides are analysed over the changed files only, so cross-file detectors (duplication, cross-function performance) see no wider context."+ ]+ },+ "ref": "working tree",+ "working_tree": true,+ "fix_history": {+ "available": true,+ "density": 1.329,+ "percentile": 74.8,+ "files": [+ {+ "path": "src/requests/_internal_utils.py",+ "churn": 36,+ "fix_pressure": 1.33+ }+ ],+ "overlap": {+ "files": [+ {+ "file_path": "src/requests/_internal_utils.py",+ "fix_count": 1,+ "overlapping_lines": 0,+ "changed_lines": 1,+ "share_of_change": 1.0,+ "last_fix_days_ago": 186+ }+ ],+ "truncated": false,+ "total_fixes": 1,+ "files_with_fixes": 1,+ "changed_lines_in_fixed_files": 1,+ "line_overlap": "approximate",+ "summary": "1 past bug-fix commit(s) touched 1 of the changed file(s). Line overlap is approximate (past ranges are numbered on their own parent commit); the per-file counts are not.",+ "concentration": "src/requests/_internal_utils.py carries 100% of the changed lines and 1 past bug fix(es)."+ }+ },+ "risk_percentile": 17.5,+ "review_priority": "low",+ "classification": "Below typical",+ "exclude_patterns": [],+ "is_fix": false,+ "impacted_tests": {+ "status": "inferred",+ "basis": "inferred",+ "map_present": false,+ "tests_to_run": [+ "tests/test_requests.py",+ "tests/test_utils.py"+ ],+ "tests_to_run_kind": "test_file",+ "total": 2,+ "truncated": false,+ "line_coverage": {+ "untested_changes": [],+ "stale_test_candidates": [],+ "covered": [],+ "no_coverage_data": []+ },+ "summary": "2 test file(s) reach the changed files in the graph. Inferred from the dependency graph, not measured. For the line-precise answer build the map with `coverage run --contexts=test` then `repowise coverage add`."+ },+ "diff_shape": "Diff shape: bigger than 18% of this repo's recent commits. Size and spread, not danger. Mechanics: get_change_risk(include=['diagnostics']).",+ "_meta": {+ "contract_version": 2,+ "timing_ms": 1016.0,+ "index_age_days": 49,+ "indexed_commit": "4ed3d1b3204c",+ "live_head": "99025b48982b",+ "index_behind": true,+ "stale_warning": "A file this response serves changed after indexing — verify against source or run `repowise update`.",+ "index_scope": {+ "version": 1,+ "projection": "compact",+ "run_mode": "standard",+ "content_provenance": "template",+ "git_tier": "full",+ "status": "unknown",+ "fingerprint": "118fda63ca3a",+ "full": "get_overview()"+ },+ "embedder": "mock",+ "embedder_degraded": false,+ "semantic_search": false,+ "source": "live_git",+ "response_budget": {+ "limit_chars": 24000,+ "tier": "default",+ "serialized_chars": 3237+ },+ "completeness": {+ "capped": false+ }+ }+}diff --git a/packages/claude-mod/test/fixtures/change-risk/unavailable.json b/packages/claude-mod/test/fixtures/change-risk/unavailable.jsonnew file mode 100644index 000000000..f1cd8520a--- /dev/null+++ b/packages/claude-mod/test/fixtures/change-risk/unavailable.json@@ -0,0 +1,154 @@+{+ "directive": {+ "status": "unknown",+ "headline": "Change health could not be compared: No changed file is health-analyzable, so nothing was compared.",+ "reasons": [+ "1 changed file were not analysed, so this is not a clean bill."+ ],+ "next_actions": [+ "No measured test map; run the suite covering the changed files.",+ "Review the skipped files by hand; they were not compared."+ ]+ },+ "health_delta": {+ "status": "unavailable",+ "explanation": "No changed file is health-analyzable, so nothing was compared.",+ "basis": "both_sides_analyzed",+ "introduced": 0,+ "worsened": 0,+ "resolved": 0,+ "by_dimension": {},+ "by_severity": {},+ "scope": {+ "changed": 1,+ "eligible": 0,+ "analyzed": 0,+ "skipped": 0,+ "failed": 0+ },+ "top_findings": [],+ "findings_total": 0,+ "findings_emitted": 0,+ "base": {+ "ref": "HEAD",+ "sha": "3bb56ba566ce783ebdc4e61929522fd1648c2527",+ "kind": "commit"+ },+ "head": {+ "ref": "WORKTREE",+ "sha": "",+ "kind": "working_tree"+ },+ "analyzer": {+ "analyzer_version": 38,+ "rules_fingerprint": "2f1b53b61c545f3ce5e44371e52b0428f710f8cee6f8d8547f8ca5c474e864fd",+ "performance_model_version": 3+ },+ "skipped": {+ "total": 1,+ "by_reason": {+ "unsupported_language": 1+ }+ }+ },+ "ref": "working tree",+ "working_tree": true,+ "fix_history": {+ "available": true,+ "density": 0.0,+ "percentile": 21.8,+ "files": [+ {+ "path": "tox.ini",+ "churn": 2,+ "fix_pressure": 0.0+ }+ ]+ },+ "risk_percentile": 34.0,+ "review_priority": "moderate",+ "classification": "Typical",+ "exclude_patterns": [],+ "is_fix": false,+ "impacted_tests": {+ "status": "no_map",+ "basis": "none",+ "map_present": false,+ "tests_to_run": [],+ "tests_to_run_kind": null,+ "total": 0,+ "truncated": false,+ "line_coverage": {+ "untested_changes": [],+ "stale_test_candidates": [],+ "covered": [],+ "no_coverage_data": []+ },+ "summary": "No per-test coverage map ingested and no test reaches the changed files in the graph; run the full suite. Inferred from the dependency graph, not measured. For the line-precise answer build the map with `coverage run --contexts=test` then `repowise coverage add`."+ },+ "branch_overlap": {+ "base": "origin/main",+ "current": "main",+ "branches": [+ {+ "branch": "origin/3.0",+ "ahead": 234,+ "behind": 1206,+ "last_commit": "2018-06-14",+ "files": [+ {+ "file": "tox.ini",+ "basis": "same file"+ }+ ]+ },+ {+ "branch": "origin/proposed/3.0.0",+ "ahead": 161,+ "behind": 1206,+ "last_commit": "2018-03-08",+ "files": [+ {+ "file": "tox.ini",+ "basis": "same file"+ }+ ]+ }+ ],+ "scanned": 6,+ "total": 6,+ "truncated": false,+ "summary": "2 of 6 open branches (6 exist) edit files this change also edits."+ },+ "diff_shape": "Diff shape: bigger than 34% of this repo's recent commits. Size and spread, not danger. Mechanics: get_change_risk(include=['diagnostics']).",+ "_meta": {+ "contract_version": 2,+ "timing_ms": 1242.0,+ "index_age_days": 49,+ "indexed_commit": "4ed3d1b3204c",+ "live_head": "3bb56ba566ce",+ "index_behind": true,+ "index_scope": {+ "version": 1,+ "projection": "compact",+ "run_mode": "standard",+ "content_provenance": "template",+ "git_tier": "full",+ "status": "unknown",+ "fingerprint": "118fda63ca3a",+ "full": "get_overview()"+ },+ "embedder": "mock",+ "embedder_degraded": false,+ "semantic_search": false,+ "source": "live_git",+ "response_budget": {+ "limit_chars": 24000,+ "tier": "default",+ "serialized_chars": 3031+ },+ "completeness": {+ "capped": false+ }+ }+}diff --git a/packages/claude-mod/test/fixtures/distill/git-diff.txt b/packages/claude-mod/test/fixtures/distill/git-diff.txtnew file mode 100644index 000000000..04db250f9--- /dev/null+++ b/packages/claude-mod/test/fixtures/distill/git-diff.txt@@ -0,0 +1,8 @@+diff: 18 files changed, +1280 -516++diff --git a/src/requests/_types.py b/src/requests/_types.py+new file mode 100644+index 00000000..6c2f59d0+--- /dev/null++[repowise#8ba29e69b831: 3391 lines omitted (~29929 tokens); restore: repowise expand 8ba29e69b831]diff --git a/packages/claude-mod/test/fixtures/distill/git-log.txt b/packages/claude-mod/test/fixtures/distill/git-log.txtnew file mode 100644index 000000000..c8b4edca5--- /dev/null+++ b/packages/claude-mod/test/fixtures/distill/git-log.txt@@ -0,0 +1,24 @@+300 commits (showing 20 most recent; subjects only)+3bb56ba5 Oct 3 2026 scratch: two files+4ed3d1b3 Jun 24 2026 Bump actions/checkout from 6.0.2 to 7.0.0 in the actions group (#7540)+d44b67eb Jun 24 2026 Bump https://github.com/astral-sh/ruff-pre-commit (#7536)+74c56d5f Jun 24 2026 Inline pre-commit linting (#7539)+d64b9ad4 Jun 15 2026 Bump https://github.com/astral-sh/ruff-pre-commit (#7515)+6f66281a Jun 9 2026 Add hasattr checks for remaining protocol isinstance checks (#7505)+6f205ff4 Jun 8 2026 Fix `_encode_files` detection for `__getattr__`-based file wrappers (#7502)+661970d1 Jun 8 2026 Disable commonly ignored Pyright linting rules (#7497)+fbd0eb37 Jun 8 2026 Bump https://github.com/astral-sh/ruff-pre-commit (#7503)+1190afd1 Jun 4 2026 Add type annotation for `Request.hooks` (#7498)+e50e5945 Jun 4 2026 Improve static typing of 3rd party imports (#7496)+3be097d4 Jun 2 2026 Bump https://github.com/astral-sh/ruff-pre-commit (#7493)+a634611d Jun 2 2026 Bump github/codeql-action from 4.35.1 to 4.36.0 in the actions group (#7492)+c4367f23 May 31 2026 Add AI Policy+cd90742e May 18 2026 docs: indent continuation line in Session.get :param params: (#7460)+6e83187b May 14 2026 v2.34.2+84d10f0b May 14 2026 Move Request.headers back to Mapping (#7441)+b7b549b5 May 13 2026 v2.34.1+e511bc72 May 13 2026 Fix mutability issues with headers input types (#7431)+5691f596 May 13 2026 Update JsonType containers to read-based collections (#7436)++[repowise#eed993b23bc3: 2928 lines omitted (~25947 tokens); restore: repowise expand eed993b23bc3]+diff --git a/packages/claude-mod/test/fixtures/distill/git-ls-files.txt b/packages/claude-mod/test/fixtures/distill/git-ls-files.txtnew file mode 100644index 000000000..94b6c5b52--- /dev/null+++ b/packages/claude-mod/test/fixtures/distill/git-ls-files.txt@@ -0,0 +1,27 @@+130 entries in 23 directories:+ ./ (16: .coveragerc, .git-blame-ignore-revs, .gitignore, .pre-commit-config.yaml, +12 more)+ .github/ (8: AI_POLICY.md, CODEOWNERS, CODE_OF_CONDUCT.md, CONTRIBUTING.md, +4 more)+ .github/ISSUE_TEMPLATE/ (3: Bug_report.md, Custom.md, Feature_request.md)+ .github/workflows/ (8: close-issues.yml, codeql-analysis.yml, lint.yml, lock-issues.yml, +4 more)+ docs/ (7: .nojekyll, Makefile, api.rst, conf.py, +3 more)+ docs/_static/ (2: custom.css, requests-sidebar.png)+ docs/_templates/ (1: sidebar.html)+ docs/_themes/ (3: .gitignore, LICENSE, flask_theme_support.py)+ docs/community/ (7: faq.rst, out-there.rst, recommended.rst, release-process.rst, +3 more)+ docs/dev/ (2: authors.rst, contributing.rst)+ docs/user/ (4: advanced.rst, authentication.rst, install.rst, quickstart.rst)+ ext/ (7: LICENSE, kr.png, psf.png, requests-logo-compressed.png, +3 more)+ src/requests/ (20: __init__.py, __version__.py, _internal_utils.py, _types.py, +16 more)+ tests/ (13: __init__.py, compat.py, conftest.py, test_adapters.py, +9 more)+ tests/certs/ (1: README.md)+ tests/certs/expired/ (2: Makefile, README.md)+ tests/certs/expired/ca/ (5: Makefile, ca-private.key, ca.cnf, ca.crt, +1 more)+ tests/certs/expired/server/ (5: Makefile, cert.cnf, server.csr, server.key, +1 more)+ tests/certs/mtls/ (2: Makefile, README.md)+ tests/certs/mtls/client/ (6: Makefile, ca, cert.cnf, client.csr, +2 more)+ tests/certs/valid/ (1: ca)+ tests/certs/valid/server/ (5: Makefile, cert.cnf, server.csr, server.key, +1 more)+ tests/testserver/ (2: __init__.py, server.py)++[repowise#41d94b327885: 106 lines omitted (~396 tokens); restore: repowise expand 41d94b327885]+diff --git a/packages/claude-mod/test/fixtures/distill/git-status-undistilled.txt b/packages/claude-mod/test/fixtures/distill/git-status-undistilled.txtnew file mode 100644index 000000000..b6e32616f--- /dev/null+++ b/packages/claude-mod/test/fixtures/distill/git-status-undistilled.txt@@ -0,0 +1,12 @@+On branch main+Your branch is ahead of 'origin/main' by 1 commit.+ (use "git push" to publish your local commits)++Untracked files:+ (use "git add <file>..." to include in what will be committed)+ .claude/+ .mcp.json+ .repowise/++nothing added to commit but untracked files present (use "git add" to track)+diff --git a/packages/claude-mod/test/fixtures/distill/grep.txt b/packages/claude-mod/test/fixtures/distill/grep.txtnew file mode 100644index 000000000..77d55cb48--- /dev/null+++ b/packages/claude-mod/test/fixtures/distill/grep.txt@@ -0,0 +1,50 @@+268 matches in 16 files:+ src/requests/cookies.py (52 matches)+ L45: def __init__(self, request: PreparedRequest) -> None:+ L604: def merge_cookies(+ src/requests/models.py (52 matches)+ L112: def path_url(self) -> str:+ L1173: def close(self) -> None:+ src/requests/utils.py (47 matches)+ L99: def proxy_bypass_registry(host: str) -> bool:+ L1139: def rewind_body(prepared_request: PreparedRequest) -> None:+ src/requests/sessions.py (29 matches)+ L76: def merge_setting(+ L908: def session() -> Session:+ src/requests/auth.py (24 matches)+ L34: def _basic_auth_str(username: bytes | str, password: bytes | str) -> str:+ L353: def __ne__(self, other: Any) -> bool:+ src/requests/adapters.py (20 matches)+ L66: def SOCKSProxyManager(*args: Any, **kwargs: Any) -> None:+ L634: def send(+ src/requests/structures.py (17 matches)+ L49: def __init__(+ L129: def get(self, key: str, default: _D | None = None) -> _VT | _D | None:+ src/requests/api.py (8 matches)+ L24: def request(+ L171: def delete(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:+ src/requests/_types.py (4 matches)+ L29: def read(self, length: int = ..., /) -> _T_co: ...+ L47: def is_prepared(request: PreparedRequest) -> TypeIs[_ValidatedRequest]:+ src/requests/exceptions.py (3 matches)+ L28: def __init__(self, *args: Any, **kwargs: Any) -> None:+ L55: def __reduce__(self) -> tuple[Any, ...] | str:+ src/requests/help.py (3 matches)+ L35: def _implementation():+ L126: def main():+ src/requests/hooks.py (2 matches)+ L25: def default_hooks() -> dict[str, list[_t.HookType]]:+ L32: def dispatch_hook(+ src/requests/status_codes.py (2 matches)+ L109: def _init():+ L116: def doc(code: int) -> str:+ src/requests/_internal_utils.py (2 matches)+ L26: def to_native_string(string: str | bytes, encoding: str = "ascii") -> str:+ L39: def unicode_is_ascii(u_string: str) -> bool:+ src/requests/__init__.py (2 matches)+ L60: def check_compatibility(+ L99: def _check_cryptography(cryptography_version: str) -> None:+ ... (1 more files, 1 matches)++[repowise#4d5207d9f4ad: 221 lines omitted (~4304 tokens); restore: repowise expand 4d5207d9f4ad]+diff --git a/packages/claude-mod/test/fixtures/distill/pytest-failing.txt b/packages/claude-mod/test/fixtures/distill/pytest-failing.txtnew file mode 100644index 000000000..1d37b94b8--- /dev/null+++ b/packages/claude-mod/test/fixtures/distill/pytest-failing.txt@@ -0,0 +1,62 @@+============================= test session starts =============================+platform win32 -- Python 3.13.5, pytest-9.0.2, pluggy-1.5.0 -- C:\Python313\python.exe+rootdir: C:\work\repo+tests\test_lens_squeeze.py::test_fails[3] FAILED [ 95%]+tests\test_lens_squeeze.py::test_fails[7] FAILED [ 96%]+tests\test_lens_squeeze.py::test_fails[11] FAILED [ 98%]+tests\test_lens_squeeze.py::test_fails[19] FAILED [100%]+================================== FAILURES ===================================+________________________________ test_fails[3] ________________________________++n = 3++ @pytest.mark.parametrize("n", [3, 7, 11, 19])+ def test_fails(n):+> assert n % 2 == 0, f"{n} is odd"+E AssertionError: 3 is odd+E assert (3 % 2) == 0++tests\test_lens_squeeze.py:11: AssertionError+________________________________ test_fails[7] ________________________________++n = 7++ @pytest.mark.parametrize("n", [3, 7, 11, 19])+ def test_fails(n):+> assert n % 2 == 0, f"{n} is odd"+E AssertionError: 7 is odd+E assert (7 % 2) == 0++tests\test_lens_squeeze.py:11: AssertionError+_______________________________ test_fails[11] ________________________________++n = 11++ @pytest.mark.parametrize("n", [3, 7, 11, 19])+ def test_fails(n):+> assert n % 2 == 0, f"{n} is odd"+E AssertionError: 11 is odd+E assert (11 % 2) == 0++tests\test_lens_squeeze.py:11: AssertionError+_______________________________ test_fails[19] ________________________________++n = 19++ @pytest.mark.parametrize("n", [3, 7, 11, 19])+ def test_fails(n):+> assert n % 2 == 0, f"{n} is odd"+E AssertionError: 19 is odd+E assert (19 % 2) == 0++tests\test_lens_squeeze.py:11: AssertionError+=========================== short test summary info ===========================+FAILED tests\test_lens_squeeze.py::test_fails[3]+FAILED tests\test_lens_squeeze.py::test_fails[7]+FAILED tests\test_lens_squeeze.py::test_fails[11]+FAILED tests\test_lens_squeeze.py::test_fails[19]+(63 progress lines omitted)+======================== 4 failed, 60 passed in 13.31s ========================++[repowise#21ece412acd8: 64 lines omitted (~2337 tokens); restore: repowise expand 21ece412acd8]+diff --git a/packages/claude-mod/test/fixtures/distill/ruff.txt b/packages/claude-mod/test/fixtures/distill/ruff.txtnew file mode 100644index 000000000..b0340b231--- /dev/null+++ b/packages/claude-mod/test/fixtures/distill/ruff.txt@@ -0,0 +1,8 @@+lint: 931 findings — 162 kept verbatim, 769 collapsed into 89 rules++S101 Use of `assert` detected (×16)+66 | assert urllib3_version_list != ["dev"] # Verify urllib3 isn't installed from git.+76 | assert major >= 1 (×3)+78 | assert minor >= 21 (×3)++[repowise#4f688e17124a: 11962 lines omitted (~103796 tokens); restore: repowise expand 4f688e17124a]diff --git a/packages/claude-mod/test/fixtures/django-blast-radius-query-depth1.json b/packages/claude-mod/test/fixtures/django-blast-radius-query-depth1.jsonnew file mode 100644index 000000000..c3163cb7a--- /dev/null+++ b/packages/claude-mod/test/fixtures/django-blast-radius-query-depth1.json@@ -0,0 +1,40 @@+{+ "transitive_affected": [+ {+ "path": "django/contrib/contenttypes/fields.py"+ },+ {+ "path": "django/contrib/contenttypes/prefetch.py"+ },+ {+ "path": "django/db/models/__init__.py"+ },+ {+ "path": "django/db/models/base.py"+ },+ {+ "path": "django/db/models/fields/related_descriptors.py"+ },+ {+ "path": "django/db/models/manager.py"+ },+ {+ "path": "django/db/models/sql/query.py"+ },+ {+ "path": "tests/basic/tests.py"+ },+ {+ "path": "tests/model_forms/tests.py"+ },+ {+ "path": "tests/prefetch_related/models.py"+ },+ {+ "path": "tests/prefetch_related/tests.py"+ },+ {+ "path": "tests/raw_query/tests.py"+ }+ ]+}\ No newline at end of filediff --git a/packages/claude-mod/test/fixtures/django-health-map.json b/packages/claude-mod/test/fixtures/django-health-map.jsonnew file mode 100644index 000000000..5f5bfd65a--- /dev/null+++ b/packages/claude-mod/test/fixtures/django-health-map.json@@ -0,0 +1 @@+{"cap":4000,"shown":2347,"eligible_total":2347,"repository_total":2970,"omitted":{"files":0},"files":[{"file_path":"django/http/response.py","score":2.0,"nloc":598},{"file_path":"django/db/backends/sqlite3/introspection.py","score":2.64,"nloc":387},{"file_path":"django/db/backends/mysql/base.py","score":5.01,"nloc":354},{"file_path":"django/core/management/templates.py","score":3.36,"nloc":347},{"file_path":"django/db/backends/sqlite3/base.py","score":7.8,"nloc":289},{"file_path":"django/core/management/utils.py","score":6.56,"nloc":148},{"file_path":"django/db/backends/mysql/creation.py","score":5.52,"nloc":89},{"file_path":"django/db/backends/base/introspection.py","score":7.0,"nloc":193},{"file_path":"django/db/backends/sqlite3/schema.py","score":2.2,"nloc":378},{"file_path":"django/db/backends/postgresql/schema.py","score":2.15,"nloc":325},{"file_path":"django/contrib/postgres/signals.py","score":9.24,"nloc":53},{"file_path":"django/db/backends/oracle/schema.py","score":2.53,"nloc":209},{"file_path":"scripts/manage_translations.py","score":6.0,"nloc":323},{"file_path":"tests/backends/sqlite/tests.py","score":7.8,"nloc":290},{"file_path":"scripts/pr_quality/check_pr.py","score":5.7,"nloc":496},{"file_path":"django/views/debug.py","score":2.0,"nloc":563},{"file_path":"tests/foreign_object/tests.py","score":8.0,"nloc":686},{"file_path":"tests/select_related/tests.py","score":7.0,"nloc":306},{"file_path":"tests/prefetch_related/tests.py","score":6.11,"nloc":1970},{"file_path":"tests/swappable_models/tests.py","score":9.0,"nloc":31},{"file_path":"tests/select_related_regress/tests.py","score":9.0,"nloc":215},{"file_path":"django/core/files/move.py","score":4.12,"nloc":66},{"file_path":"tests/backends/sqlite/test_introspection.py","score":10.0,"nloc":187},{"file_path":"django/core/files/images.py","score":4.2,"nloc":68},{"file_path":"django/core/management/commands/makemessages.py","score":2.5,"nloc":676},{"file_path":"django/contrib/admindocs/views.py","score":2.05,"nloc":399},{"file_path":"django/db/backends/base/schema.py","score":2.5,"nloc":1785},{"file_path":"django/db/migrations/writer.py","score":3.16,"nloc":254},{"file_path":"django/core/management/commands/inspectdb.py","score":2.74,"nloc":363},{"file_path":"django/contrib/admin/static/admin/js/calendar.js","score":2.5,"nloc":293},{"file_path":"django/forms/fields.py","score":2.5,"nloc":1120},{"file_path":"django/contrib/staticfiles/finders.py","score":8.0,"nloc":269},{"file_path":"django/template/library.py","score":4.89,"nloc":405},{"file_path":"django/test/utils.py","score":2.35,"nloc":780},{"file_path":"django/db/migrations/autodetector.py","score":2.35,"nloc":1824},{"file_path":"django/db/models/base.py","score":2.5,"nloc":2096},{"file_path":"django/apps/registry.py","score":5.43,"nloc":302},{"file_path":"django/urls/utils.py","score":6.8,"nloc":175},{"file_path":"django/db/models/sql/compiler.py","score":2.5,"nloc":1870},{"file_path":"django/core/management/base.py","score":3.16,"nloc":602},{"file_path":"django/core/serializers/__init__.py","score":3.89,"nloc":184},{"file_path":"django/core/management/commands/dumpdata.py","score":3.09,"nloc":255},{"file_path":"django/utils/formats.py","score":2.67,"nloc":252},{"file_path":"django/utils/csp.py","score":8.21,"nloc":68},{"file_path":"django/contrib/admin/static/admin/js/change_form.js","score":9.65,"nloc":19},{"file_path":"django/template/engine.py","score":6.11,"nloc":199},{"file_path":"django/contrib/admin/sites.py","score":3.61,"nloc":484},{"file_path":"django/core/management/__init__.py","score":2.05,"nloc":344},{"file_path":"django/db/models/deletion.py","score":2.5,"nloc":435},{"file_path":"django/db/models/fields/json.py","score":6.11,"nloc":579},{"file_path":"django/core/handlers/base.py","score":2.0,"nloc":311},{"file_path":"django/template/loader_tags.py","score":9.0,"nloc":299},{"file_path":"django/contrib/admin/utils.py","score":2.35,"nloc":523},{"file_path":"scripts/check_migrations.py","score":10.0,"nloc":19},{"file_path":"django/db/migrations/graph.py","score":4.95,"nloc":280},{"file_path":"django/db/migrations/migration.py","score":6.0,"nloc":171},{"file_path":"tests/forms_tests/tests/test_formsets.py","score":7.1,"nloc":1743},{"file_path":"docs/lint.py","score":7.46,"nloc":142},{"file_path":"tests/auth_tests/test_management.py","score":6.19,"nloc":1602},{"file_path":"tests/schema/tests.py","score":4.56,"nloc":4976},{"file_path":"tests/asgi/tests.py","score":6.82,"nloc":789},{"file_path":"tests/admin_views/tests.py","score":3.45,"nloc":8427},{"file_path":"tests/migrations/test_operations.py","score":3.5,"nloc":6450},{"file_path":"tests/migrations/test_autodetector.py","score":5.39,"nloc":5321},{"file_path":"tests/forms_tests/tests/test_forms.py","score":6.67,"nloc":4838},{"file_path":"tests/queries/tests.py","score":3.12,"nloc":3766},{"file_path":"tests/migrations/test_commands.py","score":4.74,"nloc":3298},{"file_path":"tests/admin_scripts/tests.py","score":2.5,"nloc":3124},{"file_path":"tests/model_forms/tests.py","score":5.49,"nloc":3117},{"file_path":"tests/cache/tests.py","score":3.7,"nloc":2734},{"file_path":"tests/expressions/tests.py","score":4.62,"nloc":2635},{"file_path":"tests/invalid_models_tests/test_models.py","score":7.8,"nloc":2632},{"file_path":"tests/mail/tests.py","score":3.5,"nloc":2629},{"file_path":"tests/aggregation/tests.py","score":7.8,"nloc":2591},{"file_path":"django/db/models/query.py","score":2.0,"nloc":2471},{"file_path":"django/db/models/fields/__init__.py","score":2.2,"nloc":2464},{"file_path":"django/contrib/admin/options.py","score":2.35,"nloc":2417},{"file_path":"tests/admin_inlines/tests.py","score":4.81,"nloc":2339},{"file_path":"django/db/models/sql/query.py","score":2.5,"nloc":2256},{"file_path":"tests/invalid_models_tests/test_relative_fields.py","score":8.3,"nloc":2212},{"file_path":"tests/model_formsets/tests.py","score":6.6,"nloc":2112},{"file_path":"tests/test_utils/tests.py","score":5.09,"nloc":2054},{"file_path":"tests/i18n/tests.py","score":5.59,"nloc":2023},{"file_path":"tests/expressions_window/tests.py","score":6.64,"nloc":1941},{"file_path":"tests/migrations/test_state.py","score":6.74,"nloc":1929},{"file_path":"tests/multiple_database/tests.py","score":6.64,"nloc":1916},{"file_path":"tests/view_tests/tests/test_debug.py","score":3.12,"nloc":1883},{"file_path":"tests/admin_changelist/tests.py","score":7.6,"nloc":1859},{"file_path":"tests/db_functions/datetime/test_extract_trunc.py","score":5.5,"nloc":1844},{"file_path":"django/db/models/fields/related.py","score":2.35,"nloc":1825},{"file_path":"django/db/models/expressions.py","score":2.0,"nloc":1777},{"file_path":"tests/lookup/tests.py","score":7.8,"nloc":1772},{"file_path":"tests/aggregation_regress/tests.py","score":7.0,"nloc":1713},{"file_path":"tests/admin_widgets/tests.py","score":4.98,"nloc":1707},{"file_path":"tests/urlpatterns_reverse/tests.py","score":4.68,"nloc":1686},{"file_path":"tests/admin_filters/tests.py","score":6.49,"nloc":1608},{"file_path":"django/test/testcases.py","score":2.0,"nloc":1578},{"file_path":"tests/expressions_case/tests.py","score":6.0,"nloc":1547},{"file_path":"tests/auth_tests/test_forms.py","score":5.84,"nloc":1538},{"file_path":"django/test/client.py","score":3.16,"nloc":1527},{"file_path":"tests/modeladmin/test_checks.py","score":3.5,"nloc":1492},{"file_path":"tests/requests_tests/tests.py","score":7.2,"nloc":1492},{"file_path":"tests/auth_tests/test_views.py","score":7.6,"nloc":1491},{"file_path":"tests/migrations/test_optimizer.py","score":5.89,"nloc":1442},{"file_path":"tests/annotations/tests.py","score":6.64,"nloc":1428},{"file_path":"tests/postgres_tests/test_array.py","score":5.34,"nloc":1403},{"file_path":"django/forms/models.py","score":2.05,"nloc":1347},{"file_path":"tests/gis_tests/geos_tests/test_geos.py","score":3.15,"nloc":1345},{"file_path":"tests/model_fields/test_jsonfield.py","score":6.09,"nloc":1345},{"file_path":"tests/constraints/tests.py","score":5.79,"nloc":1339},{"file_path":"tests/csrf_tests/tests.py","score":5.74,"nloc":1316},{"file_path":"tests/invalid_models_tests/test_ordinary_fields.py","score":9.0,"nloc":1314},{"file_path":"django/db/models/fields/related_descriptors.py","score":2.94,"nloc":1309},{"file_path":"django/template/defaulttags.py","score":2.5,"nloc":1291},{"file_path":"tests/postgres_tests/test_constraints.py","score":6.14,"nloc":1271},{"file_path":"django/contrib/admin/checks.py","score":2.5,"nloc":1262},{"file_path":"tests/auth_tests/test_auth_backends.py","score":5.84,"nloc":1218},{"file_path":"tests/timezones/tests.py","score":5.12,"nloc":1196},{"file_path":"tests/admin_views/admin.py","score":8.7,"nloc":1190},{"file_path":"tests/test_client_regress/tests.py","score":8.7,"nloc":1174},{"file_path":"tests/migrations/test_writer.py","score":8.7,"nloc":1163},{"file_path":"tests/test_client/tests.py","score":9.0,"nloc":1155},{"file_path":"tests/filtered_relation/tests.py","score":7.8,"nloc":1117},{"file_path":"django/db/migrations/operations/models.py","score":2.5,"nloc":1072},{"file_path":"django/forms/widgets.py","score":2.35,"nloc":1062},{"file_path":"tests/staticfiles_tests/test_storage.py","score":6.44,"nloc":1042},{"file_path":"django/test/runner.py","score":2.35,"nloc":1036},{"file_path":"tests/sessions_tests/tests.py","score":7.8,"nloc":1032},{"file_path":"tests/file_storage/tests.py","score":6.14,"nloc":1010},{"file_path":"tests/postgres_tests/test_ranges.py","score":6.54,"nloc":999},{"file_path":"tests/i18n/test_extraction.py","score":5.94,"nloc":984},{"file_path":"tests/middleware/tests.py","score":9.0,"nloc":975},{"file_path":"django/template/base.py","score":2.35,"nloc":962},{"file_path":"tests/modeladmin/tests.py","score":7.8,"nloc":960},{"file_path":"tests/mail/test_backends.py","score":5.9,"nloc":912},{"file_path":"tests/basic/tests.py","score":5.34,"nloc":907},{"file_path":"tests/fixtures_regress/tests.py","score":5.49,"nloc":907},{"file_path":"tests/gis_tests/gdal_tests/test_geom.py","score":8.25,"nloc":907},{"file_path":"tests/test_runner/tests.py","score":5.18,"nloc":905},{"file_path":"tests/validators/tests.py","score":8.3,"nloc":899},{"file_path":"tests/model_meta/results.py","score":9.59,"nloc":894},{"file_path":"tests/admin_checks/tests.py","score":9.0,"nloc":891},{"file_path":"tests/postgres_tests/test_search.py","score":7.3,"nloc":879},{"file_path":"scripts/pr_quality/tests/test_check_pr.py","score":4.59,"nloc":873},{"file_path":"tests/file_uploads/tests.py","score":6.49,"nloc":861},{"file_path":"tests/admin_views/test_actions.py","score":9.0,"nloc":848},{"file_path":"tests/gis_tests/gdal_tests/test_raster.py","score":6.14,"nloc":845},{"file_path":"tests/bulk_create/tests.py","score":7.0,"nloc":834},{"file_path":"tests/httpwrappers/tests.py","score":4.0,"nloc":834},{"file_path":"tests/migrations/test_executor.py","score":7.8,"nloc":832},{"file_path":"django/db/models/options.py","score":2.0,"nloc":831},{"file_path":"tests/forms_tests/tests/test_media.py","score":7.1,"nloc":831},{"file_path":"tests/gis_tests/geoapp/test_functions.py","score":5.12,"nloc":822},{"file_path":"tests/many_to_one/tests.py","score":7.1,"nloc":819},{"file_path":"django/db/migrations/state.py","score":2.0,"nloc":817},{"file_path":"tests/backends/tests.py","score":4.1,"nloc":813},{"file_path":"tests/admin_views/models.py","score":8.0,"nloc":810},{"file_path":"tests/logging_tests/tests.py","score":6.34,"nloc":809},{"file_path":"tests/template_tests/test_custom.py","score":6.57,"nloc":808},{"file_path":"tests/pagination/tests.py","score":5.99,"nloc":803},{"file_path":"tests/template_tests/syntax_tests/i18n/test_blocktranslate.py","score":9.59,"nloc":802},{"file_path":"tests/utils_tests/test_autoreload.py","score":5.36,"nloc":802},{"file_path":"django/template/defaultfilters.py","score":2.0,"nloc":776},{"file_path":"tests/generic_relations/tests.py","score":8.3,"nloc":773},{"file_path":"django/db/backends/base/operations.py","score":2.6,"nloc":770},{"file_path":"tests/syndication_tests/tests.py","score":7.8,"nloc":751},{"file_path":"tests/queries/test_qs_combinators.py","score":7.0,"nloc":748},{"file_path":"tests/check_framework/test_security.py","score":9.0,"nloc":742},{"file_path":"tests/generic_views/test_dates.py","score":9.0,"nloc":740},{"file_path":"tests/test_runner/test_discover_runner.py","score":7.0,"nloc":737},{"file_path":"tests/postgres_tests/test_aggregates.py","score":5.89,"nloc":725},{"file_path":"tests/delete/tests.py","score":7.8,"nloc":707},{"file_path":"django/contrib/contenttypes/fields.py","score":3.1,"nloc":702},{"file_path":"django/urls/resolvers.py","score":2.5,"nloc":695},{"file_path":"tests/forms_tests/widget_tests/test_selectdatewidget.py","score":8.3,"nloc":694},{"file_path":"tests/signals/tests.py","score":9.0,"nloc":694},{"file_path":"django/http/request.py","score":2.35,"nloc":682},{"file_path":"tests/custom_managers/tests.py","score":8.3,"nloc":681},{"file_path":"django/contrib/gis/gdal/geometries.py","score":3.35,"nloc":672},{"file_path":"tests/auth_tests/test_hashers.py","score":7.12,"nloc":671},{"file_path":"tests/postgres_tests/test_indexes.py","score":8.3,"nloc":669},{"file_path":"tests/ordering/tests.py","score":9.0,"nloc":667},{"file_path":"tests/runtests.py","score":4.3,"nloc":663},{"file_path":"tests/get_or_create/tests.py","score":6.64,"nloc":661},{"file_path":"tests/gis_tests/geoapp/tests.py","score":6.04,"nloc":655},{"file_path":"tests/migrations/test_loader.py","score":7.8,"nloc":647},{"file_path":"django/contrib/gis/geos/geometry.py","score":4.53,"nloc":642},{"file_path":"django/conf/locale/__init__.py","score":9.0,"nloc":634},{"file_path":"tests/m2m_signals/tests.py","score":9.24,"nloc":633},{"file_path":"django/views/generic/dates.py","score":3.49,"nloc":632},{"file_path":"django/db/models/constraints.py","score":2.66,"nloc":629},{"file_path":"tests/postgres_tests/test_operations.py","score":8.39,"nloc":624},{"file_path":"django/db/models/lookups.py","score":5.11,"nloc":623},{"file_path":"tests/forms_tests/tests/test_input_formats.py","score":5.89,"nloc":622},{"file_path":"django/contrib/admin/filters.py","score":4.61,"nloc":620},{"file_path":"tests/inspectdb/tests.py","score":9.0,"nloc":619},{"file_path":"tests/indexes/tests.py","score":9.0,"nloc":617},{"file_path":"django/db/backends/base/base.py","score":3.7,"nloc":613},{"file_path":"tests/humanize_tests/tests.py","score":8.3,"nloc":612},{"file_path":"tests/gis_tests/distapp/tests.py","score":5.34,"nloc":611},{"file_path":"tests/staticfiles_tests/test_management.py","score":7.1,"nloc":607},{"file_path":"tests/custom_lookups/tests.py","score":6.19,"nloc":605},{"file_path":"tests/field_deconstruction/tests.py","score":9.0,"nloc":600},{"file_path":"tests/template_tests/syntax_tests/test_partials.py","score":10.0,"nloc":589},{"file_path":"tests/postgres_tests/migrations/0002_create_test_models.py","score":9.0,"nloc":587},{"file_path":"tests/template_tests/syntax_tests/test_if.py","score":9.59,"nloc":587},{"file_path":"tests/select_for_update/tests.py","score":7.19,"nloc":584},{"file_path":"tests/many_to_many/tests.py","score":9.0,"nloc":577},{"file_path":"django/contrib/admin/static/admin/js/admin/DateTimeShortcuts.js","score":7.31,"nloc":571},{"file_path":"tests/composite_pk/test_filter.py","score":9.85,"nloc":570},{"file_path":"django/db/backends/oracle/operations.py","score":7.0,"nloc":569},{"file_path":"tests/generic_views/test_base.py","score":9.0,"nloc":564},{"file_path":"tests/model_inheritance_regress/tests.py","score":7.0,"nloc":562},{"file_path":"tests/utils_tests/test_http.py","score":6.4,"nloc":562},{"file_path":"django/core/mail/message.py","score":2.5,"nloc":561},{"file_path":"tests/user_commands/tests.py","score":7.1,"nloc":559},{"file_path":"django/contrib/auth/hashers.py","score":4.6,"nloc":553},{"file_path":"django/http/multipartparser.py","score":2.5,"nloc":549},{"file_path":"django/core/validators.py","score":4.01,"nloc":547},{"file_path":"tests/admin_docs/test_views.py","score":9.0,"nloc":546},{"file_path":"django/contrib/gis/utils/layermapping.py","score":2.35,"nloc":544},{"file_path":"django/utils/autoreload.py","score":2.0,"nloc":538},{"file_path":"tests/one_to_one/tests.py","score":7.1,"nloc":536},{"file_path":"tests/model_inheritance/tests.py","score":6.79,"nloc":535},{"file_path":"tests/backends/postgresql/tests.py","score":7.5,"nloc":532},{"file_path":"tests/auth_tests/test_models.py","score":6.44,"nloc":531},{"file_path":"tests/admin_views/test_autocomplete_view.py","score":8.0,"nloc":530},{"file_path":"tests/settings_tests/tests.py","score":6.71,"nloc":529},{"file_path":"tests/template_tests/test_partials.py","score":10.0,"nloc":528},{"file_path":"django/contrib/admin/static/admin/js/urlify.js","score":9.0,"nloc":522},{"file_path":"tests/model_fields/models.py","score":9.0,"nloc":522},{"file_path":"tests/sitemaps_tests/test_http.py","score":7.8,"nloc":522},{"file_path":"django/contrib/admin/widgets.py","score":7.5,"nloc":513},{"file_path":"tests/view_tests/tests/test_i18n.py","score":7.8,"nloc":509},{"file_path":"tests/apps/tests.py","score":6.79,"nloc":506},{"file_path":"django/utils/translation/trans_real.py","score":3.21,"nloc":503},{"file_path":"django/contrib/auth/models.py","score":5.08,"nloc":502},{"file_path":"tests/decorators/tests.py","score":6.54,"nloc":501},{"file_path":"django/templatetags/i18n.py","score":3.91,"nloc":498},{"file_path":"django/contrib/auth/forms.py","score":6.49,"nloc":495},{"file_path":"django/contrib/staticfiles/storage.py","score":2.35,"nloc":495},{"file_path":"django/contrib/gis/db/models/functions.py","score":6.8,"nloc":492},{"file_path":"django/db/backends/oracle/base.py","score":2.35,"nloc":492},{"file_path":"tests/auth_tests/test_remote_user.py","score":7.8,"nloc":490},{"file_path":"django/contrib/admin/helpers.py","score":4.12,"nloc":489},{"file_path":"tests/foreign_object/test_tuple_lookups.py","score":10.0,"nloc":484},{"file_path":"tests/urlpatterns/tests.py","score":9.0,"nloc":484},{"file_path":"tests/forms_tests/widget_tests/test_radioselect.py","score":9.24,"nloc":483},{"file_path":"tests/model_formsets_regress/tests.py","score":7.02,"nloc":482},{"file_path":"django/contrib/admin/static/admin/js/SelectFilter2.js","score":4.75,"nloc":480},{"file_path":"django/db/backends/postgresql/base.py","score":2.55,"nloc":479},{"file_path":"tests/template_tests/filter_tests/test_urlize.py","score":9.0,"nloc":478},{"file_path":"django/forms/formsets.py","score":3.45,"nloc":475},{"file_path":"django/contrib/admin/templatetags/admin_list.py","score":2.5,"nloc":474},{"file_path":"tests/generic_inline_admin/tests.py","score":9.0,"nloc":474},{"file_path":"django/core/serializers/xml_serializer.py","score":2.35,"nloc":467},{"file_path":"tests/queries/models.py","score":8.7,"nloc":465},{"file_path":"django/contrib/admin/views/main.py","score":2.35,"nloc":462},{"file_path":"tests/gis_tests/test_geoforms.py","score":9.0,"nloc":462},{"file_path":"tests/admin_utils/tests.py","score":8.3,"nloc":460},{"file_path":"tests/utils_tests/test_html.py","score":7.05,"nloc":460},{"file_path":"tests/shell/tests.py","score":8.29,"nloc":454},{"file_path":"tests/transactions/tests.py","score":7.8,"nloc":453},{"file_path":"django/core/management/commands/migrate.py","score":2.5,"nloc":451},{"file_path":"django/db/models/query_utils.py","score":3.0,"nloc":448},{"file_path":"tests/forms_tests/tests/tests.py","score":8.3,"nloc":445},{"file_path":"tests/m2m_through/tests.py","score":8.3,"nloc":445},{"file_path":"django/core/management/commands/makemigrations.py","score":2.5,"nloc":441},{"file_path":"django/db/backends/sqlite3/_functions.py","score":8.01,"nloc":437},{"file_path":"tests/serializers/tests.py","score":7.8,"nloc":437},{"file_path":"tests/auth_tests/test_checks.py","score":9.24,"nloc":436},{"file_path":"tests/i18n/patterns/tests.py","score":8.3,"nloc":429},{"file_path":"django/dispatch/dispatcher.py","score":3.8,"nloc":427},{"file_path":"tests/files/tests.py","score":6.79,"nloc":425},{"file_path":"django/contrib/gis/gdal/raster/source.py","score":2.5,"nloc":423},{"file_path":"django/utils/feedgenerator.py","score":3.46,"nloc":422},{"file_path":"django/contrib/sessions/backends/base.py","score":6.0,"nloc":420},{"file_path":"django/db/backends/oracle/creation.py","score":2.0,"nloc":417},{"file_path":"tests/serializers/test_data.py","score":9.0,"nloc":414},{"file_path":"django/utils/html.py","score":4.12,"nloc":412},{"file_path":"django/contrib/postgres/search.py","score":6.89,"nloc":410},{"file_path":"tests/template_tests/syntax_tests/test_extends.py","score":9.59,"nloc":410},{"file_path":"tests/admin_utils/test_logentry.py","score":9.0,"nloc":408},{"file_path":"tests/composite_pk/tests.py","score":7.79,"nloc":407},{"file_path":"tests/migrations/test_graph.py","score":7.34,"nloc":405},{"file_path":"django/db/backends/oracle/introspection.py","score":3.71,"nloc":403},{"file_path":"tests/introspection/tests.py","score":3.75,"nloc":403},{"file_path":"django/utils/text.py","score":8.3,"nloc":402},{"file_path":"tests/postgres_tests/test_hstore.py","score":5.69,"nloc":402},{"file_path":"tests/forms_tests/widget_tests/test_select.py","score":9.24,"nloc":400},{"file_path":"tests/model_fields/tests.py","score":7.0,"nloc":400},{"file_path":"tests/generic_views/test_edit.py","score":9.0,"nloc":399},{"file_path":"tests/gis_tests/rasterapp/test_rasterfield.py","score":3.6,"nloc":397},{"file_path":"tests/migrations/test_base.py","score":2.45,"nloc":397},{"file_path":"tests/sitemaps_tests/urls/http.py","score":9.0,"nloc":395},{"file_path":"tests/extra_regress/tests.py","score":8.3,"nloc":394},{"file_path":"tests/raw_query/tests.py","score":6.84,"nloc":394},{"file_path":"tests/model_forms/models.py","score":8.3,"nloc":387},{"file_path":"tests/gis_tests/geos_tests/test_mutable_list.py","score":4.68,"nloc":386},{"file_path":"tests/utils_tests/test_lazyobject.py","score":9.0,"nloc":386},{"file_path":"tests/utils_tests/test_text.py","score":9.0,"nloc":383},{"file_path":"tests/template_tests/syntax_tests/test_basic.py","score":9.24,"nloc":382},{"file_path":"tests/proxy_models/tests.py","score":7.0,"nloc":381},{"file_path":"tests/model_forms/test_modelchoicefield.py","score":7.8,"nloc":378},{"file_path":"tests/admin_inlines/admin.py","score":9.0,"nloc":375},{"file_path":"tests/defer/tests.py","score":6.4,"nloc":373},{"file_path":"django/db/models/aggregates.py","score":4.07,"nloc":369},{"file_path":"tests/model_fields/test_imagefield.py","score":9.0,"nloc":368},{"file_path":"tests/middleware_exceptions/tests.py","score":8.89,"nloc":367},{"file_path":"tests/model_inheritance/test_abstract_inheritance.py","score":8.64,"nloc":366},{"file_path":"django/contrib/admin/static/admin/js/inlines.js","score":6.49,"nloc":365},{"file_path":"django/core/paginator.py","score":7.5,"nloc":365},{"file_path":"tests/model_fields/test_generatedfield.py","score":8.64,"nloc":365},{"file_path":"tests/gis_tests/gdal_tests/test_srs.py","score":6.26,"nloc":364},{"file_path":"tests/gis_tests/gis_migrations/test_operations.py","score":6.89,"nloc":364},{"file_path":"django/core/management/commands/loaddata.py","score":3.34,"nloc":363},{"file_path":"django/db/models/fields/files.py","score":4.21,"nloc":362},{"file_path":"tests/generic_views/urls.py","score":9.0,"nloc":362},{"file_path":"tests/requests_tests/test_accept_header.py","score":9.44,"nloc":362},{"file_path":"tests/gis_tests/relatedapp/tests.py","score":7.0,"nloc":361},{"file_path":"tests/mail/test_deprecated.py","score":10.0,"nloc":359},{"file_path":"tests/template_tests/syntax_tests/test_include.py","score":7.8,"nloc":358},{"file_path":"django/db/migrations/loader.py","score":2.5,"nloc":355},{"file_path":"tests/queries/test_q.py","score":7.1,"nloc":353},{"file_path":"django/db/models/indexes.py","score":4.8,"nloc":352},{"file_path":"django/forms/forms.py","score":4.5,"nloc":352},{"file_path":"tests/serializers/test_natural.py","score":9.24,"nloc":352},{"file_path":"tests/template_tests/syntax_tests/test_for.py","score":9.59,"nloc":352},{"file_path":"django/core/cache/backends/base.py","score":6.7,"nloc":348},{"file_path":"tests/test_exceptions/test_validation_error.py","score":9.5,"nloc":346},{"file_path":"django/contrib/staticfiles/management/commands/collectstatic.py","score":2.2,"nloc":343},{"file_path":"tests/check_framework/test_model_checks.py","score":9.24,"nloc":342},{"file_path":"tests/generic_relations/test_forms.py","score":9.25,"nloc":341},{"file_path":"django/contrib/gis/db/backends/postgis/operations.py","score":3.9,"nloc":340},{"file_path":"django/db/backends/mysql/introspection.py","score":4.5,"nloc":340},{"file_path":"django/middleware/csrf.py","score":4.0,"nloc":340},{"file_path":"django/core/serializers/base.py","score":2.2,"nloc":339},{"file_path":"tests/queryset_pickle/tests.py","score":7.0,"nloc":339},{"file_path":"django/utils/http.py","score":2.2,"nloc":338},{"file_path":"django/utils/cache.py","score":4.6,"nloc":336},{"file_path":"django/db/models/fields/tuple_lookups.py","score":9.45,"nloc":335},{"file_path":"tests/admin_views/test_templatetags.py","score":8.89,"nloc":335},{"file_path":"django/db/backends/mysql/operations.py","score":5.19,"nloc":334},{"file_path":"tests/auth_tests/test_decorators.py","score":6.69,"nloc":334},{"file_path":"tests/deprecation/test_deprecate_posargs.py","score":10.0,"nloc":334},{"file_path":"tests/test_client/views.py","score":9.0,"nloc":334},{"file_path":"django/db/backends/sqlite3/operations.py","score":4.82,"nloc":333},{"file_path":"tests/utils_tests/test_datastructures.py","score":7.1,"nloc":333},{"file_path":"tests/template_tests/syntax_tests/test_if_changed.py","score":9.59,"nloc":331},{"file_path":"tests/auth_tests/test_validators.py","score":8.3,"nloc":330},{"file_path":"tests/serializers/test_json.py","score":8.49,"nloc":330},{"file_path":"django/contrib/gis/db/models/fields.py","score":4.38,"nloc":329},{"file_path":"django/core/mail/__init__.py","score":6.0,"nloc":329},{"file_path":"django/db/migrations/executor.py","score":2.5,"nloc":329},{"file_path":"tests/servers/tests.py","score":9.0,"nloc":327},{"file_path":"tests/check_framework/tests.py","score":6.79,"nloc":326},{"file_path":"tests/delete_regress/tests.py","score":8.3,"nloc":326},{"file_path":"tests/messages_tests/base.py","score":7.8,"nloc":326},{"file_path":"tests/backends/base/test_base.py","score":8.64,"nloc":323},{"file_path":"tests/check_framework/test_urls.py","score":8.3,"nloc":323},{"file_path":"django/db/models/functions/datetime.py","score":6.71,"nloc":322},{"file_path":"tests/update/tests.py","score":6.79,"nloc":321},{"file_path":"django/db/migrations/serializer.py","score":7.31,"nloc":320},{"file_path":"tests/defer_regress/tests.py","score":9.0,"nloc":320},{"file_path":"django/db/models/fields/reverse_related.py","score":6.24,"nloc":319},{"file_path":"tests/queries/test_bulk_update.py","score":8.24,"nloc":317},{"file_path":"tests/template_tests/test_response.py","score":9.0,"nloc":316},{"file_path":"tests/handlers/tests.py","score":7.8,"nloc":315},{"file_path":"django/conf/__init__.py","score":6.31,"nloc":314},{"file_path":"tests/model_indexes/tests.py","score":7.8,"nloc":314},{"file_path":"tests/utils_tests/test_choices.py","score":9.4,"nloc":314},{"file_path":"django/contrib/postgres/fields/array.py","score":6.5,"nloc":313},{"file_path":"django/db/backends/base/creation.py","score":4.88,"nloc":312},{"file_path":"django/db/backends/postgresql/operations.py","score":5.31,"nloc":312},{"file_path":"django/forms/boundfield.py","score":4.8,"nloc":312},{"file_path":"tests/model_meta/tests.py","score":8.3,"nloc":308},{"file_path":"django/utils/functional.py","score":4.47,"nloc":307},{"file_path":"tests/contenttypes_tests/test_models.py","score":7.8,"nloc":307},{"file_path":"django/conf/global_settings.py","score":9.0,"nloc":306},{"file_path":"django/contrib/auth/__init__.py","score":2.2,"nloc":306},{"file_path":"tests/view_tests/views.py","score":8.0,"nloc":304},{"file_path":"django/utils/deprecation.py","score":7.01,"nloc":303},{"file_path":"django/contrib/gis/gdal/srs.py","score":7.01,"nloc":302},{"file_path":"django/db/migrations/questioner.py","score":3.16,"nloc":302},{"file_path":"tests/forms_tests/tests/test_error_messages.py","score":8.3,"nloc":302},{"file_path":"django/contrib/auth/views.py","score":7.8,"nloc":300},{"file_path":"tests/gis_tests/layermap/tests.py","score":7.8,"nloc":299},{"file_path":"django/contrib/gis/measure.py","score":7.8,"nloc":298},{"file_path":"django/db/migrations/operations/fields.py","score":5.91,"nloc":296},{"file_path":"django/core/checks/security/base.py","score":8.7,"nloc":294},{"file_path":"tests/forms_tests/widget_tests/test_multiwidget.py","score":8.99,"nloc":294},{"file_path":"django/contrib/admin/static/admin/js/admin/RelatedObjectLookups.js","score":7.01,"nloc":293},{"file_path":"django/db/backends/postgresql/introspection.py","score":4.8,"nloc":293},{"file_path":"django/contrib/postgres/fields/ranges.py","score":7.1,"nloc":292},{"file_path":"django/contrib/gis/static/gis/js/OLMapWidget.js","score":4.68,"nloc":291},{"file_path":"tests/backends/base/test_creation.py","score":8.89,"nloc":291},{"file_path":"tests/sites_tests/tests.py","score":7.6,"nloc":290},{"file_path":"django/core/handlers/asgi.py","score":3.75,"nloc":289},{"file_path":"django/utils/datastructures.py","score":5.5,"nloc":288},{"file_path":"tests/backends/test_ddl_references.py","score":9.24,"nloc":288},{"file_path":"tests/gis_tests/geo3d/tests.py","score":8.3,"nloc":288},{"file_path":"tests/model_fields/test_uuid.py","score":7.39,"nloc":288},{"file_path":"django/contrib/auth/management/commands/createsuperuser.py","score":3.09,"nloc":286},{"file_path":"tests/generic_relations_regress/tests.py","score":7.34,"nloc":286},{"file_path":"tests/model_fields/test_integerfield.py","score":9.09,"nloc":282},{"file_path":"django/db/models/functions/text.py","score":9.0,"nloc":281},{"file_path":"docs/_ext/djangodocs.py","score":6.25,"nloc":281},{"file_path":"django/contrib/gis/db/models/lookups.py","score":8.3,"nloc":279},{"file_path":"django/contrib/auth/backends.py","score":5.28,"nloc":278},{"file_path":"tests/middleware/test_security.py","score":9.0,"nloc":278},{"file_path":"tests/select_related_onetoone/tests.py","score":7.8,"nloc":274},{"file_path":"django/utils/regex_helper.py","score":2.35,"nloc":273},{"file_path":"django/contrib/humanize/templatetags/humanize.py","score":7.31,"nloc":272},{"file_path":"django/db/models/sql/where.py","score":4.0,"nloc":271},{"file_path":"tests/forms_tests/tests/test_utils.py","score":7.0,"nloc":269},{"file_path":"tests/test_runner/test_debug_sql.py","score":9.24,"nloc":269},{"file_path":"django/db/backends/utils.py","score":5.25,"nloc":267},{"file_path":"django/utils/lorem_ipsum.py","score":9.59,"nloc":267},{"file_path":"tests/tasks/test_tasks.py","score":8.9,"nloc":267},{"file_path":"django/contrib/postgres/operations.py","score":6.09,"nloc":266},{"file_path":"tests/i18n/test_compilation.py","score":7.1,"nloc":266},{"file_path":"tests/serializers/test_jsonl.py","score":9.1,"nloc":265},{"file_path":"tests/template_tests/test_context.py","score":7.64,"nloc":265},{"file_path":"django/utils/dateformat.py","score":8.7,"nloc":264},{"file_path":"tests/composite_pk/test_checks.py","score":9.4,"nloc":262},{"file_path":"tests/transaction_hooks/tests.py","score":8.14,"nloc":262},{"file_path":"tests/utils_tests/test_timesince.py","score":9.0,"nloc":260},{"file_path":"tests/template_tests/syntax_tests/i18n/test_translate.py","score":9.44,"nloc":259},{"file_path":"django/utils/log.py","score":6.19,"nloc":258},{"file_path":"tests/gis_tests/gdal_tests/test_ds.py","score":4.0,"nloc":258},{"file_path":"tests/update_only_fields/tests.py","score":7.8,"nloc":257},{"file_path":"tests/utils_tests/test_functional.py","score":7.8,"nloc":256},{"file_path":"tests/contenttypes_tests/test_checks.py","score":9.09,"nloc":255},{"file_path":"tests/forms_tests/widget_tests/test_checkboxselectmultiple.py","score":9.09,"nloc":255},{"file_path":"tests/tasks/test_immediate_backend.py","score":9.3,"nloc":253},{"file_path":"tests/template_tests/syntax_tests/test_url.py","score":9.59,"nloc":253},{"file_path":"django/core/cache/backends/db.py","score":5.2,"nloc":252},{"file_path":"django/contrib/gis/geos/prototypes/io.py","score":9.0,"nloc":251},{"file_path":"tests/test_runner/test_parallel.py","score":8.3,"nloc":248},{"file_path":"tests/gis_tests/test_measure.py","score":8.3,"nloc":247},{"file_path":"tests/responses/test_fileresponse.py","score":9.59,"nloc":247},{"file_path":"tests/nested_foreign_keys/tests.py","score":9.59,"nloc":246},{"file_path":"django/db/transaction.py","score":2.5,"nloc":245},{"file_path":"tests/model_enums/tests.py","score":8.64,"nloc":244},{"file_path":"tests/admin_inlines/models.py","score":8.3,"nloc":243},{"file_path":"tests/utils_tests/test_dateformat.py","score":7.8,"nloc":243},{"file_path":"django/core/signing.py","score":8.4,"nloc":242},{"file_path":"tests/contenttypes_tests/test_views.py","score":8.64,"nloc":240},{"file_path":"django/template/context.py","score":6.64,"nloc":239},{"file_path":"tests/backends/base/test_operations.py","score":7.5,"nloc":239},{"file_path":"django/contrib/gis/geos/mutable_list.py","score":7.34,"nloc":238},{"file_path":"tests/file_storage/test_inmemory_storage.py","score":9.35,"nloc":237},{"file_path":"tests/template_tests/templatetags/custom.py","score":8.7,"nloc":237},{"file_path":"tests/template_tests/test_loaders.py","score":9.0,"nloc":237},{"file_path":"django/core/files/storage/memory.py","score":8.3,"nloc":236},{"file_path":"tests/auth_tests/test_middleware.py","score":9.24,"nloc":233},{"file_path":"tests/auth_tests/test_mixins.py","score":9.59,"nloc":233},{"file_path":"tests/requests_tests/test_data_upload_settings.py","score":9.59,"nloc":233},{"file_path":"tests/conditional_processing/tests.py","score":9.59,"nloc":232},{"file_path":"tests/dispatch/tests.py","score":7.8,"nloc":232},{"file_path":"django/views/generic/base.py","score":8.3,"nloc":231},{"file_path":"tests/inline_formsets/tests.py","score":7.8,"nloc":231},{"file_path":"django/contrib/auth/checks.py","score":6.0,"nloc":230},{"file_path":"js_tests/admin/SelectFilter2.test.js","score":8.74,"nloc":230},{"file_path":"js_tests/gis/mapwidget.test.js","score":9.85,"nloc":230},{"file_path":"tests/template_tests/syntax_tests/test_querystring.py","score":9.85,"nloc":230},{"file_path":"django/contrib/auth/password_validation.py","score":4.38,"nloc":228},{"file_path":"tests/aggregation/test_filter_argument.py","score":8.9,"nloc":228},{"file_path":"tests/get_earliest_or_latest/tests.py","score":7.1,"nloc":228},{"file_path":"tests/generic_views/test_list.py","score":7.09,"nloc":226},{"file_path":"django/utils/translation/template.py","score":4.61,"nloc":225},{"file_path":"tests/model_regress/tests.py","score":7.34,"nloc":225},{"file_path":"tests/signing/tests.py","score":7.8,"nloc":224},{"file_path":"django/contrib/auth/management/__init__.py","score":2.81,"nloc":223},{"file_path":"django/contrib/postgres/constraints.py","score":5.3,"nloc":223},{"file_path":"django/core/management/commands/shell.py","score":2.81,"nloc":223},{"file_path":"tests/prefetch_related/models.py","score":9.0,"nloc":223},{"file_path":"tests/syndication_tests/feeds.py","score":7.8,"nloc":222},{"file_path":"tests/template_tests/syntax_tests/test_filter_syntax.py","score":9.59,"nloc":222},{"file_path":"django/contrib/postgres/forms/array.py","score":7.7,"nloc":221},{"file_path":"django/test/selenium.py","score":7.5,"nloc":221},{"file_path":"tests/async/test_async_queryset.py","score":7.7,"nloc":221},{"file_path":"tests/forms_tests/widget_tests/test_clearablefileinput.py","score":8.3,"nloc":221},{"file_path":"django/core/management/commands/squashmigrations.py","score":3.46,"nloc":220},{"file_path":"tests/dbshell/test_mysql.py","score":9.44,"nloc":220},{"file_path":"tests/template_tests/tests.py","score":9.0,"nloc":220},{"file_path":"django/contrib/auth/middleware.py","score":5.73,"nloc":218},{"file_path":"tests/composite_pk/test_values.py","score":10.0,"nloc":218},{"file_path":"django/contrib/admin/static/admin/js/actions.js","score":9.0,"nloc":217},{"file_path":"django/contrib/gis/gdal/raster/band.py","score":8.19,"nloc":217},{"file_path":"tests/auth_tests/test_migrations.py","score":9.65,"nloc":217},{"file_path":"tests/generic_views/views.py","score":9.0,"nloc":217},{"file_path":"django/db/backends/oracle/features.py","score":7.55,"nloc":216},{"file_path":"django/utils/archive.py","score":4.43,"nloc":216},{"file_path":"django/contrib/gis/geos/coordseq.py","score":9.0,"nloc":215},{"file_path":"django/core/files/uploadhandler.py","score":6.64,"nloc":215},{"file_path":"django/views/i18n.py","score":4.16,"nloc":215},{"file_path":"tests/fixtures_regress/models.py","score":8.7,"nloc":215},{"file_path":"tests/forms_tests/field_tests/test_decimalfield.py","score":9.09,"nloc":214},{"file_path":"tests/order_with_respect_to/base_tests.py","score":9.24,"nloc":214},{"file_path":"django/db/backends/base/features.py","score":8.3,"nloc":213},{"file_path":"django/tasks/base.py","score":8.09,"nloc":213},{"file_path":"tests/managers_regress/tests.py","score":7.14,"nloc":213},{"file_path":"django/test/html.py","score":4.89,"nloc":212},{"file_path":"django/contrib/auth/admin.py","score":4.66,"nloc":211},{"file_path":"django/core/mail/backends/smtp.py","score":6.0,"nloc":211},{"file_path":"tests/template_tests/test_parser.py","score":8.3,"nloc":211},{"file_path":"django/contrib/admin/tests.py","score":8.7,"nloc":210},{"file_path":"django/db/backends/ddl_references.py","score":8.69,"nloc":210},{"file_path":"tests/prefetch_related/test_prefetch_related_objects.py","score":8.74,"nloc":210},{"file_path":"tests/auth_tests/urls.py","score":9.0,"nloc":209},{"file_path":"django/utils/translation/__init__.py","score":6.82,"nloc":208},{"file_path":"tests/field_defaults/tests.py","score":8.64,"nloc":208},{"file_path":"tests/validation/test_unique.py","score":7.39,"nloc":208},{"file_path":"django/contrib/gis/utils/ogrinspect.py","score":6.0,"nloc":207},{"file_path":"django/db/utils.py","score":5.51,"nloc":207},{"file_path":"tests/file_storage/test_generate_filename.py","score":9.59,"nloc":206},{"file_path":"django/db/backends/mysql/features.py","score":7.8,"nloc":205},{"file_path":"django/core/servers/basehttp.py","score":6.89,"nloc":204},{"file_path":"tests/delete/models.py","score":9.0,"nloc":204},{"file_path":"tests/forms_tests/field_tests/test_genericipaddressfield.py","score":8.84,"nloc":204},{"file_path":"tests/gis_tests/inspectapp/tests.py","score":6.8,"nloc":204},{"file_path":"tests/utils_tests/test_dateparse.py","score":9.0,"nloc":204},{"file_path":"tests/utils_tests/test_termcolors.py","score":9.59,"nloc":204},{"file_path":"tests/utils_tests/test_timezone.py","score":7.34,"nloc":204},{"file_path":"tests/gis_tests/test_geoip2.py","score":7.8,"nloc":203},{"file_path":"tests/template_tests/syntax_tests/test_cycle.py","score":9.59,"nloc":203},{"file_path":"django/contrib/gis/db/backends/oracle/operations.py","score":7.5,"nloc":202},{"file_path":"django/contrib/messages/storage/cookie.py","score":8.4,"nloc":202},{"file_path":"django/contrib/auth/migrations/0001_initial.py","score":9.44,"nloc":201},{"file_path":"django/views/generic/edit.py","score":8.3,"nloc":200},{"file_path":"django/contrib/syndication/views.py","score":3.95,"nloc":198},{"file_path":"django/db/models/fields/generated.py","score":7.19,"nloc":198},{"file_path":"django/db/backends/mysql/schema.py","score":5.19,"nloc":197},{"file_path":"tests/admin_views/test_nav_sidebar.py","score":9.44,"nloc":197},{"file_path":"tests/utils_tests/test_encoding.py","score":7.8,"nloc":196},{"file_path":"django/contrib/postgres/indexes.py","score":9.0,"nloc":195},{"file_path":"scripts/do_django_release.py","score":6.05,"nloc":195},{"file_path":"django/core/checks/model_checks.py","score":6.34,"nloc":194},{"file_path":"tests/contenttypes_tests/test_operations.py","score":9.09,"nloc":194},{"file_path":"tests/forms_tests/field_tests/test_multivaluefield.py","score":8.84,"nloc":194},{"file_path":"django/contrib/gis/db/backends/spatialite/operations.py","score":6.7,"nloc":193},{"file_path":"tests/forms_tests/field_tests/test_urlfield.py","score":8.89,"nloc":193},{"file_path":"tests/generic_views/test_detail.py","score":8.7,"nloc":192},{"file_path":"tests/template_tests/templatetags/inclusion.py","score":9.24,"nloc":192},{"file_path":"tests/utils_tests/test_crypto.py","score":9.0,"nloc":192},{"file_path":"tests/gis_tests/geos_tests/test_io.py","score":9.0,"nloc":191},{"file_path":"tests/template_tests/filter_tests/test_floatformat.py","score":8.0,"nloc":191},{"file_path":"django/contrib/gis/gdal/layer.py","score":7.5,"nloc":190},{"file_path":"scripts/tests.py","score":9.0,"nloc":190},{"file_path":"tests/check_framework/test_templates.py","score":9.24,"nloc":190},{"file_path":"tests/flatpages_tests/test_middleware.py","score":8.3,"nloc":190},{"file_path":"tests/model_fields/test_filefield.py","score":8.24,"nloc":190},{"file_path":"tests/template_tests/syntax_tests/test_cache.py","score":9.24,"nloc":190},{"file_path":"django/core/serializers/python.py","score":3.36,"nloc":189},{"file_path":"django/db/models/functions/__init__.py","score":9.0,"nloc":189},{"file_path":"django/views/generic/list.py","score":8.0,"nloc":189},{"file_path":"tests/mail/test_handler.py","score":9.0,"nloc":189},{"file_path":"tests/m2m_through_regress/tests.py","score":9.0,"nloc":188},{"file_path":"django/core/cache/backends/redis.py","score":8.24,"nloc":187},{"file_path":"django/forms/utils.py","score":7.8,"nloc":186},{"file_path":"django/utils/termcolors.py","score":6.0,"nloc":186},{"file_path":"tests/queries/test_query.py","score":8.64,"nloc":186},{"file_path":"tests/view_tests/tests/test_defaults.py","score":8.3,"nloc":186},{"file_path":"django/apps/config.py","score":2.81,"nloc":184},{"file_path":"django/contrib/gis/gdal/field.py","score":9.0,"nloc":184},{"file_path":"tests/datetimes/tests.py","score":8.64,"nloc":184},{"file_path":"tests/decorators/test_cache.py","score":8.65,"nloc":184},{"file_path":"django/db/models/sql/datastructures.py","score":8.4,"nloc":183},{"file_path":"tests/messages_tests/test_cookie.py","score":9.0,"nloc":183},{"file_path":"tests/or_lookups/tests.py","score":9.59,"nloc":182},{"file_path":"tests/servers/test_basehttp.py","score":5.97,"nloc":182},{"file_path":"tests/template_backends/test_django.py","score":9.59,"nloc":182},{"file_path":"tests/gis_tests/geos_tests/test_geos_mutation.py","score":9.0,"nloc":181},{"file_path":"tests/admin_views/test_multidb.py","score":8.54,"nloc":180},{"file_path":"tests/forms_tests/field_tests/test_datefield.py","score":9.44,"nloc":180},{"file_path":"tests/view_tests/tests/test_static.py","score":7.39,"nloc":180},{"file_path":"django/test/signals.py","score":6.12,"nloc":179},{"file_path":"tests/auth_tests/test_basic.py","score":8.3,"nloc":178},{"file_path":"tests/custom_pk/tests.py","score":7.8,"nloc":178},{"file_path":"django/contrib/gis/geoip2.py","score":7.31,"nloc":177},{"file_path":"tests/messages_tests/tests.py","score":9.24,"nloc":177},{"file_path":"tests/template_tests/test_extends.py","score":9.24,"nloc":177},{"file_path":"django/utils/encoding.py","score":8.7,"nloc":176},{"file_path":"django/utils/timezone.py","score":9.0,"nloc":176},{"file_path":"js_tests/admin/inlines.test.js","score":9.24,"nloc":176},{"file_path":"tests/model_fields/test_field_flags.py","score":9.59,"nloc":176},{"file_path":"django/contrib/gis/db/backends/base/operations.py","score":7.0,"nloc":175},{"file_path":"django/middleware/cache.py","score":5.5,"nloc":175},{"file_path":"tests/middleware/test_csp.py","score":9.44,"nloc":175},{"file_path":"tests/validation/tests.py","score":7.39,"nloc":175},{"file_path":"django/db/backends/postgresql/features.py","score":7.8,"nloc":173},{"file_path":"django/core/exceptions.py","score":6.11,"nloc":172},{"file_path":"docs/Makefile","score":null,"nloc":172},{"file_path":"tests/forms_tests/field_tests/test_integerfield.py","score":9.59,"nloc":172},{"file_path":"tests/forms_tests/widget_tests/test_selectmultiple.py","score":9.09,"nloc":172},{"file_path":"django/contrib/admin/models.py","score":4.5,"nloc":171},{"file_path":"django/core/files/storage/filesystem.py","score":2.61,"nloc":171},{"file_path":"django/core/management/commands/runserver.py","score":4.23,"nloc":170},{"file_path":"tests/admin_widgets/test_autocomplete_widget.py","score":8.99,"nloc":170},{"file_path":"tests/composite_pk/test_update.py","score":9.29,"nloc":169},{"file_path":"tests/template_tests/test_library.py","score":9.44,"nloc":169},{"file_path":"tests/auth_tests/test_templates.py","score":9.0,"nloc":168},{"file_path":"tests/dbshell/test_postgresql.py","score":8.7,"nloc":168},{"file_path":"tests/decorators/test_http.py","score":9.44,"nloc":168},{"file_path":"tests/validation/models.py","score":8.7,"nloc":168},{"file_path":"django/contrib/admin/static/admin/js/SelectBox.js","score":9.0,"nloc":167},{"file_path":"django/db/migrations/operations/special.py","score":5.76,"nloc":167},{"file_path":"django/shortcuts.py","score":6.71,"nloc":167},{"file_path":"tests/db_functions/comparison/test_cast.py","score":7.34,"nloc":167},{"file_path":"tests/db_functions/migrations/0002_create_test_models.py","score":9.29,"nloc":167},{"file_path":"django/contrib/gis/gdal/envelope.py","score":6.0,"nloc":166},{"file_path":"tests/queries/test_explain.py","score":3.15,"nloc":166},{"file_path":"tests/serializers/models/data.py","score":9.0,"nloc":166},{"file_path":"tests/template_tests/filter_tests/test_unordered_list.py","score":9.24,"nloc":165},{"file_path":"django/contrib/sessions/backends/file.py","score":3.75,"nloc":164},{"file_path":"tests/flatpages_tests/test_templatetags.py","score":7.1,"nloc":164},{"file_path":"tests/view_tests/tests/test_csrf.py","score":7.8,"nloc":164},{"file_path":"django/core/management/commands/compilemessages.py","score":3.91,"nloc":163},{"file_path":"django/urls/base.py","score":3.34,"nloc":163},{"file_path":"tests/sphinx/test_github_links.py","score":9.0,"nloc":163},{"file_path":"django/contrib/sessions/backends/db.py","score":7.7,"nloc":162},{"file_path":"django/db/backends/sqlite3/features.py","score":7.05,"nloc":162},{"file_path":"django/utils/decorators.py","score":8.4,"nloc":162},{"file_path":"tests/tasks/test_dummy_backend.py","score":8.55,"nloc":162},{"file_path":"tests/utils_tests/test_module_loading.py","score":7.8,"nloc":162},{"file_path":"django/contrib/gis/db/backends/spatialite/schema.py","score":5.74,"nloc":161},{"file_path":"tests/known_related_objects/tests.py","score":9.59,"nloc":161},{"file_path":"tests/utils_tests/test_numberformat.py","score":9.59,"nloc":161},{"file_path":"tests/custom_managers/models.py","score":8.0,"nloc":160},{"file_path":"tests/gis_tests/geogapp/tests.py","score":8.3,"nloc":160},{"file_path":"tests/distinct_on_fields/tests.py","score":8.25,"nloc":159},{"file_path":"tests/template_loader/tests.py","score":8.99,"nloc":159},{"file_path":"django/contrib/admin/static/admin/js/core.js","score":9.0,"nloc":158},{"file_path":"js_tests/admin/SelectBox.test.js","score":8.89,"nloc":158},{"file_path":"tests/cache/tests_async.py","score":9.0,"nloc":158},{"file_path":"django/core/files/storage/base.py","score":8.44,"nloc":157},{"file_path":"tests/admin_ordering/tests.py","score":7.39,"nloc":157},{"file_path":"tests/db_functions/json/test_json_array.py","score":9.4,"nloc":157},{"file_path":"tests/forms_tests/field_tests/test_filefield.py","score":8.99,"nloc":157},{"file_path":"tests/i18n/test_percents.py","score":9.59,"nloc":157},{"file_path":"tests/model_formsets/models.py","score":8.3,"nloc":157},{"file_path":"tests/responses/tests.py","score":8.29,"nloc":157},{"file_path":"tests/flatpages_tests/test_views.py","score":8.3,"nloc":156},{"file_path":"tests/postgres_tests/test_trigram.py","score":9.44,"nloc":156},{"file_path":"django/core/handlers/exception.py","score":7.35,"nloc":155},{"file_path":"django/db/models/manager.py","score":7.34,"nloc":155},{"file_path":"tests/admin_views/test_related_object_lookups.py","score":8.74,"nloc":155},{"file_path":"tests/forms_tests/tests/test_validators.py","score":9.59,"nloc":155},{"file_path":"docs/conf.py","score":9.0,"nloc":153},{"file_path":"tests/admin_widgets/models.py","score":8.7,"nloc":153},{"file_path":"django/template/smartif.py","score":7.7,"nloc":152},{"file_path":"tests/auth_tests/test_tokens.py","score":8.3,"nloc":152},{"file_path":"django/contrib/sitemaps/__init__.py","score":4.44,"nloc":151},{"file_path":"tests/check_framework/test_caches.py","score":9.59,"nloc":151},{"file_path":"tests/utils_tests/test_feedgenerator.py","score":7.8,"nloc":151},{"file_path":"django/contrib/gis/gdal/prototypes/raster.py","score":9.0,"nloc":150},{"file_path":"django/core/handlers/wsgi.py","score":8.3,"nloc":150},{"file_path":"django/core/management/commands/showmigrations.py","score":3.26,"nloc":150},{"file_path":"js_tests/admin/core.test.js","score":9.24,"nloc":149},{"file_path":"tests/force_insert_update/tests.py","score":8.89,"nloc":149},{"file_path":"tests/template_tests/test_autoreloader.py","score":8.99,"nloc":149},{"file_path":"django/contrib/contenttypes/models.py","score":8.4,"nloc":148},{"file_path":"django/contrib/gis/geos/linestring.py","score":5.4,"nloc":148},{"file_path":"django/template/backends/django.py","score":9.0,"nloc":148},{"file_path":"tests/template_tests/syntax_tests/test_autoescape.py","score":9.59,"nloc":148},{"file_path":"tests/decorators/test_csrf.py","score":9.65,"nloc":147},{"file_path":"django/contrib/admindocs/utils.py","score":8.3,"nloc":146},{"file_path":"django/contrib/messages/storage/base.py","score":8.3,"nloc":146},{"file_path":"django/core/cache/backends/filebased.py","score":8.7,"nloc":146},{"file_path":"django/db/models/functions/math.py","score":10.0,"nloc":146},{"file_path":"django/views/generic/detail.py","score":3.81,"nloc":146},{"file_path":"js_tests/admin/DateTimeShortcuts.test.js","score":9.0,"nloc":146},{"file_path":"tests/forms_tests/field_tests/test_floatfield.py","score":8.89,"nloc":146},{"file_path":"tests/postgres_tests/models.py","score":8.7,"nloc":146},{"file_path":"django/contrib/gis/geos/polygon.py","score":7.34,"nloc":145},{"file_path":"django/db/models/sql/subqueries.py","score":9.0,"nloc":145},{"file_path":"tests/composite_pk/test_create.py","score":8.75,"nloc":145},{"file_path":"tests/migrations/test_multidb.py","score":9.24,"nloc":145},{"file_path":"tests/template_backends/test_jinja2.py","score":8.94,"nloc":145},{"file_path":"tests/template_tests/syntax_tests/test_regroup.py","score":9.59,"nloc":145},{"file_path":"tests/constraints/models.py","score":8.7,"nloc":144},{"file_path":"tests/forms_tests/tests/test_i18n.py","score":8.54,"nloc":143},{"file_path":"tests/staticfiles_tests/test_checks.py","score":9.24,"nloc":143},{"file_path":"tests/template_tests/filter_tests/test_timesince.py","score":9.44,"nloc":143},{"file_path":"django/contrib/admin/templatetags/admin_modify.py","score":2.55,"nloc":142},{"file_path":"django/middleware/common.py","score":7.01,"nloc":142},{"file_path":"django/templatetags/tz.py","score":8.4,"nloc":142},{"file_path":"tests/file_uploads/views.py","score":9.0,"nloc":142},{"file_path":"tests/proxy_models/models.py","score":8.7,"nloc":142},{"file_path":"tests/utils_tests/test_safestring.py","score":8.3,"nloc":142},{"file_path":"tests/admin_changelist/admin.py","score":9.0,"nloc":141},{"file_path":"tests/composite_pk/test_aggregate.py","score":9.3,"nloc":141},{"file_path":"tests/utils_tests/test_csp.py","score":10.0,"nloc":141},{"file_path":"django/contrib/gis/management/commands/ogrinspect.py","score":9.0,"nloc":140},{"file_path":"scripts/pr_quality/errors.py","score":9.0,"nloc":140},{"file_path":"tests/serializers/test_yaml.py","score":8.84,"nloc":140},{"file_path":"tests/utils_tests/test_os_utils.py","score":9.24,"nloc":140},{"file_path":"django/db/migrations/operations/base.py","score":7.8,"nloc":138},{"file_path":"django/db/models/fields/composite.py","score":8.55,"nloc":138},{"file_path":"tests/deprecation/tests.py","score":8.3,"nloc":138},{"file_path":"tests/migrate_signals/tests.py","score":9.0,"nloc":138},{"file_path":"django/core/management/commands/listurls.py","score":9.4,"nloc":137},{"file_path":"tests/schema/models.py","score":9.0,"nloc":137},{"file_path":"django/templatetags/static.py","score":8.89,"nloc":136},{"file_path":"tests/admin_custom_urls/tests.py","score":9.0,"nloc":136},{"file_path":"tests/admin_registration/tests.py","score":8.3,"nloc":136},{"file_path":"tests/context_processors/tests.py","score":9.0,"nloc":136},{"file_path":"tests/deprecation/test_warn_about_external_use.py","score":9.65,"nloc":136},{"file_path":"tests/forms_tests/widget_tests/test_nullbooleanselect.py","score":9.09,"nloc":136},{"file_path":"tests/test_utils/test_testcase.py","score":9.24,"nloc":136},{"file_path":"django/db/models/__init__.py","score":9.0,"nloc":135},{"file_path":"tests/gis_tests/test_spatialrefsys.py","score":8.3,"nloc":135},{"file_path":"tests/template_tests/syntax_tests/test_width_ratio.py","score":9.59,"nloc":135},{"file_path":"django/contrib/gis/db/backends/mysql/operations.py","score":7.8,"nloc":134},{"file_path":"tests/forms_tests/field_tests/test_charfield.py","score":9.24,"nloc":134},{"file_path":"tests/inspectdb/models.py","score":9.0,"nloc":134},{"file_path":"tests/urlpatterns_reverse/urls.py","score":9.0,"nloc":134},{"file_path":"django/core/cache/backends/memcached.py","score":8.0,"nloc":133},{"file_path":"tests/admin_views/test_skip_link_to_content.py","score":9.65,"nloc":133},{"file_path":"tests/generic_relations_regress/models.py","score":8.7,"nloc":133},{"file_path":"tests/many_to_one_null/tests.py","score":9.0,"nloc":133},{"file_path":"tests/model_fields/test_decimalfield.py","score":8.24,"nloc":133},{"file_path":"tests/model_fields/test_foreignkey.py","score":8.84,"nloc":133},{"file_path":"django/contrib/gis/db/backends/oracle/schema.py","score":8.7,"nloc":132},{"file_path":"django/contrib/gis/gdal/prototypes/generation.py","score":8.1,"nloc":132},{"file_path":"tests/invalid_models_tests/test_deprecated_fields.py","score":9.59,"nloc":132},{"file_path":"django/contrib/gis/gdal/geomtype.py","score":9.0,"nloc":131},{"file_path":"django/contrib/gis/gdal/prototypes/geom.py","score":9.0,"nloc":131},{"file_path":"django/db/backends/sqlite3/creation.py","score":2.7,"nloc":131},{"file_path":"tests/test_client_regress/views.py","score":9.0,"nloc":131},{"file_path":"django/core/checks/urls.py","score":7.12,"nloc":130},{"file_path":"tests/backends/oracle/tests.py","score":7.1,"nloc":130},{"file_path":"tests/mail/test_sendtestemail.py","score":8.89,"nloc":130},{"file_path":"tests/responses/test_cookie.py","score":8.99,"nloc":130},{"file_path":"tests/utils_tests/test_inspect.py","score":8.59,"nloc":130},{"file_path":"django/views/decorators/http.py","score":9.0,"nloc":129},{"file_path":"tests/dates/tests.py","score":8.64,"nloc":129},{"file_path":"django/contrib/contenttypes/admin.py","score":7.01,"nloc":128},{"file_path":"tests/template_tests/utils.py","score":7.8,"nloc":128},{"file_path":"django/contrib/auth/base_user.py","score":7.19,"nloc":126},{"file_path":"django/db/models/functions/comparison.py","score":8.3,"nloc":126},{"file_path":"scripts/archive_eol_stable_branches.py","score":9.85,"nloc":126},{"file_path":"tests/composite_pk/test_models.py","score":9.85,"nloc":126},{"file_path":"tests/forms_tests/field_tests/test_choicefield.py","score":9.09,"nloc":126},{"file_path":"tests/gis_tests/geos_tests/test_coordseq.py","score":10.0,"nloc":126},{"file_path":"tests/serializers/test_deserialization.py","score":9.65,"nloc":126},{"file_path":"django/contrib/gis/db/backends/postgis/base.py","score":8.3,"nloc":125},{"file_path":"django/contrib/gis/geos/point.py","score":7.59,"nloc":125},{"file_path":"tests/model_meta/models.py","score":9.44,"nloc":125},{"file_path":"tests/builtin_server/tests.py","score":9.0,"nloc":124},{"file_path":"tests/modeladmin/test_actions.py","score":9.44,"nloc":124},{"file_path":"django/contrib/contenttypes/forms.py","score":8.69,"nloc":123},{"file_path":"tests/messages_tests/test_fallback.py","score":9.59,"nloc":122},{"file_path":"tests/postgres_tests/test_app_installed_check.py","score":9.85,"nloc":122},{"file_path":"tests/template_tests/test_engine.py","score":9.59,"nloc":122},{"file_path":"tests/test_utils/test_simpletestcase.py","score":9.65,"nloc":122},{"file_path":"django/core/files/base.py","score":4.71,"nloc":121},{"file_path":"tests/auth_tests/test_context_processors.py","score":9.0,"nloc":121},{"file_path":"tests/backends/test_utils.py","score":9.65,"nloc":121},{"file_path":"tests/composite_pk/test_get.py","score":9.65,"nloc":121},{"file_path":"tests/forms_tests/widget_tests/test_checkboxinput.py","score":9.09,"nloc":121},{"file_path":"tests/model_fields/test_promises.py","score":9.59,"nloc":121},{"file_path":"tests/template_tests/syntax_tests/test_resetcycle.py","score":10.0,"nloc":121},{"file_path":"django/views/defaults.py","score":8.7,"nloc":120},{"file_path":"tests/backends/mysql/test_creation.py","score":8.94,"nloc":120},{"file_path":"tests/backends/postgresql/test_server_side_cursors.py","score":9.59,"nloc":120},{"file_path":"tests/composite_pk/test_names_to_path.py","score":10.0,"nloc":120},{"file_path":"django/contrib/sessions/backends/cache.py","score":6.9,"nloc":119},{"file_path":"tests/deprecation/test_middleware_mixin.py","score":9.59,"nloc":119},{"file_path":"tests/template_tests/filter_tests/test_wordwrap.py","score":8.89,"nloc":119},{"file_path":"django/contrib/sitemaps/views.py","score":3.91,"nloc":118},{"file_path":"django/template/response.py","score":8.4,"nloc":118},{"file_path":"django/utils/dateparse.py","score":4.42,"nloc":118},{"file_path":"tests/forms_tests/field_tests/test_datetimefield.py","score":8.84,"nloc":118},{"file_path":"tests/model_inheritance/models.py","score":8.7,"nloc":118},{"file_path":"django/core/files/uploadedfile.py","score":7.7,"nloc":117},{"file_path":"django/core/management/commands/createcachetable.py","score":4.8,"nloc":117},{"file_path":"django/utils/inspect.py","score":9.24,"nloc":117},{"file_path":"tests/forms_tests/widget_tests/test_textinput.py","score":9.44,"nloc":117},{"file_path":"tests/serializers/models/base.py","score":8.99,"nloc":117},{"file_path":"tests/template_tests/test_callables.py","score":9.59,"nloc":117},{"file_path":"django/contrib/gis/feeds.py","score":5.75,"nloc":116},{"file_path":"tests/db_functions/math/test_round.py","score":8.64,"nloc":116},{"file_path":"tests/template_tests/filter_tests/test_timeuntil.py","score":9.44,"nloc":116},{"file_path":"tests/admin_docs/test_utils.py","score":9.59,"nloc":115},{"file_path":"tests/async/tests.py","score":9.24,"nloc":115},{"file_path":"tests/backends/models.py","score":8.7,"nloc":115},{"file_path":"tests/flatpages_tests/test_forms.py","score":9.0,"nloc":115},{"file_path":"tests/validation/test_error_messages.py","score":9.59,"nloc":115},{"file_path":"django/views/decorators/debug.py","score":9.24,"nloc":114},{"file_path":"tests/backends/oracle/test_operations.py","score":9.44,"nloc":114},{"file_path":"tests/model_inheritance_regress/models.py","score":8.7,"nloc":114},{"file_path":"django/contrib/contenttypes/management/__init__.py","score":6.85,"nloc":113},{"file_path":"tests/bulk_create/models.py","score":9.44,"nloc":113},{"file_path":"tests/flatpages_tests/test_csrf.py","score":7.6,"nloc":113},{"file_path":"tests/forms_tests/field_tests/test_jsonfield.py","score":8.84,"nloc":113},{"file_path":"tests/signed_cookies_tests/tests.py","score":8.89,"nloc":113},{"file_path":"tests/staticfiles_tests/cases.py","score":9.44,"nloc":113},{"file_path":"tests/utils_tests/test_lorem_ipsum.py","score":8.99,"nloc":113},{"file_path":"tests/wsgi/tests.py","score":9.0,"nloc":112},{"file_path":"django/contrib/auth/mixins.py","score":9.19,"nloc":111},{"file_path":"django/core/management/commands/optimizemigration.py","score":8.43,"nloc":111},{"file_path":"tests/check_framework/test_translation.py","score":10.0,"nloc":111},{"file_path":"tests/m2m_through/models.py","score":9.59,"nloc":111},{"file_path":"tests/model_fields/test_booleanfield.py","score":8.64,"nloc":111},{"file_path":"tests/serializers/test_xml.py","score":8.49,"nloc":111},{"file_path":"django/contrib/gis/db/backends/base/models.py","score":7.2,"nloc":110},{"file_path":"django/utils/timesince.py","score":5.3,"nloc":110},{"file_path":"tests/async/test_async_auth.py","score":9.44,"nloc":110},{"file_path":"tests/contenttypes_tests/test_management.py","score":9.59,"nloc":110},{"file_path":"tests/forms_tests/widget_tests/test_multiplehiddeninput.py","score":9.59,"nloc":110},{"file_path":"django/contrib/gis/geos/libgeos.py","score":7.31,"nloc":109},{"file_path":"django/contrib/sessions/backends/cached_db.py","score":7.7,"nloc":109},{"file_path":"tests/auth_tests/models/custom_user.py","score":7.8,"nloc":109},{"file_path":"tests/backends/mysql/test_introspection.py","score":9.44,"nloc":108},{"file_path":"tests/backends/sqlite/test_operations.py","score":9.44,"nloc":108},{"file_path":"tests/contenttypes_tests/test_fields.py","score":8.89,"nloc":107},{"file_path":"tests/forms_tests/field_tests/test_filepathfield.py","score":9.24,"nloc":107},{"file_path":"tests/model_formsets/test_uuid.py","score":9.65,"nloc":107},{"file_path":"tests/staticfiles_tests/test_finders.py","score":8.64,"nloc":107},{"file_path":"tests/template_tests/filter_tests/test_chaining.py","score":10.0,"nloc":107},{"file_path":"tests/template_tests/filter_tests/test_dictsort.py","score":9.65,"nloc":107},{"file_path":"django/contrib/gis/db/backends/postgis/schema.py","score":6.54,"nloc":106},{"file_path":"tests/db_functions/text/test_concat.py","score":9.4,"nloc":106},{"file_path":"tests/forms_tests/widget_tests/test_splitdatetimewidget.py","score":9.24,"nloc":106},{"file_path":"django/core/checks/registry.py","score":9.0,"nloc":105},{"file_path":"django/db/migrations/utils.py","score":6.49,"nloc":105},{"file_path":"django/db/models/fields/related_lookups.py","score":3.39,"nloc":105},{"file_path":"tests/migrations/test_questioner.py","score":9.24,"nloc":105},{"file_path":"tests/template_tests/syntax_tests/test_static.py","score":9.59,"nloc":105},{"file_path":"django/contrib/messages/api.py","score":9.44,"nloc":104},{"file_path":"django/template/backends/jinja2.py","score":9.59,"nloc":104},{"file_path":"tests/admin_views/test_password_form.py","score":10.0,"nloc":104},{"file_path":"tests/check_framework/test_mail.py","score":9.65,"nloc":104},{"file_path":"tests/gis_tests/gis_migrations/migrations/0002_create_models.py","score":9.24,"nloc":104},{"file_path":"django/contrib/admin/decorators.py","score":8.94,"nloc":103},{"file_path":"django/contrib/admin/views/autocomplete.py","score":8.99,"nloc":103},{"file_path":"docs/_ext/github_links.py","score":9.5,"nloc":103},{"file_path":"tests/m2m_recursive/tests.py","score":9.59,"nloc":103},{"file_path":"django/contrib/auth/decorators.py","score":8.7,"nloc":102},{"file_path":"tests/forms_tests/models.py","score":9.0,"nloc":102},{"file_path":"django/contrib/gis/forms/fields.py","score":5.43,"nloc":101},{"file_path":"django/views/static.py","score":9.0,"nloc":101},{"file_path":"tests/db_functions/json/test_json_object.py","score":9.25,"nloc":101},{"file_path":"tests/filtered_relation/models.py","score":9.59,"nloc":101},{"file_path":"tests/forms_tests/widget_tests/test_splithiddendatetimewidget.py","score":9.44,"nloc":101},{"file_path":"tests/tasks/test_custom_backend.py","score":9.65,"nloc":101},{"file_path":"django/contrib/auth/tokens.py","score":7.59,"nloc":100},{"file_path":"tests/backends/postgresql/test_creation.py","score":8.94,"nloc":100},{"file_path":"tests/delete_regress/models.py","score":8.7,"nloc":100},{"file_path":"tests/introspection/models.py","score":8.7,"nloc":100},{"file_path":"tests/model_options/test_default_pk.py","score":9.65,"nloc":100},{"file_path":"django/contrib/gis/gdal/libgdal.py","score":9.0,"nloc":99},{"file_path":"django/contrib/gis/gdal/prototypes/errcheck.py","score":8.4,"nloc":99},{"file_path":"django/contrib/postgres/forms/ranges.py","score":9.59,"nloc":99},{"file_path":"tests/admin_views/test_csp.py","score":9.85,"nloc":99},{"file_path":"tests/backends/mysql/tests.py","score":9.05,"nloc":99},{"file_path":"tests/m2m_regress/tests.py","score":7.59,"nloc":99},{"file_path":"tests/middleware_exceptions/middleware.py","score":9.59,"nloc":99},{"file_path":"django/core/cache/backends/locmem.py","score":9.0,"nloc":98},{"file_path":"tests/admin_views/test_adminsite.py","score":9.44,"nloc":98},{"file_path":"tests/utils_tests/test_archive.py","score":7.91,"nloc":98},{"file_path":"django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py","score":4.59,"nloc":97},{"file_path":"django/contrib/gis/gdal/datasource.py","score":9.0,"nloc":97},{"file_path":"tests/admin_views/test_history_view.py","score":8.89,"nloc":97},{"file_path":"tests/expressions/test_queryset_values.py","score":8.64,"nloc":97},{"file_path":"tests/utils_tests/test_tree.py","score":9.59,"nloc":97},{"file_path":"django/contrib/gis/gdal/feature.py","score":8.3,"nloc":96},{"file_path":"django/utils/tree.py","score":8.2,"nloc":96},{"file_path":"tests/foreign_object/models/empty_join.py","score":8.84,"nloc":96},{"file_path":"django/contrib/sites/models.py","score":7.7,"nloc":95},{"file_path":"tests/generic_relations/models.py","score":8.7,"nloc":95},{"file_path":"tests/redirects_tests/tests.py","score":8.3,"nloc":95},{"file_path":"tests/utils_tests/test_ipv6.py","score":8.89,"nloc":95},{"file_path":"django/core/files/locks.py","score":9.59,"nloc":94},{"file_path":"tests/async/test_async_related_managers.py","score":10.0,"nloc":94},{"file_path":"tests/gis_tests/geoapp/test_serializers.py","score":9.4,"nloc":94},{"file_path":"tests/prefetch_related/test_uuid.py","score":9.24,"nloc":94},{"file_path":"django/contrib/gis/forms/widgets.py","score":7.12,"nloc":93},{"file_path":"django/contrib/gis/gdal/prototypes/ds.py","score":9.0,"nloc":93},{"file_path":"django/core/serializers/json.py","score":7.6,"nloc":93},{"file_path":"django/db/models/functions/json.py","score":9.4,"nloc":93},{"file_path":"tests/admin_changelist/models.py","score":8.7,"nloc":93},{"file_path":"tests/gis_tests/geoapp/test_regress.py","score":7.8,"nloc":93},{"file_path":"tests/template_tests/filter_tests/test_urlizetrunc.py","score":9.59,"nloc":93},{"file_path":"tests/template_tests/test_extends_relative.py","score":9.65,"nloc":93},{"file_path":"js_tests/admin/RelatedObjectLookups.test.js","score":9.24,"nloc":92},{"file_path":"tests/admin_changelist/test_date_hierarchy.py","score":9.09,"nloc":92},{"file_path":"tests/custom_columns/tests.py","score":9.0,"nloc":92},{"file_path":"tests/schema/fields.py","score":8.99,"nloc":92},{"file_path":"django/core/mail/backends/base.py","score":8.64,"nloc":91},{"file_path":"django/contrib/gis/db/backends/postgis/pgraster.py","score":9.59,"nloc":90},{"file_path":"django/db/models/functions/window.py","score":10.0,"nloc":90},{"file_path":"django/utils/numberformat.py","score":3.91,"nloc":90},{"file_path":"tests/aggregation_regress/models.py","score":8.3,"nloc":90},{"file_path":"tests/datatypes/tests.py","score":7.8,"nloc":90},{"file_path":"tests/decorators/test_clickjacking.py","score":9.65,"nloc":90},{"file_path":"tests/forms_tests/field_tests/test_imagefield.py","score":9.24,"nloc":90},{"file_path":"django/contrib/gis/db/backends/mysql/schema.py","score":7.04,"nloc":89},{"file_path":"tests/auth_tests/test_signals.py","score":9.0,"nloc":89},{"file_path":"tests/bash_completion/tests.py","score":8.0,"nloc":89},{"file_path":"tests/gis_tests/tests.py","score":9.24,"nloc":89},{"file_path":"tests/sites_framework/migrations/0001_initial.py","score":9.09,"nloc":89},{"file_path":"django/contrib/gis/geos/collections.py","score":7.8,"nloc":88},{"file_path":"django/utils/version.py","score":7.41,"nloc":88},{"file_path":"tests/db_functions/comparison/test_greatest.py","score":9.05,"nloc":88},{"file_path":"tests/gis_tests/layermap/models.py","score":9.0,"nloc":88},{"file_path":"tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py","score":9.85,"nloc":88},{"file_path":"tests/expressions/models.py","score":9.0,"nloc":87},{"file_path":"tests/forms_tests/field_tests/test_multiplechoicefield.py","score":8.69,"nloc":87},{"file_path":"tests/forms_tests/field_tests/test_splitdatetimefield.py","score":9.59,"nloc":87},{"file_path":"tests/model_options/test_tablespaces.py","score":8.68,"nloc":87},{"file_path":"django/contrib/postgres/fields/hstore.py","score":7.8,"nloc":86},{"file_path":"django/templatetags/cache.py","score":7.01,"nloc":86},{"file_path":"tests/template_tests/syntax_tests/test_now.py","score":9.59,"nloc":86},{"file_path":"tests/test_runner/test_shuffler.py","score":9.65,"nloc":86},{"file_path":"django/template/utils.py","score":6.42,"nloc":85},{"file_path":"django/utils/_os.py","score":7.01,"nloc":85},{"file_path":"tests/check_framework/test_model_field_deprecation.py","score":10.0,"nloc":85},{"file_path":"tests/get_object_or_404/tests.py","score":9.59,"nloc":85},{"file_path":"tests/m2m_and_m2o/tests.py","score":9.59,"nloc":85},{"file_path":"tests/resolve_url/tests.py","score":8.89,"nloc":85},{"file_path":"tests/template_backends/test_dummy.py","score":9.44,"nloc":85},{"file_path":"tests/template_tests/syntax_tests/test_load.py","score":10.0,"nloc":85},{"file_path":"tests/validation/test_constraints.py","score":9.4,"nloc":85},{"file_path":"django/contrib/sessions/backends/signed_cookies.py","score":8.44,"nloc":84},{"file_path":"django/db/backends/postgresql/psycopg_any.py","score":9.85,"nloc":84},{"file_path":"django/views/templates/i18n_catalog.js","score":10.0,"nloc":84},{"file_path":"tests/backends/oracle/test_creation.py","score":9.4,"nloc":84},{"file_path":"tests/db_functions/test_uuid.py","score":9.25,"nloc":84},{"file_path":"tests/gis_tests/gdal_tests/test_envelope.py","score":9.24,"nloc":84},{"file_path":"tests/model_fields/test_charfield.py","score":9.24,"nloc":84},{"file_path":"tests/model_fields/test_manytomanyfield.py","score":9.85,"nloc":84},{"file_path":"django/contrib/admin/static/admin/js/nav_sidebar.js","score":9.44,"nloc":83},{"file_path":"django/contrib/postgres/aggregates/general.py","score":9.0,"nloc":83},{"file_path":"django/contrib/staticfiles/handlers.py","score":7.8,"nloc":83},{"file_path":"django/core/management/color.py","score":7.5,"nloc":83},{"file_path":"django/db/backends/oracle/utils.py","score":9.0,"nloc":83},{"file_path":"django/db/migrations/recorder.py","score":9.0,"nloc":83},{"file_path":"django/tasks/backends/base.py","score":7.95,"nloc":83},{"file_path":"tests/foreign_object/models/article.py","score":9.59,"nloc":83},{"file_path":"tests/utils_tests/test_decorators.py","score":8.99,"nloc":83},{"file_path":"django/contrib/gis/gdal/raster/const.py","score":9.59,"nloc":82},{"file_path":"django/core/mail/backends/filebased.py","score":7.58,"nloc":82},{"file_path":"tests/admin_filters/models.py","score":9.0,"nloc":82},{"file_path":"tests/db_functions/comparison/test_least.py","score":9.05,"nloc":82},{"file_path":"tests/gis_tests/geoapp/test_feeds.py","score":8.0,"nloc":82},{"file_path":"tests/sitemaps_tests/test_generic.py","score":9.0,"nloc":82},{"file_path":"tests/test_client/urls.py","score":9.0,"nloc":82},{"file_path":"tests/urlpatterns_reverse/namespace_urls.py","score":9.0,"nloc":82},{"file_path":"tests/backends/sqlite/test_creation.py","score":9.44,"nloc":81},{"file_path":"tests/foreign_object/models/person.py","score":9.24,"nloc":81},{"file_path":"tests/ordering/models.py","score":9.0,"nloc":81},{"file_path":"django/tasks/backends/immediate.py","score":9.5,"nloc":80},{"file_path":"django/template/loaders/cached.py","score":8.3,"nloc":80},{"file_path":"django/urls/conf.py","score":7.65,"nloc":80},{"file_path":"tests/contenttypes_tests/models.py","score":9.59,"nloc":80},{"file_path":"tests/postgres_tests/test_apps.py","score":9.44,"nloc":80},{"file_path":"tests/serializers/models/natural.py","score":9.09,"nloc":80},{"file_path":"django/contrib/gis/gdal/prototypes/srs.py","score":9.59,"nloc":79},{"file_path":"django/core/management/commands/check.py","score":9.44,"nloc":79},{"file_path":"tests/many_to_one/models.py","score":8.3,"nloc":79},{"file_path":"tests/template_tests/filter_tests/test_join.py","score":9.59,"nloc":79},{"file_path":"tests/template_tests/test_nodelist.py","score":9.0,"nloc":79},{"file_path":"tests/view_tests/urls.py","score":9.0,"nloc":79},{"file_path":"django/contrib/admin/actions.py","score":9.0,"nloc":78},{"file_path":"django/core/checks/security/sessions.py","score":9.59,"nloc":78},{"file_path":"django/core/management/commands/diffsettings.py","score":9.0,"nloc":78},{"file_path":"js_tests/admin/jsi18n-mocks.test.js","score":9.29,"nloc":78},{"file_path":"tests/db_typecasts/tests.py","score":9.59,"nloc":78},{"file_path":"tests/forms_tests/field_tests/test_regexfield.py","score":9.59,"nloc":78},{"file_path":"tests/managers_regress/models.py","score":9.44,"nloc":78},{"file_path":"tests/select_related_regress/models.py","score":8.3,"nloc":78},{"file_path":"tests/xor_lookups/tests.py","score":10.0,"nloc":78},{"file_path":"django/contrib/flatpages/templatetags/flatpages.py","score":9.0,"nloc":77},{"file_path":"django/utils/dates.py","score":9.59,"nloc":77},{"file_path":"django/utils/module_loading.py","score":5.77,"nloc":77},{"file_path":"tests/backends/oracle/test_introspection.py","score":10.0,"nloc":77},{"file_path":"tests/forms_tests/widget_tests/test_fileinput.py","score":8.84,"nloc":77},{"file_path":"tests/utils_tests/test_deconstruct.py","score":9.65,"nloc":77},{"file_path":"tests/utils_tests/test_duration.py","score":10.0,"nloc":77},{"file_path":"django/contrib/gis/geos/prototypes/coordseq.py","score":9.24,"nloc":76},{"file_path":"django/utils/choices.py","score":10.0,"nloc":76},{"file_path":"tests/db_utils/tests.py","score":9.59,"nloc":76},{"file_path":"tests/m2m_multiple/tests.py","score":9.59,"nloc":76},{"file_path":"tests/staticfiles_tests/storage.py","score":7.44,"nloc":76},{"file_path":"tests/template_tests/filter_tests/test_force_escape.py","score":9.59,"nloc":76},{"file_path":"tests/template_tests/syntax_tests/test_comment.py","score":10.0,"nloc":76},{"file_path":"tests/template_tests/syntax_tests/test_csp_nonce_attr.py","score":9.4,"nloc":76},{"file_path":"django/contrib/gis/gdal/driver.py","score":8.3,"nloc":75},{"file_path":"django/contrib/postgres/apps.py","score":9.0,"nloc":75},{"file_path":"django/contrib/postgres/validators.py","score":9.59,"nloc":75},{"file_path":"scripts/prepare_commit_msg.py","score":8.4,"nloc":75},{"file_path":"tests/lookup/models.py","score":9.0,"nloc":75},{"file_path":"django/db/backends/postgresql/creation.py","score":5.92,"nloc":74},{"file_path":"tests/db_functions/text/test_replace.py","score":9.65,"nloc":74},{"file_path":"tests/decorators/test_csp.py","score":9.65,"nloc":74},{"file_path":"tests/admin_docs/models.py","score":8.59,"nloc":73},{"file_path":"tests/auth_tests/test_handlers.py","score":9.0,"nloc":73},{"file_path":"tests/forms_tests/field_tests/test_typedchoicefield.py","score":8.49,"nloc":73},{"file_path":"django/contrib/admin/migrations/0001_initial.py","score":9.59,"nloc":72},{"file_path":"django/db/backends/mysql/validation.py","score":8.2,"nloc":72},{"file_path":"tests/forms_tests/widget_tests/test_choicewidget.py","score":10.0,"nloc":72},{"file_path":"tests/reserved_names/tests.py","score":9.59,"nloc":72},{"file_path":"tests/template_tests/syntax_tests/test_firstof.py","score":9.59,"nloc":72},{"file_path":"django/contrib/gis/db/models/aggregates.py","score":8.7,"nloc":71},{"file_path":"django/core/management/commands/flush.py","score":8.4,"nloc":71},{"file_path":"django/views/csrf.py","score":9.0,"nloc":71},{"file_path":"tests/backends/postgresql/test_operations.py","score":9.85,"nloc":71},{"file_path":"tests/forms_tests/widget_tests/test_timeinput.py","score":9.44,"nloc":71},{"file_path":"tests/messages_tests/urls.py","score":9.59,"nloc":71},{"file_path":"tests/template_tests/syntax_tests/test_list_index.py","score":10.0,"nloc":71},{"file_path":"tests/template_tests/syntax_tests/test_named_endblock.py","score":9.59,"nloc":71},{"file_path":"django/contrib/gis/geos/prototypes/__init__.py","score":9.59,"nloc":70},{"file_path":"django/contrib/sessions/middleware.py","score":4.15,"nloc":70},{"file_path":"tests/admin_views/customadmin.py","score":7.8,"nloc":70},{"file_path":"tests/gis_tests/geoapp/test_expressions.py","score":9.24,"nloc":70},{"file_path":"tests/template_tests/filter_tests/test_cut.py","score":10.0,"nloc":70},{"file_path":"django/contrib/gis/geos/prototypes/errcheck.py","score":9.0,"nloc":69},{"file_path":"django/template/context_processors.py","score":9.24,"nloc":69},{"file_path":"tests/middleware/views.py","score":9.09,"nloc":69},{"file_path":"tests/template_tests/filter_tests/test_date.py","score":9.59,"nloc":69},{"file_path":"tests/template_tests/syntax_tests/test_exceptions.py","score":9.24,"nloc":69},{"file_path":"django/contrib/auth/management/commands/changepassword.py","score":7.31,"nloc":68},{"file_path":"django/db/models/functions/uuid.py","score":9.4,"nloc":68},{"file_path":"tests/app_loading/tests.py","score":9.0,"nloc":68},{"file_path":"tests/composite_pk/test_delete.py","score":9.3,"nloc":68},{"file_path":"tests/db_functions/tests.py","score":8.3,"nloc":68},{"file_path":"tests/file_uploads/uploadhandler.py","score":9.44,"nloc":68},{"file_path":"tests/forms_tests/field_tests/test_durationfield.py","score":9.24,"nloc":68},{"file_path":"tests/gis_tests/geoapp/models.py","score":9.0,"nloc":68},{"file_path":"tests/gis_tests/rasterapp/migrations/0002_rastermodels.py","score":10.0,"nloc":68},{"file_path":"tests/one_to_one/models.py","score":8.3,"nloc":68},{"file_path":"tests/postgres_tests/test_unaccent.py","score":9.59,"nloc":68},{"file_path":"django/core/checks/caches.py","score":7.8,"nloc":67},{"file_path":"scripts/verify_release.sh","score":10.0,"nloc":67},{"file_path":"tests/db_functions/comparison/test_coalesce.py","score":8.99,"nloc":67},{"file_path":"tests/db_functions/text/test_strindex.py","score":9.59,"nloc":67},{"file_path":"tests/file_storage/models.py","score":9.59,"nloc":67},{"file_path":"tests/forms_tests/field_tests/test_emailfield.py","score":9.09,"nloc":67},{"file_path":"tests/forms_tests/widget_tests/test_datetimeinput.py","score":9.44,"nloc":67},{"file_path":"tests/forms_tests/widget_tests/test_textarea.py","score":9.85,"nloc":67},{"file_path":"tests/model_fields/test_durationfield.py","score":9.44,"nloc":67},{"file_path":"django/contrib/auth/migrations/0011_update_proxy_permissions.py","score":9.0,"nloc":66},{"file_path":"django/contrib/gis/db/backends/spatialite/introspection.py","score":9.59,"nloc":66},{"file_path":"django/utils/crypto.py","score":8.7,"nloc":66},{"file_path":"tests/admin_views/forms.py","score":9.24,"nloc":66},{"file_path":"tests/gis_tests/gdal_tests/test_driver.py","score":9.24,"nloc":66},{"file_path":"tests/model_fields/test_datetimefield.py","score":9.65,"nloc":66},{"file_path":"tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py","score":9.24,"nloc":66},{"file_path":"django/contrib/flatpages/migrations/0001_initial.py","score":9.59,"nloc":65},{"file_path":"django/contrib/gis/sitemaps/kml.py","score":7.49,"nloc":65},{"file_path":"django/middleware/locale.py","score":6.51,"nloc":65},{"file_path":"django/views/decorators/clickjacking.py","score":9.59,"nloc":65},{"file_path":"tests/admin_utils/models.py","score":9.0,"nloc":65},{"file_path":"tests/composite_pk/test_order_by.py","score":9.65,"nloc":65},{"file_path":"tests/defer_regress/models.py","score":9.0,"nloc":65},{"file_path":"tests/forms_tests/field_tests/test_nullbooleanfield.py","score":9.24,"nloc":65},{"file_path":"tests/null_queries/tests.py","score":9.24,"nloc":65},{"file_path":"tests/shortcuts/tests.py","score":9.0,"nloc":65},{"file_path":"tests/unmanaged_models/models.py","score":9.59,"nloc":65},{"file_path":"django/contrib/contenttypes/views.py","score":3.54,"nloc":64},{"file_path":"django/contrib/flatpages/forms.py","score":9.0,"nloc":64},{"file_path":"tests/forms_tests/field_tests/test_typedmultiplechoicefield.py","score":9.05,"nloc":64},{"file_path":"tests/gis_tests/geoapp/test_indexes.py","score":9.44,"nloc":64},{"file_path":"tests/test_client_regress/urls.py","score":9.0,"nloc":64},{"file_path":"django/contrib/gis/db/backends/spatialite/base.py","score":6.82,"nloc":63},{"file_path":"django/contrib/gis/serializers/geojson.py","score":9.0,"nloc":63},{"file_path":"tests/auth_tests/test_admin_multidb.py","score":9.24,"nloc":63},{"file_path":"tests/forms_tests/widget_tests/test_dateinput.py","score":9.44,"nloc":63},{"file_path":"tests/gis_tests/geoadmin/tests.py","score":9.0,"nloc":63},{"file_path":"tests/sitemaps_tests/test_https.py","score":8.3,"nloc":63},{"file_path":"tests/string_lookup/tests.py","score":9.59,"nloc":63},{"file_path":"tests/template_tests/test_base.py","score":9.59,"nloc":63},{"file_path":"django/contrib/admin/templatetags/admin_filters.py","score":10.0,"nloc":62},{"file_path":"django/contrib/gis/db/backends/base/features.py","score":7.8,"nloc":62},{"file_path":"django/contrib/staticfiles/utils.py","score":5.2,"nloc":62},{"file_path":"django/core/management/commands/sqlmigrate.py","score":9.0,"nloc":62},{"file_path":"django/template/backends/base.py","score":8.84,"nloc":62},{"file_path":"tests/gis_tests/test_data.py","score":9.0,"nloc":62},{"file_path":"tests/queries/test_db_returning.py","score":9.44,"nloc":62},{"file_path":"tests/test_utils/test_transactiontestcase.py","score":9.59,"nloc":62},{"file_path":"django/contrib/gis/db/models/proxy.py","score":9.0,"nloc":61},{"file_path":"django/contrib/redirects/migrations/0001_initial.py","score":9.59,"nloc":61},{"file_path":"django/utils/connection.py","score":9.65,"nloc":61},{"file_path":"django/views/decorators/cache.py","score":9.0,"nloc":61},{"file_path":"tests/apps/query_performing_app/apps.py","score":10.0,"nloc":61},{"file_path":"tests/model_package/tests.py","score":9.59,"nloc":61},{"file_path":"django/contrib/gis/db/backends/postgis/models.py","score":8.3,"nloc":60},{"file_path":"django/contrib/gis/geos/prototypes/topology.py","score":9.59,"nloc":60},{"file_path":"django/core/files/utils.py","score":9.59,"nloc":60},{"file_path":"django/db/models/utils.py","score":7.63,"nloc":60},{"file_path":"tests/admin_custom_urls/models.py","score":9.59,"nloc":60},{"file_path":"tests/csrf_tests/views.py","score":9.59,"nloc":60},{"file_path":"django/contrib/gis/db/backends/postgis/introspection.py","score":9.0,"nloc":59},{"file_path":"django/core/checks/messages.py","score":9.59,"nloc":59},{"file_path":"tests/db_functions/datetime/test_now.py","score":10.0,"nloc":59},{"file_path":"tests/sites_framework/tests.py","score":9.24,"nloc":59},{"file_path":"tests/template_tests/filter_tests/test_escapejs.py","score":9.59,"nloc":59},{"file_path":"django/conf/locale/nl/formats.py","score":9.59,"nloc":58},{"file_path":"django/contrib/gis/db/backends/spatialite/models.py","score":8.3,"nloc":58},{"file_path":"django/core/files/temp.py","score":9.29,"nloc":58},{"file_path":"django/db/migrations/optimizer.py","score":7.12,"nloc":58},{"file_path":"tests/custom_migration_operations/operations.py","score":8.64,"nloc":58},{"file_path":"tests/db_functions/text/test_reverse.py","score":9.5,"nloc":58},{"file_path":"tests/expressions_case/models.py","score":9.59,"nloc":58},{"file_path":"tests/template_tests/filter_tests/test_filesizeformat.py","score":9.59,"nloc":58},{"file_path":"tests/template_tests/filter_tests/test_linebreaks.py","score":9.59,"nloc":58},{"file_path":"django/contrib/gis/utils/srs.py","score":7.31,"nloc":57},{"file_path":"tests/custom_pk/fields.py","score":8.84,"nloc":57},{"file_path":"tests/model_fields/test_binaryfield.py","score":8.89,"nloc":57},{"file_path":"tests/template_tests/syntax_tests/test_invalid_string.py","score":9.59,"nloc":57},{"file_path":"tests/template_tests/syntax_tests/test_spaceless.py","score":9.59,"nloc":57},{"file_path":"django/contrib/gis/gdal/raster/base.py","score":10.0,"nloc":56},{"file_path":"django/db/backends/mysql/client.py","score":7.01,"nloc":56},{"file_path":"django/db/models/enums.py","score":8.64,"nloc":56},{"file_path":"django/forms/renderers.py","score":9.24,"nloc":56},{"file_path":"django/middleware/security.py","score":7.93,"nloc":56},{"file_path":"tests/admin_widgets/widgetadmin.py","score":9.59,"nloc":56},{"file_path":"tests/db_functions/text/test_sha224.py","score":9.24,"nloc":56},{"file_path":"tests/gis_tests/geoapp/test_sitemaps.py","score":8.7,"nloc":56},{"file_path":"tests/gis_tests/utils.py","score":9.0,"nloc":56},{"file_path":"tests/many_to_many/models.py","score":8.3,"nloc":56},{"file_path":"tests/postgres_tests/fields.py","score":9.24,"nloc":56},{"file_path":"tests/staticfiles_tests/test_liveserver.py","score":8.4,"nloc":56},{"file_path":"tests/template_tests/filter_tests/test_add.py","score":10.0,"nloc":56},{"file_path":"tests/template_tests/syntax_tests/test_with.py","score":9.59,"nloc":56},{"file_path":"django/contrib/admin/templatetags/log.py","score":9.0,"nloc":55},{"file_path":"django/contrib/gis/db/models/sql/conversion.py","score":7.14,"nloc":55},{"file_path":"django/core/management/commands/test.py","score":9.0,"nloc":55},{"file_path":"tests/db_functions/text/test_sha512.py","score":9.65,"nloc":55},{"file_path":"tests/decorators/test_gzip.py","score":9.3,"nloc":55},{"file_path":"tests/file_storage/test_base.py","score":10.0,"nloc":55},{"file_path":"tests/handlers/views.py","score":9.44,"nloc":55},{"file_path":"tests/m2m_through_regress/models.py","score":8.3,"nloc":55},{"file_path":"tests/model_regress/test_pickle.py","score":9.0,"nloc":55},{"file_path":"django/contrib/sites/managers.py","score":9.0,"nloc":54},{"file_path":"django/core/checks/security/csrf.py","score":9.24,"nloc":54},{"file_path":"django/core/serializers/pyyaml.py","score":8.7,"nloc":54},{"file_path":"django/utils/safestring.py","score":9.0,"nloc":54},{"file_path":"tests/admin_docs/test_middleware.py","score":9.59,"nloc":54},{"file_path":"tests/asgi/urls.py","score":9.59,"nloc":54},{"file_path":"tests/db_functions/text/test_sha384.py","score":9.65,"nloc":54},{"file_path":"tests/forms_tests/field_tests/test_booleanfield.py","score":8.84,"nloc":54},{"file_path":"tests/template_tests/filter_tests/test_linenumbers.py","score":9.59,"nloc":54},{"file_path":"tests/template_tests/filter_tests/test_striptags.py","score":9.59,"nloc":54},{"file_path":"tests/template_tests/syntax_tests/test_template_tag.py","score":10.0,"nloc":54},{"file_path":"django/contrib/admin/__init__.py","score":9.0,"nloc":53},{"file_path":"django/core/checks/translation.py","score":9.59,"nloc":53},{"file_path":"django/db/backends/dummy/base.py","score":9.0,"nloc":53},{"file_path":"django/db/backends/postgresql/client.py","score":5.8,"nloc":53},{"file_path":"tests/template_tests/filter_tests/test_slugify.py","score":9.59,"nloc":53},{"file_path":"tests/template_tests/syntax_tests/i18n/test_filters.py","score":9.65,"nloc":53},{"file_path":"django/contrib/admin/templatetags/admin_urls.py","score":7.78,"nloc":52},{"file_path":"django/contrib/gis/sitemaps/views.py","score":7.01,"nloc":52},{"file_path":"django/core/management/commands/testserver.py","score":9.0,"nloc":52},{"file_path":"django/core/serializers/jsonl.py","score":9.09,"nloc":52},{"file_path":"django/db/backends/mysql/compiler.py","score":6.76,"nloc":52},{"file_path":"django/db/models/fields/mixins.py","score":9.44,"nloc":52},{"file_path":"django/urls/__init__.py","score":10.0,"nloc":52},{"file_path":"tests/fixtures_model_package/tests.py","score":9.0,"nloc":52},{"file_path":"tests/m2m_through_regress/test_multitable.py","score":10.0,"nloc":52},{"file_path":"tests/multiple_database/models.py","score":9.44,"nloc":52},{"file_path":"tests/select_related/models.py","score":9.24,"nloc":52},{"file_path":"tests/template_tests/filter_tests/test_dictsortreversed.py","score":9.65,"nloc":52},{"file_path":"tests/template_tests/filter_tests/test_escapeseq.py","score":10.0,"nloc":52},{"file_path":"tests/template_tests/filter_tests/test_time.py","score":9.59,"nloc":52},{"file_path":"tests/template_tests/test_logging.py","score":9.59,"nloc":52},{"file_path":"django/contrib/gis/db/backends/oracle/adapter.py","score":9.59,"nloc":51},{"file_path":"django/contrib/gis/geos/prototypes/geom.py","score":9.0,"nloc":51},{"file_path":"django/contrib/postgres/lookups.py","score":9.59,"nloc":51},{"file_path":"django/core/mail/handler.py","score":9.4,"nloc":51},{"file_path":"django/http/__init__.py","score":9.0,"nloc":51},{"file_path":"django/template/loader.py","score":7.12,"nloc":51},{"file_path":"tests/absolute_url_overrides/tests.py","score":10.0,"nloc":51},{"file_path":"tests/backends/postgresql/test_compilation.py","score":9.65,"nloc":51},{"file_path":"tests/db_functions/text/test_pad.py","score":9.44,"nloc":51},{"file_path":"tests/messages_tests/test_session.py","score":8.99,"nloc":51},{"file_path":"tests/project_template/test_settings.py","score":9.24,"nloc":51},{"file_path":"tests/template_tests/filter_tests/test_truncatewords_html.py","score":9.59,"nloc":51},{"file_path":"tests/version/tests.py","score":8.99,"nloc":51},{"file_path":"django/contrib/gis/db/backends/oracle/models.py","score":8.7,"nloc":50},{"file_path":"django/core/management/sql.py","score":9.0,"nloc":50},{"file_path":"django/tasks/signals.py","score":10.0,"nloc":50},{"file_path":"django/utils/ipv6.py","score":9.0,"nloc":50},{"file_path":"tests/check_framework/test_database.py","score":9.59,"nloc":50},{"file_path":"tests/composite_pk/models/tenant.py","score":9.59,"nloc":50},{"file_path":"tests/decorators/test_vary.py","score":9.65,"nloc":50},{"file_path":"tests/field_defaults/models.py","score":9.59,"nloc":50},{"file_path":"tests/lookup/test_lookups.py","score":9.59,"nloc":50},{"file_path":"tests/m2m_regress/models.py","score":9.44,"nloc":50},{"file_path":"tests/mail/custombackend.py","score":9.44,"nloc":50},{"file_path":"tests/template_backends/test_utils.py","score":10.0,"nloc":50},{"file_path":"django/contrib/admindocs/urls.py","score":9.59,"nloc":49},{"file_path":"django/contrib/gis/gdal/__init__.py","score":9.0,"nloc":49},{"file_path":"django/contrib/postgres/aggregates/statistics.py","score":9.59,"nloc":49},{"file_path":"django/core/cache/__init__.py","score":9.0,"nloc":49},{"file_path":"django/core/checks/mail.py","score":10.0,"nloc":49},{"file_path":"django/core/management/commands/sendtestemail.py","score":9.24,"nloc":49},{"file_path":"django/db/models/functions/mixins.py","score":10.0,"nloc":49},{"file_path":"django/utils/deconstruct.py","score":9.59,"nloc":49},{"file_path":"tests/async/test_async_shortcuts.py","score":10.0,"nloc":49},{"file_path":"tests/db_functions/math/test_acos.py","score":8.64,"nloc":49},{"file_path":"tests/db_functions/math/test_asin.py","score":8.64,"nloc":49},{"file_path":"tests/db_functions/math/test_atan.py","score":8.64,"nloc":49},{"file_path":"tests/db_functions/math/test_ceil.py","score":8.89,"nloc":49},{"file_path":"tests/db_functions/math/test_degrees.py","score":8.64,"nloc":49},{"file_path":"tests/db_functions/math/test_floor.py","score":8.89,"nloc":49},{"file_path":"tests/db_functions/math/test_radians.py","score":8.64,"nloc":49},{"file_path":"tests/db_functions/math/test_sqrt.py","score":8.64,"nloc":49},{"file_path":"tests/gis_tests/gis_migrations/test_commands.py","score":9.85,"nloc":49},{"file_path":"tests/gis_tests/test_fields.py","score":9.59,"nloc":49},{"file_path":"tests/handlers/test_exception.py","score":10.0,"nloc":49},{"file_path":"tests/messages_tests/test_api.py","score":9.59,"nloc":49},{"file_path":"tests/queries/test_contains.py","score":10.0,"nloc":49},{"file_path":"tests/queries/test_iterator.py","score":9.4,"nloc":49},{"file_path":"tests/queryset_pickle/models.py","score":9.0,"nloc":49},{"file_path":"tests/template_tests/filter_tests/test_default.py","score":9.85,"nloc":49},{"file_path":"tests/template_tests/filter_tests/test_pluralize.py","score":9.59,"nloc":49},{"file_path":"tests/urlpatterns_reverse/test_localeregexdescriptor.py","score":8.99,"nloc":49},{"file_path":"django/tasks/backends/dummy.py","score":9.65,"nloc":48},{"file_path":"tests/db_functions/math/test_sign.py","score":9.3,"nloc":48},{"file_path":"tests/db_functions/text/test_sha256.py","score":9.65,"nloc":48},{"file_path":"tests/dbshell/test_oracle.py","score":9.59,"nloc":48},{"file_path":"tests/foreign_object/models/customers.py","score":10.0,"nloc":48},{"file_path":"tests/i18n/utils.py","score":9.59,"nloc":48},{"file_path":"tests/null_fk/tests.py","score":9.24,"nloc":48},{"file_path":"tests/postgres_tests/test_bulk_update.py","score":9.44,"nloc":48},{"file_path":"tests/syndication_tests/urls.py","score":9.0,"nloc":48},{"file_path":"tests/tasks/tasks.py","score":10.0,"nloc":48},{"file_path":"django/contrib/admin/static/admin/js/theme.js","score":10.0,"nloc":47},{"file_path":"django/contrib/admin/templatetags/base.py","score":9.24,"nloc":47},{"file_path":"django/contrib/flatpages/views.py","score":9.0,"nloc":47},{"file_path":"django/contrib/gis/db/backends/postgis/adapter.py","score":7.8,"nloc":47},{"file_path":"django/db/__init__.py","score":9.0,"nloc":47},{"file_path":"django/middleware/gzip.py","score":7.31,"nloc":47},{"file_path":"django/template/__init__.py","score":9.0,"nloc":47},{"file_path":"django/templatetags/l10n.py","score":9.44,"nloc":47},{"file_path":"tests/select_related_onetoone/models.py","score":9.59,"nloc":47},{"file_path":"tests/template_tests/filter_tests/test_linebreaksbr.py","score":9.59,"nloc":47},{"file_path":"tests/template_tests/syntax_tests/test_verbatim.py","score":9.59,"nloc":47},{"file_path":"tests/unmanaged_models/tests.py","score":9.59,"nloc":47},{"file_path":"tests/utils_tests/test_regex_helper.py","score":9.59,"nloc":47},{"file_path":"django/contrib/gis/utils/ogrinfo.py","score":7.17,"nloc":46},{"file_path":"tests/annotations/models.py","score":9.24,"nloc":46},{"file_path":"tests/db_functions/comparison/test_nullif.py","score":9.4,"nloc":46},{"file_path":"tests/db_functions/text/test_md5.py","score":9.65,"nloc":46},{"file_path":"tests/db_functions/text/test_sha1.py","score":9.65,"nloc":46},{"file_path":"tests/gis_tests/test_ptr.py","score":10.0,"nloc":46},{"file_path":"tests/template_tests/filter_tests/test_truncatewords.py","score":9.59,"nloc":46},{"file_path":"tests/template_tests/syntax_tests/i18n/test_get_language_info.py","score":9.59,"nloc":46},{"file_path":"django/contrib/auth/handlers/modwsgi.py","score":9.0,"nloc":45},{"file_path":"django/contrib/postgres/forms/hstore.py","score":9.0,"nloc":45},{"file_path":"django/core/checks/__init__.py","score":9.0,"nloc":45},{"file_path":"django/db/migrations/operations/__init__.py","score":10.0,"nloc":45},{"file_path":"django/template/autoreload.py","score":9.59,"nloc":45},{"file_path":"tests/db_functions/comparison/test_collate.py","score":9.65,"nloc":45},{"file_path":"tests/db_functions/math/test_cos.py","score":8.64,"nloc":45},{"file_path":"tests/db_functions/math/test_cot.py","score":8.64,"nloc":45},{"file_path":"tests/db_functions/math/test_exp.py","score":8.64,"nloc":45},{"file_path":"tests/db_functions/math/test_ln.py","score":8.64,"nloc":45},{"file_path":"tests/db_functions/math/test_sin.py","score":8.64,"nloc":45},{"file_path":"tests/db_functions/math/test_tan.py","score":8.64,"nloc":45},{"file_path":"tests/db_functions/models.py","score":9.59,"nloc":45},{"file_path":"tests/defer/models.py","score":9.44,"nloc":45},{"file_path":"tests/migrations/test_migrations_no_changes/0003_third.py","score":9.59,"nloc":45},{"file_path":"tests/shortcuts/views.py","score":10.0,"nloc":45},{"file_path":"tests/urlpatterns_reverse/views.py","score":9.0,"nloc":45},{"file_path":"django/contrib/auth/context_processors.py","score":8.64,"nloc":44},{"file_path":"django/contrib/gis/gdal/error.py","score":9.59,"nloc":44},{"file_path":"django/contrib/messages/storage/fallback.py","score":9.59,"nloc":44},{"file_path":"django/core/mail/deprecation.py","score":10.0,"nloc":44},{"file_path":"django/views/decorators/csrf.py","score":8.3,"nloc":44},{"file_path":"tests/auth_tests/models/__init__.py","score":9.59,"nloc":44},{"file_path":"tests/db_functions/math/test_abs.py","score":8.89,"nloc":44},{"file_path":"tests/forms_tests/widget_tests/test_passwordinput.py","score":9.65,"nloc":44},{"file_path":"tests/get_or_create/models.py","score":9.0,"nloc":44},{"file_path":"tests/multiple_database/routers.py","score":9.59,"nloc":44},{"file_path":"tests/proxy_model_inheritance/tests.py","score":9.0,"nloc":44},{"file_path":"tests/queries/test_sqlcompiler.py","score":10.0,"nloc":44},{"file_path":"tests/template_tests/filter_tests/test_escape.py","score":9.59,"nloc":44},{"file_path":"tests/template_tests/filter_tests/test_length.py","score":10.0,"nloc":44},{"file_path":"tests/template_tests/filter_tests/test_slice.py","score":9.59,"nloc":44},{"file_path":"tests/urlpatterns/test_resolvers.py","score":9.44,"nloc":44},{"file_path":"tests/validation/test_picklable.py","score":10.0,"nloc":44},{"file_path":"django/contrib/messages/storage/session.py","score":9.24,"nloc":43},{"file_path":"django/contrib/staticfiles/management/commands/findstatic.py","score":9.0,"nloc":43},{"file_path":"django/template/loaders/base.py","score":9.59,"nloc":43},{"file_path":"tests/db_functions/text/test_right.py","score":8.64,"nloc":43},{"file_path":"tests/gis_tests/geo3d/models.py","score":9.24,"nloc":43},{"file_path":"tests/i18n/sampleproject/update_catalogs.py","score":9.59,"nloc":43},{"file_path":"tests/template_tests/filter_tests/test_stringformat.py","score":9.59,"nloc":43},{"file_path":"django/contrib/contenttypes/migrations/0001_initial.py","score":9.24,"nloc":42},{"file_path":"django/contrib/flatpages/models.py","score":8.7,"nloc":42},{"file_path":"django/contrib/gis/geos/prototypes/threadsafe.py","score":9.24,"nloc":42},{"file_path":"django/template/backends/dummy.py","score":9.0,"nloc":42},{"file_path":"django/urls/converters.py","score":9.59,"nloc":42},{"file_path":"tests/admin_checks/models.py","score":9.59,"nloc":42},{"file_path":"tests/db_functions/text/test_chr.py","score":9.44,"nloc":42},{"file_path":"tests/foreign_object/test_empty_join.py","score":9.59,"nloc":42},{"file_path":"tests/generic_views/models.py","score":9.59,"nloc":42},{"file_path":"tests/mail/__init__.py","score":10.0,"nloc":42},{"file_path":"tests/model_fields/test_mixins.py","score":9.65,"nloc":42},{"file_path":"tests/template_tests/filter_tests/test_autoescape.py","score":9.59,"nloc":42},{"file_path":"django/contrib/postgres/utils.py","score":9.24,"nloc":41},{"file_path":"tests/backends/mysql/test_features.py","score":10.0,"nloc":41},{"file_path":"tests/db_functions/text/test_length.py","score":9.85,"nloc":41},{"file_path":"tests/forms_tests/tests/test_renderers.py","score":9.24,"nloc":41},{"file_path":"tests/inline_formsets/models.py","score":8.89,"nloc":41},{"file_path":"tests/migrations/models.py","score":9.59,"nloc":41},{"file_path":"tests/model_fields/test_floatfield.py","score":9.24,"nloc":41},{"file_path":"tests/modeladmin/models.py","score":8.3,"nloc":41},{"file_path":"tests/postgres_tests/test_introspection.py","score":9.24,"nloc":41},{"file_path":"django/conf/locale/en/formats.py","score":9.24,"nloc":40},{"file_path":"django/conf/locale/ht/formats.py","score":9.65,"nloc":40},{"file_path":"django/contrib/contenttypes/checks.py","score":9.24,"nloc":40},{"file_path":"django/contrib/redirects/middleware.py","score":6.41,"nloc":40},{"file_path":"django/contrib/sites/migrations/0001_initial.py","score":9.59,"nloc":40},{"file_path":"django/core/mail/backends/console.py","score":8.7,"nloc":40},{"file_path":"tests/admin_views/test_forms.py","score":10.0,"nloc":40},{"file_path":"tests/backends/mysql/test_operations.py","score":10.0,"nloc":40},{"file_path":"tests/custom_methods/tests.py","score":9.59,"nloc":40},{"file_path":"tests/db_functions/text/test_substr.py","score":10.0,"nloc":40},{"file_path":"tests/generic_inline_admin/models.py","score":9.59,"nloc":40},{"file_path":"tests/gis_tests/geoapp/feeds.py","score":9.59,"nloc":40},{"file_path":"tests/gis_tests/relatedapp/models.py","score":9.0,"nloc":40},{"file_path":"tests/template_tests/filter_tests/test_truncatechars_html.py","score":9.59,"nloc":40},{"file_path":"tests/test_client/test_conditional_content_removal.py","score":9.59,"nloc":40},{"file_path":"tests/test_runner_apps/sample/doctests.py","score":10.0,"nloc":40},{"file_path":"tests/utils_tests/test_json.py","score":10.0,"nloc":40},{"file_path":"django/conf/locale/id/formats.py","score":9.59,"nloc":39},{"file_path":"django/core/management/commands/dbshell.py","score":9.0,"nloc":39},{"file_path":"django/db/backends/postgresql/compiler.py","score":9.07,"nloc":39},{"file_path":"django/db/models/signals.py","score":9.0,"nloc":39},{"file_path":"tests/backends/postgresql/test_introspection.py","score":10.0,"nloc":39},{"file_path":"tests/basic/models.py","score":9.0,"nloc":39},{"file_path":"tests/db_functions/math/test_log.py","score":9.65,"nloc":39},{"file_path":"tests/db_functions/text/test_upper.py","score":9.65,"nloc":39},{"file_path":"tests/distinct_on_fields/models.py","score":9.59,"nloc":39},{"file_path":"tests/migration_test_data_persistence/migrations/0002_add_book.py","score":9.65,"nloc":39},{"file_path":"tests/migrations/test_add_many_to_many_field_initial/0001_initial.py","score":10.0,"nloc":39},{"file_path":"tests/model_regress/models.py","score":8.3,"nloc":39},{"file_path":"tests/staticfiles_tests/test_forms.py","score":9.59,"nloc":39},{"file_path":"tests/template_tests/filter_tests/test_iriencode.py","score":10.0,"nloc":39},{"file_path":"django/conf/locale/lt/formats.py","score":9.24,"nloc":38},{"file_path":"django/conf/locale/lv/formats.py","score":9.24,"nloc":38},{"file_path":"django/contrib/gis/geos/prototypes/predicates.py","score":9.59,"nloc":38},{"file_path":"django/contrib/postgres/fields/citext.py","score":10.0,"nloc":38},{"file_path":"django/db/models/fetch_modes.py","score":10.0,"nloc":38},{"file_path":"tests/db_functions/math/test_power.py","score":9.65,"nloc":38},{"file_path":"tests/dbshell/test_sqlite.py","score":9.59,"nloc":38},{"file_path":"tests/gis_tests/test_gis_tests_utils.py","score":10.0,"nloc":38},{"file_path":"tests/migration_test_data_persistence/tests.py","score":9.59,"nloc":38},{"file_path":"tests/template_tests/filter_tests/test_center.py","score":9.59,"nloc":38},{"file_path":"tests/template_tests/filter_tests/test_phone2numeric.py","score":9.59,"nloc":38},{"file_path":"tests/template_tests/syntax_tests/test_debug.py","score":10.0,"nloc":38},{"file_path":"tests/validation/test_validators.py","score":9.59,"nloc":38},{"file_path":"tests/view_tests/generic_urls.py","score":9.0,"nloc":38},{"file_path":"django/conf/locale/eo/formats.py","score":9.59,"nloc":37},{"file_path":"django/contrib/contenttypes/migrations/0002_remove_content_type_name.py","score":9.59,"nloc":37},{"file_path":"django/contrib/sessions/base_session.py","score":10.0,"nloc":37},{"file_path":"django/core/files/storage/handler.py","score":9.06,"nloc":37},{"file_path":"django/tasks/__init__.py","score":10.0,"nloc":37},{"file_path":"tests/admin_views/urls.py","score":9.0,"nloc":37},{"file_path":"tests/aggregation/models.py","score":8.3,"nloc":37},{"file_path":"tests/backends/sqlite/test_features.py","score":10.0,"nloc":37},{"file_path":"tests/custom_columns/models.py","score":8.7,"nloc":37},{"file_path":"tests/db_functions/math/test_mod.py","score":9.65,"nloc":37},{"file_path":"tests/db_functions/text/test_trim.py","score":9.59,"nloc":37},{"file_path":"tests/forms_tests/field_tests/test_timefield.py","score":10.0,"nloc":37},{"file_path":"tests/order_with_respect_to/tests.py","score":9.59,"nloc":37},{"file_path":"tests/reverse_lookup/tests.py","score":9.59,"nloc":37},{"file_path":"tests/staticfiles_tests/project/documents/cached/module.js","score":10.0,"nloc":37},{"file_path":"tests/template_tests/filter_tests/test_make_list.py","score":9.59,"nloc":37},{"file_path":"tests/urlpatterns/path_urls.py","score":9.59,"nloc":37},{"file_path":"django/conf/locale/it/formats.py","score":9.59,"nloc":36},{"file_path":"django/conf/locale/ko/formats.py","score":9.59,"nloc":36},{"file_path":"django/test/__init__.py","score":9.0,"nloc":36},{"file_path":"tests/conditional_processing/views.py","score":9.59,"nloc":36},{"file_path":"tests/db_functions/math/test_atan2.py","score":9.65,"nloc":36},{"file_path":"tests/migrations/migrations_test_apps/with_generic_model/migrations/0001_initial.py","score":10.0,"nloc":36},{"file_path":"tests/model_fields/test_autofield.py","score":9.59,"nloc":36},{"file_path":"tests/model_fields/test_genericipaddressfield.py","score":10.0,"nloc":36},{"file_path":"tests/model_fields/test_textfield.py","score":8.89,"nloc":36},{"file_path":"tests/model_forms/test_uuid.py","score":9.59,"nloc":36},{"file_path":"tests/model_formsets_regress/models.py","score":9.24,"nloc":36},{"file_path":"tests/template_tests/syntax_tests/test_filter_tag.py","score":10.0,"nloc":36},{"file_path":"tests/urlpatterns_reverse/included_namespace_urls.py","score":10.0,"nloc":36},{"file_path":"django/conf/locale/hr/formats.py","score":9.24,"nloc":35},{"file_path":"django/conf/locale/ka/formats.py","score":9.24,"nloc":35},{"file_path":"django/conf/locale/sl/formats.py","score":9.59,"nloc":35},{"file_path":"django/contrib/gis/db/backends/postgis/const.py","score":9.59,"nloc":35},{"file_path":"django/middleware/clickjacking.py","score":9.59,"nloc":35},{"file_path":"django/template/exceptions.py","score":10.0,"nloc":35},{"file_path":"django/template/loaders/filesystem.py","score":9.03,"nloc":35},{"file_path":"django/views/generic/__init__.py","score":9.59,"nloc":35},{"file_path":"tests/admin_utils/admin.py","score":10.0,"nloc":35},{"file_path":"tests/db_functions/text/test_lower.py","score":9.65,"nloc":35},{"file_path":"tests/deprecation/internal.py","score":10.0,"nloc":35},{"file_path":"tests/i18n/patterns/urls/default.py","score":9.59,"nloc":35},{"file_path":"tests/indexes/models.py","score":9.59,"nloc":35},{"file_path":"tests/postgres_tests/array_index_migrations/0001_initial.py","score":9.59,"nloc":35},{"file_path":"tests/postgres_tests/test_signals.py","score":8.84,"nloc":35},{"file_path":"tests/test_runner_apps/simple/tests.py","score":10.0,"nloc":35},{"file_path":"tests/update/models.py","score":9.0,"nloc":35},{"file_path":"django/contrib/gis/geos/prepared.py","score":10.0,"nloc":34},{"file_path":"django/contrib/sessions/migrations/0001_initial.py","score":9.59,"nloc":34},{"file_path":"django/contrib/sites/management.py","score":9.0,"nloc":34},{"file_path":"tests/auth_tests/client.py","score":9.59,"nloc":34},{"file_path":"tests/forms_tests/field_tests/test_combofield.py","score":10.0,"nloc":34},{"file_path":"tests/sessions_tests/models.py","score":9.59,"nloc":34},{"file_path":"tests/template_tests/filter_tests/test_addslashes.py","score":9.59,"nloc":34},{"file_path":"tests/template_tests/filter_tests/test_upper.py","score":9.59,"nloc":34},{"file_path":"tests/template_tests/test_smartif.py","score":9.59,"nloc":34},{"file_path":"tests/view_tests/models.py","score":9.59,"nloc":34},{"file_path":"django/conf/locale/cs/formats.py","score":9.59,"nloc":33},{"file_path":"django/contrib/gis/db/backends/oracle/introspection.py","score":9.59,"nloc":33},{"file_path":"django/db/migrations/exceptions.py","score":9.59,"nloc":33},{"file_path":"django/utils/translation/trans_null.py","score":9.0,"nloc":33},{"file_path":"tests/auth_tests/test_templatetags.py","score":10.0,"nloc":33},{"file_path":"tests/check_framework/test_multi_db.py","score":9.59,"nloc":33},{"file_path":"tests/flatpages_tests/test_sitemaps.py","score":9.44,"nloc":33},{"file_path":"tests/gis_tests/distapp/models.py","score":9.59,"nloc":33},{"file_path":"tests/migrations/test_migrations_squashed_partially_applied/0001_initial.py","score":10.0,"nloc":33},{"file_path":"tests/postgres_tests/migrations/0001_setup_extensions.py","score":9.0,"nloc":33},{"file_path":"tests/servers/test_liveserverthread.py","score":10.0,"nloc":33},{"file_path":"tests/staticfiles_tests/test_views.py","score":10.0,"nloc":33},{"file_path":"tests/template_tests/filter_tests/test_wordcount.py","score":10.0,"nloc":33},{"file_path":"tests/template_tests/syntax_tests/test_lorem.py","score":9.59,"nloc":33},{"file_path":"tests/template_tests/syntax_tests/test_numpy.py","score":9.59,"nloc":33},{"file_path":"django/conf/locale/zh_Hans/formats.py","score":9.24,"nloc":32},{"file_path":"django/conf/locale/zh_Hant/formats.py","score":9.24,"nloc":32},{"file_path":"django/conf/urls/i18n.py","score":9.59,"nloc":32},{"file_path":"django/contrib/staticfiles/management/commands/runserver.py","score":9.59,"nloc":32},{"file_path":"django/utils/duration.py","score":9.59,"nloc":32},{"file_path":"tests/admin_default_site/tests.py","score":10.0,"nloc":32},{"file_path":"tests/deprecation/test_signed_cookie_legacy_salt_fallback.py","score":9.65,"nloc":32},{"file_path":"tests/deprecation/test_use_blank_choice_dash.py","score":9.65,"nloc":32},{"file_path":"tests/handlers/tests_custom_error_handlers.py","score":9.59,"nloc":32},{"file_path":"tests/m2o_recursive/tests.py","score":9.59,"nloc":32},{"file_path":"tests/save_delete_hooks/tests.py","score":9.59,"nloc":32},{"file_path":"tests/servers/views.py","score":9.59,"nloc":32},{"file_path":"tests/staticfiles_tests/test_handlers.py","score":10.0,"nloc":32},{"file_path":"tests/template_tests/filter_tests/test_ljust.py","score":10.0,"nloc":32},{"file_path":"django/conf/locale/mk/formats.py","score":9.59,"nloc":31},{"file_path":"django/conf/locale/ms/formats.py","score":9.65,"nloc":31},{"file_path":"django/conf/locale/sr/formats.py","score":9.24,"nloc":31},{"file_path":"django/conf/locale/sr_Latn/formats.py","score":9.24,"nloc":31},{"file_path":"django/contrib/admin/static/admin/js/prepopulate.js","score":9.24,"nloc":31},{"file_path":"django/contrib/contenttypes/prefetch.py","score":9.6,"nloc":31},{"file_path":"django/contrib/gis/ptr.py","score":9.85,"nloc":31},{"file_path":"django/contrib/gis/shortcuts.py","score":9.59,"nloc":31},{"file_path":"django/contrib/redirects/models.py","score":9.0,"nloc":31},{"file_path":"tests/contenttypes_tests/operations_migrations/0002_rename_foo.py","score":9.85,"nloc":31},{"file_path":"tests/custom_methods/models.py","score":9.59,"nloc":31},{"file_path":"tests/db_functions/text/test_repeat.py","score":9.24,"nloc":31},{"file_path":"tests/db_functions/window/test_validation.py","score":10.0,"nloc":31},{"file_path":"tests/forms_tests/field_tests/test_base.py","score":9.59,"nloc":31},{"file_path":"tests/forms_tests/widget_tests/base.py","score":9.59,"nloc":31},{"file_path":"tests/max_lengths/tests.py","score":9.59,"nloc":31},{"file_path":"tests/migrations/test_migrations/0001_initial.py","score":9.24,"nloc":31},{"file_path":"tests/model_options/models/tablespaces.py","score":9.59,"nloc":31},{"file_path":"tests/template_tests/filter_tests/test_rjust.py","score":10.0,"nloc":31},{"file_path":"tests/utils_tests/test_hashable.py","score":10.0,"nloc":31},{"file_path":"django/conf/locale/en_IE/formats.py","score":9.65,"nloc":30},{"file_path":"django/contrib/auth/urls.py","score":9.59,"nloc":30},{"file_path":"django/contrib/staticfiles/views.py","score":9.0,"nloc":30},{"file_path":"django/middleware/http.py","score":9.0,"nloc":30},{"file_path":"django/utils/asyncio.py","score":9.44,"nloc":30},{"file_path":"django/views/decorators/vary.py","score":9.59,"nloc":30},{"file_path":"tests/forms_tests/widget_tests/test_widget.py","score":9.44,"nloc":30},{"file_path":"tests/lookup/test_decimalfield.py","score":10.0,"nloc":30},{"file_path":"tests/null_fk/models.py","score":9.24,"nloc":30},{"file_path":"tests/order_with_respect_to/models.py","score":9.24,"nloc":30},{"file_path":"tests/postgres_tests/test_functions.py","score":9.65,"nloc":30},{"file_path":"tests/template_tests/filter_tests/test_first.py","score":10.0,"nloc":30},{"file_path":"tests/template_tests/filter_tests/test_lower.py","score":9.59,"nloc":30},{"file_path":"tests/update_only_fields/models.py","score":9.59,"nloc":30},{"file_path":"django/contrib/admin/static/admin/js/filters.js","score":10.0,"nloc":29},{"file_path":"django/contrib/admindocs/middleware.py","score":9.19,"nloc":29},{"file_path":"django/contrib/auth/apps.py","score":9.24,"nloc":29},{"file_path":"django/contrib/gis/db/models/__init__.py","score":9.59,"nloc":29},{"file_path":"tests/async/test_async_model_methods.py","score":10.0,"nloc":29},{"file_path":"tests/backends/base/test_introspection.py","score":10.0,"nloc":29},{"file_path":"tests/logging_tests/views.py","score":9.59,"nloc":29},{"file_path":"tests/m2m_intermediary/tests.py","score":9.59,"nloc":29},{"file_path":"tests/model_indexes/models.py","score":9.59,"nloc":29},{"file_path":"tests/null_fk_ordering/tests.py","score":9.59,"nloc":29},{"file_path":"tests/raw_query/models.py","score":9.59,"nloc":29},{"file_path":"tests/template_tests/filter_tests/test_yesno.py","score":9.65,"nloc":29},{"file_path":"django/conf/locale/fi/formats.py","score":9.59,"nloc":28},{"file_path":"django/conf/locale/ro/formats.py","score":9.59,"nloc":28},{"file_path":"django/conf/locale/uk/formats.py","score":9.59,"nloc":28},{"file_path":"django/contrib/admin/static/admin/js/autocomplete.js","score":9.24,"nloc":28},{"file_path":"django/contrib/admin/static/admin/js/popup_response.js","score":9.44,"nloc":28},{"file_path":"django/contrib/gis/admin/__init__.py","score":9.59,"nloc":28},{"file_path":"django/utils/xmlutils.py","score":9.24,"nloc":28},{"file_path":"tests/check_framework/test_files.py","score":10.0,"nloc":28},{"file_path":"tests/db_functions/text/test_left.py","score":9.24,"nloc":28},{"file_path":"tests/db_functions/text/test_ord.py","score":9.65,"nloc":28},{"file_path":"tests/extra_regress/models.py","score":9.0,"nloc":28},{"file_path":"tests/gis_tests/geogapp/models.py","score":9.24,"nloc":28},{"file_path":"tests/i18n/test_management.py","score":10.0,"nloc":28},{"file_path":"tests/migrations/test_migrations_non_atomic/0001_initial.py","score":10.0,"nloc":28},{"file_path":"tests/migrations/test_migrations_squashed/0001_squashed_0002.py","score":9.24,"nloc":28},{"file_path":"tests/model_options/test_default_related_name.py","score":10.0,"nloc":28},{"file_path":"tests/str/tests.py","score":10.0,"nloc":28},{"file_path":"django/conf/locale/el/formats.py","score":9.59,"nloc":27},{"file_path":"django/conf/locale/ml/formats.py","score":9.24,"nloc":27},{"file_path":"django/conf/locale/nb/formats.py","score":9.24,"nloc":27},{"file_path":"django/conf/locale/nn/formats.py","score":9.24,"nloc":27},{"file_path":"django/conf/locale/pt/formats.py","score":9.24,"nloc":27},{"file_path":"django/conf/locale/sv/formats.py","score":9.24,"nloc":27},{"file_path":"django/core/mail/backends/locmem.py","score":9.24,"nloc":27},{"file_path":"django/core/management/commands/sqlsequencereset.py","score":8.3,"nloc":27},{"file_path":"django/utils/translation/reloader.py","score":10.0,"nloc":27},{"file_path":"django/views/decorators/csp.py","score":10.0,"nloc":27},{"file_path":"tests/decorators/test_common.py","score":9.65,"nloc":27},{"file_path":"tests/get_earliest_or_latest/models.py","score":9.24,"nloc":27},{"file_path":"tests/migrations/test_fake_initial_case_insensitive/fake_initial/0001_initial.py","score":10.0,"nloc":27},{"file_path":"tests/migrations/test_migrations_custom_user/0001_initial.py","score":9.24,"nloc":27},{"file_path":"tests/migrations2/test_migrations_2_squashed_with_replaces/0001_squashed_0002.py","score":10.0,"nloc":27},{"file_path":"tests/select_for_update/models.py","score":9.24,"nloc":27},{"file_path":"tests/template_tests/filter_tests/test_capfirst.py","score":10.0,"nloc":27},{"file_path":"django/conf/locale/cy/formats.py","score":9.24,"nloc":26},{"file_path":"django/conf/locale/en_AU/formats.py","score":9.24,"nloc":26},{"file_path":"django/conf/locale/en_GB/formats.py","score":9.24,"nloc":26},{"file_path":"django/conf/locale/th/formats.py","score":9.59,"nloc":26},{"file_path":"tests/admin_ordering/models.py","score":9.59,"nloc":26},{"file_path":"tests/auth_tests/models/with_many_to_many.py","score":10.0,"nloc":26},{"file_path":"tests/custom_pk/models.py","score":8.3,"nloc":26},{"file_path":"tests/field_subclassing/tests.py","score":9.0,"nloc":26},{"file_path":"tests/force_insert_update/models.py","score":9.59,"nloc":26},{"file_path":"tests/forms_tests/widget_tests/test_numberinput.py","score":9.24,"nloc":26},{"file_path":"tests/from_db_value/tests.py","score":8.99,"nloc":26},{"file_path":"tests/m2m_multiple/models.py","score":9.59,"nloc":26},{"file_path":"tests/m2m_recursive/models.py","score":9.59,"nloc":26},{"file_path":"tests/m2o_recursive/models.py","score":9.59,"nloc":26},{"file_path":"tests/migrations/migrations_test_apps/mutate_state_a/migrations/0001_initial.py","score":10.0,"nloc":26},{"file_path":"tests/migrations/migrations_test_apps/with_generic_model/migrations/0002_customgenericmodel.py","score":10.0,"nloc":26},{"file_path":"tests/migrations/test_migrations_fake_split_initial/0001_initial.py","score":9.24,"nloc":26},{"file_path":"tests/migrations/test_migrations_initial_false/0001_not_initial.py","score":9.24,"nloc":26},{"file_path":"tests/model_options/models/default_related_name.py","score":10.0,"nloc":26},{"file_path":"tests/null_fk_ordering/models.py","score":9.24,"nloc":26},{"file_path":"tests/postgres_tests/array_default_migrations/0001_initial.py","score":9.59,"nloc":26},{"file_path":"tests/postgres_tests/test_integration.py","score":9.59,"nloc":26},{"file_path":"tests/staticfiles_tests/settings.py","score":9.24,"nloc":26},{"file_path":"tests/template_tests/filter_tests/test_random.py","score":9.59,"nloc":26},{"file_path":"tests/urlpatterns/converters.py","score":9.4,"nloc":26},{"file_path":"tests/urlpatterns/path_same_name_urls.py","score":10.0,"nloc":26},{"file_path":"tests/urlpatterns_reverse/middleware.py","score":9.59,"nloc":26},{"file_path":"tests/utils_tests/test_warnings.py","score":10.0,"nloc":26},{"file_path":"django/conf/locale/fr_BE/formats.py","score":9.65,"nloc":25},{"file_path":"django/conf/locale/fr_CH/formats.py","score":9.65,"nloc":25},{"file_path":"django/conf/locale/ig/formats.py","score":9.65,"nloc":25},{"file_path":"django/conf/locale/ky/formats.py","score":9.65,"nloc":25},{"file_path":"django/conf/locale/tg/formats.py","score":9.65,"nloc":25},{"file_path":"django/conf/locale/tk/formats.py","score":9.65,"nloc":25},{"file_path":"django/contrib/admin/forms.py","score":9.59,"nloc":25},{"file_path":"django/contrib/gis/db/backends/oracle/features.py","score":10.0,"nloc":25},{"file_path":"django/contrib/gis/geos/factory.py","score":9.04,"nloc":25},{"file_path":"django/contrib/sessions/models.py","score":9.0,"nloc":25},{"file_path":"django/core/management/commands/sqlflush.py","score":9.24,"nloc":25},{"file_path":"tests/auth_tests/models/custom_permissions.py","score":9.59,"nloc":25},{"file_path":"tests/auth_tests/test_login.py","score":10.0,"nloc":25},{"file_path":"tests/backends/base/test_client.py","score":10.0,"nloc":25},{"file_path":"tests/forms_tests/field_tests/test_uuidfield.py","score":8.64,"nloc":25},{"file_path":"tests/i18n/commands/javascript.js","score":10.0,"nloc":25},{"file_path":"tests/middleware_exceptions/views.py","score":9.59,"nloc":25},{"file_path":"tests/migrations/migrations_test_apps/lookuperror_a/migrations/0003_a3.py","score":9.59,"nloc":25},{"file_path":"tests/migrations/test_fake_initial_case_insensitive/initial/0001_initial.py","score":10.0,"nloc":25},{"file_path":"tests/pagination/custom.py","score":9.59,"nloc":25},{"file_path":"tests/postgres_tests/__init__.py","score":9.59,"nloc":25},{"file_path":"tests/staticfiles_tests/test_templatetags.py","score":9.59,"nloc":25},{"file_path":"tests/test_runner/runner.py","score":9.59,"nloc":25},{"file_path":"django/conf/locale/es_CO/formats.py","score":9.65,"nloc":24},{"file_path":"django/conf/locale/es_MX/formats.py","score":9.24,"nloc":24},{"file_path":"django/conf/locale/es_NI/formats.py","score":9.24,"nloc":24},{"file_path":"django/conf/urls/static.py","score":9.59,"nloc":24},{"file_path":"django/contrib/admin/static/admin/js/cancel.js","score":9.85,"nloc":24},{"file_path":"django/contrib/admin/static/admin/js/prepopulate_init.js","score":10.0,"nloc":24},{"file_path":"django/contrib/gis/geos/prototypes/misc.py","score":9.59,"nloc":24},{"file_path":"django/contrib/sites/checks.py","score":10.0,"nloc":24},{"file_path":"django/contrib/staticfiles/checks.py","score":9.85,"nloc":24},{"file_path":"django/core/cache/backends/dummy.py","score":8.99,"nloc":24},{"file_path":"django/db/backends/base/validation.py","score":9.59,"nloc":24},{"file_path":"tests/admin_views/custom_has_permission_admin.py","score":9.59,"nloc":24},{"file_path":"tests/admin_views/test_breadcrumbs.py","score":9.65,"nloc":24},{"file_path":"tests/check_framework/test_4_0_compatibility.py","score":10.0,"nloc":24},{"file_path":"tests/get_object_or_404/models.py","score":9.0,"nloc":24},{"file_path":"tests/gis_tests/geoapp/urls.py","score":9.59,"nloc":24},{"file_path":"tests/migrations/migrations_test_apps/mutate_state_b/migrations/0001_initial.py","score":10.0,"nloc":24},{"file_path":"tests/signals/models.py","score":9.24,"nloc":24},{"file_path":"django/conf/locale/az/formats.py","score":9.24,"nloc":23},{"file_path":"django/conf/locale/ca/formats.py","score":9.24,"nloc":23},{"file_path":"django/conf/locale/en_CA/formats.py","score":10.0,"nloc":23},{"file_path":"django/conf/locale/es/formats.py","score":9.24,"nloc":23},{"file_path":"django/conf/locale/es_AR/formats.py","score":9.24,"nloc":23},{"file_path":"django/conf/locale/es_PR/formats.py","score":9.24,"nloc":23},{"file_path":"django/conf/locale/fr_CA/formats.py","score":10.0,"nloc":23},{"file_path":"django/conf/locale/hu/formats.py","score":9.59,"nloc":23},{"file_path":"django/conf/locale/pt_BR/formats.py","score":9.24,"nloc":23},{"file_path":"django/conf/locale/ru/formats.py","score":9.24,"nloc":23},{"file_path":"django/conf/locale/uz/formats.py","score":10.0,"nloc":23},{"file_path":"django/contrib/auth/migrations/0004_alter_user_username_opts.py","score":9.59,"nloc":23},{"file_path":"django/contrib/auth/migrations/0007_alter_validators_add_error_messages.py","score":10.0,"nloc":23},{"file_path":"django/contrib/auth/migrations/0008_alter_user_username_max_length.py","score":9.59,"nloc":23},{"file_path":"django/contrib/gis/db/backends/utils.py","score":9.59,"nloc":23},{"file_path":"tests/flatpages_tests/test_models.py","score":9.59,"nloc":23},{"file_path":"tests/lookup/test_timefield.py","score":10.0,"nloc":23},{"file_path":"tests/migrations/migrations_test_apps/lookuperror_b/migrations/0002_b2.py","score":9.24,"nloc":23},{"file_path":"tests/migrations/migrations_test_apps/lookuperror_c/migrations/0002_c2.py","score":9.24,"nloc":23},{"file_path":"tests/migrations/test_migrations_squashed_double/0005_squashed_0003_and_0004.py","score":9.65,"nloc":23},{"file_path":"tests/template_tests/filter_tests/test_truncatechars.py","score":9.59,"nloc":23},{"file_path":"tests/template_tests/syntax_tests/i18n/test_get_available_languages.py","score":9.59,"nloc":23},{"file_path":"tests/template_tests/syntax_tests/test_setup.py","score":10.0,"nloc":23},{"file_path":"tests/template_tests/test_origin.py","score":10.0,"nloc":23},{"file_path":"tests/template_tests/urls.py","score":9.0,"nloc":23},{"file_path":"tests/test_client_regress/session.py","score":8.84,"nloc":23},{"file_path":"tests/urlpatterns_reverse/included_app_urls.py","score":10.0,"nloc":23},{"file_path":"tests/user_commands/management/commands/hal.py","score":9.59,"nloc":23},{"file_path":"django/conf/locale/ar_DZ/formats.py","score":10.0,"nloc":22},{"file_path":"django/conf/locale/bn/formats.py","score":9.59,"nloc":22},{"file_path":"django/contrib/auth/templatetags/auth.py","score":10.0,"nloc":22},{"file_path":"django/contrib/gis/db/backends/spatialite/features.py","score":10.0,"nloc":22},{"file_path":"django/core/checks/commands.py","score":10.0,"nloc":22},{"file_path":"django/middleware/csp.py","score":10.0,"nloc":22},{"file_path":"tests/apps/apps.py","score":10.0,"nloc":22},{"file_path":"tests/check_framework/test_commands.py","score":10.0,"nloc":22},{"file_path":"tests/expressions_window/models.py","score":9.59,"nloc":22},{"file_path":"tests/forms_tests/field_tests/test_slugfield.py","score":10.0,"nloc":22},{"file_path":"tests/forms_tests/widget_tests/test_hiddeninput.py","score":9.65,"nloc":22},{"file_path":"tests/gis_tests/geoadmin/models.py","score":9.59,"nloc":22},{"file_path":"tests/i18n/contenttypes/tests.py","score":9.0,"nloc":22},{"file_path":"tests/m2m_intermediary/models.py","score":9.24,"nloc":22},{"file_path":"tests/migration_test_data_persistence/migrations/0001_initial.py","score":9.59,"nloc":22},{"file_path":"tests/migrations/test_migrations_no_default/0001_initial.py","score":9.59,"nloc":22},{"file_path":"tests/migrations/test_migrations_run_before/0003_third.py","score":9.65,"nloc":22},{"file_path":"tests/model_regress/test_state.py","score":9.44,"nloc":22},{"file_path":"tests/save_delete_hooks/models.py","score":9.59,"nloc":22},{"file_path":"tests/sitemaps_tests/base.py","score":9.59,"nloc":22},{"file_path":"tests/template_tests/filter_tests/test_last.py","score":10.0,"nloc":22},{"file_path":"tests/urlpatterns/path_base64_urls.py","score":10.0,"nloc":22},{"file_path":"django/conf/locale/pl/formats.py","score":9.59,"nloc":21},{"file_path":"django/conf/locale/sk/formats.py","score":9.59,"nloc":21},{"file_path":"django/conf/locale/tr/formats.py","score":9.59,"nloc":21},{"file_path":"django/contrib/gis/geos/io.py","score":9.59,"nloc":21},{"file_path":"django/core/files/storage/__init__.py","score":10.0,"nloc":21},{"file_path":"django/db/backends/base/client.py","score":9.59,"nloc":21},{"file_path":"django/db/backends/oracle/client.py","score":9.59,"nloc":21},{"file_path":"tests/admin_inlines/test_templates.py","score":10.0,"nloc":21},{"file_path":"tests/admin_scripts/another_app_waiting_migration/migrations/0001_initial.py","score":9.65,"nloc":21},{"file_path":"tests/admin_scripts/app_waiting_migration/migrations/0001_initial.py","score":9.65,"nloc":21},{"file_path":"tests/admin_scripts/app_with_urls/root_urls.py","score":10.0,"nloc":21},{"file_path":"tests/backends/base/app_unmigrated/migrations/0001_initial.py","score":9.65,"nloc":21},{"file_path":"tests/check_framework/urls/unique_namespaces.py","score":10.0,"nloc":21},{"file_path":"tests/foreign_object/models/__init__.py","score":9.59,"nloc":21},{"file_path":"tests/foreign_object/test_agnostic_order_trimjoin.py","score":10.0,"nloc":21},{"file_path":"tests/foreign_object/test_forms.py","score":10.0,"nloc":21},{"file_path":"tests/many_to_one_null/models.py","score":9.24,"nloc":21},{"file_path":"tests/middleware/urls.py","score":9.24,"nloc":21},{"file_path":"tests/migrations/migrations_test_apps/conflicting_app_with_dependencies/migrations/0001_initial.py","score":9.65,"nloc":21},{"file_path":"tests/migrations/migrations_test_apps/lookuperror_a/migrations/0002_a2.py","score":9.59,"nloc":21},{"file_path":"tests/migrations/migrations_test_apps/lookuperror_a/migrations/0004_a4.py","score":9.59,"nloc":21},{"file_path":"tests/migrations/migrations_test_apps/lookuperror_b/migrations/0003_b3.py","score":9.59,"nloc":21},{"file_path":"tests/migrations/migrations_test_apps/lookuperror_c/migrations/0003_c3.py","score":9.59,"nloc":21},{"file_path":"tests/migrations/migrations_test_apps/migrated_app/migrations/0001_initial.py","score":9.65,"nloc":21},{"file_path":"tests/migrations/migrations_test_apps/unspecified_app_with_conflict/migrations/0001_initial.py","score":9.65,"nloc":21},{"file_path":"tests/migrations/test_migrations_conflict/0001_initial.py","score":9.24,"nloc":21},{"file_path":"tests/migrations/test_migrations_first/second.py","score":9.24,"nloc":21},{"file_path":"tests/migrations/test_migrations_first/thefirst.py","score":9.65,"nloc":21},{"file_path":"tests/migrations/test_migrations_manual_porting/0004_fourth.py","score":9.65,"nloc":21},{"file_path":"tests/migrations/test_migrations_no_ancestor/0001_initial.py","score":9.65,"nloc":21},{"file_path":"tests/migrations/test_migrations_no_changes/0001_initial.py","score":9.24,"nloc":21},{"file_path":"tests/migrations/test_migrations_squashed/0001_initial.py","score":9.24,"nloc":21},{"file_path":"tests/migrations/test_migrations_squashed_no_replaces/0001_squashed_0002.py","score":9.65,"nloc":21},{"file_path":"tests/reserved_names/models.py","score":9.59,"nloc":21},{"file_path":"tests/urlpatterns_reverse/utils.py","score":9.24,"nloc":21},{"file_path":"tests/user_commands/management/commands/dance.py","score":9.59,"nloc":21},{"file_path":"django/conf/locale/de/formats.py","score":9.24,"nloc":20},{"file_path":"django/conf/locale/de_CH/formats.py","score":9.24,"nloc":20},{"file_path":"django/conf/locale/fr/formats.py","score":9.59,"nloc":20},{"file_path":"django/contrib/auth/validators.py","score":10.0,"nloc":20},{"file_path":"django/contrib/flatpages/admin.py","score":9.59,"nloc":20},{"file_path":"django/contrib/gis/db/backends/base/adapter.py","score":9.24,"nloc":20},{"file_path":"django/contrib/redirects/migrations/0002_alter_redirect_new_path_help_text.py","score":10.0,"nloc":20},{"file_path":"django/db/backends/oracle/functions.py","score":10.0,"nloc":20},{"file_path":"django/db/backends/oracle/validation.py","score":10.0,"nloc":20},{"file_path":"django/template/loaders/locmem.py","score":9.59,"nloc":20},{"file_path":"django/utils/hashable.py","score":9.19,"nloc":20},{"file_path":"js_tests/admin/URLify.test.js","score":9.44,"nloc":20},{"file_path":"tests/contenttypes_tests/test_migrations.py","score":10.0,"nloc":20},{"file_path":"tests/forms_tests/tests/test_widgets.py","score":9.0,"nloc":20},{"file_path":"tests/forms_tests/views.py","score":10.0,"nloc":20},{"file_path":"tests/invalid_models_tests/test_backend_specific.py","score":9.59,"nloc":20},{"file_path":"tests/messages_tests/test_mixins.py","score":9.59,"nloc":20},{"file_path":"tests/migrations/deprecated_field_migrations/0001_initial.py","score":10.0,"nloc":20},{"file_path":"tests/migrations/migrations_test_apps/alter_fk/book_app/migrations/0001_initial.py","score":9.59,"nloc":20},{"file_path":"tests/migrations/test_auto_now_add/0001_initial.py","score":9.65,"nloc":20},{"file_path":"tests/migrations/test_migrations/0002_second.py","score":9.65,"nloc":20},{"file_path":"tests/migrations/test_migrations_no_ancestor/0002_second.py","score":9.24,"nloc":20},{"file_path":"tests/migrations/test_migrations_no_changes/0002_second.py","score":9.24,"nloc":20},{"file_path":"tests/migrations/test_migrations_plan/0001_initial.py","score":10.0,"nloc":20},{"file_path":"tests/migrations/test_migrations_squashed_double/0003_squashed_0001_and_0002.py","score":9.65,"nloc":20},{"file_path":"tests/migrations/test_migrations_squashed_partially_applied/0002_mymodel1_field_1_mymodel2_field_2_and_more.py","score":10.0,"nloc":20},{"file_path":"tests/string_lookup/models.py","score":8.3,"nloc":20},{"file_path":"tests/urlpatterns_reverse/named_urls_conflict.py","score":10.0,"nloc":20},{"file_path":"django/__init__.py","score":9.0,"nloc":19},{"file_path":"django/conf/locale/da/formats.py","score":9.59,"nloc":19},{"file_path":"django/contrib/admin/apps.py","score":9.59,"nloc":19},{"file_path":"django/contrib/messages/constants.py","score":10.0,"nloc":19},{"file_path":"django/contrib/messages/middleware.py","score":9.59,"nloc":19},{"file_path":"js_tests/admin/navigation.test.js","score":10.0,"nloc":19},{"file_path":"tests/admin_docs/urls.py","score":9.59,"nloc":19},{"file_path":"tests/admin_docs/views.py","score":9.59,"nloc":19},{"file_path":"tests/admin_scripts/management/commands/suppress_base_options_command.py","score":10.0,"nloc":19},{"file_path":"tests/auth_tests/models/with_foreign_key.py","score":10.0,"nloc":19},{"file_path":"tests/auth_tests/settings.py","score":9.59,"nloc":19},{"file_path":"tests/backends/mysql/test_schema.py","score":10.0,"nloc":19},{"file_path":"tests/backends/sqlite/test_functions.py","score":10.0,"nloc":19},{"file_path":"tests/file_uploads/urls.py","score":9.59,"nloc":19},{"file_path":"tests/forms_tests/widget_tests/test_input.py","score":10.0,"nloc":19},{"file_path":"tests/generic_inline_admin/admin.py","score":9.59,"nloc":19},{"file_path":"tests/handlers/urls.py","score":9.59,"nloc":19},{"file_path":"tests/known_related_objects/models.py","score":9.59,"nloc":19},{"file_path":"tests/m2m_signals/models.py","score":9.24,"nloc":19},{"file_path":"tests/migrations/migrations_test_apps/lookuperror_a/migrations/0001_initial.py","score":9.59,"nloc":19},{"file_path":"tests/migrations/migrations_test_apps/lookuperror_b/migrations/0001_initial.py","score":9.59,"nloc":19},{"file_path":"tests/migrations/migrations_test_apps/lookuperror_c/migrations/0001_initial.py","score":9.59,"nloc":19},{"file_path":"tests/migrations/test_migrations_fake_split_initial/0002_second.py","score":9.24,"nloc":19},{"file_path":"tests/migrations/test_migrations_squashed_double/0001_initial.py","score":9.65,"nloc":19},{"file_path":"tests/migrations/test_migrations_squashed_partially_applied/0004_remove_mymodel1_field_1_mymodel1_field_3_and_more.py","score":10.0,"nloc":19},{"file_path":"tests/template_tests/filter_tests/test_json_script.py","score":10.0,"nloc":19},{"file_path":"tests/template_tests/filter_tests/test_title.py","score":9.59,"nloc":19},{"file_path":"tests/test_runner_apps/sample/tests_sample.py","score":9.59,"nloc":19},{"file_path":"tests/urlpatterns_reverse/nested_urls.py","score":10.0,"nloc":19},{"file_path":"tests/view_tests/tests/test_specials.py","score":9.59,"nloc":19},{"file_path":"django/contrib/contenttypes/apps.py","score":9.59,"nloc":18},{"file_path":"django/contrib/gis/db/backends/mysql/introspection.py","score":9.59,"nloc":18},{"file_path":"django/contrib/gis/geos/__init__.py","score":10.0,"nloc":18},{"file_path":"django/contrib/gis/geos/prototypes/prepared.py","score":9.59,"nloc":18},{"file_path":"django/contrib/gis/views.py","score":9.59,"nloc":18},{"file_path":"django/contrib/sites/migrations/0002_alter_domain_unique.py","score":9.59,"nloc":18},{"file_path":"tests/auth_tests/models/with_custom_email_field.py","score":10.0,"nloc":18},{"file_path":"tests/datatypes/models.py","score":9.59,"nloc":18},{"file_path":"tests/field_subclassing/fields.py","score":9.0,"nloc":18},{"file_path":"tests/gis_tests/inspectapp/models.py","score":9.59,"nloc":18},{"file_path":"tests/i18n/forms.py","score":10.0,"nloc":18},{"file_path":"tests/migrations/migrations_test_apps/with_generic_model/models.py","score":10.0,"nloc":18},{"file_path":"tests/migrations/test_migrations_conflict/0002_second.py","score":9.24,"nloc":18},{"file_path":"tests/migrations/test_migrations_manual_porting/0003_third.py","score":9.65,"nloc":18},{"file_path":"tests/migrations/test_migrations_no_ancestor/0002_conflicting_second.py","score":9.24,"nloc":18},{"file_path":"tests/migrations/test_migrations_squashed/0002_second.py","score":9.24,"nloc":18},{"file_path":"tests/syndication_tests/models.py","score":9.59,"nloc":18},{"file_path":"tests/template_tests/filter_tests/test_safeseq.py","score":9.59,"nloc":18},{"file_path":"tests/test_runner_apps/tagged/tests_inheritance.py","score":10.0,"nloc":18},{"file_path":"tests/user_commands/utils.py","score":10.0,"nloc":18},{"file_path":"django/conf/project_template/manage.py-tpl","score":9.59,"nloc":17},{"file_path":"django/contrib/admin/migrations/0002_logentry_remove_auto_add.py","score":10.0,"nloc":17},{"file_path":"django/contrib/admin/views/decorators.py","score":9.0,"nloc":17},{"file_path":"django/contrib/gis/db/backends/mysql/features.py","score":9.59,"nloc":17},{"file_path":"django/contrib/sessions/management/commands/clearsessions.py","score":9.59,"nloc":17},{"file_path":"django/core/checks/compatibility/django_4_0.py","score":10.0,"nloc":17},{"file_path":"django/utils/json.py","score":10.0,"nloc":17},{"file_path":"tests/admin_registration/models.py","score":9.59,"nloc":17},{"file_path":"tests/custom_migration_operations/more_operations.py","score":9.05,"nloc":17},{"file_path":"tests/datetimes/models.py","score":9.59,"nloc":17},{"file_path":"tests/empty_models/test_commands.py","score":10.0,"nloc":17},{"file_path":"tests/generic_views/forms.py","score":9.59,"nloc":17},{"file_path":"tests/gis_tests/rasterapp/models.py","score":10.0,"nloc":17},{"file_path":"tests/m2m_and_m2o/models.py","score":9.0,"nloc":17},{"file_path":"tests/migrations/migrations_test_apps/alter_fk/author_app/migrations/0001_initial.py","score":10.0,"nloc":17},{"file_path":"tests/migrations/migrations_test_apps/conflicting_app_with_dependencies/migrations/0002_second.py","score":9.65,"nloc":17},{"file_path":"tests/migrations/migrations_test_apps/mutate_state_b/migrations/0002_add_field.py","score":10.0,"nloc":17},{"file_path":"tests/migrations/test_migrations_run_before/0002_second.py","score":9.24,"nloc":17},{"file_path":"tests/migrations2/test_migrations_2_first/0001_initial.py","score":9.65,"nloc":17},{"file_path":"tests/model_fields/test_slugfield.py","score":10.0,"nloc":17},{"file_path":"tests/sitemaps_tests/urls/https.py","score":9.59,"nloc":17},{"file_path":"tests/sites_framework/models.py","score":9.59,"nloc":17},{"file_path":"tests/sphinx/testdata/package/module.py","score":10.0,"nloc":17},{"file_path":"tests/template_tests/filter_tests/test_urlencode.py","score":10.0,"nloc":17},{"file_path":"tests/template_tests/syntax_tests/i18n/base.py","score":9.59,"nloc":17},{"file_path":"tests/template_tests/syntax_tests/test_simple_tag.py","score":10.0,"nloc":17},{"file_path":"tests/test_runner/models.py","score":9.59,"nloc":17},{"file_path":"tests/timezones/forms.py","score":10.0,"nloc":17},{"file_path":"tests/timezones/models.py","score":10.0,"nloc":17},{"file_path":"tests/user_commands/management/commands/required_constant_option.py","score":10.0,"nloc":17},{"file_path":"tests/view_tests/tests/test_json.py","score":9.59,"nloc":17},{"file_path":"django/contrib/flatpages/middleware.py","score":8.7,"nloc":16},{"file_path":"django/contrib/gis/admin/options.py","score":9.0,"nloc":16},{"file_path":"django/http/cookie.py","score":9.0,"nloc":16},{"file_path":"scripts/backport.sh","score":10.0,"nloc":16},{"file_path":"tests/admin_docs/tests.py","score":9.0,"nloc":16},{"file_path":"tests/admin_scripts/urls.py","score":10.0,"nloc":16},{"file_path":"tests/auth_tests/models/no_natural_key.py","score":10.0,"nloc":16},{"file_path":"tests/auth_tests/models/with_integer_username.py","score":10.0,"nloc":16},{"file_path":"tests/auth_tests/models/with_unique_constraint.py","score":10.0,"nloc":16},{"file_path":"tests/backends/base/test_schema.py","score":10.0,"nloc":16},{"file_path":"tests/migrations/test_deprecated_fields.py","score":10.0,"nloc":16},{"file_path":"tests/migrations/test_migrations_atomic_operation/0001_initial.py","score":10.0,"nloc":16},{"file_path":"tests/migrations/test_migrations_plan/0002_second.py","score":10.0,"nloc":16},{"file_path":"tests/migrations/test_migrations_plan/0003_third.py","score":10.0,"nloc":16},{"file_path":"tests/model_fields/test_filepathfield.py","score":10.0,"nloc":16},{"file_path":"tests/nested_foreign_keys/models.py","score":10.0,"nloc":16},{"file_path":"tests/postgres_tests/array_default_migrations/0002_integerarraymodel_field_2.py","score":9.59,"nloc":16},{"file_path":"tests/properties/tests.py","score":9.59,"nloc":16},{"file_path":"tests/reverse_lookup/models.py","score":9.24,"nloc":16},{"file_path":"tests/transactions/models.py","score":9.0,"nloc":16},{"file_path":"tests/user_commands/management/commands/mutually_exclusive_required.py","score":10.0,"nloc":16},{"file_path":"django/contrib/admin/migrations/0003_logentry_add_action_flag_choices.py","score":10.0,"nloc":15},{"file_path":"django/contrib/gis/utils/__init__.py","score":9.0,"nloc":15},{"file_path":"django/contrib/sites/requests.py","score":9.59,"nloc":15},{"file_path":"django/core/checks/files.py","score":10.0,"nloc":15},{"file_path":"django/db/models/sql/constants.py","score":9.0,"nloc":15},{"file_path":"django/views/decorators/common.py","score":9.24,"nloc":15},{"file_path":"js_tests/admin/actions.test.js","score":9.65,"nloc":15},{"file_path":"tests/auth_tests/models/invalid_models.py","score":10.0,"nloc":15},{"file_path":"tests/auth_tests/models/no_password.py","score":10.0,"nloc":15},{"file_path":"tests/auth_tests/urls_custom_user_admin.py","score":9.59,"nloc":15},{"file_path":"tests/forms_tests/templatetags/tags.py","score":9.85,"nloc":15},{"file_path":"tests/from_db_value/models.py","score":9.59,"nloc":15},{"file_path":"tests/gis_tests/data/rasters/textrasters.py","score":10.0,"nloc":15},{"file_path":"tests/migrations/test_migrations_plan/0005_fifth.py","score":10.0,"nloc":15},{"file_path":"tests/migrations2/test_migrations_2/0001_initial.py","score":9.24,"nloc":15},{"file_path":"tests/migrations2/test_migrations_2_no_deps/0001_initial.py","score":9.65,"nloc":15},{"file_path":"tests/model_options/apps.py","score":10.0,"nloc":15},{"file_path":"tests/or_lookups/models.py","score":9.0,"nloc":15},{"file_path":"tests/schema/test_logging.py","score":10.0,"nloc":15},{"file_path":"tests/template_tests/filter_tests/timezone_utils.py","score":10.0,"nloc":15},{"file_path":"tests/template_tests/syntax_tests/test_builtins.py","score":10.0,"nloc":15},{"file_path":"tests/template_tests/syntax_tests/test_multiline.py","score":9.59,"nloc":15},{"file_path":"tests/test_client_regress/auth_backends.py","score":10.0,"nloc":15},{"file_path":"tests/test_runner_apps/failures/tests_failures.py","score":10.0,"nloc":15},{"file_path":"tests/test_utils/test_serializemixin.py","score":10.0,"nloc":15},{"file_path":"django/contrib/auth/migrations/0003_alter_user_email_max_length.py","score":10.0,"nloc":14},{"file_path":"django/contrib/auth/migrations/0005_alter_user_last_login_null.py","score":10.0,"nloc":14},{"file_path":"django/contrib/auth/migrations/0009_alter_user_last_name_max_length.py","score":10.0,"nloc":14},{"file_path":"django/contrib/auth/migrations/0012_alter_user_first_name_max_length.py","score":10.0,"nloc":14},{"file_path":"django/contrib/gis/geometry.py","score":9.59,"nloc":14},{"file_path":"django/contrib/messages/apps.py","score":9.59,"nloc":14},{"file_path":"django/contrib/messages/views.py","score":9.59,"nloc":14},{"file_path":"django/core/files/storage/mixins.py","score":10.0,"nloc":14},{"file_path":"django/core/management/commands/startproject.py","score":9.0,"nloc":14},{"file_path":"django/db/models/fields/proxy.py","score":9.59,"nloc":14},{"file_path":"django/utils/copy.py","score":10.0,"nloc":14},{"file_path":"tests/admin_docs/namespace_urls.py","score":10.0,"nloc":14},{"file_path":"tests/admin_scripts/app_with_urls/urls_cbv.py","score":10.0,"nloc":14},{"file_path":"tests/admin_scripts/app_with_urls/urls_namespaced.py","score":10.0,"nloc":14},{"file_path":"tests/admin_scripts/app_with_urls/urls_nons.py","score":10.0,"nloc":14},{"file_path":"tests/admin_scripts/management/commands/base_command.py","score":10.0,"nloc":14},{"file_path":"tests/auth_tests/urls_admin.py","score":10.0,"nloc":14},{"file_path":"tests/check_framework/urls/non_unique_namespaces.py","score":10.0,"nloc":14},{"file_path":"tests/dates/models.py","score":9.59,"nloc":14},{"file_path":"tests/dbshell/tests.py","score":10.0,"nloc":14},{"file_path":"tests/invalid_models_tests/test_custom_fields.py","score":10.0,"nloc":14},{"file_path":"tests/migrations/migrations_test_apps/migrated_unapplied_app/migrations/0001_initial.py","score":9.65,"nloc":14},{"file_path":"tests/migrations/migrations_test_apps/unspecified_app_with_conflict/migrations/0002_second.py","score":9.65,"nloc":14},{"file_path":"tests/migrations/test_migrations_unmigdep/0001_initial.py","score":9.59,"nloc":14},{"file_path":"tests/properties/models.py","score":9.59,"nloc":14},{"file_path":"tests/resolve_url/views.py","score":10.0,"nloc":14},{"file_path":"tests/str/models.py","score":9.59,"nloc":14},{"file_path":"tests/template_tests/templatetags/testtags.py","score":10.0,"nloc":14},{"file_path":"tests/template_tests/views.py","score":9.59,"nloc":14},{"file_path":"django/contrib/admin/exceptions.py","score":10.0,"nloc":13},{"file_path":"django/contrib/gis/management/commands/inspectdb.py","score":9.59,"nloc":13},{"file_path":"django/contrib/sites/apps.py","score":9.59,"nloc":13},{"file_path":"django/contrib/staticfiles/urls.py","score":10.0,"nloc":13},{"file_path":"django/core/mail/utils.py","score":9.59,"nloc":13},{"file_path":"tests/admin_scripts/configured_dynamic_settings_manage.py","score":10.0,"nloc":13},{"file_path":"tests/admin_scripts/views.py","score":10.0,"nloc":13},{"file_path":"tests/check_framework/urls/cbv_as_view.py","score":10.0,"nloc":13},{"file_path":"tests/custom_lookups/models.py","score":9.59,"nloc":13},{"file_path":"tests/flatpages_tests/urls.py","score":9.59,"nloc":13},{"file_path":"tests/logging_tests/urls.py","score":9.59,"nloc":13},{"file_path":"tests/messages_tests/test_middleware.py","score":9.59,"nloc":13},{"file_path":"tests/middleware_exceptions/urls.py","score":9.59,"nloc":13},{"file_path":"tests/migrations/migrations_test_apps/alter_fk/author_app/migrations/0002_alter_id.py","score":10.0,"nloc":13},{"file_path":"tests/migrations/migrations_test_apps/conflicting_app_with_dependencies/migrations/0002_conflicting_second.py","score":10.0,"nloc":13},{"file_path":"tests/migrations/test_add_many_to_many_field_initial/0002_initial.py","score":10.0,"nloc":13},{"file_path":"tests/migrations2/test_migrations_2_first/0002_second.py","score":10.0,"nloc":13},{"file_path":"tests/mutually_referential/models.py","score":9.59,"nloc":13},{"file_path":"tests/null_queries/models.py","score":9.59,"nloc":13},{"file_path":"tests/servers/urls.py","score":9.59,"nloc":13},{"file_path":"tests/template_tests/syntax_tests/i18n/test_get_current_language.py","score":10.0,"nloc":13},{"file_path":"tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py","score":10.0,"nloc":13},{"file_path":"tests/test_runner_apps/databases/tests.py","score":10.0,"nloc":13},{"file_path":"tests/test_sqlite.py","score":9.59,"nloc":13},{"file_path":"tests/wsgi/urls.py","score":9.59,"nloc":13},{"file_path":"Gruntfile.js","score":10.0,"nloc":12},{"file_path":"django/contrib/auth/migrations/0002_alter_permission_name_max_length.py","score":10.0,"nloc":12},{"file_path":"django/contrib/auth/migrations/0010_alter_group_name_max_length.py","score":10.0,"nloc":12},{"file_path":"django/contrib/flatpages/sitemaps.py","score":10.0,"nloc":12},{"file_path":"django/contrib/gis/forms/__init__.py","score":9.59,"nloc":12},{"file_path":"django/contrib/postgres/aggregates/mixins.py","score":9.24,"nloc":12},{"file_path":"django/contrib/sites/shortcuts.py","score":9.59,"nloc":12},{"file_path":"django/core/checks/async_checks.py","score":10.0,"nloc":12},{"file_path":"tests/admin_autodiscover/tests.py","score":9.59,"nloc":12},{"file_path":"tests/app_loading/not_installed/models.py","score":10.0,"nloc":12},{"file_path":"tests/auth_tests/models/proxy.py","score":10.0,"nloc":12},{"file_path":"tests/check_framework/urls/no_warnings.py","score":10.0,"nloc":12},{"file_path":"tests/conditional_processing/urls.py","score":9.59,"nloc":12},{"file_path":"tests/context_processors/views.py","score":9.59,"nloc":12},{"file_path":"tests/empty/tests.py","score":9.59,"nloc":12},{"file_path":"tests/forms_tests/tests/__init__.py","score":9.0,"nloc":12},{"file_path":"tests/gis_tests/gdal_tests/tests.py","score":10.0,"nloc":12},{"file_path":"tests/i18n/models.py","score":9.59,"nloc":12},{"file_path":"tests/migrations/routers.py","score":9.59,"nloc":12},{"file_path":"tests/migrations/test_migrations_manual_porting/0001_initial.py","score":10.0,"nloc":12},{"file_path":"tests/migrations/test_migrations_namespace_package/0001_initial.py","score":9.65,"nloc":12},{"file_path":"tests/migrations/test_migrations_run_before/0001_initial.py","score":10.0,"nloc":12},{"file_path":"tests/serializers/models/multi_table.py","score":9.24,"nloc":12},{"file_path":"tests/test_utils/models.py","score":9.59,"nloc":12},{"file_path":"tests/test_utils/views.py","score":9.59,"nloc":12},{"file_path":"tests/urlpatterns_reverse/included_urls2.py","score":9.59,"nloc":12},{"file_path":"tests/urlpatterns_reverse/method_view_urls.py","score":9.59,"nloc":12},{"file_path":"tests/urlpatterns_reverse/urlconf_inner.py","score":9.59,"nloc":12},{"file_path":"tests/user_commands/management/commands/common_args.py","score":9.85,"nloc":12},{"file_path":"tests/utils_tests/test_simplelazyobject.py","score":9.0,"nloc":12},{"file_path":"tests/utils_tests/utils.py","score":10.0,"nloc":12},{"file_path":"django/conf/locale/eu/formats.py","score":9.24,"nloc":11},{"file_path":"django/contrib/gis/apps.py","score":9.59,"nloc":11},{"file_path":"django/contrib/gis/db/backends/postgis/features.py","score":10.0,"nloc":11},{"file_path":"django/contrib/messages/context_processors.py","score":10.0,"nloc":11},{"file_path":"django/contrib/postgres/fields/jsonb.py","score":9.0,"nloc":11},{"file_path":"django/contrib/staticfiles/apps.py","score":9.59,"nloc":11},{"file_path":"django/core/checks/database.py","score":10.0,"nloc":11},{"file_path":"django/core/mail/exceptions.py","score":10.0,"nloc":11},{"file_path":"django/core/management/commands/startapp.py","score":9.59,"nloc":11},{"file_path":"django/tasks/exceptions.py","score":10.0,"nloc":11},{"file_path":"django/template/backends/utils.py","score":9.59,"nloc":11},{"file_path":"tests/admin_scripts/app_with_urls/views.py","score":10.0,"nloc":11},{"file_path":"tests/auth_tests/operations_migrations/0001_initial.py","score":10.0,"nloc":11},{"file_path":"tests/auth_tests/operations_migrations/0002_rename_oldmodel_to_newmodel.py","score":10.0,"nloc":11},{"file_path":"tests/backends/postgresql/test_features.py","score":10.0,"nloc":11},{"file_path":"tests/builtin_server/views.py","score":10.0,"nloc":11},{"file_path":"tests/check_framework/test_async_checks.py","score":10.0,"nloc":11},{"file_path":"tests/check_framework/urls/bad_class_based_error_handlers.py","score":10.0,"nloc":11},{"file_path":"tests/check_framework/urls/warning_in_include.py","score":10.0,"nloc":11},{"file_path":"tests/csrf_tests/test_context_processor.py","score":9.59,"nloc":11},{"file_path":"tests/forms_tests/widget_tests/test_colorinput.py","score":10.0,"nloc":11},{"file_path":"tests/i18n/urls_default_unprefixed.py","score":10.0,"nloc":11},{"file_path":"tests/max_lengths/models.py","score":10.0,"nloc":11},{"file_path":"tests/migrations/deprecated_field_migrations/0002_remove_ipaddressfield_ip.py","score":10.0,"nloc":11},{"file_path":"tests/migrations/migrations_test_apps/unspecified_app_with_conflict/migrations/0002_conflicting_second.py","score":10.0,"nloc":11},{"file_path":"tests/migrations/test_migrations_conflict/0002_conflicting_second.py","score":9.24,"nloc":11},{"file_path":"tests/migrations/test_migrations_conflict_long_name/0001_initial.py","score":10.0,"nloc":11},{"file_path":"tests/migrations/test_migrations_conflict_long_name/0002_conflicting_second_migration_with_long_name.py","score":10.0,"nloc":11},{"file_path":"tests/migrations/test_migrations_conflict_long_name/0002_second.py","score":9.65,"nloc":11},{"file_path":"tests/migrations/test_migrations_squashed_replaced_order/app1/0002_squashed_initial.py","score":10.0,"nloc":11},{"file_path":"tests/mutually_referential/tests.py","score":9.59,"nloc":11},{"file_path":"tests/proxy_model_inheritance/models.py","score":9.59,"nloc":11},{"file_path":"tests/sitemaps_tests/models.py","score":10.0,"nloc":11},{"file_path":"tests/staticfiles_tests/test_utils.py","score":10.0,"nloc":11},{"file_path":"tests/template_tests/filter_tests/test_get_digit.py","score":10.0,"nloc":11},{"file_path":"tests/template_tests/filter_tests/test_safe.py","score":10.0,"nloc":11},{"file_path":"tests/template_tests/syntax_tests/i18n/test_language.py","score":10.0,"nloc":11},{"file_path":"tests/test_client/test_fakepayload.py","score":10.0,"nloc":11},{"file_path":"tests/test_runner_apps/buffer/tests_buffer.py","score":10.0,"nloc":11},{"file_path":"tests/urlpatterns_reverse/extra_urls.py","score":9.59,"nloc":11},{"file_path":"tests/user_commands/models.py","score":9.59,"nloc":11},{"file_path":"tests/utils_tests/test_connection.py","score":10.0,"nloc":11},{"file_path":"tests/validation/__init__.py","score":9.59,"nloc":11},{"file_path":"django/conf/locale/ckb/formats.py","score":10.0,"nloc":10},{"file_path":"django/conf/locale/fa/formats.py","score":9.59,"nloc":10},{"file_path":"django/conf/locale/gl/formats.py","score":9.59,"nloc":10},{"file_path":"django/conf/locale/ja/formats.py","score":9.59,"nloc":10},{"file_path":"django/conf/locale/ug/formats.py","score":10.0,"nloc":10},{"file_path":"django/contrib/gis/db/backends/mysql/base.py","score":9.59,"nloc":10},{"file_path":"django/contrib/gis/db/backends/oracle/base.py","score":10.0,"nloc":10},{"file_path":"django/contrib/messages/utils.py","score":10.0,"nloc":10},{"file_path":"django/contrib/postgres/expressions.py","score":10.0,"nloc":10},{"file_path":"django/contrib/sessions/exceptions.py","score":10.0,"nloc":10},{"file_path":"django/contrib/staticfiles/testing.py","score":10.0,"nloc":10},{"file_path":"django/core/asgi.py","score":10.0,"nloc":10},{"file_path":"django/core/wsgi.py","score":9.59,"nloc":10},{"file_path":"django/forms/__init__.py","score":9.0,"nloc":10},{"file_path":"tests/admin_scripts/app_raising_messages/models.py","score":10.0,"nloc":10},{"file_path":"tests/check_framework/models.py","score":9.59,"nloc":10},{"file_path":"tests/check_framework/urls/good_error_handler_deferred_annotations.py","score":10.0,"nloc":10},{"file_path":"tests/composite_pk/models/__init__.py","score":10.0,"nloc":10},{"file_path":"tests/contenttypes_tests/operations_migrations/0001_initial.py","score":10.0,"nloc":10},{"file_path":"tests/db_functions/math/test_pi.py","score":10.0,"nloc":10},{"file_path":"tests/db_functions/math/test_random.py","score":10.0,"nloc":10},{"file_path":"tests/flatpages_tests/settings.py","score":10.0,"nloc":10},{"file_path":"tests/gis_tests/gis_migrations/migrations/0001_setup_extensions.py","score":10.0,"nloc":10},{"file_path":"tests/gis_tests/rasterapp/migrations/0001_setup_extensions.py","score":10.0,"nloc":10},{"file_path":"tests/i18n/patterns/urls/namespace.py","score":9.59,"nloc":10},{"file_path":"tests/logging_tests/logconfig.py","score":9.44,"nloc":10},{"file_path":"tests/migrate_signals/custom_migrations/0001_initial.py","score":10.0,"nloc":10},{"file_path":"tests/migrations/migrations_test_apps/lookuperror_a/models.py","score":10.0,"nloc":10},{"file_path":"tests/migrations/test_migrations_manual_porting/0002_second.py","score":10.0,"nloc":10},{"file_path":"tests/migrations/test_migrations_squashed_double/0002_auto.py","score":10.0,"nloc":10},{"file_path":"tests/migrations/test_migrations_squashed_double/0004_auto.py","score":10.0,"nloc":10},{"file_path":"tests/swappable_models/models.py","score":10.0,"nloc":10},{"file_path":"tests/template_tests/templatetags/tag_27584.py","score":10.0,"nloc":10},{"file_path":"tests/test_runner_apps/tagged/tests.py","score":10.0,"nloc":10},{"file_path":"tests/urlpatterns/more_urls.py","score":10.0,"nloc":10},{"file_path":"tests/user_commands/management/commands/mutually_exclusive_required_with_same_dest.py","score":10.0,"nloc":10},{"file_path":"tests/user_commands/management/commands/subparser_required.py","score":10.0,"nloc":10},{"file_path":"tests/validation/test_custom_messages.py","score":9.59,"nloc":10},{"file_path":"django/conf/locale/gd/formats.py","score":10.0,"nloc":9},{"file_path":"django/conf/locale/he/formats.py","score":9.59,"nloc":9},{"file_path":"django/conf/locale/vi/formats.py","score":9.59,"nloc":9},{"file_path":"django/contrib/messages/storage/__init__.py","score":10.0,"nloc":9},{"file_path":"django/core/cache/utils.py","score":9.24,"nloc":9},{"file_path":"django/core/checks/templates.py","score":9.59,"nloc":9},{"file_path":"django/template/loaders/app_directories.py","score":9.03,"nloc":9},{"file_path":"django/utils/warnings.py","score":10.0,"nloc":9},{"file_path":"tests/admin_scripts/management/commands/app_command.py","score":9.59,"nloc":9},{"file_path":"tests/admin_scripts/management/commands/label_command.py","score":10.0,"nloc":9},{"file_path":"tests/apps/models.py","score":10.0,"nloc":9},{"file_path":"tests/async/models.py","score":10.0,"nloc":9},{"file_path":"tests/auth_tests/models/is_active.py","score":10.0,"nloc":9},{"file_path":"tests/cache/models.py","score":9.59,"nloc":9},{"file_path":"tests/fixtures_model_package/models/__init__.py","score":9.59,"nloc":9},{"file_path":"tests/i18n/patterns/urls/wrong.py","score":9.59,"nloc":9},{"file_path":"tests/i18n/patterns/urls/wrong_namespace.py","score":9.59,"nloc":9},{"file_path":"tests/messages_tests/utils.py","score":10.0,"nloc":9},{"file_path":"tests/migrations/migrations_test_apps/migrated_unapplied_app/models.py","score":10.0,"nloc":9},{"file_path":"tests/migrations/test_exceptions.py","score":10.0,"nloc":9},{"file_path":"tests/migrations/test_migrations_squashed_complex/3_squashed_5.py","score":9.65,"nloc":9},{"file_path":"tests/migrations/test_migrations_squashed_erroneous/3_squashed_5.py","score":9.65,"nloc":9},{"file_path":"tests/migrations/test_migrations_squashed_partially_applied/0003_alter_mymodel2_unique_together.py","score":10.0,"nloc":9},{"file_path":"tests/shortcuts/urls.py","score":10.0,"nloc":9},{"file_path":"tests/template_tests/filter_tests/test_default_if_none.py","score":9.65,"nloc":9},{"file_path":"tests/timezones/admin.py","score":9.59,"nloc":9},{"file_path":"tests/user_commands/management/commands/subparser_vanilla.py","score":10.0,"nloc":9},{"file_path":"django/conf/locale/bs/formats.py","score":9.59,"nloc":8},{"file_path":"django/conf/locale/is/formats.py","score":9.59,"nloc":8},{"file_path":"django/conf/locale/km/formats.py","score":9.59,"nloc":8},{"file_path":"django/contrib/auth/migrations/0006_require_contenttypes_0002.py","score":10.0,"nloc":8},{"file_path":"django/contrib/sites/middleware.py","score":10.0,"nloc":8},{"file_path":"django/db/models/constants.py","score":9.59,"nloc":8},{"file_path":"tests/admin_inlines/urls.py","score":9.59,"nloc":8},{"file_path":"tests/admin_views/views.py","score":9.59,"nloc":8},{"file_path":"tests/auth_tests/models/uuid_pk.py","score":10.0,"nloc":8},{"file_path":"tests/db_functions/migrations/0001_setup_extensions.py","score":10.0,"nloc":8},{"file_path":"tests/empty/models.py","score":10.0,"nloc":8},{"file_path":"tests/forms_tests/widget_tests/test_searchinput.py","score":10.0,"nloc":8},{"file_path":"tests/forms_tests/widget_tests/test_telinput.py","score":10.0,"nloc":8},{"file_path":"tests/i18n/commands/__init__.py","score":9.59,"nloc":8},{"file_path":"tests/i18n/urls.py","score":10.0,"nloc":8},{"file_path":"tests/migrations/migrations_test_apps/unmigrated_app_syncdb/models.py","score":10.0,"nloc":8},{"file_path":"tests/migrations/test_migrations_squashed_complex_multi_apps/app1/2_squashed_3.py","score":9.24,"nloc":8},{"file_path":"tests/migrations/test_migrations_squashed_complex_multi_apps/app2/1_squashed_2.py","score":9.59,"nloc":8},{"file_path":"tests/migrations/test_migrations_squashed_replaced_order/app1/0001_squashed_initial.py","score":10.0,"nloc":8},{"file_path":"tests/migrations/test_migrations_squashed_replaced_order/app2/0001_squashed_initial.py","score":10.0,"nloc":8},{"file_path":"tests/model_utils/tests.py","score":10.0,"nloc":8},{"file_path":"tests/resolve_url/models.py","score":10.0,"nloc":8},{"file_path":"tests/resolve_url/urls.py","score":9.44,"nloc":8},{"file_path":"tests/template_tests/templatetags/bad_tag.py","score":9.59,"nloc":8},{"file_path":"tests/test_client/auth_backends.py","score":10.0,"nloc":8},{"file_path":"tests/test_client_regress/models.py","score":10.0,"nloc":8},{"file_path":"tests/test_utils/urls.py","score":9.59,"nloc":8},{"file_path":"tests/urlpatterns_reverse/included_named_urls.py","score":9.59,"nloc":8},{"file_path":"tests/urlpatterns_reverse/named_urls.py","score":9.59,"nloc":8},{"file_path":"tests/urlpatterns_reverse/reverse_lazy_urls.py","score":9.59,"nloc":8},{"file_path":"tests/user_commands/management/commands/reverse_url.py","score":10.0,"nloc":8},{"file_path":"tests/user_commands/management/commands/subparser.py","score":10.0,"nloc":8},{"file_path":"tests/user_commands/management/commands/subparser_dest.py","score":10.0,"nloc":8},{"file_path":"tests/utils_tests/test_module/another_bad_module.py","score":10.0,"nloc":8},{"file_path":"django/__main__.py","score":10.0,"nloc":7},{"file_path":"django/conf/locale/ar/formats.py","score":9.59,"nloc":7},{"file_path":"django/conf/locale/sq/formats.py","score":9.59,"nloc":7},{"file_path":"django/conf/urls/__init__.py","score":9.0,"nloc":7},{"file_path":"django/contrib/gis/db/backends/spatialite/adapter.py","score":9.59,"nloc":7},{"file_path":"django/contrib/messages/test.py","score":10.0,"nloc":7},{"file_path":"django/contrib/postgres/functions.py","score":9.59,"nloc":7},{"file_path":"django/contrib/redirects/admin.py","score":9.59,"nloc":7},{"file_path":"django/core/mail/backends/dummy.py","score":10.0,"nloc":7},{"file_path":"django/db/backends/sqlite3/client.py","score":9.59,"nloc":7},{"file_path":"django/dispatch/__init__.py","score":9.59,"nloc":7},{"file_path":"django/tasks/checks.py","score":10.0,"nloc":7},{"file_path":"tests/admin_scripts/management/commands/custom_startproject.py","score":9.59,"nloc":7},{"file_path":"tests/apps/two_default_configs_app/apps.py","score":10.0,"nloc":7},{"file_path":"tests/cache/closeable_cache.py","score":10.0,"nloc":7},{"file_path":"tests/check_framework/urls/bad_function_based_error_handlers.py","score":10.0,"nloc":7},{"file_path":"tests/check_framework/urls/good_function_based_error_handlers.py","score":10.0,"nloc":7},{"file_path":"tests/check_framework/urls/path_compatibility/unmatched_angle_brackets.py","score":10.0,"nloc":7},{"file_path":"tests/contenttypes_tests/test_order_with_respect_to.py","score":10.0,"nloc":7},{"file_path":"tests/context_processors/urls.py","score":9.59,"nloc":7},{"file_path":"tests/i18n/patterns/urls/disabled.py","score":10.0,"nloc":7},{"file_path":"tests/i18n/sampleproject/manage.py","score":10.0,"nloc":7},{"file_path":"tests/middleware/extra_urls.py","score":9.59,"nloc":7},{"file_path":"tests/migration_test_data_persistence/models.py","score":10.0,"nloc":7},{"file_path":"tests/migrations/migrations_test_apps/lookuperror_b/models.py","score":10.0,"nloc":7},{"file_path":"tests/migrations/migrations_test_apps/lookuperror_c/models.py","score":10.0,"nloc":7},{"file_path":"tests/migrations/migrations_test_apps/unmigrated_app_simple/models.py","score":10.0,"nloc":7},{"file_path":"tests/migrations/test_migrations_squashed_ref_squashed/app1/2_squashed_3.py","score":9.65,"nloc":7},{"file_path":"tests/migrations/test_migrations_squashed_ref_squashed/app2/1_squashed_2.py","score":10.0,"nloc":7},{"file_path":"tests/migrations/test_migrations_squashed_replaced_order/app2/0001_initial.py","score":10.0,"nloc":7},{"file_path":"tests/model_package/models/article.py","score":9.59,"nloc":7},{"file_path":"tests/no_models/tests.py","score":10.0,"nloc":7},{"file_path":"tests/template_tests/filter_tests/test_divisibleby.py","score":10.0,"nloc":7},{"file_path":"tests/test_client/urls_middleware_urlconf.py","score":10.0,"nloc":7},{"file_path":"tests/urlpatterns/lazy_path_urls.py","score":10.0,"nloc":7},{"file_path":"tests/urlpatterns_reverse/included_named_urls2.py","score":10.0,"nloc":7},{"file_path":"tests/urlpatterns_reverse/included_urls.py","score":9.59,"nloc":7},{"file_path":"tests/user_commands/management/commands/required_list_option.py","score":10.0,"nloc":7},{"file_path":"tests/user_commands/management/commands/required_option.py","score":10.0,"nloc":7},{"file_path":"tests/user_commands/management/commands/transaction.py","score":10.0,"nloc":7},{"file_path":"tests/utils_tests/test_module/another_good_module.py","score":10.0,"nloc":7},{"file_path":"django/conf/locale/bg/formats.py","score":9.59,"nloc":6},{"file_path":"django/conf/locale/et/formats.py","score":9.59,"nloc":6},{"file_path":"django/conf/locale/ga/formats.py","score":9.59,"nloc":6},{"file_path":"django/conf/locale/hi/formats.py","score":9.59,"nloc":6},{"file_path":"django/contrib/flatpages/apps.py","score":9.59,"nloc":6},{"file_path":"django/contrib/postgres/serializers.py","score":10.0,"nloc":6},{"file_path":"django/contrib/redirects/apps.py","score":9.59,"nloc":6},{"file_path":"django/contrib/sitemaps/apps.py","score":9.59,"nloc":6},{"file_path":"django/contrib/sites/admin.py","score":10.0,"nloc":6},{"file_path":"tests/admin_scripts/app_raising_warning/models.py","score":10.0,"nloc":6},{"file_path":"tests/admin_scripts/configured_settings_manage.py","score":10.0,"nloc":6},{"file_path":"tests/admin_scripts/management/commands/noargs_command.py","score":10.0,"nloc":6},{"file_path":"tests/admin_utils/urls.py","score":10.0,"nloc":6},{"file_path":"tests/apps/namespace_package_base/nsapp/apps.py","score":9.59,"nloc":6},{"file_path":"tests/apps/two_configs_one_default_app/apps.py","score":10.0,"nloc":6},{"file_path":"tests/bash_completion/management/commands/test_command.py","score":9.59,"nloc":6},{"file_path":"tests/cache/failing_cache.py","score":10.0,"nloc":6},{"file_path":"tests/cache/liberal_backend.py","score":9.59,"nloc":6},{"file_path":"tests/check_framework/urls/good_class_based_error_handlers.py","score":10.0,"nloc":6},{"file_path":"tests/check_framework/urls/no_warnings_i18n.py","score":10.0,"nloc":6},{"file_path":"tests/forms_tests/field_tests/__init__.py","score":10.0,"nloc":6},{"file_path":"tests/forms_tests/urls.py","score":10.0,"nloc":6},{"file_path":"tests/gis_tests/geoapp/sitemaps.py","score":9.59,"nloc":6},{"file_path":"tests/i18n/patterns/urls/included.py","score":10.0,"nloc":6},{"file_path":"tests/i18n/patterns/urls/path_unused.py","score":10.0,"nloc":6},{"file_path":"tests/logging_tests/urls_i18n.py","score":10.0,"nloc":6},{"file_path":"tests/migrations/test_migrations_noop/0001_initial.py","score":10.0,"nloc":6},{"file_path":"tests/migrations/test_migrations_plan/0004_fourth.py","score":10.0,"nloc":6},{"file_path":"tests/migrations/test_migrations_squashed_extra/0001_squashed_0002.py","score":10.0,"nloc":6},{"file_path":"tests/pagination/models.py","score":9.03,"nloc":6},{"file_path":"tests/sitecustomize.py","score":9.85,"nloc":6},{"file_path":"tests/template_tests/alternate_urls.py","score":9.59,"nloc":6},{"file_path":"tests/test_runner_apps/tagged/tests_syntax_error.py","score":10.0,"nloc":6},{"file_path":"tests/urlpatterns/converter_urls.py","score":10.0,"nloc":6},{"file_path":"tests/urlpatterns/included_urls.py","score":10.0,"nloc":6},{"file_path":"tests/urlpatterns/path_dynamic_urls.py","score":10.0,"nloc":6},{"file_path":"tests/urlpatterns_reverse/urlconf_outer.py","score":9.59,"nloc":6},{"file_path":"tests/urlpatterns_reverse/urls_error_handlers_callables.py","score":9.59,"nloc":6},{"file_path":"tests/urlpatterns_reverse/urls_without_handlers.py","score":10.0,"nloc":6},{"file_path":"tests/user_commands/management/commands/no_translations.py","score":10.0,"nloc":6},{"file_path":"tests/user_commands/management/commands/outputwrapper.py","score":10.0,"nloc":6},{"file_path":"tests/user_commands/management/commands/set_option.py","score":10.0,"nloc":6},{"file_path":"tests/user_commands/management/commands/specific_system_checks.py","score":10.0,"nloc":6},{"file_path":"django/contrib/admindocs/apps.py","score":9.59,"nloc":5},{"file_path":"django/contrib/flatpages/urls.py","score":9.59,"nloc":5},{"file_path":"django/contrib/gis/db/models/sql/__init__.py","score":9.59,"nloc":5},{"file_path":"django/contrib/humanize/apps.py","score":9.59,"nloc":5},{"file_path":"django/contrib/postgres/fields/__init__.py","score":10.0,"nloc":5},{"file_path":"django/contrib/sessions/apps.py","score":9.59,"nloc":5},{"file_path":"django/contrib/syndication/apps.py","score":9.59,"nloc":5},{"file_path":"django/core/signals.py","score":9.59,"nloc":5},{"file_path":"django/db/models/sql/__init__.py","score":9.59,"nloc":5},{"file_path":"django/urls/exceptions.py","score":10.0,"nloc":5},{"file_path":"tests/admin_changelist/urls.py","score":10.0,"nloc":5},{"file_path":"tests/admin_custom_urls/urls.py","score":10.0,"nloc":5},{"file_path":"tests/admin_scripts/another_app_waiting_migration/models.py","score":10.0,"nloc":5},{"file_path":"tests/admin_scripts/app_waiting_migration/models.py","score":10.0,"nloc":5},{"file_path":"tests/admin_scripts/complex_app/models/bar.py","score":9.59,"nloc":5},{"file_path":"tests/admin_scripts/complex_app/models/foo.py","score":10.0,"nloc":5},{"file_path":"tests/admin_widgets/urls.py","score":10.0,"nloc":5},{"file_path":"tests/apps/two_configs_app/apps.py","score":10.0,"nloc":5},{"file_path":"tests/backends/base/app_unmigrated/models.py","score":10.0,"nloc":5},{"file_path":"tests/backends/base/test_features.py","score":10.0,"nloc":5},{"file_path":"tests/base/models.py","score":9.59,"nloc":5},{"file_path":"tests/builtin_server/urls.py","score":10.0,"nloc":5},{"file_path":"tests/check_framework/custom_commands_app/management/commands/makemigrations.py","score":10.0,"nloc":5},{"file_path":"tests/check_framework/urls/bad_error_handlers_invalid_path.py","score":10.0,"nloc":5},{"file_path":"tests/check_framework/urls/beginning_with_slash.py","score":10.0,"nloc":5},{"file_path":"tests/contenttypes_tests/urls.py","score":9.59,"nloc":5},{"file_path":"tests/file_storage/urls.py","score":10.0,"nloc":5},{"file_path":"tests/flatpages_tests/absolute_urls.py","score":10.0,"nloc":5},{"file_path":"tests/generic_inline_admin/urls.py","score":9.59,"nloc":5},{"file_path":"tests/gis_tests/admin.py","score":10.0,"nloc":5},{"file_path":"tests/gis_tests/geoadmin/urls.py","score":10.0,"nloc":5},{"file_path":"tests/middleware/cond_get_urls.py","score":10.0,"nloc":5},{"file_path":"tests/migrations/migrations_test_apps/unmigrated_app/models.py","score":10.0,"nloc":5},{"file_path":"tests/migrations/test_migrations_squashed_loop/2_auto.py","score":10.0,"nloc":5},{"file_path":"tests/migrations/test_migrations_squashed_loop/2_squashed.py","score":10.0,"nloc":5},{"file_path":"tests/migrations/test_migrations_squashed_replaced_order/app1/0001_initial.py","score":10.0,"nloc":5},{"file_path":"tests/project_template/urls.py","score":10.0,"nloc":5},{"file_path":"tests/proxy_models/admin.py","score":10.0,"nloc":5},{"file_path":"tests/proxy_models/urls.py","score":10.0,"nloc":5},{"file_path":"tests/redirects_tests/urls.py","score":10.0,"nloc":5},{"file_path":"tests/shell/models.py","score":10.0,"nloc":5},{"file_path":"tests/staticfiles_tests/project/documents/cached/module_test.js","score":10.0,"nloc":5},{"file_path":"tests/staticfiles_tests/urls/default.py","score":9.59,"nloc":5},{"file_path":"tests/template_tests/annotated_tag_function.py","score":10.0,"nloc":5},{"file_path":"tests/template_tests/templatetags/subpackage/echo.py","score":10.0,"nloc":5},{"file_path":"tests/timezones/urls.py","score":9.59,"nloc":5},{"file_path":"tests/urlpatterns_reverse/erroneous_urls.py","score":10.0,"nloc":5},{"file_path":"tests/urlpatterns_reverse/included_no_kwargs_urls.py","score":10.0,"nloc":5},{"file_path":"tests/urlpatterns_reverse/urls_error_handlers.py","score":9.59,"nloc":5},{"file_path":"tests/urls.py","score":9.0,"nloc":5},{"file_path":"tests/user_commands/management/commands/no_system_checks.py","score":10.0,"nloc":5},{"file_path":"tests/utils_tests/models.py","score":9.59,"nloc":5},{"file_path":"tests/view_tests/default_urls.py","score":10.0,"nloc":5},{"file_path":"tests/view_tests/regression_21530_urls.py","score":10.0,"nloc":5},{"file_path":"tests/view_tests/templatetags/debugtags.py","score":9.59,"nloc":5},{"file_path":"tests/xor_lookups/models.py","score":10.0,"nloc":5},{"file_path":"django/conf/locale/kn/formats.py","score":9.59,"nloc":4},{"file_path":"django/conf/locale/ta/formats.py","score":9.59,"nloc":4},{"file_path":"django/conf/locale/te/formats.py","score":9.59,"nloc":4},{"file_path":"django/contrib/auth/signals.py","score":10.0,"nloc":4},{"file_path":"django/contrib/gis/gdal/base.py","score":9.59,"nloc":4},{"file_path":"django/contrib/gis/geos/base.py","score":9.59,"nloc":4},{"file_path":"django/db/backends/dummy/features.py","score":10.0,"nloc":4},{"file_path":"django/views/decorators/gzip.py","score":10.0,"nloc":4},{"file_path":"tests/admin_autodiscover/admin.py","score":10.0,"nloc":4},{"file_path":"tests/admin_default_site/apps.py","score":10.0,"nloc":4},{"file_path":"tests/admin_scripts/app_with_import/models.py","score":9.59,"nloc":4},{"file_path":"tests/admin_scripts/complex_app/management/commands/duplicate.py","score":10.0,"nloc":4},{"file_path":"tests/admin_scripts/simple_app/management/commands/duplicate.py","score":10.0,"nloc":4},{"file_path":"tests/auth_tests/models/minimal.py","score":10.0,"nloc":4},{"file_path":"tests/check_framework/urls/include_contains_tuple.py","score":10.0,"nloc":4},{"file_path":"tests/check_framework/urls/include_with_dollar.py","score":10.0,"nloc":4},{"file_path":"tests/check_framework/urls/name_with_colon.py","score":10.0,"nloc":4},{"file_path":"tests/check_framework/urls/path_compatibility/beginning_with_caret.py","score":10.0,"nloc":4},{"file_path":"tests/check_framework/urls/path_compatibility/contains_re_named_group.py","score":10.0,"nloc":4},{"file_path":"tests/check_framework/urls/path_compatibility/ending_with_dollar.py","score":10.0,"nloc":4},{"file_path":"tests/check_framework/urls/path_compatibility/matched_angle_brackets.py","score":10.0,"nloc":4},{"file_path":"tests/flatpages_tests/no_slash_urls.py","score":10.0,"nloc":4},{"file_path":"tests/migrations/test_migrations_backwards_deps_1/0002_second.py","score":10.0,"nloc":4},{"file_path":"tests/migrations/test_migrations_no_operations/0001_initial.py","score":10.0,"nloc":4},{"file_path":"tests/migrations/test_migrations_order/0001.py","score":10.0,"nloc":4},{"file_path":"tests/migrations/test_migrations_squashed_complex/2_auto.py","score":10.0,"nloc":4},{"file_path":"tests/migrations/test_migrations_squashed_complex/3_auto.py","score":10.0,"nloc":4},{"file_path":"tests/migrations/test_migrations_squashed_complex/4_auto.py","score":10.0,"nloc":4},{"file_path":"tests/migrations/test_migrations_squashed_complex/5_auto.py","score":10.0,"nloc":4},{"file_path":"tests/migrations/test_migrations_squashed_complex/6_auto.py","score":10.0,"nloc":4},{"file_path":"tests/migrations/test_migrations_squashed_complex/7_auto.py","score":10.0,"nloc":4},{"file_path":"tests/migrations/test_migrations_squashed_complex_multi_apps/app1/2_auto.py","score":9.59,"nloc":4},{"file_path":"tests/migrations/test_migrations_squashed_complex_multi_apps/app1/3_auto.py","score":9.59,"nloc":4},{"file_path":"tests/migrations/test_migrations_squashed_complex_multi_apps/app1/4_auto.py","score":9.59,"nloc":4},{"file_path":"tests/migrations/test_migrations_squashed_complex_multi_apps/app2/1_auto.py","score":9.59,"nloc":4},{"file_path":"tests/migrations/test_migrations_squashed_complex_multi_apps/app2/2_auto.py","score":9.59,"nloc":4},{"file_path":"tests/migrations/test_migrations_squashed_erroneous/2_auto.py","score":10.0,"nloc":4},{"file_path":"tests/migrations/test_migrations_squashed_erroneous/6_auto.py","score":10.0,"nloc":4},{"file_path":"tests/migrations/test_migrations_squashed_erroneous/7_auto.py","score":10.0,"nloc":4},{"file_path":"tests/model_fields/storage.py","score":10.0,"nloc":4},{"file_path":"tests/postgres_tests/integration_settings.py","score":10.0,"nloc":4},{"file_path":"tests/proxy_model_inheritance/app1/models.py","score":10.0,"nloc":4},{"file_path":"tests/serializers/models/__init__.py","score":10.0,"nloc":4},{"file_path":"tests/sessions_tests/no_clear_expired.py","score":10.0,"nloc":4},{"file_path":"tests/test_runner_apps/sample/pattern_tests.py","score":10.0,"nloc":4},{"file_path":"tests/test_runner_apps/sample/tests/tests.py","score":10.0,"nloc":4},{"file_path":"tests/user_commands/urls.py","score":10.0,"nloc":4},{"file_path":"django/apps/__init__.py","score":10.0,"nloc":3},{"file_path":"django/conf/locale/mn/formats.py","score":9.59,"nloc":3},{"file_path":"django/contrib/gis/db/backends/spatialite/client.py","score":10.0,"nloc":3},{"file_path":"django/contrib/gis/geos/error.py","score":10.0,"nloc":3},{"file_path":"django/contrib/messages/__init__.py","score":9.59,"nloc":3},{"file_path":"django/contrib/postgres/fields/utils.py","score":10.0,"nloc":3},{"file_path":"django/contrib/postgres/forms/__init__.py","score":10.0,"nloc":3},{"file_path":"tests/admin_autodiscover/models.py","score":10.0,"nloc":3},{"file_path":"tests/admin_default_site/sites.py","score":10.0,"nloc":3},{"file_path":"tests/admin_scripts/complex_app/admin/foo.py","score":10.0,"nloc":3},{"file_path":"tests/admin_scripts/complex_app/models/__init__.py","score":10.0,"nloc":3},{"file_path":"tests/apps/one_config_app/apps.py","score":10.0,"nloc":3},{"file_path":"tests/auth_tests/models/with_last_login_attr.py","score":10.0,"nloc":3},{"file_path":"tests/check_framework/template_test_apps/different_tags_app/apps.py","score":10.0,"nloc":3},{"file_path":"tests/check_framework/template_test_apps/same_tags_app_1/apps.py","score":10.0,"nloc":3},{"file_path":"tests/check_framework/template_test_apps/same_tags_app_2/apps.py","score":10.0,"nloc":3},{"file_path":"tests/check_framework/urls/contains_tuple.py","score":10.0,"nloc":3},{"file_path":"tests/context_processors/models.py","score":10.0,"nloc":3},{"file_path":"tests/file_uploads/models.py","score":9.59,"nloc":3},{"file_path":"tests/i18n/exclude/__init__.py","score":10.0,"nloc":3},{"file_path":"tests/i18n/loading_app/apps.py","score":10.0,"nloc":3},{"file_path":"tests/i18n/unchanged/__init__.py","score":10.0,"nloc":3},{"file_path":"tests/messages_tests/models.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_backwards_deps_1/0001_initial.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_clashing_prefix/a.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_clashing_prefix/ab.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_private/0001_initial.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_squashed_complex/1_auto.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_squashed_complex_multi_apps/app1/1_auto.py","score":9.59,"nloc":3},{"file_path":"tests/migrations/test_migrations_squashed_erroneous/1_auto.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_squashed_extra/0001_initial.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_squashed_extra/0002_second.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_squashed_extra/0003_third.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_squashed_loop/1_auto.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_squashed_ref_squashed/app1/1_auto.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_squashed_ref_squashed/app1/2_auto.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_squashed_ref_squashed/app1/3_auto.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_squashed_ref_squashed/app1/4_auto.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_squashed_ref_squashed/app2/1_auto.py","score":10.0,"nloc":3},{"file_path":"tests/migrations/test_migrations_squashed_ref_squashed/app2/2_auto.py","score":10.0,"nloc":3},{"file_path":"tests/model_package/models/__init__.py","score":9.59,"nloc":3},{"file_path":"tests/model_package/models/publication.py","score":10.0,"nloc":3},{"file_path":"tests/project_template/views.py","score":10.0,"nloc":3},{"file_path":"tests/proxy_model_inheritance/app2/models.py","score":10.0,"nloc":3},{"file_path":"tests/servers/models.py","score":10.0,"nloc":3},{"file_path":"tests/sphinx/testdata/package/import_error.py","score":10.0,"nloc":3},{"file_path":"tests/sphinx/testdata/package/wildcard_module.py","score":10.0,"nloc":3},{"file_path":"tests/staticfiles_tests/apps/staticfiles_config.py","score":10.0,"nloc":3},{"file_path":"tests/transaction_hooks/models.py","score":10.0,"nloc":3},{"file_path":"tests/urlpatterns/views.py","score":10.0,"nloc":3},{"file_path":"tests/urlpatterns_reverse/nonimported_module.py","score":10.0,"nloc":3},{"file_path":"tests/utils_tests/test_module/__init__.py","score":10.0,"nloc":3},{"file_path":"django/contrib/admin/static/admin/js/jquery.init.js","score":9.59,"nloc":2},{"file_path":"django/contrib/gis/sitemaps/__init__.py","score":10.0,"nloc":2},{"file_path":"django/contrib/postgres/aggregates/__init__.py","score":10.0,"nloc":2},{"file_path":"django/contrib/sessions/serializers.py","score":9.59,"nloc":2},{"file_path":"django/core/files/__init__.py","score":10.0,"nloc":2},{"file_path":"django/db/backends/signals.py","score":10.0,"nloc":2},{"file_path":"django/db/migrations/__init__.py","score":10.0,"nloc":2},{"file_path":"django/views/__init__.py","score":10.0,"nloc":2},{"file_path":"tests/admin_scripts/simple_app/models.py","score":9.59,"nloc":2},{"file_path":"tests/auth_tests/backend_alias.py","score":10.0,"nloc":2},{"file_path":"tests/check_framework/template_test_apps/different_tags_app/templatetags/different_tags.py","score":10.0,"nloc":2},{"file_path":"tests/check_framework/template_test_apps/same_tags_app_1/templatetags/same_tags.py","score":10.0,"nloc":2},{"file_path":"tests/check_framework/template_test_apps/same_tags_app_2/templatetags/same_tags.py","score":10.0,"nloc":2},{"file_path":"tests/csrf_tests/csrf_token_error_handler_urls.py","score":10.0,"nloc":2},{"file_path":"tests/dbshell/fake_client.py","score":10.0,"nloc":2},{"file_path":"tests/i18n/obsolete_translations/__init__.py","score":10.0,"nloc":2},{"file_path":"tests/i18n/project_dir/__init__.py","score":10.0,"nloc":2},{"file_path":"tests/i18n/project_dir/app_no_locale/models.py","score":10.0,"nloc":2},{"file_path":"tests/i18n/project_dir/app_with_locale/models.py","score":10.0,"nloc":2},{"file_path":"tests/sphinx/testdata/package/other_module.py","score":10.0,"nloc":2},{"file_path":"tests/sphinx/testdata/package/wildcard_base.py","score":10.0,"nloc":2},{"file_path":"tests/staticfiles_tests/project/documents/absolute_root.js","score":10.0,"nloc":2},{"file_path":"tests/staticfiles_tests/urls/helper.py","score":10.0,"nloc":2},{"file_path":"tests/template_backends/apps/good/templatetags/good_tags.py","score":10.0,"nloc":2},{"file_path":"tests/template_backends/apps/good/templatetags/override.py","score":10.0,"nloc":2},{"file_path":"tests/template_backends/apps/good/templatetags/subpackage/tags.py","score":10.0,"nloc":2},{"file_path":"tests/test_client_regress/context_processors.py","score":10.0,"nloc":2},{"file_path":"tests/utils_tests/test_module/bad_module.py","score":10.0,"nloc":2},{"file_path":"tests/admin_scripts/broken_app/models.py","score":10.0,"nloc":1},{"file_path":"tests/i18n/commands/someapp/static/javascript.js","score":10.0,"nloc":1},{"file_path":"tests/i18n/commands/static/javascript_ignored.js","score":10.0,"nloc":1},{"file_path":"tests/i18n/other/locale/fr/formats.py","score":10.0,"nloc":1},{"file_path":"tests/import_error_package/__init__.py","score":10.0,"nloc":1},{"file_path":"tests/sphinx/testdata/package/__init__.py","score":10.0,"nloc":1},{"file_path":"tests/staticfiles_tests/project/documents/cached/source_map.js","score":10.0,"nloc":1},{"file_path":"tests/staticfiles_tests/project/documents/cached/source_map_data_uri.js","score":10.0,"nloc":1},{"file_path":"tests/staticfiles_tests/project/documents/cached/source_map_trailing_whitespace.js","score":10.0,"nloc":1},{"file_path":"tests/staticfiles_tests/project/documents/cached/test.js","score":10.0,"nloc":1},{"file_path":"tests/staticfiles_tests/project/documents/nested/js/nested.js","score":10.0,"nloc":1},{"file_path":"tests/template_backends/apps/importerror/templatetags/broken_tags.py","score":10.0,"nloc":1},{"file_path":"tests/template_tests/broken_tag.py","score":10.0,"nloc":1},{"file_path":"tests/urlpatterns_reverse/views_broken.py","score":10.0,"nloc":1},{"file_path":"tests/utils_tests/deconstructible_classes.py","score":10.0,"nloc":1},{"file_path":"tests/utils_tests/test_module/child_module/grandchild_module.py","score":10.0,"nloc":1},{"file_path":"tests/utils_tests/test_module/good_module.py","score":10.0,"nloc":1},{"file_path":"tests/wsgi/wsgi.py","score":10.0,"nloc":1}]}\ No newline at end of filediff --git a/packages/claude-mod/test/fixtures/locks/garbage.json b/packages/claude-mod/test/fixtures/locks/garbage.jsonnew file mode 100644index 000000000..2c3953db1--- /dev/null+++ b/packages/claude-mod/test/fixtures/locks/garbage.json@@ -0,0 +1 @@+{"pid": "not a number", "port": 7411\ No newline at end of filediff --git a/packages/claude-mod/test/fixtures/locks/stale-pid.json b/packages/claude-mod/test/fixtures/locks/stale-pid.jsonnew file mode 100644index 000000000..8657deb25--- /dev/null+++ b/packages/claude-mod/test/fixtures/locks/stale-pid.json@@ -0,0 +1,9 @@+{+ "pid": 9999,+ "host": "127.0.0.1",+ "port": 7411,+ "url": "http://127.0.0.1:7411",+ "ui_port": null,+ "server_version": "0.54.0",+ "started_at": "2026-10-01T09:00:00Z"+}diff --git a/packages/claude-mod/test/fixtures/locks/valid.json b/packages/claude-mod/test/fixtures/locks/valid.jsonnew file mode 100644index 000000000..8dc2a6a5f--- /dev/null+++ b/packages/claude-mod/test/fixtures/locks/valid.json@@ -0,0 +1,9 @@+{+ "pid": 4242,+ "host": "127.0.0.1",+ "port": 7411,+ "url": "http://127.0.0.1:7411",+ "ui_port": null,+ "server_version": "0.54.0",+ "started_at": "2026-10-03T09:00:00Z"+}diff --git a/packages/claude-mod/test/fixtures/mcp/get_context-models.json b/packages/claude-mod/test/fixtures/mcp/get_context-models.jsonnew file mode 100644index 000000000..b824be640--- /dev/null+++ b/packages/claude-mod/test/fixtures/mcp/get_context-models.json@@ -0,0 +1,9 @@+{+ "content": [+ {+ "type": "text",+ "text": "{\"result\":{\"targets\":{\"src/requests/models.py\":{\"type\":\"file\",\"path\":\"src/requests/models.py\",\"parent_page\":{\"title\":\"Application Requests\",\"target_path\":\"src/requests\",\"section\":\"4\"},\"docs\":{\"title\":\"File: src/requests/models.py\",\"summary\":\"requests.models ~~~~~~~~~~~~~~~\",\"symbols\":[{\"name\":\"REDIRECT_STATI\",\"kind\":\"constant\",\"signature\":\"REDIRECT_STATI: Final[tuple[int, ...]] = ( # type: ignore[assignment]\",\"line\":95,\"symbol_id\":\"src/requests/models.py::REDIRECT_STATI\"},{\"name\":\"DEFAULT_REDIRECT_LIMIT\",\"kind\":\"constant\",\"signature\":\"DEFAULT_REDIRECT_LIMIT: int = 30\",\"line\":103,\"symbol_id\":\"src/requests/models.py::DEFAULT_REDIRECT_LIMIT\"},{\"name\":\"CONTENT_CHUNK_SIZE\",\"kind\":\"constant\",\"signature\":\"CONTENT_CHUNK_SIZE: int = 10 * 1024\",\"line\":104,\"symbol_id\":\"src/requests/models.py::CONTENT_CHUNK_SIZE\"},{\"name\":\"ITER_CHUNK_SIZE\",\"kind\":\"constant\",\"signature\":\"ITER_CHUNK_SIZE: int = 512\",\"line\":105,\"symbol_id\":\"src/requests/models.py::ITER_CHUNK_SIZE\"},{\"name\":\"RequestEncodingMixin\",\"kind\":\"class\",\"signature\":\"class RequestEncodingMixin\",\"line\":108,\"symbol_id\":\"src/requests/models.py::RequestEncodingMixin\"},{\"name\":\"path_url\",\"kind\":\"method\",\"signature\":\"def path_url(self) -> str\",\"line\":112,\"symbol_id\":\"src/requests/models.py::RequestEncodingMixin::path_url\"},{\"name\":\"_encode_params\",\"kind\":\"method\",\"signature\":\"def _encode_params( data: _t.EncodableDataType, ) -> str | bytes | _t.SupportsRead[str | bytes]\",\"line\":151,\"symbol_id\":\"src/requests/models.py::RequestEncodingMixin::_encode_params\"},{\"name\":\"_encode_files\",\"kind\":\"method\",\"signature\":\"def _encode_files( files: _t.FilesType, data: _t.RawDataType | None ) -> tuple[bytes, str]\",\"line\":183,\"symbol_id\":\"src/requests/models.py::RequestEncodingMixin::_encode_files\"},{\"name\":\"RequestHooksMixin\",\"kind\":\"class\",\"signature\":\"class RequestHooksMixin\",\"line\":254,\"symbol_id\":\"src/requests/models.py::RequestHooksMixin\"},{\"name\":\"register_hook\",\"kind\":\"method\",\"signature\":\"def register_hook( self, event: str, hook: Iterable[_t.HookType] | _t.HookType ) -> None\",\"line\":257,\"symbol_id\":\"src/requests/models.py::RequestHooksMixin::register_hook\"},{\"name\":\"deregister_hook\",\"kind\":\"method\",\"signature\":\"def deregister_hook(self, event: str, hook: _t.HookType) -> bool\",\"line\":272,\"symbol_id\":\"src/requests/models.py::RequestHooksMixin::deregister_hook\"},{\"name\":\"Request\",\"kind\":\"class\",\"signature\":\"class Request\",\"line\":284,\"symbol_id\":\"src/requests/models.py::Request\"},{\"name\":\"__init__\",\"kind\":\"method\",\"signature\":\"def __init__( self, method: str | None = None, url: _t.UriType | None = None, headers: _t.HeadersType = None, files: _t.FilesType = None, data: _t.DataType = None, params: _t.ParamsType = None, auth: _t.AuthType = None, cookies: [REDACTED] | CookieJar | dict[str, str] | None = None, hooks: _t.HooksInputType | None = None, json: _t.JsonType = None, ) -> None\",\"line\":323,\"symbol_id\":\"src/requests/models.py::Request::__init__\"},{\"name\":\"__repr__\",\"kind\":\"method\",\"signature\":\"def __repr__(self) -> str\",\"line\":357,\"symbol_id\":\"src/requests/models.py::Request::__repr__\"},{\"name\":\"prepare\",\"kind\":\"method\",\"signature\":\"def prepare(self) -> PreparedRequest\",\"line\":360,\"symbol_id\":\"src/requests/models.py::Request::prepare\"},{\"name\":\"PreparedRequest\",\"kind\":\"class\",\"signature\":\"class PreparedRequest\",\"line\":378,\"symbol_id\":\"src/requests/models.py::PreparedRequest\"},{\"name\":\"__init__\",\"kind\":\"method\",\"signature\":\"def __init__(self) -> None\",\"line\":407,\"symbol_id\":\"src/requests/models.py::PreparedRequest::__init__\"},{\"name\":\"prepare\",\"kind\":\"method\",\"signature\":\"def prepare( self, method: str | None = None, url: _t.UriType | None = None, headers: Mapping[str, str | bytes] | None = None, files: _t.FilesType = None, data: _t.DataType = None, params: _t.ParamsType = None, auth: _t.AuthType = None, cookies: [REDACTED] | CookieJar | dict[str, str] | None = None, hooks: _t.HooksInputType | None = None, json: _t.JsonType = None, ) -> None\",\"line\":424,\"symbol_id\":\"src/requests/models.py::PreparedRequest::prepare\"},{\"name\":\"__repr__\",\"kind\":\"method\",\"signature\":\"def __repr__(self) -> str\",\"line\":453,\"symbol_id\":\"src/requests/models.py::PreparedRequest::__repr__\"},{\"name\":\"copy\",\"kind\":\"method\",\"signature\":\"def copy(self) -> PreparedRequest\",\"line\":456,\"symbol_id\":\"src/requests/models.py::PreparedRequest::copy\"},{\"name\":\"prepare_method\",\"kind\":\"method\",\"signature\":\"def prepare_method(self, method: str | None) -> None\",\"line\":467,\"symbol_id\":\"src/requests/models.py::PreparedRequest::prepare_method\"},{\"name\":\"_get_idna_encoded_host\",\"kind\":\"method\",\"signature\":\"def _get_idna_encoded_host(host: str) -> str\",\"line\":474,\"symbol_id\":\"src/requests/models.py::PreparedRequest::_get_idna_encoded_host\"},{\"name\":\"prepare_url\",\"kind\":\"method\",\"signature\":\"def prepare_url( self, url: _t.UriType, params: _t.ParamsType, ) -> None\",\"line\":483,\"symbol_id\":\"src/requests/models.py::PreparedRequest::prepare_url\"},{\"name\":\"prepare_headers\",\"kind\":\"method\",\"signature\":\"def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None\",\"line\":565,\"symbol_id\":\"src/requests/models.py::PreparedRequest::prepare_headers\"},{\"name\":\"prepare_body\",\"kind\":\"method\",\"signature\":\"def prepare_body( self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None ) -> None\",\"line\":576,\"symbol_id\":\"src/requests/models.py::PreparedRequest::prepare_body\"},{\"name\":\"prepare_content_length\",\"kind\":\"method\",\"signature\":\"def prepare_content_length(self, body: _t.BodyType) -> None\",\"line\":654,\"symbol_id\":\"src/requests/models.py::PreparedRequest::prepare_content_length\"},{\"name\":\"prepare_auth\",\"kind\":\"method\",\"signature\":\"def prepare_auth( self, auth: _t.AuthType, url: _t.UriType = \\\"\\\", ) -> None\",\"line\":670,\"symbol_id\":\"src/requests/models.py::PreparedRequest::prepare_auth\"},{\"name\":\"prepare_cookies\",\"kind\":\"method\",\"signature\":\"def prepare_cookies( self, cookies: [REDACTED] | CookieJar | dict[str, str] | None ) -> None\",\"line\":699,\"symbol_id\":\"src/requests/models.py::PreparedRequest::prepare_cookies\"},{\"name\":\"prepare_hooks\",\"kind\":\"method\",\"signature\":\"def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None\",\"line\":722,\"symbol_id\":\"src/requests/models.py::PreparedRequest::prepare_hooks\"},{\"name\":\"Response\",\"kind\":\"class\",\"signature\":\"class Response\",\"line\":732,\"symbol_id\":\"src/requests/models.py::Response\"},{\"name\":\"__init__\",\"kind\":\"method\",\"signature\":\"def __init__(self) -> None\",\"line\":765,\"symbol_id\":\"src/requests/models.py::Response::__init__\"},{\"name\":\"__enter__\",\"kind\":\"method\",\"signature\":\"def __enter__(self) -> Self\",\"line\":812,\"symbol_id\":\"src/requests/models.py::Response::__enter__\"},{\"name\":\"__exit__\",\"kind\":\"method\",\"signature\":\"def __exit__(self, *args: Any) -> None\",\"line\":815,\"symbol_id\":\"src/requests/models.py::Response::__exit__\"},{\"name\":\"__getstate__\",\"kind\":\"method\",\"signature\":\"def __getstate__(self) -> dict[str, Any]\",\"line\":818,\"symbol_id\":\"src/requests/models.py::Response::__getstate__\"},{\"name\":\"__setstate__\",\"kind\":\"method\",\"signature\":\"def __setstate__(self, state: dict[str, Any]) -> None\",\"line\":826,\"symbol_id\":\"src/requests/models.py::Response::__setstate__\"},{\"name\":\"__repr__\",\"kind\":\"method\",\"signature\":\"def __repr__(self) -> str\",\"line\":834,\"symbol_id\":\"src/requests/models.py::Response::__repr__\"},{\"name\":\"__bool__\",\"kind\":\"method\",\"signature\":\"def __bool__(self) -> bool\",\"line\":837,\"symbol_id\":\"src/requests/models.py::Response::__bool__\"},{\"name\":\"__nonzero__\",\"kind\":\"method\",\"signature\":\"def __nonzero__(self) -> bool\",\"line\":847,\"symbol_id\":\"src/requests/models.py::Response::__nonzero__\"},{\"name\":\"__iter__\",\"kind\":\"method\",\"signature\":\"def __iter__(self) -> Iterator[bytes]\",\"line\":857,\"symbol_id\":\"src/requests/models.py::Response::__iter__\"},{\"name\":\"ok\",\"kind\":\"method\",\"signature\":\"def ok(self) -> bool\",\"line\":862,\"symbol_id\":\"src/requests/models.py::Response::ok\"}],\"symbols_truncated\":{\"shown\":40,\"total\":52,\"hint\":\"Call with compact=False or include=['full_doc'] for the full list.\"}},\"hotspot\":true,\"fix_history\":{\"fix_count\":3,\"last_fix_days_ago\":116},\"ownership\":{\"primary_owner\":\"Nate Prewitt\",\"owner_pct\":0.4444,\"owner_line_pct\":0.3936,\"contributor_count\":6,\"bus_factor\":3,\"recent_owner\":\"Joren Hammudoglu\",\"recent_owner_pct\":0.6},\"freshness\":{\"confidence_score\":1,\"freshness_status\":\"fresh\",\"is_stale\":false},\"architectural_layer\":{\"name\":\"Application\",\"description\":\"\",\"role\":\"edge_connector\"},\"callers\":[{\"file\":\"tests/test_requests.py\",\"imports\":true,\"inbound_calls\":25},{\"file\":\"src/requests/sessions.py\",\"imports\":true,\"inbound_calls\":2},{\"file\":\"src/requests/adapters.py\",\"imports\":true,\"inbound_calls\":1},{\"file\":\"src/requests/cookies.py\",\"imports\":true,\"inbound_calls\":1},{\"file\":\"src/requests/__init__.py\",\"imports\":true},{\"file\":\"src/requests/_types.py\",\"imports\":true},{\"file\":\"src/requests/api.py\",\"imports\":true},{\"file\":\"src/requests/auth.py\",\"imports\":true},{\"file\":\"src/requests/exceptions.py\",\"imports\":true},{\"file\":\"src/requests/hooks.py\",\"imports\":true},{\"file\":\"src/requests/utils.py\",\"imports\":true}],\"_call_graph_note\":\"File-level rollup: importing files plus inbound cross-file call counts. For symbol-precise callers pass 'file.py::Symbol'.\",\"episodes\":3}},\"_meta\":{\"contract_version\":2,\"timing_ms\":28.28,\"index_age_days\":49,\"indexed_commit\":\"4ed3d1b3204c\",\"live_head\":\"3bb56ba566ce\",\"index_behind\":true,\"index_scope\":{\"version\":1,\"projection\":\"compact\",\"run_mode\":\"standard\",\"content_provenance\":\"template\",\"git_tier\":\"full\",\"status\":\"unknown\",\"fingerprint\":\"118fda63ca3a\",\"full\":\"get_overview()\"},\"embedder\":\"mock\",\"embedder_degraded\":false,\"semantic_search\":false,\"scope_hint\":\"Unrelated to what was served: Config (19 files), Docs & Tooling (4).\",\"response_budget\":{\"limit_chars\":32000,\"tier\":\"expanded\",\"serialized_chars\":9804},\"completeness\":{\"capped\":false}}}}"+ }+ ],+ "isError": false+}\ No newline at end of filediff --git a/packages/claude-mod/test/fixtures/mcp/get_context-sessions.json b/packages/claude-mod/test/fixtures/mcp/get_context-sessions.jsonnew file mode 100644index 000000000..c02f84b70--- /dev/null+++ b/packages/claude-mod/test/fixtures/mcp/get_context-sessions.json@@ -0,0 +1,9 @@+{+ "content": [+ {+ "type": "text",+ "text": "{\"result\":{\"targets\":{\"src/requests/sessions.py\":{\"type\":\"file\",\"path\":\"src/requests/sessions.py\",\"parent_page\":{\"title\":\"Application Requests\",\"target_path\":\"src/requests\",\"section\":\"4\"},\"docs\":{\"title\":\"File: src/requests/sessions.py\",\"summary\":\"requests.sessions ~~~~~~~~~~~~~~~~~\",\"symbols\":[{\"name\":\"merge_setting\",\"kind\":\"function\",\"signature\":\"def merge_setting( request_setting: Any, session_setting: Any, dict_class: type = OrderedDict ) -> Any\",\"line\":76,\"symbol_id\":\"src/requests/sessions.py::merge_setting\"},{\"name\":\"merge_hooks\",\"kind\":\"function\",\"signature\":\"def merge_hooks( request_hooks: _t.HooksType, session_hooks: _t.HooksType, dict_class: type = OrderedDict, ) -> _t.HooksType\",\"line\":108,\"symbol_id\":\"src/requests/sessions.py::merge_hooks\"},{\"name\":\"SessionRedirectMixin\",\"kind\":\"class\",\"signature\":\"class SessionRedirectMixin\",\"line\":127,\"symbol_id\":\"src/requests/sessions.py::SessionRedirectMixin\"},{\"name\":\"send\",\"kind\":\"method\",\"signature\":\"def send(self, request: PreparedRequest, **kwargs: Any) -> Response\",\"line\":132,\"symbol_id\":\"src/requests/sessions.py::SessionRedirectMixin::send\"},{\"name\":\"get_redirect_target\",\"kind\":\"method\",\"signature\":\"def get_redirect_target(self, resp: Response) -> str | None\",\"line\":134,\"symbol_id\":\"src/requests/sessions.py::SessionRedirectMixin::get_redirect_target\"},{\"name\":\"should_strip_auth\",\"kind\":\"method\",\"signature\":\"def should_strip_auth(self, old_url: str, new_url: str) -> bool\",\"line\":154,\"symbol_id\":\"src/requests/sessions.py::SessionRedirectMixin::should_strip_auth\"},{\"name\":\"resolve_redirects\",\"kind\":\"method\",\"signature\":\"def resolve_redirects( self, resp: Response, req: PreparedRequest, stream: bool = False, timeout: _t.TimeoutType = None, verify: _t.VerifyType = True, cert: _t.CertType = None, proxies: dict[str, str] | None = None, yield_requests: bool = False, **adapter_kwargs: Any, ) -> Generator[Response, None, None]\",\"line\":186,\"symbol_id\":\"src/requests/sessions.py::SessionRedirectMixin::resolve_redirects\"},{\"name\":\"rebuild_auth\",\"kind\":\"method\",\"signature\":\"def rebuild_auth( self, prepared_request: PreparedRequest, response: Response ) -> None\",\"line\":309,\"symbol_id\":\"src/requests/sessions.py::SessionRedirectMixin::rebuild_auth\"},{\"name\":\"rebuild_proxies\",\"kind\":\"method\",\"signature\":\"def rebuild_proxies( self, prepared_request: PreparedRequest, proxies: dict[str, str] | None, ) -> dict[str, str]\",\"line\":334,\"symbol_id\":\"src/requests/sessions.py::SessionRedirectMixin::rebuild_proxies\"},{\"name\":\"rebuild_method\",\"kind\":\"method\",\"signature\":\"def rebuild_method( self, prepared_request: PreparedRequest, response: Response ) -> None\",\"line\":370,\"symbol_id\":\"src/requests/sessions.py::SessionRedirectMixin::rebuild_method\"},{\"name\":\"Session\",\"kind\":\"class\",\"signature\":\"class Session\",\"line\":395,\"symbol_id\":\"src/requests/sessions.py::Session\"},{\"name\":\"__init__\",\"kind\":\"method\",\"signature\":\"def __init__(self) -> None\",\"line\":442,\"symbol_id\":\"src/requests/sessions.py::Session::__init__\"},{\"name\":\"__enter__\",\"kind\":\"method\",\"signature\":\"def __enter__(self) -> Self\",\"line\":505,\"symbol_id\":\"src/requests/sessions.py::Session::__enter__\"},{\"name\":\"__exit__\",\"kind\":\"method\",\"signature\":\"def __exit__(self, *args: Any) -> None\",\"line\":508,\"symbol_id\":\"src/requests/sessions.py::Session::__exit__\"},{\"name\":\"prepare_request\",\"kind\":\"method\",\"signature\":\"def prepare_request(self, request: Request) -> PreparedRequest\",\"line\":511,\"symbol_id\":\"src/requests/sessions.py::Session::prepare_request\"},{\"name\":\"request\",\"kind\":\"method\",\"signature\":\"def request( self, method: str, url: _t.UriType, params: _t.ParamsType = None, data: _t.DataType = None, headers: _t.HeadersType = None, cookies: [REDACTED] | CookieJar | dict[str, str] | None = None, files: _t.FilesType = None, auth: _t.AuthType = None, timeout: _t.TimeoutType = None, allow_redirects: bool = True, proxies: dict[str, str] | None = None, hooks: _t.HooksInputType | None = None, stream: bool | None = None, verify: _t.VerifyType | None = None, cert: _t.CertType = None, json: _t.JsonType = None, ) -> Response\",\"line\":557,\"symbol_id\":\"src/requests/sessions.py::Session::request\"},{\"name\":\"get\",\"kind\":\"method\",\"signature\":\"def get( self, url: _t.UriType, params: _t.ParamsType = None, **kwargs: Unpack[_t.GetKwargs], ) -> Response\",\"line\":655,\"symbol_id\":\"src/requests/sessions.py::Session::get\"},{\"name\":\"options\",\"kind\":\"method\",\"signature\":\"def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response\",\"line\":673,\"symbol_id\":\"src/requests/sessions.py::Session::options\"},{\"name\":\"head\",\"kind\":\"method\",\"signature\":\"def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response\",\"line\":684,\"symbol_id\":\"src/requests/sessions.py::Session::head\"},{\"name\":\"post\",\"kind\":\"method\",\"signature\":\"def post( self, url: _t.UriType, data: _t.DataType = None, json: _t.JsonType = None, **kwargs: Unpack[_t.PostKwargs], ) -> Response\",\"line\":695,\"symbol_id\":\"src/requests/sessions.py::Session::post\"},{\"name\":\"put\",\"kind\":\"method\",\"signature\":\"def put( self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs] ) -> Response\",\"line\":714,\"symbol_id\":\"src/requests/sessions.py::Session::put\"},{\"name\":\"patch\",\"kind\":\"method\",\"signature\":\"def patch( self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs] ) -> Response\",\"line\":728,\"symbol_id\":\"src/requests/sessions.py::Session::patch\"},{\"name\":\"delete\",\"kind\":\"method\",\"signature\":\"def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response\",\"line\":742,\"symbol_id\":\"src/requests/sessions.py::Session::delete\"},{\"name\":\"send\",\"kind\":\"method\",\"signature\":\"def send(self, request: PreparedRequest, **kwargs: Any) -> Response\",\"line\":752,\"symbol_id\":\"src/requests/sessions.py::Session::send\"},{\"name\":\"merge_environment_settings\",\"kind\":\"method\",\"signature\":\"def merge_environment_settings( self, url: str, proxies: dict[str, str] | None, stream: bool | None, verify: _t.VerifyType | None, cert: _t.CertType, ) -> dict[str, Any]\",\"line\":831,\"symbol_id\":\"src/requests/sessions.py::Session::merge_environment_settings\"},{\"name\":\"get_adapter\",\"kind\":\"method\",\"signature\":\"def get_adapter(self, url: str) -> BaseAdapter\",\"line\":870,\"symbol_id\":\"src/requests/sessions.py::Session::get_adapter\"},{\"name\":\"close\",\"kind\":\"method\",\"signature\":\"def close(self) -> None\",\"line\":883,\"symbol_id\":\"src/requests/sessions.py::Session::close\"},{\"name\":\"mount\",\"kind\":\"method\",\"signature\":\"def mount(self, prefix: str, adapter: BaseAdapter) -> None\",\"line\":888,\"symbol_id\":\"src/requests/sessions.py::Session::mount\"},{\"name\":\"__getstate__\",\"kind\":\"method\",\"signature\":\"def __getstate__(self) -> dict[str, Any]\",\"line\":899,\"symbol_id\":\"src/requests/sessions.py::Session::__getstate__\"},{\"name\":\"__setstate__\",\"kind\":\"method\",\"signature\":\"def __setstate__(self, state: dict[str, Any]) -> None\",\"line\":903,\"symbol_id\":\"src/requests/sessions.py::Session::__setstate__\"},{\"name\":\"session\",\"kind\":\"function\",\"signature\":\"def session() -> Session\",\"line\":908,\"symbol_id\":\"src/requests/sessions.py::session\"}]},\"hotspot\":false,\"fix_history\":{\"fix_count\":2,\"last_fix_days_ago\":142},\"ownership\":{\"primary_owner\":\"Nate Prewitt\",\"owner_pct\":0.5455,\"owner_line_pct\":0.3554,\"contributor_count\":6,\"bus_factor\":4,\"recent_owner\":\"Joren Hammudoglu\",\"recent_owner_pct\":0.5},\"freshness\":{\"confidence_score\":1,\"freshness_status\":\"fresh\",\"is_stale\":false},\"architectural_layer\":{\"name\":\"Application\",\"description\":\"\",\"role\":\"edge_connector\"},\"callers\":[{\"file\":\"src/requests/api.py\",\"imports\":true,\"inbound_calls\":1},{\"file\":\"src/requests/__init__.py\",\"imports\":true},{\"file\":\"tests/test_requests.py\",\"imports\":true}],\"_call_graph_note\":\"File-level rollup: importing files plus inbound cross-file call counts. For symbol-precise callers pass 'file.py::Symbol'.\",\"episodes\":2}},\"_meta\":{\"contract_version\":2,\"timing_ms\":56.67,\"index_age_days\":49,\"indexed_commit\":\"4ed3d1b3204c\",\"live_head\":\"3bb56ba566ce\",\"index_behind\":true,\"index_scope\":{\"version\":1,\"projection\":\"compact\",\"run_mode\":\"standard\",\"content_provenance\":\"template\",\"git_tier\":\"full\",\"status\":\"unknown\",\"fingerprint\":\"118fda63ca3a\",\"full\":\"get_overview()\"},\"embedder\":\"mock\",\"embedder_degraded\":false,\"semantic_search\":false,\"scope_hint\":\"Unrelated to what was served: Config (19 files), Docs & Tooling (4).\",\"response_budget\":{\"limit_chars\":32000,\"tier\":\"expanded\",\"serialized_chars\":8446},\"completeness\":{\"capped\":false}}}}"+ }+ ],+ "isError": false+}\ No newline at end of filediff --git a/packages/claude-mod/test/fixtures/replay/repowise-edit-session.json b/packages/claude-mod/test/fixtures/replay/repowise-edit-session.jsonnew file mode 100644index 000000000..9b384e4b4--- /dev/null+++ b/packages/claude-mod/test/fixtures/replay/repowise-edit-session.json@@ -0,0 +1,321 @@+[+ {+ "tool_name": "Read",+ "tool_use_id": "toolu_014LSeErwKf4nsu1ArL7rfXo",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\core\\src\\repowise\\core\\ingestion\\parser.py",+ "limit": 15+ },+ "result": {}+ },+ {+ "tool_name": "mcp__plugin_repowise_repowise__get_context",+ "tool_use_id": "toolu_plugin_5e95632d76bf49e7886230b8a7aa3e2a",+ "tool_input": {+ "targets": [+ "packages/core/src/repowise/core/ingestion/parser.py"+ ],+ "include": [+ "callers",+ "ownership"+ ]+ },+ "result": {}+ },+ {+ "tool_name": "Edit",+ "tool_use_id": "toolu_01P77H3c1LrnnZBi8MTE2LvR",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\core\\src\\repowise\\core\\ingestion\\parser.py",+ "old_string": "\"\"\"Unified AST parser \u2014 one class for all languages.\n",+ "new_string": "\"\"\"Unified AST parser \u2014 one class for all languages.\n# lens replay\n",+ "replace_all": false+ },+ "result": {+ "additionalContext": [+ "[repowise] packages/core/src/repowise/core/ingestion/parser.py has a decision recorded in it, mined but not reviewed: Configure languages declaratively in queries and language configs because Adding a language requires only one ``.scm`` file and one ``LanguageConfig`` entry, rather than a new Python class or module..\n[repowise] packages/core/src/repowise/core/ingestion/parser.py has been bug-fixed 42x in the last 6 months, last today (bug magnet); mostly in parse_file."+ ]+ }+ },+ {+ "tool_name": "Grep",+ "tool_use_id": "toolu_01WohgYiv8LCTJGJjm9aGzEA",+ "tool_input": {+ "pattern": "def parse_file",+ "path": "C:\\work\\repo\\packages\\core\\src\\repowise\\core\\ingestion"+ },+ "result": {}+ },+ {+ "tool_name": "Read",+ "tool_use_id": "toolu_01SQrvMx7WTmTXRWKcmWzEW8",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\core\\src\\repowise\\core\\analysis\\health\\engine.py",+ "limit": 15+ },+ "result": {}+ },+ {+ "tool_name": "mcp__plugin_repowise_repowise__get_context",+ "tool_use_id": "toolu_plugin_fdca0f2233a84f929a005acc16948dbe",+ "tool_input": {+ "targets": [+ "packages/core/src/repowise/core/analysis/health/engine.py"+ ],+ "include": [+ "callers",+ "ownership"+ ]+ },+ "result": {}+ },+ {+ "tool_name": "Edit",+ "tool_use_id": "toolu_01RQU8ACcXBE7y2MqQFUiYXW",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\core\\src\\repowise\\core\\analysis\\health\\engine.py",+ "old_string": "\"\"\"HealthAnalyzer \u2014 thin orchestrator over walker \u2192 biomarkers \u2192 scorer.\n",+ "new_string": "\"\"\"HealthAnalyzer \u2014 thin orchestrator over walker \u2192 biomarkers \u2192 scorer.\n# lens replay\n",+ "replace_all": false+ },+ "result": {+ "additionalContext": [+ "[repowise] packages/core/src/repowise/core/analysis/health/engine.py has a decision recorded in it, mined but not reviewed: Propagate maximum complexity to symbols because This lets downstream consumers benefit from the computed complexity..\n[repowise] packages/core/src/repowise/core/analysis/health/engine.py has been bug-fixed 39x in the last 6 months, last today (bug magnet); mostly in analyze."+ ]+ }+ },+ {+ "tool_name": "Read",+ "tool_use_id": "toolu_018enhLPN24xDA5otC3ULC4B",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\core\\src\\repowise\\core\\analysis\\dead_code\\analyzer.py",+ "limit": 15+ },+ "result": {}+ },+ {+ "tool_name": "mcp__plugin_repowise_repowise__get_context",+ "tool_use_id": "toolu_plugin_0356eca91d6442a19f72c5a03d58f26f",+ "tool_input": {+ "targets": [+ "packages/core/src/repowise/core/analysis/dead_code/analyzer.py"+ ],+ "include": [+ "callers",+ "ownership"+ ]+ },+ "result": {}+ },+ {+ "tool_name": "Edit",+ "tool_use_id": "toolu_018jYGKirRfgW3qFpfn18zGJ",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\core\\src\\repowise\\core\\analysis\\dead_code\\analyzer.py",+ "old_string": "\"\"\"DeadCodeAnalyzer \u00e2\u20ac\u201d pure graph + git-metadata dead-code detection.\n",+ "new_string": "\"\"\"DeadCodeAnalyzer \u00e2\u20ac\u201d pure graph + git-metadata dead-code detection.\n# lens replay\n",+ "replace_all": false+ },+ "result": {+ "additionalContext": [+ "[repowise] packages/core/src/repowise/core/analysis/dead_code/analyzer.py has a decision recorded in it, mined but not reviewed: Share one identifier shape for absence scans.\n[repowise] packages/core/src/repowise/core/analysis/dead_code/analyzer.py has been bug-fixed 53x in the last 6 months, last today (bug magnet); mostly in _member_is_used."+ ]+ }+ },+ {+ "tool_name": "Glob",+ "tool_use_id": "toolu_01XErLAprHk19bXLHLpFRe9o",+ "tool_input": {+ "pattern": "packages/core/src/repowise/core/persistence/*.py"+ },+ "result": {}+ },+ {+ "tool_name": "Read",+ "tool_use_id": "toolu_014P2jjzhiE2JJ5CmJC5TSy8",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\core\\src\\repowise\\core\\persistence\\database.py",+ "limit": 15+ },+ "result": {}+ },+ {+ "tool_name": "mcp__plugin_repowise_repowise__get_context",+ "tool_use_id": "toolu_plugin_b9f0e77f4e924b4bb8cb758c095528e0",+ "tool_input": {+ "targets": [+ "packages/core/src/repowise/core/persistence/database.py"+ ],+ "include": [+ "callers",+ "ownership"+ ]+ },+ "result": {}+ },+ {+ "tool_name": "Edit",+ "tool_use_id": "toolu_01UbCz8kNz6XGe1DGjsHkQcJ",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\core\\src\\repowise\\core\\persistence\\database.py",+ "old_string": "\"\"\"Async database engine and session factory for repowise.\n",+ "new_string": "\"\"\"Async database engine and session factory for repowise.\n# lens replay\n",+ "replace_all": false+ },+ "result": {}+ },+ {+ "tool_name": "Read",+ "tool_use_id": "toolu_01Sw91kGAFQevCFd6VjaCedp",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\core\\src\\repowise\\core\\pipeline\\persist.py",+ "limit": 15+ },+ "result": {}+ },+ {+ "tool_name": "mcp__plugin_repowise_repowise__get_context",+ "tool_use_id": "toolu_plugin_ac0d74f12f54410e857680767f8fdc30",+ "tool_input": {+ "targets": [+ "packages/core/src/repowise/core/pipeline/persist.py"+ ],+ "include": [+ "callers",+ "ownership"+ ]+ },+ "result": {}+ },+ {+ "tool_name": "Edit",+ "tool_use_id": "toolu_01Ji132q7tGduw4sNJcNHejh",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\core\\src\\repowise\\core\\pipeline\\persist.py",+ "old_string": "\"\"\"Shared persistence logic for pipeline results.\n",+ "new_string": "\"\"\"Shared persistence logic for pipeline results.\n# lens replay\n",+ "replace_all": false+ },+ "result": {}+ },+ {+ "tool_name": "Bash",+ "tool_use_id": "toolu_01B6BEUFkdNnSBHWYQT9tKf7",+ "tool_input": {+ "command": "repowise distill git log -n 200",+ "description": "Run repowise distill over recent git log"+ },+ "result": {}+ },+ {+ "tool_name": "Read",+ "tool_use_id": "toolu_01A6bt3WudnErhxY8Ru5HXmX",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\types\\src\\health.ts",+ "limit": 15+ },+ "result": {}+ },+ {+ "tool_name": "mcp__plugin_repowise_repowise__get_context",+ "tool_use_id": "toolu_plugin_609be1095ace4b77b2181c765de36c31",+ "tool_input": {+ "targets": [+ "packages/types/src/health.ts"+ ],+ "include": [+ "callers",+ "ownership"+ ]+ },+ "result": {}+ },+ {+ "tool_name": "Edit",+ "tool_use_id": "toolu_01KKaWAvH2qnoRUWj4eBhkUq",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\types\\src\\health.ts",+ "old_string": "/**\n * Canonical code-health wire contract",+ "new_string": "/**\n// lens replay\n * Canonical code-health wire contract",+ "replace_all": false+ },+ "result": {}+ },+ {+ "tool_name": "Grep",+ "tool_use_id": "toolu_01MvhxzUMbfWPGcgAJwZ7hk7",+ "tool_input": {+ "pattern": "_persist_full_update_async",+ "path": "C:\\work\\repo\\packages\\cli\\src\\repowise\\cli\\commands\\update_cmd"+ },+ "result": {}+ },+ {+ "tool_name": "Read",+ "tool_use_id": "toolu_01S6C1u9GmwTEpDfGLXNxFhm",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\cli\\src\\repowise\\cli\\commands\\update_cmd\\persistence.py",+ "limit": 15+ },+ "result": {}+ },+ {+ "tool_name": "mcp__plugin_repowise_repowise__get_context",+ "tool_use_id": "toolu_plugin_951e839681434442b5b7d1c0677bc447",+ "tool_input": {+ "targets": [+ "packages/cli/src/repowise/cli/commands/update_cmd/persistence.py"+ ],+ "include": [+ "callers",+ "ownership"+ ]+ },+ "result": {}+ },+ {+ "tool_name": "Edit",+ "tool_use_id": "toolu_01CH2YPi9ddZv5R41aXaesyY",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\cli\\src\\repowise\\cli\\commands\\update_cmd\\persistence.py",+ "old_string": "\"\"\"Persistence + health-rescore helpers for ``repowise update``.\n",+ "new_string": "\"\"\"Persistence + health-rescore helpers for ``repowise update``.\n# lens replay\n",+ "replace_all": false+ },+ "result": {}+ },+ {+ "tool_name": "Read",+ "tool_use_id": "toolu_015hW12uHNqdtNeiW3emAzoX",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\cli\\src\\repowise\\cli\\__init__.py",+ "limit": 15+ },+ "result": {}+ },+ {+ "tool_name": "mcp__plugin_repowise_repowise__get_context",+ "tool_use_id": "toolu_plugin_d4cca228061144de8690de9d159013f3",+ "tool_input": {+ "targets": [+ "packages/cli/src/repowise/cli/__init__.py"+ ],+ "include": [+ "callers",+ "ownership"+ ]+ },+ "result": {}+ },+ {+ "tool_name": "Edit",+ "tool_use_id": "toolu_01715f5pFwN9aafddu46MNJs",+ "tool_input": {+ "file_path": "C:\\work\\repo\\packages\\cli\\src\\repowise\\cli\\__init__.py",+ "old_string": "\"\"\"repowise CLI package.\n",+ "new_string": "\"\"\"repowise CLI package.\n# lens replay\n",+ "replace_all": false+ },+ "result": {}+ }+]\ No newline at end of filediff --git a/packages/claude-mod/test/fixtures/repos.json b/packages/claude-mod/test/fixtures/repos.jsonnew file mode 100644index 000000000..565c8d0e7--- /dev/null+++ b/packages/claude-mod/test/fixtures/repos.json@@ -0,0 +1,18 @@+[+ {+ "id": "repo-outer",+ "name": "workspace",+ "local_path": "C:\\work"+ },+ {+ "id": "repo-requests",+ "name": "requests",+ "local_path": "c:/work/requests/",+ "updated_at": "2026-10-03T05:21:18.324285"+ },+ {+ "id": "repo-other",+ "name": "other",+ "local_path": "C:\\work\\other"+ }+]diff --git a/packages/claude-mod/test/fixtures/savings/after-distill.json b/packages/claude-mod/test/fixtures/savings/after-distill.jsonnew file mode 100644index 000000000..e5d625247--- /dev/null+++ b/packages/claude-mod/test/fixtures/savings/after-distill.json@@ -0,0 +1,72 @@+{+ "available": true,+ "window_days": null,+ "as_of": "2026-10-03T06:47:56.472074+00:00",+ "first_event_at": "2026-10-03T06:47:56.352609Z",+ "last_event_at": "2026-10-03T06:47:56.352609Z",+ "unique_events": 1,+ "successful_or_usable_partial_events": 1,+ "saving_interactions": 1,+ "mcp_queries_answered": 0,+ "dead_ends": 0,+ "saved_input_tokens": 7099,+ "measured_saved_input_tokens": 7099,+ "inferred_saved_input_tokens": 0,+ "priced_saved_input_tokens": 7099,+ "unpriced_saved_input_tokens": 0,+ "priced_input_savings_usd": 0.035495,+ "saved_output_tokens": null,+ "priced_saved_output_tokens": 0,+ "unpriced_saved_output_tokens": 0,+ "priced_output_savings_usd": 0.0,+ "baseline_events": 1,+ "reducing_events": 1,+ "baseline_input_tokens": 7500,+ "baseline_saved_input_tokens": 7099,+ "input_reduction_ratio": 0.9465333333333333,+ "input_reduction_ratio_p90": 0.9465333333333333,+ "per_operation": [+ {+ "group": "git_log",+ "events": 1,+ "saved_input_tokens": 7099+ }+ ],+ "per_surface": [+ {+ "group": "distill",+ "events": 1,+ "saved_input_tokens": 7099+ }+ ],+ "per_agent": [+ {+ "agent": "unknown",+ "agent_display_name": "Unknown",+ "events": 1,+ "saved_input_tokens": 7099+ }+ ],+ "per_model": [+ {+ "group": "claude-opus-5-5",+ "events": 1,+ "saved_input_tokens": 7099+ }+ ],+ "per_day": [+ {+ "group": "2026-10-03",+ "events": 1,+ "saved_input_tokens": 7099+ }+ ],+ "opportunity_count": 0,+ "opportunity_tokens_excluded": 0,+ "per_opportunity_kind": [],+ "missed_events": 0,+ "missed_tokens_est": 0,+ "missed_window_days": 7.0,+ "reread_events": 0,+ "reread_tokens_est": 0+}\ No newline at end of filediff --git a/packages/claude-mod/test/fixtures/savings/before-distill.json b/packages/claude-mod/test/fixtures/savings/before-distill.jsonnew file mode 100644index 000000000..52c1e1991--- /dev/null+++ b/packages/claude-mod/test/fixtures/savings/before-distill.json@@ -0,0 +1,41 @@+{+ "available": true,+ "window_days": null,+ "as_of": "2026-10-03T06:47:49.051852+00:00",+ "first_event_at": null,+ "last_event_at": null,+ "unique_events": 0,+ "successful_or_usable_partial_events": 0,+ "saving_interactions": 0,+ "mcp_queries_answered": 0,+ "dead_ends": 0,+ "saved_input_tokens": 0,+ "measured_saved_input_tokens": 0,+ "inferred_saved_input_tokens": 0,+ "priced_saved_input_tokens": 0,+ "unpriced_saved_input_tokens": 0,+ "priced_input_savings_usd": 0.0,+ "saved_output_tokens": null,+ "priced_saved_output_tokens": 0,+ "unpriced_saved_output_tokens": 0,+ "priced_output_savings_usd": 0.0,+ "baseline_events": 0,+ "reducing_events": 0,+ "baseline_input_tokens": 0,+ "baseline_saved_input_tokens": 0,+ "input_reduction_ratio": null,+ "input_reduction_ratio_p90": null,+ "per_operation": [],+ "per_surface": [],+ "per_agent": [],+ "per_model": [],+ "per_day": [],+ "opportunity_count": 0,+ "opportunity_tokens_excluded": 0,+ "per_opportunity_kind": [],+ "missed_events": 0,+ "missed_tokens_est": 0,+ "missed_window_days": 7.0,+ "reread_events": 0,+ "reread_tokens_est": 0+}\ No newline at end of filediff --git a/packages/claude-mod/test/fixtures/tool-calls.json b/packages/claude-mod/test/fixtures/tool-calls.jsonnew file mode 100644index 000000000..e51e968a0--- /dev/null+++ b/packages/claude-mod/test/fixtures/tool-calls.json@@ -0,0 +1,138 @@+{+ "grep_files": {+ "e": {+ "pattern": "class QuerySet",+ "output_mode": "files_with_matches",+ "tool": "Grep",+ "tool_use_id": "toolu_01A6atUt9VFRynCBNkNSjniw"+ },+ "r": {+ "ref": 1,+ "result": {+ "mode": "files_with_matches",+ "filenames": [+ "django\\db\\models\\query.py",+ "tests\\queries\\tests.py",+ "tests\\queries\\test_qs_combinators.py",+ "tests\\queries\\test_iterator.py"+ ],+ "numFiles": 4,+ "totalFiles": 4+ },+ "text": "Found 4 files\ndjango\\db\\models\\query.py\ntests\\queries\\tests.py\ntests\\queries\\test_qs_combinators.py\ntests\\queries\\test_i",+ "isReadOnly": true+ }+ },+ "grep_content": {+ "e": {+ "pattern": "def bulk_create",+ "output_mode": "content",+ "path": "django/db/models",+ "tool": "Grep",+ "tool_use_id": "toolu_01E8PKtqjGzSWCHR9ZED7DRe"+ },+ "r": {+ "ref": 1,+ "result": {+ "mode": "content",+ "numFiles": 0,+ "filenames": [],+ "content": "django\\db\\models\\query.py:817: def bulk_create(",+ "numLines": 1,+ "totalLines": 1+ },+ "text": "django\\db\\models\\query.py:817: def bulk_create(",+ "isReadOnly": true+ }+ },+ "glob": {+ "e": {+ "pattern": "django/db/models/sql/*.py",+ "tool": "Glob",+ "tool_use_id": "toolu_01EKYYymkeVSExbXUTqsS8k9"+ },+ "r": {+ "ref": 1,+ "result": {+ "filenames": [+ "django\\db\\models\\sql\\subqueries.py",+ "django\\db\\models\\sql\\__init__.py",+ "django\\db\\models\\sql\\where.py",+ "django\\db\\models\\sql\\datastructures.py",+ "django\\db\\models\\sql\\query.py",+ "django\\db\\models\\sql\\compiler.py",+ "django\\db\\models\\sql\\constants.py"+ ],+ "durationMs": 168,+ "numFiles": 7,+ "truncated": false,+ "totalMatches": 7,+ "countIsComplete": true+ },+ "text": "django\\db\\models\\sql\\subqueries.py\ndjango\\db\\models\\sql\\__init__.py\ndjango\\db\\models\\sql\\where.py\ndjango\\db\\models\\sql\\d",+ "isReadOnly": true+ }+ },+ "read": {+ "e": {+ "file_path": "C:\\work\\django\\django\\db\\models\\manager.py",+ "limit": 5,+ "tool": "Read",+ "tool_use_id": "toolu_01TB5Tozy9Ms3YgeWruKitBo"+ },+ "r": {+ "ref": 1,+ "result": {+ "type": "text",+ "file": {+ "filePath": "C:\\work\\django\\django\\db\\models\\manager.py",+ "content": "import copy\nimport inspect\nfrom functools import wraps\nfrom importlib import import_module\n",+ "numLines": 5,+ "startLine": 1,+ "totalLines": 214+ }+ },+ "text": "1\timport copy\n2\timport inspect\n3\tfrom functools import wraps\n4\tfrom importlib import import_module\n5\t",+ "isReadOnly": true+ }+ },+ "edit": {+ "e": {+ "replace_all": false,+ "file_path": "C:\\work\\django\\django\\db\\models\\manager.py",+ "old_string": "import copy",+ "new_string": "import copy # probe",+ "tool": "Edit",+ "tool_use_id": "toolu_01DHH1MUSCrMG2dYMfRdbTV3"+ },+ "r": {+ "ref": 1,+ "result": {+ "filePath": "C:\\work\\django\\django\\db\\models\\manager.py",+ "oldString": "import copy",+ "newString": "import copy # probe",+ "originalFile": "import copy\nimport inspect\nfrom functools import wraps\nfrom importlib import import_module\n\nfrom django.db import router",+ "userModified": false,+ "replaceAll": false,+ "contentNotInModelContext": true+ },+ "text": "The file C:\\work\\django\\django\\db\\models\\manager.py has been updated successfully."+ }+ },+ "edit_failed": {+ "e": {+ "replace_all": false,+ "file_path": "C:\\work\\django\\django\\db\\models\\manager.py",+ "old_string": "THIS TEXT DOES NOT EXIST xyz",+ "new_string": "nothing",+ "tool": "Edit",+ "tool_use_id": "toolu_01JFe1M5eiC5PtJZJwi2FBvD"+ },+ "r": {+ "ref": 1,+ "result": "Error: String to replace not found in file.\nString: THIS TEXT DOES NOT EXIST xyz",+ "text": "<tool_use_error>String to replace not found in file.\nString: THIS TEXT DOES NOT EXIST xyz</tool_use_error>",+ "isError": true+ }+ }+}\ No newline at end of filediff --git a/packages/claude-mod/test/map-register.test.ts b/packages/claude-mod/test/map-register.test.tsnew file mode 100644index 000000000..ff4aa5cf3--- /dev/null+++ b/packages/claude-mod/test/map-register.test.ts@@ -0,0 +1,445 @@+// The map's wiring through register(): /lens, the Pane, the trail from tool+// calls, importers and the ripple, auto-open. Answers come from the recorded+// Django payloads (test/fixtures).+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { Hook, ModApi, On, PluginOptions } from "../src/mod-api";+import { MAP_COPY, PANE_COPY } from "../src/views/copy";+import { fixture, flatten, textOf, type Tree } from "./fake-host";++type Hooks = Record<string, Hook<any>>;++/** Hooks by event, and by `event:component` / `event:command` where a matcher narrows them. */+async function load(options?: PluginOptions): Promise<Hooks> {+ vi.resetModules();+ const { register } = await import("../src/register");+ const hooks: Hooks = {};+ const on = ((event: string, a: unknown, b?: unknown) => {+ const matcher = b === undefined ? null : (a as { component?: string; command?: string });+ const name = matcher === null ? event : `${event}:${matcher.component ?? matcher.command}`;+ hooks[name] = (b ?? a) as Hook<any>;+ }) as On;+ register(on, options);+ return hooks;+}++interface Calls {+ cwd: number;+ invalidate: number;+ logs: string[];+ open: unknown[];+ close: unknown[];+ blit: { columns: number; rows: number; cells: string }[];+ commands: unknown[];+ http: string[];+}++/** The surface's side: redraws, logs, elements, and the pane and blit calls, all recorded. */+function uiFake(calls: Calls): ModApi["ui"] {+ return {+ invalidate: () => {+ calls.invalidate++;+ },+ log: (text) => {+ calls.logs.push(text);+ },+ resolve: () => ({+ Box: (props) => ({ el: "Box", props }),+ Text: (props) => ({ el: "Text", props }),+ Raster: (props) => ({ el: "Raster", props }),+ Button: (props) => ({ el: "Button", props }),+ Input: (props) => ({ el: "Input", props }),+ Markdown: (props) => ({ el: "Markdown", props }),+ Svg: (props) => ({ el: "Svg", props }),+ }),+ open: async (pane) => {+ calls.open.push(pane);+ return { isPlaced: true };+ },+ close: async (pane) => {+ calls.close.push(pane);+ },+ blit: async (args) => {+ calls.blit.push(args);+ return {};+ },+ };+}++/** A `$` for a git work tree with no index and a connecting MCP server. */+function fakeDollar() {+ const calls: Calls = { cwd: 0, invalidate: 0, logs: [], open: [], close: [], blit: [], commands: [], http: [] };+ let release: () => void = () => {};+ const gate = { hold: false, wait: Promise.resolve() };+ const $: ModApi = {+ session: {+ cwd: async () => {+ calls.cwd++;+ if (gate.hold) await gate.wait;+ return "/work/app";+ },+ },+ fs: { read: async () => Promise.reject(new Error("ENOENT")), exists: async () => false },+ process: {+ run: async (argv) => ({ exitCode: 0, stdout: argv.includes("--is-inside-work-tree") ? "true\n" : "", stderr: "" }),+ },+ http: { fetch: async () => ({ status: 500, ok: false, headers: {}, text: "" }) },+ mcp: {+ connect: async () => ({ isConnected: true }),+ call: async () => Promise.reject(new Error("no MCP in this test")),+ },+ prompt: { submit: async () => ({}) },+ ui: uiFake(calls),+ command: {+ register: async (c) => {+ calls.commands.push(c);+ return { command: c.name };+ },+ },+ settings: { read: async () => ({}) },+ };+ const hold = () => {+ gate.hold = true;+ gate.wait = new Promise<void>((resolve) => (release = resolve));+ };+ return { $, calls, hold, release: () => release() };+}++const ROOT = "C:\\work\\django";+const SHA = "e78991410b78391bc07a4b5010b273dfec814ff6";+const json = (status: number, body: unknown) => ({ status, ok: status < 300, headers: {}, text: JSON.stringify(body) });++/** A `$` in full mode: an indexed Django copy with its local server up, answering from recorded payloads. */+function fullDollar() {+ const d = fakeDollar();+ const files: Record<string, string> = {+ "C:/work/django/.repowise/state.json": JSON.stringify({ last_sync_commit: SHA }),+ "C:/work/django/.repowise/serve.lock.json": fixture("locks/valid.json"),+ };+ d.$.session.cwd = async () => ROOT;+ d.$.fs = {+ exists: async (p) => p.replace(/\\/g, "/") in files,+ read: async (p) => files[p.replace(/\\/g, "/")] ?? Promise.reject(new Error("ENOENT")),+ };+ d.$.process.run = async (argv) => {+ if (argv[0] === "tasklist") return { exitCode: 0, stdout: '"python.exe","4242","Console"\r\n', stderr: "" };+ if (argv.includes("HEAD")) return { exitCode: 0, stdout: `${SHA}\n`, stderr: "" };+ return { exitCode: 0, stdout: "true\n", stderr: "" };+ };+ d.$.http.fetch = async (url) => {+ d.calls.http.push(url);+ if (url.endsWith("/health")) return json(200, { status: "healthy" });+ if (url.endsWith("/api/repos")) {+ return json(200, [{ id: "dj", name: "django", local_path: "c:/work/django/", updated_at: null }]);+ }+ if (url.includes("/health/map")) return { status: 200, ok: true, headers: {}, text: fixture("django-health-map.json") };+ if (url.endsWith("/blast-radius")) {+ return { status: 200, ok: true, headers: {}, text: fixture("django-blast-radius-query-depth1.json") };+ }+ return json(404, {});+ };+ return d;+}++const settle = () => new Promise((resolve) => setTimeout(resolve, 0));+async function until(check: () => boolean): Promise<void> {+ for (let i = 0; i < 200 && !check(); i++) await new Promise((resolve) => setTimeout(resolve, 5));+ expect(check()).toBe(true);+}+const band = { props: { hasSurvey: false, bodyColumns: 100 } };+const pane = (requestId = "lens", surface = "terminal") => ({+ surface,+ requestId,+ props: { bodyColumns: 180, placement: "dock", scroll: { bodyRows: 55 } },+});+const THEIRS = { el: "theirs" };++let hooks: Hooks;+beforeEach(async () => {+ hooks = await load();+});++describe("register, for the map", () => {+ it("an observer that cannot learn the cwd still returns the tool's result", async () => {+ const { $, calls } = fakeDollar();+ $.session.cwd = async () => {+ throw new Error("gone");+ };+ const marker = { result: {} };+ expect(await hooks["tool.call"]!($, { tool: "Read", file_path: "/a" }, async () => marker)).toBe(marker);+ await settle();+ expect(calls.logs).toEqual(["lens: cwd failed: Error: gone"]);+ });++ it("session.start registers /lens", async () => {+ const { $, calls } = fakeDollar();+ await hooks["session.start"]!($, {}, async () => undefined);+ expect(calls.commands).toEqual([+ { name: "lens", description: PANE_COPY.command, argumentHint: "[map | ask <question> | recap]", immediate: true },+ ]);+ });+});++type Full = ReturnType<typeof fullDollar>;+const START = { cwd: ROOT };+const editQuery = { tool: "Edit", tool_use_id: "toolu_9", file_path: `${ROOT}\\django\\db\\models\\query.py` };+const asked = (d: Full, part: string) => d.calls.http.filter((u) => u.includes(part)).length;+const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++async function started(d: Full = fullDollar()): Promise<Full> {+ await hooks["session.start"]!(d.$, START, async () => undefined);+ await until(() => asked(d, "/api/repos") > 0);+ await settle();+ return d;+}++async function opened(d: Full = fullDollar()): Promise<Full> {+ await started(d);+ await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({ text: "core" }));+ await until(() => asked(d, "/health/map?cap=4000") > 0);+ await settle();+ await settle();+ return d;+}++const render = async (d: Full) => (await hooks["ui.render:Pane"]!(d.$, pane(), async () => THEIRS)) as Tree;++describe("the map pane", () => {+ it("/lens opens the pane with the keyboard (it was asked for) and prints nothing", async () => {+ const d = await started();+ expect(await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({ text: "core" }))).toEqual({});+ expect(d.calls.open).toEqual([{ id: "lens", title: "Lens", rows: 29, focus: true }]);+ });++ it("/lens on a surface that cannot place the pane says why in one band line", async () => {+ const d = await started();+ d.$.ui.open = async () => ({ isPlaced: false, reason: "below 110 columns (90 now)" });+ await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({}));+ const shown = JSON.stringify(await hooks["ui.render:AbovePrompt"]!(d.$, band, async () => null));+ expect(shown).toContain("Lens map needs a wider terminal: below 110 columns (90 now)");+ });++ it("draws the Django map with a legend that counts what it drew", async () => {+ const d = await opened();+ const tree = await render(d);+ const r = flatten(tree).find((n) => n.el === "Raster")!;+ // The pane's 55 rows less the tab row and the legend.+ expect(r.props).toMatchObject({ key: "lens-map", columns: 180, rows: 48 });+ expect(r.props.cells).toHaveLength(180 * 48 * 16);+ expect(textOf(tree).some((t) => /^1,\d{3} of 2,970 files drawn at this size/.test(t))).toBe(true);+ });++ it("the desktop app gets the same map as SVG under the element's limit, and the same legend", async () => {+ const d = await opened();+ const tree = (await hooks["ui.render:Pane"]!(d.$, pane("lens", "desktop"), async () => THEIRS)) as Tree;+ const drawing = flatten(tree).find((n) => n.el === "Svg")!;+ expect(String(drawing.props.source).startsWith("<svg ")).toBe(true);+ expect(String(drawing.props.source).length).toBeLessThan(131_072);+ expect(drawing.props.alt).toMatch(/^Code health map: 1,\d{3} files drawn/);+ expect(flatten(tree).some((n) => n.el === "Raster")).toBe(false);+ expect(textOf(tree).some((t) => / of 2,970 files drawn at this size/.test(t))).toBe(true);+ });++ it("at rest nothing is asked of the server: no map, no importers, until /lens", async () => {+ const d = await started();+ await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));+ await wait(30);+ expect([asked(d, "/health/map"), asked(d, "/blast-radius")]).toEqual([0, 0]);+ // Asked for later, the map fetches the importers of the edit it missed.+ await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({}));+ await until(() => asked(d, "/blast-radius") === 1);+ });++ it("an edit fetches its direct importers once and ripples them in with blits", async () => {+ const d = await opened();+ await render(d);+ await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));+ await until(() => d.calls.blit.length >= 2);+ expect(d.calls.blit[0]).toMatchObject({ requestId: "lens", key: "lens-map", columns: 180, rows: 48 });+ const shown = textOf(await render(d));+ // At 180x48 one of the twelve is under a pixel: counted, not hidden.+ expect(shown).toContain("edited query.py · 12 files import it (from imports, not calls) · 1 not drawn");+ expect(shown).toContain("1 file read");+ expect(asked(d, "/blast-radius")).toBe(1);+ });++ it("observing a tool call waits on nothing once next(e) resolved", async () => {+ const d = await opened();+ d.$.session.cwd = () => new Promise(() => {});+ const out = { result: {} };+ expect(await hooks["tool.call"]!(d.$, editQuery, async () => out)).toBe(out);+ });++ it("drops the importers an earlier session asked for", async () => {+ const d = await opened();+ let release: () => void = () => {};+ const fetch = d.$.http.fetch;+ d.$.http.fetch = async (url, init) => {+ if (url.endsWith("/blast-radius")) await new Promise<void>((r) => (release = r));+ return fetch(url, init);+ };+ await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));+ await settle();+ await hooks["session.start"]!(d.$, START, async () => undefined);+ release();+ await wait(30);+ expect(textOf(await render(d)).some((t) => t.startsWith("edited"))).toBe(false);+ });++ it("one blit at a time: a surface that never answers gets no second frame", async () => {+ const d = await opened();+ await render(d);+ d.$.ui.blit = (args) => {+ d.calls.blit.push(args);+ return new Promise(() => {});+ };+ await hooks["tool.call"]!(d.$, { tool: "Glob", pattern: "*" }, async () => ({ result: { filenames: ["setup.py"] } }));+ await wait(150);+ expect(d.calls.blit).toHaveLength(1);+ });++ it("a blit the surface refuses stops the animation and redraws", async () => {+ const d = await opened();+ await render(d);+ d.$.ui.blit = async (args) => {+ d.calls.blit.push(args);+ return { deny: "another size" };+ };+ const before = d.calls.invalidate;+ await hooks["tool.call"]!(d.$, { tool: "Glob", pattern: "*" }, async () => ({ result: { filenames: ["setup.py"] } }));+ await until(() => d.calls.blit.length >= 1);+ await wait(100);+ expect(d.calls.blit).toHaveLength(1);+ expect(d.calls.invalidate).toBeGreaterThan(before + 1);+ });++ it("no ripple when there is nowhere to ripple to: an edit off the map", async () => {+ const d = await opened();+ await render(d);+ await hooks["tool.call"]!(d.$, { tool: "Write", file_path: `${ROOT}\\new_module.py` }, async () => ({ result: {} }));+ await until(() => asked(d, "/blast-radius") === 1);+ await wait(100);+ expect(d.calls.blit).toEqual([]);+ });++ it("with reduced motion, attention redraws the resting frame and never blits", async () => {+ const d = fullDollar();+ d.$.settings.read = async () => ({ prefersReducedMotion: true });+ await opened(d);+ await render(d);+ await hooks["tool.call"]!(d.$, { tool: "Grep", pattern: "x" }, async () => ({ result: { filenames: ["django/db/models/query.py"] } }));+ await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));+ await until(() => asked(d, "/blast-radius") === 1);+ await wait(120);+ expect(d.calls.blit).toEqual([]);+ expect(textOf(await render(d))).toContain("1 file read · last search matched 1 file");+ });++ it("an edit with no local server asks nothing of the network", async () => {+ const d = fakeDollar();+ await hooks["session.start"]!(d.$, { cwd: "/work/app" }, async () => undefined);+ await settle();+ await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({}));+ await hooks["tool.call"]!(d.$, { tool: "Edit", file_path: "/work/app/a.py" }, async () => ({ result: {} }));+ expect(d.calls.http).toEqual([]);+ });++ it("says why when there is no map: no local server, or another surface", async () => {+ const lite = fakeDollar();+ await hooks["session.start"]!(lite.$, {}, async () => undefined);+ await settle();+ const tree = (await hooks["ui.render:Pane"]!(lite.$, pane(), async () => THEIRS)) as Tree;+ expect(textOf(tree)).toEqual(["index this repo for Lens: repowise init --no-prose --yes"]);+ const vscode = (await hooks["ui.render:Pane"]!(lite.$, pane("lens", "vscode"), async () => THEIRS)) as Tree;+ expect(textOf(vscode)).toEqual([MAP_COPY.desktop]);+ });++ it("before discovery lands, the pane says it is looking", async () => {+ const { $ } = fakeDollar();+ expect(textOf((await hooks["ui.render:Pane"]!($, pane(), async () => THEIRS)) as Tree)).toEqual([MAP_COPY.looking]);+ });++ it("a failed health map says so, and /lens tries again", async () => {+ const d = fullDollar();+ const fetch = d.$.http.fetch;+ let mapCalls = 0;+ d.$.http.fetch = async (url, init) => {+ if (url.includes("/health/map") && ++mapCalls === 1) return json(500, { detail: "boom" });+ return fetch(url, init);+ };+ await started(d);+ await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({}));+ await until(() => mapCalls === 1);+ await settle();+ expect(textOf(await render(d))).toEqual([MAP_COPY.failed]);+ await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({}));+ await until(() => mapCalls === 2);+ });++ it("a render that throws hands the site back", async () => {+ const d = fakeDollar();+ d.$.ui.resolve = () => {+ throw new Error("no table");+ };+ expect(await hooks["ui.render:Pane"]!(d.$, pane(), async () => THEIRS)).toBe(THEIRS);+ expect(d.calls.logs).toEqual(["lens: pane render failed: Error: no table"]);+ });++ it("loaded mid-session: learns the cwd from the first call and observes from the next", async () => {+ const d = await started();+ await hooks["session.start"]!(d.$, {}, async () => undefined);+ await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({}));+ await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));+ await settle();+ await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));+ await until(() => asked(d, "/blast-radius") === 1);+ });+});++describe("auto-open", () => {+ const read = { tool: "Read", file_path: `${ROOT}\\django\\db\\models\\query.py` };++ async function start(options: PluginOptions, placed: boolean): Promise<Full> {+ hooks = await load(options);+ const d = fullDollar();+ d.$.ui.open = async (p) => {+ d.calls.open.push(p);+ return placed ? { isPlaced: true } : { isPlaced: false, reason: "below 144 columns" };+ };+ return started(d);+ }++ it("stays shut when the toggle is off", async () => {+ const d = await start({}, true);+ await hooks["tool.call"]!(d.$, read, async () => ({ result: {} }));+ expect(d.calls.open).toEqual([]);+ });++ it("opens on the first read when on and placed, once, and fetches the map", async () => {+ const d = await start({ lens_pane_autoopen: true }, true);+ await hooks["tool.call"]!(d.$, read, async () => ({ result: {} }));+ await hooks["tool.call"]!(d.$, read, async () => ({ result: {} }));+ // Never the keyboard: the person did not ask for it.+ expect(d.calls.open).toEqual([{ id: "lens", title: "Lens", rows: 29 }]);+ await until(() => asked(d, "/health/map") === 1);+ });++ it("never touches a pane the person opened with /lens", async () => {+ const d = await start({ lens_pane_autoopen: true }, false);+ await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({}));+ await hooks["tool.call"]!(d.$, read, async () => ({ result: {} }));+ await settle();+ expect(d.calls.open).toHaveLength(1);+ expect(d.calls.close).toEqual([]);+ });++ it("too narrow: closes the waiting pane and says so in one band line until the turn ends", async () => {+ const d = await start({ lens_pane_autoopen: true }, false);+ await hooks["tool.call"]!(d.$, read, async () => ({ result: {} }));+ await until(() => d.calls.close.length === 1);+ await settle();+ expect(JSON.stringify(await hooks["ui.render:AbovePrompt"]!(d.$, band, async () => null))).toContain(MAP_COPY.waiting);+ await hooks["turn.complete"]!(d.$, {}, async () => undefined);+ const after = await hooks["ui.render:AbovePrompt"]!(d.$, band, async () => null);+ expect(JSON.stringify(after ?? null)).not.toContain(MAP_COPY.waiting);+ });+});diff --git a/packages/claude-mod/test/map.test.ts b/packages/claude-mod/test/map.test.tsnew file mode 100644index 000000000..6a1d9d11a--- /dev/null+++ b/packages/claude-mod/test/map.test.ts@@ -0,0 +1,180 @@+import { describe, expect, it } from "vitest";+import { DARK, DARK_CANVAS } from "@repowise-dev/ui/brand";+import { scopeParts } from "../src/views/copy";+import {+ GROUND,+ colorForScore,+ encodeCells,+ groupKeys,+ labelText,+ layoutMap,+ mix,+ type MapFile,+ type MapLayout,+ type PlacedFile,+} from "../src/views/map";+import { decode, feed } from "./django";++/** Every pixel index a placed file owns. */+function pixelsOf(f: PlacedFile, width: number): number[] {+ const out: number[] = [];+ for (let y = f.py0; y < f.py1; y++) for (let x = f.px0; x < f.px1; x++) out.push(y * width + x);+ return out;+}++/** Which drawn file owns each pixel; throws if two claim one. */+function owners(layout: MapLayout): Int32Array {+ const grid = new Int32Array(layout.width * layout.height).fill(-1);+ for (const i of layout.drawn) {+ for (const p of pixelsOf(layout.files[i]!, layout.width)) {+ if (grid[p] !== -1) throw new Error(`pixel ${p} claimed twice`);+ grid[p] = i;+ }+ }+ return grid;+}++const distinctOwners = (layout: MapLayout) => new Set([...owners(layout)].filter((i) => i >= 0)).size;++describe("groupKeys", () => {+ it("splits a folder that would hold most of the map, judged on Django", () => {+ const keyed = groupKeys(feed.files);+ const keys = new Set(keyed);+ for (const k of ["django/db", "django/contrib", "tests/migrations", "scripts"]) expect(keys.has(k)).toBe(true);+ // What stays in `tests` is only the files directly in it.+ const direct = feed.files.filter((f) => f.file_path.split("/").length === 2 && f.file_path.startsWith("tests/"));+ expect(keyed.filter((k) => k === "tests")).toHaveLength(direct.length);+ });++ it("keeps root files and files directly in a split folder in their own group", () => {+ const files: MapFile[] = [+ { file_path: "README", score: null, nloc: 1 },+ { file_path: "a/x.py", score: 9, nloc: 50 },+ { file_path: "a/b/y.py", score: 9, nloc: 50 },+ { file_path: "a/c/z.py", score: 9, nloc: 50 },+ ];+ expect(groupKeys(files)).toEqual(["", "a", "a/b", "a/c"]);+ });++ it("leaves a heavy folder whole when splitting would not divide it", () => {+ const files: MapFile[] = [+ { file_path: "a/b/x.py", score: 9, nloc: 90 },+ { file_path: "c/y.py", score: 9, nloc: 10 },+ ];+ expect(groupKeys(files)).toEqual(["a", "c"]);+ });+});++describe("layoutMap on the Django feed at 180x50", () => {+ const layout = layoutMap(feed.files, 180, 50, true);+ const total = feed.files.reduce((s, f) => s + f.nloc, 0);+ const canvas = 180 * 100;++ it("places every file with lines, with areas proportional to lines and inside the canvas", () => {+ expect(layout.files).toHaveLength(feed.files.filter((f) => f.nloc > 0).length);+ for (const f of layout.files) {+ expect(f.rect.w * f.rect.h).toBeCloseTo((f.nloc / total) * canvas, 6);+ expect(f.rect.x + f.rect.w).toBeLessThanOrEqual(180 + 1e-6);+ expect(f.rect.y + f.rect.h).toBeLessThanOrEqual(100 + 1e-6);+ }+ for (const g of layout.groups) expect(g.rect.w * g.rect.h).toBeCloseTo((g.nloc / total) * canvas, 6);+ });++ it("no two files own one pixel, and only drawn files own any", () => {+ expect(distinctOwners(layout)).toBe(layout.drawn.length);+ expect(layout.drawn.length).toBeGreaterThan(1_000);+ expect(layout.drawn.length).toBeLessThanOrEqual(feed.shown);+ });++ it("is deterministic, whatever order the feed arrives in", () => {+ const again = layoutMap([...feed.files].reverse(), 180, 50, true);+ expect(again.files).toEqual(layout.files);+ expect(again.base).toEqual(layout.base);+ expect(again.labels).toEqual(layout.labels);+ });++ it("paints the ground and gutters, never the terminal's own background", () => {+ expect(GROUND).toBe(parseInt(DARK.bgRoot.slice(1), 16));+ expect([...layout.base].some((c) => c === GROUND)).toBe(true);+ expect([...layout.base].every((c) => c < 0x01000000)).toBe(true);+ });++ it("darkens the last column and row of a file big enough, so neighbours part", () => {+ const big = layout.files.find((f) => f.px1 - f.px0 >= 3 && f.py1 - f.py0 >= 3)!;+ const fill = colorForScore(big.score);+ expect(layout.base[big.py0 * 180 + big.px0]).toBe(fill);+ expect(layout.base[big.py0 * 180 + big.px1 - 1]).toBe(mix(fill, 0, 0.3));+ expect(layout.base[(big.py1 - 1) * 180 + big.px0]).toBe(mix(fill, 0, 0.3));+ });++ it("paints a missing score neutral", () => {+ expect(colorForScore(null)).toBe(parseInt(DARK_CANVAS.nodeNeutral.slice(1), 16));+ });++ it("labels wide groups inside their own cells, never two on one cell", () => {+ expect(layout.labels.map((l) => l.text)).toContain("django/db");+ const cells = layout.labels.flatMap((l) => [...l.text].map((_, k) => l.row * 180 + l.col + k));+ expect(new Set(cells).size).toBe(cells.length);+ });++ it("the legend counts exactly the files drawn", () => {+ const parts = scopeParts({ drawn: layout.drawn.length, repositoryTotal: feed.repository_total, indexed: "2h ago", beyondCap: 0, cap: 4_000 });+ expect(parts[0]).toBe(`${layout.drawn.length.toLocaleString("en-US")} of 2,970 files drawn at this size`);+ });+});++describe("labelText", () => {+ it("steps down from the folder to its last two segments to its last", () => {+ expect(labelText("tests/gis_tests/geoapp", 30)).toBe("tests/gis_tests/geoapp");+ expect(labelText("tests/gis_tests/geoapp", 18)).toBe("gis_tests/geoapp");+ expect(labelText("tests/gis_tests/geoapp", 8)).toBe("geoapp");+ expect(labelText("tests/gis_tests/geoapp", 3)).toBeNull();+ });++ it("refuses anything but printable ASCII, which is width 1 in every terminal", () => {+ expect(labelText("docs/日本語", 40)).toBeNull();+ expect(labelText("src/café", 40)).toBeNull();+ });+});++describe("a tiny canvas", () => {+ it("draws fewer files than it places, and counts only those", () => {+ const layout = layoutMap(feed.files, 12, 4, true);+ expect(layout.drawn.length).toBeLessThan(layout.files.length);+ expect(distinctOwners(layout)).toBe(layout.drawn.length);+ });++ it("four equal files fill a 4x2 canvas", () => {+ const files: MapFile[] = ["a/1", "a/2", "a/3", "a/4"].map((p) => ({ file_path: p, score: 9, nloc: 1 }));+ const layout = layoutMap(files, 4, 2, false);+ expect(layout.drawn).toHaveLength(4);+ expect([...layout.base].every((c) => c !== GROUND)).toBe(true);+ });+});++describe("cell encoding", () => {+ it("round-trips pixels through upper half blocks, labels aside", () => {+ const layout = { ...layoutMap(feed.files, 60, 20, true), labels: [] };+ const words = decode(encodeCells(layout, layout.base));+ expect(words).toHaveLength(60 * 20 * 3);+ for (let i = 0; i < 60 * 20; i++) {+ const [r, c] = [Math.floor(i / 60), i % 60];+ expect([words[i * 3], words[i * 3 + 1], words[i * 3 + 2]]).toEqual([0x2580, layout.base[2 * r * 60 + c], layout.base[(2 * r + 1) * 60 + c]]);+ }+ });++ it("writes a label whole on ground cells, or not at all when a mark covers any of its cells", () => {+ const layout = layoutMap(feed.files, 180, 50, true);+ const label = layout.labels[0]!;+ const text = (words: Uint32Array) => [...label.text].map((_, k) => String.fromCharCode(words[(label.row * 180 + label.col + k) * 3]!)).join("");+ expect(text(decode(encodeCells(layout, layout.base)))).toBe(label.text);+ const marked = new Uint8Array(layout.width * layout.height);+ marked[(2 * label.row + 1) * 180 + label.col + label.text.length - 1] = 1;+ expect(text(decode(encodeCells(layout, layout.base, marked)))).toBe("▀".repeat(label.text.length));+ });++ it("encodes a 180x50 frame to the documented size", () => {+ const layout = layoutMap(feed.files, 180, 50, true);+ expect(encodeCells(layout, layout.base)).toHaveLength(144_000);+ });+});diff --git a/packages/claude-mod/test/mapPane.test.ts b/packages/claude-mod/test/mapPane.test.tsnew file mode 100644index 000000000..8ce13f319--- /dev/null+++ b/packages/claude-mod/test/mapPane.test.ts@@ -0,0 +1,174 @@+import { describe, expect, it } from "vitest";+import { BRAND, DARK_CANVAS_BAND } from "@repowise-dev/ui/brand";+import { initialTrail, reduceTrail, type TrailState } from "../src/model/trail";+import { HINTS, MAP_COPY, callersLine, freshnessLine, notPlacedLine, readsLine, scopeParts } from "../src/views/copy";+import type { Node } from "../src/views/elements";+import { layoutMap } from "../src/views/map";+import { MAP_KEY, legendRows, mapPaneView, mapSize, noticeView, packRows } from "../src/views/mapPane";+import { frameCells, resolveOverlay } from "../src/views/overlay";+import { feed } from "./django";++function texts(node: Node): string[] {+ if (node.type === "Text") return [node.children.join("")];+ if (node.type === "Button") return [node.props.label];+ if (node.type !== "Box") return [];+ return node.children.flatMap(texts);+}++/** One row as drawn: a Text, or a row Box's items, each item's texts run together, items two apart. */+function line(node: Node): string {+ if (node.type !== "Box") return texts(node).join("");+ return node.children.map((c) => texts(c).join("")).join(" ".repeat(node.props.columnGap ?? 0));+}++function rows(node: Node): string[] {+ return node.type === "Box" ? node.children.map(line) : [];+}++const scope = { drawn: 1_639, repositoryTotal: 2_970, indexed: "2h ago", beyondCap: 0, cap: 4_000 };++describe("mapSize and legendRows", () => {+ it("docked: full width, the pane's rows less the legend at that width", () => {+ expect(legendRows(180)).toBe(6);+ expect(mapSize({ bodyColumns: 180, placement: "dock", bodyRows: 55 })).toEqual({ columns: 180, rows: 49 });+ });++ it("a narrow pane wraps the swatches and reserves the rows for them", () => {+ expect(legendRows(40)).toBe(9);+ expect(mapSize({ bodyColumns: 40, placement: "dock", bodyRows: 30 })).toEqual({ columns: 40, rows: 21 });+ });++ it("inline: a squat share of the width, capped", () => {+ expect(mapSize({ bodyColumns: 120, placement: "inline", bodyRows: 3 })).toEqual({ columns: 120, rows: 20 });+ expect(mapSize({ bodyColumns: 60, placement: "inline", bodyRows: 3 })).toEqual({ columns: 60, rows: 10 });+ });++ it("stays within the Raster's limits", () => {+ expect(mapSize({ bodyColumns: 900, placement: "dock", bodyRows: 900 })).toEqual({ columns: 512, rows: 256 });+ expect(mapSize({ bodyColumns: 0, placement: "dock", bodyRows: 2 })).toEqual({ columns: 1, rows: 4 });+ });++ it("packRows breaks before an item that would pass the width", () => {+ expect(packRows(["aaa", "bb", "cccc"], (s) => s.length, 7, 2)).toEqual([["aaa", "bb"], ["cccc"]]);+ expect(packRows([], (s: string) => s.length, 7, 2)).toEqual([]);+ });+});++describe("copy", () => {+ it("scope: all drawn, or how many at this size, then age and any cap", () => {+ expect(scopeParts({ ...scope, drawn: 2_914, repositoryTotal: 2_914 })).toEqual(["2,914 files, all drawn", "indexed 2h ago"]);+ expect(scopeParts({ ...scope, indexed: null, beyondCap: 1_200 })).toEqual([+ "1,639 of 2,970 files drawn at this size",+ "rest empty or too small",+ "1,200 beyond the 4,000-file cap",+ ]);+ });++ it("reads: nothing before the first, then reads, what was not drawn, and the last search", () => {+ const r = (count: number, notDrawn = 0, capped = false) => ({ count, capped, notDrawn });+ expect(readsLine(r(0), null)).toBeNull();+ expect(readsLine(r(1), null)).toBe("1 file read");+ expect(readsLine(r(8, 3), null)).toBe("8 files read · 3 not drawn");+ expect(readsLine(r(200, 0, true), 14)).toBe("200+ files read · last search matched 14 files");+ expect(readsLine(r(0), 0)).toBe("last search matched 0 files");+ });++ it("importers: loading, unavailable, found, some not drawn", () => {+ expect(callersLine("query.py", null, 0)).toBe("edited query.py · finding the files that import it");+ expect(callersLine("query.py", { status: "loading" }, 0)).toBe("edited query.py · finding the files that import it");+ expect(callersLine("query.py", { status: "failed" }, 0)).toBe("edited query.py · import graph unavailable");+ expect(callersLine("query.py", { status: "ready", paths: ["a"] }, 0)).toBe("edited query.py · 1 file imports it (from imports, not calls)");+ expect(callersLine("query.py", { status: "ready", paths: new Array(12).fill("x") }, 3)).toBe(+ "edited query.py · 12 files import it (from imports, not calls) · 3 not drawn",+ );+ });++ it("no em dash in anything Lens writes", () => {+ const all = [+ ...Object.values(HINTS),+ ...Object.values(MAP_COPY),+ notPlacedLine("below 110 columns (80 now)"),+ freshnessLine({ changedFiles: 3 }),+ ...scopeParts({ ...scope, beyondCap: 5 }),+ readsLine({ count: 3, capped: true, notDrawn: 1 }, 2),+ callersLine("a.py", { status: "ready", paths: ["b"] }, 1),+ callersLine("a.py", { status: "failed" }, 0),+ callersLine("a.py", null, 0),+ ];+ for (const line of all) expect(line).not.toMatch(/[\u2013\u2014]/);+ });+});++describe("mapPaneView", () => {+ const layout = layoutMap(feed.files, 120, 20, true);+ const root = "C:\\work\\django";+ const view = (t: TrailState, columns = 120, facts = scope) => {+ const resolved = resolveOverlay(layout, t, root);+ return mapPaneView({ ...layout, columns }, frameCells(layout, resolved.overlay), resolved, facts);+ };++ it("draws the Raster at the layout's size and the legend outside it, with every band word", () => {+ const tree = view(initialTrail);+ if (tree.type !== "Box") throw new Error("expected a Box");+ expect(tree.children[0]).toMatchObject({ type: "Raster", props: { key: MAP_KEY, columns: 120, rows: 20 } });+ expect(rows(tree)).toEqual([+ "",+ "■ At risk ■ Needs work ■ Fair ■ Good ■ Excellent ■ Not scored",+ "□ Claude read ◆ edited",+ "1,639 of 2,970 files drawn at this size · rest empty or too small · indexed 2h ago",+ ]);+ });++ it("colors swatches with the canvas band ramp and Claude's marks orange", () => {+ const json = JSON.stringify(view(initialTrail));+ expect(json).toContain(DARK_CANVAS_BAND.at_risk);+ expect(json).toContain(DARK_CANVAS_BAND.excellent);+ expect(json).toContain(BRAND.accent);+ });++ it("names the importer and match marks only when they are on the map, and states the trail", () => {+ let t = reduceTrail(initialTrail, { type: "read", path: "c:/work/django/django/db/models/base.py" });+ t = reduceTrail(t, { type: "read", path: "c:/elsewhere/x.py" });+ t = reduceTrail(t, { type: "search", paths: ["c:/work/django/django/db/models/base.py"] });+ t = reduceTrail(t, { type: "edit", path: "c:/work/django/django/db/models/query.py" });+ t = reduceTrail(t, { type: "callers", edits: 1, callers: { status: "ready", paths: ["django/db/models/base.py", "not/in/feed.py"] } });+ const shown = rows(view(t));+ expect(shown).toContain("□ Claude read ◆ edited · imports the edited file ▪ search match");+ expect(shown).toContain("3 files read · 1 not drawn · last search matched 1 file");+ expect(shown).toContain("edited query.py · 2 files import it (from imports, not calls) · 1 not drawn");+ });++ it("wraps the scope onto a second row when narrow, so the age survives", () => {+ const shown = rows(view(initialTrail, 50));+ expect(shown.slice(-2)).toEqual(["1,639 of 2,970 files drawn at this size", "rest empty or too small · indexed 2h ago"]);+ });++ it("at 60 columns the edit and reads rows keep every count, in a short form", () => {+ let t = reduceTrail(initialTrail, { type: "read", path: "c:/elsewhere/x.py" });+ t = reduceTrail(t, { type: "search", paths: ["c:/work/django/django/db/models/base.py"] });+ t = reduceTrail(t, { type: "edit", path: "c:/work/django/django/db/models/query.py" });+ const paths = ["django/db/models/base.py", ...Array.from({ length: 10 }, (_, i) => `not/in/feed${i}.py`)];+ t = reduceTrail(t, { type: "callers", edits: 1, callers: { status: "ready", paths } });+ const shown = rows(view(t, 60));+ expect(shown).toContain("edited query.py · 11 import it · 10 not drawn");+ expect(shown).toContain("2 files read · 1 not drawn · last search matched 1 file");+ const long = callersLine("a_very_long_module_name_that_goes_on_and_on.py", { status: "ready", paths }, 10, 40);+ expect(long).toMatch(/· 11 import it · 10 not drawn$/);+ expect(long.length).toBeLessThanOrEqual(40);+ expect(readsLine({ count: 200, capped: true, notDrawn: 1_234 }, 1_204, 60)).toBe("200+ read · 1,234 not drawn · search matched 1,204");+ });++ it("at 60 columns the cap clause survives; the rest note and the age leave first", () => {+ const capped = { ...scope, drawn: 1_500, repositoryTotal: 8_281, beyondCap: 4_281 };+ const shown = rows(view(initialTrail, 60, capped));+ expect(shown.slice(-2)).toEqual(["1,500 of 8,281 files drawn at this size · indexed 2h ago", "4,281 beyond the 4,000-file cap"]);+ expect(rows(view(initialTrail, 45, capped)).slice(-2)).toEqual(["1,500 of 8,281 files drawn at this size", "4,281 beyond the 4,000-file cap"]);+ expect(rows(view(initialTrail, 120, capped)).at(-1)).toBe(+ "1,500 of 8,281 files drawn at this size · rest empty or too small · indexed 2h ago · 4,281 beyond the 4,000-file cap",+ );+ });++ it("noticeView is one dim line, fitted", () => {+ expect(texts(noticeView(MAP_COPY.loading, 20))).toEqual(["Lens map: loading t…"]);+ });+});diff --git a/packages/claude-mod/test/mapSvg.test.ts b/packages/claude-mod/test/mapSvg.test.tsnew file mode 100644index 000000000..75206baec--- /dev/null+++ b/packages/claude-mod/test/mapSvg.test.ts@@ -0,0 +1,69 @@+// The desktop map over the recorded Django health-map feed (test/django.ts).+import { describe, expect, it } from "vitest";+import { DARK_CANVAS_BAND } from "@repowise-dev/ui/brand";+import { initialTrail, reduceTrail, type TrailState } from "../src/model/trail";+import { GROUND, layoutMap } from "../src/views/map";+import { mapSize } from "../src/views/mapPane";+import { SVG_CHARS, desktopSize, mapSvg, svgPaneView } from "../src/views/mapSvg";+import { framePixels, resolveOverlay } from "../src/views/overlay";+import { feed, importers } from "./django";++const ROOT = "C:\\work\\django";+const scope = { drawn: 0, repositoryTotal: feed.repository_total, indexed: null, beyondCap: 0, cap: 4_000 };++/** The busiest trail the model keeps: 200 reads, a search, and an edit with its importers. */+function busy(): TrailState {+ let t = initialTrail;+ for (const f of feed.files.slice(0, 260)) t = reduceTrail(t, { type: "read", path: `c:/work/django/${f.file_path}`.toLowerCase() });+ t = reduceTrail(t, { type: "search", paths: feed.files.slice(300, 400).map((f) => `c:/work/django/${f.file_path}`.toLowerCase()) });+ t = reduceTrail(t, { type: "edit", path: "c:/work/django/django/db/models/query.py" });+ return reduceTrail(t, { type: "callers", edits: t.edits, callers: { status: "ready", paths: importers } });+}++describe("desktop map", () => {+ const size = desktopSize(mapSize({ bodyColumns: 400, placement: "dock", bodyRows: 200 }));+ const layout = layoutMap(feed.files, size.columns, size.rows, true);++ it("caps the size, and stays under the Svg limit on the Django feed, at rest and with the busiest trail", () => {+ expect(size).toEqual({ columns: 160, rows: 45 });+ expect(mapSvg(layout, resolveOverlay(layout, initialTrail, ROOT)).length).toBeLessThan(SVG_CHARS);+ expect(mapSvg(layout, resolveOverlay(layout, busy(), ROOT)).length).toBeLessThan(SVG_CHARS);+ expect(desktopSize({ columns: 80, rows: 20 })).toEqual({ columns: 80, rows: 20 });+ });++ it("draws the terminal's resting frame: every non-ground pixel of it, once, in its color", () => {+ const resolved = resolveOverlay(layout, busy(), ROOT);+ const source = mapSvg(layout, resolved);+ const { pixels } = framePixels(layout, resolved.overlay);+ const counted = new Map<string, number>();+ for (const [, color, d] of source.matchAll(/<path stroke="(#[0-9a-f]{6})" d="([^"]+)"\/>/g)) {+ const n = [...d!.matchAll(/h(\d+)/g)].reduce((sum, m) => sum + Number(m[1]), 0);+ counted.set(color!, (counted.get(color!) ?? 0) + n);+ }+ const expected = new Map<string, number>();+ for (const p of pixels) {+ if (p !== GROUND) expected.set(`#${p.toString(16).padStart(6, "0")}`, (expected.get(`#${p.toString(16).padStart(6, "0")}`) ?? 0) + 1);+ }+ expect(counted).toEqual(expected);+ expect(source).toContain(DARK_CANVAS_BAND.good.toLowerCase());+ });++ it("is deterministic, labels its groups as text, and escapes them", () => {+ const resolved = resolveOverlay(layout, initialTrail, ROOT);+ expect(mapSvg(layout, resolved)).toBe(mapSvg(layout, resolved));+ expect(mapSvg(layout, resolved)).toMatch(/<text x="\d+" y="[\d.]+">django\//);+ const odd = { ...layout, labels: [{ row: 0, col: 0, text: "a<b&c" }] };+ expect(mapSvg(odd, resolved)).toContain("<text x=\"0\" y=\"1.6\">a<b&c</text>");+ });++ it("the pane: the drawing with its alt text over the legend; a drawing over the limit says so instead", () => {+ const resolved = resolveOverlay(layout, initialTrail, ROOT);+ const view = svgPaneView(layout, resolved, { ...scope, drawn: layout.drawn.length });+ if (view.type !== "Box") throw new Error("expected a Box");+ expect(view.children[0]).toMatchObject({ type: "Svg", props: { alt: expect.stringMatching(/^Code health map: [\d,]+ files drawn/) } });+ const huge = layoutMap(feed.files, 512, 256, true);+ const over = svgPaneView(huge, resolveOverlay(huge, busy(), ROOT), scope);+ if (over.type !== "Box") throw new Error("expected a Box");+ expect(over.children[0]).toMatchObject({ type: "Text", children: ["Lens map has too much detail to draw here; the terminal map shows it"] });+ });+});diff --git a/packages/claude-mod/test/margin.test.ts b/packages/claude-mod/test/margin.test.tsnew file mode 100644index 000000000..da9bee578--- /dev/null+++ b/packages/claude-mod/test/margin.test.ts@@ -0,0 +1,143 @@+import { describe, expect, it } from "vitest";+import { EDIT_TOOLS, notesFromAugment } from "../src/model/events";+import { initialSession, reduce, type MarginNote, type SessionState } from "../src/model/session";+import { marginLine } from "../src/views/copy";+import { marginView, MAX_MARGIN_LINES } from "../src/views/margin";+import { fixture, golden } from "./fake-host";++interface RecordedEvent {+ tool_name: string;+ tool_use_id: string;+ tool_input: unknown;+ result: { additionalContext?: string[] };+}++/**+ * A real session on a copy of this repository (one of the fastest-moving+ * indexed repos: hundreds of files fixed in the last 6 months, hundreds of+ * mined decisions): 20 of Claude's tool calls (8 edits of bug-fix-heavy and+ * decision-governed files) and Lens's own 8 lookups, recorded from+ * `classic.PostToolUse` with the plugin's augment hook running.+ */+const SESSION = JSON.parse(fixture("replay/repowise-edit-session.json")) as RecordedEvent[];++/** Replays the session through the same steps register.ts takes. */+function replay(events: RecordedEvent[]): SessionState {+ let state = initialSession;+ for (const e of events) {+ if (!EDIT_TOOLS.has(e.tool_name) || e.tool_use_id.startsWith("toolu_plugin_")) continue;+ state = reduce(state, { type: "notesFor", id: e.tool_use_id, notes: notesFromAugment(e.result.additionalContext) });+ }+ return state;+}++describe("margin notes over a recorded session", () => {+ it("is the session it claims to be", () => {+ const claude = SESSION.filter((e) => !e.tool_use_id.startsWith("toolu_plugin_"));+ expect(claude).toHaveLength(20);+ expect(claude.filter((e) => EDIT_TOOLS.has(e.tool_name))).toHaveLength(8);+ expect(SESSION.filter((e) => e.tool_use_id.startsWith("toolu_plugin_"))).toHaveLength(8);+ });++ it("shows at most three notes, each under the edit the hook flagged", () => {+ const state = replay(SESSION);+ const flagged = Object.keys(state.notes);+ expect(flagged.length).toBeLessThanOrEqual(3);+ expect(flagged).toEqual(["toolu_01P77H3c1LrnnZBi8MTE2LvR", "toolu_01RQU8ACcXBE7y2MqQFUiYXW", "toolu_018jYGKirRfgW3qFpfn18zGJ"]);+ for (const id of flagged) {+ const e = SESSION.find((x) => x.tool_use_id === id)!;+ expect(e.tool_name).toBe("Edit");+ expect(e.result.additionalContext?.length).toBeGreaterThan(0);+ }+ });++ it("draws exactly what the hook emitted, in Lens's words", () => {+ const state = replay(SESSION);+ const drawn = Object.values(state.notes).map((notes) => notes.map(marginLine));+ expect(drawn).toEqual([+ [+ "a decision found in this file, not yet reviewed: Configure languages declaratively in queries and language configs",+ "fixed 42 times in 6 months, most recently today, mostly in parse_file",+ ],+ [+ "a decision found in this file, not yet reviewed: Propagate maximum complexity to symbols",+ "fixed 39 times in 6 months, most recently today, mostly in analyze",+ ],+ [+ "a decision found in this file, not yet reviewed: Share one identifier shape for absence scans",+ "fixed 53 times in 6 months, most recently today, mostly in _member_is_used",+ ],+ ]);+ });++ it("ignores Lens's own lookups even when a hook adds context to them", () => {+ const own = SESSION.find((e) => e.tool_use_id.startsWith("toolu_plugin_"))!;+ const loud = { ...own, tool_name: "Edit", result: SESSION.find((e) => e.result.additionalContext)!.result };+ expect(Object.keys(replay([loud]).notes)).toEqual([]);+ });+});++describe("notesFromAugment", () => {+ it("reads every notice the hook's real formatters write (golden lines shared with the Python test)", () => {+ const [standingLine, minedLine, fixLine] = golden("augment-edit-notices.txt").split("\n").map((l) => l.trimEnd());+ expect(notesFromAugment([standingLine])).toEqual([{ kind: "decision", reviewed: true, title: "Use JWT auth" }]);+ expect(notesFromAugment([minedLine])).toEqual([+ { kind: "decision", reviewed: false, title: "Keep the parser allocation-free" },+ ]);+ expect(notesFromAugment([fixLine])).toEqual([{ kind: "fixes", count: 5, age: "2 weeks ago", symbol: "run_pipeline" }]);+ });++ const standing = "[repowise] a.py is governed by a standing decision: Keep the cache bounded because memory is finite (confirmed across 3 sessions).";++ it("reads a standing decision without its rationale or confirmation tail", () => {+ expect(notesFromAugment([standing])).toEqual([{ kind: "decision", reviewed: true, title: "Keep the cache bounded" }]);+ });++ it("reads a fix history with no symbol and no bug-magnet tail", () => {+ expect(notesFromAugment(["[repowise] a.py has been bug-fixed 3x in the last 6 months, last 2 weeks ago."])).toEqual([+ { kind: "fixes", count: 3, age: "2 weeks ago", symbol: null },+ ]);+ });++ it("keeps one note of each kind, across every hook's entry", () => {+ const fix = "[repowise] a.py has been bug-fixed 4x in the last 6 months, last yesterday; mostly in f.";+ const notes = notesFromAugment([standing, `${fix}\r\n${standing}`, fix]);+ expect(notes.map((n) => n.kind)).toEqual(["decision", "fixes"]);+ });++ it("ignores every other notice and anything that is not a hook's text", () => {+ const skeleton = "[repowise] You have only seen a.py as a skeleton this session — its bodies were elided.";+ expect(notesFromAugment([skeleton, "unrelated hook output", 42])).toEqual([]);+ expect(notesFromAugment(undefined)).toEqual([]);+ expect(notesFromAugment("[repowise] a.py has been bug-fixed 3x in the last 6 months, last today.")).toEqual([]);+ });+});++describe("margin view", () => {+ const decision: MarginNote = { kind: "decision", reviewed: true, title: "Keep the cache bounded" };+ const fixes: MarginNote = { kind: "fixes", count: 1, age: "yesterday", symbol: null };++ it("frames history as help, always with its age", () => {+ expect(marginLine(decision)).toBe("a standing decision covers this file: Keep the cache bounded");+ expect(marginLine(fixes)).toBe("fixed 1 time in 6 months, most recently yesterday");+ });++ it("is nothing without notes, and at most two dim lines", () => {+ expect(marginView(undefined)).toBeNull();+ expect(marginView([])).toBeNull();+ const tree = marginView([decision, fixes, decision]);+ expect(tree).toEqual({+ type: "Box",+ props: { key: "lens-margin", flexDirection: "column" },+ children: [+ { type: "Text", props: { dimColor: true, wrap: "truncate-end" }, children: [` ${marginLine(decision)}`] },+ { type: "Text", props: { dimColor: true, wrap: "truncate-end" }, children: [` ${marginLine(fixes)}`] },+ ],+ });+ expect(MAX_MARGIN_LINES).toBe(2);+ });++ it("an edit with nothing flagged leaves the state as it was", () => {+ expect(reduce(initialSession, { type: "notesFor", id: "x", notes: [] })).toBe(initialSession);+ });+});diff --git a/packages/claude-mod/test/mcp.test.ts b/packages/claude-mod/test/mcp.test.tsnew file mode 100644index 000000000..f4e136a81--- /dev/null+++ b/packages/claude-mod/test/mcp.test.ts@@ -0,0 +1,198 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ callTool,+ fetchFileContext,+ isOwnLensCall,+ LENS_TOOLS,+ mcpReady,+ PLUGIN_NAME,+ resetMcp,+ toolName,+ warmMcp,+} from "../src/data/mcp";+import type { McpToolResult } from "../src/mod-api";+import { fakeHost, fixture, mcpResult } from "./fake-host";++/** Recorded through Lens in a real session on the requests index. */+const sessions = JSON.parse(fixture("mcp/get_context-sessions.json")) as McpToolResult;+const models = JSON.parse(fixture("mcp/get_context-models.json")) as McpToolResult;++beforeEach(() => resetMcp());+afterEach(() => vi.useRealTimers());++/** Resolves the server name the way a session does, before any call. */+async function warmed(host: ReturnType<typeof fakeHost>): Promise<typeof host> {+ warmMcp(host);+ await new Promise((resolve) => setTimeout(resolve, 0));+ return host;+}++describe("mcpReady", () => {+ it("waits for the server name, then says whether it resolved", async () => {+ expect(await mcpReady(fakeHost())).toBe(true);+ expect(await mcpReady(fakeHost())).toBe(true);+ resetMcp();+ expect(await mcpReady(fakeHost({ connected: false }))).toBe(false);+ });++ it("gives up on a server that never answers, after its timeout", async () => {+ const host = fakeHost();+ host.mcp.server = () => new Promise(() => undefined);+ expect(await mcpReady(host, 10)).toBe(false);+ });+});++describe("callTool", () => {+ it("calls the server under the name the engine resolved, and returns `result`", async () => {+ const host = await warmed(fakeHost({ server: "plugin_repowise_repowise", mcp: () => mcpResult({ ok: 1 }) }));+ expect(await callTool(host, "get_context", { targets: ["a.py"] })).toEqual({ ok: 1 });+ expect(host.calls.mcp).toEqual([{ server: "plugin_repowise_repowise", tool: "get_context", args: { targets: ["a.py"] } }]);+ });++ it("starts the call synchronously, inside the caller's hook", async () => {+ const host = await warmed(fakeHost({ mcp: () => new Promise<McpToolResult>(() => undefined) }));+ void callTool(host, "get_context", {}).catch(() => undefined);+ expect(host.calls.mcp).toHaveLength(1);+ });++ it("never starts a call before the name is resolved: it rejects and starts resolving", async () => {+ const host = fakeHost({ mcp: () => mcpResult({}) });+ await expect(callTool(host, "get_context", {})).rejects.toThrow("not resolved yet");+ expect(host.calls.mcp).toEqual([]);+ expect(host.calls.connect).toBe(1);+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(await callTool(host, "get_context", {})).toEqual({});+ });++ it("resolves the server name once per session", async () => {+ const host = await warmed(fakeHost({ mcp: () => mcpResult({}) }));+ warmMcp(host);+ await callTool(host, "get_context", {});+ expect(host.calls.connect).toBe(1);+ resetMcp();+ await warmed(host);+ expect(host.calls.connect).toBe(2);+ });++ it("asks again after the server did not connect", async () => {+ const host = await warmed(fakeHost({ connected: false }));+ await expect(callTool(host, "get_context", {})).rejects.toThrow("not resolved yet");+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(host.calls.connect).toBe(2);+ expect(host.calls.mcp).toEqual([]);+ });++ it("never calls a server that is not this plugin's, even when connect names it", async () => {+ const host = await warmed(fakeHost({ server: "repowise", mcp: () => mcpResult({}) }));+ await expect(callTool(host, "get_context", {})).rejects.toThrow("not resolved yet");+ expect(host.calls.mcp).toEqual([]);+ });++ it("reads a bare result the way a plain MCP client sees it", async () => {+ const host = await warmed(+ fakeHost({ mcp: () => ({ content: [{ type: "text", text: JSON.stringify({ targets: {} }) }], isError: false }) }),+ );+ expect(await callTool(host, "get_context", {})).toEqual({ targets: {} });+ });++ it("rejects a tool error with its text", async () => {+ const host = await warmed(fakeHost({ mcp: () => mcpResult("bad target", true) }));+ await expect(callTool(host, "get_context", {})).rejects.toThrow('get_context failed: "bad target"');+ });++ it("rejects a result with no text block", async () => {+ const host = await warmed(fakeHost({ mcp: () => ({ content: [], isError: false }) }));+ await expect(callTool(host, "get_context", {})).rejects.toThrow("get_context returned no text");+ });++ it("does not retry a failed call", async () => {+ const host = await warmed(+ fakeHost({+ mcp: () => {+ throw new Error('no connected MCP tool "get_context"');+ },+ }),+ );+ await expect(callTool(host, "get_context", {})).rejects.toThrow("no connected MCP tool");+ expect(host.calls.mcp).toHaveLength(1);+ });++ it("times out", async () => {+ const host = await warmed(fakeHost({ mcp: () => new Promise<McpToolResult>(() => undefined) }));+ vi.useFakeTimers();+ const call = callTool(host, "get_context", {}, { timeoutMs: 50 });+ const settled = expect(call).rejects.toThrow("get_context timed out after 50 ms");+ await vi.advanceTimersByTimeAsync(60);+ await settled;+ });+});++describe("fetchFileContext", () => {+ it("reads caller files and contributors from a recorded card", async () => {+ const host = await warmed(fakeHost({ mcp: () => sessions }));+ expect(await fetchFileContext(host, "src/requests/sessions.py")).toEqual({ callerFiles: 3, contributors: 6 });+ expect(host.calls.mcp[0]?.args).toEqual({ targets: ["src/requests/sessions.py"], include: ["callers", "ownership"] });+ });++ it("counts every caller file when the list was capped", async () => {+ const host = await warmed(+ fakeHost({+ mcp: () => mcpResult({ targets: { "q.py": { callers: [{}, {}], callers_total: 41, ownership: { contributor_count: 3 } } } }),+ }),+ );+ expect(await fetchFileContext(host, "q.py")).toEqual({ callerFiles: 41, contributors: 3 });+ });++ it("keeps an unreported count unknown rather than zero", async () => {+ const host = await warmed(fakeHost({ mcp: () => mcpResult({ targets: { "q.py": { type: "file" } } }) }));+ expect(await fetchFileContext(host, "q.py")).toEqual({ callerFiles: null, contributors: null });+ });++ it("is null for a file the index does not know", async () => {+ const host = await warmed(fakeHost({ mcp: () => mcpResult({ targets: { "x.py": { error: "Target not found: 'x.py'" } } }) }));+ expect(await fetchFileContext(host, "x.py")).toBeNull();+ resetMcp();+ expect(await fetchFileContext(await warmed(fakeHost({ mcp: () => models })), "elsewhere.py")).toBeNull();+ });+});++describe("isOwnLensCall", () => {+ const own = { tool: "mcp__plugin_repowise_repowise__get_context", tool_use_id: "toolu_plugin_ab12" };++ it("approves Lens's own call to an allowlisted tool on this plugin's server", () => {+ expect(isOwnLensCall(own, PLUGIN_NAME)).toBe(true);+ });++ it("refuses a call another plugin made, or the engine", () => {+ expect(isOwnLensCall(own, "other-plugin")).toBe(false);+ expect(isOwnLensCall(own, "engine")).toBe(false);+ expect(isOwnLensCall(own, undefined)).toBe(false);+ });++ it("refuses Claude's own call to the same tool, and a query with no call id", () => {+ expect(isOwnLensCall({ ...own, tool_use_id: "toolu_01abc" }, PLUGIN_NAME)).toBe(false);+ expect(isOwnLensCall({ tool: own.tool }, PLUGIN_NAME)).toBe(false);+ });++ it("refuses a tool outside the allowlist, or on another server", () => {+ expect(isOwnLensCall({ ...own, tool: "mcp__plugin_repowise_repowise__get_dead_code" }, PLUGIN_NAME)).toBe(false);+ expect(isOwnLensCall({ ...own, tool: "mcp__evil__get_context" }, PLUGIN_NAME)).toBe(false);+ expect(isOwnLensCall({ ...own, tool: "Bash" }, PLUGIN_NAME)).toBe(false);+ });++ it("approves both forms of this plugin's server and never a name connect resolved to elsewhere", async () => {+ expect(isOwnLensCall({ ...own, tool: toolName("plugin:repowise:repowise", "get_context") }, PLUGIN_NAME)).toBe(true);+ await warmed(fakeHost({ server: "repowise" }));+ expect(isOwnLensCall({ ...own, tool: toolName("repowise", "get_context") }, PLUGIN_NAME)).toBe(false);+ });++ it("allowlists only the tools a shipped feature calls", () => {+ expect(LENS_TOOLS).toEqual(["get_context", "get_change_risk", "get_why", "get_answer"]);+ expect(isOwnLensCall({ ...own, tool: "mcp__plugin_repowise_repowise__get_why" }, PLUGIN_NAME)).toBe(true);+ expect(isOwnLensCall({ ...own, tool: "mcp__plugin_repowise_repowise__get_answer" }, PLUGIN_NAME)).toBe(true);+ });++ it("spells a server's tools the way tool.check names them", () => {+ expect(toolName("plugin:repowise:repowise", "get_context")).toBe("mcp__plugin_repowise_repowise__get_context");+ });+});diff --git a/packages/claude-mod/test/overlay.test.ts b/packages/claude-mod/test/overlay.test.tsnew file mode 100644index 000000000..e58075eab--- /dev/null+++ b/packages/claude-mod/test/overlay.test.ts@@ -0,0 +1,151 @@+import { describe, expect, it } from "vitest";+import { initialTrail, reduceTrail, type TrailState } from "../src/model/trail";+import { ACCENT, GROUND, layoutMap, mix, type MapLayout, type PlacedFile } from "../src/views/map";+import { EDIT_TINT, frameCells, framePixels, resolveOverlay, rippleRadius } from "../src/views/overlay";+import { feed, importers } from "./django";++const ROOT = "C:\\Users\\dev\\django";+const ROOT_KEY = "c:/users/dev/django";+const QUERY = "django/db/models/query.py";+const layout = layoutMap(feed.files, 180, 50, true);++/** The trail after reading these repo files in order, then editing one. */+function session(reads: string[], edit?: string): TrailState {+ let t = initialTrail;+ for (const r of reads) t = reduceTrail(t, { type: "read", path: `${ROOT_KEY}/${r}` });+ if (edit !== undefined) t = reduceTrail(t, { type: "edit", path: `${ROOT_KEY}/${edit}` });+ return t;+}++const withImporters = (t: TrailState) => reduceTrail(t, { type: "callers", edits: t.edits, callers: { status: "ready", paths: importers } });++function centerOf(l: MapLayout, i: number): number {+ const f = l.files[i]!;+ return Math.floor((f.py0 + f.py1 - 1) / 2) * l.width + Math.floor((f.px0 + f.px1 - 1) / 2);+}++const at = (f: PlacedFile, x: number, y: number) => y * layout.width + x;++describe("resolveOverlay", () => {+ const edited = withImporters(session(["django/db/models/base.py", "django/db/models/manager.py"], QUERY));+ const resolved = resolveOverlay(layout, edited, ROOT);++ it("the importer count shown equals the count fetched: drawn plus not drawn", () => {+ expect(importers).toHaveLength(12);+ expect(resolved.overlay.callers.length + resolved.edit!.notDrawn).toBe(importers.length);+ expect(resolved.edit!.name).toBe("query.py");+ });++ it("maps reads case-insensitively under the root and counts the rest as not drawn", () => {+ const t = reduceTrail(edited, { type: "read", path: "c:/elsewhere/notes.md" });+ const r = resolveOverlay(layout, t, ROOT);+ expect(r.overlay.reads).toHaveLength(3);+ expect(r.reads).toEqual({ count: 4, capped: false, notDrawn: 1 });+ });++ it("reports what the last search matched, drawn or not", () => {+ expect(resolveOverlay(layout, initialTrail, ROOT).matched).toBeNull();+ const t = reduceTrail(initialTrail, { type: "search", paths: [`${ROOT_KEY}/${QUERY}`, "c:/elsewhere/x.py"] });+ const r = resolveOverlay(layout, t, ROOT);+ expect(r.matched).toBe(2);+ expect(r.overlay.hits).toHaveLength(1);+ });++ it("is quiet before any attention", () => {+ const r = resolveOverlay(layout, initialTrail, ROOT);+ expect(r.edit).toBeNull();+ expect(framePixels(layout, r.overlay).pixels).toEqual(layout.base);+ });+});++describe("frames", () => {+ const edited = withImporters(session(["django/db/models/base.py", "django/db/models/manager.py"], QUERY));+ const { overlay } = resolveOverlay(layout, edited, ROOT);+ const rest = framePixels(layout, overlay).pixels;++ it("outlines a read in orange and dims its inside", () => {+ const f = layout.files[overlay.reads[0]!]!;+ expect(rest[at(f, f.px0, f.py0)]).toBe(ACCENT);+ const inside = at(f, f.px0 + 1, f.py0 + 1);+ expect(rest[inside]).toBe(mix(layout.base[inside]!, 0, 0.4));+ });++ it("fills the edited file pale orange inside an orange outline", () => {+ const q = layout.files[overlay.edited!]!;+ expect(rest[at(q, q.px0, q.py0)]).toBe(ACCENT);+ expect(rest[at(q, q.px0 + 1, q.py0 + 1)]).toBe(EDIT_TINT);+ });++ it("dots each importer with a dark companion pixel in its cell", () => {+ for (const i of overlay.callers) {+ const c = centerOf(layout, i);+ const y = Math.floor(c / layout.width);+ expect(rest[c]).toBe(ACCENT);+ expect(rest[(y ^ 1) * layout.width + (c % layout.width)]).toBe(GROUND);+ }+ });++ it("the ripple reaches importers as it passes and rests with every one dotted", () => {+ const dotted = (t: number) =>+ overlay.callers.filter((i) => framePixels(layout, overlay, { kind: "ripple", t }).pixels[centerOf(layout, i)] === ACCENT).length;+ const counts = [0, 0.25, 0.5, 0.75, 1].map(dotted);+ expect(counts[0]).toBeLessThan(overlay.callers.length);+ for (let k = 1; k < counts.length; k++) expect(counts[k]!).toBeGreaterThanOrEqual(counts[k - 1]!);+ expect(counts[4]).toBe(overlay.callers.length);+ expect(frameCells(layout, overlay, { kind: "ripple", t: 1 })).toBe(frameCells(layout, overlay));+ });++ it("draws a ring mid-ripple that is gone at rest", () => {+ const mid = framePixels(layout, overlay, { kind: "ripple", t: 0.5 }).pixels;+ expect(mid.filter((c, i) => c !== rest[i]).length).toBeGreaterThan(overlay.callers.length);+ });++ it("a search flashes, then settles to a faint tint", () => {+ const t = reduceTrail(initialTrail, { type: "search", paths: [`${ROOT_KEY}/${QUERY}`] });+ const r = resolveOverlay(layout, t, ROOT).overlay;+ const c = centerOf(layout, r.hits[0]!);+ expect(framePixels(layout, r, { kind: "flash", t: 0 }).pixels[c]).toBe(mix(layout.base[c]!, ACCENT, 0.85));+ expect(framePixels(layout, r, { kind: "flash", t: 1 }).pixels[c]).toBe(mix(layout.base[c]!, ACCENT, 0.25));+ expect(framePixels(layout, r).pixels[c]).toBe(mix(layout.base[c]!, ACCENT, 0.25));+ });++ it("nothing to ripple to: radius 0, whether the edit is off the map or has no importers", () => {+ const off = resolveOverlay(layout, withImporters(session([], "setup.py")), ROOT).overlay;+ expect(off.edited).toBeNull();+ expect(rippleRadius(layout, off)).toBe(0);+ const lonely = reduceTrail(session([], QUERY), { type: "callers", edits: 1, callers: { status: "ready", paths: [] } });+ expect(rippleRadius(layout, resolveOverlay(layout, lonely, ROOT).overlay)).toBe(0);+ expect(rippleRadius(layout, overlay)).toBeGreaterThan(3);+ });++ it("an edit off the map still dots its importers", () => {+ const off = resolveOverlay(layout, withImporters(session([], "setup.py")), ROOT).overlay;+ const pixels = framePixels(layout, off, { kind: "ripple", t: 0 }).pixels;+ expect(off.callers.every((c) => pixels[centerOf(layout, c)] === ACCENT)).toBe(true);+ });++ it("a small edited file is all pale, unlike a small read", () => {+ const small = layout.drawn.map((i) => layout.files[i]!).find((f) => f.px1 - f.px0 < 3 && f.path.startsWith("django/"))!;+ const rel = small.path;+ const asEdit = resolveOverlay(layout, session([], rel), ROOT).overlay;+ const asRead = resolveOverlay(layout, session([rel]), ROOT).overlay;+ const p = at(small, small.px0, small.py0);+ expect(framePixels(layout, asEdit).pixels[p]).toBe(EDIT_TINT);+ expect(framePixels(layout, asRead).pixels[p]).toBe(ACCENT);+ });+});++describe("performance", () => {+ // The budget is 16 ms per frame at 180x50 (npm run bench:map measures it);+ // this guard fails only at five times that, to stay steady under CI load.+ it("lays out Django and encodes a ripple frame within 5x the frame budget", () => {+ const trail = withImporters(session(["django/db/models/base.py"], QUERY));+ const runs = 10;+ const start = performance.now();+ for (let k = 0; k < runs; k++) {+ const l = layoutMap(feed.files, 180, 50, true);+ frameCells(l, resolveOverlay(l, trail, ROOT).overlay, { kind: "ripple", t: 0.5 });+ }+ expect((performance.now() - start) / runs).toBeLessThan(16 * 5);+ });+});diff --git a/packages/claude-mod/test/pane-register.test.ts b/packages/claude-mod/test/pane-register.test.tsnew file mode 100644index 000000000..6e8953add--- /dev/null+++ b/packages/claude-mod/test/pane-register.test.ts@@ -0,0 +1,294 @@+// The pane's wiring through register(): /lens routing and tabs, the Ask field+// (its lookup started inside Lens's own `ui.input` hook), the review's Why+// button, and the brief offered after a compaction. MCP answers come from the+// replies recorded in test/fixtures/ask.+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { Hook, McpToolResult, ModApi, On } from "../src/mod-api";+import { ASK_KEY } from "../src/views/pane";+import { buttonsOf, fixture, flatten, mcpResult, textOf } from "./fake-host";++type Hooks = Record<string, Hook<any>>;++async function load(options: Record<string, boolean> = {}): Promise<{ hooks: Hooks; events: string[] }> {+ vi.resetModules();+ const { register } = await import("../src/register");+ const hooks: Hooks = {};+ const events: string[] = [];+ const on = ((event: string, a: unknown, b?: unknown) => {+ events.push(event);+ const m = a as { component?: string; command?: string; element?: string };+ hooks[b === undefined ? event : `${event}:${m.component ?? m.command ?? m.element}`] = (b ?? a) as Hook<any>;+ }) as On;+ register(on, options);+ return { hooks, events };+}+++function fakeDollar(mcp: (tool: string, args: Record<string, unknown>) => Promise<McpToolResult>) {+ const calls = { mcp: [] as Array<[string, Record<string, unknown>]>, open: [] as unknown[], submitted: [] as string[], logs: [] as string[] };+ const $: ModApi = {+ session: { cwd: async () => "/work/app" },+ fs: { read: async () => Promise.reject(new Error("ENOENT")), exists: async (p) => p === "/work/app/.repowise/state.json" },+ process: { run: async (argv) => ({ exitCode: 0, stdout: argv.includes("--is-inside-work-tree") ? "true\n" : "", stderr: "" }) },+ http: { fetch: async () => ({ status: 500, ok: false, headers: {}, text: "" }) },+ mcp: {+ connect: async () => ({ isConnected: true, server: "plugin:repowise:repowise" }),+ call: (_server, tool, args = {}) => {+ calls.mcp.push([tool, args]);+ return mcp(tool, args);+ },+ },+ prompt: {+ submit: async ({ text }) => {+ calls.submitted.push(text);+ return {};+ },+ },+ ui: {+ invalidate: () => undefined,+ log: (text) => {+ calls.logs.push(text);+ },+ resolve: () =>+ Object.fromEntries(["Box", "Text", "Button", "Input", "Markdown", "Raster"].map((el) => [el, (props: Record<string, unknown>) => ({ el, props })])),+ open: async (pane) => {+ calls.open.push(pane);+ return { isPlaced: true };+ },+ close: async () => undefined,+ blit: async () => ({}),+ },+ command: { register: async () => ({}) },+ settings: { read: async () => ({}) },+ };+ return { $, calls };+}++const settle = () => new Promise((resolve) => setTimeout(resolve, 0));+const reply = (name: string) => mcpResult(JSON.parse(fixture(`ask/${name}.json`)));+const PANE = { surface: "terminal", requestId: "lens", props: { bodyColumns: 120, placement: "dock", scroll: { bodyRows: 40 } } };+const BAND = { props: { hasSurvey: false, bodyColumns: 120 } };+const answers = async (tool: string) => {+ if (tool === "get_why") return reply("requests-why-archaeology");+ if (tool === "get_answer") return reply("django-answer-filter");+ throw new Error(`no ${tool} here`);+};++let hooks: Hooks;+let events: string[];+beforeEach(async () => {+ ({ hooks, events } = await load());+});++/** A session in an indexed repo whose MCP server name has resolved. */+async function session(mcp = answers) {+ const d = fakeDollar(mcp);+ await hooks["session.start"]!(d.$, { cwd: "/work/app" }, async () => undefined);+ for (let i = 0; i < 6; i++) await settle();+ return d;+}++const pane = async (d: { $: ModApi }) => hooks["ui.render:Pane"]!(d.$, PANE, async () => null);+const band = async (d: { $: ModApi }) => hooks["ui.render:AbovePrompt"]!(d.$, BAND, async () => null);+const lens = (d: { $: ModApi }, args: string) => hooks["command.run:lens"]!(d.$, { command: "lens", args }, async () => ({}));++describe("/lens routing and tabs", () => {+ it("/lens recap opens the pane with the keyboard on the recap; a bare /lens keeps the tab", async () => {+ const d = await session();+ expect(await lens(d, "recap")).toEqual({});+ expect(d.calls.open).toEqual([{ id: "lens", title: "Lens", rows: 29, focus: true }]);+ const shown = textOf(await pane(d));+ expect(shown[0]!.trim()).toBe("Files");+ expect(shown.at(-1)).toBe("Lens made no model calls. Every figure here is read from the local index.");+ await lens(d, "");+ expect(textOf(await pane(d))[0]!.trim()).toBe("Files");+ expect(d.calls.mcp).toEqual([]);+ });++ it("a tab press switches the body: Map, then Ask with its field", async () => {+ const d = await session();+ await lens(d, "recap");+ const tabs = buttonsOf(await pane(d));+ expect(tabs.map((b) => [b.props.hotkey, b.props.label])).toEqual([["1", "Map"], ["2", "Ask"], ["3", "Recap"]]);+ tabs[1]!.props.onPress();+ const ask = flatten(await pane(d)).find((n) => n.el === "Input");+ expect(ask?.props).toMatchObject({ key: "lens-ask", autoFocus: true });+ tabs[0]!.props.onPress();+ expect(textOf(await pane(d))).toEqual(["Lens map needs the local server: repowise serve --no-ui"]);+ });++ it("/lens ask starts the lookup inside the command's own hook and shows the reply with its evidence", async () => {+ const d = await session();+ await lens(d, "ask why does Session merge environment settings?");+ // Started before the hook returned: approved as Lens's own call.+ expect(d.calls.mcp).toEqual([["get_why", { query: "why does Session merge environment settings?" }]]);+ await settle();+ const md = textOf(await pane(d)).at(-1)!;+ expect(md).toContain("**Built from the index** · basis archaeology");+ expect(md).toContain("`ev_8964f795d9001bd297ca`");+ });+});++describe("the Ask field", () => {+ const submit = (d: { $: ModApi }, value: string, kind = "submit") =>+ hooks["ui.input:lens-ask"]!(d.$, { plugin: "repowise", element: "lens-ask", kind, value }, async (e) => ({ element: e.element, value: e.value }));++ it("Enter starts the lookup in the ui.input hook; the field's own closure does nothing", async () => {+ const d = await session();+ await lens(d, "ask");+ const input = flatten(await pane(d)).find((n) => n.el === "Input")!;+ input.props.onSubmit("how does filter() build SQL?");+ expect(d.calls.mcp).toEqual([]);+ expect(await submit(d, "how does filter() build SQL?")).toEqual({ element: "lens-ask", value: "how does filter() build SQL?" });+ expect(d.calls.mcp).toEqual([["get_answer", { question: "how does filter() build SQL?" }]]);+ await settle();+ const md = textOf(await pane(d)).at(-1)!;+ expect(md).toContain("**Built from the index** · confidence low · retrieval weak");+ expect(md).toContain("evidence: `django/utils/tree.py`, `django/db/models/sql/constants.py`");+ });++ it("typing and empty submits ask nothing; one question at a time", async () => {+ let land: (r: McpToolResult) => void = () => undefined;+ const d = await session(() => new Promise((resolve) => (land = resolve)));+ await submit(d, "why", "change");+ await submit(d, " ");+ expect(d.calls.mcp).toEqual([]);+ await submit(d, "why A");+ await submit(d, "why B");+ expect(d.calls.mcp).toHaveLength(1);+ await lens(d, "ask");+ // The second was not asked, and the tab says so.+ expect(textOf(await pane(d))).toEqual(["> why A", "asking the decision records...", "still answering the last question; ask again when it lands"]);+ land(reply("django-why-no-record"));+ });++ it("a failed lookup says so in the tab, one line", async () => {+ const d = await session(async () => {+ throw new Error("refused\nsecond line");+ });+ await lens(d, "ask how?");+ await settle();+ expect(textOf(await pane(d)).at(-1)).toBe("Could not answer: refused");+ expect(d.calls.logs).toContain("lens: ask failed: Error: refused\nsecond line");+ });++ it("/lens ask before the server connected waits for it inside the hook, then asks", async () => {+ const d = fakeDollar(answers);+ const waiting: Array<(v: { isConnected: boolean; server: string }) => void> = [];+ d.$.mcp.connect = () => new Promise((resolve) => waiting.push(resolve));+ const running = lens(d, "ask how?");+ await settle();+ expect(d.calls.mcp).toEqual([]);+ for (const connected of waiting) connected({ isConnected: true, server: "plugin:repowise:repowise" });+ await running;+ // Started before the hook returned.+ expect(d.calls.mcp).toEqual([["get_answer", { question: "how?" }]]);+ });++ it("a server that never connects: the ask fails at once and starts nothing late", async () => {+ const d = fakeDollar(answers);+ d.$.mcp.connect = async () => ({ isConnected: false });+ await lens(d, "ask how?");+ await submit(d, "how?");+ await settle();+ expect(d.calls.mcp).toEqual([]);+ expect(textOf(await pane(d)).at(-1)).toBe("Could not answer: repowise MCP server name not resolved yet");+ });++ it("the field's address is the one the hook's literal matcher names", () => {+ expect(ASK_KEY).toBe("lens-ask");+ });+});++describe("Why on the review", () => {+ const EDIT = { tool: "Edit", tool_use_id: "toolu_e1", file_path: "/work/app/src/a.py" };+ const NOTICE = "[repowise] src/a.py is governed by a standing decision: Keep the cache bounded because memory is finite.";++ async function reviewed(notice: string | null) {+ const d = await session(async (tool) => (tool === "get_change_risk" ? mcpResult(JSON.parse(fixture("change-risk/clear.json"))) : answers(tool)));+ await hooks["turn.start"]!(d.$, {}, async () => undefined);+ await hooks["tool.call"]!(d.$, EDIT, async () => ({ result: { type: "update" } }));+ const post = { tool_name: "Edit", tool_use_id: "toolu_e1", tool_input: {} };+ await hooks["classic.PostToolUse"]!(d.$, post, async () => ({ additionalContext: notice === null ? [] : [notice] }));+ await hooks["turn.complete"]!(d.$, { answer: "Done.", reason: "answer" }, async () => ({ text: "Done." }));+ return d;+ }++ it("shows 2: Why when a decision governs the edit; the press opens Ask with the decision, asking nothing", async () => {+ const d = await reviewed(NOTICE);+ const why = buttonsOf(await band(d)).find((b) => b.props.label === "Why")!;+ expect(why.props.hotkey).toBe("2");+ const asked = d.calls.mcp.length;+ why.props.onPress();+ await settle();+ expect(d.calls.open).toEqual([{ id: "lens", title: "Lens", rows: 29, focus: true }]);+ expect(flatten(await pane(d)).find((n) => n.el === "Input")?.props.value).toBe("why Keep the cache bounded");+ expect(d.calls.mcp).toHaveLength(asked);+ });++ it("stays hidden without a decision; a clear review then keeps the band quiet", async () => {+ const d = await reviewed(null);+ expect(buttonsOf(await band(d)).map((b) => b.props.label)).not.toContain("Why");+ });++ it("the recap counts the edited file and the surfaced decision", async () => {+ const d = await reviewed(NOTICE);+ await lens(d, "recap");+ const shown = textOf(await pane(d));+ const at = (label: string) => shown[shown.findIndex((t) => t.trim() === label) + 1];+ expect(at("Files")).toBe("1 edited of 1 file touched");+ expect(at("Decisions surfaced")).toBe("1: Keep the cache bounded");+ expect(at("Code health")).toBe("no new findings in the 1 changed file");+ });+});++describe("the brief after a compaction", () => {+ it("never hooks session.compact; PostCompact passes on untouched", async () => {+ expect(events).not.toContain("session.compact");+ expect(events.filter((e) => e === "classic.PostCompact")).toHaveLength(1);+ const d = await session();+ const out = { from: "next" };+ expect(await hooks["classic.PostCompact"]!(d.$, { trigger: "auto" }, async () => out)).toBe(out);+ });++ it("offers Brief Claude only when there is something to brief; the press submits it visibly, once", async () => {+ const d = await session();+ await hooks["classic.PostCompact"]!(d.$, { trigger: "manual" }, async () => ({}));+ expect(buttonsOf(await band(d))).toEqual([]);+ await hooks["tool.call"]!(d.$, { tool: "Write", tool_use_id: "toolu_w", file_path: "/work/app/src/new.py" }, async () => ({ result: {} }));+ expect(d.calls.submitted).toEqual([]);+ const brief = buttonsOf(await band(d)).find((b) => b.props.label === "Brief Claude")!;+ expect(brief.props.hotkey).toBe("1");+ brief.props.onPress();+ await settle();+ expect(d.calls.submitted).toEqual([+ "The context was compacted. This brief is built from the Repowise index and this session's edits:\nFiles edited: src/new.py",+ ]);+ expect(buttonsOf(await band(d))).toEqual([]);+ });++ it("a new turn retires the offer unsent", async () => {+ const d = await session();+ await hooks["tool.call"]!(d.$, { tool: "Write", tool_use_id: "toolu_w", file_path: "/work/app/src/new.py" }, async () => ({ result: {} }));+ await hooks["classic.PostCompact"]!(d.$, {}, async () => ({}));+ await hooks["turn.start"]!(d.$, {}, async () => undefined);+ expect(buttonsOf(await band(d))).toEqual([]);+ expect(d.calls.submitted).toEqual([]);+ });+});++describe("with lens_review off", () => {+ it("a new turn leaves the review state alone and only retires the brief offer", async () => {+ ({ hooks } = await load({ lens_review: false }));+ const d = await session(async (tool) => {+ throw new Error(`no ${tool} here`);+ });+ await hooks["tool.call"]!(d.$, { tool: "Write", tool_use_id: "toolu_w", file_path: "/work/app/src/new.py" }, async () => ({ result: {} }));+ await hooks["classic.PostCompact"]!(d.$, {}, async () => ({}));+ expect(buttonsOf(await band(d)).map((b) => b.props.label)).toEqual(["Brief Claude"]);+ await hooks["turn.start"]!(d.$, {}, async () => undefined);+ expect(buttonsOf(await band(d))).toEqual([]);+ // No review was started: the only lookup is the spinner's file context.+ expect(d.calls.mcp.map(([tool]) => tool)).not.toContain("get_change_risk");+ });+});diff --git a/packages/claude-mod/test/pane.test.ts b/packages/claude-mod/test/pane.test.tsnew file mode 100644index 000000000..7d0c5d7bc--- /dev/null+++ b/packages/claude-mod/test/pane.test.ts@@ -0,0 +1,324 @@+// The pane's Ask and Recap tabs and the compaction brief, over replies+// recorded from `repowise mcp` 0.54.0 on indexed copies of Django and+// requests (test/fixtures/ask, cut to the fields Lens reads).+import { describe, expect, it } from "vitest";+import { askReply, askRoute, lensCommand, mayHaveUsedModel, whyDraft, type AskReply } from "../src/model/ask";+import type { ChangeRisk } from "../src/model/review";+import { initialSession, reduce, surfacedDecisions, type SessionAction, type SessionState } from "../src/model/session";+import { replyMarkdown } from "../src/views/answer";+import { bandView } from "../src/views/band";+import { BRIEF_PRESS, briefBandRow, briefText, listWithin } from "../src/views/brief";+import { ASK_CHARS, BRIEF_CHARS, savingsLine } from "../src/views/copy";+import type { Node } from "../src/views/elements";+import { ASK_KEY, askView, paneView, recapRows, recapView, tabsView, type RecapRow } from "../src/views/pane";+import { health } from "../src/views/review";+import { fixture } from "./fake-host";++const reply = (name: string) => JSON.parse(fixture(`ask/${name}.json`)) as unknown;+const risk = (name: string) => JSON.parse(fixture(`change-risk/${name}.json`)) as ChangeRisk;+/** The recap's label and value rows by label; sub-heads left out. */+const byLabel = (rows: RecapRow[]) => Object.fromEntries(rows.filter((r): r is [string, string] => typeof r !== "string"));+const run = (actions: SessionAction[], from: SessionState = initialSession) => actions.reduce(reduce, from);++function texts(node: Node | null): string[] {+ if (node === null) return [];+ if (node.type === "Text") return node.children;+ if (node.type === "Button") return [`${node.props.hotkey}: ${node.props.label}`];+ if (node.type === "Markdown") return [node.props.text];+ if (node.type !== "Box") return [];+ return node.children.flatMap(texts);+}++describe("routing", () => {+ it("a why question reads the decision records; anything else asks get_answer", () => {+ expect(askRoute("why is QuerySet lazy?")).toEqual({ tool: "get_why", args: { query: "why is QuerySet lazy?" } });+ expect(askRoute(" Why not?")).toEqual({ tool: "get_why", args: { query: " Why not?" } });+ expect(askRoute("whyever")).toEqual({ tool: "get_answer", args: { question: "whyever" } });+ expect(askRoute("how does filter() build SQL?")).toEqual({ tool: "get_answer", args: { question: "how does filter() build SQL?" } });+ });++ it("/lens arguments: a tab, or ask with its question", () => {+ expect(lensCommand("")).toEqual({ tab: null, question: null });+ expect(lensCommand("recap")).toEqual({ tab: "recap", question: null });+ expect(lensCommand(" MAP ")).toEqual({ tab: "map", question: null });+ expect(lensCommand("ask")).toEqual({ tab: "ask", question: null });+ expect(lensCommand("ask why is QuerySet lazy?")).toEqual({ tab: "ask", question: "why is QuerySet lazy?" });+ expect(lensCommand("frobnicate")).toEqual({ tab: null, question: null });+ });++ it("only an answer that says it had no provider is known to have used no model", () => {+ expect(mayHaveUsedModel(askReply("get_answer", reply("django-answer-filter")))).toBe(false);+ expect(mayHaveUsedModel(askReply("get_answer", { answer: "synthesized", confidence: "high" }))).toBe(true);+ expect(mayHaveUsedModel(askReply("get_why", reply("requests-why-archaeology")))).toBe(false);+ expect(askReply("get_answer", null)).toEqual({ tool: "get_answer", reply: {} });+ });++ it("the Why draft names the decision", () => {+ expect(whyDraft("QuerySet evaluation stays lazy")).toBe("why QuerySet evaluation stays lazy");+ });+});++describe("Ask replies as Markdown", () => {+ it("get_answer: confidence, retrieval and the reason it is not a synthesis, verbatim, then the cited files", () => {+ const md = replyMarkdown("how does filter() build SQL?", askReply("get_answer", reply("django-answer-filter")));+ expect(md.split("\n\n")).toEqual([+ "> how does filter() build SQL?",+ "**Built from the index** · confidence low · retrieval weak",+ "Synthesis is unavailable (no-llm-provider). Source rationale in django/utils/tree.py: A class for storing a tree graph. Primarily used for filter constructs in the ORM.",+ "evidence: `django/utils/tree.py`, `django/db/models/sql/constants.py`",+ ]);+ expect(replyMarkdown("q", askReply("get_answer", { answer: "x" }))).toContain("no evidence cited");+ // No `degraded`: the reply may be the configured model's synthesis, and says so.+ expect(replyMarkdown("q", askReply("get_answer", { answer: "x", confidence: "high" }))).toContain(+ "**Written by this repo's configured model, from the index** · confidence high",+ );+ const named = replyMarkdown("where is QuerySet defined?", askReply("get_answer", reply("django-answer-queryset")));+ expect(named).toContain("**Built from the index** · confidence medium · retrieval high");+ expect(named).toContain("evidence: `django/db/models/query.py`");+ });++ it("get_why: the basis and reason, each commit with its evidence id", () => {+ const md = replyMarkdown("why does Session merge environment settings?", askReply("get_why", reply("requests-why-archaeology")));+ expect(md).toContain("**Built from the index** · basis archaeology");+ expect(md).toContain("No decision record covers this question.");+ expect(md).toContain("- `827bbe2a7e40` docs: correct error in 'merge_environment_settings' usage (2019-02-04) · `ev_8964f795d9001bd297ca`");+ });++ it("get_why on a path: five rows of each list, the rest counted against the server's own total", () => {+ const w = reply("django-why-query-path") as { git_archaeology: { git_log: unknown[] }; code_rationale_total: number };+ const md = replyMarkdown("why django/db/models/query.py", askReply("get_why", w));+ expect(md).toContain("**Built from the index** · basis rationale");+ expect(md).toContain(`- and ${w.git_archaeology.git_log.length - 5} more`);+ expect(md).toContain(`- and ${w.code_rationale_total - 5} more`);+ expect(md).toMatch(/- `django\/db\/models\/query\.py:\d+` .+ · `ev_[0-9a-f]+`/);+ expect(md.length).toBeLessThanOrEqual(ASK_CHARS);+ });++ it("get_why with no record says so, as the server put it", () => {+ const md = replyMarkdown("why rotate?", askReply("get_why", reply("django-why-no-record")));+ expect(md.split("\n\n")).toEqual([+ "> why rotate?",+ "**Built from the index**",+ "No recorded rationale: no decision record covers this question. The store holds none carrying its terms, and the closest ones would be noise.",+ ]);+ });++ it("a decision row carries its status, authority, confidence and id as sent", () => {+ // The row shape `_governing_decision_entry` serializes (tool_why/projection.py).+ const a: AskReply = {+ tool: "get_why",+ reply: { decisions: [{ id: "dec_1", title: "Querysets stay lazy", status: "active", authority: "accepted", confidence: 0.9, decision: "Defer\nthe query." }] },+ };+ expect(replyMarkdown("why lazy", a)).toContain("- **Querysets stay lazy** (active · accepted · confidence 0.9) · `dec_1`: Defer the query.");+ });++ it("a long reply is cut at the stated limit, and says so", () => {+ const md = replyMarkdown("q", askReply("get_answer", { answer: "x".repeat(9_000) }));+ expect(md.length).toBeLessThanOrEqual(ASK_CHARS);+ expect(md.endsWith("_reply cut at 4,000 characters_")).toBe(true);+ });+});++describe("tabs and the Ask tab", () => {+ it("draws three tabs with the shown one at full strength", () => {+ const tabs = tabsView("ask");+ expect(texts(tabs)).toEqual(["1: Map", "2: Ask", "3: Recap"]);+ if (tabs.type !== "Box") throw new Error("expected a Box");+ expect(tabs.children.map((c) => (c.type === "Button" ? c.props.dimColor === true : null))).toEqual([true, false, true]);+ });++ it("the field takes the keyboard when the pane does, pre-filled only by Why", () => {+ const idle = askView(initialSession, 80);+ if (idle.type !== "Box") throw new Error("expected a Box");+ expect(idle.children[0]).toMatchObject({ type: "Input", props: { key: ASK_KEY, autoFocus: true } });+ expect((idle.children[0]!.props as { value?: string }).value).toBeUndefined();+ const why = askView(run([{ type: "tab", tab: "ask", draft: "why X" }]), 80);+ if (why.type !== "Box") throw new Error("expected a Box");+ expect(why.children[0]).toMatchObject({ props: { value: "why X" } });+ });++ it("asking, failed and answered each say so; asking empties the field", () => {+ const asking = run([{ type: "tab", tab: "ask", draft: "why X" }, { type: "asked", question: "why X", tool: "get_why" }]);+ expect(asking.pane.draft).toBe("");+ expect(texts(askView(asking, 80)).slice(-1)).toEqual(["asking the decision records..."]);+ const failed = reduce(asking, { type: "askFailed", question: "why X", tool: "get_why", message: "timed out" });+ expect(texts(askView(failed, 80)).slice(-1)).toEqual(["Could not answer: timed out"]);+ const answered = reduce(asking, { type: "answered", question: "why X", answer: askReply("get_why", reply("django-why-no-record")) });+ expect(texts(askView(answered, 80)).at(-1)).toContain("**Built from the index**");+ });++ it("paneView puts the tabs over the body", () => {+ expect(texts(paneView("recap", { type: "Text", props: {}, children: ["body"] }))).toEqual(["1: Map", "2: Ask", "3: Recap", "body"]);+ });+});++/** A session that edited two files, saw a decision, reviewed, saved, and asked. */+function busySession(): SessionState {+ return run([+ { type: "discovered", mode: "full", freshness: null, repoRoot: "C:\\work\\requests" },+ { type: "touched", path: "src/requests/sessions.py" },+ { type: "touched", path: "src/requests/models.py" },+ { type: "touched", path: "src/requests/sessions.py" },+ { type: "notesFor", id: "toolu_1", notes: [{ kind: "decision", reviewed: true, title: "Sessions own their adapters" }] },+ { type: "notesFor", id: "toolu_2", notes: [{ kind: "decision", reviewed: true, title: "Sessions own their adapters" }, { kind: "fixes", count: 3, age: "2 weeks ago", symbol: null }] },+ { type: "notesFor", id: "toolu_3", notes: [{ kind: "decision", reviewed: false, title: "Retry on 503" }] },+ { type: "reviewed", risk: risk("overlap") },+ { type: "savings", delta: { tokens: 18_240, inferredTokens: 1_000, usd: 0.24 } },+ { type: "answered", question: "q", answer: askReply("get_answer", reply("django-answer-filter")) },+ ]);+}++describe("recap", () => {+ it("every figure equals its source in the session model", () => {+ const s = busySession();+ const reads = { count: 41, capped: false };+ const rows = byLabel(recapRows(s, reads));+ const r = s.lastReview!;+ const hd = r.health_delta!;+ expect(rows["Files"]).toBe(`${s.touched.length} edited of ${reads.count} files touched`);+ expect(s.touched).toEqual(["src/requests/sessions.py", "src/requests/models.py"]);+ expect(rows["Code health"]).toBe(health(r).words);+ expect(rows["Findings"]).toBe(`${hd.resolved} resolved · ${hd.findings_total} new finding${hd.findings_total === 1 ? "" : "s"}`);+ const tests = r.impacted_tests!;+ expect(rows["Tests to run"]).toBe(+ `${tests.total ?? tests.tests_to_run!.length} test file${(tests.total ?? 0) === 1 ? "" : "s"}, ${tests.basis === "measured" ? "measured" : "inferred"}`,+ );+ expect(rows["Saved"]).toBe(savingsLine(s.savings!, Number.POSITIVE_INFINITY));+ const decisions = surfacedDecisions(s);+ expect(decisions).toEqual([+ { title: "Sessions own their adapters", reviewed: true },+ { title: "Retry on 503", reviewed: false },+ ]);+ expect(rows["Decisions surfaced"]).toBe(`${decisions.length}: Sessions own their adapters; Retry on 503`);+ const branches = r.branch_overlap!.branches!.map((b) => b.branch);+ expect(rows["Branches overlapping"]).toContain(`(${branches.join(", ")})`);+ expect(rows["Branches overlapping"]!.startsWith("◦ ")).toBe(true);+ expect(texts(recapView(s, reads, 200)).at(-1)).toBe("Lens made no model calls. Every figure here is read from the local index.");+ });++ it("the last review outlives its turn; a new session starts empty", () => {+ const s = reduce(busySession(), { type: "turnStarted" });+ expect(s.review.outcome).toEqual({ phase: "none" });+ expect(s.lastReview).not.toBeNull();+ const empty = byLabel(recapRows(initialSession, { count: 0, capped: false }));+ expect(empty).toEqual({+ Files: "0 edited of 0 files touched",+ "Change review": "none this session",+ Saved: "needs the local server: repowise serve --no-ui",+ "Decisions surfaced": "none",+ });+ });++ it("states what is unknown rather than zero: capped reads, no tests, no overlap block, nothing saved yet", () => {+ const { branch_overlap: _unreported, ...noOverlapBlock } = risk("clear");+ const clear = run([{ type: "discovered", mode: "full", freshness: null }, { type: "reviewed", risk: { ...noOverlapBlock, impacted_tests: {} } }]);+ const rows = byLabel(recapRows(clear, { count: 200, capped: true }));+ expect(rows["Files"]).toBe("0 edited of 200+ files touched");+ expect(rows["Tests to run"]).toBe("none named");+ expect(rows["Branches overlapping"]).toBe("not reported");+ expect(rows["Saved"]).toBe("nothing yet since this session started");+ const none = reduce(clear, { type: "reviewed", risk: { ...risk("clear"), branch_overlap: { branches: [] } } });+ expect(byLabel(recapRows(none, { count: 0, capped: false }))["Branches overlapping"]).toBe("none found");+ const unavailable = reduce(clear, { type: "reviewed", risk: risk("unavailable") });+ expect(byLabel(recapRows(unavailable, { count: 0, capped: false }))["Findings"]).toBe("not compared");+ });++ it("the footer counts get_answer asks from their start; a reply that had no provider is uncounted", () => {+ const asked = run([{ type: "asked", question: "q", tool: "get_answer" }]);+ expect(asked.modelAsks).toBe(1);+ expect(texts(recapView(asked, { count: 0, capped: false }, 300)).at(-1)).toBe(+ "Lens made no model calls. 1 Ask reply from get_answer may have been written by this repo's configured model.",+ );+ // Failed or timed out: it stays counted; the provider may have seen the question.+ expect(reduce(asked, { type: "askFailed", question: "q", tool: "get_answer", message: "timeout" }).modelAsks).toBe(1);+ expect(reduce(asked, { type: "answered", question: "q", answer: askReply("get_answer", { answer: "a" }) }).modelAsks).toBe(1);+ expect(reduce(asked, { type: "answered", question: "q", answer: askReply("get_answer", reply("django-answer-filter")) }).modelAsks).toBe(0);+ expect(run([{ type: "asked", question: "why", tool: "get_why" }]).modelAsks).toBe(0);+ });++ it("draws a dim sub-head over the review rows and aligns values to one label column", () => {+ const shown = texts(recapView(busySession(), { count: 41, capped: false }, 200));+ expect(shown[2]).toBe("from the last change review");+ expect(shown[0]).toBe("Files ");+ expect(shown[3]).toBe("Code health ");+ });++ it("an errored or empty review does not replace the last one", () => {+ const s = busySession();+ expect(reduce(s, { type: "reviewed", risk: { error: "boom" } }).lastReview).toBe(s.lastReview);+ expect(reduce(s, { type: "reviewed", risk: risk("nothing-to-score") }).lastReview).toBe(s.lastReview);+ });+});++describe("compaction brief", () => {+ it("nothing to brief: no text, no band row, even after a compaction", () => {+ const s = reduce(initialSession, { type: "compacted" });+ expect(briefText(s)).toBeNull();+ expect(briefBandRow(s, 100)).toBeNull();+ });++ it("files, decisions in play and the last review's open items, under the budget", () => {+ const s = reduce(busySession(), { type: "compacted" });+ const brief = briefText(s)!;+ const lines = brief.split("\n");+ expect(lines[0]).toBe("The context was compacted. This brief is built from the Repowise index and this session's edits:");+ expect(lines[1]).toBe("Files edited: src/requests/sessions.py; src/requests/models.py");+ expect(lines[2]).toBe(+ "Decisions in play: Sessions own their adapters (standing decision); Retry on 503 (found in the code, not yet reviewed)",+ );+ expect(lines[3]).toMatch(/^Open review items: /);+ expect(lines[3]).toContain("tests to run, inferred from the dependency graph, not measured:");+ expect(lines[3]).toContain("◦ ");+ expect(brief.length).toBeLessThanOrEqual(BRIEF_CHARS);+ });++ it("stays under the budget however much the session holds, and counts what it left out", () => {+ const actions: SessionAction[] = Array.from({ length: 500 }, (_, i) => ({ type: "touched" as const, path: `src/pkg${i}/module_with_a_long_name_${i}.py` }));+ actions.push(...Array.from({ length: 50 }, (_, i) => ({ type: "notesFor" as const, id: `t${i}`, notes: [{ kind: "decision" as const, reviewed: true, title: `decision ${i} ${"x".repeat(400)}` }] })));+ actions.push({ type: "reviewed", risk: risk("findings") });+ const brief = briefText(run(actions))!;+ expect(brief.length).toBeLessThanOrEqual(BRIEF_CHARS);+ expect(brief).toMatch(/Files edited: .+; and \d+ more/);+ expect(brief).toMatch(/Decisions in play: .+and \d+ more/);+ expect(brief).toContain("Open review items:");+ });++ it("listWithin keeps as many items as fit, then the count; never more than its room", () => {+ expect(listWithin("Files:", ["a", "b", "c"], 100)).toBe("Files: a; b; c");+ expect(listWithin("Files:", ["aaaa", "bbbb", "cccc", "dddd"], 23)).toBe("Files: aaaa; and 3 more");+ expect(listWithin("Files:", ["a".repeat(50)], 20)).toBe("Files: and 1 more");+ expect(listWithin("Files:", ["a"], 5).length).toBeLessThanOrEqual(5);+ });++ it("the band offers it beside a pending review row (hotkey 4), or alone (hotkey 1), until pressed or a new turn", () => {+ const s = reduce(busySession(), { type: "compacted" });+ const band = bandView(s, { columns: 100, hasSurvey: false });+ expect(texts(band)).toContain("2: Why");+ expect(texts(band).slice(-2)).toEqual(["context compacted", "4: Brief Claude"]);+ expect(JSON.stringify(band)).toContain(BRIEF_PRESS);+ const alone = run([{ type: "touched", path: "a.py" }, { type: "compacted" }]);+ expect(texts(bandView(alone, { columns: 100, hasSurvey: false }))).toEqual(["context compacted", "1: Brief Claude"]);+ expect(reduce(s, { type: "briefDone" }).compacted).toBe(false);+ expect(reduce(s, { type: "turnStarted" }).compacted).toBe(false);+ expect(reduce(s, { type: "compacted" })).toBe(s);+ expect(reduce(initialSession, { type: "briefDone" })).toBe(initialSession);+ });++ it("joins an item written over several lines", () => {+ expect(listWithin("Decisions:", ["keep\n it\tbounded"], 100)).toBe("Decisions: keep it bounded");+ });+});++describe("copy", () => {+ it("no em or en dash in anything the pane or the brief writes", async () => {+ const copy = await import("../src/views/copy");+ const all = [+ ...Object.values(copy.PANE_COPY).flatMap((v) => (typeof v === "string" ? [v] : Object.values(v))),+ ...Object.values(copy.RECAP_COPY),+ ...Object.values(copy.BRIEF_COPY),+ copy.recapFooter(2),+ copy.briefDecision("t", false),+ ];+ for (const line of all) expect(line).not.toMatch(/[–—]/);+ });+});diff --git a/packages/claude-mod/test/register.test.ts b/packages/claude-mod/test/register.test.tsnew file mode 100644index 000000000..d8f5f31f3--- /dev/null+++ b/packages/claude-mod/test/register.test.ts@@ -0,0 +1,773 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { CheckNext, Hook, McpToolResult, ModApi, On, ToolCheckEvent } from "../src/mod-api";+import { DARK } from "@repowise-dev/ui/brand";+import { TimeoutError } from "../src/data/transport";+import { buttonsOf, fixture, mcpResult } from "./fake-host";++type Hooks = Record<string, Hook<any>>;++async function load(options: Record<string, boolean> = {}): Promise<Hooks> {+ vi.resetModules();+ const { register } = await import("../src/register");+ const hooks: Hooks = {};+ // Hooks with a matcher are keyed by it: `ui.render:AbovePrompt`, `command.run:lens`, `ui.input:lens-ask`.+ const on = ((event: string, a: unknown, b?: unknown) => {+ const matcher = a as { component?: string; command?: string; element?: string };+ const key = b === undefined ? event : `${event}:${matcher.component ?? matcher.command ?? matcher.element}`;+ hooks[key] = (b ?? a) as Hook<any>;+ }) as On;+ register(on, options);+ return hooks;+}++interface DollarOptions {+ indexed?: boolean;+ mcp?: (server: string, tool: string) => Promise<McpToolResult>;+ /** A live local server listing this repo, answering the savings route with each payload in turn. */+ savings?: unknown[];+ /** The repo id that server lists; default `r1`. */+ repoId?: string;+}++type Calls = {+ cwd: number;+ invalidate: number;+ logs: string[];+ mcp: unknown[][];+ savings: number;+ submitted: string[];+ transcript: string[];+};++const LOCK = "/work/app/.repowise/serve.lock.json";+const STATE = "/work/app/.repowise/state.json";++function fsFor(o: DollarOptions): ModApi["fs"] {+ const served = o.savings !== undefined;+ return {+ read: async (path) => (served && path === LOCK ? fixture("locks/valid.json") : Promise.reject(new Error("ENOENT"))),+ exists: async (path) => (o.indexed === true || served) && path === STATE,+ };+}++/** `ps` says the lock's pid is alive; git says this is a work tree. */+const processFake: ModApi["process"] = {+ run: async (argv) => {+ if (argv[0] === "ps") return { exitCode: 0, stdout: "4242\n", stderr: "" };+ return { exitCode: 0, stdout: argv.includes("--is-inside-work-tree") ? "true\n" : "", stderr: "" };+ },+};++const reply = (body: unknown) => ({ status: 200, ok: true, headers: {}, text: JSON.stringify(body) });+const status = (code: number) => ({ status: code, ok: false, headers: {}, text: "" });++function httpFor(o: DollarOptions, calls: Calls): ModApi["http"] {+ return {+ fetch: async (url) => {+ const id = o.repoId ?? "r1";+ if (o.savings === undefined) return status(500);+ if (url.endsWith("/health")) return reply({ status: "ok" });+ if (url.endsWith("/api/repos")) return reply([{ id, name: "app", local_path: "/work/app" }]);+ if (!url.includes(`/api/repos/${id}/savings`)) return status(404);+ calls.savings++;+ const next = o.savings.shift();+ return next === undefined ? status(503) : reply(next);+ },+ };+}++function mcpFor(o: DollarOptions, calls: Calls): ModApi["mcp"] {+ return {+ connect: async () => ({ isConnected: true, server: "plugin:repowise:repowise" }),+ call: async (...args) => {+ calls.mcp.push(args);+ return o.mcp ? o.mcp(args[0], args[1]) : Promise.reject(new Error("no MCP in this test"));+ },+ };+}++function uiFor(calls: Calls): ModApi["ui"] {+ return {+ invalidate: () => {+ calls.invalidate++;+ },+ log: (text, options) => {+ (options.to === "transcript" ? calls.transcript : calls.logs).push(text);+ },+ resolve: () => ({+ Box: (props) => ({ el: "Box", props }),+ Text: (props) => ({ el: "Text", props }),+ Button: (props) => ({ el: "Button", props }),+ }),+ open: async () => ({ isPlaced: true }),+ close: async () => {},+ blit: async () => ({}),+ };+}++function promptFor(calls: Calls): ModApi["prompt"] {+ return {+ submit: async ({ text }) => {+ calls.submitted.push(text);+ return { text };+ },+ };+}++/** A `$` for a git work tree: no index by default, an index with `indexed`, a live server with `savings`. */+function fakeDollar(o: DollarOptions = {}) {+ const calls: Calls = { cwd: 0, invalidate: 0, logs: [], mcp: [], savings: 0, submitted: [], transcript: [] };+ let release: () => void = () => {};+ const gate = { hold: false, wait: Promise.resolve() };+ const session: ModApi["session"] = {+ cwd: async () => {+ calls.cwd++;+ if (gate.hold) await gate.wait;+ return "/work/app";+ },+ };+ const $: ModApi = { session, fs: fsFor(o), process: processFake, http: httpFor(o, calls), mcp: mcpFor(o, calls), prompt: promptFor(calls), ui: uiFor(calls), command: { register: async () => ({}) }, settings: { read: async () => ({}) } };+ const hold = () => {+ gate.hold = true;+ gate.wait = new Promise<void>((resolve) => (release = resolve));+ };+ return { $, calls, hold, release: () => release() };+}++const settle = () => new Promise((resolve) => setTimeout(resolve, 0));+const band = { props: { hasSurvey: false, bodyColumns: 100 } };+const THEIRS = { el: "theirs" };++let hooks: Hooks;+beforeEach(async () => {+ hooks = await load();+});++describe("register", () => {+ it("registers its hooks and nothing else", () => {+ expect(Object.keys(hooks).sort()).toEqual([+ "classic.PostCompact",+ "classic.PostToolUse",+ "command.run:lens",+ "session.start",+ "tool.call",+ "tool.check",+ "turn.complete",+ "turn.start",+ "ui.input:lens-ask",+ "ui.render:AbovePrompt",+ "ui.render:Pane",+ "ui.render:Spinner",+ "ui.render:ToolResult",+ "ui.render:ToolUse",+ ].sort());+ });++ it("leaves the margin and squeeze hooks out when their toggles are off", async () => {+ const off = await load({ lens_margin: false, lens_squeeze: false });+ expect(Object.keys(off)).not.toContain("classic.PostToolUse");+ expect(Object.keys(off)).not.toContain("ui.render:ToolUse");+ expect(Object.keys(off)).not.toContain("ui.render:ToolResult");+ expect(Object.keys(off)).toContain("ui.render:Spinner");+ });++ it("every hook returns what next(e) returned", async () => {+ const { $ } = fakeDollar();+ const marker = { from: "next" };+ expect(await hooks["session.start"]!($, {}, async () => marker)).toBe(marker);+ expect(await hooks["turn.complete"]!($, {}, async () => marker)).toBe(marker);+ expect(await hooks["turn.complete"]!($, { agentId: "a" }, async () => marker)).toBe(marker);+ });++ it("the band passes the site on at rest", async () => {+ const { $ } = fakeDollar();+ expect(await hooks["ui.render:AbovePrompt"]!($, band, async () => THEIRS)).toBe(THEIRS);+ });++ it("draws its rows above whatever the next hook drew, and alone when nothing was", async () => {+ const { $, calls } = fakeDollar();+ await hooks["session.start"]!($, {}, async () => undefined);+ await settle();+ expect(calls.invalidate).toBe(1);+ const composed = (await hooks["ui.render:AbovePrompt"]!($, band, async () => THEIRS)) as { props: { children: unknown[] } };+ expect(composed.props.children[1]).toBe(THEIRS);+ expect(JSON.stringify(composed.props.children[0])).toContain("index this repo for Lens");+ const alone = await hooks["ui.render:AbovePrompt"]!($, band, async () => null);+ expect(JSON.stringify(alone)).toContain("index this repo for Lens");+ });++ it("a failing draw keeps the band as it was and says why in the debug log only", async () => {+ const { $, calls } = fakeDollar();+ await hooks["session.start"]!($, {}, async () => undefined);+ await settle();+ $.ui.resolve = () => {+ throw new Error("no table");+ };+ expect(await hooks["ui.render:AbovePrompt"]!($, band, async () => THEIRS)).toBe(THEIRS);+ expect(calls.logs).toEqual(["lens: band render failed: Error: no table"]);+ });++ it("a failing refresh is logged, not thrown", async () => {+ const { $, calls } = fakeDollar();+ $.session.cwd = async () => {+ throw new Error("no cwd");+ };+ await hooks["session.start"]!($, {}, async () => undefined);+ await settle();+ expect(calls.logs).toEqual(["lens: refresh failed: Error: no cwd"]);+ expect(calls.invalidate).toBe(0);+ });++ it("yields to a survey", async () => {+ const { $ } = fakeDollar();+ await hooks["session.start"]!($, {}, async () => undefined);+ await settle();+ expect(await hooks["ui.render:AbovePrompt"]!($, { props: { hasSurvey: true } }, async () => THEIRS)).toBe(THEIRS);+ });++ it("discovers on the first turn when the module loaded after the session started", async () => {+ const { $, calls } = fakeDollar();+ await hooks["turn.complete"]!($, {}, async () => undefined);+ await settle();+ expect(calls.cwd).toBe(1);+ });++ it("runs once more after a refresh asked for while one was running", async () => {+ const { $, calls, hold, release } = fakeDollar();+ hold();+ await hooks["session.start"]!($, {}, async () => undefined);+ await hooks["turn.complete"]!($, {}, async () => undefined);+ await hooks["turn.complete"]!($, {}, async () => undefined);+ expect(calls.cwd).toBe(1);+ release();+ await settle();+ await settle();+ expect(calls.cwd).toBe(2);+ });++ it("drops a refresh that finishes after a new session started", async () => {+ const old = fakeDollar();+ old.hold();+ await hooks["session.start"]!(old.$, {}, async () => undefined);+ const fresh = fakeDollar();+ await hooks["session.start"]!(fresh.$, {}, async () => undefined);+ old.release();+ await settle();+ await settle();+ // The old run lands nothing; the new session's own refresh then draws.+ expect(old.calls.invalidate).toBe(0);+ expect(fresh.calls.invalidate).toBe(1);+ });+});++const SESSIONS = JSON.parse(fixture("mcp/get_context-sessions.json")) as McpToolResult;+const READ = { tool: "Read", tool_use_id: "toolu_01", file_path: "/work/app/src/requests/sessions.py" };+const SPINNER = { props: { word: "Sauteing", message: null, suffix: "…", mode: "tool-use" } };++function checkNext(plugin: string, verdict: unknown): CheckNext {+ return Object.assign(async (_e: ToolCheckEvent) => verdict, { origin: { plugin, tier: "user" } });+}++describe("tool.check", () => {+ const own = { tool: "mcp__plugin_repowise_repowise__get_context", input: {}, tool_use_id: "toolu_plugin_1" };+ const core = { decision: "ask", reason: "core" };++ it("approves Lens's own lookup", async () => {+ const { $ } = fakeDollar();+ expect(await hooks["tool.check"]!($, own, checkNext("repowise", core))).toMatchObject({ decision: "allow" });+ const review = { ...own, tool: "mcp__plugin_repowise_repowise__get_change_risk" };+ expect(await hooks["tool.check"]!($, review, checkNext("repowise", core))).toMatchObject({ decision: "allow" });+ });++ it("returns the engine's verdict for Claude's call, another plugin's call, and any other tool", async () => {+ const { $ } = fakeDollar();+ const asks = [+ [{ ...own, tool_use_id: "toolu_01abc" }, "engine"],+ [own, "someone-else"],+ [{ ...own, tool: "mcp__plugin_repowise_repowise__get_dead_code" }, "repowise"],+ [{ ...own, tool: "Bash", input: { command: "rm -rf /" } }, "repowise"],+ ] as const;+ for (const [e, plugin] of asks) {+ expect(await hooks["tool.check"]!($, e, checkNext(plugin, core))).toBe(core);+ }+ });+});++describe("tool.call and the spinner", () => {+ async function indexedSession(mcp?: () => Promise<McpToolResult>) {+ const d = fakeDollar({ indexed: true, ...(mcp ? { mcp } : {}) });+ await hooks["session.start"]!(d.$, {}, async () => undefined);+ await settle();+ await settle();+ return d;+ }++ it("returns what next(e) returned, for every tool", async () => {+ const { $ } = await indexedSession(async () => SESSIONS);+ const result = { from: "the tool" };+ expect(await hooks["tool.call"]!($, READ, async () => result)).toBe(result);+ expect(await hooks["tool.call"]!($, { tool: "Bash", tool_use_id: "t2", command: "ls" }, async () => result)).toBe(result);+ });++ it("starts the context fetch during the call without waiting for it", async () => {+ let land: (r: McpToolResult) => void = () => undefined;+ const { $, calls } = await indexedSession(() => new Promise((resolve) => (land = resolve)));+ let ranTool = false;+ await hooks["tool.call"]!($, READ, async () => {+ // The call has started (it is in flight) and the tool runs before it lands.+ await settle();+ expect(calls.mcp).toHaveLength(1);+ ranTool = true;+ return {};+ });+ expect(ranTool).toBe(true);+ expect(calls.mcp[0]).toEqual([+ "plugin:repowise:repowise",+ "get_context",+ { targets: ["src/requests/sessions.py"], include: ["callers", "ownership"] },+ ]);+ land(SESSIONS);+ });++ it("shows the suffix from the next render after the context lands, keeping the engine's own line", async () => {+ const { $ } = await indexedSession(async () => SESSIONS);+ const seen: unknown[] = [];+ const engine = async (e: typeof SPINNER) => {+ seen.push(e);+ return { drawn: e.props.suffix };+ };+ // First read: nothing cached yet, so the spinner is the engine's.+ await hooks["tool.call"]!($, READ, async () => {+ expect(await hooks["ui.render:Spinner"]!($, SPINNER, engine)).toEqual({ drawn: "…" });+ return {};+ });+ await settle();+ // Second read of the same file: the context is in, and it is not fetched again.+ await hooks["tool.call"]!($, { ...READ, tool_use_id: "toolu_02" }, async () => {+ const drawn = await hooks["ui.render:Spinner"]!($, SPINNER, engine);+ expect(drawn).toEqual({ drawn: "… sessions.py · 3 caller files · 6 contributors" });+ return {};+ });+ expect(seen[1]).toEqual({ props: { ...SPINNER.props, suffix: "… sessions.py · 3 caller files · 6 contributors" } });+ // After the tool ends the spinner is the engine's again.+ expect(await hooks["ui.render:Spinner"]!($, SPINNER, engine)).toEqual({ drawn: "…" });+ });++ it("asks again after a failed fetch, and logs the failure to debug only", async () => {+ let n = 0;+ const { $, calls } = await indexedSession(async () => {+ if (n++ === 0) throw new Error("refused");+ return SESSIONS;+ });+ await hooks["tool.call"]!($, READ, async () => ({}));+ await settle();+ expect(calls.logs.some((l) => l.includes("context for src/requests/sessions.py failed: Error: refused"))).toBe(true);+ await hooks["tool.call"]!($, READ, async () => ({}));+ expect(calls.mcp).toHaveLength(2);+ });++ it("fetches nothing without an index", async () => {+ const { $, calls } = fakeDollar();+ await hooks["session.start"]!($, {}, async () => undefined);+ await settle();+ await hooks["tool.call"]!($, { ...READ, file_path: "/work/app/a.py" }, async () => ({}));+ expect(calls.mcp).toEqual([]);+ expect(await hooks["ui.render:Spinner"]!($, SPINNER, async () => "engine")).toBe("engine");+ });+});++const DISTILLED = fixture("distill/git-log.txt");+const REPLAY = JSON.parse(fixture("replay/repowise-edit-session.json")) as Array<{+ tool_name: string;+ tool_use_id: string;+ tool_input: unknown;+ result: unknown;+}>;+const FLAGGED_EDIT = REPLAY.find((e) => e.tool_use_id === "toolu_01P77H3c1LrnnZBi8MTE2LvR")!;++describe("squeeze rows", () => {+ const bash = (output: unknown, id = "toolu_b1") => ({ props: { tool_use_id: id, tool: "Bash", output, isErrored: false } });++ it("draw under a distilled Bash result, keeping the engine's drawing above", async () => {+ const { $ } = fakeDollar();+ const drawn = (await hooks["ui.render:ToolResult"]!($, bash({ stdout: DISTILLED, stderr: "" }), async () => THEIRS)) as {+ props: { children: Array<{ props: { children: unknown } }> };+ };+ expect(drawn.props.children[0]).toBe(THEIRS);+ expect(JSON.stringify(drawn.props.children[1])).toContain("2,949 lines → 21 · ~25,947 tokens omitted · repowise expand eed993b23bc3");+ });++ it("pass the site on for output distill left alone, another tool, or a result with no text", async () => {+ const { $ } = fakeDollar();+ const plain = fixture("distill/git-status-undistilled.txt");+ expect(await hooks["ui.render:ToolResult"]!($, bash({ stdout: plain }), async () => THEIRS)).toBe(THEIRS);+ const read = { props: { tool_use_id: "r", tool: "Read", output: DISTILLED, isErrored: false } };+ expect(await hooks["ui.render:ToolResult"]!($, read, async () => THEIRS)).toBe(THEIRS);+ expect(await hooks["ui.render:ToolResult"]!($, bash({ exitCode: 1 }, "t3"), async () => THEIRS)).toBe(THEIRS);+ });++ it("a failing draw keeps the engine's result and logs to debug", async () => {+ const { $, calls } = fakeDollar();+ $.ui.resolve = () => {+ throw new Error("no table");+ };+ expect(await hooks["ui.render:ToolResult"]!($, bash({ stdout: DISTILLED }), async () => THEIRS)).toBe(THEIRS);+ expect(calls.logs).toEqual(["lens: squeeze render failed: Error: no table"]);+ });+});++describe("margin notes", () => {+ const row = (id: string) => ({ props: { tool_use_id: id, tool: "Edit", input: {}, isRunning: false, isErrored: false } });++ it("returns the settings hooks' result untouched and draws the notes under that edit's row only", async () => {+ const { $, calls } = fakeDollar();+ const out = await hooks["classic.PostToolUse"]!($, FLAGGED_EDIT, async () => FLAGGED_EDIT.result);+ expect(out).toBe(FLAGGED_EDIT.result);+ expect(calls.invalidate).toBe(1);+ const drawn = JSON.stringify(await hooks["ui.render:ToolUse"]!($, row(FLAGGED_EDIT.tool_use_id), async () => THEIRS));+ expect(drawn).toContain('"el":"theirs"');+ expect(drawn).toContain("a decision found in this file, not yet reviewed: Configure languages declaratively");+ expect(drawn).toContain("fixed 42 times in 6 months, most recently today, mostly in parse_file");+ expect(await hooks["ui.render:ToolUse"]!($, row("toolu_other"), async () => THEIRS)).toBe(THEIRS);+ });++ it("ignores Lens's own lookups, reads, and an edit the hook said nothing about", async () => {+ const { $, calls } = fakeDollar();+ for (const e of REPLAY.filter((x) => x.tool_name !== "Edit" || x.tool_use_id !== FLAGGED_EDIT.tool_use_id).slice(0, 5)) {+ await hooks["classic.PostToolUse"]!($, e, async () => e.result);+ }+ await hooks["classic.PostToolUse"]!($, { ...FLAGGED_EDIT, tool_use_id: "toolu_plugin_x" }, async () => FLAGGED_EDIT.result);+ await hooks["classic.PostToolUse"]!($, { ...FLAGGED_EDIT, tool_name: "Read" }, async () => FLAGGED_EDIT.result);+ expect(calls.invalidate).toBe(0);+ });++ it("a failing draw keeps the row, and a malformed result is passed on", async () => {+ const { $, calls } = fakeDollar();+ await hooks["classic.PostToolUse"]!($, FLAGGED_EDIT, async () => FLAGGED_EDIT.result);+ $.ui.resolve = () => {+ throw new Error("no table");+ };+ expect(await hooks["ui.render:ToolUse"]!($, row(FLAGGED_EDIT.tool_use_id), async () => THEIRS)).toBe(THEIRS);+ expect(calls.logs).toEqual(["lens: margin render failed: Error: no table"]);+ expect(await hooks["classic.PostToolUse"]!($, { ...FLAGGED_EDIT, tool_use_id: 7 }, async () => null)).toBeNull();+ expect(calls.logs[1]).toContain("lens: PostToolUse failed");+ });+});++describe("savings", () => {+ const before = JSON.parse(fixture("savings/before-distill.json")) as unknown;+ const after = JSON.parse(fixture("savings/after-distill.json")) as unknown;++ it("snapshots at session start, shows the growth on a later turn, at most once a minute", async () => {+ const now = vi.spyOn(Date, "now");+ try {+ now.mockReturnValue(1_000_000);+ const { $, calls } = fakeDollar({ savings: [before, after, after] });+ await hooks["session.start"]!($, {}, async () => undefined);+ for (let i = 0; i < 6; i++) await settle();+ expect(calls.savings).toBe(1);+ expect(await hooks["ui.render:AbovePrompt"]!($, band, async () => null)).toBeNull();++ // Inside the cool-down a turn reads nothing.+ now.mockReturnValue(1_030_000);+ await hooks["turn.complete"]!($, {}, async () => undefined);+ for (let i = 0; i < 6; i++) await settle();+ expect(calls.savings).toBe(1);++ now.mockReturnValue(1_061_000);+ await hooks["turn.complete"]!($, {}, async () => undefined);+ for (let i = 0; i < 6; i++) await settle();+ expect(calls.savings).toBe(2);+ expect(JSON.stringify(await hooks["ui.render:AbovePrompt"]!($, band, async () => null))).toContain(+ "7,099 tokens · $0.04 saved since this session started · all agents on this repo",+ );+ } finally {+ now.mockRestore();+ }+ });++ it("reads nothing outside full mode", async () => {+ const { $, calls } = fakeDollar({ indexed: true });+ await hooks["session.start"]!($, {}, async () => undefined);+ for (let i = 0; i < 4; i++) await settle();+ expect(calls.savings).toBe(0);+ });++ it("a failed read is logged to debug and shows nothing", async () => {+ const { $, calls } = fakeDollar({ savings: [] });+ await hooks["session.start"]!($, {}, async () => undefined);+ for (let i = 0; i < 6; i++) await settle();+ expect(calls.logs.some((l) => l.startsWith("lens: savings failed"))).toBe(true);+ expect(await hooks["ui.render:AbovePrompt"]!($, band, async () => null)).toBeNull();+ });+});++describe("follow-ups", () => {+ const after = JSON.parse(fixture("savings/after-distill.json")) as Record<string, unknown>;++ async function turnAt(d: ReturnType<typeof fakeDollar>, now: ReturnType<typeof vi.spyOn>, ms: number) {+ now.mockReturnValue(ms);+ await hooks["turn.complete"]!(d.$, {}, async () => undefined);+ for (let i = 0; i < 6; i++) await settle();+ }++ it("a ledger that shrank clears the row and counts again from there", async () => {+ const now = vi.spyOn(Date, "now");+ try {+ now.mockReturnValue(1_000_000);+ const shrunk = { ...after, saved_input_tokens: 10, priced_input_savings_usd: 0 };+ const grown = { ...shrunk, saved_input_tokens: 510, priced_input_savings_usd: 0.01 };+ const bigger = { ...after, saved_input_tokens: 8099, priced_input_savings_usd: 0.045495 };+ const d = fakeDollar({ savings: [after, bigger, shrunk, grown] });+ await hooks["session.start"]!(d.$, {}, async () => undefined);+ for (let i = 0; i < 6; i++) await settle();+ await turnAt(d, now, 1_061_000);+ expect(JSON.stringify(await hooks["ui.render:AbovePrompt"]!(d.$, band, async () => null))).toContain("1,000 tokens · $0.01 saved");+ await turnAt(d, now, 1_122_000);+ expect(await hooks["ui.render:AbovePrompt"]!(d.$, band, async () => null)).toBeNull();+ await turnAt(d, now, 1_183_000);+ expect(JSON.stringify(await hooks["ui.render:AbovePrompt"]!(d.$, band, async () => null))).toContain(+ "500 tokens · $0.01 saved",+ );+ } finally {+ now.mockRestore();+ }+ });++ it("a different repo starts its own baseline", async () => {+ const now = vi.spyOn(Date, "now");+ try {+ now.mockReturnValue(1_000_000);+ const bigger = { ...after, saved_input_tokens: 9099 };+ const opts = { savings: [after, bigger, { ...bigger, saved_input_tokens: 9599 }] as unknown[], repoId: "r1" };+ const d = fakeDollar(opts);+ await hooks["session.start"]!(d.$, {}, async () => undefined);+ for (let i = 0; i < 6; i++) await settle();+ // The server now lists this checkout under another id: its first read is a baseline, not a delta.+ opts.repoId = "r2";+ await turnAt(d, now, 1_061_000);+ expect(await hooks["ui.render:AbovePrompt"]!(d.$, band, async () => null)).toBeNull();+ await turnAt(d, now, 1_122_000);+ expect(JSON.stringify(await hooks["ui.render:AbovePrompt"]!(d.$, band, async () => null))).toContain("500 tokens");+ } finally {+ now.mockRestore();+ }+ });++ it("a squeeze is looked for again when an early render had no marker yet", async () => {+ const { $ } = fakeDollar();+ const row = (stdout: string) => ({ props: { tool_use_id: "toolu_b9", tool: "Bash", output: { stdout }, isErrored: false } });+ expect(await hooks["ui.render:ToolResult"]!($, row("300 commits (show"), async () => THEIRS)).toBe(THEIRS);+ expect(JSON.stringify(await hooks["ui.render:ToolResult"]!($, row(DISTILLED), async () => THEIRS))).toContain("2,949 lines");+ });++ it("the spinner suffix stands alone when the engine's is empty or missing", async () => {+ const d = fakeDollar({ indexed: true, mcp: async () => JSON.parse(fixture("mcp/get_context-sessions.json")) as McpToolResult });+ await hooks["session.start"]!(d.$, {}, async () => undefined);+ for (let i = 0; i < 4; i++) await settle();+ const read = { tool: "Read", tool_use_id: "toolu_s1", file_path: "/work/app/src/requests/sessions.py" };+ await hooks["tool.call"]!(d.$, read, async () => ({}));+ await settle();+ await hooks["tool.call"]!(d.$, { ...read, tool_use_id: "toolu_s2" }, async () => {+ for (const suffix of ["", undefined]) {+ const drawn = await hooks["ui.render:Spinner"]!(d.$, { props: { word: "W", message: null, suffix, mode: "tool-use" } }, async (e) => e);+ expect((drawn as { props: { suffix: string } }).props.suffix).toBe(" sessions.py · 3 caller files · 6 contributors");+ }+ return {};+ });+ });+});++describe("change review", () => {+ const EDIT = { tool: "Edit", tool_use_id: "toolu_e1", file_path: "/elsewhere/x.py" };+ const EDITED = { result: { type: "update" }, text: "The file has been updated." };+ const DONE = { turnId: "t1", answer: "Done.", reason: "answer" as const };+ const answered = async () => ({ text: "Done." });+ const FINDINGS = JSON.parse(fixture("change-risk/findings.json")) as unknown;++ /** MCP that answers get_change_risk from `risk`, counting the calls. */+ function reviewing(risk: () => Promise<McpToolResult>) {+ const d = fakeDollar({ mcp: (_server, tool) => (tool === "get_change_risk" ? risk() : Promise.reject(new Error(tool))) });+ const reviews = () => d.calls.mcp.filter((c) => c[1] === "get_change_risk").length;+ return { ...d, reviews };+ }++ /** A session whose turn edited a file once. */+ async function editedTurn(risk: () => Promise<McpToolResult>) {+ const d = reviewing(risk);+ await hooks["session.start"]!(d.$, {}, async () => undefined);+ await hooks["turn.start"]!(d.$, {}, async () => undefined);+ await hooks["tool.call"]!(d.$, EDIT, async () => EDITED);+ return d;+ }++ /** The band's drawn tree as one string. */+ const bandText = async ($: ModApi) => JSON.stringify(await hooks["ui.render:AbovePrompt"]!($, band, async () => null));++ it("starts the review when the edit lands and puts the card beneath the answer as one row", async () => {+ const d = await editedTurn(async () => mcpResult(FINDINGS));+ // Started from the edit's own tool.call, before the turn ends.+ expect(d.calls.mcp).toEqual([["plugin:repowise:repowise", "get_change_risk", {}]]);+ await settle();+ const result = (await hooks["turn.complete"]!(d.$, DONE, answered)) as { text: string };+ // The landed review is reused: no second call.+ expect(d.reviews()).toBe(1);+ expect(result.text).not.toContain("\n");+ expect(result.text.split(" · ").slice(0, 2)).toEqual([+ "Change review (working tree, 1 changed file)",+ "Health: 2 new findings need review, starting with nested_complexity in src/requests/_internal_utils.py",+ ]);+ const drawn = await bandText(d.$);+ expect(drawn).toContain("review · health: 2 new findings, review required");+ expect(drawn).toContain(`"color":"${DARK.error}"`);+ });++ it("an edit while a review is in flight starts none; the turn's end starts one covering it", async () => {+ let land: (r: McpToolResult) => void = () => undefined;+ let n = 0;+ const d = await editedTurn(() => (n++ === 0 ? new Promise((resolve) => (land = resolve)) : Promise.resolve(mcpResult(FINDINGS))));+ await hooks["tool.call"]!(d.$, { ...EDIT, tool_use_id: "toolu_e2" }, async () => EDITED);+ expect(d.reviews()).toBe(1);+ const result = (await hooks["turn.complete"]!(d.$, DONE, answered)) as { text: string };+ expect(d.reviews()).toBe(2);+ expect(result.text).toContain("Change review (working tree, 1 changed file)");+ land(mcpResult(FINDINGS));+ });++ it("an edit after a review landed starts a fresh one, which the turn's end then reuses", async () => {+ const d = await editedTurn(async () => mcpResult(FINDINGS));+ await settle();+ await hooks["tool.call"]!(d.$, { ...EDIT, tool_use_id: "toolu_e2" }, async () => EDITED);+ expect(d.reviews()).toBe(2);+ await settle();+ await hooks["turn.complete"]!(d.$, DONE, answered);+ expect(d.reviews()).toBe(2);+ });++ it("a review started at an edit that failed is tried once more, awaited, at the turn's end", async () => {+ let n = 0;+ const d = await editedTurn(async () => {+ if (n++ === 0) throw new Error("refused: no verdict");+ return mcpResult(FINDINGS);+ });+ await settle();+ const result = (await hooks["turn.complete"]!(d.$, DONE, answered)) as { text: string };+ expect(d.reviews()).toBe(2);+ expect(result.text).toContain("Health: 2 new findings need review");+ });++ it("shows the placeholder in the band while the turn waits for the review", async () => {+ let land: (r: McpToolResult) => void = () => undefined;+ const d = await editedTurn(() => new Promise((resolve) => (land = resolve)));+ const pending = hooks["turn.complete"]!(d.$, DONE, answered);+ await settle();+ expect(await bandText(d.$)).toContain("Reviewing the change...");+ land(mcpResult(FINDINGS));+ await pending;+ expect(await bandText(d.$)).not.toContain("Reviewing the change...");+ });++ it("Run tests submits a visible prompt naming the tests; Details prints the directive row by row", async () => {+ const d = await editedTurn(async () => mcpResult(FINDINGS));+ await hooks["turn.complete"]!(d.$, DONE, answered);+ expect(d.calls.submitted).toEqual([]);+ const tree = (await hooks["ui.render:AbovePrompt"]!(d.$, band, async () => null)) as unknown;+ const buttons = buttonsOf(tree).map((b) => b.props as { key: string; onPress: () => void });+ expect(buttons.map((b) => b.key)).toEqual(["lens-review-tests", "lens-review-details"]);+ buttons[0]!.onPress();+ buttons[1]!.onPress();+ await settle();+ expect(d.calls.submitted).toEqual([+ "Run the tests Repowise names for this change, inferred from the dependency graph, not measured: tests/test_requests.py tests/test_utils.py",+ ]);+ expect(d.calls.transcript.slice(0, 2)).toEqual([+ "Change review: review required",+ "2 new findings need review, starting with nested_complexity in src/requests/_internal_utils.py.",+ ]);+ expect(d.calls.transcript.every((row) => !row.includes("\n"))).toBe(true);++ // A press that fails says so in the debug log and never throws.+ d.$.ui.log = (text, options) => {+ if (options.to === "transcript") throw new Error("gone");+ d.calls.logs.push(text);+ };+ d.$.prompt.submit = () => {+ throw new Error("no prompt");+ };+ expect(() => buttons[1]!.onPress()).not.toThrow();+ expect(() => buttons[0]!.onPress()).not.toThrow();+ expect(d.calls.logs).toEqual(expect.arrayContaining(["lens: details failed: Error: gone", "lens: run tests failed: Error: no prompt"]));+ });++ it("a turn with no edit, a refused edit and a Read are quiet", async () => {+ const d = reviewing(async () => mcpResult(FINDINGS));+ await hooks["session.start"]!(d.$, {}, async () => undefined);+ await hooks["turn.start"]!(d.$, {}, async () => undefined);+ await hooks["tool.call"]!(d.$, EDIT, async () => ({ deny: "no" }));+ await hooks["tool.call"]!(d.$, { ...EDIT, tool: "Read" }, async () => EDITED);+ const result = { text: "Done." };+ expect(await hooks["turn.complete"]!(d.$, DONE, async () => result)).toBe(result);+ expect(d.reviews()).toBe(0);+ });++ it.each([+ ["a subagent's turn", { agentId: "sub" }],+ ["an interrupted turn", { reason: "aborted", isAborted: true }],+ ["a turn an API error ended", { reason: "error" }],+ ])("%s shows no card", async (_name, extra) => {+ const d = await editedTurn(async () => mcpResult(FINDINGS));+ const result = { text: "Done." };+ expect(await hooks["turn.complete"]!(d.$, { ...DONE, ...extra }, async () => result)).toBe(result);+ expect(await bandText(d.$)).not.toContain("review · health");+ });++ it("an empty diff shows no card and no band row", async () => {+ const empty = JSON.parse(fixture("change-risk/nothing-to-score.json")) as unknown;+ const d = await editedTurn(async () => mcpResult(empty));+ const result = { text: "Done." };+ expect(await hooks["turn.complete"]!(d.$, DONE, async () => result)).toBe(result);+ expect(await bandText(d.$)).not.toContain("review");+ });++ it("a new turn retires the last review's row", async () => {+ const d = await editedTurn(async () => mcpResult(FINDINGS));+ await hooks["turn.complete"]!(d.$, DONE, answered);+ await hooks["turn.start"]!(d.$, {}, async () => undefined);+ expect(await bandText(d.$)).not.toContain("review · health");+ });++ it("a review still in flight when the next turn starts is dropped", async () => {+ let land: (r: McpToolResult) => void = () => undefined;+ const d = await editedTurn(() => new Promise((resolve) => (land = resolve)));+ const result = { text: "Done." };+ const pending = hooks["turn.complete"]!(d.$, DONE, async () => result);+ await settle();+ await hooks["turn.start"]!(d.$, {}, async () => undefined);+ land(mcpResult(FINDINGS));+ expect(await pending).toBe(result);+ expect(await bandText(d.$)).not.toContain("review");+ });++ it("an error and a timeout each say so in one line, and the band stays quiet", async () => {+ const failing = await editedTurn(async () => Promise.reject(new Error("server gone\nstack")));+ const failed = (await hooks["turn.complete"]!(failing.$, DONE, answered)) as { text: string };+ expect(failed.text).toBe("Change review could not run: server gone");+ expect(failing.calls.logs.some((l) => l.startsWith("lens: change review failed"))).toBe(true);+ expect(await bandText(failing.$)).not.toContain("review");++ const slow = await editedTurn(async () => Promise.reject(new TimeoutError("get_change_risk", 20_000)));+ const timedOut = (await hooks["turn.complete"]!(slow.$, DONE, answered)) as { text: string };+ expect(timedOut.text).toBe("Change review timed out after 20 s");+ });++ it("with lens_review off, nothing is reviewed", async () => {+ hooks = await load({ lens_review: false });+ const d = reviewing(async () => mcpResult(FINDINGS));+ await hooks["session.start"]!(d.$, {}, async () => undefined);+ await hooks["turn.start"]!(d.$, {}, async () => undefined);+ await hooks["tool.call"]!(d.$, EDIT, async () => EDITED);+ const result = { text: "Done." };+ expect(await hooks["turn.complete"]!(d.$, DONE, async () => result)).toBe(result);+ expect(d.reviews()).toBe(0);+ });+});diff --git a/packages/claude-mod/test/review.test.ts b/packages/claude-mod/test/review.test.tsnew file mode 100644index 000000000..23ab18207--- /dev/null+++ b/packages/claude-mod/test/review.test.ts@@ -0,0 +1,374 @@+// Views over `get_change_risk` results recorded from the real server on an+// indexed copy of `requests` (one uncommitted edit per state; the overlap state+// adds a second local branch editing the same file). Error and timeout are+// client-side states, so they have no recorded payload.+import { describe, expect, it } from "vitest";+import { initialReview, isFileEdit, isRetryable, reduceReview, shouldReview, testsToRun, type ChangeRisk, type ReviewOutcome } from "../src/model/review";+import { initialSession, reduce } from "../src/model/session";+import { bandView } from "../src/views/band";+import { box, button, materialize, text, type Node } from "../src/views/elements";+import { DARK } from "@repowise-dev/ui/brand";+import { PRESS, directiveRows, reviewBandRow, reviewText, runTestsText, withCard } from "../src/views/review";+import { fixture } from "./fake-host";++const risk = (name: string): ChangeRisk => JSON.parse(fixture(`change-risk/${name}.json`)) as ChangeRisk;+const done = (name: string): ReviewOutcome => ({ phase: "done", risk: risk(name) });++/** Every string a tree draws, in order, with button labels as `hotkey: label`. */+function drawn(node: Node | null): string[] {+ if (node === null) return [];+ if (node.type === "Text") return node.children;+ if (node.type === "Button") return [`${node.props.hotkey}: ${node.props.label}`];+ if (node.type !== "Box") return [];+ return node.children.flatMap(drawn);+}++function colors(node: Node | null): string[] {+ if (node?.type === "Text") return node.props.color === undefined ? [] : [node.props.color];+ return node?.type === "Box" ? node.children.flatMap(colors) : [];+}++/** The card is one row of segments; split it back to compare them. */+const segments = (outcome: ReviewOutcome) => reviewText(outcome)?.split(" · ");++const TESTS = "Tests to run: 2 test files, inferred from the dependency graph, not measured: tests/test_requests.py, tests/test_utils.py";++describe("review model", () => {+ it("counts only edits that ran, made by Claude or its subagents", () => {+ const ran = { result: { type: "update" }, text: "ok" };+ expect(isFileEdit({ tool: "Edit", tool_use_id: "toolu_01" }, ran)).toBe(true);+ expect(isFileEdit({ tool: "Write", tool_use_id: "toolu_02" }, ran)).toBe(true);+ expect(isFileEdit({ tool: "MultiEdit" }, ran)).toBe(true);+ expect(isFileEdit({ tool: "NotebookEdit", tool_use_id: "toolu_03" }, ran)).toBe(true);+ expect(isFileEdit({ tool: "Read", tool_use_id: "toolu_04" }, ran)).toBe(false);+ expect(isFileEdit({ tool: "Bash", tool_use_id: "toolu_05" }, ran)).toBe(false);+ expect(isFileEdit({ tool: "Edit", tool_use_id: "toolu_plugin_06" }, ran)).toBe(false);+ expect(isFileEdit({ tool: "Edit", tool_use_id: "toolu_07" }, { deny: "no" })).toBe(false);+ expect(isFileEdit({ tool: "Edit", tool_use_id: "toolu_08" }, { isError: true, text: "old_string not found" })).toBe(false);+ expect(isFileEdit({ tool: "Edit", tool_use_id: "toolu_09" }, undefined)).toBe(false);+ expect(isFileEdit({}, ran)).toBe(false);+ });++ it("remembers an edit until the next turn starts, and a new turn drops the last review", () => {+ let s = reduceReview(initialReview, { type: "fileEdited" });+ expect(s.edited).toBe(true);+ expect(reduceReview(s, { type: "fileEdited" })).toBe(s);+ s = reduceReview(s, { type: "reviewStarted" });+ expect(s.outcome).toEqual({ phase: "reviewing" });+ s = reduceReview(s, { type: "reviewed", risk: risk("clear") });+ expect(s.outcome.phase).toBe("done");+ expect(reduceReview(s, { type: "turnStarted" })).toBe(initialReview);+ expect(reduceReview(initialReview, { type: "turnStarted" })).toBe(initialReview);+ const failed = reduceReview(s, { type: "reviewFailed", reason: "timeout", message: "x" });+ expect(failed.outcome).toEqual({ phase: "failed", reason: "timeout", message: "x" });+ });++ it("the session carries the review and leaves the rest of its state alone", () => {+ const s = reduce(initialSession, { type: "fileEdited" });+ expect(s.review.edited).toBe(true);+ expect({ ...s, review: initialReview }).toEqual(initialSession);+ expect(reduce(initialSession, { type: "turnStarted" })).toBe(initialSession);+ // A discovery keeps the review it found.+ expect(reduce(s, { type: "discovered", mode: "no-index", freshness: null }).review).toBe(s.review);+ });++ it("reviews only a finished main-loop turn that edited files", () => {+ expect(shouldReview({ reason: "answer" }, 1)).toBe(true);+ expect(shouldReview({}, 2)).toBe(true);+ expect(shouldReview({ reason: "answer" }, 0)).toBe(false);+ expect(shouldReview({ agentId: "sub" }, 1)).toBe(false);+ expect(shouldReview({ isAborted: true }, 1)).toBe(false);+ expect(shouldReview({ reason: "aborted" }, 1)).toBe(false);+ expect(shouldReview({ reason: "error" }, 1)).toBe(false);+ });++ it("retries a failed review once unless it timed out", () => {+ expect(isRetryable({ type: "reviewFailed", reason: "error" })).toBe(true);+ expect(isRetryable({ type: "reviewFailed", reason: "timeout" })).toBe(false);+ expect(isRetryable({ type: "reviewed" })).toBe(false);+ });++ it("reads the tests and their basis as the server sent them", () => {+ expect(testsToRun(risk("clear"))).toEqual({+ tests: ["tests/test_requests.py", "tests/test_utils.py"],+ total: 2,+ truncated: false,+ files: true,+ measured: false,+ });+ expect(testsToRun(risk("unavailable"))).toBeNull();+ expect(testsToRun(risk("nothing-to-score"))).toBeNull();+ const measured = { impacted_tests: { basis: "measured", tests_to_run: ["t::a"], tests_to_run_kind: "test_id" } } as ChangeRisk;+ expect(testsToRun(measured)).toEqual({ tests: ["t::a"], total: 1, truncated: false, files: false, measured: true });+ });+});++describe("review card beneath the answer", () => {+ it("says nothing before a review has a result", () => {+ expect(reviewText({ phase: "none" })).toBeNull();+ expect(reviewText({ phase: "reviewing" })).toBeNull();+ });++ it("clear with no other branch in these files collapses to one line", () => {+ expect(reviewText(done("clear"))).toBe("Change review (working tree) · health: no new findings in the 1 changed file");+ });++ it("a change that resolves findings and adds none says so in words", () => {+ expect(reviewText(done("resolved"))).toBe("Change review (working tree) · health: improved, 2 findings resolved, none new");+ });++ it("is one row: the engine stores a line break in this text as U+FFFD", () => {+ for (const name of ["clear", "findings", "overlap", "partial", "unavailable", "resolved"]) {+ expect(reviewText(done(name))).not.toMatch(/[\n\r]/);+ }+ });++ it("new findings lead, each with severity, reason and place", () => {+ expect(segments(done("findings"))).toEqual([+ "Change review (working tree, 1 changed file)",+ "Health: 2 new findings need review, starting with nested_complexity in src/requests/_internal_utils.py",+ "critical nested_complexity: classify_headers nests 7 levels deep (src/requests/_internal_utils.py:55)",+ "high complex_method: classify_headers has cyclomatic complexity 15 (src/requests/_internal_utils.py:55)",+ "Diff shape: bigger than 92% of this repo's recent commits; size, not danger",+ TESTS,+ ]);+ });++ it("another branch editing the same file keeps the full card, with a neutral mark", () => {+ expect(segments(done("overlap"))).toEqual([+ "Change review (working tree, 1 changed file)",+ "Health: no new findings in the 1 changed file",+ "Diff shape: bigger than 34% of this repo's recent commits; size, not danger",+ TESTS,+ "Branches: ◦ 1 other branch also edits src/requests/_internal_utils.py (fix-native-strings)",+ ]);+ });++ it("a partial comparison carries a scope line and is never read as clear", () => {+ expect(segments(done("partial"))).toEqual([+ "Change review (working tree, 2 changed files)",+ "Health: Nothing new in what was compared, but part of the change was not analysed",+ "Scope: compared 1 of 2 changed files; 1 not analysed (1 unsupported language), so this is not a clean bill",+ "Diff shape: bigger than 40% of this repo's recent commits; size, not danger",+ TESTS,+ "Branches: ◦ 2 other branches also edit tox.ini (origin/3.0, origin/proposed/3.0.0)",+ ]);+ });++ it("a change with nothing health can read says it was not compared", () => {+ expect(segments(done("unavailable"))).toEqual([+ "Change review (working tree, 1 changed file)",+ "Health: not compared: No changed file is health-analyzable, so nothing was compared",+ "Diff shape: bigger than 34% of this repo's recent commits; size, not danger",+ "Branches: ◦ 2 other branches also edit tox.ini (origin/3.0, origin/proposed/3.0.0)",+ ]);+ });++ it("an empty diff shows no card", () => {+ expect(reviewText(done("nothing-to-score"))).toBeNull();+ });++ it("a review of 0 changed files (an edit reverted) shows no card and no diff shape", () => {+ const base = risk("findings");+ const reverted: ChangeRisk = {+ ...base,+ risk_percentile: 100,+ health_delta: { ...base.health_delta!, scope: { ...base.health_delta!.scope!, changed: 0, analyzed: 0, eligible: 0 } },+ };+ expect(reviewText({ phase: "done", risk: reverted })).toBeNull();+ expect(reviewBandRow({ phase: "done", risk: reverted }, 100)).toBeNull();+ });++ it("an error and a timeout each say so in one line", () => {+ expect(reviewText({ phase: "failed", reason: "error", message: "repowise MCP server is not connected" })).toBe(+ "Change review could not run: repowise MCP server is not connected",+ );+ expect(reviewText({ phase: "failed", reason: "timeout", message: "get_change_risk timed out after 20000 ms" })).toBe(+ "Change review timed out after 20 s",+ );+ expect(reviewText({ phase: "done", risk: { error: "Could not read change 'HEAD': bad revision" } })).toBe(+ "Change review could not run: Could not read change 'HEAD': bad revision",+ );+ });++ it("a clean tree reviews HEAD and says the working tree had nothing", () => {+ const head = { ...risk("findings"), ref: "HEAD", working_tree: false };+ expect(segments({ phase: "done", risk: head })?.[0]).toBe(+ "Change review (HEAD (no uncommitted changes), 1 changed file)",+ );+ });++ it("counts findings past the ones the server listed, and resolved ones beside new ones", () => {+ const base = risk("findings");+ const more = { ...base, health_delta: { ...base.health_delta!, findings_total: 5, resolved: 1 } };+ const lines = segments({ phase: "done", risk: more })!;+ expect(lines[1]).toBe(+ "Health: 2 new findings need review, starting with nested_complexity in src/requests/_internal_utils.py; 1 finding resolved",+ );+ expect(lines).toContain("and 3 more (Details)");+ });++ it("an unranked diff and a capped test list say so", () => {+ const base = risk("clear");+ const capped = {+ ...base,+ risk_percentile: null,+ branch_overlap: risk("overlap").branch_overlap!,+ impacted_tests: { ...base.impacted_tests!, total: 23, truncated: true },+ };+ const lines = segments({ phase: "done", risk: capped })!;+ expect(lines).toContain("Diff shape: not ranked (no recent commits to compare); size, not danger");+ expect(lines).toContain(+ "Tests to run: 23 test files, inferred from the dependency graph, not measured (first 2 shown): tests/test_requests.py, tests/test_utils.py",+ );+ expect(runTestsText({ phase: "done", risk: capped })).toBe(+ "Run the tests Repowise names for this change (the first 2 of 23), inferred from the dependency graph, not measured: tests/test_requests.py tests/test_utils.py",+ );+ });++ it("a result without a directive says health was not reported", () => {+ expect(reviewText({ phase: "done", risk: { ref: "working tree", working_tree: true, risk_percentile: 10 } })).toBe(+ ["Change review (working tree)", "Health: not reported", "Diff shape: bigger than 10% of this repo's recent commits; size, not danger"].join(" · "),+ );+ });+});++describe("review band row", () => {+ it("shows the placeholder while the review runs", () => {+ expect(drawn(reviewBandRow({ phase: "reviewing" }, 100))).toEqual(["Reviewing the change..."]);+ });++ it("draws nothing without a result, for an empty diff, or on a failure", () => {+ expect(reviewBandRow({ phase: "none" }, 100)).toBeNull();+ expect(reviewBandRow(done("nothing-to-score"), 100)).toBeNull();+ expect(reviewBandRow({ phase: "failed", reason: "timeout", message: "" }, 100)).toBeNull();+ expect(reviewBandRow({ phase: "done", risk: { error: "boom" } }, 100)).toBeNull();+ });++ it.each([+ ["clear", ["review · health: no new findings", "1: Run tests", "3: Details"], []],+ ["resolved", ["review · health: improved, 2 resolved", "1: Run tests", "3: Details"], [DARK.success]],+ ["findings", ["review · health: 2 new findings, review required", "1: Run tests", "3: Details"], [DARK.error]],+ [+ "overlap",+ ["review · health: no new findings", " · ◦ 1 other branch edits these files", "1: Run tests", "3: Details"],+ [],+ ],+ [+ "partial",+ ["review · health: partly compared, no new findings", " · ◦ 2 other branches edit these files", "1: Run tests", "3: Details"],+ [],+ ],+ ["unavailable", ["review · health: not compared", " · ◦ 2 other branches edit these files", "3: Details"], []],+ ])("%s: health word in a health color only, then the buttons", (name, expected, expectedColors) => {+ const row = reviewBandRow(done(name), 120);+ expect(drawn(row)).toEqual(expected);+ expect(colors(row)).toEqual(expectedColors);+ });++ it("a clear review with no tests to run and no other branch leaves the band quiet", () => {+ const base = risk("clear");+ const quiet = { ...base, impacted_tests: { ...base.impacted_tests!, tests_to_run: [], total: 0 } };+ expect(reviewBandRow({ phase: "done", risk: quiet }, 120)).toBeNull();+ expect(reviewText({ phase: "done", risk: quiet })).toBe("Change review (working tree) · health: no new findings in the 1 changed file");+ });++ it("low-severity findings are amber", () => {+ const base = risk("findings");+ const low = { ...base, directive: { ...base.directive!, status: "review_recommended" as const } };+ const row = reviewBandRow({ phase: "done", risk: low }, 120);+ expect(drawn(row)[0]).toBe("review · health: 2 new findings, low severity");+ expect(colors(row)).toEqual([DARK.warning]);+ });++ it.each([60, 100, 180])("fits %i columns, dropping the overlap words before the buttons", (columns) => {+ const row = reviewBandRow(done("partial"), columns)!;+ const labels = drawn(row);+ expect(labels.slice(-2)).toEqual(["1: Run tests", "3: Details"]);+ const width = labels.reduce((n, s) => n + s.length, 0) + 2 * 2;+ expect(width).toBeLessThanOrEqual(columns);+ });++ it("joins the band under the hint, holding its place within two rows", () => {+ const state = {+ ...initialSession,+ mode: "lite" as const,+ hint: "no-server" as const,+ hintsShown: ["no-server" as const],+ freshness: { changedFiles: 3 },+ review: { edited: true, outcome: done("findings"), decision: null },+ };+ const band = bandView(state, { columns: 120, hasSurvey: false });+ expect(drawn(band)).toEqual([+ "Lens map needs the local server: repowise serve --no-ui",+ "review · health: 2 new findings, review required",+ "1: Run tests",+ "3: Details",+ ]);+ expect(bandView({ ...initialSession, review: { edited: true, outcome: { phase: "reviewing" }, decision: null } }, { columns: 80, hasSurvey: true })).toBeNull();+ });+});++describe("review buttons", () => {+ it("Details prints the whole directive", () => {+ expect(directiveRows(done("findings"))).toEqual([+ "Change review: review required",+ "2 new findings need review, starting with nested_complexity in src/requests/_internal_utils.py.",+ "Reasons:",+ " critical defect: nested_complexity in classify_headers (added_lines)",+ " high defect: complex_method in classify_headers (added_lines)",+ "Next actions:",+ " Inspect src/requests/_internal_utils.py:55 (chf_7c35d63fcc13e52b)",+ " Inspect src/requests/_internal_utils.py:55 (chf_1d478916e70baee8)",+ " Run: tests/test_requests.py tests/test_utils.py",+ ]);+ expect(directiveRows(done("nothing-to-score"))).toBeNull();+ expect(directiveRows({ phase: "reviewing" })).toBeNull();+ });++ it("Run tests submits the tests with their basis in words", () => {+ expect(runTestsText(done("clear"))).toBe(+ "Run the tests Repowise names for this change, inferred from the dependency graph, not measured: tests/test_requests.py tests/test_utils.py",+ );+ const measured = { impacted_tests: { basis: "measured", tests_to_run: ["tests/a.py::t"], total: 1 } } as ChangeRisk;+ expect(runTestsText({ phase: "done", risk: measured })).toBe(+ "Run the tests Repowise names for this change, measured by stored coverage: tests/a.py::t",+ );+ expect(runTestsText(done("unavailable"))).toBeNull();+ expect(runTestsText({ phase: "none" })).toBeNull();+ });++ it("materializes buttons with the action their key names", () => {+ const pressed: string[] = [];+ const tree = box({ flexDirection: "row" }, [text("x"), button(PRESS.tests, "1", "Run tests")]);+ const table = {+ Box: (props: Record<string, unknown>) => props,+ Text: (props: Record<string, unknown>) => props,+ Button: (props: Record<string, unknown>) => props,+ };+ const built = materialize(tree, table, { [PRESS.tests]: () => pressed.push("tests") }) as {+ children: Array<{ onPress?: () => void; label?: string }>;+ };+ expect(built.children[1]?.label).toBe("Run tests");+ built.children[1]?.onPress?.();+ expect(pressed).toEqual(["tests"]);+ expect(() => materialize(tree, table)).toThrow("button lens-review-tests has no action");+ });+});++describe("card beneath the answer", () => {+ it("replaces the answer's text with the card, which the engine then shows beneath it", () => {+ const usage = { input_tokens: 1 };+ expect(withCard({ text: "done", usage }, "done", "Change review · x")).toEqual({ text: "Change review · x", usage });+ });++ it("keeps a line another hook already put beneath the answer", () => {+ expect(withCard({ text: "TL;DR" }, "done", "card")).toEqual({ text: "TL;DR · card" });+ });++ it("passes on a result it cannot read", () => {+ expect(withCard(undefined, "done", "card")).toBeUndefined();+ const odd = { other: 1 };+ expect(withCard(odd, "done", "card")).toBe(odd);+ });+});diff --git a/packages/claude-mod/test/session.test.ts b/packages/claude-mod/test/session.test.tsnew file mode 100644index 000000000..06a2b330e--- /dev/null+++ b/packages/claude-mod/test/session.test.ts@@ -0,0 +1,130 @@+import { describe, expect, it } from "vitest";+import { fromTurnComplete } from "../src/model/events";+import { initialReview } from "../src/model/review";+import { hintFor, initialSession, reduce, type SessionAction, type SessionState } from "../src/model/session";++function run(actions: SessionAction[], from: SessionState = initialSession): SessionState {+ return actions.reduce(reduce, from);+}++const lite: SessionAction = { type: "discovered", mode: "lite", freshness: null };+const full: SessionAction = { type: "discovered", mode: "full", freshness: null };+const noIndex: SessionAction = { type: "discovered", mode: "no-index", freshness: null };+const noCli: SessionAction = { type: "discovered", mode: "no-cli", freshness: null };+const turn: SessionAction = { type: "turnCompleted" };++describe("hintFor", () => {+ it("names one hint per degraded mode and none in full mode", () => {+ expect(hintFor("full", undefined)).toBeNull();+ expect(hintFor("no-repo", undefined)).toBeNull();+ expect(hintFor("lite", undefined)).toBe("no-server");+ expect(hintFor("lite", "auth")).toBe("auth");+ expect(hintFor("lite", "unlisted")).toBe("unlisted");+ expect(hintFor("no-index", undefined)).toBe("no-index");+ expect(hintFor("no-cli", undefined)).toBe("no-cli");+ });+});++describe("session reducer", () => {+ it("starts with no mode and nothing to show", () => {+ expect(initialSession).toEqual({+ mode: null,+ freshness: null,+ hint: null,+ hintsShown: [],+ repoRoot: null,+ running: null,+ contexts: {},+ notes: {},+ savings: null,+ review: initialReview,+ lastReview: null,+ touched: [],+ pane: { tab: "map", draft: "" },+ ask: { phase: "idle" },+ modelAsks: 0,+ compacted: false,+ });+ });++ it("outside a repo shows nothing at all", () => {+ expect(run([{ type: "discovered", mode: "no-repo", freshness: { changedFiles: 3 } }])).toMatchObject({+ mode: "no-repo",+ hint: null,+ freshness: null,+ });+ });++ it("full mode shows no hint", () => {+ expect(run([full])).toMatchObject({ mode: "full", hint: null, hintsShown: [] });+ });++ it.each([+ [lite, "no-server"],+ [{ ...lite, liteReason: "auth" } as SessionAction, "auth"],+ [noIndex, "no-index"],+ [noCli, "no-cli"],+ ])("a degraded mode raises its hint", (action, kind) => {+ const s = run([action]);+ expect(s.hint).toBe(kind);+ expect(s.hintsShown).toEqual([kind]);+ });++ it("a hint shows once per session: it retires after a turn and never comes back", () => {+ const afterTurn = run([noIndex, turn]);+ expect(afterTurn.hint).toBeNull();+ const again = run([noIndex, turn, noIndex, turn, noIndex]);+ expect(again.hint).toBeNull();+ expect(again.hintsShown).toEqual(["no-index"]);+ });++ it("rediscovering the same mode keeps the hint on screen until a turn ends", () => {+ expect(run([lite, lite]).hint).toBe("no-server");+ });++ it("lite to full: the map hint leaves at once", () => {+ const s = run([lite, full]);+ expect(s.mode).toBe("full");+ expect(s.hint).toBeNull();+ });++ it("full back to lite after the hint was shown does not show it again", () => {+ expect(run([lite, full, lite]).hint).toBeNull();+ });++ it("a new degraded state shows its own hint even after another one was shown", () => {+ const s = run([noCli, turn, noIndex]);+ expect(s.hint).toBe("no-index");+ expect(s.hintsShown).toEqual(["no-cli", "no-index"]);+ });++ it("no-index to lite (the user indexed): the old hint leaves and the lite hint shows", () => {+ const s = run([noIndex, lite]);+ expect(s.hint).toBe("no-server");+ expect(s.mode).toBe("lite");+ });++ it("keeps freshness only where an index and the CLI exist", () => {+ const behind = { changedFiles: 14 };+ expect(run([{ ...full, freshness: behind }]).freshness).toEqual(behind);+ expect(run([{ ...lite, freshness: behind }]).freshness).toEqual(behind);+ expect(run([{ ...noCli, freshness: behind }]).freshness).toBeNull();+ expect(run([{ ...noIndex, freshness: behind }]).freshness).toBeNull();+ });++ it("freshness clears when the index catches up", () => {+ expect(run([{ ...full, freshness: { changedFiles: 3 } }, full]).freshness).toBeNull();+ });++ it("a turn with no hint up changes nothing", () => {+ const s = run([full]);+ expect(reduce(s, turn)).toBe(s);+ });+});++describe("events", () => {+ it("counts only main-loop turns", () => {+ expect(fromTurnComplete({})).toEqual({ type: "turnCompleted" });+ expect(fromTurnComplete({ agentId: "a1" })).toBeNull();+ });+});diff --git a/packages/claude-mod/test/setup.ts b/packages/claude-mod/test/setup.tsnew file mode 100644index 000000000..f39fd2b95--- /dev/null+++ b/packages/claude-mod/test/setup.ts@@ -0,0 +1,9 @@+// The mod runtime has Uint8Array.prototype.toBase64; Node 22 does not yet.+const proto = Uint8Array.prototype as Uint8Array & { toBase64?: () => string };+if (typeof proto.toBase64 !== "function") {+ Object.defineProperty(Uint8Array.prototype, "toBase64", {+ value(this: Uint8Array) {+ return Buffer.from(this.buffer, this.byteOffset, this.byteLength).toString("base64");+ },+ });+}diff --git a/packages/claude-mod/test/spinner.test.ts b/packages/claude-mod/test/spinner.test.tsnew file mode 100644index 000000000..a8c63779a--- /dev/null+++ b/packages/claude-mod/test/spinner.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from "vitest";+import { fileTarget } from "../src/model/events";+import { initialSession, reduce, type SessionState } from "../src/model/session";+import { spinnerLine } from "../src/views/copy";+import { spinnerSuffix } from "../src/views/spinner";++describe("fileTarget", () => {+ const win = "C:\\work\\requests";++ it("is the repo-relative path of a Read, Edit or Write inside the repo", () => {+ for (const tool of ["Read", "Edit", "Write"]) {+ expect(fileTarget({ tool, file_path: "C:\\work\\requests\\src\\requests\\sessions.py" }, win)).toBe(+ "src/requests/sessions.py",+ );+ }+ });++ it("compares Windows paths without case and either separator", () => {+ expect(fileTarget({ tool: "Read", file_path: "c:/Work/Requests/src/api.py" }, win)).toBe("src/api.py");+ expect(fileTarget({ tool: "Read", file_path: "C:\\work\\requests\\a.py" }, "C:\\work\\requests\\")).toBe("a.py");+ });++ it("keeps case on POSIX paths", () => {+ expect(fileTarget({ tool: "Read", file_path: "/work/app/src/x.ts" }, "/work/app")).toBe("src/x.ts");+ expect(fileTarget({ tool: "Read", file_path: "/Work/app/src/x.ts" }, "/work/app")).toBeNull();+ });++ it("is null for other tools, files outside the repo, a sibling with the same prefix, or no repo", () => {+ expect(fileTarget({ tool: "Bash", file_path: "C:\\work\\requests\\a.py" }, win)).toBeNull();+ expect(fileTarget({ tool: "Grep" }, win)).toBeNull();+ expect(fileTarget({ tool: "Read", file_path: "C:\\work\\requests-old\\a.py" }, win)).toBeNull();+ expect(fileTarget({ tool: "Read", file_path: "C:\\elsewhere\\a.py" }, win)).toBeNull();+ expect(fileTarget({ tool: "Read", file_path: 42 }, win)).toBeNull();+ expect(fileTarget({ tool: "Read", file_path: "C:\\work\\requests\\a.py" }, null)).toBeNull();+ });+});++describe("running tool and context reducers", () => {+ const ctx = { callerFiles: 41, contributors: 3 };++ it("tracks the file tool running now; an overlapping call's end does not clear it", () => {+ let s = reduce(initialSession, { type: "toolStarted", tool: { id: "a", file: "x.py" } });+ s = reduce(s, { type: "toolStarted", tool: { id: "b", file: "y.py" } });+ expect(reduce(s, { type: "toolEnded", id: "a" })).toBe(s);+ expect(reduce(s, { type: "toolEnded", id: "b" }).running).toBeNull();+ });++ it("keeps each file's context", () => {+ const s = reduce(initialSession, { type: "contextLoaded", file: "x.py", context: ctx });+ expect(reduce(s, { type: "contextLoaded", file: "y.py", context: ctx }).contexts).toEqual({ "x.py": ctx, "y.py": ctx });+ });++ it("remembers the repo root only while indexed", () => {+ const s = reduce(initialSession, { type: "discovered", mode: "lite", freshness: null, repoRoot: "C:\\r" });+ expect(s.repoRoot).toBe("C:\\r");+ expect(reduce(s, { type: "discovered", mode: "no-cli", freshness: null, repoRoot: "C:\\r" }).repoRoot).toBeNull();+ expect(reduce(initialSession, { type: "discovered", mode: "full", freshness: null }).repoRoot).toBeNull();+ });+});++describe("spinner suffix", () => {+ const running: SessionState = { ...initialSession, running: { id: "a", file: "django/db/models/query.py" } };++ it("names the file, its caller files and contributors once the context has landed", () => {+ const s = { ...running, contexts: { "django/db/models/query.py": { callerFiles: 41, contributors: 3 } } };+ expect(spinnerSuffix(s)).toBe("query.py · 41 caller files · 3 contributors");+ });++ it("says nothing while the context is still on its way, or when no file tool runs", () => {+ expect(spinnerSuffix(running)).toBeNull();+ expect(spinnerSuffix({ ...running, running: null, contexts: { "a.py": { callerFiles: 1, contributors: 1 } } })).toBeNull();+ });++ it("uses singulars, thousands separators, and leaves out unknown or zero counts", () => {+ expect(spinnerLine("a.py", { callerFiles: 1, contributors: 1 })).toBe("a.py · 1 caller file · 1 contributor");+ expect(spinnerLine("src/a.py", { callerFiles: 1204, contributors: null })).toBe("a.py · 1,204 caller files");+ expect(spinnerLine("a.py", { callerFiles: 0, contributors: null })).toBe("a.py");+ });+});diff --git a/packages/claude-mod/test/squeeze.test.ts b/packages/claude-mod/test/squeeze.test.tsnew file mode 100644index 000000000..1d0ee8a1d--- /dev/null+++ b/packages/claude-mod/test/squeeze.test.ts@@ -0,0 +1,147 @@+import { describe, expect, it } from "vitest";+import { bashText, parseSqueeze, runnerFailures, type Squeeze } from "../src/model/squeeze";+import { squeezeLine } from "../src/views/copy";+import { BAR_CELLS, squeezeBar, squeezeView } from "../src/views/squeeze";+import { fixture, golden } from "./fake-host";++// Real `repowise distill <cmd>` output, recorded on the requests index (CRLF,+// as the Windows console wrote it; local paths in the pytest run rewritten to+// a neutral root). The raw counts were checked against the commands run+// without distill: `git log -n 300` prints 2,949 lines, `git ls-files` 130,+// `grep -rn "def " src` 268. git-diff and ruff are cut to their first kept+// lines and the verbatim marker, so their counts are the cut file's.+const CASES = [+ { file: "pytest-failing.txt", ref: "21ece412acd8", original: 123, kept: 59, tokens: 2337, failed: 4, errors: 0 },+ { file: "git-log.txt", ref: "eed993b23bc3", original: 2949, kept: 21, tokens: 25947, failed: 0, errors: 0 },+ { file: "git-diff.txt", ref: "8ba29e69b831", original: 3397, kept: 6, tokens: 29929, failed: 0, errors: 0 },+ { file: "git-ls-files.txt", ref: "41d94b327885", original: 130, kept: 24, tokens: 396, failed: 0, errors: 0 },+ { file: "grep.txt", ref: "4d5207d9f4ad", original: 268, kept: 47, tokens: 4304, failed: 0, errors: 0 },+ { file: "ruff.txt", ref: "4f688e17124a", original: 11968, kept: 6, tokens: 103796, failed: 0, errors: 0 },+];++const marker = (ref: string, lines: number, tokens = 50) =>+ `[repowise#${ref}: ${lines} lines omitted (~${tokens} tokens); restore: repowise expand ${ref}]`;+const A = "aaaaaaaaaaaa";+const B = "bbbbbbbbbbbb";++describe("parseSqueeze over real distill output", () => {+ it.each(CASES)("$file", ({ file, ref, original, kept, tokens, failed, errors }) => {+ expect(parseSqueeze(fixture(`distill/${file}`))).toEqual({+ originalLines: original,+ keptLines: kept,+ omittedTokens: tokens,+ failed,+ errors,+ refs: [ref],+ });+ });++ it("reads the marker core/distill writes (golden line shared with the Python test)", () => {+ const line = golden("distill-marker.txt").trim();+ expect(parseSqueeze(`kept one\nkept two\n\n${line}\n`)).toMatchObject({+ originalLines: 66,+ keptLines: 2,+ omittedTokens: 2337,+ refs: ["21ece412acd8"],+ });+ });++ it("reads the same output with LF line ends", () => {+ const lf = fixture("distill/git-log.txt").replace(/\r\n/g, "\n");+ expect(parseSqueeze(lf)).toMatchObject({ originalLines: 2949, keptLines: 21 });+ });++ it("is null for output distill left alone", () => {+ expect(parseSqueeze(fixture("distill/git-status-undistilled.txt"))).toBeNull();+ });++ it("draws nothing for a marker the command itself printed, anywhere but the end", () => {+ expect(parseSqueeze(`${marker(A, 10)}\nmore output after it\n`)).toBeNull();+ expect(parseSqueeze(`see ${marker(A, 10)} above\n`)).toBeNull();+ });++ it("ignores a marker without counts, or whose restore ref disagrees with its own", () => {+ expect(parseSqueeze(`x\n\n[repowise#${A}: ~6.1k tokens omitted]\n`)).toBeNull();+ expect(parseSqueeze(`[repowise#${A}: 64 lines omitted (~2337 tokens); restore: repowise expand ${B}]`)).toBeNull();+ });++ it("adds up the trailing markers, each ref once", () => {+ expect(parseSqueeze(`one\ntwo\n\n${marker(A, 10)}\n\n${marker(B, 5, 20)}\n${marker(A, 10)}\n`)).toEqual({+ originalLines: 17,+ keptLines: 2,+ omittedTokens: 70,+ failed: 0,+ errors: 0,+ refs: [A, B],+ });+ });+});++describe("runnerFailures", () => {+ it("reads pytest's own summary, failures and errors apart", () => {+ expect(runnerFailures(["==== 4 failed, 1 error, 60 passed in 1.2s ===="])).toEqual({ failed: 4, errors: 1 });+ expect(runnerFailures(["==== 2 errors in 0.3s ===="])).toEqual({ failed: 0, errors: 2 });+ expect(runnerFailures(["==== 60 passed in 1.2s ===="])).toEqual({ failed: 0, errors: 0 });+ });++ it("reads jest and vitest summaries", () => {+ expect(runnerFailures(["Tests: 2 failed, 30 passed, 32 total"])).toEqual({ failed: 2, errors: 0 });+ });++ it("sums every cargo result line", () => {+ expect(+ runnerFailures([+ "test result: FAILED. 8 passed; 3 failed; 0 ignored",+ "test result: FAILED. 1 passed; 2 failed; 0 ignored",+ "test result: ok. 5 passed; 0 failed; 0 ignored",+ ]),+ ).toEqual({ failed: 5, errors: 0 });+ });++ it("counts go's top-level failures, not their subtests", () => {+ expect(runnerFailures(["--- FAIL: TestA (0.00s)", " --- FAIL: TestA/sub (0.00s)", "--- FAIL: TestB (0.00s)", "FAIL"])).toEqual({+ failed: 2,+ errors: 0,+ });+ });++ it("takes nothing from text that only mentions failing", () => {+ expect(runnerFailures(["abc123 Fix 2 failed uploads"])).toEqual({ failed: 0, errors: 0 });+ });+});++describe("bashText", () => {+ it("reads stdout from a Bash result, or the text an errored call carried", () => {+ expect(bashText({ stdout: "out", stderr: "" })).toBe("out");+ expect(bashText("Exit code 1\nout")).toBe("Exit code 1\nout");+ expect(bashText({ stderr: "x" })).toBeNull();+ expect(bashText(null)).toBeNull();+ });+});++describe("squeeze row", () => {+ const s: Squeeze = { originalLines: 1204, keptLines: 38, omittedTokens: 9400, failed: 4, errors: 0, refs: ["9c1e4b2a7f01"] };++ it("says lines before and after, tokens omitted, failures as the runner said them, and the restore command", () => {+ expect(squeezeLine(s)).toBe("1,204 lines → 38 · ~9,400 tokens omitted · 4 failed · repowise expand 9c1e4b2a7f01");+ expect(squeezeLine({ ...s, failed: 4, errors: 1 })).toContain("· 4 failed, 1 error ·");+ expect(squeezeLine({ ...s, failed: 0, errors: 2 })).toContain("· 2 errors ·");+ expect(squeezeLine({ ...s, failed: 0, omittedTokens: 0, refs: ["9c1e4b2a7f01", A] })).toBe(+ "1,204 lines → 38 · repowise expand 9c1e4b2a7f01 (+1 more)",+ );+ });++ it("draws the kept share as a bar, never empty", () => {+ expect(squeezeBar(s)).toBe(`█${"░".repeat(BAR_CELLS - 1)}`);+ expect(squeezeBar({ ...s, keptLines: 602 })).toBe("██████░░░░░░");+ expect(squeezeBar({ ...s, keptLines: 1204 })).toBe("█".repeat(BAR_CELLS));+ });++ it("is one dim row, cut at the edge rather than wrapped", () => {+ expect(squeezeView(s)).toEqual({+ type: "Text",+ props: { dimColor: true, wrap: "truncate-end" },+ children: [`█${"░".repeat(BAR_CELLS - 1)} ${squeezeLine(s)}`],+ });+ });+});diff --git a/packages/claude-mod/test/trail.test.ts b/packages/claude-mod/test/trail.test.tsnew file mode 100644index 000000000..90188a574--- /dev/null+++ b/packages/claude-mod/test/trail.test.ts@@ -0,0 +1,182 @@+import { describe, expect, it } from "vitest";+import { absoluteKey, absolutePath, fromToolCall, relativeTo } from "../src/model/events";+import { initialTrail, reduceTrail, type TrailAction } from "../src/model/trail";+import { layoutMap } from "../src/views/map";+import { resolveOverlay } from "../src/views/overlay";+import { fixture } from "./fake-host";++/** Tool calls recorded from a headless Claude Code 2.1.288 run in a Django copy, its root renamed to C:/work/django (long strings cut). */+const recorded = JSON.parse(fixture("tool-calls.json")) as Record<string, { e: { tool: string; [k: string]: unknown }; r: unknown }>;+const django = { cwd: "C:/work/django", isWindows: true };++const win = { cwd: "C:\\Users\\Dev\\django", isWindows: true };+const posix = { cwd: "/home/dev/django", isWindows: false };+const ok = { result: {} };++describe("fromToolCall, per tool shape", () => {+ it("Read with a Windows absolute path: backslashes, drive letter and case normalized", () => {+ const e = { tool: "Read", tool_use_id: "toolu_1", file_path: "C:\\Users\\Dev\\django\\django\\db\\models\\Query.py" };+ expect(fromToolCall(e, ok, win)).toEqual({ type: "read", path: "c:/users/dev/django/django/db/models/query.py" });+ });++ it("a lowercase drive letter and forward slashes land on the same key", () => {+ const a = fromToolCall({ tool: "Read", file_path: "c:/users/dev/django/setup.py" }, ok, win);+ const b = fromToolCall({ tool: "Read", file_path: "C:\\USERS\\Dev\\django\\setup.py" }, ok, win);+ expect(a).toEqual(b);+ });++ it("keeps case on POSIX, where it is significant", () => {+ expect(fromToolCall({ tool: "Read", file_path: "/home/dev/django/README.rst" }, ok, posix)).toEqual({+ type: "read",+ path: "/home/dev/django/README.rst",+ });+ });++ it("Edit and Write are edits", () => {+ expect(fromToolCall({ tool: "Edit", file_path: "/home/dev/django/a.py" }, ok, posix)).toEqual({ type: "edit", path: "/home/dev/django/a.py" });+ expect(fromToolCall({ tool: "Write", file_path: "/home/dev/django/b.py" }, ok, posix)).toEqual({ type: "edit", path: "/home/dev/django/b.py" });+ });++ it("Grep and Glob hits come from the result, relative to the cwd", () => {+ const grep = fromToolCall(+ { tool: "Grep", pattern: "QuerySet" },+ { result: { mode: "files_with_matches", numFiles: 2, filenames: ["django\\db\\models\\query.py", ".\\tests\\basic\\tests.py"] } },+ win,+ );+ expect(grep).toEqual({+ type: "search",+ paths: ["c:/users/dev/django/django/db/models/query.py", "c:/users/dev/django/tests/basic/tests.py"],+ });+ const glob = fromToolCall({ tool: "Glob", pattern: "**/*.py" }, { result: { filenames: ["/home/dev/django/x.py", 3] } }, posix);+ expect(glob).toEqual({ type: "search", paths: ["/home/dev/django/x.py"] });+ });++ it("a files-with-matches search that found nothing is a search with no hits", () => {+ expect(fromToolCall({ tool: "Grep", pattern: "x" }, { result: { mode: "files_with_matches", filenames: [] } }, posix)).toEqual({+ type: "search",+ paths: [],+ });+ expect(fromToolCall({ tool: "Glob", pattern: "x" }, undefined, posix)).toEqual({ type: "search", paths: [] });+ });++ it("a subagent's read counts: it is Claude's attention too", () => {+ expect(fromToolCall({ tool: "Read", agentId: "sub-1", file_path: "/home/dev/django/a.py" }, ok, posix)).toEqual({+ type: "read",+ path: "/home/dev/django/a.py",+ });+ });++ it("MCP tools, other tools, Lens's own calls, failures and malformed calls are not", () => {+ expect(fromToolCall({ tool: "mcp__plugin_repowise_repowise__get_context", targets: ["a.py"] }, ok, posix)).toBeNull();+ expect(fromToolCall({ tool: "Bash", command: "cat a.py" }, ok, posix)).toBeNull();+ expect(fromToolCall({ tool: "Read", tool_use_id: "toolu_plugin_9", file_path: "/a.py" }, ok, posix)).toBeNull();+ expect(fromToolCall({ tool: "Read", file_path: "/a.py" }, { isError: true, result: "ENOENT" }, posix)).toBeNull();+ expect(fromToolCall({ tool: "Read" }, ok, posix)).toBeNull();+ });+});++describe("fromToolCall on recorded calls", () => {+ const of = (name: string) => fromToolCall(recorded[name]!.e, recorded[name]!.r, django);++ it("Grep files_with_matches: the hits, relative paths with backslashes resolved against the cwd", () => {+ expect(of("grep_files")).toEqual({+ type: "search",+ paths: [+ "c:/work/django/django/db/models/query.py",+ "c:/work/django/tests/queries/tests.py",+ "c:/work/django/tests/queries/test_qs_combinators.py",+ "c:/work/django/tests/queries/test_iterator.py",+ ],+ });+ });++ it("Grep content mode names no files: not a search, so earlier hits stay", () => {+ expect(of("grep_content")).toBeNull();+ });++ it("Glob: its filenames", () => {+ const glob = of("glob") as { type: string; paths: string[] };+ expect(glob.type).toBe("search");+ expect(glob.paths).toContain("c:/work/django/django/db/models/sql/query.py");+ });++ it("Read and a successful Edit: their absolute file_path", () => {+ expect(of("read")).toEqual({ type: "read", path: "c:/work/django/django/db/models/manager.py" });+ expect(of("edit")).toEqual({ type: "edit", path: "c:/work/django/django/db/models/manager.py" });+ });++ it("a failed Edit (isError, a string result) is nothing", () => {+ expect(of("edit_failed")).toBeNull();+ });+});++describe("paths", () => {+ it("absolutePath keeps case and joins relative paths to the cwd", () => {+ expect(absolutePath("django\\db\\Query.py", win)).toBe("C:/Users/Dev/django/django/db/Query.py");+ expect(absolutePath("./a.py", posix)).toBe("/home/dev/django/a.py");+ expect(absoluteKey("\\\\server\\share\\x.py", win)).toBe("//server/share/x.py");+ });++ it("relativeTo matches the root without case on Windows and keeps the file's own case", () => {+ expect(relativeTo("c:/users/dev/django/django/db/models/query.py", "C:\\Users\\Dev\\django\\", true)).toBe(+ "django/db/models/query.py",+ );+ expect(relativeTo("C:\\Users\\Dev\\django\\Docs\\Index.txt", "c:/users/dev/django", true)).toBe("Docs/Index.txt");+ expect(relativeTo("C:/Users/Dev/other/x.py", "C:/Users/Dev/django", true)).toBeNull();+ expect(relativeTo("/home/dev/Django/x.py", "/home/dev/django", false)).toBeNull();+ // A sibling whose name extends the root's is outside it.+ expect(relativeTo("/home/dev/django2/x.py", "/home/dev/django", false)).toBeNull();+ });++ it("a Windows read lands on its map cell regardless of separators and case", () => {+ const layout = layoutMap([{ file_path: "django/db/models/query.py", score: 6, nloc: 10 }], 4, 2, true);+ const action = fromToolCall({ tool: "Read", file_path: "c:\\users\\dev\\DJANGO\\Django\\DB\\models\\query.py" }, ok, win);+ const trail = reduceTrail(initialTrail, action as TrailAction);+ expect(resolveOverlay(layout, trail, "C:\\Users\\Dev\\django").overlay.reads).toEqual([0]);+ });++ it("a POSIX read differing only in case is off the map", () => {+ const layout = layoutMap([{ file_path: "src/App.ts", score: 6, nloc: 10 }], 4, 2, false);+ const trail = reduceTrail(initialTrail, { type: "read", path: "/repo/src/app.ts" });+ expect(resolveOverlay(layout, trail, "/repo").reads.notDrawn).toBe(1);+ });+});++describe("trail reducer", () => {+ it("keeps reads in first-read order, once each", () => {+ let t = reduceTrail(initialTrail, { type: "read", path: "/a" });+ t = reduceTrail(t, { type: "read", path: "/b" });+ const same = reduceTrail(t, { type: "read", path: "/a" });+ expect(same).toBe(t);+ expect(t.reads).toEqual(["/a", "/b"]);+ });++ it("keeps only the newest reads past the cap", () => {+ let t = initialTrail;+ for (let i = 0; i < 205; i++) t = reduceTrail(t, { type: "read", path: `/f${i}` });+ expect(t.reads).toHaveLength(200);+ expect(t.reads[0]).toBe("/f5");+ expect(t.readsCapped).toBe(true);+ });++ it("each search replaces the hits and counts", () => {+ let t = reduceTrail(initialTrail, { type: "search", paths: ["/a"] });+ t = reduceTrail(t, { type: "search", paths: ["/a"] });+ expect(t.hits).toEqual(["/a"]);+ expect(t.searches).toBe(2);+ });++ it("an edit is also a read, and starts loading its callers", () => {+ const t = reduceTrail(initialTrail, { type: "edit", path: "/q.py" });+ expect(t).toMatchObject({ reads: ["/q.py"], edit: "/q.py", edits: 1, callers: { status: "loading" } });+ });++ it("drops callers that answer an older edit", () => {+ let t = reduceTrail(initialTrail, { type: "edit", path: "/a.py" });+ t = reduceTrail(t, { type: "edit", path: "/b.py" });+ const stale = reduceTrail(t, { type: "callers", edits: 1, callers: { status: "ready", paths: ["x"] } });+ expect(stale).toBe(t);+ const fresh = reduceTrail(t, { type: "callers", edits: 2, callers: { status: "failed" } });+ expect(fresh.callers).toEqual({ status: "failed" });+ });+});diff --git a/packages/claude-mod/tsconfig.json b/packages/claude-mod/tsconfig.jsonnew file mode 100644index 000000000..b59ba29b9--- /dev/null+++ b/packages/claude-mod/tsconfig.json@@ -0,0 +1,18 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "lib": ["ES2022", "DOM"],+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "exactOptionalPropertyTypes": true,+ "noImplicitOverride": true,+ "isolatedModules": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "noEmit": true,+ "types": ["node"]+ },+ "include": ["src/**/*.ts", "test/**/*.ts"]+}diff --git a/packages/claude-mod/vitest.config.ts b/packages/claude-mod/vitest.config.tsnew file mode 100644index 000000000..3e9f5b278--- /dev/null+++ b/packages/claude-mod/vitest.config.ts@@ -0,0 +1,14 @@+import { defineConfig } from "vitest/config";++export default defineConfig({+ test: {+ include: ["test/**/*.test.ts"],+ setupFiles: ["test/setup.ts"],+ coverage: {+ provider: "v8",+ include: ["src/model/**", "src/views/**", "src/data/**"],+ reporter: ["text"],+ thresholds: { lines: 90 },+ },+ },+});diff --git a/packages/types/src/chat.ts b/packages/types/src/chat.tsindex 6a4b8dddd..82af8372c 100644--- a/packages/types/src/chat.ts+++ b/packages/types/src/chat.ts@@ -269,6 +269,10 @@ export interface RiskReportArtifactData {classification?: string;warning?: string;error?: string;+ /** `nothing_to_score` when the change has no counted files. */+ status?: string;+ /** True when uncommitted work was scored; false when a clean tree fell back to `HEAD`. */+ working_tree?: boolean;/** `get_change_risk` action-first blocks. */directive?: ChangeRiskDirective;health_delta?: ChangeHealthDeltaData;@@ -282,7 +286,17 @@ export interface RiskReportArtifactData {groups?: Array<{ files: string[]; bridging_files?: string[] }>;[k: string]: unknown;};- impacted_tests?: { tests_to_run?: string[]; status?: string; summary?: string };+ impacted_tests?: {+ tests_to_run?: string[];+ status?: string;+ summary?: string;+ /** `measured` from stored coverage, `inferred` from the dependency graph. */+ basis?: "measured" | "inferred" | "none";+ /** Test ids, or whole test files when inferred. */+ tests_to_run_kind?: "test_id" | "test_file" | null;+ total?: number;+ truncated?: boolean;+ };/** Bug-fix record of the touched files: the "historically fragile" signal. */fix_history?: {available?: boolean;diff --git a/plugins/claude-code/.claude-plugin/plugin.json b/plugins/claude-code/.claude-plugin/plugin.jsonindex d5de7f516..dff618c92 100644--- a/plugins/claude-code/.claude-plugin/plugin.json+++ b/plugins/claude-code/.claude-plugin/plugin.json@@ -10,6 +10,32 @@"homepage": "https://repowise.dev","repository": "https://github.com/repowise-dev/repowise","license": "AGPL-3.0",+ "userConfig": {+ "lens_margin": {+ "type": "boolean",+ "title": "Lens margin notes",+ "description": "Under an Edit or Write, show the governing decision or recent fix history the Repowise hook flagged for that file.",+ "default": true+ },+ "lens_squeeze": {+ "type": "boolean",+ "title": "Lens squeeze rows",+ "description": "Under a Bash result that repowise distill shortened, show the lines before and after and the command that restores the rest.",+ "default": true+ },+ "lens_review": {+ "type": "boolean",+ "title": "Lens change review",+ "description": "After a turn that edits files, review the working tree with get_change_risk and show the result beneath Claude's answer.",+ "default": true+ },+ "lens_pane_autoopen": {+ "type": "boolean",+ "title": "Open the Lens map on the first read",+ "description": "Opens the Lens map pane when Claude first reads a file, if the terminal is wide enough to place it without asking. /lens opens it at any time.",+ "default": false+ }+ },"keywords": ["codebase","code-intelligence",diff --git a/plugins/claude-code/hooks/hooks.json b/plugins/claude-code/hooks/hooks.jsonindex e0ffac121..1de5312ca 100644--- a/plugins/claude-code/hooks/hooks.json+++ b/plugins/claude-code/hooks/hooks.json@@ -1,4 +1,5 @@{+ "modules": ["./lens/lens.js"],"hooks": {"SessionStart": [{diff --git a/plugins/claude-code/hooks/lens/lens.js b/plugins/claude-code/hooks/lens/lens.jsnew file mode 100644index 000000000..f0d2f2b30--- /dev/null+++ b/plugins/claude-code/hooks/lens/lens.js@@ -0,0 +1,3481 @@+// Generated by packages/claude-mod (npm run build:mod). Do not edit.+var __defProp = Object.defineProperty;+var __name = (target, value) => __defProp(target, "name", { value, configurable: true });++// ../api-client/src/client.ts+var config = { baseUrl: "" };+function configureApiClient(next) {+ config = next;+ BASE_URL = next.baseUrl;+}+__name(configureApiClient, "configureApiClient");+var BASE_URL = "";+function resolveToken() {+ const { token } = config;+ if (typeof token === "function") return token();+ return token ?? null;+}+__name(resolveToken, "resolveToken");+function requestHeaders(extra) {+ const headers = {+ "Content-Type": "application/json",+ ...extra+ };+ const token = resolveToken();+ if (token) {+ headers["Authorization"] = `Bearer ${token}`;+ }+ return headers;+}+__name(requestHeaders, "requestHeaders");+var ApiClientError = class extends Error {+ constructor(status, detail) {+ super(`API error ${status}: ${detail}`);+ this.status = status;+ this.detail = detail;+ this.name = "ApiClientError";+ }+ status;+ detail;+ static {+ __name(this, "ApiClientError");+ }+};+function stringifyDetail(detail) {+ if (typeof detail === "string") return detail;+ if (Array.isArray(detail)) {+ const msgs = detail.map(+ (d) => d && typeof d === "object" && "msg" in d ? String(d.msg) : null+ ).filter((m) => !!m).map((m) => m.replace(/^Value error, /, ""));+ if (msgs.length > 0) return msgs.join("; ");+ }+ return null;+}+__name(stringifyDetail, "stringifyDetail");+async function handleResponse(res) {+ if (!res.ok) {+ let detail = res.statusText;+ try {+ const json = await res.json();+ detail = stringifyDetail(json.detail) ?? detail;+ } catch {+ }+ throw new ApiClientError(res.status, detail);+ }+ if (res.status === 204) return void 0;+ return res.json();+}+__name(handleResponse, "handleResponse");+function doFetch(url, init) {+ return (config.fetch ?? fetch)(url, init);+}+__name(doFetch, "doFetch");+function headersToRecord(headers) {+ const out = {};+ if (!headers) return out;+ if (Array.isArray(headers)) {+ for (const [name, value] of headers) out[name] = value;+ } else if (typeof headers.forEach === "function") {+ headers.forEach((value, name) => {+ out[name] = value;+ });+ } else {+ Object.assign(out, headers);+ }+ return out;+}+__name(headersToRecord, "headersToRecord");+function createAdapterFetch(minimal) {+ const adapted = /* @__PURE__ */ __name(async (input2, init) => {+ const url = typeof input2 === "string" ? input2 : "href" in input2 ? input2.href : input2.url;+ const body = init?.body;+ if (body != null && typeof body !== "string") {+ throw new TypeError("createAdapterFetch only sends string bodies");+ }+ const request = { headers: headersToRecord(init?.headers) };+ if (init?.method) request.method = init.method;+ if (body != null) request.body = body;+ if (init?.signal) request.signal = init.signal;+ const res = await minimal(url, request);+ return {+ ok: res.ok,+ status: res.status,+ statusText: `HTTP ${res.status}`,+ json: /* @__PURE__ */ __name(async () => JSON.parse(res.text), "json"),+ text: /* @__PURE__ */ __name(async () => res.text, "text")+ };+ }, "adapted");+ return adapted;+}+__name(createAdapterFetch, "createAdapterFetch");+async function apiGet(path, params, fetchOptions) {+ const url = new URL(`${BASE_URL}${path}`, typeof window !== "undefined" ? window.location.href : "http://localhost");+ if (params) {+ for (const [k, v] of Object.entries(params)) {+ if (v !== void 0 && v !== null) {+ url.searchParams.set(k, String(v));+ }+ }+ }+ const res = await doFetch(url.toString(), {+ method: "GET",+ headers: requestHeaders(),+ ...fetchOptions+ });+ return handleResponse(res);+}+__name(apiGet, "apiGet");+async function apiPost(path, body, fetchOptions, params) {+ const url = new URL(`${BASE_URL}${path}`, typeof window !== "undefined" ? window.location.href : "http://localhost");+ if (params) {+ for (const [k, v] of Object.entries(params)) {+ if (v !== void 0 && v !== null) {+ url.searchParams.set(k, String(v));+ }+ }+ }+ const res = await doFetch(url.toString(), {+ method: "POST",+ headers: requestHeaders(),+ ...body !== void 0 ? { body: JSON.stringify(body) } : {},+ ...fetchOptions+ });+ return handleResponse(res);+}+__name(apiPost, "apiPost");++// ../api-client/src/costs.ts+async function getSavings(repoId, opts = {}) {+ return apiGet(`/api/repos/${repoId}/savings`, {+ days: opts.days+ });+}+__name(getSavings, "getSavings");++// ../api-client/src/health.ts+async function getHealth() {+ return apiGet("/health");+}+__name(getHealth, "getHealth");++// ../api-client/src/repos.ts+async function listRepos() {+ return apiGet("/api/repos");+}+__name(listRepos, "listRepos");++// ../types/src/repos.ts+function normalizeRepoPath(p, isWindows) {+ const slashed = isWindows ? p.replace(/\\/g, "/") : p;+ const trimmed = slashed.replace(/\/+$/, "");+ return isWindows ? trimmed.toLowerCase() : trimmed;+}+__name(normalizeRepoPath, "normalizeRepoPath");++// ../types/src/serve-lock.ts+function isServeLock(value) {+ if (typeof value !== "object" || value === null) return false;+ const v = value;+ return typeof v.pid === "number" && typeof v.host === "string" && typeof v.port === "number" && typeof v.url === "string" && (typeof v.ui_port === "number" || v.ui_port === null) && typeof v.server_version === "string" && typeof v.started_at === "string";+}+__name(isServeLock, "isServeLock");++// src/data/transport.ts+function connectApiClient(host, baseUrl) {+ configureApiClient({ baseUrl, fetch: createAdapterFetch(host.http) });+}+__name(connectApiClient, "connectApiClient");+var TimeoutError = class extends Error {+ static {+ __name(this, "TimeoutError");+ }+ constructor(label, ms) {+ super(`${label} timed out after ${ms} ms`);+ this.name = "TimeoutError";+ }+};+function withTimeout(work, ms, label) {+ let timer;+ const timeout = new Promise((_, reject) => {+ timer = setTimeout(() => reject(new TimeoutError(label, ms)), ms);+ });+ return Promise.race([work, timeout]).finally(() => clearTimeout(timer));+}+__name(withTimeout, "withTimeout");++// src/data/discovery.ts+var HEALTH_TIMEOUT_MS = 800;+var LIST_TIMEOUT_MS = 3e3;+var CONNECT_TIMEOUT_MS = 35e3;+var GIT_TIMEOUT_MS = 5e3;+var MAX_WALK = 20;+var SHA = /^[0-9a-f]{7,64}$/i;+function isWindowsPath(p) {+ return /^[A-Za-z]:[\\/]/.test(p) || p.startsWith("\\\\");+}+__name(isWindowsPath, "isWindowsPath");+function join(dir, rel) {+ return `${dir.replace(/[\\/]+$/, "")}/${rel}`;+}+__name(join, "join");+function parentDir(p) {+ const trimmed = p.replace(/[\\/]+$/, "");+ const cut = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));+ if (cut < 0) return null;+ if (cut === 0) return trimmed === "" ? null : "/";+ return trimmed.slice(0, cut);+}+__name(parentDir, "parentDir");+async function findIndexedRoot(host, cwd2) {+ let dir = cwd2;+ for (let i = 0; dir !== null && i < MAX_WALK; i++) {+ if (await host.fs.exists(join(dir, ".repowise/state.json"))) return dir;+ dir = parentDir(dir);+ }+ return null;+}+__name(findIndexedRoot, "findIndexedRoot");+async function readJson(host, path) {+ try {+ return JSON.parse(await host.fs.read(path));+ } catch {+ return null;+ }+}+__name(readJson, "readJson");+async function readServeLock(host, repoRoot) {+ const parsed = await readJson(host, join(repoRoot, ".repowise/serve.lock.json"));+ return isServeLock(parsed) ? parsed : null;+}+__name(readServeLock, "readServeLock");+var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);+function isLoopbackUrl(url) {+ try {+ const u = new URL(url);+ return u.protocol === "http:" && LOOPBACK_HOSTS.has(u.hostname);+ } catch {+ return false;+ }+}+__name(isLoopbackUrl, "isLoopbackUrl");+async function isPidAlive(host, pid, cwd2) {+ try {+ if (isWindowsPath(cwd2)) {+ const out2 = await host.process.run(["tasklist", "/FI", `PID eq ${pid}`, "/NH", "/FO", "CSV"], cwd2);+ return out2.exitCode === 0 && out2.stdout.includes(`"${pid}"`);+ }+ const out = await host.process.run(["ps", "-p", String(pid), "-o", "pid="], cwd2);+ return out.exitCode === 0 && out.stdout.trim() === String(pid);+ } catch {+ return null;+ }+}+__name(isPidAlive, "isPidAlive");+async function probeServer(host, lock, repoRoot) {+ connectApiClient(host, lock.url);+ try {+ await withTimeout(getHealth(), HEALTH_TIMEOUT_MS, "health");+ } catch {+ return { kind: "down" };+ }+ try {+ const repos = await withTimeout(listRepos(), LIST_TIMEOUT_MS, "listRepos");+ const win = isWindowsPath(repoRoot);+ const target = normalizeRepoPath(repoRoot, win);+ const match = repos.find((r) => r.local_path && normalizeRepoPath(r.local_path, win) === target);+ return match ? { kind: "ok", repoId: match.id, updatedAt: match.updated_at ?? null } : { kind: "unlisted" };+ } catch (err) {+ if (err instanceof ApiClientError && (err.status === 401 || err.status === 403)) return { kind: "auth" };+ return { kind: "down" };+ }+}+__name(probeServer, "probeServer");+async function mcpReachable(host) {+ try {+ return await withTimeout(host.mcp.connect(), CONNECT_TIMEOUT_MS, "mcp connect");+ } catch {+ return false;+ }+}+__name(mcpReachable, "mcpReachable");+async function unindexedMode(host, cwd2) {+ const inWorkTree = (await git(host, cwd2, ["rev-parse", "--is-inside-work-tree"]))?.trim() === "true";+ if (!inWorkTree) return "no-repo";+ return await mcpReachable(host) ? "no-index" : "no-cli";+}+__name(unindexedMode, "unindexedMode");+async function serverState(host, repoRoot) {+ const lock = await readServeLock(host, repoRoot);+ if (!lock || !isLoopbackUrl(lock.url)) return { kind: "down" };+ if (await isPidAlive(host, lock.pid, repoRoot) === false) return { kind: "down" };+ return probeServer(host, lock, repoRoot);+}+__name(serverState, "serverState");+async function discover(host) {+ const cwd2 = await host.session.cwd();+ const repoRoot = await findIndexedRoot(host, cwd2);+ if (repoRoot === null) return { mode: await unindexedMode(host, cwd2), repoRoot };+ const server = await serverState(host, repoRoot);+ if (server.kind === "ok") return { mode: "full", repoRoot, repo: { id: server.repoId, updatedAt: server.updatedAt } };+ if (!await mcpReachable(host)) return { mode: "no-cli", repoRoot };+ const liteReason = server.kind === "down" ? "no-server" : server.kind;+ return { mode: "lite", liteReason, repoRoot };+}+__name(discover, "discover");+async function git(host, cwd2, args) {+ try {+ const out = await withTimeout(host.process.run(["git", ...args], cwd2), GIT_TIMEOUT_MS, "git");+ return out.exitCode === 0 ? out.stdout : null;+ } catch {+ return null;+ }+}+__name(git, "git");+async function updateRunning(host, repoRoot) {+ const lock = await readJson(host, join(repoRoot, ".repowise/.update.lock"));+ const pid = lock?.pid;+ return typeof pid === "number" && await isPidAlive(host, pid, repoRoot) === true;+}+__name(updateRunning, "updateRunning");+async function readFreshness(host, repoRoot) {+ const state2 = await readJson(host, join(repoRoot, ".repowise/state.json"));+ const indexed = state2?.last_sync_commit;+ if (typeof indexed !== "string" || !SHA.test(indexed)) return null;+ const head = (await git(host, repoRoot, ["rev-parse", "HEAD"]))?.trim();+ if (!head || !SHA.test(head) || head === indexed) return null;+ if (await updateRunning(host, repoRoot)) return null;+ const diff = await git(host, repoRoot, ["diff", "--name-only", indexed, head, "--"]);+ const changedFiles = diff === null ? null : diff.split("\n").filter((l) => l.trim() !== "").length;+ return { changedFiles };+}+__name(readFreshness, "readFreshness");++// src/data/mcp.ts+var PLUGIN_NAME = "repowise";+var LENS_TOOLS = ["get_context", "get_change_risk", "get_why", "get_answer"];+var PLUGIN_SERVER_FORMS = ["plugin:repowise:repowise", "plugin_repowise_repowise"];+var DEFAULT_TIMEOUT_MS = 1e4;+var resolvedServer = null;+var resolving = null;+function resetMcp() {+ resolvedServer = null;+ resolving = null;+}+__name(resetMcp, "resetMcp");+function warmMcp(host) {+ if (resolvedServer !== null || resolving !== null) return;+ const asked = host.mcp.server().then((name) => {+ if (name !== null && PLUGIN_SERVER_FORMS.includes(name)) resolvedServer = name;+ }).catch(() => void 0).finally(() => {+ if (resolving === asked) resolving = null;+ });+ resolving = asked;+}+__name(warmMcp, "warmMcp");+async function mcpReady(host, timeoutMs = DEFAULT_TIMEOUT_MS) {+ warmMcp(host);+ const pending = resolving;+ if (resolvedServer === null && pending !== null) await withTimeout(pending, timeoutMs, "MCP connect").catch(() => void 0);+ return resolvedServer !== null;+}+__name(mcpReady, "mcpReady");+function toolName(serverForm, tool) {+ return `mcp__${serverForm.replace(/[^A-Za-z0-9_-]/g, "_")}__${tool}`;+}+__name(toolName, "toolName");+var OWN_TOOL_NAMES = new Set(+ PLUGIN_SERVER_FORMS.flatMap((form) => LENS_TOOLS.map((tool) => toolName(form, tool)))+);+function isOwnLensCall(e, originPlugin) {+ if (originPlugin !== PLUGIN_NAME) return false;+ if (typeof e.tool_use_id !== "string" || !e.tool_use_id.startsWith("toolu_plugin_")) return false;+ return OWN_TOOL_NAMES.has(e.tool);+}+__name(isOwnLensCall, "isOwnLensCall");+function parse(result, tool) {+ const text2 = result.content[0]?.text;+ if (result.isError) throw new Error(`${tool} failed: ${String(text2).slice(0, 200)}`);+ if (typeof text2 !== "string") throw new Error(`${tool} returned no text`);+ const parsed = JSON.parse(text2);+ return parsed !== null && typeof parsed === "object" && "result" in parsed ? parsed.result : parsed;+}+__name(parse, "parse");+function callTool(host, tool, args, opts = {}) {+ if (resolvedServer === null) {+ warmMcp(host);+ return Promise.reject(new Error("repowise MCP server name not resolved yet"));+ }+ const call = host.mcp.call(resolvedServer, tool, args).then((r) => parse(r, tool));+ return withTimeout(call, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS, tool);+}+__name(callTool, "callTool");+async function fetchFileContext(host, path) {+ const result = await callTool(host, "get_context", {+ targets: [path],+ include: ["callers", "ownership"]+ });+ const target = result.targets?.[path];+ if (target === void 0 || target.error !== void 0) return null;+ const callers = target.callers_total ?? target.callers?.length;+ const contributors = target.ownership?.contributor_count;+ return {+ callerFiles: typeof callers === "number" ? callers : null,+ contributors: typeof contributors === "number" ? contributors : null+ };+}+__name(fetchFileContext, "fetchFileContext");++// ../ui/src/lib/format.ts+function parseDate(date) {+ if (date instanceof Date) return date;+ if (!/[zZ]|[+-]\d\d?:\d\d$/.test(date.trim())) {+ return /* @__PURE__ */ new Date(`${date.trim()}Z`);+ }+ return new Date(date);+}+__name(parseDate, "parseDate");+var NUMBER_FORMAT = new Intl.NumberFormat("en-US");+function formatNumber(n) {+ return NUMBER_FORMAT.format(n);+}+__name(formatNumber, "formatNumber");+function formatRelativeTime(date) {+ const d = parseDate(date);+ const now = Date.now();+ const diff = now - d.getTime();+ const seconds = Math.floor(diff / 1e3);+ const minutes = Math.floor(seconds / 60);+ const hours = Math.floor(minutes / 60);+ const days = Math.floor(hours / 24);+ const weeks = Math.floor(days / 7);+ const months = Math.floor(days / 30);+ if (seconds < 10) return "just now";+ if (seconds < 60) return `${seconds}s ago`;+ if (minutes < 60) return `${minutes}m ago`;+ if (hours < 24) return `${hours}h ago`;+ if (days < 7) return `${days}d ago`;+ if (weeks < 5) return `${weeks}w ago`;+ if (months < 12) return `${months}mo ago`;+ return `${Math.floor(months / 12)}y ago`;+}+__name(formatRelativeTime, "formatRelativeTime");+function formatRelativeTimeOrNull(iso, fallback = "—") {+ if (!iso) return fallback;+ const d = parseDate(iso);+ if (Number.isNaN(d.getTime()) || d.getTime() > Date.now()) return fallback;+ return formatRelativeTime(d);+}+__name(formatRelativeTimeOrNull, "formatRelativeTimeOrNull");++// src/format.ts+function countOf(n, singular, plural) {+ return `${formatNumber(n)} ${n === 1 ? singular : plural}`;+}+__name(countOf, "countOf");+function fit(text2, columns) {+ if (columns <= 0) return "";+ if (text2.length <= columns) return text2;+ return `${text2.slice(0, columns - 1).trimEnd()}…`;+}+__name(fit, "fit");++// ../api-client/src/blast-radius.ts+async function analyzeBlastRadius(repoId, body) {+ return apiPost(+ `/api/repos/${repoId}/blast-radius`,+ body+ );+}+__name(analyzeBlastRadius, "analyzeBlastRadius");++// ../api-client/src/code-health.ts+async function getHealthMap(repoId, opts = {}) {+ return apiGet(`/api/repos/${repoId}/health/map`, {+ cap: opts.cap,+ active: opts.active?.length ? opts.active.join(",") : void 0,+ scope: opts.scope,+ counts: opts.counts+ });+}+__name(getHealthMap, "getHealthMap");++// src/model/events.ts+function fromTurnComplete(e) {+ return e.agentId === void 0 ? { type: "turnCompleted" } : null;+}+__name(fromTurnComplete, "fromTurnComplete");+var FILE_TOOLS = /* @__PURE__ */ new Set(["Read", "Edit", "Write"]);+function fileTarget(e, repoRoot) {+ if (!FILE_TOOLS.has(e.tool) || repoRoot === null || typeof e.file_path !== "string") return null;+ const windows = /^[A-Za-z]:[\\/]|^[\\/]{2}/.test(repoRoot);+ return relativeTo(e.file_path, repoRoot, windows);+}+__name(fileTarget, "fileTarget");+var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "Write"]);+var STANDING = /^\[repowise\] .+? is governed by a standing decision: (.+?)(?: because .*)?\.$/;+var MINED = /^\[repowise\] .+? has a decision recorded in it, mined but not reviewed: (.+?)(?: because .*)?\.$/;+var FIXES = /^\[repowise\] .+? has been bug-fixed (\d+)x in the last 6 months, last (.+?)(?: \(bug magnet\))?(?:; mostly in (.+?))?\.$/;+function stripConfirmed(line2) {+ return line2.replace(/ \(confirmed across \d+ sessions\)\.$/, ".");+}+__name(stripConfirmed, "stripConfirmed");+function notesFromAugment(additionalContext) {+ if (!Array.isArray(additionalContext)) return [];+ const notes = [];+ const lines = additionalContext.filter((c) => typeof c === "string").flatMap((c) => c.split(/\r?\n/));+ for (const raw of lines) {+ const line2 = stripConfirmed(raw.trim());+ const standing = STANDING.exec(line2);+ const decision = standing ?? MINED.exec(line2);+ const fixes = FIXES.exec(line2);+ if (decision !== null && !notes.some((n) => n.kind === "decision")) {+ notes.push({ kind: "decision", reviewed: standing !== null, title: decision[1] });+ } else if (fixes !== null && !notes.some((n) => n.kind === "fixes")) {+ notes.push({ kind: "fixes", count: Number(fixes[1]), age: fixes[2], symbol: fixes[3] ?? null });+ }+ }+ return notes;+}+__name(notesFromAugment, "notesFromAugment");+function savingsTotals(s) {+ return {+ tokens: s.saved_input_tokens,+ inferredTokens: Math.min(s.inferred_saved_input_tokens, s.saved_input_tokens),+ usd: s.priced_input_savings_usd+ };+}+__name(savingsTotals, "savingsTotals");+function savingsSince(now, base) {+ const tokens = now.tokens - base.tokens;+ const inferredTokens = now.inferredTokens - base.inferredTokens;+ const usd = now.usd - base.usd;+ if (tokens < 0 || inferredTokens < 0 || usd < 0) return null;+ return { tokens, inferredTokens: Math.min(inferredTokens, tokens), usd };+}+__name(savingsSince, "savingsSince");+var OBSERVED_TOOLS = /* @__PURE__ */ new Set(["Read", "Edit", "Write", "Grep", "Glob"]);+var OWN_CALL_PREFIX = "toolu_plugin_";+function absolutePath(raw, ctx) {+ const absolute = ctx.isWindows ? /^[A-Za-z]:[\\/]|^\\\\/.test(raw) : raw.startsWith("/");+ const joined = absolute ? raw : `${ctx.cwd.replace(/[\\/]+$/, "")}/${raw.replace(/^\.[\\/]/, "")}`;+ return ctx.isWindows ? joined.replace(/\\/g, "/") : joined;+}+__name(absolutePath, "absolutePath");+function absoluteKey(raw, ctx) {+ return normalizeRepoPath(absolutePath(raw, ctx), ctx.isWindows);+}+__name(absoluteKey, "absoluteKey");+function relativeTo(absolute, root, isWindows) {+ const rootKey = normalizeRepoPath(root, isWindows);+ const slashed = isWindows ? absolute.replace(/\\/g, "/") : absolute;+ if (!normalizeRepoPath(slashed, isWindows).startsWith(`${rootKey}/`)) return null;+ return slashed.slice(rootKey.length + 1);+}+__name(relativeTo, "relativeTo");+function filenamesOf(out) {+ const names = typeof out.result === "object" ? out.result.filenames : void 0;+ return Array.isArray(names) ? names.filter((v) => typeof v === "string") : [];+}+__name(filenamesOf, "filenamesOf");+function isContentGrep(tool, out) {+ return tool === "Grep" && typeof out.result === "object" && out.result.mode === "content";+}+__name(isContentGrep, "isContentGrep");+function searchAction(out, ctx) {+ return { type: "search", paths: filenamesOf(out).map((f) => absoluteKey(f, ctx)) };+}+__name(searchAction, "searchAction");+function fileAction(e, ctx) {+ const raw = e["file_path"];+ if (typeof raw !== "string") return null;+ const path = absoluteKey(raw, ctx);+ return e.tool === "Read" ? { type: "read", path } : { type: "edit", path };+}+__name(fileAction, "fileAction");+function fromToolCall(e, outcome, ctx) {+ if (!OBSERVED_TOOLS.has(e.tool) || e.tool_use_id?.startsWith(OWN_CALL_PREFIX)) return null;+ const out = outcome ?? {};+ if (out.isError === true || isContentGrep(e.tool, out)) return null;+ return e.tool === "Grep" || e.tool === "Glob" ? searchAction(out, ctx) : fileAction(e, ctx);+}+__name(fromToolCall, "fromToolCall");+function touchedPath(e, cwd2, repoRoot) {+ const raw = typeof e.file_path === "string" ? e.file_path : e["notebook_path"];+ if (typeof raw !== "string") return null;+ const base = cwd2 ?? repoRoot;+ if (base === null) return raw;+ const isWindows = /^[A-Za-z]:[\/]|^[\/]{2}/.test(base);+ const abs = absolutePath(raw, { cwd: base, isWindows });+ return (repoRoot === null ? null : relativeTo(abs, repoRoot, isWindows)) ?? abs;+}+__name(touchedPath, "touchedPath");++// src/model/trail.ts+var MAX_READS = 200;+var initialTrail = {+ reads: [],+ readsCapped: false,+ hits: [],+ searches: 0,+ edit: null,+ edits: 0,+ callers: null+};+function withRead(state2, path) {+ if (state2.reads.includes(path)) return state2;+ const reads = [...state2.reads, path];+ if (reads.length <= MAX_READS) return { ...state2, reads };+ return { ...state2, reads: reads.slice(reads.length - MAX_READS), readsCapped: true };+}+__name(withRead, "withRead");+function reduceTrail(state2, action) {+ switch (action.type) {+ case "read":+ return withRead(state2, action.path);+ case "search":+ return { ...state2, hits: action.paths, searches: state2.searches + 1 };+ case "edit":+ return {+ ...withRead(state2, action.path),+ edit: action.path,+ edits: state2.edits + 1,+ callers: { status: "loading" }+ };+ case "callers":+ return action.edits === state2.edits ? { ...state2, callers: action.callers } : state2;+ }+}+__name(reduceTrail, "reduceTrail");++// src/views/copy.ts+var HINTS = {+ "no-server": "Lens map needs the local server: repowise serve --no-ui",+ auth: "local server needs an API key; Lens does not read keys",+ unlisted: "Lens map needs a local server for this repo: repowise serve --no-ui",+ "no-index": "index this repo for Lens: repowise init --no-prose --yes",+ "no-cli": "Lens needs the Repowise CLI: pip install repowise"+};+function freshnessLine(f) {+ const changed = f.changedFiles === null ? "" : ` (${countOf(f.changedFiles, "file", "files")} changed)`;+ return `index behind HEAD${changed} · repowise update`;+}+__name(freshnessLine, "freshnessLine");+function spinnerLine(file, ctx) {+ const parts = [file.slice(file.lastIndexOf("/") + 1)];+ if (ctx.callerFiles) parts.push(countOf(ctx.callerFiles, "caller file", "caller files"));+ if (ctx.contributors) parts.push(countOf(ctx.contributors, "contributor", "contributors"));+ return parts.join(" · ");+}+__name(spinnerLine, "spinnerLine");+function squeezeLine(s) {+ const parts = [`${countOf(s.originalLines, "line", "lines")} → ${s.keptLines.toLocaleString("en-US")}`];+ if (s.omittedTokens > 0) parts.push(`~${countOf(s.omittedTokens, "token", "tokens")} omitted`);+ const failures = [s.failed > 0 ? `${s.failed.toLocaleString("en-US")} failed` : "", s.errors > 0 ? countOf(s.errors, "error", "errors") : ""];+ if (s.failed + s.errors > 0) parts.push(failures.filter((f) => f !== "").join(", "));+ const more = s.refs.length > 1 ? ` (+${s.refs.length - 1} more)` : "";+ parts.push(`repowise expand ${s.refs[0]}${more}`);+ return parts.join(" · ");+}+__name(squeezeLine, "squeezeLine");+function marginLine(note) {+ if (note.kind === "decision") {+ return note.reviewed ? `a standing decision covers this file: ${note.title}` : `a decision found in this file, not yet reviewed: ${note.title}`;+ }+ const where = note.symbol === null ? "" : `, mostly in ${note.symbol}`;+ return `fixed ${countOf(note.count, "time", "times")} in 6 months, most recently ${note.age}${where}`;+}+__name(marginLine, "marginLine");+function savingsLine(d, columns) {+ const inferred = d.inferredTokens > 0 ? ` (${d.inferredTokens.toLocaleString("en-US")} inferred)` : "";+ const usd = d.usd >= 5e-3 ? ` · $${d.usd.toFixed(2)}` : "";+ const head = `${countOf(d.tokens, "token", "tokens")}${inferred}${usd} saved`;+ const full = `${head} since this session started · all agents on this repo`;+ return full.length <= columns ? full : `${head} this session · all agents`;+}+__name(savingsLine, "savingsLine");+var REVIEWING = "Reviewing the change...";+var REVIEW_TIMEOUT_S = 20;+var REVIEW_TIMED_OUT = `Change review timed out after ${REVIEW_TIMEOUT_S} s`;+var RUN_TESTS = "Run tests";+var WHY = "Why";+var DETAILS = "Details";+var OVERLAP_MARK = "◦";+function reviewFailed(message) {+ return `Change review could not run: ${message}`;+}+__name(reviewFailed, "reviewFailed");+function reviewScope(ref, workingTree, changed) {+ const where = workingTree ? ref : `${ref} (no uncommitted changes)`;+ return changed === null ? where : `${where}, ${countOf(changed, "changed file", "changed files")}`;+}+__name(reviewScope, "reviewScope");+function noNewFindings(analyzed) {+ return `no new findings in ${analyzed === 1 ? "the 1 changed file" : `all ${analyzed.toLocaleString("en-US")} changed files`}`;+}+__name(noNewFindings, "noNewFindings");+function healthImproved(resolved) {+ return `improved, ${countOf(resolved, "finding", "findings")} resolved, none new`;+}+__name(healthImproved, "healthImproved");+var HEALTH_NOT_REPORTED = "not reported";+var NO_NEW_FINDINGS = "no new findings";+var PARTLY_COMPARED = "partly compared, no new findings";+function notCompared(why) {+ return why === "" ? "not compared" : `not compared: ${why}`;+}+__name(notCompared, "notCompared");+function improvedShort(resolved) {+ return `improved, ${resolved.toLocaleString("en-US")} resolved`;+}+__name(improvedShort, "improvedShort");+function newFindings(total, required2) {+ return `${countOf(total, "new finding", "new findings")}, ${required2 ? "review required" : "low severity"}`;+}+__name(newFindings, "newFindings");+function resolvedToo(resolved) {+ return `${countOf(resolved, "finding", "findings")} resolved`;+}+__name(resolvedToo, "resolvedToo");+function findingLine(f) {+ const at = f.lines === void 0 ? f.path : `${f.path}:${f.lines[0]}`;+ return `${f.severity} ${f.biomarker}: ${f.reason} (${at})`;+}+__name(findingLine, "findingLine");+function moreFindings(more) {+ return `and ${more.toLocaleString("en-US")} more (Details)`;+}+__name(moreFindings, "moreFindings");+function partialScope(analyzed, changed, reasons) {+ const why = Object.entries(reasons).map(([reason, n]) => `${n.toLocaleString("en-US")} ${reason.replace(/_/g, " ")}`).join(", ");+ const skipped = changed - analyzed;+ return `Scope: compared ${analyzed.toLocaleString("en-US")} of ${countOf(changed, "changed file", "changed files")}; ${skipped.toLocaleString("en-US")} not analysed${why ? ` (${why})` : ""}, so this is not a clean bill`;+}+__name(partialScope, "partialScope");+function diffShape(percentile) {+ const where = percentile === null || percentile === void 0 ? "not ranked (no recent commits to compare)" : `bigger than ${Math.round(percentile)}% of this repo's recent commits`;+ return `Diff shape: ${where}; size, not danger`;+}+__name(diffShape, "diffShape");+function testsBasis(measured) {+ return measured ? "measured by stored coverage" : "inferred from the dependency graph, not measured";+}+__name(testsBasis, "testsBasis");+function testsLine(t) {+ const count2 = countOf(t.total, t.files ? "test file" : "test", t.files ? "test files" : "tests");+ const shown = t.truncated ? ` (first ${t.tests.length.toLocaleString("en-US")} shown)` : "";+ return `Tests to run: ${count2}, ${testsBasis(t.measured)}${shown}: ${t.tests.join(", ")}`;+}+__name(testsLine, "testsLine");+function overlapLine(branches, files, more) {+ const who = countOf(branches.length, "other branch", "other branches") + (more ? " or more" : "");+ const what = files.length === 1 ? files[0] : countOf(files.length, "changed file", "changed files");+ const verb = branches.length === 1 && !more ? "edits" : "edit";+ return `${OVERLAP_MARK} ${who} also ${verb} ${what} (${branches.join(", ")})`;+}+__name(overlapLine, "overlapLine");+function overlapShort(branches) {+ return `${OVERLAP_MARK} ${countOf(branches, "other branch edits", "other branches edit")} these files`;+}+__name(overlapShort, "overlapShort");+function directiveLines(d) {+ const out = [`Change review: ${d.status.replace(/_/g, " ")}`, d.headline];+ if (d.reasons?.length) out.push("Reasons:", ...d.reasons.map((r) => ` ${r}`));+ if (d.next_actions?.length) out.push("Next actions:", ...d.next_actions.map((a) => ` ${a}`));+ return out;+}+__name(directiveLines, "directiveLines");+function runTestsPrompt(t) {+ const rest = t.truncated ? ` (the first ${t.tests.length} of ${t.total})` : "";+ return `Run the tests Repowise names for this change${rest}, ${testsBasis(t.measured)}: ${t.tests.join(" ")}`;+}+__name(runTestsPrompt, "runTestsPrompt");+var MAP_COPY = {+ title: "Lens",+ looking: "Lens map: looking for the local server",+ loading: "Lens map: loading the health map",+ failed: "Lens map could not load the health map; it tries again on /lens",+ desktop: "Lens map: not drawn on this surface (terminal and desktop app only)",+ tooLarge: "Lens map has too much detail to draw here; the terminal map shows it",+ noScore: "Not scored",+ read: "Claude read",+ edited: "edited",+ importer: "imports the edited file",+ match: "search match",+ waiting: "Lens map is ready; this pane is too narrow to open on its own. Run /lens"+};+function mapAlt(drawn) {+ return `Code health map: ${countOf(drawn, "file", "files")} drawn, colored by health band, with the files Claude read and edited marked`;+}+__name(mapAlt, "mapAlt");+function notPlacedLine(reason) {+ return `Lens map needs a wider terminal: ${reason}`;+}+__name(notPlacedLine, "notPlacedLine");+var SCOPE_REST = "rest empty or too small";+function indexedPart(age) {+ return `indexed ${age}`;+}+__name(indexedPart, "indexedPart");+function scopeParts(s) {+ const parts = s.drawn === s.repositoryTotal ? [`${countOf(s.drawn, "file", "files")}, all drawn`] : [`${formatNumber(s.drawn)} of ${countOf(s.repositoryTotal, "file", "files")} drawn at this size`, SCOPE_REST];+ if (s.indexed !== null) parts.push(indexedPart(s.indexed));+ if (s.beyondCap > 0) parts.push(`${formatNumber(s.beyondCap)} beyond the ${formatNumber(s.cap)}-file cap`);+ return parts;+}+__name(scopeParts, "scopeParts");+function readsLine(reads, matched, columns = Number.POSITIVE_INFINITY) {+ const count2 = reads.capped ? `${formatNumber(reads.count)}+` : formatNumber(reads.count);+ const full = [];+ const short = [];+ if (reads.count > 0) {+ full.push(reads.capped ? `${count2} files read` : countOf(reads.count, "file read", "files read"));+ short.push(`${count2} read`);+ }+ if (reads.notDrawn > 0) {+ full.push(`${formatNumber(reads.notDrawn)} not drawn`);+ short.push(`${formatNumber(reads.notDrawn)} not drawn`);+ }+ if (matched !== null) {+ full.push(`last search matched ${countOf(matched, "file", "files")}`);+ short.push(`search matched ${formatNumber(matched)}`);+ }+ if (full.length === 0) return null;+ const line2 = full.join(" · ");+ return line2.length <= columns ? line2 : short.join(" · ");+}+__name(readsLine, "readsLine");+function callersLine(name, callers, notDrawn, columns = Number.POSITIVE_INFINITY) {+ if (callers === null || callers.status === "loading") return `edited ${name} · finding the files that import it`;+ if (callers.status === "failed") return `edited ${name} · import graph unavailable`;+ const missing = notDrawn === 0 ? "" : ` · ${formatNumber(notDrawn)} not drawn`;+ const full = `edited ${name} · ${countOf(callers.paths.length, "file imports", "files import")} it (from imports, not calls)${missing}`;+ if (full.length <= columns) return full;+ const rest = ` · ${formatNumber(callers.paths.length)} import it${missing}`;+ return `edited ${fit(name, columns - "edited ".length - rest.length)}${rest}`;+}+__name(callersLine, "callersLine");+var PANE_COPY = {+ command: "Open Lens: the health map, ask the index, and the session recap",+ argumentHint: "[map | ask <question> | recap]",+ tabs: { map: "Map", ask: "Ask", recap: "Recap" },+ askLabel: "ask ",+ askPlaceholder: "why ...? asks the decision records; anything else asks the index",+ askSubmit: "ask",+ askIdle: "Ask about this repo. Answers cite the evidence they used.",+ askBusy: "still answering the last question; ask again when it lands",+ noEvidence: "no evidence cited",+ fromIndex: "Built from the index",+ fromModel: "Written by this repo's configured model, from the index"+};+var ASK_CHARS = 4e3;+function askingLine(tool) {+ return tool === "get_why" ? "asking the decision records..." : "asking the index...";+}+__name(askingLine, "askingLine");+function askFailedLine(message) {+ return `Could not answer: ${message}`;+}+__name(askFailedLine, "askFailedLine");+function askCut(chars) {+ return `reply cut at ${formatNumber(chars)} characters`;+}+__name(askCut, "askCut");+function moreRows(more) {+ return `and ${formatNumber(more)} more`;+}+__name(moreRows, "moreRows");+var RECAP_COPY = {+ files: "Files",+ fromReview: "from the last change review",+ review: "Change review",+ health: "Code health",+ findings: "Findings",+ tests: "Tests to run",+ overlap: "Branches overlapping",+ saved: "Saved",+ decisions: "Decisions surfaced",+ noReview: "none this session",+ notCompared: "not compared",+ noTests: "none named",+ noOverlap: "none found",+ notReported: "not reported",+ noSavings: "nothing yet since this session started",+ savingsNeedServer: "needs the local server: repowise serve --no-ui",+ noDecisions: "none",+ noModel: "Lens made no model calls.",+ fromIndex: "Every figure here is read from the local index."+};+function filesTouched(edited, touched) {+ const all = touched.capped ? `${formatNumber(touched.count)}+` : formatNumber(touched.count);+ return `${formatNumber(edited)} edited of ${all} ${touched.count === 1 && !touched.capped ? "file" : "files"} touched`;+}+__name(filesTouched, "filesTouched");+function findingsCounts(resolved, total) {+ return `${formatNumber(resolved)} resolved · ${countOf(total, "new finding", "new findings")}`;+}+__name(findingsCounts, "findingsCounts");+function testsToRunCount(t) {+ const count2 = countOf(t.total, t.files ? "test file" : "test", t.files ? "test files" : "tests");+ return `${count2}, ${t.measured ? "measured" : "inferred"}`;+}+__name(testsToRunCount, "testsToRunCount");+function decisionsSurfaced(titles) {+ return `${formatNumber(titles.length)}: ${titles.join("; ")}`;+}+__name(decisionsSurfaced, "decisionsSurfaced");+function recapFooter(modelAsks) {+ if (modelAsks === 0) return `${RECAP_COPY.noModel} ${RECAP_COPY.fromIndex}`;+ const asks = countOf(modelAsks, "Ask reply", "Ask replies");+ return `${RECAP_COPY.noModel} ${asks} from get_answer may have been written by this repo's configured model.`;+}+__name(recapFooter, "recapFooter");+var BRIEF_COPY = {+ compacted: "context compacted",+ button: "Brief Claude",+ intro: "The context was compacted. This brief is built from the Repowise index and this session's edits:",+ files: "Files edited:",+ decisions: "Decisions in play:",+ review: "Open review items:"+};+var BRIEF_CHARS = 1200;+function briefDecision(title, reviewed) {+ return reviewed ? `${title} (standing decision)` : `${title} (found in the code, not yet reviewed)`;+}+__name(briefDecision, "briefDecision");+function briefTests(t) {+ return `tests to run, ${testsBasis(t.measured)}: ${t.tests.join(" ")}`;+}+__name(briefTests, "briefTests");++// ../../node_modules/d3-hierarchy/src/hierarchy/count.js+function count(node) {+ var sum = 0, children = node.children, i = children && children.length;+ if (!i) sum = 1;+ else while (--i >= 0) sum += children[i].value;+ node.value = sum;+}+__name(count, "count");+function count_default() {+ return this.eachAfter(count);+}+__name(count_default, "default");++// ../../node_modules/d3-hierarchy/src/hierarchy/each.js+function each_default(callback, that) {+ let index = -1;+ for (const node of this) {+ callback.call(that, node, ++index, this);+ }+ return this;+}+__name(each_default, "default");++// ../../node_modules/d3-hierarchy/src/hierarchy/eachBefore.js+function eachBefore_default(callback, that) {+ var node = this, nodes = [node], children, i, index = -1;+ while (node = nodes.pop()) {+ callback.call(that, node, ++index, this);+ if (children = node.children) {+ for (i = children.length - 1; i >= 0; --i) {+ nodes.push(children[i]);+ }+ }+ }+ return this;+}+__name(eachBefore_default, "default");++// ../../node_modules/d3-hierarchy/src/hierarchy/eachAfter.js+function eachAfter_default(callback, that) {+ var node = this, nodes = [node], next = [], children, i, n, index = -1;+ while (node = nodes.pop()) {+ next.push(node);+ if (children = node.children) {+ for (i = 0, n = children.length; i < n; ++i) {+ nodes.push(children[i]);+ }+ }+ }+ while (node = next.pop()) {+ callback.call(that, node, ++index, this);+ }+ return this;+}+__name(eachAfter_default, "default");++// ../../node_modules/d3-hierarchy/src/hierarchy/find.js+function find_default(callback, that) {+ let index = -1;+ for (const node of this) {+ if (callback.call(that, node, ++index, this)) {+ return node;+ }+ }+}+__name(find_default, "default");++// ../../node_modules/d3-hierarchy/src/hierarchy/sum.js+function sum_default(value) {+ return this.eachAfter(function(node) {+ var sum = +value(node.data) || 0, children = node.children, i = children && children.length;+ while (--i >= 0) sum += children[i].value;+ node.value = sum;+ });+}+__name(sum_default, "default");++// ../../node_modules/d3-hierarchy/src/hierarchy/sort.js+function sort_default(compare) {+ return this.eachBefore(function(node) {+ if (node.children) {+ node.children.sort(compare);+ }+ });+}+__name(sort_default, "default");++// ../../node_modules/d3-hierarchy/src/hierarchy/path.js+function path_default(end) {+ var start = this, ancestor = leastCommonAncestor(start, end), nodes = [start];+ while (start !== ancestor) {+ start = start.parent;+ nodes.push(start);+ }+ var k = nodes.length;+ while (end !== ancestor) {+ nodes.splice(k, 0, end);+ end = end.parent;+ }+ return nodes;+}+__name(path_default, "default");+function leastCommonAncestor(a, b) {+ if (a === b) return a;+ var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null;+ a = aNodes.pop();+ b = bNodes.pop();+ while (a === b) {+ c = a;+ a = aNodes.pop();+ b = bNodes.pop();+ }+ return c;+}+__name(leastCommonAncestor, "leastCommonAncestor");++// ../../node_modules/d3-hierarchy/src/hierarchy/ancestors.js+function ancestors_default() {+ var node = this, nodes = [node];+ while (node = node.parent) {+ nodes.push(node);+ }+ return nodes;+}+__name(ancestors_default, "default");++// ../../node_modules/d3-hierarchy/src/hierarchy/descendants.js+function descendants_default() {+ return Array.from(this);+}+__name(descendants_default, "default");++// ../../node_modules/d3-hierarchy/src/hierarchy/leaves.js+function leaves_default() {+ var leaves = [];+ this.eachBefore(function(node) {+ if (!node.children) {+ leaves.push(node);+ }+ });+ return leaves;+}+__name(leaves_default, "default");++// ../../node_modules/d3-hierarchy/src/hierarchy/links.js+function links_default() {+ var root = this, links = [];+ root.each(function(node) {+ if (node !== root) {+ links.push({ source: node.parent, target: node });+ }+ });+ return links;+}+__name(links_default, "default");++// ../../node_modules/d3-hierarchy/src/hierarchy/iterator.js+function* iterator_default() {+ var node = this, current, next = [node], children, i, n;+ do {+ current = next.reverse(), next = [];+ while (node = current.pop()) {+ yield node;+ if (children = node.children) {+ for (i = 0, n = children.length; i < n; ++i) {+ next.push(children[i]);+ }+ }+ }+ } while (next.length);+}+__name(iterator_default, "default");++// ../../node_modules/d3-hierarchy/src/hierarchy/index.js+function hierarchy(data, children) {+ if (data instanceof Map) {+ data = [void 0, data];+ if (children === void 0) children = mapChildren;+ } else if (children === void 0) {+ children = objectChildren;+ }+ var root = new Node(data), node, nodes = [root], child, childs, i, n;+ while (node = nodes.pop()) {+ if ((childs = children(node.data)) && (n = (childs = Array.from(childs)).length)) {+ node.children = childs;+ for (i = n - 1; i >= 0; --i) {+ nodes.push(child = childs[i] = new Node(childs[i]));+ child.parent = node;+ child.depth = node.depth + 1;+ }+ }+ }+ return root.eachBefore(computeHeight);+}+__name(hierarchy, "hierarchy");+function node_copy() {+ return hierarchy(this).eachBefore(copyData);+}+__name(node_copy, "node_copy");+function objectChildren(d) {+ return d.children;+}+__name(objectChildren, "objectChildren");+function mapChildren(d) {+ return Array.isArray(d) ? d[1] : null;+}+__name(mapChildren, "mapChildren");+function copyData(node) {+ if (node.data.value !== void 0) node.value = node.data.value;+ node.data = node.data.data;+}+__name(copyData, "copyData");+function computeHeight(node) {+ var height = 0;+ do+ node.height = height;+ while ((node = node.parent) && node.height < ++height);+}+__name(computeHeight, "computeHeight");+function Node(data) {+ this.data = data;+ this.depth = this.height = 0;+ this.parent = null;+}+__name(Node, "Node");+Node.prototype = hierarchy.prototype = {+ constructor: Node,+ count: count_default,+ each: each_default,+ eachAfter: eachAfter_default,+ eachBefore: eachBefore_default,+ find: find_default,+ sum: sum_default,+ sort: sort_default,+ path: path_default,+ ancestors: ancestors_default,+ descendants: descendants_default,+ leaves: leaves_default,+ links: links_default,+ copy: node_copy,+ [Symbol.iterator]: iterator_default+};++// ../../node_modules/d3-hierarchy/src/accessors.js+function required(f) {+ if (typeof f !== "function") throw new Error();+ return f;+}+__name(required, "required");++// ../../node_modules/d3-hierarchy/src/constant.js+function constantZero() {+ return 0;+}+__name(constantZero, "constantZero");+function constant_default(x) {+ return function() {+ return x;+ };+}+__name(constant_default, "default");++// ../../node_modules/d3-hierarchy/src/treemap/round.js+function round_default(node) {+ node.x0 = Math.round(node.x0);+ node.y0 = Math.round(node.y0);+ node.x1 = Math.round(node.x1);+ node.y1 = Math.round(node.y1);+}+__name(round_default, "default");++// ../../node_modules/d3-hierarchy/src/treemap/dice.js+function dice_default(parent, x0, y0, x1, y1) {+ var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (x1 - x0) / parent.value;+ while (++i < n) {+ node = nodes[i], node.y0 = y0, node.y1 = y1;+ node.x0 = x0, node.x1 = x0 += node.value * k;+ }+}+__name(dice_default, "default");++// ../../node_modules/d3-hierarchy/src/treemap/slice.js+function slice_default(parent, x0, y0, x1, y1) {+ var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (y1 - y0) / parent.value;+ while (++i < n) {+ node = nodes[i], node.x0 = x0, node.x1 = x1;+ node.y0 = y0, node.y1 = y0 += node.value * k;+ }+}+__name(slice_default, "default");++// ../../node_modules/d3-hierarchy/src/treemap/squarify.js+var phi = (1 + Math.sqrt(5)) / 2;+function squarifyRatio(ratio, parent, x0, y0, x1, y1) {+ var rows = [], nodes = parent.children, row, nodeValue, i0 = 0, i1 = 0, n = nodes.length, dx, dy, value = parent.value, sumValue, minValue, maxValue, newRatio, minRatio, alpha, beta;+ while (i0 < n) {+ dx = x1 - x0, dy = y1 - y0;+ do+ sumValue = nodes[i1++].value;+ while (!sumValue && i1 < n);+ minValue = maxValue = sumValue;+ alpha = Math.max(dy / dx, dx / dy) / (value * ratio);+ beta = sumValue * sumValue * alpha;+ minRatio = Math.max(maxValue / beta, beta / minValue);+ for (; i1 < n; ++i1) {+ sumValue += nodeValue = nodes[i1].value;+ if (nodeValue < minValue) minValue = nodeValue;+ if (nodeValue > maxValue) maxValue = nodeValue;+ beta = sumValue * sumValue * alpha;+ newRatio = Math.max(maxValue / beta, beta / minValue);+ if (newRatio > minRatio) {+ sumValue -= nodeValue;+ break;+ }+ minRatio = newRatio;+ }+ rows.push(row = { value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1) });+ if (row.dice) dice_default(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1);+ else slice_default(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1);+ value -= sumValue, i0 = i1;+ }+ return rows;+}+__name(squarifyRatio, "squarifyRatio");+var squarify_default = (/* @__PURE__ */ __name((function custom(ratio) {+ function squarify(parent, x0, y0, x1, y1) {+ squarifyRatio(ratio, parent, x0, y0, x1, y1);+ }+ __name(squarify, "squarify");+ squarify.ratio = function(x) {+ return custom((x = +x) > 1 ? x : 1);+ };+ return squarify;+}), "custom"))(phi);++// ../../node_modules/d3-hierarchy/src/treemap/index.js+function treemap_default() {+ var tile = squarify_default, round = false, dx = 1, dy = 1, paddingStack = [0], paddingInner = constantZero, paddingTop = constantZero, paddingRight = constantZero, paddingBottom = constantZero, paddingLeft = constantZero;+ function treemap(root) {+ root.x0 = root.y0 = 0;+ root.x1 = dx;+ root.y1 = dy;+ root.eachBefore(positionNode);+ paddingStack = [0];+ if (round) root.eachBefore(round_default);+ return root;+ }+ __name(treemap, "treemap");+ function positionNode(node) {+ var p = paddingStack[node.depth], x0 = node.x0 + p, y0 = node.y0 + p, x1 = node.x1 - p, y1 = node.y1 - p;+ if (x1 < x0) x0 = x1 = (x0 + x1) / 2;+ if (y1 < y0) y0 = y1 = (y0 + y1) / 2;+ node.x0 = x0;+ node.y0 = y0;+ node.x1 = x1;+ node.y1 = y1;+ if (node.children) {+ p = paddingStack[node.depth + 1] = paddingInner(node) / 2;+ x0 += paddingLeft(node) - p;+ y0 += paddingTop(node) - p;+ x1 -= paddingRight(node) - p;+ y1 -= paddingBottom(node) - p;+ if (x1 < x0) x0 = x1 = (x0 + x1) / 2;+ if (y1 < y0) y0 = y1 = (y0 + y1) / 2;+ tile(node, x0, y0, x1, y1);+ }+ }+ __name(positionNode, "positionNode");+ treemap.round = function(x) {+ return arguments.length ? (round = !!x, treemap) : round;+ };+ treemap.size = function(x) {+ return arguments.length ? (dx = +x[0], dy = +x[1], treemap) : [dx, dy];+ };+ treemap.tile = function(x) {+ return arguments.length ? (tile = required(x), treemap) : tile;+ };+ treemap.padding = function(x) {+ return arguments.length ? treemap.paddingInner(x).paddingOuter(x) : treemap.paddingInner();+ };+ treemap.paddingInner = function(x) {+ return arguments.length ? (paddingInner = typeof x === "function" ? x : constant_default(+x), treemap) : paddingInner;+ };+ treemap.paddingOuter = function(x) {+ return arguments.length ? treemap.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap.paddingTop();+ };+ treemap.paddingTop = function(x) {+ return arguments.length ? (paddingTop = typeof x === "function" ? x : constant_default(+x), treemap) : paddingTop;+ };+ treemap.paddingRight = function(x) {+ return arguments.length ? (paddingRight = typeof x === "function" ? x : constant_default(+x), treemap) : paddingRight;+ };+ treemap.paddingBottom = function(x) {+ return arguments.length ? (paddingBottom = typeof x === "function" ? x : constant_default(+x), treemap) : paddingBottom;+ };+ treemap.paddingLeft = function(x) {+ return arguments.length ? (paddingLeft = typeof x === "function" ? x : constant_default(+x), treemap) : paddingLeft;+ };+ return treemap;+}+__name(treemap_default, "default");++// ../types/src/health.ts+var EXCELLENT_MIN = 8.5;+var GOOD_MIN = 7;+var FAIR_MIN = 5.5;+var NEEDS_WORK_MIN = 4;+var HEALTH_BAND_ORDER = [+ "at_risk",+ "needs_work",+ "fair",+ "good",+ "excellent"+];+var HEALTH_BAND_LABEL = {+ excellent: "Excellent",+ good: "Good",+ fair: "Fair",+ needs_work: "Needs work",+ at_risk: "At risk"+};+function bandForScore(score) {+ if (score >= EXCELLENT_MIN) return "excellent";+ if (score >= GOOD_MIN) return "good";+ if (score >= FAIR_MIN) return "fair";+ if (score >= NEEDS_WORK_MIN) return "needs_work";+ return "at_risk";+}+__name(bandForScore, "bandForScore");++// ../ui/src/brand.ts+var BRAND = {+ /** Accent orange — the brand fill (CTAs, owl eyes, highlights). */+ accent: "#f59520",+ /** Accent text on light surfaces (darkened for 4.5:1 contrast). */+ accentTextLight: "#a16215",+ /** Brand plum — logo strokes on light surfaces, secondary accent. */+ plum: "#473659",+ /** Plum near-black — primary ink on warm paper. */+ ink: "#241b2c",+ /** Warm paper — the light-mode page background. */+ paper: "#fbf6f1",+ /** Cream — the logo stroke color on dark surfaces. */+ cream: "#fce9dd"+};+var DARK = {+ bgRoot: "#0e0e0f",+ bgSurface: "#141416",+ bgElevated: "#191a1c",+ bgInset: "#0a0a0b",+ textPrimary: "#f2f2f3",+ textSecondary: "#b4b4b9",+ textTertiary: "#7c7c82",+ accentPrimary: "#f59520",+ accentFill: "#f59520",+ accentSecondary: "#a98fc4",+ success: "#34d399",+ warning: "#f2a03d",+ error: "#e06a5a"+};+var DARK_CANVAS = {+ nodeAtRisk: "#b0544b",+ nodeNeedsWork: "#bd7c42",+ nodeFair: "#a89453",+ nodeGood: "#42906f",+ nodeExcellent: "#5cb389",+ nodeNeutral: "#333336",+ caution: "#d9b04a"+};+var DARK_CANVAS_BAND = {+ excellent: DARK_CANVAS.nodeExcellent,+ good: DARK_CANVAS.nodeGood,+ fair: DARK_CANVAS.nodeFair,+ needs_work: DARK_CANVAS.nodeNeedsWork,+ at_risk: DARK_CANVAS.nodeAtRisk+};++// src/views/map.ts+var UPPER_HALF = 9600;+var hex = /* @__PURE__ */ __name((s) => parseInt(s.slice(1), 16), "hex");+var ACCENT = hex(BRAND.accent);+var GROUND = hex(DARK.bgRoot);+var LABEL_FG = hex(DARK.textSecondary);+var NEUTRAL = hex(DARK_CANVAS.nodeNeutral);+var BLACK = 0;+var SPLIT_SHARE = 0.25;+var MAX_SPLITS = 8;+var GUTTER_MIN = 6;+var EDGE_MIN = 3;+function colorForScore(score) {+ return score === null ? NEUTRAL : hex(DARK_CANVAS_BAND[bandForScore(score)]);+}+__name(colorForScore, "colorForScore");+function mix(a, b, amount) {+ const ch = /* @__PURE__ */ __name((shift) => {+ const x = a >> shift & 255;+ const y = b >> shift & 255;+ return Math.round(x + (y - x) * amount) << shift;+ }, "ch");+ return (ch(16) | ch(8) | ch(0)) >>> 0;+}+__name(mix, "mix");+var byName = /* @__PURE__ */ __name((a, b) => a < b ? -1 : a > b ? 1 : 0, "byName");+function dirsOf(path) {+ return path.split("/").slice(0, -1);+}+__name(dirsOf, "dirsOf");+function keyOf(path, split2) {+ const dirs = dirsOf(path);+ let depth = Math.min(1, dirs.length);+ while (depth < dirs.length && split2.has(dirs.slice(0, depth).join("/"))) depth++;+ return dirs.slice(0, depth).join("/");+}+__name(keyOf, "keyOf");+function nextSplit(files, split2, limit) {+ const weight = /* @__PURE__ */ new Map();+ for (const f of files) {+ const key = keyOf(f.file_path, split2);+ weight.set(key, (weight.get(key) ?? 0) + f.nloc);+ }+ const heavy = [...weight].filter(([key, w]) => key !== "" && w > limit).sort((a, b) => b[1] - a[1] || byName(a[0], b[0]));+ for (const [key] of heavy) {+ const deeper = /* @__PURE__ */ new Set([...split2, key]);+ const parts = new Set(files.filter((f) => keyOf(f.file_path, split2) === key).map((f) => keyOf(f.file_path, deeper)));+ if (parts.size > 1) return key;+ }+ return null;+}+__name(nextSplit, "nextSplit");+function groupKeys(files) {+ const split2 = /* @__PURE__ */ new Set();+ const limit = files.reduce((sum, f) => sum + f.nloc, 0) * SPLIT_SHARE;+ for (let i = 0; i < MAX_SPLITS; i++) {+ const key = nextSplit(files, split2, limit);+ if (key === null) break;+ split2.add(key);+ }+ return files.map((f) => keyOf(f.file_path, split2));+}+__name(groupKeys, "groupKeys");+function treemapOf(files, width, height) {+ const keys = groupKeys(files);+ const groups = /* @__PURE__ */ new Map();+ files.forEach((file, i) => {+ const key = keys[i] ?? "";+ groups.set(key, [...groups.get(key) ?? [], { name: file.file_path, file }]);+ });+ const data = { name: "", children: [...groups].map(([name, children]) => ({ name, children })) };+ const root = hierarchy(data).sum((d) => d.file?.nloc ?? 0).sort((a, b) => (b.value ?? 0) - (a.value ?? 0) || byName(a.data.name, b.data.name));+ return treemap_default().tile(squarify_default).size([width, height])(root);+}+__name(treemapOf, "treemapOf");+var rectOf = /* @__PURE__ */ __name((n) => ({ x: n.x0, y: n.y0, w: n.x1 - n.x0, h: n.y1 - n.y0 }), "rectOf");+function pixelSpan(from, to) {+ return [Math.ceil(from - 0.5), Math.ceil(to - 0.5)];+}+__name(pixelSpan, "pixelSpan");+function groupInterior(rect, width, height) {+ const [x0, x1] = pixelSpan(rect.x, rect.x + rect.w);+ const [y0, y1] = pixelSpan(rect.y, rect.y + rect.h);+ const gutter = x1 - x0 >= GUTTER_MIN && y1 - y0 >= GUTTER_MIN;+ return { x0, y0, x1: gutter && x1 < width ? x1 - 1 : x1, y1: gutter && y1 < height ? y1 - 1 : y1 };+}+__name(groupInterior, "groupInterior");+function placeFile(leaf, group, inner) {+ const file = leaf.data.file;+ const rect = rectOf(leaf);+ const [x0, x1] = pixelSpan(rect.x, rect.x + rect.w);+ const [y0, y1] = pixelSpan(rect.y, rect.y + rect.h);+ return {+ path: file.file_path,+ score: file.score,+ nloc: file.nloc,+ group,+ rect,+ px0: Math.max(x0, inner.x0),+ py0: Math.max(y0, inner.y0),+ px1: Math.min(x1, inner.x1),+ py1: Math.min(y1, inner.y1)+ };+}+__name(placeFile, "placeFile");+function paintFile(base, width, f) {+ const fill = colorForScore(f.score);+ const edge = mix(fill, BLACK, 0.3);+ const edgeX = f.px1 - f.px0 >= EDGE_MIN ? f.px1 - 1 : -1;+ const edgeY = f.py1 - f.py0 >= EDGE_MIN ? f.py1 - 1 : -1;+ for (let y = f.py0; y < f.py1; y++) {+ base.fill(y === edgeY ? edge : fill, y * width + f.px0, y * width + f.px1);+ if (edgeX >= 0) base[y * width + edgeX] = edge;+ }+}+__name(paintFile, "paintFile");+function labelText(key, width) {+ const parts = key.split("/");+ const rungs = [key, parts.slice(-2).join("/"), parts[parts.length - 1] ?? ""];+ const text2 = rungs.find((r) => r.length > 0 && r.length <= width);+ return text2 !== void 0 && /^[\x20-\x7e]+$/.test(text2) ? text2 : null;+}+__name(labelText, "labelText");+function labelFor(g, columns, rows) {+ const col = Math.ceil(g.rect.x);+ const row = Math.ceil(g.rect.y / 2);+ const width = Math.min(columns, Math.floor(g.rect.x + g.rect.w)) - col - 1;+ const height = Math.floor((g.rect.y + g.rect.h) / 2) - row;+ if (g.key === "" || height < 2 || row >= rows) return null;+ const text2 = labelText(g.key, width);+ return text2 === null ? null : { row, col, text: text2 };+}+__name(labelFor, "labelFor");+function labelsFor(groups, columns, rows) {+ return [...groups].sort((a, b) => b.nloc - a.nloc).map((g) => labelFor(g, columns, rows)).filter((l) => l !== null);+}+__name(labelsFor, "labelsFor");+function layoutMap(feed, columns, rows, caseInsensitive) {+ const width = columns;+ const height = rows * 2;+ const root = treemapOf(+ feed.filter((f) => f.nloc > 0),+ width,+ height+ );+ const groups = [];+ const files = [];+ for (const node of root.children ?? []) {+ const group = groups.push({ key: node.data.name, rect: rectOf(node), nloc: node.value ?? 0 }) - 1;+ const inner = groupInterior(rectOf(node), width, height);+ for (const leaf of node.children ?? []) files.push(placeFile(leaf, group, inner));+ }+ const base = new Uint32Array(width * height).fill(GROUND);+ const drawn = [];+ const index = /* @__PURE__ */ new Map();+ files.forEach((f, i) => {+ if (f.px1 <= f.px0 || f.py1 <= f.py0) return;+ drawn.push(i);+ index.set(caseInsensitive ? f.path.toLowerCase() : f.path, i);+ paintFile(base, width, f);+ });+ return { columns, rows, width, height, groups, files, drawn, index, caseInsensitive, labels: labelsFor(groups, columns, rows), base };+}+__name(layoutMap, "layoutMap");+function labelCovered(label, marked, width) {+ if (marked === void 0) return false;+ for (let c = label.col; c < label.col + label.text.length; c++) {+ if (marked[2 * label.row * width + c] || marked[(2 * label.row + 1) * width + c]) return true;+ }+ return false;+}+__name(labelCovered, "labelCovered");+function encodeCells(layout, pixels, marked) {+ const { columns, rows, width } = layout;+ const words = new Uint32Array(columns * rows * 3);+ for (let i = 0; i < columns * rows; i++) {+ const r = Math.floor(i / columns);+ const c = i % columns;+ words[i * 3] = UPPER_HALF;+ words[i * 3 + 1] = pixels[2 * r * width + c] ?? GROUND;+ words[i * 3 + 2] = pixels[(2 * r + 1) * width + c] ?? GROUND;+ }+ for (const label of layout.labels) {+ if (labelCovered(label, marked, width)) continue;+ for (let k = 0; k < label.text.length && label.col + k < columns; k++) {+ const o = (label.row * columns + label.col + k) * 3;+ words.set([label.text.charCodeAt(k), LABEL_FG, GROUND], o);+ }+ }+ return new Uint8Array(words.buffer).toBase64();+}+__name(encodeCells, "encodeCells");++// src/views/elements.ts+function text(value, props = {}) {+ return { type: "Text", props, children: [value] };+}+__name(text, "text");+function box(props, children) {+ return { type: "Box", props, children };+}+__name(box, "box");+function button(key, hotkey, label, dimColor = false) {+ return { type: "Button", props: { key, label, hotkey, plain: true, ...dimColor ? { dimColor } : {} } };+}+__name(button, "button");+function raster(props) {+ return { type: "Raster", props };+}+__name(raster, "raster");+function input(props) {+ return { type: "Input", props };+}+__name(input, "input");+function markdown(text2) {+ return { type: "Markdown", props: { text: text2 } };+}+__name(markdown, "markdown");+function svg(source, alt) {+ return { type: "Svg", props: { source, alt } };+}+__name(svg, "svg");+var SUBMIT_IN_HOOK = /* @__PURE__ */ __name(() => void 0, "SUBMIT_IN_HOOK");+function pressFor(key, presses) {+ const onPress = presses[key];+ if (!onPress) throw new Error(`button ${key} has no action`);+ return onPress;+}+__name(pressFor, "pressFor");+var PROPS = {+ Text: /* @__PURE__ */ __name((n) => ({ ...n.props, children: n.children }), "Text"),+ Box: /* @__PURE__ */ __name((n, table, presses) => ({ ...n.props, children: n.children.map((child) => materialize(child, table, presses)) }), "Box"),+ Button: /* @__PURE__ */ __name((n, _table, presses) => ({ ...n.props, onPress: pressFor(n.props.key, presses) }), "Button"),+ Input: /* @__PURE__ */ __name((n) => ({ ...n.props, onSubmit: SUBMIT_IN_HOOK }), "Input"),+ Raster: /* @__PURE__ */ __name((n) => ({ ...n.props }), "Raster"),+ Markdown: /* @__PURE__ */ __name((n) => ({ ...n.props }), "Markdown"),+ Svg: /* @__PURE__ */ __name((n) => ({ ...n.props }), "Svg")+};+function materialize(node, table, presses = {}) {+ const build = table[node.type];+ if (!build) throw new Error(`element ${node.type} is not on this surface`);+ return build(PROPS[node.type](node, table, presses));+}+__name(materialize, "materialize");++// src/views/overlay.ts+var EDIT_TINT = mix(ACCENT, 16777215, 0.45);+var READ_DIM = 0.4;+var PATH_AMOUNT = 0.85;+var MATCH_FLASH = 0.85;+var MATCH_REST = 0.25;+var RING_AMOUNT = 0.5;+var SMALL = 3;+function lookup(layout, rel) {+ return layout.index.get(layout.caseInsensitive ? rel.toLowerCase() : rel);+}+__name(lookup, "lookup");+function locate(layout, abs, root) {+ const rel = relativeTo(abs, root, layout.caseInsensitive);+ return rel === null ? void 0 : lookup(layout, rel);+}+__name(locate, "locate");+function split(items, find) {+ const found = [];+ for (const item of items) {+ const i = find(item);+ if (i !== void 0) found.push(i);+ }+ return { found, missing: items.length - found.length };+}+__name(split, "split");+function resolveOverlay(layout, trail, repoRoot) {+ const reads = split(trail.reads, (p) => locate(layout, p, repoRoot));+ const hits = split(trail.hits, (p) => locate(layout, p, repoRoot)).found;+ const callers = split(trail.callers?.status === "ready" ? trail.callers.paths : [], (p) => lookup(layout, p));+ const edited = trail.edit === null ? null : locate(layout, trail.edit, repoRoot) ?? null;+ const edit = trail.edit === null ? null : { name: trail.edit.slice(trail.edit.lastIndexOf("/") + 1), callers: trail.callers, notDrawn: callers.missing };+ return {+ overlay: { reads: reads.found, hits, edited, callers: callers.found },+ reads: { count: trail.reads.length, capped: trail.readsCapped, notDrawn: reads.missing },+ matched: trail.searches === 0 ? null : trail.hits.length,+ edit+ };+}+__name(resolveOverlay, "resolveOverlay");+function center(f) {+ return [Math.floor((f.px0 + f.px1 - 1) / 2), Math.floor((f.py0 + f.py1 - 1) / 2)];+}+__name(center, "center");+function distance(a, b) {+ const [ax, ay] = center(a);+ const [bx, by] = center(b);+ return Math.hypot(ax - bx, ay - by);+}+__name(distance, "distance");+function rippleRadius(layout, overlay) {+ const origin = overlay.edited === null ? void 0 : layout.files[overlay.edited];+ if (!origin || overlay.callers.length === 0) return 0;+ return Math.max(...overlay.callers.map((i) => distance(origin, layout.files[i]))) + 3;+}+__name(rippleRadius, "rippleRadius");+function inside(layout, x, y) {+ return x >= 0 && y >= 0 && x < layout.width && y < layout.height;+}+__name(inside, "inside");+function set(p, x, y, color2) {+ if (!inside(p.layout, x, y)) return;+ const width = p.layout.width;+ p.px[y * width + x] = color2;+ p.marked[y * width + x] = 1;+}+__name(set, "set");+function fillFile(p, f, color2) {+ const w = p.layout.width;+ for (let y = f.py0; y < f.py1; y++) for (let x = f.px0; x < f.px1; x++) set(p, x, y, color2(p.px[y * w + x] ?? GROUND));+}+__name(fillFile, "fillFile");+function outlineFile(p, f, color2) {+ for (let x = f.px0; x < f.px1; x++) {+ set(p, x, f.py0, color2);+ set(p, x, f.py1 - 1, color2);+ }+ for (let y = f.py0; y < f.py1; y++) {+ set(p, f.px0, y, color2);+ set(p, f.px1 - 1, y, color2);+ }+}+__name(outlineFile, "outlineFile");+var isSmall = /* @__PURE__ */ __name((f) => f.px1 - f.px0 < SMALL || f.py1 - f.py0 < SMALL, "isSmall");+function paintPath(p, overlay) {+ const files = p.layout.files;+ for (let k = 1; k < overlay.reads.length; k++) {+ const [ax, ay] = center(files[overlay.reads[k - 1]]);+ const [bx, by] = center(files[overlay.reads[k]]);+ const steps = Math.max(Math.abs(bx - ax), Math.abs(by - ay));+ for (let s = 1; s < steps; s += 3) {+ const x = Math.round(ax + (bx - ax) * s / steps);+ const y = Math.round(ay + (by - ay) * s / steps);+ set(p, x, y, mix(p.px[y * p.layout.width + x] ?? GROUND, ACCENT, PATH_AMOUNT));+ }+ }+}+__name(paintPath, "paintPath");+function paintHits(p, overlay, amount) {+ for (const i of overlay.hits) fillFile(p, p.layout.files[i], (c) => mix(c, ACCENT, amount));+}+__name(paintHits, "paintHits");+function paintReads(p, overlay) {+ for (const i of overlay.reads) {+ const f = p.layout.files[i];+ fillFile(p, f, (c) => mix(c, 0, READ_DIM));+ outlineFile(p, f, ACCENT);+ }+}+__name(paintReads, "paintReads");+function paintEdited(p, f) {+ fillFile(p, f, () => EDIT_TINT);+ if (!isSmall(f)) outlineFile(p, f, ACCENT);+}+__name(paintEdited, "paintEdited");+function paintRing(p, origin, reach) {+ const [ox, oy] = center(origin);+ const { width, height } = p.layout;+ for (let y = Math.max(0, Math.floor(oy - reach)); y <= Math.min(height - 1, oy + reach); y++) {+ for (let x = Math.max(0, Math.floor(ox - reach)); x <= Math.min(width - 1, ox + reach); x++) {+ const d = Math.hypot(x - ox, y - oy);+ if (d <= reach && d > reach - 2) set(p, x, y, mix(p.px[y * width + x] ?? GROUND, ACCENT, RING_AMOUNT));+ }+ }+}+__name(paintRing, "paintRing");+function paintCallers(p, overlay, origin, reach) {+ for (const i of overlay.callers) {+ const f = p.layout.files[i];+ if (origin !== void 0 && distance(origin, f) > reach) continue;+ const [x, y] = center(f);+ set(p, x, y, ACCENT);+ set(p, x, y ^ 1, GROUND);+ }+}+__name(paintCallers, "paintCallers");+function matchAmount(anim) {+ return anim?.kind === "flash" ? MATCH_REST + (MATCH_FLASH - MATCH_REST) * (1 - anim.t) : MATCH_REST;+}+__name(matchAmount, "matchAmount");+function rippleReach(layout, overlay, anim) {+ return anim?.kind === "ripple" && anim.t < 1 ? rippleRadius(layout, overlay) * anim.t : Infinity;+}+__name(rippleReach, "rippleReach");+function framePixels(layout, overlay, anim) {+ const p = { layout, px: layout.base.slice(), marked: new Uint8Array(layout.width * layout.height) };+ const origin = overlay.edited === null ? void 0 : layout.files[overlay.edited];+ const reach = rippleReach(layout, overlay, anim);+ paintPath(p, overlay);+ paintHits(p, overlay, matchAmount(anim));+ paintReads(p, overlay);+ if (origin !== void 0) paintEdited(p, origin);+ if (origin !== void 0 && reach < Infinity) paintRing(p, origin, reach);+ paintCallers(p, overlay, origin, reach);+ return { pixels: p.px, marked: p.marked };+}+__name(framePixels, "framePixels");+function frameCells(layout, overlay, anim) {+ const { pixels, marked } = framePixels(layout, overlay, anim);+ return encodeCells(layout, pixels, marked);+}+__name(frameCells, "frameCells");+var FRAME_MS = 40;+var FLASH_MS = 600;+var RIPPLE_MS = 1200;++// src/views/mapPane.ts+var MAP_KEY = "lens-map";+var MAX_COLUMNS = 512;+var MAX_ROWS = 256;+var MIN_ROWS = 4;+var GAP = 2;+var SEP = " · ";+var FACT_ROWS = 4;+var INLINE_ROWS_PER_COLUMN = 1 / 6;+var INLINE_MAX_ROWS = 20;+var hexOf = /* @__PURE__ */ __name((n) => `#${n.toString(16).padStart(6, "0")}`, "hexOf");+var BAND_SWATCHES = [+ ...HEALTH_BAND_ORDER.map((band) => ({ glyph: "■", color: DARK_CANVAS_BAND[band], label: HEALTH_BAND_LABEL[band] })),+ { glyph: "■", color: DARK_CANVAS.nodeNeutral, label: MAP_COPY.noScore }+];+var READ = { glyph: "□", color: BRAND.accent, label: MAP_COPY.read };+var EDITED = { glyph: "◆", color: hexOf(EDIT_TINT), label: MAP_COPY.edited };+var IMPORTER = { glyph: "·", color: BRAND.accent, label: MAP_COPY.importer };+var MATCH = { glyph: "▪", color: BRAND.accent, label: MAP_COPY.match };+function packRows(items, width, columns, gap) {+ const rows = [];+ let used = Infinity;+ for (const item of items) {+ const w = width(item);+ const last = rows[rows.length - 1];+ if (last === void 0 || used + gap + w > columns) {+ rows.push([item]);+ used = w;+ } else {+ last.push(item);+ used += gap + w;+ }+ }+ return rows;+}+__name(packRows, "packRows");+var swatchWidth = /* @__PURE__ */ __name((s) => s.label.length + 2, "swatchWidth");+function legendRows(columns) {+ const swatchRows2 = /* @__PURE__ */ __name((items) => packRows(items, swatchWidth, columns, GAP).length, "swatchRows");+ return swatchRows2(BAND_SWATCHES) + swatchRows2([READ, EDITED, IMPORTER, MATCH]) + FACT_ROWS;+}+__name(legendRows, "legendRows");+function mapSize(pane) {+ const columns = Math.max(1, Math.min(MAX_COLUMNS, pane.bodyColumns));+ const wanted = pane.placement === "dock" ? pane.bodyRows - legendRows(columns) : Math.min(INLINE_MAX_ROWS, Math.round(columns * INLINE_ROWS_PER_COLUMN));+ return { columns, rows: Math.max(MIN_ROWS, Math.min(MAX_ROWS, wanted)) };+}+__name(mapSize, "mapSize");+function swatchRows(items, columns) {+ return packRows(items, swatchWidth, columns, GAP).map(+ (row) => box(+ { flexDirection: "row", columnGap: GAP },+ row.map((s) => box({ flexDirection: "row" }, [text(s.glyph, { color: s.color }), text(` ${s.label}`, { dimColor: true })]))+ )+ );+}+__name(swatchRows, "swatchRows");+function marksOf(resolved) {+ const marks = [READ, EDITED];+ if (resolved.overlay.callers.length > 0) marks.push(IMPORTER);+ if (resolved.overlay.hits.length > 0) marks.push(MATCH);+ return marks;+}+__name(marksOf, "marksOf");+function scopeRows(scope, columns) {+ const rows = /* @__PURE__ */ __name((parts2) => packRows(parts2, (p) => p.length, columns, SEP.length), "rows");+ let parts = scopeParts(scope);+ for (const optional of [SCOPE_REST, scope.indexed === null ? null : indexedPart(scope.indexed)]) {+ if (rows(parts).length <= 2) break;+ parts = parts.filter((p) => p !== optional);+ }+ return rows(parts).slice(0, 2).map((row) => row.join(SEP));+}+__name(scopeRows, "scopeRows");+function factRows(resolved, scope, columns) {+ const facts = [];+ const reads = readsLine(resolved.reads, resolved.matched, columns);+ if (reads !== null) facts.push(reads);+ if (resolved.edit !== null) facts.push(callersLine(resolved.edit.name, resolved.edit.callers, resolved.edit.notDrawn, columns));+ return [...facts, ...scopeRows(scope, columns)];+}+__name(factRows, "factRows");+function legendView(resolved, scope, columns) {+ return [+ ...swatchRows(BAND_SWATCHES, columns),+ ...swatchRows(marksOf(resolved), columns),+ ...factRows(resolved, scope, columns).map((f) => text(fit(f, columns), { dimColor: true, wrap: "truncate-end" }))+ ];+}+__name(legendView, "legendView");+function mapPaneView(layout, cells, resolved, scope) {+ return box({ key: "lens-map-pane", flexDirection: "column" }, [+ raster({ key: MAP_KEY, columns: layout.columns, rows: layout.rows, cells }),+ ...legendView(resolved, scope, layout.columns)+ ]);+}+__name(mapPaneView, "mapPaneView");+function noticeView(line2, columns) {+ return box({ key: "lens-map-pane", flexDirection: "column" }, [text(fit(line2, columns), { dimColor: true, wrap: "truncate-end" })]);+}+__name(noticeView, "noticeView");++// src/views/mapSvg.ts+var SVG_CHARS = 131072;+var DESKTOP_MAX_COLUMNS = 160;+var DESKTOP_MAX_ROWS = 45;+var color = /* @__PURE__ */ __name((c) => `#${c.toString(16).padStart(6, "0")}`, "color");+var escape = /* @__PURE__ */ __name((s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"), "escape");+function desktopSize(size) {+ return { columns: Math.min(DESKTOP_MAX_COLUMNS, size.columns), rows: Math.min(DESKTOP_MAX_ROWS, size.rows) };+}+__name(desktopSize, "desktopSize");+function mapSvg(layout, resolved) {+ const { width, height } = layout;+ const { pixels } = framePixels(layout, resolved.overlay);+ const runs = /* @__PURE__ */ new Map();+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; ) {+ const c = pixels[y * width + x] ?? GROUND;+ let end = x + 1;+ while (end < width && pixels[y * width + end] === c) end++;+ if (c !== GROUND) {+ const list2 = runs.get(c) ?? [];+ list2.push(`M${x} ${y}.5h${end - x}`);+ runs.set(c, list2);+ }+ x = end;+ }+ }+ const paths = [...runs].map(([c, d]) => `<path stroke="${color(c)}" d="${d.join("")}"/>`).join("");+ const labels = layout.labels.map((l) => `<text x="${l.col}" y="${2 * l.row + 1.6}">${escape(l.text)}</text>`).join("");+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" shape-rendering="crispEdges"><rect width="${width}" height="${height}" fill="${color(GROUND)}"/><g stroke-width="1" fill="none">${paths}</g><g font-family="monospace" font-size="1.7" fill="${color(LABEL_FG)}">${labels}</g></svg>`;+}+__name(mapSvg, "mapSvg");+function svgPaneView(layout, resolved, scope) {+ const source = mapSvg(layout, resolved);+ const picture = source.length <= SVG_CHARS ? svg(source, mapAlt(layout.drawn.length)) : text(fit(MAP_COPY.tooLarge, layout.columns), { dimColor: true, wrap: "truncate-end" });+ return box({ key: "lens-map-pane", flexDirection: "column" }, [picture, ...legendView(resolved, scope, layout.columns)]);+}+__name(svgPaneView, "svgPaneView");++// src/map-controller.ts+var MAP_CAP = 4e3;+var MAP_TIMEOUT_MS = 15e3;+var CALLERS_TIMEOUT_MS = 2e4;+var CALLERS_DEPTH = 1;+function scopeFacts(layout, data, repo) {+ return {+ drawn: layout.drawn.length,+ repositoryTotal: data.repository_total,+ indexed: formatRelativeTimeOrNull(repo.updatedAt, "") || null,+ beyondCap: data.omitted.files,+ cap: data.cap+ };+}+__name(scopeFacts, "scopeFacts");+var Animator = class {+ static {+ __name(this, "Animator");+ }+ anim = null;+ timer;+ blitting = false;+ stopped = false;+ progress(now) {+ const a = this.anim;+ return a === null ? void 0 : { kind: a.kind, t: Math.min(1, (now - a.start) / a.duration) };+ }+ play(io, kind, screen) {+ this.stop();+ if (this.stopped) return;+ this.anim = { kind, start: Date.now(), duration: kind === "flash" ? FLASH_MS : RIPPLE_MS };+ io.redraw();+ this.timer = setInterval(() => this.tick(io, screen), FRAME_MS);+ }+ stop() {+ clearInterval(this.timer);+ this.timer = void 0;+ this.anim = null;+ }+ /** For good: a disposed map plays nothing more. */+ end() {+ this.stopped = true;+ this.stop();+ }+ tick(io, screen) {+ const step = this.progress(Date.now());+ const frame = step === void 0 ? null : screen(step);+ if (step === void 0 || frame === null) return this.stop();+ if (this.blitting) return;+ if (step.t >= 1) this.stop();+ this.blitting = true;+ io.blit(frame.cells, frame.columns, frame.rows).then((r) => r.deny === void 0 || this.refused(io, r.deny)).catch((err) => this.refused(io, String(err))).finally(() => {+ this.blitting = false;+ });+ }+ /** Resized, closed or refused under the animation: stop and let a redraw show the resting frame. */+ refused(io, why) {+ io.debug(`blit refused: ${why}`);+ this.stop();+ if (!this.stopped) io.redraw();+ }+};+var LensMap = class {+ static {+ __name(this, "LensMap");+ }+ trail = initialTrail;+ disposed = false;+ /** One band row the map asks for (the pane could not open), until the turn ends. */+ band = null;+ repo = null;+ feed = { status: "idle" };+ requested = false;+ autoOpenTried = false;+ /** The latest edit's absolute path with its case, for the importers request. */+ editPath = null;+ /** The edit whose importers were asked for, so each is asked once. */+ callersAsked = 0;+ drawn = null;+ layoutCache = null;+ animator = new Animator();+ reducedMotion = false;+ autoOpenOnRead;+ constructor(autoOpenOnRead) {+ this.autoOpenOnRead = autoOpenOnRead;+ }+ /** The band row the map wants shown, if any. */+ bandLine() {+ return this.band;+ }+ /** The person's `prefersReducedMotion` setting: resting frames only. */+ setReducedMotion(on) {+ this.reducedMotion = on;+ }+ dispose() {+ this.disposed = true;+ this.animator.end();+ }+ setRepo(io, repo) {+ this.repo = repo;+ this.fetchWanted(io);+ }+ /** One observed tool call; `editPath` is the edited file's absolute path, case kept. */+ observe(io, action, editPath) {+ if (action.type === "edit") this.editPath = editPath;+ this.apply(io, action);+ if (action.type === "edit") this.fetchWanted(io);+ if (action.type === "read") void this.autoOpen(io);+ }+ /** /lens: open the pane with focus (asked, so placed at any width) and start what it shows. */+ async request(io) {+ this.requested = true;+ this.band = null;+ if (this.feed.status === "failed") this.feed = { status: "idle" };+ const opened = await io.openPane(true);+ if (!opened.isPlaced) this.band = notPlacedLine(opened.reason);+ this.fetchWanted(io);+ io.redraw();+ }+ /** A main-loop turn ended: the band row has been seen. */+ turnEnded() {+ this.band = null;+ }+ /** Another tab is shown: nothing of the map is on screen to animate. */+ offScreen() {+ this.drawn = null;+ }+ /** The pane's tree; starts the feed fetch when the map is wanted and not yet asked for. */+ paneTree(io, pane) {+ this.drawn = null;+ const notice = this.noticeFor(io, pane);+ if (notice !== null) return noticeView(notice, pane.bodyColumns);+ const { data } = this.feed;+ const repo = this.repo;+ const desktop = pane.surface === "desktop";+ const layout = this.layoutFor(data, desktop ? desktopSize(mapSize(pane)) : mapSize(pane), repo.caseInsensitive);+ const resolved = resolveOverlay(layout, this.trail, repo.root);+ const scope = scopeFacts(layout, data, repo);+ if (desktop) return svgPaneView(layout, resolved, scope);+ this.drawn = { layout, root: repo.root };+ return mapPaneView(layout, frameCells(layout, resolved.overlay, this.animator.progress(Date.now())), resolved, scope);+ }+ /** Why there is no map to draw yet (and the feed fetch started when wanted), or null once it can be drawn. */+ noticeFor(io, pane) {+ if (pane.surface !== void 0 && pane.surface !== "terminal" && pane.surface !== "desktop") return MAP_COPY.desktop;+ if (this.repo === null) return pane.notice;+ this.requested = true;+ this.fetchWanted(io);+ const status = this.feed.status;+ if (status === "ready") return null;+ return status === "failed" ? MAP_COPY.failed : MAP_COPY.loading;+ }+ layoutFor(data, size, caseInsensitive) {+ const cached = this.cachedLayout(data, size);+ if (cached !== null) return cached;+ const layout = layoutMap(data.files, size.columns, size.rows, caseInsensitive);+ this.layoutCache = { data, columns: size.columns, rows: size.rows, layout };+ return layout;+ }+ cachedLayout(data, size) {+ const c = this.layoutCache;+ const same = c !== null && c.data === data && c.columns === size.columns && c.rows === size.rows;+ return same ? c.layout : null;+ }+ apply(io, action) {+ const next = reduceTrail(this.trail, action);+ if (next === this.trail) return;+ this.trail = next;+ if (action.type === "search") this.animate(io, "flash");+ else if (action.type === "callers" && action.callers.status === "ready") this.animate(io, "ripple");+ else io.redraw();+ }+ /** The feed and the latest edit's importers, once the map is wanted and the repo known. */+ fetchWanted(io) {+ if (!this.requested || this.repo === null) return;+ this.loadFeed(io, this.repo);+ this.loadCallers(io, this.repo);+ }+ loadFeed(io, repo) {+ if (this.feed.status !== "idle") return;+ this.feed = { status: "loading" };+ withTimeout(getHealthMap(repo.id, { cap: MAP_CAP }), MAP_TIMEOUT_MS, "health map").then((data) => {+ this.feed = { status: "ready", data };+ }).catch((err) => {+ this.feed = { status: "failed" };+ io.debug(`health map failed: ${String(err)}`);+ }).finally(() => {+ if (!this.disposed) io.redraw();+ });+ }+ loadCallers(io, repo) {+ const edits = this.trail.edits;+ if (this.editPath === null || this.callersAsked === edits) return;+ this.callersAsked = edits;+ const rel = relativeTo(this.editPath, repo.root, repo.caseInsensitive);+ if (rel === null) return this.apply(io, { type: "callers", edits, callers: { status: "failed" } });+ const request = { changed_files: [rel], max_depth: CALLERS_DEPTH };+ withTimeout(analyzeBlastRadius(repo.id, request), CALLERS_TIMEOUT_MS, "importers").then((r) => {+ const paths = [...new Set(r.transitive_affected.map((t) => t.path))].filter((p) => p !== rel);+ if (!this.disposed) this.apply(io, { type: "callers", edits, callers: { status: "ready", paths } });+ }).catch((err) => {+ io.debug(`importers failed: ${String(err)}`);+ if (!this.disposed) this.apply(io, { type: "callers", edits, callers: { status: "failed" } });+ });+ }+ /** The first read opens the map when the toggle is on and the pane would be placed; never forced. */+ async autoOpen(io) {+ if (!this.mayAutoOpen()) return;+ this.autoOpenTried = true;+ const opened = await io.openPane(false);+ if (this.disposed || this.requested) return;+ if (opened.isPlaced) {+ this.requested = true;+ this.fetchWanted(io);+ return;+ }+ await io.closePane();+ this.band = MAP_COPY.waiting;+ io.redraw();+ }+ /** Once, with the toggle on, before the person asked, and only for a repo with a map. */+ mayAutoOpen() {+ return this.autoOpenOnRead && !this.autoOpenTried && !this.requested && this.repo !== null;+ }+ /** Whether an animation would show anything: a map on screen, motion allowed, a ripple with somewhere to go. */+ canAnimate(kind) {+ const on = this.drawn;+ if (this.reducedMotion || on === null) return false;+ return kind === "flash" || rippleRadius(on.layout, resolveOverlay(on.layout, this.trail, on.root).overlay) > 0;+ }+ /** A flash or a ripple when it would show; otherwise (reduced motion, nothing on screen) the resting frame. */+ animate(io, kind) {+ this.animator.stop();+ if (!this.canAnimate(kind)) return io.redraw();+ this.animator.play(io, kind, (step) => this.frame(step));+ }+ /** The current trail on the drawn map at one step, or null once the map is off screen. */+ frame(step) {+ const on = this.drawn;+ if (on === null) return null;+ const cells = frameCells(on.layout, resolveOverlay(on.layout, this.trail, on.root).overlay, step);+ return { cells, columns: on.layout.columns, rows: on.layout.rows };+ }+};++// src/model/ask.ts+function askRoute(question) {+ return /^\s*why\b/i.test(question) ? { tool: "get_why", args: { query: question } } : { tool: "get_answer", args: { question } };+}+__name(askRoute, "askRoute");+function askReply(tool, reply) {+ const body = typeof reply === "object" && reply !== null ? reply : {};+ return tool === "get_why" ? { tool, reply: body } : { tool, reply: body };+}+__name(askReply, "askReply");+function mayHaveUsedModel(a) {+ return a.tool === "get_answer" && a.reply.degraded !== "no-llm-provider";+}+__name(mayHaveUsedModel, "mayHaveUsedModel");+function lensCommand(args) {+ const [word = "", ...rest] = args.trim().split(/\s+/);+ const question = rest.join(" ");+ switch (word.toLowerCase()) {+ case "map":+ case "recap":+ return { tab: word.toLowerCase(), question: null };+ case "ask":+ return { tab: "ask", question: question === "" ? null : question };+ default:+ return { tab: null, question: null };+ }+}+__name(lensCommand, "lensCommand");+function whyDraft(decision) {+ return `why ${decision}`;+}+__name(whyDraft, "whyDraft");++// src/model/review.ts+var initialReview = { edited: false, outcome: { phase: "none" }, decision: null };+function reduceReview(state2, action) {+ switch (action.type) {+ case "turnStarted":+ return state2.edited || state2.outcome.phase !== "none" || state2.decision !== null ? initialReview : state2;+ case "fileEdited":+ return state2.edited ? state2 : { ...state2, edited: true };+ case "reviewStarted":+ return { ...state2, outcome: { phase: "reviewing" } };+ case "reviewed":+ return { ...state2, outcome: { phase: "done", risk: action.risk } };+ case "reviewFailed":+ return { ...state2, outcome: { phase: "failed", reason: action.reason, message: action.message } };+ case "decisionNoted":+ return state2.decision === action.title ? state2 : { ...state2, decision: action.title };+ }+}+__name(reduceReview, "reduceReview");+function emptyDiff(risk) {+ return risk.status === "nothing_to_score" || risk.health_delta?.scope?.changed === 0;+}+__name(emptyDiff, "emptyDiff");+function reviewable(risk) {+ return risk.error === void 0 && !emptyDiff(risk);+}+__name(reviewable, "reviewable");+var WRITE_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);+function isFileEdit(e, result) {+ if (typeof e.tool !== "string" || !WRITE_TOOLS.has(e.tool)) return false;+ if (typeof e.tool_use_id === "string" && e.tool_use_id.startsWith("toolu_plugin_")) return false;+ if (typeof result !== "object" || result === null) return false;+ const r = result;+ return r.deny === void 0 && r.isError !== true;+}+__name(isFileEdit, "isFileEdit");+function shouldReview(e, edits) {+ if (e.agentId !== void 0 || edits === 0) return false;+ return e.isAborted !== true && e.reason !== "aborted" && e.reason !== "error";+}+__name(shouldReview, "shouldReview");+function isRetryable(action) {+ return action.type === "reviewFailed" && action.reason !== "timeout";+}+__name(isRetryable, "isRetryable");+function testsToRun(risk) {+ const block = risk.impacted_tests;+ const tests = block?.tests_to_run ?? [];+ if (block === void 0 || tests.length === 0) return null;+ return {+ tests,+ total: block.total ?? tests.length,+ truncated: block.truncated === true,+ files: block.tests_to_run_kind === "test_file",+ measured: block.basis === "measured"+ };+}+__name(testsToRun, "testsToRun");++// src/model/session.ts+var initialSession = {+ mode: null,+ freshness: null,+ hint: null,+ hintsShown: [],+ repoRoot: null,+ running: null,+ contexts: {},+ notes: {},+ savings: null,+ review: initialReview,+ lastReview: null,+ touched: [],+ pane: { tab: "map", draft: "" },+ ask: { phase: "idle" },+ modelAsks: 0,+ compacted: false+};+function hintFor(mode, liteReason) {+ if (mode === "full" || mode === "no-repo") return null;+ if (mode === "lite") return liteReason ?? "no-server";+ return mode;+}+__name(hintFor, "hintFor");+function reduce(state2, action) {+ switch (action.type) {+ case "discovered": {+ const kind = hintFor(action.mode, action.liteReason);+ const indexed = action.mode === "full" || action.mode === "lite";+ const freshness = indexed ? action.freshness : null;+ const repoRoot = indexed ? action.repoRoot ?? null : null;+ const savings = action.mode === "full" ? state2.savings : null;+ if (kind !== null && !state2.hintsShown.includes(kind)) {+ const hintsShown = [...state2.hintsShown, kind];+ return { ...state2, mode: action.mode, freshness, repoRoot, savings, hint: kind, hintsShown };+ }+ const hint = state2.hint === kind ? state2.hint : null;+ return { ...state2, mode: action.mode, freshness, repoRoot, savings, hint };+ }+ case "turnCompleted":+ return state2.hint === null ? state2 : { ...state2, hint: null };+ case "toolStarted":+ return { ...state2, running: action.tool };+ case "toolEnded":+ return state2.running?.id === action.id ? { ...state2, running: null } : state2;+ case "contextLoaded":+ return { ...state2, contexts: { ...state2.contexts, [action.file]: action.context } };+ case "notesFor": {+ if (action.notes.length === 0) return state2;+ const notes = { ...state2.notes, [action.id]: action.notes };+ const decision = action.notes.find((n) => n.kind === "decision");+ const review = decision === void 0 ? state2.review : reduceReview(state2.review, { type: "decisionNoted", title: decision.title });+ return { ...state2, notes, review };+ }+ case "savings":+ return { ...state2, savings: action.delta.tokens > 0 ? action.delta : null };+ case "touched":+ return state2.touched.includes(action.path) ? state2 : { ...state2, touched: [...state2.touched, action.path] };+ case "tab":+ return { ...state2, pane: { tab: action.tab, draft: action.draft ?? state2.pane.draft } };+ case "asked": {+ const modelAsks = state2.modelAsks + (action.tool === "get_answer" ? 1 : 0);+ const ask = { phase: "asking", question: action.question, tool: action.tool, busy: false };+ return { ...state2, modelAsks, ask, pane: { ...state2.pane, draft: "" } };+ }+ case "askBusy":+ return state2.ask.phase === "asking" && !state2.ask.busy ? { ...state2, ask: { ...state2.ask, busy: true } } : state2;+ case "answered": {+ const modelAsks = Math.max(0, state2.modelAsks - (action.answer.tool === "get_answer" && !mayHaveUsedModel(action.answer) ? 1 : 0));+ return { ...state2, modelAsks, ask: { phase: "answered", question: action.question, answer: action.answer } };+ }+ case "askFailed":+ return { ...state2, ask: { phase: "failed", question: action.question, tool: action.tool, message: action.message } };+ case "compacted":+ return state2.compacted ? state2 : { ...state2, compacted: true };+ case "briefDone":+ return state2.compacted ? { ...state2, compacted: false } : state2;+ default:+ return reduceTurn(state2, action);+ }+}+__name(reduce, "reduce");+function reduceTurn(state2, action) {+ const review = reduceReview(state2.review, action);+ const compacted = action.type === "turnStarted" ? false : state2.compacted;+ const lastReview = action.type === "reviewed" && reviewable(action.risk) ? action.risk : state2.lastReview;+ if (review === state2.review && compacted === state2.compacted && lastReview === state2.lastReview) return state2;+ return { ...state2, review, compacted, lastReview };+}+__name(reduceTurn, "reduceTurn");+function surfacedDecisions(state2) {+ const seen = /* @__PURE__ */ new Map();+ for (const notes of Object.values(state2.notes)) {+ for (const n of notes) if (n.kind === "decision" && !seen.has(n.title)) seen.set(n.title, n.reviewed);+ }+ return [...seen].map(([title, reviewed]) => ({ title, reviewed }));+}+__name(surfacedDecisions, "surfacedDecisions");++// src/views/review.ts+var PRESS = { tests: "lens-review-tests", why: "lens-review-why", details: "lens-review-details" };+var COMPARED = /* @__PURE__ */ new Set(["available", "partial"]);+var NOT_REPORTED = { words: HEALTH_NOT_REPORTED, short: HEALTH_NOT_REPORTED };+function notComparedWords(hd) {+ return { words: notCompared(hd.explanation.replace(/\.$/, "")), short: notCompared("") };+}+__name(notComparedWords, "notComparedWords");+function clearWords(hd) {+ if (hd.resolved === 0) return { words: noNewFindings(hd.scope?.analyzed ?? 0), short: NO_NEW_FINDINGS };+ return { words: healthImproved(hd.resolved), short: improvedShort(hd.resolved), color: DARK.success };+}+__name(clearWords, "clearWords");+var FINDINGS_TONE = {+ review_required: { required: true, color: DARK.error },+ review_recommended: { required: false, color: DARK.warning }+};+function findingsWords(d, hd) {+ const headline = d.headline.replace(/\.$/, "");+ const words = hd.resolved > 0 ? `${headline}; ${resolvedToo(hd.resolved)}` : headline;+ const tone = FINDINGS_TONE[d.status];+ if (tone === void 0) return { words, short: PARTLY_COMPARED };+ return { words, short: newFindings(hd.findings_total, tone.required), color: tone.color };+}+__name(findingsWords, "findingsWords");+function health(risk) {+ const d = risk.directive;+ const hd = risk.health_delta;+ if (d === void 0 || hd === void 0) return NOT_REPORTED;+ if (!COMPARED.has(hd.status)) return notComparedWords(hd);+ if (d.status === "clear_in_analyzed_scope") return clearWords(hd);+ return findingsWords(d, hd);+}+__name(health, "health");+function overlap(risk) {+ const block = risk.branch_overlap;+ const branches = block?.branches ?? [];+ if (branches.length === 0) return null;+ const files = [...new Set(branches.flatMap((b) => (b.files ?? []).map((f) => f.file)))];+ return { branches: branches.map((b) => b.branch), files, more: block?.truncated === true };+}+__name(overlap, "overlap");+function isClear(risk) {+ return risk.directive?.status === "clear_in_analyzed_scope";+}+__name(isClear, "isClear");+function header(risk, changed) {+ return `Change review (${reviewScope(risk.ref ?? "working tree", risk.working_tree !== false, changed)})`;+}+__name(header, "header");+function findingSegments(hd) {+ const rows = hd?.top_findings ?? [];+ const segments = rows.map(findingLine);+ const more = (hd?.findings_total ?? 0) - rows.length;+ if (more > 0) segments.push(moreFindings(more));+ return segments;+}+__name(findingSegments, "findingSegments");+function scopeSegments(hd) {+ if (hd?.status !== "partial" || hd.scope === void 0) return [];+ return [partialScope(hd.scope.analyzed, hd.scope.changed, hd.skipped?.by_reason ?? {})];+}+__name(scopeSegments, "scopeSegments");+function testSegments(risk) {+ const tests = testsToRun(risk);+ return tests === null ? [] : [testsLine(tests)];+}+__name(testSegments, "testSegments");+function overlapSegments(risk) {+ const shared = overlap(risk);+ return shared === null ? [] : [`Branches: ${overlapLine(shared.branches, shared.files, shared.more)}`];+}+__name(overlapSegments, "overlapSegments");+function cardSegments(risk) {+ if (isClear(risk) && overlap(risk) === null) return [header(risk, null), `health: ${health(risk).words}`];+ const hd = risk.health_delta;+ return [+ header(risk, hd?.scope?.changed ?? null),+ `Health: ${health(risk).words}`,+ ...findingSegments(hd),+ ...scopeSegments(hd),+ diffShape(risk.risk_percentile),+ ...testSegments(risk),+ ...overlapSegments(risk)+ ];+}+__name(cardSegments, "cardSegments");+function doneText(risk) {+ if (risk.error !== void 0) return reviewFailed(risk.error);+ if (emptyDiff(risk)) return null;+ return cardSegments(risk).join(" · ");+}+__name(doneText, "doneText");+function reviewText(outcome) {+ switch (outcome.phase) {+ case "none":+ case "reviewing":+ return null;+ case "failed":+ return outcome.reason === "timeout" ? REVIEW_TIMED_OUT : reviewFailed(outcome.message);+ case "done":+ return doneText(outcome.risk);+ }+}+__name(reviewText, "reviewText");+function buttons(risk, decision) {+ const out = [];+ if (testsToRun(risk) !== null) out.push(button(PRESS.tests, "1", RUN_TESTS));+ if (decision !== null) out.push(button(PRESS.why, "2", WHY));+ if (risk.directive !== void 0) out.push(button(PRESS.details, "3", DETAILS));+ return out;+}+__name(buttons, "buttons");+var GAP2 = 2;+function buttonCells(pressable) {+ return pressable.reduce((n, b) => n + (b.type === "Button" ? b.props.label.length + 3 : 0) + GAP2, 0);+}+__name(buttonCells, "buttonCells");+function quietInBand(risk, decision) {+ return isClear(risk) && testsToRun(risk) === null && overlap(risk) === null && decision === null;+}+__name(quietInBand, "quietInBand");+function summaryParts(risk, room) {+ const h = health(risk);+ const words = fit(`review · health: ${h.short}`, room);+ const parts = [text(words, h.color === void 0 ? { dimColor: true } : { color: h.color })];+ const shared = overlap(risk);+ const tail = shared === null ? "" : ` · ${overlapShort(shared.branches.length)}`;+ if (tail !== "" && room - words.length >= tail.length) parts.push(text(tail, { dimColor: true }));+ return parts;+}+__name(summaryParts, "summaryParts");+function resultRow(risk, columns, decision) {+ if (!reviewable(risk) || quietInBand(risk, decision)) return null;+ const pressable = buttons(risk, decision);+ const room = Math.max(0, columns - buttonCells(pressable));+ return box({ key: "lens-review", flexDirection: "row", columnGap: GAP2 }, [+ box({ flexDirection: "row" }, summaryParts(risk, room)),+ ...pressable+ ]);+}+__name(resultRow, "resultRow");+function reviewBandRow(outcome, columns, decision = null) {+ if (outcome.phase === "reviewing") return text(fit(REVIEWING, columns), { dimColor: true, wrap: "truncate-end" });+ return outcome.phase === "done" ? resultRow(outcome.risk, columns, decision) : null;+}+__name(reviewBandRow, "reviewBandRow");+function directiveRows(outcome) {+ if (outcome.phase !== "done" || outcome.risk.directive === void 0) return null;+ return directiveLines(outcome.risk.directive);+}+__name(directiveRows, "directiveRows");+function runTestsText(outcome) {+ if (outcome.phase !== "done") return null;+ const tests = testsToRun(outcome.risk);+ return tests === null ? null : runTestsPrompt(tests);+}+__name(runTestsText, "runTestsText");+function withCard(result, answer, card) {+ if (typeof result !== "object" || result === null) return result;+ const r = result;+ if (typeof r.text !== "string") return result;+ return { ...r, text: r.text === answer ? card : `${r.text} · ${card}` };+}+__name(withCard, "withCard");++// src/views/brief.ts+var BRIEF_PRESS = "lens-brief";+var ITEM_CHARS = 240;+function listWithin(head, items, room) {+ const cut = items.map((i) => fit(i.replace(/\s+/g, " ").trim(), ITEM_CHARS));+ for (let k = cut.length; k >= 0; k--) {+ const more = cut.length - k;+ const shown = cut.slice(0, k).join("; ");+ const tail = more === 0 ? "" : `${shown === "" ? "" : "; "}and ${more} more`;+ const line2 = `${head} ${shown}${tail}`;+ if (line2.length <= room) return line2;+ }+ return fit(`${head} and ${cut.length} more`, room);+}+__name(listWithin, "listWithin");+function reviewItems(state2) {+ const risk = state2.lastReview;+ if (risk === null) return [];+ const findings = (risk.health_delta?.findings_total ?? 0) > 0 ? (risk.health_delta?.top_findings ?? []).map(findingLine) : [];+ const tests = testsToRun(risk);+ const shared = overlap(risk);+ return [+ ...findings,+ ...tests === null ? [] : [briefTests(tests)],+ ...shared === null ? [] : [overlapLine(shared.branches, shared.files, shared.more)]+ ];+}+__name(reviewItems, "reviewItems");+function briefText(state2) {+ const sections = [+ [BRIEF_COPY.files, [...state2.touched]],+ [BRIEF_COPY.decisions, surfacedDecisions(state2).map((d) => briefDecision(d.title, d.reviewed))],+ [BRIEF_COPY.review, reviewItems(state2)]+ ];+ const filled = sections.filter(([, items]) => items.length > 0);+ if (filled.length === 0) return null;+ let brief = BRIEF_COPY.intro;+ filled.forEach(([head, items], i) => {+ const room = Math.floor((BRIEF_CHARS - brief.length) / (filled.length - i)) - 1;+ brief += `+${listWithin(head, items, Math.max(0, room))}`;+ });+ return brief;+}+__name(briefText, "briefText");+function briefBandRow(state2, columns, besideReview = false) {+ if (!state2.compacted || briefText(state2) === null) return null;+ return box({ key: "lens-brief", flexDirection: "row", columnGap: 2 }, [+ text(fit(BRIEF_COPY.compacted, Math.max(1, columns - BRIEF_COPY.button.length - 5)), { dimColor: true }),+ button(BRIEF_PRESS, besideReview ? "4" : "1", BRIEF_COPY.button)+ ]);+}+__name(briefBandRow, "briefBandRow");++// src/views/band.ts+var MAX_BAND_ROWS = 2;+function bandRows(state2, columns = Number.POSITIVE_INFINITY) {+ const rows = [];+ if (state2.hint !== null) rows.push(HINTS[state2.hint]);+ if (state2.freshness !== null) rows.push(freshnessLine(state2.freshness));+ if (state2.savings !== null) rows.push(savingsLine(state2.savings, columns));+ return rows.slice(0, MAX_BAND_ROWS);+}+__name(bandRows, "bandRows");+function bandView(state2, viewport, extra = []) {+ if (viewport.hasSurvey) return null;+ const review = reviewBandRow(state2.review.outcome, viewport.columns, state2.review.decision);+ const actions = [review, briefBandRow(state2, viewport.columns, review !== null)].filter((n) => n !== null);+ const own = [...bandRows(state2, viewport.columns), ...extra].slice(0, Math.max(0, MAX_BAND_ROWS - actions.length));+ if (own.length === 0 && actions.length === 0) return null;+ const nodes = own.map((row) => text(fit(row, viewport.columns), { dimColor: true, wrap: "truncate-end" }));+ return box({ key: "lens-band", flexDirection: "column" }, [...nodes, ...actions]);+}+__name(bandView, "bandView");++// src/views/margin.ts+var MAX_MARGIN_LINES = 2;+function marginView(notes) {+ if (notes === void 0 || notes.length === 0) return null;+ return box(+ { key: "lens-margin", flexDirection: "column" },+ notes.slice(0, MAX_MARGIN_LINES).map((n) => text(` ${marginLine(n)}`, { dimColor: true, wrap: "truncate-end" }))+ );+}+__name(marginView, "marginView");++// src/views/answer.ts+var LIST_ROWS = 5;+var ROW_CHARS = 300;+var code = /* @__PURE__ */ __name((s) => `\`${s.replace(/`/g, "'")}\``, "code");+var line = /* @__PURE__ */ __name((s, chars = ROW_CHARS) => fit(s.replace(/\s+/g, " ").trim(), chars), "line");+function ids(refs) {+ const found = (refs ?? []).map((r) => r.id).filter((id) => typeof id === "string");+ return found.length === 0 ? "" : ` · ${found.map(code).join(" ")}`;+}+__name(ids, "ids");+function list(head, rows, row, total) {+ if (rows === void 0 || rows.length === 0) return [];+ const shown = rows.slice(0, LIST_ROWS);+ const more = Math.max(total ?? 0, rows.length) - shown.length;+ return [`**${head}**`, ...shown.map((r) => `- ${row(r)}`), ...more > 0 ? [`- ${moreRows(more)}`] : []];+}+__name(list, "list");+function answerHead(a) {+ const parts = [`**${a.degraded === void 0 ? PANE_COPY.fromModel : PANE_COPY.fromIndex}**`];+ if (a.confidence !== void 0) parts.push(`confidence ${a.confidence}`);+ if (a.retrieval_quality !== void 0) parts.push(`retrieval ${a.retrieval_quality}`);+ return parts.join(" · ");+}+__name(answerHead, "answerHead");+function answerMarkdown(a) {+ const cited = a.citations ?? [];+ const evidence = cited.length === 0 ? PANE_COPY.noEvidence : `evidence: ${cited.map(code).join(", ")}`;+ return [answerHead(a), a.answer ?? "", evidence];+}+__name(answerMarkdown, "answerMarkdown");+var decisionRow = /* @__PURE__ */ __name((d) => {+ const facts = [d.status, d.authority, d.confidence === null || d.confidence === void 0 ? void 0 : `confidence ${d.confidence}`].filter((f) => f !== void 0).join(" · ");+ const id = d.id === void 0 ? "" : ` · ${code(d.id)}`;+ const body = d.decision === void 0 ? "" : `: ${line(d.decision)}`;+ return `**${line(d.title, 120)}**${facts === "" ? "" : ` (${facts})`}${id}${body}`;+}, "decisionRow");+var commitRow = /* @__PURE__ */ __name((c) => `${code(c.sha ?? "?")} ${line(c.message ?? "", 160)}${c.date === void 0 ? "" : ` (${c.date.slice(0, 10)})`}${ids(c.evidence_refs)}`, "commitRow");+var rationaleRow = /* @__PURE__ */ __name((r) => `${code(r.lines === void 0 ? r.path : `${r.path}:${r.lines[0]}`)} ${line(r.comment)}${ids(r.evidence_refs)}`, "rationaleRow");+function whyMarkdown(w) {+ const from = `**${PANE_COPY.fromIndex}**`;+ const head = w.answer_basis === void 0 ? from : `${from} · basis ${w.answer_basis}`;+ const commits = w.git_archaeology?.git_log ?? w.git_archaeology?.file_commits;+ return [+ head,+ ...w.reason === void 0 ? [] : [w.reason],+ ...list("Decisions", w.decisions, decisionRow),+ ...list("Commits", commits, commitRow),+ ...list("Rationale in the code", w.code_rationale, rationaleRow, w.code_rationale_total)+ ];+}+__name(whyMarkdown, "whyMarkdown");+function replyMarkdown(question, a) {+ const body = a.tool === "get_answer" ? answerMarkdown(a.reply) : whyMarkdown(a.reply);+ const text2 = [`> ${line(question, 200)}`, ...body].join("\n\n");+ if (text2.length <= ASK_CHARS) return text2;+ const note = `++_${askCut(ASK_CHARS)}_`;+ return `${text2.slice(0, ASK_CHARS - note.length).trimEnd()}${note}`;+}+__name(replyMarkdown, "replyMarkdown");++// src/views/pane.ts+var TABS = ["map", "ask", "recap"];+var TAB_PRESS = { map: "lens-tab-map", ask: "lens-tab-ask", recap: "lens-tab-recap" };+var ASK_KEY = "lens-ask";+var TAB_ROWS = 1;+function tabsView(current) {+ return box(+ { key: "lens-tabs", flexDirection: "row", columnGap: 2 },+ TABS.map((tab, i) => button(TAB_PRESS[tab], String(i + 1), PANE_COPY.tabs[tab], tab !== current))+ );+}+__name(tabsView, "tabsView");+var dim = /* @__PURE__ */ __name((line2, columns) => text(fit(line2, columns), { dimColor: true, wrap: "truncate-end" }), "dim");+function askStatus(state2, columns) {+ const ask = state2.ask;+ switch (ask.phase) {+ case "idle":+ return [dim(PANE_COPY.askIdle, columns)];+ case "asking":+ return [+ dim(`> ${ask.question}`, columns),+ dim(askingLine(ask.tool), columns),+ ...ask.busy ? [dim(PANE_COPY.askBusy, columns)] : []+ ];+ case "failed":+ return [dim(`> ${ask.question}`, columns), dim(askFailedLine(ask.message), columns)];+ case "answered":+ return [markdown(replyMarkdown(ask.question, ask.answer))];+ }+}+__name(askStatus, "askStatus");+function askView(state2, columns) {+ const field = input({+ key: ASK_KEY,+ label: PANE_COPY.askLabel,+ placeholder: PANE_COPY.askPlaceholder,+ submitLabel: PANE_COPY.askSubmit,+ autoFocus: true,+ ...state2.pane.draft === "" ? {} : { value: state2.pane.draft }+ });+ return box({ key: "lens-ask-tab", flexDirection: "column" }, [field, ...askStatus(state2, columns)]);+}+__name(askView, "askView");+function overlapWords(risk) {+ const shared = overlap(risk);+ if (shared !== null) return overlapLine(shared.branches, shared.files, shared.more);+ return risk.branch_overlap === void 0 ? RECAP_COPY.notReported : RECAP_COPY.noOverlap;+}+__name(overlapWords, "overlapWords");+function reviewRows(state2) {+ const risk = state2.lastReview;+ if (risk === null) return [[RECAP_COPY.review, RECAP_COPY.noReview]];+ const hd = risk.health_delta;+ const compared = hd !== void 0 && (hd.status === "available" || hd.status === "partial");+ const tests = testsToRun(risk);+ return [+ RECAP_COPY.fromReview,+ [RECAP_COPY.health, health(risk).words],+ [RECAP_COPY.findings, compared ? findingsCounts(hd.resolved, hd.findings_total) : RECAP_COPY.notCompared],+ [RECAP_COPY.tests, tests === null ? RECAP_COPY.noTests : testsToRunCount(tests)],+ [RECAP_COPY.overlap, overlapWords(risk)]+ ];+}+__name(reviewRows, "reviewRows");+function savedRow(state2) {+ if (state2.savings !== null) return savingsLine(state2.savings, Number.POSITIVE_INFINITY);+ return state2.mode === "full" ? RECAP_COPY.noSavings : RECAP_COPY.savingsNeedServer;+}+__name(savedRow, "savedRow");+function recapRows(state2, touched) {+ const decisions = surfacedDecisions(state2).map((d) => d.title);+ return [+ [RECAP_COPY.files, filesTouched(state2.touched.length, touched)],+ ...reviewRows(state2),+ [RECAP_COPY.saved, savedRow(state2)],+ [RECAP_COPY.decisions, decisions.length === 0 ? RECAP_COPY.noDecisions : decisionsSurfaced(decisions)]+ ];+}+__name(recapRows, "recapRows");+function recapView(state2, touched, columns) {+ const rows = recapRows(state2, touched);+ const width = Math.max(...rows.map((r) => typeof r === "string" ? 0 : r[0].length)) + 2;+ const drawn = rows.map(+ (r) => typeof r === "string" ? dim(r, columns) : box({ flexDirection: "row" }, [+ text(r[0].padEnd(width), { dimColor: true }),+ text(fit(r[1], Math.max(1, columns - width)), { wrap: "truncate-end" })+ ])+ );+ return box({ key: "lens-recap", flexDirection: "column" }, [...drawn, dim(recapFooter(state2.modelAsks), columns)]);+}+__name(recapView, "recapView");+function paneView(tab, body) {+ return box({ key: "lens-pane", flexDirection: "column" }, [tabsView(tab), body]);+}+__name(paneView, "paneView");++// src/views/spinner.ts+function spinnerSuffix(state2) {+ if (state2.running === null) return null;+ const ctx = state2.contexts[state2.running.file];+ return ctx === void 0 ? null : spinnerLine(state2.running.file, ctx);+}+__name(spinnerSuffix, "spinnerSuffix");++// src/model/squeeze.ts+var MARKER = /^\[repowise#([0-9a-f]{12}): (\d+) lines omitted \(~(\d+) tokens\); restore: repowise expand \1\]$/;+function markerOf(line2) {+ const m = MARKER.exec(line2.trim());+ return m === null ? null : { ref: m[1], lines: Number(m[2]), tokens: Number(m[3]) };+}+__name(markerOf, "markerOf");+var isBlank = /* @__PURE__ */ __name((line2) => line2.trim() === "", "isBlank");+function trailingMarkers(lines) {+ let end = lines.length;+ const markers = [];+ while (end > 0) {+ const line2 = lines[end - 1];+ const marker = isBlank(line2) ? null : markerOf(line2);+ if (!isBlank(line2) && marker === null) break;+ if (marker !== null) markers.unshift(marker);+ end--;+ }+ return { kept: lines.slice(0, end), markers };+}+__name(trailingMarkers, "trailingMarkers");+var PYTEST_SUMMARY = /^=+ (.*\b(?:passed|failed|error|errors|skipped)\b.*) =+$/;+var PYTEST_FAILED = /\b(\d+) failed\b/;+var PYTEST_ERRORS = /\b(\d+) errors?\b/;+var JEST_SUMMARY = /^\s*Tests?:\s.*?\b(\d+) failed\b/;+var CARGO_SUMMARY = /^test result: \w+\. \d+ passed; (\d+) failed;/;+var GO_FAIL = /^--- FAIL:/;+function pytestCounts(line2) {+ const m = PYTEST_SUMMARY.exec(line2);+ if (m === null) return null;+ return { failed: Number(PYTEST_FAILED.exec(m[1])?.[1] ?? 0), errors: Number(PYTEST_ERRORS.exec(m[1])?.[1] ?? 0) };+}+__name(pytestCounts, "pytestCounts");+function runnerFailures(kept) {+ let cargo = 0;+ let go = 0;+ for (const line2 of kept) {+ const pytest = pytestCounts(line2);+ if (pytest !== null) return pytest;+ const jest = JEST_SUMMARY.exec(line2);+ if (jest !== null) return { failed: Number(jest[1]), errors: 0 };+ cargo += Number(CARGO_SUMMARY.exec(line2)?.[1] ?? 0);+ if (GO_FAIL.test(line2)) go++;+ }+ return { failed: cargo + go, errors: 0 };+}+__name(runnerFailures, "runnerFailures");+function parseSqueeze(output) {+ const { kept, markers } = trailingMarkers(output.split(/\r?\n/));+ if (markers.length === 0) return null;+ const refs = /* @__PURE__ */ new Set();+ let lines = 0;+ let tokens = 0;+ for (const m of markers) {+ if (refs.has(m.ref)) continue;+ refs.add(m.ref);+ lines += m.lines;+ tokens += m.tokens;+ }+ return {+ originalLines: kept.length + lines,+ keptLines: kept.length,+ omittedTokens: tokens,+ ...runnerFailures(kept),+ refs: [...refs]+ };+}+__name(parseSqueeze, "parseSqueeze");+function bashText(output) {+ if (typeof output === "string") return output;+ const stdout = output?.stdout;+ return typeof stdout === "string" ? stdout : null;+}+__name(bashText, "bashText");++// src/views/squeeze.ts+var BAR_CELLS = 12;+function squeezeBar(s, cells = BAR_CELLS) {+ const filled = Math.min(cells, Math.max(1, Math.round(cells * s.keptLines / Math.max(1, s.originalLines))));+ return `${"█".repeat(filled)}${"░".repeat(cells - filled)}`;+}+__name(squeezeBar, "squeezeBar");+function squeezeView(s) {+ return text(`${squeezeBar(s)} ${squeezeLine(s)}`, { dimColor: true, wrap: "truncate-end" });+}+__name(squeezeView, "squeezeView");++// src/register.ts+var PROCESS_TIMEOUT_MS = 5e3;+var SAVINGS_TIMEOUT_MS = 3e4;+var SAVINGS_COOLDOWN_MS = 6e4;+var MCP_SERVER_KEY = "repowise";+var PANE_ID = "lens";+var PANE_ROWS = 29;+var ASK_TIMEOUT_MS = 3e4;+var state = initialSession;+var generation = 0;+var running = false;+var dirty = false;+var latest = null;+var mcpConnected = false;+var savingsBase = null;+var savingsBusy = false;+var savingsAskedAt = Number.NEGATIVE_INFINITY;+var squeezes = /* @__PURE__ */ new Map();+var contextAsked = /* @__PURE__ */ new Set();+var reviewOn = true;+var reviewGeneration = 0;+var editsThisTurn = 0;+var started = null;+var autoOpenOn = false;+var discovery = null;+var cwd = null;+var map = new LensMap(false);+var ERROR_CELLS = 160;+function bind($) {+ const host = {+ session: { cwd: /* @__PURE__ */ __name(() => $.session.cwd(), "cwd") },+ fs: {+ read: /* @__PURE__ */ __name((path) => $.fs.read(path), "read"),+ exists: /* @__PURE__ */ __name((path) => $.fs.exists(path), "exists")+ },+ process: {+ run: /* @__PURE__ */ __name((argv, cwd2) => $.process.run(argv, { cwd: cwd2, timeoutMs: PROCESS_TIMEOUT_MS }), "run")+ },+ http: /* @__PURE__ */ __name((url, init) => {+ const request = {};+ if (init.method !== void 0) request.method = init.method;+ if (init.headers !== void 0) request.headers = init.headers;+ if (init.body !== void 0) request.body = init.body;+ return $.http.fetch(url, request);+ }, "http"),+ mcp: {+ connect: /* @__PURE__ */ __name(async () => mcpConnected ||= (await $.mcp.connect(MCP_SERVER_KEY)).isConnected, "connect"),+ server: /* @__PURE__ */ __name(async () => {+ const r = await $.mcp.connect(MCP_SERVER_KEY);+ return r.isConnected && typeof r.server === "string" ? r.server : null;+ }, "server"),+ call: /* @__PURE__ */ __name((server, tool, args) => $.mcp.call(server, tool, args), "call")+ }+ };+ return {+ host,+ redraw: /* @__PURE__ */ __name(() => $.ui.invalidate("ui.render"), "redraw"),+ debug: /* @__PURE__ */ __name((message) => $.ui.log(`lens: ${message}`, { to: "debug" }), "debug"),+ blit: /* @__PURE__ */ __name((cells, columns, rows) => $.ui.blit({ requestId: PANE_ID, key: MAP_KEY, cells, columns, rows }), "blit"),+ // Focus only when asked (/lens, a press): an automatic open leaves the prompt the keyboard.+ openPane: /* @__PURE__ */ __name((focus) => $.ui.open(+ focus ? { id: PANE_ID, title: MAP_COPY.title, rows: PANE_ROWS, focus: true } : { id: PANE_ID, title: MAP_COPY.title, rows: PANE_ROWS }+ ), "openPane"),+ closePane: /* @__PURE__ */ __name(() => $.ui.close({ id: PANE_ID }), "closePane")+ };+}+__name(bind, "bind");+function mapRepo(d) {+ if (d.mode !== "full" || d.repo === void 0 || d.repoRoot === null) return null;+ return { id: d.repo.id, root: d.repoRoot, updatedAt: d.repo.updatedAt, caseInsensitive: isWindowsPath(d.repoRoot) };+}+__name(mapRepo, "mapRepo");+function dispatch(b, action) {+ const next = reduce(state, action);+ if (next === state) return;+ state = next;+ b.redraw();+}+__name(dispatch, "dispatch");+async function refreshOnce(b, gen) {+ const h = b.host;+ const found = await discover(h);+ const indexed = found.mode === "full" || found.mode === "lite";+ const freshness = indexed && found.repoRoot !== null ? await readFreshness(h, found.repoRoot) : null;+ if (gen !== generation) return;+ if (indexed) warmMcp(h);+ discovery = found;+ const action = { type: "discovered", mode: found.mode, freshness, repoRoot: found.repoRoot };+ if (found.liteReason !== void 0) action.liteReason = found.liteReason;+ dispatch(b, action);+ if (found.repo !== void 0) refreshSavings(b, found.repo.id, gen);+ map.setRepo(b, mapRepo(found));+}+__name(refreshOnce, "refreshOnce");+function refreshSavings(b, repoId, gen) {+ const now = Date.now();+ if (savingsBusy || now - savingsAskedAt < SAVINGS_COOLDOWN_MS) return;+ savingsBusy = true;+ savingsAskedAt = now;+ withTimeout(getSavings(repoId), SAVINGS_TIMEOUT_MS, "savings").then((s) => {+ if (gen !== generation) return;+ const totals = savingsTotals(s);+ const delta = savingsBase?.repoId === repoId ? savingsSince(totals, savingsBase.totals) : null;+ if (delta !== null) {+ dispatch(b, { type: "savings", delta });+ return;+ }+ if (savingsBase !== null) dispatch(b, { type: "savings", delta: { tokens: 0, inferredTokens: 0, usd: 0 } });+ savingsBase = { repoId, totals };+ }).catch((err) => b.debug(`savings failed: ${String(err)}`)).finally(() => savingsBusy = false);+}+__name(refreshSavings, "refreshSavings");+function refresh(b) {+ latest = b;+ if (running) {+ dirty = true;+ return;+ }+ running = true;+ dirty = false;+ refreshOnce(b, generation).catch((err) => b.debug(`refresh failed: ${String(err)}`)).finally(() => {+ running = false;+ if (dirty && latest !== null) refresh(latest);+ });+}+__name(refresh, "refresh");+async function onSessionStart($, e, next) {+ const b = bind($);+ try {+ generation++;+ cwd = typeof e.cwd === "string" ? e.cwd : null;+ map.dispose();+ map = new LensMap(autoOpenOn);+ state = initialSession;+ reviewGeneration++;+ editsThisTurn = 0;+ started = null;+ contextAsked.clear();+ squeezes.clear();+ savingsBase = null;+ savingsAskedAt = Number.NEGATIVE_INFINITY;+ resetMcp();+ warmMcp(b.host);+ refresh(b);+ await $.command.register({ name: "lens", description: PANE_COPY.command, argumentHint: PANE_COPY.argumentHint, immediate: true });+ map.setReducedMotion((await $.settings.read())["prefersReducedMotion"] === true);+ } catch (err) {+ b.debug(`session.start failed: ${String(err)}`);+ }+ return next(e);+}+__name(onSessionStart, "onSessionStart");+async function onTurnComplete($, e, next) {+ const b = bind($);+ noteTurnEnd(b, e);+ const result = await next(e);+ return reviewOn && shouldReview(e, editsThisTurn) ? withReview(b, e, result) : result;+}+__name(onTurnComplete, "onTurnComplete");+function noteTurnEnd(b, e) {+ try {+ const action = fromTurnComplete(e);+ if (action === null) return;+ map.turnEnded();+ dispatch(b, action);+ refresh(b);+ } catch (err) {+ b.debug(`turn.complete failed: ${String(err)}`);+ }+}+__name(noteTurnEnd, "noteTurnEnd");+async function withReview(b, e, result) {+ try {+ const card = await finishReview(b);+ return card === null ? result : withCard(result, e.answer ?? "", card);+ } catch (err) {+ b.debug(`change review failed: ${String(err)}`);+ return result;+ }+}+__name(withReview, "withReview");+async function fetchReview(b) {+ try {+ const risk = await callTool(b.host, "get_change_risk", {}, { timeoutMs: REVIEW_TIMEOUT_S * 1e3 });+ return { type: "reviewed", risk };+ } catch (err) {+ b.debug(`change review failed: ${String(err)}`);+ const message = fit((err instanceof Error ? err.message : String(err)).split("\n")[0] ?? "", ERROR_CELLS);+ return { type: "reviewFailed", reason: err instanceof Error && err.name === "TimeoutError" ? "timeout" : "error", message };+ }+}+__name(fetchReview, "fetchReview");+function startReview(b) {+ const review = { gen: reviewGeneration, covers: editsThisTurn, settled: false, outcome: fetchReview(b) };+ void review.outcome.then(() => {+ review.settled = true;+ });+ started = review;+ return review;+}+__name(startReview, "startReview");+function reviewAfterEdit(b) {+ editsThisTurn++;+ dispatch(b, { type: "fileEdited" });+ if (started !== null && started.gen === reviewGeneration && !started.settled) return;+ startReview(b);+}+__name(reviewAfterEdit, "reviewAfterEdit");+function coveringReview() {+ const s = started;+ return s !== null && s.gen === reviewGeneration && s.covers === editsThisTurn ? s : null;+}+__name(coveringReview, "coveringReview");+async function outcomeOf(b, review, reused) {+ const action = await review.outcome;+ return reused && isRetryable(action) ? startReview(b).outcome : action;+}+__name(outcomeOf, "outcomeOf");+async function finishReview(b) {+ const gen = reviewGeneration;+ const reused = coveringReview();+ const review = reused ?? startReview(b);+ if (!review.settled) dispatch(b, { type: "reviewStarted" });+ const action = await outcomeOf(b, review, reused !== null);+ if (gen !== reviewGeneration) return null;+ dispatch(b, action);+ return reviewText(state.review.outcome);+}+__name(finishReview, "finishReview");+async function onTurnStart($, e, next) {+ try {+ if (reviewOn) {+ reviewGeneration++;+ editsThisTurn = 0;+ started = null;+ }+ dispatch(bind($), reviewOn ? { type: "turnStarted" } : { type: "briefDone" });+ } catch (err) {+ bind($).debug(`turn.start failed: ${String(err)}`);+ }+ return next(e);+}+__name(onTurnStart, "onTurnStart");+function pressRunTests($) {+ try {+ const prompt = runTestsText(state.review.outcome);+ if (prompt === null) return;+ $.prompt.submit({ text: prompt }).catch((err) => bind($).debug(`run tests failed: ${String(err)}`));+ } catch (err) {+ bind($).debug(`run tests failed: ${String(err)}`);+ }+}+__name(pressRunTests, "pressRunTests");+function pressWhy($) {+ const b = bind($);+ try {+ const decision = state.review.decision;+ if (decision === null) return;+ dispatch(b, { type: "tab", tab: "ask", draft: whyDraft(decision) });+ map.request(b).catch((err) => b.debug(`why failed: ${String(err)}`));+ } catch (err) {+ b.debug(`why failed: ${String(err)}`);+ }+}+__name(pressWhy, "pressWhy");+function pressBrief($) {+ const b = bind($);+ try {+ const brief = briefText(state);+ dispatch(b, { type: "briefDone" });+ if (brief === null) return;+ $.prompt.submit({ text: brief }).catch((err) => b.debug(`brief failed: ${String(err)}`));+ } catch (err) {+ b.debug(`brief failed: ${String(err)}`);+ }+}+__name(pressBrief, "pressBrief");+async function onPostCompact($, e, next) {+ try {+ dispatch(bind($), { type: "compacted" });+ } catch (err) {+ bind($).debug(`PostCompact failed: ${String(err)}`);+ }+ return next(e);+}+__name(onPostCompact, "onPostCompact");+function startAsk(b, question) {+ const q = question.trim();+ if (q === "") return;+ if (state.ask.phase === "asking") return dispatch(b, { type: "askBusy" });+ const { tool, args } = askRoute(q);+ dispatch(b, { type: "asked", question: q, tool });+ const gen = generation;+ callTool(b.host, tool, args, { timeoutMs: ASK_TIMEOUT_MS }).then((reply) => {+ if (gen === generation) dispatch(b, { type: "answered", question: q, answer: askReply(tool, reply) });+ }).catch((err) => {+ b.debug(`ask failed: ${String(err)}`);+ const message = fit((err instanceof Error ? err.message : String(err)).split("\n")[0] ?? "", ERROR_CELLS);+ if (gen === generation) dispatch(b, { type: "askFailed", question: q, tool, message });+ });+}+__name(startAsk, "startAsk");+async function onAskInput($, e, next) {+ try {+ if (e.kind === "submit" && e.element === ASK_KEY) startAsk(bind($), e.value);+ } catch (err) {+ bind($).debug(`ask failed: ${String(err)}`);+ }+ return next(e);+}+__name(onAskInput, "onAskInput");+function pressDetails($) {+ try {+ for (const row of directiveRows(state.review.outcome) ?? []) $.ui.log(row, { to: "transcript" });+ } catch (err) {+ bind($).debug(`details failed: ${String(err)}`);+ }+}+__name(pressDetails, "pressDetails");+async function onBand($, e, next) {+ const theirs = await next(e);+ try {+ const line2 = map.bandLine();+ const viewport = { columns: e.props.bodyColumns ?? 80, hasSurvey: e.props.hasSurvey === true };+ const tree = bandView(state, viewport, line2 === null ? [] : [line2]);+ if (tree === null) return theirs;+ const elements = $.ui.resolve(e);+ const ours = materialize(tree, elements, {+ [PRESS.tests]: () => pressRunTests($),+ [PRESS.why]: () => pressWhy($),+ [PRESS.details]: () => pressDetails($),+ [BRIEF_PRESS]: () => pressBrief($)+ });+ const box2 = elements["Box"];+ if (theirs === null || theirs === void 0 || box2 === void 0) return ours;+ return box2({ flexDirection: "column", children: [ours, theirs] });+ } catch (err) {+ bind($).debug(`band render failed: ${String(err)}`);+ return theirs;+ }+}+__name(onBand, "onBand");+function fetchContext(b, file) {+ if (contextAsked.has(file)) return;+ contextAsked.add(file);+ const gen = generation;+ fetchFileContext(b.host, file).then((context) => {+ if (gen !== generation || context === null) return;+ dispatch(b, { type: "contextLoaded", file, context });+ }).catch((err) => {+ contextAsked.delete(file);+ b.debug(`context for ${file} failed: ${String(err)}`);+ });+}+__name(fetchContext, "fetchContext");+async function onToolCall($, e, next) {+ const b = bind($);+ const file = fileToolStarted(b, e);+ let result;+ try {+ result = await next(e);+ } finally {+ if (file !== null) dispatch(b, { type: "toolEnded", id: e.tool_use_id });+ }+ editLanded(b, e, result);+ observeTrail($, b, e, result);+ return result;+}+__name(onToolCall, "onToolCall");+function observeTrail($, b, e, result) {+ if (!OBSERVED_TOOLS.has(e.tool)) return;+ try {+ const here = cwd;+ if (here === null) {+ void $.session.cwd().then(+ (c) => cwd = c,+ (err) => b.debug(`cwd failed: ${String(err)}`)+ );+ return;+ }+ const ctx = { cwd: here, isWindows: isWindowsPath(here) };+ const action = fromToolCall(e, result, ctx);+ const raw = e.file_path;+ if (action !== null) map.observe(b, action, typeof raw === "string" ? absolutePath(raw, ctx) : null);+ } catch (err) {+ b.debug(`tool.call observe failed: ${String(err)}`);+ }+}+__name(observeTrail, "observeTrail");+function fileToolStarted(b, e) {+ try {+ const file = fileTarget(e, state.repoRoot);+ if (file === null) return null;+ dispatch(b, { type: "toolStarted", tool: { id: e.tool_use_id, file } });+ fetchContext(b, file);+ return file;+ } catch (err) {+ b.debug(`tool.call failed: ${String(err)}`);+ return null;+ }+}+__name(fileToolStarted, "fileToolStarted");+function editLanded(b, e, result) {+ try {+ if (!isFileEdit(e, result)) return;+ const path = touchedPath(e, cwd, state.repoRoot);+ if (path !== null) dispatch(b, { type: "touched", path });+ if (reviewOn) reviewAfterEdit(b);+ } catch (err) {+ b.debug(`tool.call failed: ${String(err)}`);+ }+}+__name(editLanded, "editLanded");+async function onToolCheck($, e, next) {+ try {+ if (isOwnLensCall(e, next.origin?.plugin)) {+ return { decision: "allow", reason: "Repowise Lens: its own read-only index lookup" };+ }+ } catch (err) {+ bind($).debug(`tool.check failed: ${String(err)}`);+ }+ return next(e);+}+__name(onToolCheck, "onToolCheck");+async function onSpinner($, e, next) {+ let line2 = null;+ try {+ line2 = spinnerSuffix(state);+ } catch (err) {+ bind($).debug(`spinner render failed: ${String(err)}`);+ }+ if (line2 === null) return next(e);+ const theirs = typeof e.props.suffix === "string" ? e.props.suffix : "";+ return next({ ...e, props: { ...e.props, suffix: `${theirs} ${line2}` } });+}+__name(onSpinner, "onSpinner");+function below(elements, theirs, tree) {+ const ours = materialize(tree, elements);+ const box2 = elements["Box"];+ if (theirs === null || theirs === void 0 || box2 === void 0) return ours;+ return box2({ flexDirection: "column", children: [theirs, ours] });+}+__name(below, "below");+function squeezeOf(e) {+ const id = e.props.tool_use_id;+ const known = squeezes.get(id);+ if (known !== void 0 || e.props.tool !== "Bash") return known ?? null;+ const out = bashText(e.props.output);+ const found = out === null ? null : parseSqueeze(out);+ if (found !== null) squeezes.set(id, found);+ return found;+}+__name(squeezeOf, "squeezeOf");+async function onToolResult($, e, next) {+ const theirs = await next(e);+ try {+ const s = squeezeOf(e);+ return s === null ? theirs : below($.ui.resolve(e), theirs, squeezeView(s));+ } catch (err) {+ bind($).debug(`squeeze render failed: ${String(err)}`);+ return theirs;+ }+}+__name(onToolResult, "onToolResult");+async function onPostToolUse($, e, next) {+ const result = await next(e);+ try {+ if (EDIT_TOOLS.has(e.tool_name) && !e.tool_use_id.startsWith("toolu_plugin_")) {+ const notes = notesFromAugment(result?.additionalContext);+ if (notes.length > 0) dispatch(bind($), { type: "notesFor", id: e.tool_use_id, notes });+ }+ } catch (err) {+ bind($).debug(`PostToolUse failed: ${String(err)}`);+ }+ return result;+}+__name(onPostToolUse, "onPostToolUse");+async function onToolUse($, e, next) {+ const theirs = await next(e);+ try {+ const tree = marginView(state.notes[e.props.tool_use_id]);+ return tree === null ? theirs : below($.ui.resolve(e), theirs, tree);+ } catch (err) {+ bind($).debug(`margin render failed: ${String(err)}`);+ return theirs;+ }+}+__name(onToolUse, "onToolUse");+async function onLensCommand($, e) {+ const b = bind($);+ try {+ const asked = lensCommand(e.args ?? "");+ if (asked.tab !== null) dispatch(b, { type: "tab", tab: asked.tab });+ if (discovery === null || mapRepo(discovery) === null) refresh(b);+ await map.request(b);+ if (asked.question !== null) {+ await mcpReady(b.host);+ startAsk(b, asked.question);+ }+ } catch (err) {+ b.debug(`/lens failed: ${String(err)}`);+ }+ return {};+}+__name(onLensCommand, "onLensCommand");+function selectTab($, tab) {+ try {+ dispatch(bind($), { type: "tab", tab });+ } catch (err) {+ bind($).debug(`tab failed: ${String(err)}`);+ }+}+__name(selectTab, "selectTab");+function tabBody(b, e) {+ const { bodyColumns, placement, scroll } = e.props;+ const tab = state.pane.tab;+ if (tab !== "map") map.offScreen();+ if (tab === "ask") return askView(state, bodyColumns);+ if (tab === "recap") return recapView(state, { count: map.trail.reads.length, capped: map.trail.readsCapped }, bodyColumns);+ const d = discovery;+ const notice = d === null ? MAP_COPY.looking : HINTS[hintFor(d.mode, d.liteReason) ?? "no-index"];+ const bodyRows = scroll.bodyRows - TAB_ROWS;+ return map.paneTree(b, { surface: e.surface, notice, bodyColumns, placement, bodyRows });+}+__name(tabBody, "tabBody");+async function onPane($, e, next) {+ if (e.requestId !== PANE_ID) return next(e);+ const b = bind($);+ try {+ const presses = Object.fromEntries(TABS.map((tab) => [TAB_PRESS[tab], () => selectTab($, tab)]));+ return materialize(paneView(state.pane.tab, tabBody(b, e)), $.ui.resolve(e), presses);+ } catch (err) {+ b.debug(`pane render failed: ${String(err)}`);+ return next(e);+ }+}+__name(onPane, "onPane");+function register(on, options = {}) {+ reviewOn = options["lens_review"] !== false;+ autoOpenOn = options["lens_pane_autoopen"] === true;+ on("session.start", onSessionStart);+ on("turn.start", onTurnStart);+ on("turn.complete", onTurnComplete);+ on("ui.render", { component: "AbovePrompt" }, onBand);+ on("ui.render", { component: "Pane" }, onPane);+ on("command.run", { command: "lens" }, onLensCommand);+ on("ui.input", { plugin: "repowise", element: "lens-ask" }, onAskInput);+ on("classic.PostCompact", onPostCompact);+ on("tool.call", onToolCall);+ on("tool.check", onToolCheck);+ on("ui.render", { component: "Spinner" }, onSpinner);+ if (options["lens_squeeze"] !== false) on("ui.render", { component: "ToolResult" }, onToolResult);+ if (options["lens_margin"] !== false) {+ on("classic.PostToolUse", onPostToolUse);+ on("ui.render", { component: "ToolUse" }, onToolUse);+ }+}+__name(register, "register");+export {+ register+};diff --git a/tests/fixtures/lens/augment-edit-notices.txt b/tests/fixtures/lens/augment-edit-notices.txtnew file mode 100644index 000000000..8b737caa1--- /dev/null+++ b/tests/fixtures/lens/augment-edit-notices.txt@@ -0,0 +1,3 @@+[repowise] src/core/auth.py is governed by a standing decision: Use JWT auth because session cookies broke the mobile clients (confirmed across 2 sessions).+[repowise] src/core/parser.py has a decision recorded in it, mined but not reviewed: Keep the parser allocation-free because reuse the buffer.+[repowise] src/core/pipeline.py has been bug-fixed 5x in the last 6 months, last 2 weeks ago (bug magnet); mostly in run_pipeline.diff --git a/tests/fixtures/lens/distill-marker.txt b/tests/fixtures/lens/distill-marker.txtnew file mode 100644index 000000000..7c695cd3d--- /dev/null+++ b/tests/fixtures/lens/distill-marker.txt@@ -0,0 +1 @@+[repowise#21ece412acd8: 64 lines omitted (~2337 tokens); restore: repowise expand 21ece412acd8]diff --git a/tests/unit/cli/test_claude_plugin.py b/tests/unit/cli/test_claude_plugin.pyindex ffd193137..193810140 100644--- a/tests/unit/cli/test_claude_plugin.py+++ b/tests/unit/cli/test_claude_plugin.py@@ -36,6 +36,44 @@ def test_claude_plugin_manifest_paths() -> None:assert "[TODO" not in manifest_path.read_text(encoding="utf-8")+def test_claude_plugin_lens_module() -> None:+ hooks = _load_json(PLUGIN_ROOT / "hooks" / "hooks.json")++ # The engine takes exactly one module, relative to hooks.json.+ assert hooks["modules"] == ["./lens/lens.js"]+ bundle = PLUGIN_ROOT / "hooks" / "lens" / "lens.js"+ assert bundle.is_file()+ assert re.search(r"export\s*\{\s*register\s*\}", bundle.read_text(encoding="utf-8"))+++ ("field", "default", "read_as"),+ [+ # On by default: the bundle treats only `false` as off.+ ("lens_margin", True, "!== false"),+ ("lens_squeeze", True, "!== false"),+ ("lens_review", True, "!== false"),+ # Off by default: the map opens unasked only for someone who turned this on.+ ("lens_pane_autoopen", False, "=== true"),+ ],+)+def test_claude_plugin_lens_toggles(field: str, default: bool, read_as: str) -> None:+ config = _load_json(PLUGIN_ROOT / ".claude-plugin" / "plugin.json")["userConfig"]++ assert set(config[field]) == {"type", "title", "description", "default"}+ assert config[field]["type"] == "boolean"+ assert config[field]["default"] is default+ assert "—" not in config[field]["description"]+ bundle = (PLUGIN_ROOT / "hooks" / "lens" / "lens.js").read_text(encoding="utf-8")+ assert f'options["{field}"] {read_as}' in bundle+++def test_claude_plugin_lens_toggles_are_all_tested() -> None:+ config = _load_json(PLUGIN_ROOT / ".claude-plugin" / "plugin.json")["userConfig"]++ assert set(config) == {"lens_margin", "lens_squeeze", "lens_review", "lens_pane_autoopen"}++def test_claude_plugin_mcp_uses_repowise() -> None:config = _load_json(PLUGIN_ROOT / ".mcp.json")diff --git a/tests/unit/cli/test_lens_contract.py b/tests/unit/cli/test_lens_contract.pynew file mode 100644index 000000000..bdaca804a--- /dev/null+++ b/tests/unit/cli/test_lens_contract.py@@ -0,0 +1,142 @@+"""The text Repowise Lens (the Claude Code mod in packages/claude-mod) reads.++Lens draws rows from two strings the Python side writes: the distill omission+marker at the end of a distilled output, and the augment hook's edit-time+notices. It parses them; it does not recompute them. The golden lines in+tests/fixtures/lens/ are asserted here against the real formatters and parsed+by the mod's own tests from the same files, so a wording change on either side+fails CI instead of silently blanking a Lens row.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime, timedelta+from pathlib import Path++from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++from repowise.cli.commands.augment_cmd import decision_inject+from repowise.core.distill.markers import parse_markers, render_marker+from repowise.core.persistence.database import init_db+from repowise.core.persistence.models import (+ DecisionAcceptance,+ DecisionEvidence,+ DecisionNodeLink,+ DecisionRecord,+ GitMetadata,+ Repository,+)++GOLDEN = Path(__file__).resolve().parents[2] / "fixtures" / "lens"+_REPO_ID = "repo1"+++def _golden_lines(name: str) -> list[str]:+ return (GOLDEN / name).read_text(encoding="utf-8").splitlines()+++def test_distill_marker_matches_the_golden_line() -> None:+ (golden,) = _golden_lines("distill-marker.txt")+ assert render_marker("21ece412acd8", 64, 2337) == golden+ (parsed,) = parse_markers(golden)+ assert (parsed.ref, parsed.lines_omitted, parsed.tokens_omitted) == ("21ece412acd8", 64, 2337)+++def _decision(spec: dict) -> list:+ rows: list = [+ DecisionRecord(+ id=spec["id"],+ repository_id=_REPO_ID,+ title=spec["title"],+ decision=spec["decision"],+ rationale=spec.get("rationale", ""),+ status=spec["status"],+ source=spec["source"],+ scope_basis="",+ confidence=0.9,+ staleness_score=0.0,+ evidence_file=spec["id"],+ ),+ DecisionNodeLink(+ repository_id=_REPO_ID, decision_id=spec["id"], node_id=spec["file"], link_type="file"+ ),+ ]+ if spec.get("accepted"):+ rows.append(+ DecisionAcceptance(+ repository_id=_REPO_ID,+ decision_id=spec["id"],+ seq=1,+ action="accepted",+ currency="active",+ reason=spec["title"],+ scope_json=json.dumps([spec["id"]]),+ evidence_json=json.dumps([spec["id"]]),+ accepter="tester",+ )+ )+ rows += [+ DecisionEvidence(+ decision_id=spec["id"], source="session", evidence_commit=s, source_quote="q"+ )+ for s in spec.get("sessions", [])+ ]+ return rows+++async def _build_wiki_db(repo_root: Path) -> None:+ db_path = repo_root / ".repowise" / "wiki.db"+ db_path.parent.mkdir(parents=True, exist_ok=True)+ engine = create_async_engine(f"sqlite+aiosqlite:///{db_path.as_posix()}")+ await init_db(engine)+ factory = async_sessionmaker(engine, expire_on_commit=False)+ last_fix = datetime.now(UTC).replace(tzinfo=None) - timedelta(days=14)+ async with factory() as session:+ session.add(Repository(id=_REPO_ID, name="repo", local_path=str(repo_root)))+ for row in _decision(+ {+ "id": "d-standing",+ "title": "Use JWT auth",+ "decision": "All service auth uses short-lived JWT tokens",+ "rationale": "session cookies broke the mobile clients",+ "status": "active",+ "source": "cli",+ "accepted": True,+ "file": "src/core/auth.py",+ "sessions": ["sess-a", "sess-b"],+ }+ ) + _decision(+ {+ "id": "d-mined",+ "title": "Keep the parser allocation-free",+ "decision": "reuse the buffer",+ "status": "proposed",+ "source": "comment",+ "file": "src/core/parser.py",+ }+ ):+ session.add(row)+ session.add(+ GitMetadata(+ id="gm1",+ repository_id=_REPO_ID,+ file_path="src/core/pipeline.py",+ prior_defect_count=5,+ bug_magnet=True,+ last_fix_at=last_fix,+ fix_symbol_counts_json=json.dumps({"src/core/pipeline.py::run_pipeline": 4}),+ )+ )+ await session.commit()+ await engine.dispose()+++async def test_augment_edit_notices_match_the_golden_lines(tmp_path) -> None:+ await _build_wiki_db(tmp_path)+ standing, mined, fixes = _golden_lines("augment-edit-notices.txt")++ # No session id: the formatters run without claiming the session ledger.+ assert decision_inject._edit_decision_notice(tmp_path, "src/core/auth.py", "", {}) == standing+ assert decision_inject._edit_decision_notice(tmp_path, "src/core/parser.py", "", {}) == mined+ assert decision_inject._edit_fix_history_notice(tmp_path, "src/core/pipeline.py", "") == fixes