Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
__pycache__/
.context/
node_modules/
2 changes: 1 addition & 1 deletion plugins/altimate-code/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ Rule drafting uses altimate-code's own model (sign in to the Altimate LLM Gatewa

## Settings

The plugin has five settings, shown when you enable it (`userConfig` in `.claude-plugin/plugin.json`). None is used yet: the features that read them are not in this version, so changing one changes nothing. The table says what each will control.
The plugin has six settings, shown when you enable it (`userConfig` in `.claude-plugin/plugin.json`). `dbt_mods` is used, and so are `healthBlocksPush` and `healthConfigPath`, by the project health check. `maxScanBytes` and the comments settings are not used yet: the features that read them are not in this version, so changing one changes nothing. The table says what each controls or will control.

| Setting | Default | What it controls |
| --- | --- | --- |
Expand Down
34 changes: 34 additions & 0 deletions plugins/altimate-code/hooks/dbt-mods.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// The dbt helpers (compile and validate, Explain and Fix, the Query results pane, model context, the doctor).
//
// features/index.ts calls each function below at its moment, in the same phases and band as the other
// features; one with nothing to do stays a no-op. The helpers themselves are filled in by their own change.
import type { Args, EngineInterface, On, PluginOptions, RenderElement, ToolCallResult } from 'claude-code'

/** How long the edit phase may hold an edit's result for a slow check, in milliseconds. */
export const CHECK_HOLD_MS = 30_000

export async function dbtModsCallStart($: EngineInterface, e: { tool: string; agentId?: string }): Promise<void> {}

export async function dbtModsBashAfter($: EngineInterface, e: { tool: string; command: string; agentId?: string }, result: ToolCallResult): Promise<string[]> {
return []
}

export async function dbtModsEditAfter($: EngineInterface, e: { tool: string; agentId?: string }, result: ToolCallResult, file: { path: string }): Promise<string[]> {
return []
}

export async function dbtModsReadOrEditAfter($: EngineInterface, e: { tool: string; agentId?: string }, result: ToolCallResult, file: { path: string }): Promise<string[]> {
return []
}

export async function endDbtMods($: EngineInterface) {}

export function newTurnDbtMods(e: { agentId?: string }) {}

export async function sessionStartDbtMods($: EngineInterface, e: Args<'session.start'>) {}

export async function bandDbtMods($: EngineInterface, ui: { Box: any; Button: any; Text: any }): Promise<RenderElement | null> {
return null
}

export function registerDbtMods(on: On, context: { options: PluginOptions }) {}
11 changes: 9 additions & 2 deletions plugins/altimate-code/hooks/features/docs.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { expect, mock, test } from 'claude-code/testing'
import { expect, mock, test as kitTest } from 'claude-code/testing'

// These tests are about the docs feature: the dbt helpers, which run the project's own dbt, are off here
// and tested in dbt-mods.test.tsx.
const test = (name: string, body: Parameters<typeof kitTest>[1]) => kitTest(name, { options: { dbt_mods: false } }, body as any)

import { PHASE_TIMEOUT_MS } from '../tool-chain'
import { ROUND_MS, applyPrompt, candidatesFrom, changedDescriptions, columnDescriptions, modelPaths, sentGroups } from './docs'
import { nothingToReport } from '../inert-features'

const ROOT = '/repo'
const MANIFEST_PATH = `${ROOT}/target/manifest.json`
Expand Down Expand Up @@ -256,7 +261,9 @@ async function start($: any, on: any, options: Options = {}) {
})
on('process.run', (_: unknown, e: { argv: readonly string[] }) => {
const [, command, , tool] = e.argv
if (command !== 'tool') return { value: { exitCode: 1, stdout: '', stderr: 'not this test' } }
if (command !== 'tool' || tool === 'docs_share_comments') return { value: { exitCode: 1, stdout: '', stderr: 'not this test' } }
// The project health check asks for its own tool at session start: not a call this feature makes.
if (tool === 'dbt_health') return { value: nothingToReport(e.argv)! }
calls.push(`cli:${tool}`)
toolArgs.push(String(e.argv[5]))
if (tool === 'dbt_docs_coverage') {
Expand Down
19 changes: 17 additions & 2 deletions plugins/altimate-code/hooks/features/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { expect, test } from 'claude-code/testing'

import { nothingToReport } from '../inert-features'
import {
registerFeatures,
attempt,
featureBandLines,
featuresBashAfter,
Expand Down Expand Up @@ -86,8 +87,22 @@ test('each phase runs through the features, which find nothing to report and log
expect(await featuresBashRewrite($, bash)).toBe('dbt run -s a')
expect(await featuresBashGate($, bash)).toBeNull()
// A dbt command may get a note from a feature that watches dbt (what a run would scan); a call no feature watches gets none.
expect(await featuresBashAfter($, { tool: 'Bash', command: 'ls models' } as any, {} as any)).toEqual([])
expect(await featuresBashAfter($, { tool: 'Bash', command: 'ls models', tool_use_id: 'ls' } as any, {} as any)).toEqual([])
expect(await featuresEditAfter($, file, {} as any, { path: '/repo/models/a.sql', before: null })).toEqual([])
expect(await featuresReadOrEditAfter($, file, {} as any, { path: '/repo/models/a.sql' })).toEqual([])
expect(logs).toEqual([])
// The runs feature is real here and needs a fuller engine than this stub; every other feature must log nothing.
expect(logs.filter(line => !line.startsWith('runs · '))).toEqual([])
})

test('a feature whose register throws never reaches the caller, so the tool hook after the features still installs', () => {
let calls = 0
const on = new Proxy(() => {}, {
get: () => on,
apply: () => {
calls++
throw new Error('refused matcher')
},
}) as any
expect(() => registerFeatures(on, { options: {} } as any)).not.toThrow()
expect(calls).toBeGreaterThan(0)
})
50 changes: 47 additions & 3 deletions plugins/altimate-code/hooks/features/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,27 @@
// The dbt Power User features, each in its own file here, and the one place that calls them, in a
// fixed order: runs, defer, toModel, comments, cost, health, sqlGraph, docs, cteProfile.
// fixed order: runs, defer, toModel, comments, cost, health, sqlGraph, docs, cteProfile. The dbt helpers
// (hooks/dbt-mods.tsx: compile and validate, Explain and Fix, the Query results pane, model context, the
// doctor) are called last, in the same phases and band; they have no status-line part.
//
// A plugin hooks each shared event once (a second hook on an event without a matcher is refused), and
// the engine refuses `$` handed to anything but a function it can name, so this file calls every
// feature's functions by name instead of looping over a list. A feature fills in its own file only.
// A function that throws, at once or as a rejection, is logged and skipped: one feature's failure never stops another or the call.
import type { Args, EngineInterface, EventResult, On, PluginOptions, RenderElement, ToolCallResult } from 'claude-code'
// A function that throws, at once or as a rejection, is logged and skipped: one feature's failure never stops another or the call. A `register` failure is silent (`$` is not available at load).
import type { Args, EngineInterface, EventResult, On, PluginOptions, RenderElement, ToolCallInput, ToolCallResult } from 'claude-code'

import type { BashCall, EditedFile, FileCall } from '../tool-chain'
import {
CHECK_HOLD_MS as dbtModsCheckHoldMs,
bandDbtMods,
dbtModsBashAfter,
dbtModsCallStart,
dbtModsEditAfter,
dbtModsReadOrEditAfter,
endDbtMods,
newTurnDbtMods,
registerDbtMods,
sessionStartDbtMods,
} from '../dbt-mods'
import {
register as runsRegister,
sessionStart as runsSessionStart,
Expand All @@ -18,6 +32,7 @@ import {
bashRewrite as runsBashRewrite,
bashGate as runsBashGate,
bashAfter as runsBashAfter,
bashDropped as runsBashDropped,
editAfter as runsEditAfter,
readOrEditAfter as runsReadOrEditAfter,
editReadsBefore as runsEditReadsBefore,
Expand Down Expand Up @@ -195,6 +210,9 @@ export function registerFeatures(on: On, context: FeatureContext) {
try {
cteProfileRegister(on, context)
} catch {}
try {
registerDbtMods(on, context)
} catch {}
}

export async function featuresSessionStart($: EngineInterface, e: Args<'session.start'>) {
Expand All @@ -207,6 +225,7 @@ export async function featuresSessionStart($: EngineInterface, e: Args<'session.
await attempt($, 'sqlGraph', 'sessionStart', () => sqlGraphSessionStart($, e))
await attempt($, 'docs', 'sessionStart', () => docsSessionStart($, e))
await attempt($, 'cteProfile', 'sessionStart', () => cteProfileSessionStart($, e))
await attempt($, 'dbtMods', 'sessionStart', () => sessionStartDbtMods($, e))
}

export async function featuresTurnStart($: EngineInterface, e: Args<'turn.start'>) {
Expand All @@ -219,6 +238,7 @@ export async function featuresTurnStart($: EngineInterface, e: Args<'turn.start'
await attempt($, 'sqlGraph', 'turnStart', () => sqlGraphTurnStart($, e))
await attempt($, 'docs', 'turnStart', () => docsTurnStart($, e))
await attempt($, 'cteProfile', 'turnStart', () => cteProfileTurnStart($, e))
await attempt($, 'dbtMods', 'turnStart', () => newTurnDbtMods(e))
}

export async function featuresTurnComplete($: EngineInterface, e: Args<'turn.complete'>, out: EventResult<'turn.complete'>) {
Expand All @@ -243,6 +263,7 @@ export async function featuresSessionEnd($: EngineInterface, e: Args<'session.en
await attempt($, 'sqlGraph', 'sessionEnd', () => sqlGraphSessionEnd($, e))
await attempt($, 'docs', 'sessionEnd', () => docsSessionEnd($, e))
await attempt($, 'cteProfile', 'sessionEnd', () => cteProfileSessionEnd($, e))
await attempt($, 'dbtMods', 'sessionEnd', () => endDbtMods($))
}

/** Each feature's band line, in order, with its id; a feature with nothing to say is left out. */
Expand All @@ -260,6 +281,7 @@ export async function featureBandLines($: EngineInterface, ui: BandUi): Promise<
add('sqlGraph', await attempt($, 'sqlGraph', 'bandLine', () => sqlGraphBandLine($, ui)))
add('docs', await attempt($, 'docs', 'bandLine', () => docsBandLine($, ui)))
add('cteProfile', await attempt($, 'cteProfile', 'bandLine', () => cteProfileBandLine($, ui)))
add('dbtMods', await attempt($, 'dbtMods', 'bandLine', () => bandDbtMods($, ui)))
return lines
}

Expand Down Expand Up @@ -299,6 +321,19 @@ export async function featuresBashGate($: EngineInterface, e: BashCall): Promise
return gate
}

/** A Bash call that a gate refused, or whose result is a refusal, never reaches bashAfter: the features that kept it let go. */
export async function featuresBashDropped($: EngineInterface, e: BashCall): Promise<void> {
await attempt($, 'runs', 'bashDropped', () => runsBashDropped($, e))
}

/**
* Before a call runs, after the rewrites and the gate: what a feature needs to know of the call as it was
* then (the conversation it is in, the folder a command starts in). It cannot refuse or change the call.
*/
export async function featuresCallStart($: EngineInterface, e: ToolCallInput): Promise<void> {
await attempt($, 'dbtMods', 'callStart', () => dbtModsCallStart($, e))
}

/** The context lines every feature adds after a Bash call ran. */
export async function featuresBashAfter($: EngineInterface, e: BashCall, result: ToolCallResult): Promise<string[]> {
const lines: string[] = []
Expand All @@ -311,9 +346,16 @@ export async function featuresBashAfter($: EngineInterface, e: BashCall, result:
addLines(lines, await attempt($, 'sqlGraph', 'bashAfter', () => sqlGraphBashAfter($, e, result)))
addLines(lines, await attempt($, 'docs', 'bashAfter', () => docsBashAfter($, e, result)))
addLines(lines, await attempt($, 'cteProfile', 'bashAfter', () => cteProfileBashAfter($, e, result)))
addLines(lines, await attempt($, 'dbtMods', 'bashAfter', () => dbtModsBashAfter($, e, result)))
return lines
}

/**
* How long the edit phase may take: the dbt helpers hold an edit's result for up to their check's wait
* (dbt-mods.tsx), so the phase's deadline allows that and a little more.
*/
export const EDIT_AFTER_TIMEOUT_MS = dbtModsCheckHoldMs + 5_000

/** Whether any feature's `editAfter` needs the file's text from before the edit. */
export const EDIT_READS_BEFORE: boolean = runsEditReadsBefore || deferEditReadsBefore || toModelEditReadsBefore || commentsEditReadsBefore || costEditReadsBefore || healthEditReadsBefore || sqlGraphEditReadsBefore || docsEditReadsBefore || cteProfileEditReadsBefore

Expand All @@ -329,6 +371,7 @@ export async function featuresEditAfter($: EngineInterface, e: FileCall, result:
addLines(lines, await attempt($, 'sqlGraph', 'editAfter', () => sqlGraphEditAfter($, e, result, sqlGraphEditReadsBefore ? file : { path: file.path, before: null })))
addLines(lines, await attempt($, 'docs', 'editAfter', () => docsEditAfter($, e, result, docsEditReadsBefore ? file : { path: file.path, before: null })))
addLines(lines, await attempt($, 'cteProfile', 'editAfter', () => cteProfileEditAfter($, e, result, cteProfileEditReadsBefore ? file : { path: file.path, before: null })))
addLines(lines, await attempt($, 'dbtMods', 'editAfter', () => dbtModsEditAfter($, e, result, file)))
return lines
}

Expand All @@ -344,6 +387,7 @@ export async function featuresReadOrEditAfter($: EngineInterface, e: FileCall, r
addLines(lines, await attempt($, 'sqlGraph', 'readOrEditAfter', () => sqlGraphReadOrEditAfter($, e, result, file)))
addLines(lines, await attempt($, 'docs', 'readOrEditAfter', () => docsReadOrEditAfter($, e, result, file)))
addLines(lines, await attempt($, 'cteProfile', 'readOrEditAfter', () => cteProfileReadOrEditAfter($, e, result, file)))
addLines(lines, await attempt($, 'dbtMods', 'readOrEditAfter', () => dbtModsReadOrEditAfter($, e, result, file)))
return lines
}

Expand Down
3 changes: 3 additions & 0 deletions plugins/altimate-code/hooks/features/runs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ export async function bashGate($: EngineInterface, e: BashCall): Promise<{ deny:

export async function bashAfter($: EngineInterface, e: BashCall, result: ToolCallResult): Promise<ContextLines> {}

/** A Bash call that a gate refused, or whose result is a refusal, never reaches `bashAfter`: the place to let go of what this feature kept for it. */
export async function bashDropped($: EngineInterface, e: BashCall): Promise<void> {}

/** `file.before` holds the text from before the edit only when `editReadsBefore` is true. */
export async function editAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: EditedFile): Promise<ContextLines> {}

Expand Down
33 changes: 32 additions & 1 deletion plugins/altimate-code/hooks/tool-chain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,11 +159,27 @@ test('a phase that never settles is given up on: the call passes through unchang
expect(await afterCall(edit, ok, null, steps)).toBe(ok)
expect(seen).toEqual(
['bashRewrite', 'bashGate', 'bashAfter', 'readBefore', 'editAfter', 'readOrEditAfter'].map(
phase => `log:tool chain · ${phase} did not finish within 5000 ms or failed: the call goes on unchanged`,
phase => `log:tool chain · ${phase} did not finish within ${phase === 'editAfter' ? 35000 : 5000} ms or failed: the call goes on unchanged`,
),
)
})

test('the edit phase may hold an edit longer than the others: a slow check still rides on its result', async () => {
const deadlines: number[] = []
const { steps } = recording({
editAfter: async () => ['held note'],
limit: (async (work: Promise<unknown>, ms: number) => {
deadlines.push(ms)
return work
}) as any,
})
const edit = { tool: 'Edit', file_path: '/repo/models/a.sql' } as any
const result = await afterCall(edit, ok, null, steps)
expect((result as any).context).toContain('held note')
// editAfter, then readOrEditAfter.
expect(deadlines).toEqual([35000, 5000])
})

test('a phase that throws at once is treated like one that timed out', async () => {
const { steps } = recording({
bashRewrite: (() => {
Expand Down Expand Up @@ -191,3 +207,18 @@ test('a deadline or a logger that throws drops only that phase: the gate after i
expect(pre.deny).toEqual({ deny: 'refused' })
expect(seen).toEqual(['bashRewrite:dbt run', 'bashGate:dbt run'])
})

test('a call a gate refuses is reported as dropped, and so is one whose result is a refusal; a call that runs is not', async () => {
const dropped: string[] = []
const bashDropped = async (e: { command: string }) => void dropped.push(e.command)
const refused = recording({ bashGate: async () => ({ deny: 'held' }), bashDropped })
expect((await beforeCall({ tool: 'Bash', command: 'dbt build -s a' } as any, refused.steps)).deny).toEqual({ deny: 'held' })
expect(dropped).toEqual(['dbt build -s a'])

const open = recording({ bashDropped })
const call = { tool: 'Bash', command: 'dbt build -s b' } as any
await afterCall(call, { deny: 'later' } as any, null, open.steps)
expect(dropped).toEqual(['dbt build -s a', 'dbt build -s b'])
await afterCall(call, ok, null, open.steps)
expect(dropped).toHaveLength(2)
})
Loading
Loading