diff --git a/PRIVACY.md b/PRIVACY.md index 3b90b2d..70b47a6 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -1,7 +1,7 @@ # Privacy Policy — Altimate Code plugin for Claude Code **Effective date:** November 2, 2026 -**Last revised:** November 19, 2026 +**Last revised:** November 20, 2026 **Applies to:** the `altimate-code` Claude Code plugin distributed from this repository, and the data flows it initiates through the [altimate-code](https://github.com/AltimateAI/altimate-code) MCP server and CLI. This policy supplements the Altimate AI [Privacy Policy](https://www.altimate.ai/privacy) and [Terms](https://www.altimate.ai/terms), which govern Altimate services generally. Where this document is silent, the master policy applies. Questions: **info@altimate.ai**. @@ -17,6 +17,7 @@ This policy supplements the Altimate AI [Privacy Policy](https://www.altimate.ai - Warehouse queries, dbt commands, and file edits run **locally on your machine, under your credentials**. Your warehouse credentials are never sent to Altimate. - In a project linked to an Altimate workspace, the plugin copies the workspace's team skills into the project's `.claude/skills/` and refreshes them from Altimate in the background at session start and at most hourly. Their text loads into the Claude Code conversation like any project skill. `ALTIMATE_CLAUDE_SKILL_SYNC=0` turns this off and removes the copies at the next session start. - The plugin counts its own use anonymously, through the altimate-code CLI's usage telemetry: one event at each session start (plugin and altimate-code versions, OS, a random install id) and one each time a panel or command opens or a gate holds or allows a command (its name and outcome). No session id, project, model, column or file names, SQL or session text, and nothing that links them to your account or to the CLI's other telemetry. `ALTIMATE_TELEMETRY_DISABLED=true` turns it off. See [Plugin usage events](#plugin-usage-events). +- `/altimate-feedback` only drafts a GitHub issue and shows it to you; nothing is sent unless you then confirm with `--confirm` (see [Feedback](#feedback)). - Installing the plugin is an explicit act — `/plugin marketplace add` does not install it, and `/plugin install` never auto-runs. Nothing is delegated until the plugin is installed and you send a task that matches the skill. ## What the plugin does and does not do @@ -108,6 +109,14 @@ To learn whether the report gets used, the plugin asks the local altimate-code C Each event carries the step and the Claude Code session id (`claude:`) only: no model, column, file or project names. It goes through Altimate's usage telemetry, described in [Usage telemetry](#usage-telemetry), and that section's opt-out turns it off; with `ALTIMATE_TELEMETRY_DISABLED` set, the plugin does not start the CLI for it. With an altimate-code that predates the command, nothing is sent. +## Feedback + +`/altimate-feedback` drafts a GitHub issue for this plugin's repository. **Nothing is sent when you run it**: it shows you the exact title and body, and only `/altimate-feedback --confirm` sends them. The draft is kept in memory until then and is dropped when you discard or replace it, or the session ends. The plugin does not start `gh` or open a browser before you confirm. + +The issue holds your own words (with the dbt profile's secret values, tokens, passwords, connection-string credentials and paths under your home folder cut out) and these facts: the plugin's version, altimate-code's version and binary name (not its path), the Claude Code version, the OS, dbt-core, adapter and Python versions when the dbt doctor has run, and the plugin's on/off settings. With `--with-error` it also holds the kind of the last error the plugin met: only the error's type and code (for example `Database Error`, `ENOENT`) and a few fixed phrases are kept, none of the message, so no file path, SQL, or project, model, relation or column name comes with it. The plugin collects no file paths, SQL, or project, model or column names; if you write them in your description they are included (a home-folder path is cut out when it is quoted or has no space in a folder name), so check the draft. + +After you confirm, the text goes to GitHub: through `gh issue create`, signed in as you, or through a prefilled link you open and submit yourself. The issue is public on [AltimateAI/altimate-claude-plugin](https://github.com/AltimateAI/altimate-claude-plugin/issues) and subject to GitHub's terms and privacy statement. Altimate receives it as any public issue; the plugin sends nothing to Altimate's services for this command. Before creating the issue with `gh`, the plugin runs `gh auth status` and `gh label list` for that repository, which contact GitHub with your sign-in but carry none of the draft. The plugin never signs you in to `gh`. + ## Plugin usage events To count installs, active use and which features are used, the plugin asks the local altimate-code CLI (`altimate-code tool report-event`) to send these events through Altimate's usage telemetry, described in [Usage telemetry](#usage-telemetry). The plugin itself contacts no server for them. diff --git a/plugins/altimate-code/CHANGELOG.md b/plugins/altimate-code/CHANGELOG.md index 14d356a..8ce87e6 100644 --- a/plugins/altimate-code/CHANGELOG.md +++ b/plugins/altimate-code/CHANGELOG.md @@ -13,6 +13,9 @@ All notable changes to this plugin will be documented in this file. - `--defer --state …`, `--favor-state` and `--target …` that `/defer` and `/target` add to Claude's dbt commands are no longer invisible: Claude's result says what the command ran as, and a line above the prompt shows it until the next prompt. - **Resolve** on a thread the lagging comment list still shows after it was resolved elsewhere is done (the thread is hidden) instead of answering "not an open thread"; a reply to such a thread says it is no longer open and reads the list again. +### Added +- `/altimate-feedback ` drafts a GitHub issue for this plugin's repository from your words and a few facts the plugin knows (plugin, altimate-code and Claude Code versions, the altimate-code binary name, OS, dbt-core, adapter and Python versions when the dbt doctor has run, and the plugin's on/off settings), shows the exact title and body, and creates it only after `--confirm`: with `gh issue create` (labelled `feedback` when the repository has that label) when `gh` is installed and signed in, otherwise as a prefilled new-issue link. `--with-error` also attaches the kind of the last plugin error (its type and code only, none of its message); `--cancel` discards the draft. + ## [1.8.3] — 2026-11-19 ### Fixed diff --git a/plugins/altimate-code/README.md b/plugins/altimate-code/README.md index fed6fc3..b7fd390 100644 --- a/plugins/altimate-code/README.md +++ b/plugins/altimate-code/README.md @@ -156,6 +156,18 @@ Compile and validate runs a query on your warehouse after every model edit (`dbt When Claude mentions `altimate-dbt`, it is the dbt command line that comes with altimate-code (`npm i -g @altimateai/altimate-code`, the same install as the plugin's engine). It finds your dbt project folder, Python environment and warehouse adapter by itself, and altimate-code's agent uses it instead of the raw dbt tool for better error messages. Its commands include `init`, `doctor`, `compile`, `build`, `run`, `test`, `deps`, `columns `, `graph` (lineage) and `execute ""` (a query through the dbt adapter). You do not need to run it yourself: Claude and the altimate-code agent call it when a task needs it, and the plugin's own dbt helpers above do not depend on it. See [altimate-dbt in the altimate-code docs](https://docs.altimate.sh/data-engineering/tools/dbt-tools/#altimate-dbt-cli). +## Send feedback + +**`/altimate-feedback `** drafts a GitHub issue for this plugin's repository ([AltimateAI/altimate-claude-plugin](https://github.com/AltimateAI/altimate-claude-plugin/issues)) from your words and a few facts the plugin already knows, shows you the exact title and body, and creates the issue only after you confirm. Run it with no text and it tells you how to start. + +1. `/altimate-feedback the band said nothing after a failed dbt run` shows the draft. Nothing is sent, and `gh` and the browser are not touched, yet. +2. `/altimate-feedback --confirm` creates exactly what you saw. With the [GitHub CLI](https://cli.github.com) installed and signed in (`gh auth status`), it runs `gh issue create` and prints the issue's URL, adding the `feedback` label when the repository has one. Without `gh`, or with `gh` not signed in or failing, it opens a prefilled new-issue link (and prints it, URL-encoded and kept under GitHub's length limit; a longer body is cut at the end and says so). Nothing is created until you press "Submit new issue" there. The plugin never signs you in. +3. `/altimate-feedback --cancel` discards the draft. Running the command again with new text replaces it. A draft is kept in memory only and ends with the session. + +What the issue holds besides your words: the plugin's version, altimate-code's version and binary name (`altimate` or `altimate-code`, never its path), the Claude Code version, the OS, dbt-core, adapter and Python versions when the dbt doctor has run, and which of the plugin's on/off settings are on. Add `--with-error` to also attach the kind of the last error the plugin met: only its type and code (for example `Database Error`, `ENOENT`, `$.process.run`) and a few fixed phrases (`not found`, `timed out`) are kept, none of the message, so no path, SQL, relation, model or column name or secret can come with it. Your own words get the dbt profile's secret values, tokens, passwords, connection-string credentials and paths under your home folder cut out (a home path with a space in a folder name is cut whole when it is quoted or another separator follows the space); the rest is as you wrote it, so leave out what you do not want public: the repository's issues are public. + +To see what would run without creating anything, set `ALTIMATE_FEEDBACK_DRY_RUN=1`: `--confirm` then prints the `gh issue create` command (or the link) and stops. + ## Settings The plugin has seven settings, shown when you enable it (`userConfig` in `.claude-plugin/plugin.json`). All are optional: Claude Code may report them as "not set", and each then takes the default below. `dbt_mods` is used by the dbt helpers, `maxScanBytes` by the scan check (BigQuery, Snowflake, Databricks), `healthBlocksPush` and `healthConfigPath` by the project health check, the two comments settings by team comments, and `show_edit_impact` by the per-edit impact note. @@ -217,6 +229,7 @@ Still stuck? See [Support](#support). - **Agent** — `agents/analyst.md` — read-only data analyst (MCP or CLI) - **Command** — `commands/altimate.md` — `/altimate-code:altimate` slash command for explicit delegation - **Command** — `commands/rules.md` — `/altimate-code:rules` to answer proposed team rules +- **Mod command** — `hooks/feedback.ts` — `/altimate-feedback` to draft and, once you confirm, file a GitHub issue - **Hooks** — `hooks/hooks.json` — SessionStart capability description and workspace skill copy; Stop hook hourly background skill refresh; the team rules hooks (`hooks-handlers/workspace-rules.sh`): SessionStart, UserPromptSubmit and Stop, which call `altimate learn hook ` and never fail the session (the per-turn hooks run in the background; session start waits at most 15 seconds); opt-in PreToolUse `warehouse-guard.sh` (needs `ALTIMATE_ROUTE_GUARD=1`) ## Support diff --git a/plugins/altimate-code/hooks/dbt-mods-core.ts b/plugins/altimate-code/hooks/dbt-mods-core.ts index 996c1a9..3d5c99d 100644 --- a/plugins/altimate-code/hooks/dbt-mods-core.ts +++ b/plugins/altimate-code/hooks/dbt-mods-core.ts @@ -124,6 +124,8 @@ export function redactionForms(value: string): string[] { const repr = part.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') forms.add(repr) forms.add(repr.replace(/'/g, "\\'")) + // A single-quoted YAML scalar doubles its apostrophes. + forms.add(part.replace(/'/g, "''")) } return [...forms].filter(one => one.length > 0) } diff --git a/plugins/altimate-code/hooks/dbt-mods.tsx b/plugins/altimate-code/hooks/dbt-mods.tsx index c838bd8..3b9b1a0 100644 --- a/plugins/altimate-code/hooks/dbt-mods.tsx +++ b/plugins/altimate-code/hooks/dbt-mods.tsx @@ -7,6 +7,7 @@ import type { Args, EngineInterface, EventResult, On, PluginOptions, RenderEleme import type { CheckView, DoctorCheck, DoctorView, FailureView, QueryResult, SavedQuery } from '../types' import { later } from './altimate-cli' import { openTracked } from './usage' +import { doctorFacts, noteProblem, type DoctorFacts } from './last-problem' import { loadPaneSizesOnce, noteTerminal, paneTerminalColumns, paneRequest, sizeControls, type PaneSpec } from './pane-size' import { cellText, @@ -761,6 +762,7 @@ async function recordRun($: EngineInterface, command: string, verb: string, sele if (generation !== mineGeneration) return null await update($, failureAtom, () => view) const names = failures.map(one => one.name) + noteProblem(`dbt ${verb} failed`, failures[0]!.message) $.ui.toast(`✖ dbt ${verb} failed · ${names.slice(0, 3).join(', ')}${names.length > 3 ? ` +${names.length - 3}` : ''} · Explain or Fix above the prompt`, { timeoutMs: 8000 }) return view } @@ -1779,6 +1781,12 @@ export async function dbtModsReadOrEditAfter($: EngineInterface, e: { tool: stri * A conversation ended (a /clear): its notes, context, check and failed run are not the next one's. * Called from the plugin's one session.end hook. A check still running lands nowhere. */ +/** What the dbt doctor found for /feedback: the versions only, null before it has run. */ +export async function dbtModsDoctorFacts($: EngineInterface): Promise { + const view = await read($, doctorAtom) + return view ? doctorFacts(view.checks) : null +} + export async function endDbtMods($: EngineInterface) { generation++ // A check of the conversation that ended answers nobody in the next. diff --git a/plugins/altimate-code/hooks/features/index.ts b/plugins/altimate-code/hooks/features/index.ts index 28f1b4b..4b309ed 100644 --- a/plugins/altimate-code/hooks/features/index.ts +++ b/plugins/altimate-code/hooks/features/index.ts @@ -10,6 +10,8 @@ import type { Args, EngineInterface, EventResult, On, PluginOptions, RenderElement, ToolCallInput, ToolCallResult } from 'claude-code' import { later } from '../altimate-cli' +import { feedbackSessionEnd, feedbackSessionStart, registerFeedback } from '../feedback' +import { noteProblem } from '../last-problem' import { keepStatusParts, restoreStatusParts } from '../status-line' import type { BashCall, EditedFile, FileCall } from '../tool-chain' import { @@ -168,6 +170,9 @@ export type FeatureContext = { } function failed($: EngineInterface, id: string, part: string, error: unknown) { + try { + noteProblem(`${id} ${part} failed`, String(error)) + } catch {} try { $.ui.log(`${id} · ${part} failed: ${String(error)}`, { to: 'debug' }) } catch {} @@ -218,6 +223,9 @@ export function registerFeatures(on: On, context: FeatureContext) { try { registerDbtMods(on, context) } catch {} + try { + registerFeedback(on, context) + } catch {} } export async function featuresSessionStart($: EngineInterface, e: Args<'session.start'>) { @@ -231,6 +239,7 @@ export async function featuresSessionStart($: EngineInterface, e: Args<'session. await attempt($, 'docs', 'sessionStart', () => docsSessionStart($, e)) await attempt($, 'cteProfile', 'sessionStart', () => cteProfileSessionStart($, e)) await attempt($, 'dbtMods', 'sessionStart', () => sessionStartDbtMods($, e)) + await attempt($, 'feedback', 'sessionStart', () => feedbackSessionStart($)) } /** @@ -305,6 +314,7 @@ export async function featuresSessionEnd($: EngineInterface, e: Args<'session.en await attempt($, 'docs', 'sessionEnd', () => docsSessionEnd($, e)) await attempt($, 'cteProfile', 'sessionEnd', () => cteProfileSessionEnd($, e)) await attempt($, 'dbtMods', 'sessionEnd', () => endDbtMods($)) + feedbackSessionEnd() } /** Each feature's band line, in order, with its id; a feature with nothing to say is left out. */ diff --git a/plugins/altimate-code/hooks/feedback.test.tsx b/plugins/altimate-code/hooks/feedback.test.tsx new file mode 100644 index 0000000..670a611 --- /dev/null +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -0,0 +1,695 @@ +import { expect, mock, test } from 'claude-code/testing' + +import { nothingToReport } from './inert-features' +import { setRedactions, clearRedactions } from './dbt-mods-core' +import { MAX_URL, buildDraft, cleanDescription, issueUrl, redactSecrets, titleOf, withoutHome, type Facts } from './feedback' +import { doctorFacts, errorKinds } from './last-problem' + +const HOME = '/Users/alice' +const ROOT = '/Users/alice/work/acme_secret_project' +const REPO_URL = 'https://github.com/AltimateAI/altimate-claude-plugin/issues' + +const facts = (over: Partial = {}): Facts => ({ + plugin: '1.8.3', + altimate: { name: 'altimate', version: '0.12.11' }, + claudeCode: '2.1.329', + os: 'macos', + doctor: { dbtCore: '1.8.2', adapter: 'snowflake 1.8.0', python: '3.11.4' }, + settings: [ + ['dbt helpers', true], + ['project health blocks git push', false], + ], + problem: null, + ...over, +}) + +// ─── The payload builder ────────────────────────────────────────────────────────────────────────────── + +test('the issue holds the description and each fact the plugin knows, and nothing else', () => { + const draft = buildDraft(facts(), 'The band said nothing after a failed run') + expect(draft.title).toBe('Feedback: The band said nothing after a failed run') + expect(draft.body).toBe( + [ + 'The band said nothing after a failed run', + '', + '---', + '', + '**Environment** (added by `/altimate-feedback`; nothing else is attached)', + '', + '- Plugin: altimate-code 1.8.3', + '- altimate-code: altimate 0.12.11', + '- Claude Code: 2.1.329', + '- OS: macos', + '- dbt: dbt-core 1.8.2, adapter snowflake 1.8.0, Python 3.11.4', + '- Settings: dbt helpers on, project health blocks git push off', + ].join('\n'), + ) + expect(draft.withProblem).toBe(false) +}) + +test('a fact that is not known says so: no altimate-code on PATH, no doctor run', () => { + const draft = buildDraft(facts({ altimate: null, doctor: null, settings: [] }), 'x') + expect(draft.body).toContain('- altimate-code: not found on PATH') + expect(draft.body).toContain('- dbt: not checked this session') + expect(draft.body).not.toContain('Settings') +}) + +test('the title is the first line of the description, one line, at most 80 characters', () => { + expect(titleOf('\n\n first line \nsecond')).toBe('Feedback: first line') + const long = titleOf('x'.repeat(200)) + expect(Array.from(long.slice('Feedback: '.length))).toHaveLength(80) + expect(long.endsWith('…')).toBe(true) +}) + +test('the last plugin error is a fenced block that says it holds the error type and code only', () => { + const draft = buildDraft(facts({ problem: { source: 'dbt run failed', text: 'Database Error, 002003 (42S02)' } }), 'x') + expect(draft.body).toContain("**Last plugin error** (dbt run failed; the error's type and code only, none of its message)\n\n```text\nDatabase Error, 002003 (42S02)\n```") + expect(draft.withProblem).toBe(true) +}) + +test('the dbt doctor contributes versions only, never its free text', () => { + expect( + doctorFacts([ + { id: 'dbt', status: 'ok', detail: 'dbt-core 1.8.2 (.venv/bin/dbt)' }, + { id: 'python', status: 'ok', detail: 'Python 3.11.4' }, + { id: 'adapter', status: 'ok', detail: 'snowflake 1.8.0' }, + ]), + ).toEqual({ dbtCore: '1.8.2', python: '3.11.4', adapter: 'snowflake 1.8.0' }) + expect( + doctorFacts([ + { id: 'dbt', status: 'ok', detail: 'dbt-core $(whoami) (/Users/alice/venv)' }, + { id: 'python', status: 'warn', detail: 'could not tell which Python runs dbt' }, + { id: 'adapter', status: 'fail', detail: 'the profile uses snowflake, but only bigquery is installed' }, + ]), + ).toBeNull() +}) + +// ─── Redaction ──────────────────────────────────────────────────────────────────────────────────────── + +test('tokens, passwords, connection-string credentials and keys are cut out of any text', () => { + const text = [ + 'token ghp_abcdefghijklmnopqrstuvwxyz0123456789', + 'password = "hunter2 hunter2"', + 'url postgres://bob:s3cret@db.example.com/x', + 'Authorization: Bearer abcdefgh12345678', + 'key sk-abcdefghijklmnopqrstuvwx', + 'aws AKIAABCDEFGHIJKLMNOP', + '-----BEGIN PRIVATE KEY-----\nMIIEvQ\n-----END PRIVATE KEY-----', + 'jwt eyJhbGciOiJIUzI1.eyJzdWIiOiIxMjM0.abcDEF123', + 'long 0123456789abcdef0123456789abcdef01234567', + ].join('\n') + const out = redactSecrets(text) + for (const leaked of ['ghp_abc', 'hunter2', 's3cret', 'abcdefgh12345678', 'sk-abcdef', 'AKIAABC', 'MIIEvQ', 'eyJhbGci', '0123456789abcdef0123']) expect(out).not.toContain(leaked) + expect(out).toContain('postgres://‹redacted›@db.example.com/x') +}) + +test('the values of the dbt profile that the plugin holds are cut out of the description', () => { + setRedactions(ROOT, ['wh-pa55-phrase']) + try { + expect(cleanDescription('it failed with wh-pa55-phrase in the log', [HOME])).toBe('it failed with ‹redacted› in the log') + } finally { + clearRedactions() + } +}) + +test('a path under the home folder is replaced whole, in either slash style, and a bare home folder too', () => { + expect(withoutHome(`open ${HOME}/work/acme/models/fct_orders.sql now`, [HOME])).toBe('open now') + expect(withoutHome('C:\\Users\\Alice\\work\\x.sql', ['C:\\Users\\Alice'])).toBe('') + expect(withoutHome(`in ${HOME}`, [HOME])).toBe('in ') + // A root or one-segment value would match everything: it is not a home folder. + expect(withoutHome('/etc/hosts', ['/'])).toBe('/etc/hosts') +}) + +test('the description keeps the person\'s own words but loses secrets and home paths, and is cut to length', () => { + const out = cleanDescription(`run in ${ROOT}/models/a.sql used password=abc123 and /clear`, [HOME]) + expect(out).toBe('run in used password=‹redacted› and /clear') + expect(Array.from(cleanDescription('é'.repeat(5000), [HOME]))).toHaveLength(4000) + expect(cleanDescription('a\u0000b\u001b[31mc\r\nd', [HOME])).toBe('ab[31mc\nd') +}) + +test('an error is kept as its type, code and fixed phrases only: no part of its message can reach the issue', () => { + const raw = [ + `Database Error in model fct_orders (${ROOT}/models/fct_orders.sql)`, + " 002003 (42S02): SQL compilation error: Object 'ACME_DB.RAW.ORDERS' does not exist or not authorized.", + ' LINE 1: select private_column', + ' select\n employee_ssn,\n salary * 1.2\nfrom payroll', + "Model 'fct_orders' depends on a node named 'stg_payroll' which was not found", + ` config ${HOME}/Client Files/settings.json password: p4ssw0rd Authorization: Basic dXNlcjpodW50ZXIy`, + 'C:/work/payroll/models/orders.sql \\\\corp\\share\\hr.sql target/run/acme/models/fct_orders.sql', + 'relation "analytics"."marts"."fct_orders" and private_schema.private_customers missing', + ].join('\n') + const out = errorKinds(raw) + expect(out).toBe('Database Error, 002003 (42S02), SQL compilation error, does not exist, not authorized, not found') + for (const leaked of ['fct_orders', 'ACME', 'private', 'employee_ssn', 'salary', 'payroll', 'p4ssw0rd', 'dXNl', 'Client', 'analytics', 'marts', 'corp', 'acme']) expect(out).not.toContain(leaked) +}) + +test('the plugin host-call names and error codes are kept, and a lookalike that is not on the list is not', () => { + expect(errorKinds('HooksError: altimate-code: $.process.run(dbt) failed to start: ENOENT: Executable not found in $PATH')).toBe('HooksError, $.process.run, failed to start, ENOENT, not found') + expect(errorKinds('AcmePayrollError EXYZ 12345 (hello) $.acme.thing')).toBe('') + // A JSON path in a SQL error is not a host call, and a host call's name only counts whole. + expect(errorKinds("JSON_VALUE(data, '$.store.payroll') $.session.customersecret $.store.getpayroll")).toBe('') + expect(errorKinds('TypeError TypeError ENOENT ENOENT')).toBe('TypeError, ENOENT') + expect(errorKinds('x'.repeat(100_000) + ' ENOENT')).toBe('') + expect(errorKinds(Array.from({ length: 30 }, (_, i) => `SQLSTATE ${10000 + i}`).join(' ')).split(', ').length).toBe(8) +}) + +test('a secret that straddles the length limit is gone whole, never left as a prefix', () => { + for (const secret of ['ghp_abcdefghijklmnopqrstuvwxyz0123456789', 'Authorization: Bearer abcdefgh12345678xyz']) { + for (const pad of [3980, 3990, 3995, 3999, 4000]) { + const out = cleanDescription(`${'ok '.repeat(2000).slice(0, pad)}${secret}`, [HOME]) + expect(out).not.toMatch(/ghp_|Bearer abc|abcdefgh/) + } + } + setRedactions(ROOT, ['sup3r-long-warehouse-secret']) + try { + expect(cleanDescription(`${'x '.repeat(1995)}sup3r-long-warehouse-secret`, [HOME])).not.toContain('sup3r') + } finally { + clearRedactions() + } +}) + +test('Basic and other authorization schemes are cut out whole, not only Bearer', () => { + const out = redactSecrets('Authorization: Basic dXNlcjpodW50ZXIy\nProxy-Authorization: Digest abcdefgh12345678\nsent Basic dXNlcjpodW50ZXIy twice') + expect(out).not.toMatch(/dXNl|abcdefgh/) + expect(out).toContain('Authorization: ‹redacted›') +}) + +test('a home path with a space in a folder name is replaced whole, quoted or not, and Windows paths in either slash style', () => { + expect(withoutHome(`"${HOME}/Client Files/acme/models/payroll.sql"`, [HOME])).toBe('""') + expect(withoutHome(`'${HOME}/Client Files'`, [HOME])).toBe("''") + expect(withoutHome(`open ${HOME}/Client Files/acme/models/payroll.sql with password`, [HOME])).toBe('open with password') + expect(withoutHome('C:/Users/Alice/Client Files/x.sql', ['C:\\Users\\Alice'])).toBe('') + expect(withoutHome('C:\\Users\\Alice\\Client Files\\y.sql', ['C:\\Users\\Alice'])).toBe('') + // Two paths close together may be cut as one: more is cut, never less. + expect(withoutHome('C:/Users/Alice/Client Files/x.sql and C:\\Users\\Alice\\Client Files\\y.sql', ['C:\\Users\\Alice'])).not.toMatch(/Client|x\.sql|y\.sql/) +}) + +// ─── The link ───────────────────────────────────────────────────────────────────────────────────────── + +test('the link is the new-issue page with the title and body URL-encoded, and decodes back to them', () => { + const draft = { title: 'Feedback: a & b = c?', body: 'line one\n\n- é ✓ 😀 #tag & more=1' } + const { url, truncated } = issueUrl(draft) + expect(truncated).toBe(false) + expect(url.startsWith(`${REPO_URL}/new?title=`)).toBe(true) + const parsed = new URL(url) + expect(parsed.searchParams.get('title')).toBe(draft.title) + expect(parsed.searchParams.get('body')).toBe(draft.body) + expect([...parsed.searchParams.keys()]).toEqual(['title', 'body']) +}) + +test('a body too long for a link is cut to fit the limit, on a character boundary, and the cut is stated', () => { + const body = `${'😀é'.repeat(3000)} END` + const { url, truncated } = issueUrl({ title: 'Feedback: long', body }) + expect(truncated).toBe(true) + expect(url.length).toBeLessThanOrEqual(MAX_URL) + // Still valid: decoding throws on a split pair, and the note is the last thing in the body. + const decoded = new URL(url).searchParams.get('body')! + expect(decoded).toContain('[Cut to fit the link') + expect(decoded).not.toContain('END') + expect(decoded.startsWith('😀é')).toBe(true) + // Nearly all the room is used: a cut that gave up early would be a bug too. + expect(url.length).toBeGreaterThan(MAX_URL - 40) + expect(issueUrl({ title: 'Feedback: long', body }, 500).url.length).toBeLessThanOrEqual(500) +}) + +// ─── The command: nothing leaves without confirmation ───────────────────────────────────────────────── + +type Gh = { + /** `gh` is not installed. */ + missing?: boolean + /** `gh auth status` exits with this. */ + auth?: number + /** The repository's labels. */ + labels?: string[] + /** `gh issue create` fails with this exit code. */ + createFails?: number + /** `gh issue create` never answers within its time. */ + createTimesOut?: boolean +} + +async function start($: any, on: any, options: { holdVersion?: () => Promise | undefined; registerError?: string; gh?: Gh; env?: Record; platform?: string; claude?: string } = {}) { + const clock = mock.clock(on) + mock.env(on, { HOME, ...(options.env ?? {}) }) + const gh = options.gh ?? {} + const calls: Array<{ argv: string[]; stdin?: string }> = [] + const logs: string[] = [] + on('session.id', () => ({ value: 'a1b2c3d4-0000-4000-8000-000000000001' })) + on('session.info', () => ({ value: { platform: options.platform ?? 'macos', isHosted: false } })) + on('session.version', async () => { + await options.holdVersion?.() + return { value: { version: options.claude ?? '2.1.329' } } + }) + on('session.start', (_: unknown, e: { cwd: string }) => ({ cwd: e.cwd })) + on('session.root', () => ({ value: ROOT })) + on('session.cwd', () => ({ value: ROOT })) + on('command.register', (_: unknown, e: { name: string }) => (options.registerError && e.name === 'defer' ? { deny: options.registerError } : { value: { command: e.name } })) + on('turn.start', (_: unknown, e: { turnId: string }) => ({ turnId: e.turnId })) + on('turn.complete', (_: unknown, e: { answer: string }) => ({ text: e.answer })) + on('session.end', () => ({ sessionId: 'test' })) + on('store.get', () => ({ value: undefined })) + on('store.set', () => ({ value: undefined })) + on('ui.status', () => ({ value: undefined })) + on('ui.toast', () => ({ value: undefined })) + on('ui.log', (_: unknown, e: { text: string }) => { + logs.push(e.text) + return { value: undefined } + }) + on('ui.render', ($$: any, e: any) => { + const { Box } = $$.ui.resolve(e) + return + }) + on('fs.exists', () => ({ value: false })) + on('fs.stat', () => { + throw new Error('ENOENT') + }) + on('fs.list', () => ({ value: [] })) + on('fs.read', (_: unknown, e: { path: string }) => { + if (e.path.endsWith('/.claude-plugin/plugin.json')) return { value: JSON.stringify({ name: 'altimate-code', version: '1.8.3' }) } + throw new Error('ENOENT ' + e.path) + }) + on('tool.list', () => ({ value: [] })) + on('mcp.connect', () => ({ value: { isConnected: false, reason: 'not_connected', message: 'off' } })) + on('process.run', async (_: unknown, e: { argv: readonly string[]; init?: { stdin?: string } }) => { + const argv = [...e.argv] + const [bin, a, b] = argv + if (bin === 'altimate' && a === '--version') return { value: { exitCode: 0, stdout: '0.12.11\n', stderr: '' } } + if (bin === 'gh') { + calls.push({ argv, stdin: e.init?.stdin }) + if (gh.missing) return { deny: 'spawn gh ENOENT' } + if (a === 'auth') return { value: { exitCode: gh.auth ?? 0, stdout: '', stderr: gh.auth ? 'You are not logged in' : '' } } + if (a === 'label') return { value: { exitCode: 0, stdout: JSON.stringify((gh.labels ?? ['feedback', 'bug']).map(name => ({ name }))), stderr: '' } } + if (a === 'issue' && b === 'create') { + if (gh.createTimesOut) return { deny: 'process timed out after 60000ms' } + if (gh.createFails) return { value: { exitCode: gh.createFails, stdout: '', stderr: `GraphQL: Resource not accessible (${HOME}/x) token ghp_abcdefghijklmnopqrstuvwxyz0123456789` } } + return { value: { exitCode: 0, stdout: `${REPO_URL}/77\n`, stderr: '' } } + } + } + if (bin === 'open' || bin === 'xdg-open') { + calls.push({ argv }) + return { value: { exitCode: 0, stdout: '', stderr: '' } } + } + if (argv[1] === 'tool' && argv[2] === 'report-event') return { value: { exitCode: 0, stdout: '', stderr: '' } } + const inert = nothingToReport(argv) + if (inert) return { value: inert } + return { value: { exitCode: 1, stdout: '', stderr: 'not this test' } } + }) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + await clock.settle() + const run = async (args: string) => { + const answer = (await $.command.run({ command: 'altimate-feedback', args } as any)) as { text?: string } + await clock.settle() + return answer.text ?? '' + } + const creates = () => calls.filter(call => call.argv[1] === 'issue') + const opens = () => calls.filter(call => call.argv[0] === 'open' || call.argv[0] === 'xdg-open') + return { run, calls, creates, opens, logs, clock } +} + +/** The body the preview shows: everything between its `Body:` line and the closing rule. */ +const shownBody = (text: string) => text.slice(text.indexOf('\nBody:\n') + '\nBody:\n'.length, text.lastIndexOf('\n\n---\nCreate it:')) +const shownTitle = (text: string) => /^Title: (.*)$/m.exec(text)![1] + +test('with no description the command asks for one and does nothing else', async ($, on) => { + const { run, calls } = await start($, on) + const text = await run('') + expect(text).toContain('/altimate-feedback ') + expect(await run('--with-error')).toContain('/altimate-feedback ') + expect(calls).toEqual([]) +}) + +test('a description gives the exact draft and sends nothing: no gh call, no browser, no issue', async ($, on) => { + const { run, calls } = await start($, on) + const text = await run('The band said nothing after a failed run') + expect(text).toContain('Nothing has been sent.') + expect(shownTitle(text)).toBe('Feedback: The band said nothing after a failed run') + expect(shownBody(text)).toContain('- Plugin: altimate-code 1.8.3') + expect(shownBody(text)).toContain('- altimate-code: altimate 0.12.11') + expect(shownBody(text)).toContain('- Claude Code: 2.1.329') + expect(shownBody(text)).toContain('- OS: macos') + expect(shownBody(text)).toContain('- dbt: not checked this session') + expect(shownBody(text)).toContain('- Settings: dbt helpers on') + expect(text).toContain('/altimate-feedback --confirm') + expect(calls).toEqual([]) +}) + +test('--confirm with no draft, and --confirm after --cancel, create nothing', async ($, on) => { + const { run, calls } = await start($, on) + expect(await run('--confirm')).toContain('no draft to send') + await run('some feedback') + expect(await run('--cancel')).toContain('Discarded') + expect(await run('--confirm')).toContain('no draft to send') + expect(await run('--cancel')).toContain('no draft to discard') + expect(calls).toEqual([]) +}) + +test('a draft replaced by a new description is the one that is sent', async ($, on) => { + const { run, creates } = await start($, on) + await run('first thoughts') + const second = await run('second thoughts') + expect(await run('--confirm')).toContain(`Created: ${REPO_URL}/77`) + expect(creates()).toHaveLength(1) + expect(creates()[0]!.argv).toContain(shownTitle(second)) +}) + +test('a description that holds the word --confirm is a description, not a confirmation', async ($, on) => { + const { run, calls } = await start($, on) + const text = await run('please --confirm nothing') + expect(text).toContain('Draft issue') + expect(calls).toEqual([]) +}) + +test('gh installed and signed in: the confirmed draft is created with gh, labelled feedback, body and title as shown', async ($, on) => { + const { run, creates, opens } = await start($, on) + const preview = await run('The band said nothing after a failed run') + const done = await run('--confirm') + expect(done).toBe(`Created: ${REPO_URL}/77`) + expect(creates()).toHaveLength(1) + const { argv, stdin } = creates()[0]! + expect(argv).toEqual(['gh', 'issue', 'create', '--repo', 'AltimateAI/altimate-claude-plugin', '--title', shownTitle(preview), '--body-file', '-', '--label', 'feedback']) + expect(stdin).toBe(shownBody(preview)) + expect(opens()).toEqual([]) +}) + +test('a repository without a feedback label gets the issue without a label', async ($, on) => { + const { run, creates } = await start($, on, { gh: { labels: ['bug'] } }) + await run('x') + await run('--confirm') + expect(creates()[0]!.argv).not.toContain('--label') +}) + +test('gh missing: the link is given and opened, and no issue is created', async ($, on) => { + const { run, creates, opens } = await start($, on, { gh: { missing: true } }) + const preview = await run('x & y') + const done = await run('--confirm') + expect(creates()).toEqual([]) + expect(done).toContain('gh is not installed') + const url = /https:\/\/github\.com\S+/.exec(done)![0] + const parsed = new URL(url) + expect(`${parsed.origin}${parsed.pathname}`).toBe(`${REPO_URL}/new`) + expect(parsed.searchParams.get('title')).toBe(shownTitle(preview)) + expect(parsed.searchParams.get('body')).toBe(shownBody(preview)) + expect(opens()).toEqual([{ argv: ['open', url] }]) + expect(done).toContain('nothing is created until you press "Submit new issue"') +}) + +test('gh missing on Linux opens with xdg-open; on another platform the link is only given', async ($, on) => { + const linux = await start($, on, { gh: { missing: true }, platform: 'linux' }) + await linux.run('x') + await linux.run('--confirm') + expect(linux.opens().map(call => call.argv[0])).toEqual(['xdg-open']) +}) + +test('gh not signed in: the link, no sign-in attempt, no create', async ($, on) => { + const { run, calls, creates } = await start($, on, { gh: { auth: 1 } }) + await run('x') + const done = await run('--confirm') + expect(done).toContain('gh is not signed in') + expect(done).toContain('never signs in') + expect(creates()).toEqual([]) + expect(calls.filter(call => call.argv.includes('login'))).toEqual([]) +}) + +test('gh failing to create falls back to the link, with its reason redacted', async ($, on) => { + const { run, creates } = await start($, on, { gh: { createFails: 1 } }) + await run('x') + const done = await run('--confirm') + expect(creates()).toHaveLength(1) + expect(done).toContain('gh could not create the issue') + expect(done).toContain('/issues/new?title=') + expect(done).not.toContain('ghp_abc') + expect(done).not.toContain(HOME) +}) + +test('gh that times out is not retried and the link is not offered as if nothing had happened', async ($, on) => { + const { run, creates } = await start($, on, { gh: { createTimesOut: true } }) + await run('x') + const done = await run('--confirm') + expect(creates()).toHaveLength(1) + expect(done).toContain('may have been created') + expect(await run('--confirm')).toContain('no draft to send') +}) + +test('two confirmations create one issue', async ($, on) => { + const { run, creates } = await start($, on) + await run('x') + await run('--confirm') + expect(await run('--confirm')).toContain('no draft to send') + expect(creates()).toHaveLength(1) +}) + +test('ALTIMATE_FEEDBACK_DRY_RUN prints the gh command and creates nothing, opens nothing', async ($, on) => { + const { run, creates, opens } = await start($, on, { env: { ALTIMATE_FEEDBACK_DRY_RUN: '1' } }) + await run("it's broken") + const done = await run('--confirm') + expect(done).toContain('Dry run') + expect(done).toContain("gh issue create --repo AltimateAI/altimate-claude-plugin --title 'Feedback: it'\\''s broken' --body-file -") + expect(creates()).toEqual([]) + expect(opens()).toEqual([]) +}) + +test('ALTIMATE_FEEDBACK_DRY_RUN without gh prints the link and opens nothing', async ($, on) => { + const { run, opens } = await start($, on, { env: { ALTIMATE_FEEDBACK_DRY_RUN: 'true' }, gh: { missing: true } }) + await run('x') + const done = await run('--confirm') + expect(done).toContain('/issues/new?title=') + expect(opens()).toEqual([]) +}) + +test('the description\'s secrets and home paths are gone from the draft, the title and the issue that is sent', async ($, on) => { + const { run, creates } = await start($, on) + const preview = await run(`crash in ${ROOT}/models/a.sql with token=abc123def and ghp_abcdefghijklmnopqrstuvwxyz0123456789`) + for (const text of [preview, shownTitle(preview), shownBody(preview)]) { + expect(text).not.toContain(HOME) + expect(text).not.toContain('acme_secret_project') + expect(text).not.toContain('abc123def') + expect(text).not.toContain('ghp_abc') + } + await run('--confirm') + const sent = JSON.stringify(creates()[0]) + expect(sent).not.toContain(HOME) + expect(sent).not.toContain('ghp_abc') +}) + +test('--with-error with no error recorded says so and attaches nothing', async ($, on) => { + const { run } = await start($, on) + const text = await run('x --with-error') + expect(text).toContain('No plugin error has been recorded this session') + expect(shownBody(text)).not.toContain('Last plugin error') +}) + +test('the last plugin error is attached only with --with-error, as its type and code and none of its message', async ($, on) => { + // A feature that fails is the plugin's own error: here the /defer registration fails, with a message naming a path, a relation and a token. + const { run } = await start($, on, { registerError: `ENOENT: no such file ${ROOT}/target/manifest.json while reading 'ACME.RAW.ORDERS' (token ghp_abcdefghijklmnopqrstuvwxyz0123456789)` }) + const without = await run('it failed') + expect(shownBody(without)).not.toContain('Last plugin error') + const withError = await run('it failed --with-error') + const body = shownBody(withError) + expect(body).toContain("**Last plugin error** (defer sessionStart failed; the error's type and code only, none of its message)") + expect(body).toContain('```text\nHooksError, $.command.register, ENOENT\n```') + for (const leaked of [HOME, 'manifest.json', 'ACME', 'ghp_abc', 'no such file']) expect(body).not.toContain(leaked) +}) + +test('a draft still being built when it is discarded, or when the session ends, is not kept and cannot be sent', async ($, on) => { + let release!: () => void + const held = new Promise(resolve => (release = resolve)) + const { run, creates } = await start($, on, { holdVersion: () => held }) + const building = run('slow draft') + await run('--cancel') + release() + expect(await building).toContain('replaced or discarded before it was ready') + expect(await run('--confirm')).toContain('no draft to send') + expect(creates()).toEqual([]) +}) + +test('a confirmation while a replacement draft is being built sends nothing: the draft it replaces is gone, and the new one is sent only when confirmed', async ($, on) => { + let hold = false + let release!: () => void + const held = new Promise(resolve => (release = resolve)) + const { run, creates } = await start($, on, { holdVersion: () => (hold ? held : undefined) }) + await run('first draft') + hold = true + const replacing = run('second draft') + expect(await run('--confirm')).toContain('no draft to send') + expect(creates()).toEqual([]) + release() + const preview = await replacing + expect(shownTitle(preview)).toBe('Feedback: second draft') + await run('--confirm') + expect(creates()).toHaveLength(1) + expect(creates()[0]!.argv).toContain('Feedback: second draft') +}) + +test('a description over the read limit is refused, not cut: no secret is split before it is redacted', async ($, on) => { + const { run, calls } = await start($, on) + const text = await run(`${'1'.repeat(100_000)} ghp_abcdefghijklmnopqrstuvwxyz0123456789`) + expect(text).toContain('too long') + expect(text).not.toContain('ghp_') + expect(calls).toEqual([]) +}) + +test('a description at the read limit is redacted whole and quickly, whatever shrinks before it', () => { + const started = Date.now() + const out = cleanDescription(`${'Authorization: Basic dXNlcjpodW50ZXIy\n'.repeat(2600)}${'1'.repeat(99_000 - 2600 * 37)} ghp_abcdefghijklmnopqrstuvwxyz0123456789`.slice(0, 100_000), [HOME]) + expect(out).not.toMatch(/ghp_|dXNl/) + expect(Date.now() - started).toBeLessThan(3000) + const worst = Date.now() + cleanDescription(`${'a-1'.repeat(33_000)}${' x/'.repeat(1000)}${HOME}/${'a '.repeat(30_000)}`, [HOME]) + expect(Date.now() - worst).toBeLessThan(3000) +}) + +test('a quoted secret value is cut whole, whatever escaped quotes it holds', () => { + for (const text of ['{"password":"alpha\\"omega-secret"}', "password='alpha\\'omega-secret'", 'secret = "x" and then password=plain-secret']) { + const out = redactSecrets(text) + expect(out).not.toMatch(/omega|b-secret|plain-secret/) + } + expect(redactSecrets('{"password":"alpha\\"omega-secret","user":"bob"}')).toBe('{"password":‹redacted›,"user":"bob"}') +}) + +test('a home path whose names hold apostrophes, quotes of another kind, or many spaces is replaced whole', () => { + expect(withoutHome(`"${HOME}/O'Brien/payroll.sql"`, [HOME])).toBe('""') + expect(withoutHome(`'${HOME}/say "hi"/payroll.sql'`, [HOME])).toBe("''") + expect(withoutHome(`see ${HOME}/O'Brien/payroll.sql now`, [HOME])).toBe('see now') + expect(withoutHome(`see ${HOME}/My Very Private Client Files/payroll.sql now`, [HOME])).toBe('see now') + expect(withoutHome(`a "${HOME}/x\\"y/z.sql" b`, [HOME])).toBe('a "" b') +}) + +test('a description that is refused as too long, or empty after the flag, leaves no earlier draft to confirm, finished or still being built', async ($, on) => { + let hold = false + let release!: () => void + const held = new Promise(resolve => (release = resolve)) + const { run, creates } = await start($, on, { holdVersion: () => (hold ? held : undefined) }) + await run('obsolete draft') + expect(await run('x'.repeat(100_001))).toContain('too long') + expect(await run('--confirm')).toContain('no draft to send') + hold = true + const building = run('in flight draft') + expect(await run('y'.repeat(100_001))).toContain('too long') + release() + expect(await building).toContain('replaced or discarded before it was ready') + expect(await run('--confirm')).toContain('no draft to send') + expect(creates()).toEqual([]) +}) + +test('credential keys with a prefix or suffix (DBT_PASSWORD, access_token), YAML block scalars and doubled apostrophes are cut out whole, with no profile values loaded', () => { + const text = [ + 'DBT_PASSWORD=hunter2', + 'SNOWFLAKE_PASSWORD="warehouse private secret"', + 'access_token=private-token-value', + "password: 'alpha''omega-secret'", + 'password: |\n my-database-password\n second-line-secret\nuser: bob', + 'client_secret: >-\n folded-secret', + 'AWS_SECRET_ACCESS_KEY=abcd/efgh+ijkl', + ].join('\n') + const out = redactSecrets(text) + expect(out).not.toMatch(/hunter2|warehouse|private-token|omega|database-password|second-line|folded-secret|abcd\/efgh/) + expect(out).toContain('user: bob') +}) + +test('a YAML block scalar under a credential key is cut whole: comments on its header, blank lines inside it, folded and literal', () => { + const out = redactSecrets(['password: | # database password', ' correct-horse', '', ' battery-staple', 'client_secret: >- # note', ' folded', 'next: kept', '- db_token: |', ' listed-secret', 'last: kept too'].join('\n')) + expect(out).not.toMatch(/correct|battery|folded|listed/) + expect(out).toContain('next: kept') + expect(out).toContain('last: kept too') + expect(out.split('\n')[0]).toBe('password: ‹redacted›') +}) + +test('a YAML credential under a quoted key, or with a value of several words, is cut whole', () => { + const out = redactSecrets(['password: correct horse battery staple', '"password": |', ' quoted-key-secret', "'db_token': >-", ' folded-quoted', ' - secret: two words here', 'name: kept'].join('\n')) + expect(out).not.toMatch(/correct|horse|staple|quoted-key|folded-quoted|two words/) + expect(out).toContain('name: kept') + expect(out.split('\n')[0]).toBe('password: ‹redacted›') +}) + +test('connection-string passwords are cut whole: braced, multi-word, and an Azure account key with slashes', () => { + const key = `${'Ab1/'.repeat(21)}Zz+/Qw==` + const out = redactSecrets( + ['Driver={ODBC Driver 18};Server=db;PWD={correct horse battery staple};Encrypt=yes', 'Server=db;Password=correct horse staple;User=bob', `DefaultEndpointsProtocol=https;AccountName=acme;AccountKey=${key};EndpointSuffix=core.windows.net`, 'PWD={a}}b c};x=1'].join('\n'), + ) + expect(out).not.toMatch(/correct|horse|battery|staple|Ab1\/|Zz\+|b c/) + expect(out).toContain('Encrypt=yes') + expect(out).toContain('User=bob') + expect(out).toContain('AccountName=acme') +}) + +test('a quoted password with a semicolon inside, and a last unquoted connection-string password with spaces, are cut whole', () => { + const out = redactSecrets(['password="alpha;omega-secret"', 'Server=db;Password=correct horse battery staple', "pwd='x;y-secret' and more", 'Server=db;Password=last words here;'].join('\n')) + expect(out).not.toMatch(/alpha|omega|correct|horse|battery|staple|y-secret|last words/) + expect(out).toContain('Server=db;Password=‹redacted›') + expect(out).toContain('and more') +}) + +test('the rules read the text as written: a profile value that is a key name or a home folder, or the base of a long key, cannot hide anything', () => { + const key = `${'Ab1/'.repeat(21)}Zz+/Qw==` + setRedactions(ROOT, [key, HOME, 'password']) + try { + const out = cleanDescription(`"${HOME}/work/acme/models/fct_orders.sql" key=${key} password=hunter2-production-key`, [HOME]) + expect(out).not.toMatch(/work|acme|fct_orders|Ab1|Zz|hunter2|production/) + } finally { + clearRedactions() + } +}) + +test('a password inside a JSON string that is itself JSON-escaped is cut whole', () => { + const out = redactSecrets(JSON.stringify({ message: JSON.stringify({ password: 'hunter2-prod', user: 'bob' }) })) + expect(out).not.toContain('hunter2') + expect(redactSecrets(JSON.stringify({ message: JSON.stringify({ message: JSON.stringify({ api_key: 'deep-secret-value' }) }) }))).not.toContain('deep-secret') +}) + +test('a multi-word password inside JSON strings escaped one, two or three times is cut whole', () => { + let value = JSON.stringify({ password: 'correct horse battery staple', user: 'bob' }) + for (let depth = 0; depth < 3; depth++) { + const out = redactSecrets(value) + expect(out).not.toMatch(/correct|horse|battery|staple/) + expect(out).toContain('bob') + value = JSON.stringify({ message: value }) + } +}) + +test('ADO.NET doubled quotes inside a quoted password are part of it, and a profile value that is also a key name does not hide the key', () => { + const out = redactSecrets('Server=db;Password="alpha""omega-secret";Encrypt=yes') + expect(out).not.toMatch(/alpha|omega/) + expect(out).toContain('Encrypt=yes') + setRedactions(ROOT, ['password', 'secret']) + try { + expect(redactSecrets('password=hunter2-production-key and client_secret=private-client-credential')).not.toMatch(/hunter2|private-client/) + } finally { + clearRedactions() + } +}) + +test('a profile value that YAML writes with doubled apostrophes is cut out too', () => { + setRedactions(ROOT, ["alpha'omega-secret"]) + try { + expect(redactSecrets("it said 'alpha''omega-secret' and alpha'omega-secret")).not.toMatch(/alpha|omega/) + } finally { + clearRedactions() + } +}) + +test('~/ paths and a path with parentheses in a folder name are replaced whole, with or without a home folder known', () => { + expect(withoutHome('see ~/private/payroll.sql now', [HOME])).toBe('see now') + expect(withoutHome('see ~/private/payroll.sql now', [])).toBe('see now') + expect(withoutHome("open '~/My Files/a.sql'", [])).toBe("open ''") + expect(withoutHome(`see ${HOME}/Client(Private)/payroll.sql now`, [HOME])).toBe('see now') + expect(withoutHome(`(see ${HOME}/x.sql)`, [HOME])).toBe('(see )') + expect(withoutHome('a~b and file:///Users/alice/x.sql', [HOME])).toBe('a~b and file://') + expect(withoutHome('2~3 and ~ alone', [])).toBe('2~3 and ~ alone') +}) + +test('a Windows home path as JSON or a Python repr writes it, with doubled backslashes or escaped slashes, is replaced whole', () => { + const home = 'C:\\Users\\Alice' + const json = JSON.stringify({ path: 'C:\\Users\\Alice\\work\\orders.sql', posix: `${HOME}/work/orders.sql` }) + expect(json).toContain('C:\\\\Users') + const out = withoutHome(json, [home, HOME]) + expect(out).toBe('{"path":"","posix":""}') + expect(withoutHome('{"p":"\\/Users\\/alice\\/work\\/a.sql"}', [HOME])).not.toContain('work') + expect(cleanDescription(json, [home, HOME])).not.toMatch(/Alice|orders/) +}) + +test('a new session starts with no draft', async ($, on) => { + const { run, creates } = await start($, on) + await run('x') + await $.session.end({ reason: 'clear', sessionId: 'a1b2c3d4-0000-4000-8000-000000000001' } as any) + expect(await run('--confirm')).toContain('no draft to send') + expect(creates()).toEqual([]) +}) diff --git a/plugins/altimate-code/hooks/feedback.ts b/plugins/altimate-code/hooks/feedback.ts new file mode 100644 index 0000000..c16b195 --- /dev/null +++ b/plugins/altimate-code/hooks/feedback.ts @@ -0,0 +1,497 @@ +// `/altimate-feedback `: drafts a GitHub issue for this plugin's repository from the +// person's words plus a few facts the plugin already knows, shows the exact title and body, and creates the +// issue only after the person confirms with `--confirm`. Nothing is sent, and no `gh` or browser call is +// made, before that: the draft lives in memory until it is confirmed, discarded, replaced or the session ends. +// +// What is attached: plugin version, altimate-code version and binary name (never its path), Claude Code +// version, OS, dbt-core / adapter / Python versions when the dbt doctor has run, and the plugin's own +// on/off settings. The last plugin error is attached only when asked for with `--with-error`; it is +// redacted first (the dbt profile's secret values, tokens, home-directory and other absolute paths, lines +// that look like SQL, relation and node names). No paths, SQL, project, model or column names are collected. +import type { EngineInterface, On, PluginOptions } from 'claude-code' + +import { MISSING_BINARY, parseVersion } from './altimate-cli' +import { redactionForms, redactionValues } from './dbt-mods-core' +import { dbtModsDoctorFacts } from './dbt-mods' +import { asVersion, forgetProblem, problemNoted, type DoctorFacts } from './last-problem' +import { pluginVersion } from './usage' + +export const REPO = 'AltimateAI/altimate-claude-plugin' +export const COMMAND = 'altimate-feedback' +export const LABEL = 'feedback' +/** The issue link is kept under this many characters: GitHub refuses a longer one. */ +export const MAX_URL = 7000 +export const MAX_DESCRIPTION = 4000 +export const MAX_TITLE = 80 +const DRY_RUN_ENV = 'ALTIMATE_FEEDBACK_DRY_RUN' +const CLI_NAMES = ['altimate', 'altimate-code'] as const +const CONFIRM = '--confirm' +const CANCEL = '--cancel' +const WITH_ERROR = '--with-error' +const TRUNCATION_NOTE = '\n\n[Cut to fit the link: the full text was shown before it was opened.]' +/** The plugin settings that are shown: an allow-list, so a setting that holds a path or a name is never read. */ +const SETTINGS: ReadonlyArray = [ + ['dbt_mods', 'dbt helpers'], + ['healthBlocksPush', 'project health blocks git push'], + ['commentsInContext', 'team comments in context'], + ['show_edit_impact', 'edit impact notes'], +] + +// ─── Redaction ──────────────────────────────────────────────────────────────────────────────────────── +// +// Every rule reads the text as it was written and only reports spans to cut; the spans are merged and cut in one pass. A rule never +// sees another rule's mask, so one cannot hide a key, a value or a path from another (a profile value that is also a key's name, +// a secret that begins like a path). + +const MASK = '‹redacted›' +const HOME_MASK = '' + +type Span = { start: number; end: number; home: boolean } + +const CREDENTIAL_KEY = String.raw`(?:pass(?:word|wd|phrase)?|pwd|secret|token|api[_-]?key|access[_-]?key|account[_-]?key|shared[_-]?access[_-]?key|private[_-]?key|credential|cookie|session[_-]?id|authorization)s?` +// A YAML line of a credential key: a block-scalar header (`password: |`, `secret: >- # note`) takes the indented lines after it, and a plain value +// (`password: correct horse battery staple`) is the rest of its line. +const KEY_LINE = String.raw`^([ \t]*(?:-[ \t]+)?["']?[\w.-]*?${CREDENTIAL_KEY}(?:\\*["'])?[ \t]*:[ \t]*)` +const BLOCK_HEADER = new RegExp(String.raw`${KEY_LINE}[|>][+-]?\d?[ \t]*(?:#.*)?$`, 'i') +const PLAIN_VALUE = new RegExp(String.raw`${KEY_LINE}(?![|>"'])(\S.*)$`, 'i') + +/** Each pattern's group 1, when it has one, is text that stays (a key, a scheme); the rest of the match is cut. */ +const SECRET_PATTERNS: RegExp[] = [ + /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g, + /\bgithub_pat_[A-Za-z0-9_]{20,}/g, + /\bsk-[A-Za-z0-9_-]{16,}/g, + /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, + /\bxox[abprs]-[A-Za-z0-9-]{10,}/g, + /\beyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{4,}/g, + /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, + /\b((?:proxy-)?authorization["']?\s*[:=]\s*)[^\n]+/gi, + /\b((?:Bearer|Basic|Digest|Token)\s+)[A-Za-z0-9._~+/=-]{8,}/g, + // user:password@host in a connection string or URL. + /(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]*:[^\s/@]+(?=@)/gi, + // A connection string's password: a quoted or braced value to its own closing delimiter (ODBC `PWD={a b};`, `}}` is a literal brace), or a + // value that runs to the next `;`, spaces included; the last field of a string (after a `;`, or alone on its line) runs to the end of the line. + /((? start) spans.push({ start, end, home: false }) + } + } + return spans +} + +/** The YAML values under credential keys: the rest of a line, or the indented lines (blank ones between them too) after a block-scalar header. */ +function yamlSpans(text: string): Span[] { + const spans: Span[] = [] + const lines = text.split('\n') + let offset = 0 + const starts = lines.map(line => { + const at = offset + offset += line.length + 1 + return at + }) + const bare = (line: string) => line.replace(/\r$/, '') + for (let i = 0; i < lines.length; i++) { + const line = bare(lines[i]!) + const plainValue = PLAIN_VALUE.exec(line) + if (plainValue) { + spans.push({ start: starts[i]! + plainValue[1]!.length, end: starts[i]! + line.length, home: false }) + continue + } + const header = BLOCK_HEADER.exec(line) + if (!header) continue + let last = i + for (let next = i + 1; next < lines.length; next++) { + if (/^[ \t]+\S/.test(lines[next]!)) last = next + else if (!/^[ \t]*\r?$/.test(lines[next]!)) break + } + spans.push({ start: starts[i]! + header[1]!.length, end: starts[last]! + bare(lines[last]!).length, home: false }) + i = last + } + return spans +} + +/** Every place a value of the dbt profile the plugin holds appears, in any of the forms dbt may print it. */ +function valueSpans(text: string): Span[] { + const spans: Span[] = [] + for (const form of new Set(redactionValues().flatMap(redactionForms))) { + for (let at = text.indexOf(form); at !== -1; at = text.indexOf(form, at + form.length)) spans.push({ start: at, end: at + form.length, home: false }) + } + return spans +} + +const escapeRegex = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + +/** The home folder forms to look for, from the values of HOME and USERPROFILE. */ +function homeForms(homes: readonly string[]): string[] { + const forms = new Set() + for (const home of homes) { + const trimmed = home.replace(/[\\/]+$/, '') + // A root (`/`) or a one-segment value would match everything. + if (trimmed.length < 3) continue + forms.add(trimmed) + forms.add(trimmed.replace(/\\/g, '/')) + forms.add(trimmed.replace(/\//g, '\\')) + // As JSON or a Python repr writes a path: backslashes doubled, or slashes escaped. + forms.add(trimmed.replace(/\\/g, '\\\\')) + forms.add(trimmed.replace(/\//g, '\\/')) + } + return [...forms].sort((a, b) => b.length - a.length) +} + +const PATH_SEGMENT = `(?:[^\\s'"\`<>()\\\\/]|'(?=[A-Za-z0-9])|\\([^\\s()'"\`<>]*\\))` +// The rest of a path after its home folder: segments, and a space inside one when a separator follows within eight words +// ("Client Files/acme"). A path that ends in a space-separated word ("Client Files") is cut at the space unless it is quoted. +const PATH_TAIL = `(?:[\\\\/]${PATH_SEGMENT}*(?: (?=(?:${PATH_SEGMENT}+ ){0,7}${PATH_SEGMENT}+[\\\\/])${PATH_SEGMENT}+)*)*` + +/** Every path under the home folder, and every `~/…` path: a quoted one up to its own closing quote (a quote of another kind, or an escaped one, is part of the name), an unquoted one with the spaces inside its folder names. */ +function homeSpans(text: string, homes: readonly string[]): Span[] { + const spans: Span[] = [] + // `~` stands for the home folder whoever the user is, so it counts only before a separator. + const forms = [...homeForms(homes).map(form => escapeRegex(form)), '(? span.end > span.start).sort((a, b) => a.start - b.start || b.end - a.end) + const merged: Span[] = [] + for (const span of sorted) { + const last = merged[merged.length - 1] + if (last && span.start <= last.end) { + last.end = Math.max(last.end, span.end) + last.home = last.home && span.home + } else merged.push({ ...span }) + } + let out = '' + let at = 0 + for (const span of merged) { + out += text.slice(at, span.start) + (span.home ? HOME_MASK : MASK) + at = span.end + } + return out + text.slice(at) +} + +const secretSpans = (text: string) => [...patternSpans(text), ...yamlSpans(text), ...valueSpans(text)] + +/** The text with every token, key, password, connection-string credential and value of the dbt profile cut out. */ +export function redactSecrets(text: string): string { + return cut(text, secretSpans(text)) +} + +/** The text with every path under the home folder, and every `~/…` path, cut out. */ +export function withoutHome(text: string, homes: readonly string[]): string { + return cut(text, homeSpans(text, homes)) +} + +/** Secrets and home paths together, found in the text as written. */ +export function redactAll(text: string, homes: readonly string[]): string { + return cut(text, [...secretSpans(text), ...homeSpans(text, homes)]) +} + +const CONTROL = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g +const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? text.replace(/\r\n?/g, '\n').replace(CONTROL, '').replace(LONE_SURROGATE, '') +/** The longest text read at all: a longer one is refused, not cut, so no secret is ever split before it is redacted. */ +export const MAX_INPUT = 100_000 + +/** + * What the person typed, as it will be filed: secrets and home-folder paths out of the whole text first, then cut to length, + * so a secret that straddles the cut is gone whole. The person's other words are kept. + */ +export function cleanDescription(text: string, homes: readonly string[]): string { + const clean = redactAll(plain(text).trim(), homes) + return Array.from(clean.trim()).slice(0, MAX_DESCRIPTION).join('') +} + +// ─── The facts ──────────────────────────────────────────────────────────────────────────────────────── + +export type Facts = { + plugin: string + altimate: { name: string; version: string } | null + claudeCode: string + os: string + doctor: DoctorFacts + settings: Array<[string, boolean]> + problem: { source: string; text: string } | null +} + +export type Draft = { title: string; body: string; withProblem: boolean } + +const OS = new Set(['macos', 'linux', 'windows', 'wsl']) + + +async function homesOf($: EngineInterface): Promise { + const [home, profile] = await Promise.all([$.env.get('HOME').catch(() => undefined), $.env.get('USERPROFILE').catch(() => undefined)]) + return [home, profile].filter((one): one is string => typeof one === 'string' && one !== '') +} + +/** The altimate-code on PATH: the binary name that answered (`altimate` or `altimate-code`) and its version; never where it lives. */ +async function altimateFacts($: EngineInterface): Promise { + for (const name of CLI_NAMES) { + try { + const answer = await $.process.run([name, '--version'], { timeoutMs: 10_000 }) + const version = answer.exitCode === 0 ? (parseVersion(answer.stdout ?? '') ?? parseVersion(answer.stderr ?? '')) : null + return version ? { name, version } : null + } catch (error) { + if (!MISSING_BINARY.test(String(error))) return null + } + } + return null +} + +export type Ask = { withProblem: boolean } + +/** Gathers the facts. A fact that cannot be read is left out or `unknown`, never an error. */ +export async function collectFacts($: EngineInterface, ask: Ask, extra: { doctor: DoctorFacts; settings: PluginOptions }): Promise { + const [plugin, altimate, claudeCode, os] = await Promise.all([ + pluginVersion($).catch(() => 'unknown'), + altimateFacts($).catch(() => null), + $.session + .version() + .then(one => asVersion(one.version) ?? one.version.match(/^\d+(?:\.\d+){0,3}(?:-[\w.]+)?/)?.[0] ?? 'unknown') + .catch(() => 'unknown'), + $.session + .info() + .then(info => (OS.has(info.platform) ? info.platform : 'unknown')) + .catch(() => 'unknown'), + ]) + const settings: Array<[string, boolean]> = [] + for (const [key, label] of SETTINGS) { + const value = extra.settings[key] + if (typeof value === 'boolean') settings.push([label, value]) + } + const problem = ask.withProblem ? problemNoted() : null + return { plugin, altimate, claudeCode, os, doctor: extra.doctor, settings, problem } +} + +// ─── The draft ──────────────────────────────────────────────────────────────────────────────────────── + +/** The first line of the description, as the issue title. */ +export function titleOf(description: string): string { + const first = description.split('\n').find(line => line.trim()) ?? '' + const oneLine = first.replace(/\s+/g, ' ').trim() + const chars = Array.from(oneLine) + return `Feedback: ${chars.length > MAX_TITLE ? `${chars.slice(0, MAX_TITLE - 1).join('')}…` : oneLine}` +} + +/** The issue: the person's words, then the facts, then (when asked for) the last plugin error. */ +export function buildDraft(facts: Facts, description: string): Draft { + const lines = [ + description, + '', + '---', + '', + '**Environment** (added by `/altimate-feedback`; nothing else is attached)', + '', + `- Plugin: altimate-code ${facts.plugin}`, + `- altimate-code: ${facts.altimate ? `${facts.altimate.name} ${facts.altimate.version}` : 'not found on PATH'}`, + `- Claude Code: ${facts.claudeCode}`, + `- OS: ${facts.os}`, + ] + if (facts.doctor) { + const parts = [facts.doctor.dbtCore && `dbt-core ${facts.doctor.dbtCore}`, facts.doctor.adapter && `adapter ${facts.doctor.adapter}`, facts.doctor.python && `Python ${facts.doctor.python}`].filter(Boolean) + lines.push(`- dbt: ${parts.join(', ')}`) + } else lines.push('- dbt: not checked this session') + if (facts.settings.length) lines.push(`- Settings: ${facts.settings.map(([label, on]) => `${label} ${on ? 'on' : 'off'}`).join(', ')}`) + if (facts.problem) lines.push('', `**Last plugin error** (${facts.problem.source}; the error's type and code only, none of its message)`, '', '```text', facts.problem.text, '```') + return { title: titleOf(description), body: lines.join('\n'), withProblem: !!facts.problem } +} + +/** The prefilled new-issue link. A body too long for the link is cut, on a character boundary, and says so. */ +export function issueUrl(draft: Pick, max = MAX_URL): { url: string; truncated: boolean } { + const make = (body: string) => `https://github.com/${REPO}/issues/new?title=${encodeURIComponent(draft.title)}&body=${encodeURIComponent(body)}` + const whole = make(draft.body) + if (whole.length <= max) return { url: whole, truncated: false } + const chars = Array.from(draft.body) + let low = 0 + let high = chars.length + // The longest start of the body that fits with the note after it. + while (low < high) { + const mid = Math.ceil((low + high) / 2) + if (make(chars.slice(0, mid).join('') + TRUNCATION_NOTE).length <= max) low = mid + else high = mid - 1 + } + return { url: make(chars.slice(0, low).join('') + TRUNCATION_NOTE), truncated: true } +} + +// ─── Sending ────────────────────────────────────────────────────────────────────────────────────────── + +const quote = (text: string) => `'${text.replace(/'/g, "'\\''")}'` +const firstLine = (text: string) => (text.split('\n').find(line => line.trim()) ?? '').trim().slice(0, 200) + +async function openLink($: EngineInterface, url: string): Promise { + const platform = await $.session + .info() + .then(info => info.platform) + .catch(() => 'unknown') + const argv = platform === 'macos' ? ['open', url] : platform === 'linux' ? ['xdg-open', url] : null + if (!argv) return false + try { + return (await $.process.run(argv, { timeoutMs: 10_000 })).exitCode === 0 + } catch { + return false + } +} + +/** A reason gh gave, in one short line: secrets and home-folder paths out. */ +async function reasonOf($: EngineInterface, text: string): Promise { + return firstLine(redactAll(text, await homesOf($))) +} + +async function linkAnswer($: EngineInterface, draft: Draft, lead: string, dry: boolean): Promise { + const { url, truncated } = issueUrl(draft) + const opened = dry ? false : await openLink($, url) + return [ + lead, + opened ? 'The link is open in your browser; nothing is created until you press "Submit new issue" there.' : 'Open this link to file it (nothing is created until you press "Submit new issue" there):', + url, + truncated ? 'The body was too long for a link and was cut at the end; paste the rest in the issue if it matters.' : '', + ] + .filter(Boolean) + .join('\n') +} + +/** Creates the issue with `gh` when it is installed and signed in, else gives the prefilled link. Called only after the person confirmed. */ +export async function send($: EngineInterface, draft: Draft): Promise { + const dry = ['1', 'true'].includes(((await $.env.get('ALTIMATE_FEEDBACK_DRY_RUN').catch(() => undefined)) ?? '').toLowerCase()) + let signedIn = false + let why = 'gh is not installed' + try { + const status = await $.process.run(['gh', 'auth', 'status', '--hostname', 'github.com'], { timeoutMs: 15_000 }) + signedIn = status.exitCode === 0 + if (!signedIn) why = 'gh is not signed in (run `gh auth login` yourself; the plugin never signs in)' + } catch (error) { + if (!MISSING_BINARY.test(String(error))) why = 'gh could not be run' + } + if (!signedIn) return linkAnswer($, draft, `${why}, so the issue is not created from here.`, dry) + + let withLabel = false + if (!dry) { + try { + const labels = await $.process.run(['gh', 'label', 'list', '--repo', REPO, '--json', 'name', '--limit', '500'], { timeoutMs: 20_000 }) + const names = labels.exitCode === 0 ? (JSON.parse(labels.stdout) as Array<{ name?: unknown }>) : [] + withLabel = Array.isArray(names) && names.some(one => one?.name === LABEL) + } catch { + withLabel = false + } + } + const argv = ['gh', 'issue', 'create', '--repo', REPO, '--title', draft.title, '--body-file', '-', ...(withLabel ? ['--label', LABEL] : [])] + if (dry) { + return [`Dry run (${DRY_RUN_ENV} is set): nothing was created. This would run, with the body shown above on stdin:`, argv.map((word, i) => (i === 6 ? quote(word) : word)).join(' '), `(adds --label ${LABEL} when the repository has that label)`].join('\n') + } + try { + const made = await $.process.run(argv, { timeoutMs: 60_000, stdin: draft.body }) + if (made.exitCode === 0) { + const url = new RegExp(`https://github\\.com/${escapeRegex(REPO)}/issues/\\d+`).exec(made.stdout)?.[0] + return url ? `Created: ${url}` : 'gh reported success but printed no link; check the repository\'s issues.' + } + return linkAnswer($, draft, `gh could not create the issue (${(await reasonOf($, made.stderr || made.stdout)) || `exit ${made.exitCode}`}).`, dry) + } catch (error) { + // A call that timed out may have created the issue: it is not retried. + if (/time(d)? ?out/i.test(String(error))) return 'gh took too long to answer; the issue may have been created. Check the repository\'s issues before trying again.' + return linkAnswer($, draft, `gh could not create the issue (${await reasonOf($, String(error))}).`, dry) + } +} + +// ─── The command ────────────────────────────────────────────────────────────────────────────────────── + +let pending: Draft | null = null +/** Moves on whenever a draft is discarded, replaced, sent or the session ends: a draft still being built for an earlier number is dropped. */ +let epoch = 0 +let sending = false +let settings: PluginOptions = {} + +const usage = `Say what happened, in your own words: + /altimate-feedback +Add ${WITH_ERROR} to attach the last plugin error (redacted). You will see the exact issue before anything is sent.` + +function preview(draft: Draft): string { + return [ + `Draft issue for ${REPO}. Nothing has been sent.`, + '', + `Title: ${draft.title}`, + '', + 'Body:', + draft.body, + '', + '---', + `Create it: /altimate-feedback ${CONFIRM} (uses gh when it is installed and signed in, else gives a prefilled link)`, + `Discard it: /altimate-feedback ${CANCEL} · Change it: run the command again with new text`, + ].join('\n') +} + +/** The command's answer for `args`; exported for the tests. */ +export async function answer($: EngineInterface, args: string): Promise { + const text = args.trim() + if (text === CANCEL) { + const had = pending !== null + epoch++ + pending = null + return had ? 'Discarded. Nothing was sent.' : 'There is no draft to discard.' + } + if (text === CONFIRM) { + if (!pending) return `There is no draft to send. Start with /altimate-feedback .` + if (sending) return 'The issue is already being created.' + const draft = pending + epoch++ + pending = null + sending = true + try { + return await send($, draft) + } finally { + sending = false + } + } + const withProblem = new RegExp(`(?:^|\\s)${WITH_ERROR}(?=\\s|$)`).test(text) + const description = text.replace(new RegExp(`(?:^|\\s)${WITH_ERROR}(?=\\s|$)`, 'g'), ' ').trim() + if (!description) return usage + // The draft shown before is gone from this moment, whatever follows: a confirmation while this one is being built, or after it is refused, sends nothing. + pending = null + const mine = ++epoch + if (description.length > MAX_INPUT) return `That is too long (over ${MAX_INPUT} characters). Say it shorter; nothing was drafted or sent.` + const homes = await homesOf($) + const facts = await collectFacts($, { withProblem }, { doctor: await dbtModsDoctorFacts($).catch(() => null), settings }) + // A discard, a send, another description or the end of the session while the facts were read: this draft is not kept. + if (mine !== epoch) return 'This draft was replaced or discarded before it was ready. Nothing was kept or sent.' + pending = buildDraft(facts, cleanDescription(description, homes)) + const note = withProblem && !facts.problem ? 'No plugin error has been recorded this session, so none is attached.\n\n' : '' + return note + preview(pending) +} + +/** Registers the command. */ +export function registerFeedback(on: On, context: { options: PluginOptions }) { + settings = context.options ?? {} + on('command.run', { command: COMMAND }, async ($, e) => ({ text: await answer($, e.args ?? '') })) +} + +/** After the session started: the command's place in the slash menu. A new session starts with no draft; an error a feature met while starting stays, as the last one. */ +export async function feedbackSessionStart($: EngineInterface) { + epoch++ + pending = null + await $.command.register({ name: COMMAND, description: 'Draft a GitHub issue for this plugin from your words and a few redacted facts; created only after you confirm', argumentHint: ' [--with-error]' }) +} + +/** The conversation ended: no draft or error outlives it. */ +export function feedbackSessionEnd() { + epoch++ + pending = null + forgetProblem() +} diff --git a/plugins/altimate-code/hooks/last-problem.ts b/plugins/altimate-code/hooks/last-problem.ts new file mode 100644 index 0000000..312d310 --- /dev/null +++ b/plugins/altimate-code/hooks/last-problem.ts @@ -0,0 +1,72 @@ +// What /feedback may attach, kept apart from feedback.ts so the dbt helpers can record into it without importing it: the +// last plugin error (in memory only) and the versions the dbt doctor found. +// The last plugin error is never kept as text. An error's message can hold a path, SQL, a relation, model or column name or a +// secret, in any form, so only what a fixed list recognises is taken out of it at once: the error's type, an errno or SQLSTATE code, +// the plugin's own host-call names (`$.process.run`), and a few fixed phrases. Nothing else of the message is kept, so nothing +// else can be filed. +const KNOWN_TOKENS = [ + String.raw`\b(?:Compilation|Database|Runtime|Parsing|Dependency|Configuration) Error\b`, + String.raw`\b(?:Type|Range|Syntax|Reference|Hooks|Eval|URI)Error\b`, + String.raw`\bE(?:NOENT|ACCES|PERM|EXIST|NOTDIR|ISDIR|TIMEDOUT|CONNREFUSED|CONNRESET|PIPE|MFILE|NOTEMPTY|AGAIN)\b`, + String.raw`\b\d{5,6} \([0-9A-Z]{5}\)`, + String.raw`\bSQLSTATE[ =:]*[0-9A-Z]{5}\b`, + String.raw`\$\.(?:command\.(?:register|run)|process\.run|session\.(?:start|end|info|version|id|root|cwd|send)|ui\.(?:render|toast|log|open|status|resolve)|fs\.(?:read|write|exists|stat|list)|env\.get|store\.(?:get|set)|state\.(?:get|set)|prompt\.submit|clock\.(?:now|sleep))(?![\w])`, + String.raw`\b(?:[Tt]imed out|[Nn]ot found|no implementation|[Pp]ermission denied|[Cc]onnection refused|[Nn]ot authorized|does not exist|[Ss]yntax error|SQL compilation error|could not be parsed|failed to start)\b`, +] +const KNOWN = new RegExp(KNOWN_TOKENS.join('|'), 'g') +const MAX_TOKENS = 8 + +/** What a fixed list recognises in an error's text, in order, each once; never any other part of the text. */ +export function errorKinds(text: string): string { + const found: string[] = [] + for (const match of String(text).slice(0, 20_000).matchAll(KNOWN)) { + const kind = match[0] + if (!found.includes(kind)) found.push(kind) + if (found.length >= MAX_TOKENS) break + } + return found.join(', ') +} + +let lastProblem: { source: string; text: string } | null = null + +/** + * Remembers the last plugin error, in memory only, for `--with-error`: `source` is the plugin's own words ("dbt run failed"), + * and of `raw` only what `errorKinds` recognises is kept. + */ +export function noteProblem(source: string, raw: string): void { + lastProblem = { source: source.slice(0, 80), text: errorKinds(raw) || 'no known error type or code' } +} + +/** The last problem noted, or null. */ +export const problemNoted = () => lastProblem + +export const forgetProblem = (): void => { + lastProblem = null +} + +/** The versions the dbt doctor found, when it has run. */ +export type DoctorFacts = { dbtCore?: string; adapter?: string; python?: string } | null + +const VERSION = /^\d+(?:\.\d+){0,3}(?:[-+][0-9A-Za-z.+-]{1,40})?$/ +/** A version as the doctor printed it, or null when it is anything else. */ +export const asVersion = (text: unknown): string | null => (typeof text === 'string' && text.length <= 48 && VERSION.test(text) ? text : null) + +/** The doctor's checks reduced to versions, never to their free text. */ +export function doctorFacts(checks: ReadonlyArray<{ id: string; status: string; detail: string }>): DoctorFacts { + const found: NonNullable = {} + for (const check of checks) { + if (check.id === 'dbt') { + const core = asVersion(/^dbt-core (\S+)/.exec(check.detail)?.[1]) + if (core) found.dbtCore = core + } else if (check.id === 'python') { + const python = asVersion(/^(?:Python )?(\d+\.\d+(?:\.\d+)?)/.exec(check.detail)?.[1]) + if (python) found.python = python + } else if (check.id === 'adapter' && check.status === 'ok') { + const match = /^([a-z][a-z0-9_]{1,30})(?: (\S+))?$/.exec(check.detail) + const version = asVersion(match?.[2]) + if (match) found.adapter = version ? `${match[1]} ${version}` : match[1] + } + } + return Object.keys(found).length ? found : null +} + diff --git a/plugins/altimate-code/hooks/usage.ts b/plugins/altimate-code/hooks/usage.ts index 14a1e1e..fcb981a 100644 --- a/plugins/altimate-code/hooks/usage.ts +++ b/plugins/altimate-code/hooks/usage.ts @@ -75,7 +75,7 @@ async function readOrMakeId($: EngineInterface): Promise { let ownVersion: string | null = null /** This plugin's version from its manifest, or `unknown`. */ -async function pluginVersion($: EngineInterface): Promise { +export async function pluginVersion($: EngineInterface): Promise { if (ownVersion) return ownVersion const version = await $.fs .read(`${$.plugin.root}/.claude-plugin/plugin.json`)