diff --git a/plugins/altimate-code/CHANGELOG.md b/plugins/altimate-code/CHANGELOG.md index 549a4da7..c8480d8f 100644 --- a/plugins/altimate-code/CHANGELOG.md +++ b/plugins/altimate-code/CHANGELOG.md @@ -11,6 +11,7 @@ All notable changes to this plugin will be documented in this file. - `info_toasts` (on by default): off, the dbt helpers raise no toast for what the transcript or the band already shows (model context added for Claude, a model compiled and validated, the dbt doctor passing); failures still toast. ### Fixed +- The lineage pane reloads by itself, at the next tool call, after a `dbt compile`, `run`, `build` or `parse` rewrites the manifest it shows, so the out-of-date warning clears without pressing r (it stays while the model's files are still newer than the manifest). A manifest that cannot be read (dbt still writing it) or no longer has the model leaves the pane as it was and says so; each rewrite is tried once (again at the next tool call only if another lookup took the pane first, or when the file changes again after a failed read), and r reads it at once. A reload never sends the model's table to a connected warehouse server; only `/lineage` or a press does. - A model Claude edits with a shell command (`sed -i`, a script, a redirect) is now compiled and validated like one edited with Edit or Write: the "Compile & validate" check shows above the prompt as an edit's does, and Claude gets its result with its next tool result (up to three models a command). A command that also runs `dbt run`, `build`, `compile` or `show` is left to that run, and a subagent's shell command is left out, as its lineage notes are. - After `/clear`, the new conversation loads the team comments again (the band, and the threads Claude gets when it reads a commented model) instead of waiting for `/comments` or the next poll, and project health keeps its baseline, the changes not yet checked and the issues found (`/health` no longer says the session has no project; a check the `/clear` cut short runs again). The status line keeps the integrations and altimate-code parts; health draws its own again. - The dbt runs the plugin starts by itself (compile and validate's `dbt show` and `dbt ls`, `/dbt-show` and Re-run, and the project health check's parse) write their artifacts to `target/.altimate-plugin/` instead of `target/`, so they no longer replace the project's `manifest.json` (with every model's compiled SQL) or `run_results.json`. The health check runs its CLI call in its own process for that, with the project's `catalog.json` copied beside its manifest. The doctor's **Run dbt parse** still refreshes the project's own manifest. diff --git a/plugins/altimate-code/README.md b/plugins/altimate-code/README.md index 3454ce6e..484ee84e 100644 --- a/plugins/altimate-code/README.md +++ b/plugins/altimate-code/README.md @@ -115,7 +115,7 @@ The plugin's lineage pane follows the dbt model Claude reads or edits (by Read, - **Warehouse lineage.** When a connected MCP server offers Altimate's `table_lineage` (Snowflake) or `databricks_table_lineage`, the pane adds what the warehouse's query history shows for the model's table. The plugin calls a tool of that name on whichever connected server offers it, itself and without a permission prompt, and sends it the model's `database.schema.table`. It does so only when you ask for the model (`/lineage`, a press in the pane, or `r`), never when the pane follows one of Claude's reads. - **Claude's own lineage calls.** A `dbt_lineage` result is drawn as a list of edges colored by how each column is derived; ctrl+o keeps the original output under it. -`/lineage [.column]` opens the pane on a model, at any width. When the pane follows Claude's reads on its own, Claude Code draws it only in a terminal at least 144 columns wide (110 once you have opened it yourself); in a narrower one it waits, and a toast and a line above the prompt say so until the pane can open. The remedy: make the text smaller (Cmd -) or type `/lineage`. The pane's line `N tests` counts the tests on the model and on the models downstream of it; with a column selected it counts only the tests on that column of the model (`3 tests on amount`), when the graph says which column each test checks (a manifest over 4 MiB, read through altimate-code, keeps the first count). Lineage calls go to the plugin's MCP server without a permission prompt, or to `altimate tool run` when the server is not available. A manifest over 4 MiB is read through altimate-code (`dbt_lineage` with `include_graph`). Run `dbt parse` or `dbt compile` first; column lineage and reach need compiled SQL. When the shown model's `.sql` file changed after the manifest was written, the pane and the edit note say so: run `dbt compile`, then `r`. +`/lineage [.column]` opens the pane on a model, at any width. When the pane follows Claude's reads on its own, Claude Code draws it only in a terminal at least 144 columns wide (110 once you have opened it yourself); in a narrower one it waits, and a toast and a line above the prompt say so until the pane can open. The remedy: make the text smaller (Cmd -) or type `/lineage`. The pane's line `N tests` counts the tests on the model and on the models downstream of it; with a column selected it counts only the tests on that column of the model (`3 tests on amount`), when the graph says which column each test checks (a manifest over 4 MiB, read through altimate-code, keeps the first count). Lineage calls go to the plugin's MCP server without a permission prompt, or to `altimate tool run` when the server is not available. A manifest over 4 MiB is read through altimate-code (`dbt_lineage` with `include_graph`). Run `dbt parse` or `dbt compile` first; column lineage and reach need compiled SQL. When the shown model's `.sql` file changed after the manifest was written, the pane and the edit note say so: run `dbt compile`, then `r`. Once a dbt command has rewritten the manifest the pane shows, the next tool call reloads the pane by itself and the warning clears, unless the model's files are still newer than that manifest; a manifest that cannot be read yet, or no longer has the model, leaves the pane as it was and says so, and `r` reads it at once. ### Team rules diff --git a/plugins/altimate-code/hooks/lineage.test.tsx b/plugins/altimate-code/hooks/lineage.test.tsx index 7ba77362..d012e904 100644 --- a/plugins/altimate-code/hooks/lineage.test.tsx +++ b/plugins/altimate-code/hooks/lineage.test.tsx @@ -62,7 +62,7 @@ const REACH = { }, } -type Options = { duringTool?: () => Promise; fileText?: (path: string) => string | undefined; shell?: (argv: readonly string[]) => { exitCode: number; stdout: string } | undefined; mcp?: boolean; warehouse?: boolean; structured?: boolean; size?: number; mtime?: () => number; reach?: Record; capped?: boolean; lineageText?: string; toolResult?: (e: { tool: string }) => unknown; failColumn?: string; holdFirstManifestRead?: Promise; holdReach?: { column: string; until: Promise }; modelLineage?: Record; cliTooLarge?: boolean; cliCutOff?: (tool?: string) => boolean; cliCutOffExit?: number; cliStdout?: string; cliFailure?: boolean; sqlFiles?: Record; holdFirstSqlRead?: Promise; holdManifestStat?: { at: number; until: Promise }; noRootProject?: boolean; mcpHang?: string; narrow?: string; fileMtime?: (path: string) => number | undefined; manifest?: unknown; cliLineage?: Record; persisted?: { readable: boolean }; holdCliLineage?: Promise; cliGraph?: (graph: any) => any; packageRepo?: boolean; runnerManifestGone?: () => boolean; cliId?: (model: string) => string; cliModels?: string[]; present?: string[]; listed?: string[]; missing?: (path: string) => boolean; holdRead?: (path: string) => Promise | undefined } +type Options = { duringTool?: () => Promise; fileText?: (path: string) => string | undefined; shell?: (argv: readonly string[]) => { exitCode: number; stdout: string } | undefined; mcp?: boolean; warehouse?: boolean; structured?: boolean; size?: number; mtime?: () => number; reach?: Record; capped?: boolean; lineageText?: string; toolResult?: (e: { tool: string }) => unknown; failColumn?: string; holdFirstManifestRead?: Promise; holdReach?: { column: string; until: Promise }; modelLineage?: Record; cliTooLarge?: boolean; cliCutOff?: (tool?: string) => boolean; cliCutOffExit?: number; cliStdout?: string; cliFailure?: boolean; sqlFiles?: Record; holdFirstSqlRead?: Promise; holdManifestStat?: { at: number; until: Promise }; noRootProject?: boolean; mcpHang?: string; narrow?: string; fileMtime?: (path: string) => number | undefined; manifest?: unknown; cliLineage?: Record; persisted?: { readable: boolean }; holdCliLineage?: Promise; cliGraph?: (graph: any) => any; packageRepo?: boolean; runnerManifestGone?: () => boolean; cliId?: (model: string) => string; cliModels?: string[]; present?: string[]; listed?: string[]; missing?: (path: string) => boolean; holdRead?: (path: string) => Promise | undefined; holdExists?: (path: string) => Promise | undefined } /** * A dbt project at /repo, the plugin's MCP server (or the CLI when it is not connected), and the @@ -118,9 +118,12 @@ async function start($: any, on: any, options: Options = {}) { const RUNNER = `${ROOT}/integration_tests` const runnerFiles: Record = options.packageRepo ? { [`${RUNNER}/dbt_project.yml`]: "name: 'shop_tests'\n", [`${RUNNER}/packages.yml`]: 'packages:\n - local: ../\n' } : {} const MANIFEST_AT = options.packageRepo ? `${RUNNER}/target/manifest.json` : MANIFEST_PATH - on('fs.exists', (_: unknown, e: { path: string }) => ({ + on('fs.exists', async (_: unknown, e: { path: string }) => { + await options.holdExists?.(e.path) + return { value: (e.path === `${ROOT}/dbt_project.yml` && !options.noRootProject) || (hasManifest && e.path === MANIFEST_AT && !options.runnerManifestGone?.()) || e.path in runnerFiles || !!options.present?.includes(e.path) || (!!sql && e.path.slice(ROOT.length + 1) in sql), - })) + } + }) on('fs.stat', async (_: unknown, e: { path: string }) => { if (e.path === MANIFEST_PATH && options.holdManifestStat && ++manifestStats === options.holdManifestStat.at) await options.holdManifestStat.until if (!hasManifest && e.path.endsWith('/target/manifest.json')) throw new Error('ENOENT') @@ -257,7 +260,7 @@ async function start($: any, on: any, options: Options = {}) { }) await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) await clock.settle() - return { clock, calls, toasts, notes, logs, debug, lists, opens, kept } + return { clock, calls, toasts, notes, logs, debug, lists, opens, kept, stats: () => manifestStats } } test('the lineage pane keeps its default size and Min / Default / Max resize it', async ($, on) => { @@ -1026,6 +1029,367 @@ test('a model whose SQL changed after the manifest was written says so; r keeps await ui.unmount() }) +// fct_orders after Claude swapped its ref('int_orders') for a hardcoded table, compiled. +const RECOMPILED = { + ...MANIFEST, + nodes: { + ...MANIFEST.nodes, + 'model.shop.fct_orders': { ...MANIFEST.nodes['model.shop.fct_orders'], depends_on: { nodes: ['model.shop.stg_customers'] } }, + }, +} +const STALE_WARNING = /⚠ fct_orders\.sql changed after the manifest was written: run `dbt compile`, then press r$/ +const MANIFEST_LOADS = (logs: string[]) => logs.filter(line => line.startsWith('lineage-pane · target/manifest.json · ')) + +test('a dbt compile that rewrites the manifest reloads the pane by itself and clears the out-of-date warning', async ($, on) => { + let manifestMtime = 1 + let compiled = false + const { clock, logs } = await start($, on, { + mtime: () => manifestMtime, + fileMtime: path => (path === FILE ? 5 : undefined), + fileText: path => (path === MANIFEST_PATH && compiled ? JSON.stringify(RECOMPILED) : undefined), + }) + await $.tool.call({ tool: 'Read', file_path: FILE }) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await ui.press({ key: 'lineage-view' }) + await clock.settle() + expect(await ui.find({ type: 'Text', text: STALE_WARNING })).toBeDefined() + expect(await ui.find({ type: 'Button', text: /int_orders/ })).toBeDefined() + expect(MANIFEST_LOADS(logs)).toHaveLength(1) + // Claude's `dbt compile` rewrites the manifest. + compiled = true + manifestMtime = 10 + await $.tool.call({ tool: 'Bash', command: 'dbt compile' } as any) + await clock.settle() + expect(await ui.find({ type: 'Text', text: STALE_WARNING })).toBeUndefined() + expect(await ui.find({ type: 'Button', text: /int_orders/ })).toBeUndefined() + expect(MANIFEST_LOADS(logs)).toHaveLength(2) + await ui.unmount() +}) + +test('a tool call that leaves the manifest as it was keeps the out-of-date warning and reloads nothing', async ($, on) => { + const { clock, logs } = await start($, on, { fileMtime: path => (path === FILE ? 5 : undefined) }) + await $.tool.call({ tool: 'Read', file_path: FILE }) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await $.tool.call({ tool: 'Bash', command: 'dbt compile' } as any) + await clock.settle() + expect(await ui.find({ type: 'Text', text: STALE_WARNING })).toBeDefined() + expect(MANIFEST_LOADS(logs)).toHaveLength(1) + await ui.unmount() +}) + +test('a rewritten manifest opens no pane when none was ever shown', async ($, on) => { + let manifestMtime = 1 + const { clock, opens, logs } = await start($, on, { mtime: () => manifestMtime }) + manifestMtime = 10 + await $.tool.call({ tool: 'Bash', command: 'dbt compile' } as any) + await clock.settle() + expect(opens).toEqual([]) + expect(MANIFEST_LOADS(logs)).toEqual([]) +}) + +test('a manifest is reloaded once: the next tool call with the same modified time does not read it again', async ($, on) => { + let manifestMtime = 1 + const { clock, logs } = await start($, on, { mtime: () => manifestMtime }) + await $.tool.call({ tool: 'Read', file_path: FILE }) + await clock.settle() + manifestMtime = 10 + await $.tool.call({ tool: 'Bash', command: 'dbt compile' } as any) + await clock.settle() + expect(MANIFEST_LOADS(logs)).toHaveLength(2) + await $.tool.call({ tool: 'Bash', command: 'ls' } as any) + await clock.settle() + await $.tool.call({ tool: 'Bash', command: 'ls' } as any) + await clock.settle() + expect(MANIFEST_LOADS(logs)).toHaveLength(2) +}) + +test('a reload that cannot read the new manifest keeps the graph shown and says so; the file written again is read again', async ($, on) => { + let manifestMtime = 1 + let written = false + const { clock, logs } = await start($, on, { + mtime: () => manifestMtime, + fileMtime: path => (path === FILE ? 5 : undefined), + // dbt is still writing it: half a file. + fileText: path => (path === MANIFEST_PATH && manifestMtime > 1 ? (written ? JSON.stringify(RECOMPILED) : '{"nodes": {"model.shop.fct_or') : undefined), + }) + await $.tool.call({ tool: 'Read', file_path: FILE }) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await ui.press({ key: 'lineage-view' }) + await clock.settle() + manifestMtime = 10 + await $.tool.call({ tool: 'Bash', command: 'dbt compile' } as any) + await clock.settle() + expect(await ui.find({ type: 'Button', text: /int_orders/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /lineage · fct_orders/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: STALE_WARNING })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /Could not read target\/manifest\.json: is dbt still writing it\? Press r to retry\./ })).toBeDefined() + expect(MANIFEST_LOADS(logs)).toHaveLength(1) + // The same file is not read again by every tool call that follows. + written = true + await $.tool.call({ tool: 'Bash', command: 'ls' } as any) + await clock.settle() + expect(MANIFEST_LOADS(logs)).toHaveLength(1) + expect(await ui.find({ type: 'Button', text: /int_orders/ })).toBeDefined() + // dbt finishes writing: the file's time moves on. + manifestMtime = 11 + await $.tool.call({ tool: 'Bash', command: 'ls' } as any) + await clock.settle() + expect(await ui.find({ type: 'Button', text: /int_orders/ })).toBeUndefined() + expect(await ui.find({ type: 'Text', text: STALE_WARNING })).toBeUndefined() + expect(await ui.find({ type: 'Text', text: /Could not read/ })).toBeUndefined() + expect(MANIFEST_LOADS(logs)).toHaveLength(2) + await ui.unmount() +}) + +test('a rewritten manifest without the shown model keeps the graph, says the model is gone, and is not read again by later calls', async ($, on) => { + let manifestMtime = 1 + let dropped = false + const { nodes } = MANIFEST + const { 'model.shop.fct_orders': _gone, ...others } = nodes + let readsAfterRewrite = 0 + const { clock } = await start($, on, { + mtime: () => manifestMtime, + fileText: path => { + if (path !== MANIFEST_PATH || !dropped) return undefined + readsAfterRewrite++ + return JSON.stringify({ ...MANIFEST, nodes: others }) + }, + }) + await $.tool.call({ tool: 'Read', file_path: FILE }) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await ui.press({ key: 'lineage-view' }) + await clock.settle() + dropped = true + manifestMtime = 10 + for (const command of ['dbt compile', 'ls', 'ls']) { + await $.tool.call({ tool: 'Bash', command } as any) + await clock.settle() + } + expect(await ui.find({ type: 'Button', text: /int_orders/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /No dbt model matches/ })).toBeDefined() + expect(readsAfterRewrite).toBe(1) + await ui.unmount() +}) + +// A pane showing fct_orders whose manifest dbt then rewrites; `hold` pauses the next read of the manifest until released. +async function rewrittenPane($: any, on: any, extra: Options = {}) { + let manifestMtime = 1 + let hold: Promise | undefined + const run = await start($, on, { + mtime: () => manifestMtime, + fileText: path => (path === MANIFEST_PATH && manifestMtime > 1 ? JSON.stringify(RECOMPILED) : undefined), + holdRead: path => { + if (path !== MANIFEST_PATH || !hold) return undefined + const held = hold + hold = undefined + return held + }, + ...extra, + }) + await $.tool.call({ tool: 'Read', file_path: FILE }) + await run.clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await ui.press({ key: 'lineage-view' }) + await run.clock.settle() + const rewrite = (mtime: number) => (manifestMtime = mtime) + let releaseHeld = () => {} + const holdNextRead = () => { + hold = new Promise(resolve => (releaseHeld = resolve)) + } + return { ...run, ui, rewrite, holdNextRead, release: () => releaseHeld(), setMtime: rewrite } +} + +test('a reload that finds a follow in flight yields: the follow lands, the manifest is not reloaded over it', async ($, on) => { + const OTHER = `${ROOT}/models/stg_customers.sql` + const gate = { at: Infinity, until: new Promise(() => {}) } + let release!: () => void + gate.until = new Promise(resolve => (release = resolve)) + const { clock, ui, rewrite, logs, stats } = await rewrittenPane($, on, { present: [OTHER], holdManifestStat: gate }) + // Claude's read of stg_customers is still looking at the manifest when dbt rewrites it and the next tool call checks. + gate.at = stats() + 2 + await $.tool.call({ tool: 'Read', file_path: OTHER }) + await clock.settle() + rewrite(10) + await $.tool.call({ tool: 'Bash', command: 'ls' } as any) + await clock.settle() + release() + await clock.advance(200) + await clock.settle() + expect(await ui.find({ type: 'Text', text: /lineage · stg_customers/ })).toBeDefined() + expect(await ui.find({ type: 'Text', text: /lineage · fct_orders/ })).toBeUndefined() + // The first read, and the follow's: no reload beside them. + expect(MANIFEST_LOADS(logs)).toHaveLength(2) + await ui.unmount() +}) + +test("a reload that finds the answer's own follow in flight yields: the answer's model lands", async ($, on) => { + const gate = { at: Infinity, until: new Promise(() => {}) } + let release!: () => void + gate.until = new Promise(resolve => (release = resolve)) + const { clock, ui, rewrite, stats } = await rewrittenPane($, on, { holdManifestStat: gate }) + await $.turn.start({ text: 'q', turnId: 't21' } as any) + gate.at = stats() + 2 + await $.turn.complete({ answer: 'See `int_orders`.', durationMs: 5, isAborted: false, reason: 'answer', turnId: 't21' } as any) + await clock.advance(1000) + rewrite(10) + await $.tool.call({ tool: 'Bash', command: 'ls' } as any) + await clock.settle() + release() + await clock.advance(200) + await clock.settle() + expect(await ui.find({ type: 'Text', text: /lineage · int_orders/ })).toBeDefined() + await ui.unmount() +}) + +test('a reload overtaken by a follow that lands nothing is dropped, and the next call reloads again', async ($, on) => { + const GHOST = `${ROOT}/models/ghost.sql` + const { clock, ui, rewrite, holdNextRead, release, logs } = await rewrittenPane($, on, { present: [GHOST] }) + rewrite(10) + holdNextRead() + // The reload is reading the rewritten manifest. + await $.tool.call({ tool: 'Bash', command: 'dbt compile' } as any) + await clock.settle() + // A follow starts meanwhile and finds no model for that file. + await $.tool.call({ tool: 'Read', file_path: GHOST }) + await clock.settle() + release() + await clock.advance(200) + await clock.settle() + expect(await ui.find({ type: 'Button', text: /int_orders/ })).toBeDefined() + expect(MANIFEST_LOADS(logs)).toHaveLength(1) + await $.tool.call({ tool: 'Bash', command: 'ls' } as any) + await clock.settle() + expect(await ui.find({ type: 'Button', text: /int_orders/ })).toBeUndefined() + expect(MANIFEST_LOADS(logs)).toHaveLength(2) + await ui.unmount() +}) + +test('a /clear while a reload is still reading does not stop the next conversation\'s reloads', async ($, on) => { + const { clock, ui, rewrite, holdNextRead, logs } = await rewrittenPane($, on) + rewrite(10) + // The reload never gets its read back. + holdNextRead() + await $.tool.call({ tool: 'Bash', command: 'dbt compile' } as any) + await clock.settle() + await $.session.end({ reason: 'clear' } as any) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + await clock.settle() + const before = MANIFEST_LOADS(logs).length + // The new conversation follows the model again, then dbt rewrites the manifest once more. + await $.tool.call({ tool: 'Read', file_path: FILE }) + await clock.settle() + rewrite(20) + await $.tool.call({ tool: 'Bash', command: 'dbt compile' } as any) + await clock.settle() + // The new conversation's own read, and the reload after the second rewrite. + expect(MANIFEST_LOADS(logs)).toHaveLength(before + 2) + await ui.unmount() +}) + +test('a pane that was shown and closed is not opened again by a rewritten manifest', async ($, on) => { + let manifestMtime = 1 + const { clock, opens, logs } = await start($, on, { mtime: () => manifestMtime }) + await $.tool.call({ tool: 'Read', file_path: FILE }) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await ui.press({ key: 'lineage-view' }) + await clock.settle() + await ui.unmount() + const opened = opens.length + manifestMtime = 10 + await $.tool.call({ tool: 'Bash', command: 'dbt compile' } as any) + await clock.settle() + expect(MANIFEST_LOADS(logs)).toHaveLength(2) + expect(opens).toHaveLength(opened) +}) + +test('a manifest that is gone when the reload reads it leaves the graph shown, says it is gone, and draws no SQL files over it', async ($, on) => { + let manifestMtime = 1 + let gone = false + let stats = 0 + const { clock, logs } = await start($, on, { + mtime: () => manifestMtime, + // The check that the manifest changed sees it; the reload's own read of it finds it removed. + missing: path => path === MANIFEST_PATH && gone && ++stats > 1, + }) + await $.tool.call({ tool: 'Read', file_path: FILE }) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await ui.press({ key: 'lineage-view' }) + await clock.settle() + gone = true + manifestMtime = 10 + await $.tool.call({ tool: 'Bash', command: 'dbt clean' } as any) + await clock.settle() + expect(await ui.find({ type: 'Button', text: /int_orders/ })).toBeDefined() + expect(logs.filter(line => line.includes('from the SQL files'))).toEqual([]) + expect(await ui.find({ type: 'Text', text: /No dbt model matches/ })).toBeUndefined() + expect(await ui.find({ type: 'Text', text: /No dbt manifest at that path/ })).toBeDefined() + expect(MANIFEST_LOADS(logs)).toHaveLength(1) + await ui.unmount() +}) + +test("a shell command that rewrites the manifest and reads another model's file still moves the pane to that model", async ($, on) => { + const OTHER = `${ROOT}/models/stg_customers.sql` + let armed = false + let releaseFile!: () => void + const fileHeld = new Promise(resolve => (releaseFile = resolve)) + let releaseReload!: () => void + const gate = { at: Infinity, until: new Promise(resolve => (releaseReload = resolve)) } + const { clock, ui, rewrite, stats } = await rewrittenPane($, on, { + present: [OTHER], + holdManifestStat: gate, + // The command's own follow waits to find its file while the same call's manifest check, started late, begins its reload. + holdExists: path => { + if (!armed || path !== OTHER) return undefined + armed = false + return fileHeld + }, + }) + rewrite(10) + armed = true + gate.at = stats() + 1 + await $.tool.call({ tool: 'Bash', command: `dbt compile --select ${OTHER}` } as any) + await clock.settle() + releaseReload() + await clock.settle() + releaseFile() + await clock.advance(200) + await clock.settle() + expect(await ui.find({ type: 'Text', text: /lineage · stg_customers/ })).toBeDefined() + await ui.unmount() +}) + +test("a rewritten manifest does not send the model's table to the warehouse server: the reload is no ask", async ($, on) => { + let manifestMtime = 1 + const { clock, calls, logs } = await start($, on, { warehouse: true, mtime: () => manifestMtime }) + await $.tool.call({ tool: 'Read', file_path: FILE }) + await clock.settle() + manifestMtime = 10 + await $.tool.call({ tool: 'Bash', command: 'dbt compile' } as any) + await clock.settle() + expect(calls).not.toContain('mcp:table_lineage') + // The manifest was reloaded, and still nothing was sent. + expect(MANIFEST_LOADS(logs)).toHaveLength(2) +}) + +test("a rewritten manifest does not re-send the table of a model the person asked for", async ($, on) => { + let manifestMtime = 1 + const { clock, calls, logs } = await start($, on, { warehouse: true, mtime: () => manifestMtime }) + await $.command.run({ command: 'lineage', args: 'fct_orders' } as any) + await clock.settle() + expect(calls.filter(one => one === 'mcp:table_lineage')).toEqual(['mcp:table_lineage']) + manifestMtime = 10 + await $.tool.call({ tool: 'Bash', command: 'dbt compile' } as any) + await clock.settle() + expect(MANIFEST_LOADS(logs)).toHaveLength(2) + expect(calls.filter(one => one === 'mcp:table_lineage')).toEqual(['mcp:table_lineage']) +}) + test('a shell command that changes the shown model\'s file brings the warning up, and the edit note says the manifest is older', async ($, on) => { let fileMtime = 1 const { clock, notes } = await start($, on, { fileMtime: path => (path === FILE ? fileMtime : undefined) }) @@ -1897,8 +2261,8 @@ test("the person's press still loading when the answer ends wins over the answer test("a newer turn arriving while the answer's own model lookup runs keeps the answer out", async ($, on) => { let release!: () => void - // Stats 1-2 are the read's own follow; stat 3 is the answer's model lookup, held until the next turn has started. - const { clock } = await start($, on, { holdManifestStat: { at: 3, until: new Promise(resolve => (release = resolve)) } }) + // Stats 1-3 are the read's own follow and the check that it did not rewrite the manifest; stat 4 is the answer's model lookup, held until the next turn has started. + const { clock } = await start($, on, { holdManifestStat: { at: 4, until: new Promise(resolve => (release = resolve)) } }) await $.tool.call({ tool: 'Read', file_path: FILE }) await clock.settle() await $.turn.start({ text: 'q', turnId: 't11' } as any) diff --git a/plugins/altimate-code/hooks/lineage.tsx b/plugins/altimate-code/hooks/lineage.tsx index c3192c84..bd1f1bb7 100644 --- a/plugins/altimate-code/hooks/lineage.tsx +++ b/plugins/altimate-code/hooks/lineage.tsx @@ -108,6 +108,13 @@ let showEditImpact = false // pane unless a newer one already has. A follow that fails claims nothing, so it cancels nobody. let startedSeq = 0 let claimedSeq = 0 +// How many of those numbers went to reloads: a shell command's own reads count the ones that are not. +let reloadsStarted = 0 +const readsStarted = () => startedSeq - reloadsStarted +// The manifest revision a reload last tried, whether it landed or not: each is tried once, the next one when dbt writes the file again. +let reloadAttempted: string | null = null +// The conversation a reload is reading in: another is not started beside it, and one that lands checks for a newer rewrite itself. +let reloadSession: number | null = null // The focus that owns the pane (model, manifest, revision), set when a follow claims it. Detail // answers are written only while it is still the focus they were asked for; a re-follow of the same // model keeps it, so its in-flight answers still land. @@ -120,13 +127,17 @@ const contextGiven = new Set() let turnCount = 0 let followedTurn = -1 let followsInFlight = 0 +// The answer's own follows, which `followsInFlight` leaves out. +let answersInFlight = 0 // Bumped when a conversation starts or ends: a follow left from the last one cannot touch the count. let followSession = 0 const newConversation = () => { turnCount++ followedTurn = -1 followsInFlight = 0 + answersInFlight = 0 followSession++ + reloadAttempted = null projectSeen = false forgetProjects() askedFor = null @@ -492,6 +503,8 @@ type FollowInput = { auto?: boolean /** Re-read the manifest (and, unless a large manifest's cached columns stand, the column lineage) even when the model is unchanged. */ refresh?: boolean + /** The manifest changed under the pane: a refresh nobody asked for, so it counts as no ask, opens nothing, and gives way to any other follow that starts meanwhile. */ + reload?: boolean /** `model` may end in `.column`: read so only when the whole text is not itself a model (a unique_id or path has dots). */ dottedColumn?: boolean /** The manifest a tool call named (Claude's own dbt_lineage call): its project is the one to follow. */ @@ -502,7 +515,15 @@ type FollowInput = { async function follow($: EngineInterface, given: FollowInput): Promise { // A file spelled through `..` (a shell read from integration_tests) is the file it names. const input = given.file ? { ...given, file: normalize(given.file) } : given - if (input.fromAnswer !== undefined) return followOnce($, input) + if (input.fromAnswer !== undefined) { + const session = followSession + answersInFlight++ + try { + return await followOnce($, input) + } finally { + if (session === followSession) answersInFlight-- + } + } // Claude's reads and the person's own presses alike: in flight, the answer waits for them; landed, // the answer leaves the pane where they put it. const turn = turnCount @@ -522,9 +543,12 @@ async function followOnce($: EngineInterface, input: FollowInput): Promise { - if (!input.auto || (always && !isPackage)) await update($, messageAtom, () => text) + // A reload that another follow has overtaken leaves that follow's pane and message alone. + if (input.reload && startedSeq !== seq) return + if (!input.auto || (always && !isPackage)) await update($, messageAtom, prev => (input.reload && startedSeq !== seq ? prev : text)) } const seq = ++startedSeq + if (input.reload) reloadsStarted++ const current = await read($, focusAtom) const sessionRoot = await $.session.root().catch(() => '.') const given = input.manifest ? normalize(/^([\\/]|[A-Za-z]:)/.test(input.manifest) ? input.manifest : `${sessionRoot}/${input.manifest}`) : null @@ -567,7 +591,8 @@ async function followOnce($: EngineInterface, input: FollowInput): Promise seq || (input.fromAnswer !== undefined && input.fromAnswer !== turnCount)) return false + // A reload gives way to a follow that started after it: the next tool call looks at the manifest again. + if (input.reload && startedSeq !== seq) { + reloadAttempted = null + return false + } claimedSeq = seq ownerKey = `${id}\u0000${manifest}\u0000${mtimeMs}` // The person's own follows; Claude's reads and the answer's follow are not asks. - if (!input.auto && input.fromAnswer === undefined) askedFor = `${id}\u0000${manifest}` + if (!input.auto && !input.reload && input.fromAnswer === undefined) askedFor = `${id}\u0000${manifest}` + // A reload is no ask: the person's earlier ask does not carry over to the rewritten manifest. + else if (input.reload) askedFor = null // update() may retry its write after a conflict, so each write below re-checks ownership inside // its callback: once a newer follow has claimed the pane, this one leaves the state as it is. const superseded = () => claimedSeq !== seq @@ -825,11 +857,39 @@ async function staleSql($: EngineInterface, root: string, node: GraphNode | unde return null } -/** The shown model's file may have changed since the pane read it (an edit, a shell command): checked again. */ +/** + * A dbt command (Claude's, or the person's in another terminal) rewrote the manifest the pane shows: the pane + * reads it again, as r does, so the lineage and the out-of-date warning follow the compile without a press. + * Each rewrite is tried once, whether the read lands or not (one that gave way to another follow is tried again at the next call); one that failed (dbt still writing the file) + * is tried again when the file changes again, and r reads it at once. + * Whether the pane now shows the new manifest. + */ +async function reloadIfRewritten($: EngineInterface, focus: LineageFocus): Promise { + const stat = await $.fs.stat(focus.manifest).catch(() => null) + if (!stat || stat.mtimeMs <= focus.mtimeMs) return false + const revision = `${focus.model}\u0000${focus.manifest}\u0000${stat.mtimeMs}` + if (reloadAttempted === revision) return false + // Checked after the last await before the follow numbers itself, so no other follow slips in between: + // the focus is still the one shown and nothing is moving the pane to another model. + if (!sameFocus(await read($, focusAtom), focus) || followsInFlight > 0 || answersInFlight > 0 || reloadAttempted === revision || reloadSession === followSession) return false + reloadAttempted = revision + const session = followSession + reloadSession = session + try { + return await followOnce($, { model: focus.model, refresh: true, reload: true }) + } finally { + if (reloadSession === session) reloadSession = null + } +} + +/** The shown model's file or manifest may have changed since the pane read them (an edit, a dbt command): checked again. */ async function recheckStale($: EngineInterface) { const focus = await read($, focusAtom) const graph = await read($, graphAtom) - if (!focus || !graph || focus.via === 'sql') return + if (!focus || !graph) return + // A reload that lands ends with its own check, against the manifest it read. + if (await reloadIfRewritten($, focus)) return + if (focus.via === 'sql') return const stale = await staleSql($, focus.root, graph.nodes[focus.model], focus.mtimeMs) if (sameFocus(await read($, focusAtom), focus)) await update($, staleAtom, prev => (prev === stale ? prev : stale)) } @@ -1368,7 +1428,7 @@ export function registerLineage(on: On, options: Record = {}) { if (showEditImpact) $.ui.log(note.toast) } const result = await next(e) - // Any tool may have changed the shown model's file (Edit, a shell command): one stat says so. + // Any tool may have changed the shown model's file or rewritten its manifest (Edit, a shell command): a stat of each says so. later($, () => recheckStale($)) // A shell command that failed may still have changed models first (`python3 rewrite.py && dbt test`): looked at too. if (result.deny || (result.isError && !bash)) return result @@ -1440,7 +1500,7 @@ export function registerLineage(on: On, options: Record = {}) { later($, async () => { // A path that exists but is in no project (a redirect target) is skipped for the next one; once // a newer follow (another read) has started, this command's candidates stop. - const start = startedSeq + const start = readsStarted() let own = 0 // A named file of a project that its manifest does not have as the project's own model is not followed by // its name either (that name may be another package's model). @@ -1449,14 +1509,14 @@ export function registerLineage(on: On, options: Record = {}) { if (!(await $.fs.exists(file).catch(() => false))) continue if (await projectRoot($, file, true).catch(() => null)) projectFile = true // A read that started while this check waited owns the pane now. - if (startedSeq - start > own) return + if (readsStarted() - start > own) return own++ if (await follow($, { file, auto: true })) return - if (startedSeq - start > own) return + if (readsStarted() - start > own) return } // Only a name (find -name x.sql): the model of that name in the command's project, unless a // newer follow has started since this command's own ones. - if (startedSeq - start > own || projectFile) return + if (readsStarted() - start > own || projectFile) return await follow($, { model: named[0]!.split('/').pop()!.replace(/\.sql$/i, ''), root: dir, auto: true }) }) }