From 8c44c81480ba67e0d827ae1da820646a2df858d1 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 20 Nov 2026 22:00:15 +0530 Subject: [PATCH 01/14] feat: /altimate-code:feedback drafts a GitHub issue and files it only after you confirm Builds the issue from the description plus plugin, altimate-code, Claude Code, OS, dbt and settings facts (and, with --with-error, the last plugin error, redacted), shows the exact title and body, and creates it with gh issue create or a prefilled new-issue link after --confirm. Co-Authored-By: Claude Sonnet 5.5 --- PRIVACY.md | 11 +- plugins/altimate-code/CHANGELOG.md | 3 + plugins/altimate-code/README.md | 13 + plugins/altimate-code/hooks/dbt-mods.tsx | 8 + plugins/altimate-code/hooks/features/index.ts | 10 + plugins/altimate-code/hooks/feedback.test.tsx | 468 ++++++++++++++++++ plugins/altimate-code/hooks/feedback.ts | 404 +++++++++++++++ plugins/altimate-code/hooks/last-problem.ts | 45 ++ plugins/altimate-code/hooks/usage.ts | 2 +- 9 files changed, 962 insertions(+), 2 deletions(-) create mode 100644 plugins/altimate-code/hooks/feedback.test.tsx create mode 100644 plugins/altimate-code/hooks/feedback.ts create mode 100644 plugins/altimate-code/hooks/last-problem.ts diff --git a/PRIVACY.md b/PRIVACY.md index 3b90b2d..f906a20 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-code: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-code: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-code: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 secrets and home-folder paths 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 last error the plugin met, redacted: the dbt profile's secret values, tokens, passwords, connection-string credentials, file paths, lines that look like SQL, and relation and model names are removed, and the text is cut to a few short lines. No file paths, SQL, or project, model or column names are collected; if you write them in your description they are included, 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..57f6a48 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-code: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 last plugin error, redacted (secrets, paths, SQL and relation and model names removed); `--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..890fc6a 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-code: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-code: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-code: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-code: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 last error the plugin met, redacted first: the dbt profile's secret values, tokens and passwords, connection-string credentials, every file path (home-folder paths included), lines that look like SQL, and relation and model names are cut out, to at most six short lines. Without that flag no error text is attached. Your own words get the secrets and home-folder paths cut out too; 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-code: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.tsx b/plugins/altimate-code/hooks/dbt-mods.tsx index c838bd8..6510fe6 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, names) $.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..e970448 --- /dev/null +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -0,0 +1,468 @@ +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, cleanProblem, issueUrl, redactSecrets, titleOf, withoutHome, type Facts } from './feedback' +import { doctorFacts } 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-code: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, labelled redacted, and cannot close its fence', () => { + const draft = buildDraft(facts({ problem: { source: 'dbt run failed', text: "boom ''' end" } }), 'x') + expect(draft.body).toContain('**Last plugin error** (dbt run failed; redacted)\n\n```text\nboom \'\'\' end\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 and the error', () => { + 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') + expect(cleanProblem('Database Error: login wh-pa55-phrase refused', [HOME])).not.toContain('wh-pa55-phrase') + } 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 reduced: paths, SQL, relation and node names, secrets and home folders are all gone, in few short lines', () => { + 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.`, + ' select order_id, secret_column from raw.orders where token = abc', + ' compiled code at /private/tmp/target/run/acme/fct_orders.sql', + ` config ${HOME}/.dbt/settings.json password: p4ssw0rd`, + ' relation "analytics"."marts"."fct_orders" missing', + ...Array.from({ length: 20 }, (_, i) => `extra line ${i}`), + ].join('\n') + const out = cleanProblem(raw, [HOME], ['fct_orders']) + for (const leaked of [ROOT, HOME, 'fct_orders', 'ACME_DB', 'RAW.ORDERS', 'secret_column', 'raw.orders', 'p4ssw0rd', '/private/tmp', 'analytics', 'marts']) expect(out).not.toContain(leaked) + expect(out).toContain('') + expect(out).toContain(' { + setRedactions(ROOT, ['sup3r-long-warehouse-secret']) + try { + const out = cleanProblem(`${'x '.repeat(3990)}sup3r-long-warehouse-sec`, [HOME]) + expect(out).not.toContain('sup3r') + } finally { + clearRedactions() + } +}) + +// ─── 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: { 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', () => ({ 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: '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-code:feedback ') + expect(await run('--with-error')).toContain('/altimate-code: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-code: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, redacted, and without the file, model or relation names', 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** (') + expect(body).toContain('failed; redacted)') + expect(body).toContain('ENOENT: no such file ') + for (const leaked of [HOME, 'manifest.json', 'ACME.RAW.ORDERS', 'ghp_abc']) expect(body).not.toContain(leaked) +}) + +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..d4bf486 --- /dev/null +++ b/plugins/altimate-code/hooks/feedback.ts @@ -0,0 +1,404 @@ +// `/altimate-code: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 { redactValues, scrubDbt, withoutValueFragment } from './dbt-mods-core' +import { dbtModsDoctorFacts } from './dbt-mods' +import { MAX_RAW_PROBLEM, asVersion, forgetProblem, problemNoted, type DoctorFacts } from './last-problem' +import { pluginVersion } from './usage' + +export const REPO = 'AltimateAI/altimate-claude-plugin' +export const COMMAND = '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 +export const MAX_PROBLEM_CHARS = 600 +export const MAX_PROBLEM_LINES = 6 +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 ──────────────────────────────────────────────────────────────────────────────────────── + +const MASK = '‹redacted›' +const SECRET_PATTERNS: Array<[RegExp, string]> = [ + [/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g, MASK], + [/\bgithub_pat_[A-Za-z0-9_]{20,}/g, MASK], + [/\bsk-[A-Za-z0-9_-]{16,}/g, MASK], + [/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, MASK], + [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, MASK], + [/\beyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{4,}/g, MASK], + [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, MASK], + [/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi, `Bearer ${MASK}`], + // user:password@host in a connection string or URL. + [/(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]*:[^\s/@]+@/gi, `$1${MASK}@`], + [/\b((?:pass(?:word|wd)?|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret|authorization)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|\S+)/gi, `$1${MASK}`], + // A long unbroken run of key-like characters. + [/\b(?=[A-Za-z0-9_+-]*\d)[A-Za-z0-9_+-]{40,}={0,2}/g, MASK], +] + +/** The text with every token, key, password and connection-string credential cut out. */ +export function redactSecrets(text: string): string { + return SECRET_PATTERNS.reduce((out, [pattern, to]) => out.replace(pattern, to), redactValues(text)) +} + +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, '\\')) + } + return [...forms].sort((a, b) => b.length - a.length) +} + +/** Every path under the home folder, however long, replaced whole. */ +export function withoutHome(text: string, homes: readonly string[]): string { + return homeForms(homes).reduce((out, form) => out.replace(new RegExp(`${escapeRegex(form)}(?:[\\\\/][^\\s'"\`<>()]*)?`, 'gi'), ''), text) +} + +/** Every absolute path of two or more parts (a POSIX path, `~/…`, or a drive path), replaced whole. */ +export function withoutPaths(text: string): string { + return text + .replace(/(?()]+/g, '') + .replace(/(?()/]+\/[^\s'"`<>()]*/g, '') + .replace(/\b[A-Za-z]:\\[^\s'"`<>()]+/g, '') +} + +const SQL_LINE = /\b(?:select\b[^\n]*\bfrom\b|insert\s+into|delete\s+from|create\s+(?:or\s+replace\s+)?(?:temp(?:orary)?\s+)?(?:table|view)|merge\s+into|update\s+\S+\s+set|alter\s+table|drop\s+(?:table|view))\b|^\s*(?:select|with|from|where|join|(?:left|right|inner|outer|cross|full)\s+join|group\s+by|order\s+by|having|union|limit\s+\d+|on)\b\s*\S/i + +/** A line that reads as SQL is replaced by a fixed line; a dbt or warehouse error often quotes the statement. */ +export function withoutSql(text: string): string { + return text + .split('\n') + .map(line => (SQL_LINE.test(line) ? '' : line)) + .join('\n') +} + +/** Quoted or three-part relation names (`db.schema.table`, `"RAW"."ORDERS"`) and the names given. */ +function withoutNames(text: string, names: readonly string[]): string { + let out = text + for (const name of [...names].filter(one => one.length >= 2).sort((a, b) => b.length - a.length)) { + out = out.replace(new RegExp(`(?') + } + return out + .replace(/(["'`])[A-Za-z_][\w$]*(?:\.[A-Za-z_][\w$]*){1,2}\1/g, '') + .replace(/(?:"[\w$ -]+"|`[\w$ -]+`)(?:\.(?:"[\w$ -]+"|`[\w$ -]+`)){1,2}/g, '') + .replace(/\b[A-Za-z_][\w$]*\.[A-Za-z_][\w$]*\.[A-Za-z_][\w$]*\b/g, '') +} + +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, '') + +/** What the person typed, as it will be filed: secrets and home-folder paths out, cut to length. Their own words are otherwise kept. */ +export function cleanDescription(text: string, homes: readonly string[]): string { + const cut = Array.from(plain(text).trim()).slice(0, MAX_DESCRIPTION).join('') + return withoutHome(redactSecrets(withoutValueFragment(cut)), homes) +} + +/** A plugin error as it may be filed: nothing the plugin has not redacted or reduced, in at most a few short lines. */ +export function cleanProblem(raw: string, homes: readonly string[], names: readonly string[] = []): string { + const capped = withoutValueFragment(plain(raw).slice(0, MAX_RAW_PROBLEM)) + const clean = withoutNames(withoutPaths(withoutSql(withoutHome(redactSecrets(scrubDbt(capped)), homes))), names) + const lines = clean + .split('\n') + .map(line => line.trim()) + .filter(Boolean) + .slice(0, MAX_PROBLEM_LINES) + const joined = Array.from(lines.join('\n')).slice(0, MAX_PROBLEM_CHARS).join('') + // The text sits in a code fence: nothing in it may close the fence. + return joined.replace(/`{3,}/g, "'''") +} + +// ─── 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, homes] = 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'), + homesOf($), + ]) + 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 noted = problemNoted() + const problem = ask.withProblem && noted ? { source: noted.source, text: cleanProblem(noted.raw, homes, noted.names) } : null + return { plugin, altimate, claudeCode, os, doctor: extra.doctor, settings, problem: problem && problem.text ? problem : null } +} + +// ─── 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-code: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}; redacted)`, '', '```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(withoutHome(redactSecrets(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 +let sending = false +let settings: PluginOptions = {} + +const usage = `Say what happened, in your own words: + /altimate-code: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-code:feedback ${CONFIRM} (uses gh when it is installed and signed in, else gives a prefilled link)`, + `Discard it: /altimate-code: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 + 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-code:feedback .` + if (sending) return 'The issue is already being created.' + const draft = pending + 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 + const homes = await homesOf($) + const facts = await collectFacts($, { withProblem }, { doctor: await dbtModsDoctorFacts($).catch(() => null), settings }) + 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) { + 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() { + 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..7ed2bc6 --- /dev/null +++ b/plugins/altimate-code/hooks/last-problem.ts @@ -0,0 +1,45 @@ +// 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 raw problem text kept in memory, before it is redacted and cut. */ +export const MAX_RAW_PROBLEM = 8000 + +let lastProblem: { source: string; raw: string; names: string[] } | null = null + +/** Remembers the last plugin error, in memory only, for `--with-error`. `source` is the plugin's own words ("dbt run failed"), `raw` the error, `names` the nodes it is about. */ +export function noteProblem(source: string, raw: string, names: readonly string[] = []): void { + lastProblem = { source: source.slice(0, 80), raw: String(raw).slice(0, MAX_RAW_PROBLEM), names: names.slice(0, 20) } +} + +/** 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`) From 6bf08a79188f7e740b528eec0f50d3b78ee974c5 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 20 Nov 2026 22:08:02 +0530 Subject: [PATCH 02/14] fix: name the feedback command altimate-feedback, as Claude Code's own /feedback shadows a plugin command of that name Co-Authored-By: Claude Sonnet 5.5 --- PRIVACY.md | 4 ++-- plugins/altimate-code/CHANGELOG.md | 2 +- plugins/altimate-code/README.md | 10 +++++----- plugins/altimate-code/hooks/feedback.test.tsx | 10 +++++----- plugins/altimate-code/hooks/feedback.ts | 14 +++++++------- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/PRIVACY.md b/PRIVACY.md index f906a20..f6bd486 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -17,7 +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-code:feedback` only drafts a GitHub issue and shows it to you; nothing is sent unless you then confirm with `--confirm` (see [Feedback](#feedback)). +- `/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 @@ -111,7 +111,7 @@ Each event carries the step and the Claude Code session id (`claude:`) only: ## Feedback -`/altimate-code: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-code: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. +`/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 secrets and home-folder paths 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 last error the plugin met, redacted: the dbt profile's secret values, tokens, passwords, connection-string credentials, file paths, lines that look like SQL, and relation and model names are removed, and the text is cut to a few short lines. No file paths, SQL, or project, model or column names are collected; if you write them in your description they are included, so check the draft. diff --git a/plugins/altimate-code/CHANGELOG.md b/plugins/altimate-code/CHANGELOG.md index 57f6a48..37470dc 100644 --- a/plugins/altimate-code/CHANGELOG.md +++ b/plugins/altimate-code/CHANGELOG.md @@ -14,7 +14,7 @@ All notable changes to this plugin will be documented in this file. - **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-code: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 last plugin error, redacted (secrets, paths, SQL and relation and model names removed); `--cancel` discards the draft. +- `/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 last plugin error, redacted (secrets, paths, SQL and relation and model names removed); `--cancel` discards the draft. ## [1.8.3] — 2026-11-19 diff --git a/plugins/altimate-code/README.md b/plugins/altimate-code/README.md index 890fc6a..2c80a6a 100644 --- a/plugins/altimate-code/README.md +++ b/plugins/altimate-code/README.md @@ -158,11 +158,11 @@ When Claude mentions `altimate-dbt`, it is the dbt command line that comes with ## Send feedback -**`/altimate-code: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. +**`/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-code: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-code: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-code: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. +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 last error the plugin met, redacted first: the dbt profile's secret values, tokens and passwords, connection-string credentials, every file path (home-folder paths included), lines that look like SQL, and relation and model names are cut out, to at most six short lines. Without that flag no error text is attached. Your own words get the secrets and home-folder paths cut out too; the rest is as you wrote it, so leave out what you do not want public: the repository's issues are public. @@ -229,7 +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-code:feedback` to draft and, once you confirm, file a GitHub issue +- **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/feedback.test.tsx b/plugins/altimate-code/hooks/feedback.test.tsx index e970448..a09db3f 100644 --- a/plugins/altimate-code/hooks/feedback.test.tsx +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -34,7 +34,7 @@ test('the issue holds the description and each fact the plugin knows, and nothin '', '---', '', - '**Environment** (added by `/altimate-code:feedback`; nothing else is attached)', + '**Environment** (added by `/altimate-feedback`; nothing else is attached)', '', '- Plugin: altimate-code 1.8.3', '- altimate-code: altimate 0.12.11', @@ -265,7 +265,7 @@ async function start($: any, on: any, options: { registerError?: string; gh?: Gh await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) await clock.settle() const run = async (args: string) => { - const answer = (await $.command.run({ command: 'feedback', args } as any)) as { text?: string } + const answer = (await $.command.run({ command: 'altimate-feedback', args } as any)) as { text?: string } await clock.settle() return answer.text ?? '' } @@ -281,8 +281,8 @@ 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-code:feedback ') - expect(await run('--with-error')).toContain('/altimate-code:feedback ') + expect(text).toContain('/altimate-feedback ') + expect(await run('--with-error')).toContain('/altimate-feedback ') expect(calls).toEqual([]) }) @@ -297,7 +297,7 @@ test('a description gives the exact draft and sends nothing: no gh call, no brow 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-code:feedback --confirm') + expect(text).toContain('/altimate-feedback --confirm') expect(calls).toEqual([]) }) diff --git a/plugins/altimate-code/hooks/feedback.ts b/plugins/altimate-code/hooks/feedback.ts index d4bf486..4273bea 100644 --- a/plugins/altimate-code/hooks/feedback.ts +++ b/plugins/altimate-code/hooks/feedback.ts @@ -1,4 +1,4 @@ -// `/altimate-code:feedback `: drafts a GitHub issue for this plugin's repository from the +// `/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. @@ -17,7 +17,7 @@ import { MAX_RAW_PROBLEM, asVersion, forgetProblem, problemNoted, type DoctorFac import { pluginVersion } from './usage' export const REPO = 'AltimateAI/altimate-claude-plugin' -export const COMMAND = 'feedback' +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 @@ -218,7 +218,7 @@ export function buildDraft(facts: Facts, description: string): Draft { '', '---', '', - '**Environment** (added by `/altimate-code:feedback`; nothing else is attached)', + '**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'}`, @@ -337,7 +337,7 @@ let sending = false let settings: PluginOptions = {} const usage = `Say what happened, in your own words: - /altimate-code:feedback + /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 { @@ -350,8 +350,8 @@ function preview(draft: Draft): string { draft.body, '', '---', - `Create it: /altimate-code:feedback ${CONFIRM} (uses gh when it is installed and signed in, else gives a prefilled link)`, - `Discard it: /altimate-code:feedback ${CANCEL} · Change it: run the command again with new text`, + `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') } @@ -364,7 +364,7 @@ export async function answer($: EngineInterface, args: string): Promise 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-code:feedback .` + 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 pending = null From 3e05fb46c01f23c033206ff0725fb0d62f26fd5a Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 20 Nov 2026 22:18:45 +0530 Subject: [PATCH 03/14] fix: keep only the error type and code of the last plugin error, redact the description before cutting it, and drop a draft that is discarded while it is built Co-Authored-By: Claude Sonnet 5.5 --- PRIVACY.md | 2 +- plugins/altimate-code/CHANGELOG.md | 2 +- plugins/altimate-code/README.md | 2 +- plugins/altimate-code/hooks/dbt-mods.tsx | 2 +- plugins/altimate-code/hooks/feedback.test.tsx | 97 +++++++++++++------ plugins/altimate-code/hooks/feedback.ts | 97 +++++++------------ plugins/altimate-code/hooks/last-problem.ts | 39 ++++++-- 7 files changed, 141 insertions(+), 100 deletions(-) diff --git a/PRIVACY.md b/PRIVACY.md index f6bd486..70b47a6 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -113,7 +113,7 @@ Each event carries the step and the Claude Code session id (`claude:`) only: `/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 secrets and home-folder paths 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 last error the plugin met, redacted: the dbt profile's secret values, tokens, passwords, connection-string credentials, file paths, lines that look like SQL, and relation and model names are removed, and the text is cut to a few short lines. No file paths, SQL, or project, model or column names are collected; if you write them in your description they are included, so check the draft. +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`. diff --git a/plugins/altimate-code/CHANGELOG.md b/plugins/altimate-code/CHANGELOG.md index 37470dc..8ce87e6 100644 --- a/plugins/altimate-code/CHANGELOG.md +++ b/plugins/altimate-code/CHANGELOG.md @@ -14,7 +14,7 @@ All notable changes to this plugin will be documented in this file. - **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 last plugin error, redacted (secrets, paths, SQL and relation and model names removed); `--cancel` discards the draft. +- `/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 diff --git a/plugins/altimate-code/README.md b/plugins/altimate-code/README.md index 2c80a6a..b7fd390 100644 --- a/plugins/altimate-code/README.md +++ b/plugins/altimate-code/README.md @@ -164,7 +164,7 @@ When Claude mentions `altimate-dbt`, it is the dbt command line that comes with 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 last error the plugin met, redacted first: the dbt profile's secret values, tokens and passwords, connection-string credentials, every file path (home-folder paths included), lines that look like SQL, and relation and model names are cut out, to at most six short lines. Without that flag no error text is attached. Your own words get the secrets and home-folder paths cut out too; the rest is as you wrote it, so leave out what you do not want public: the repository's issues are public. +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. diff --git a/plugins/altimate-code/hooks/dbt-mods.tsx b/plugins/altimate-code/hooks/dbt-mods.tsx index 6510fe6..3b9b1a0 100644 --- a/plugins/altimate-code/hooks/dbt-mods.tsx +++ b/plugins/altimate-code/hooks/dbt-mods.tsx @@ -762,7 +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, names) + 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 } diff --git a/plugins/altimate-code/hooks/feedback.test.tsx b/plugins/altimate-code/hooks/feedback.test.tsx index a09db3f..53c8aab 100644 --- a/plugins/altimate-code/hooks/feedback.test.tsx +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -2,8 +2,8 @@ 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, cleanProblem, issueUrl, redactSecrets, titleOf, withoutHome, type Facts } from './feedback' -import { doctorFacts } from './last-problem' +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' @@ -61,9 +61,9 @@ test('the title is the first line of the description, one line, at most 80 chara expect(long.endsWith('…')).toBe(true) }) -test('the last plugin error is a fenced block, labelled redacted, and cannot close its fence', () => { - const draft = buildDraft(facts({ problem: { source: 'dbt run failed', text: "boom ''' end" } }), 'x') - expect(draft.body).toContain('**Last plugin error** (dbt run failed; redacted)\n\n```text\nboom \'\'\' end\n```') +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) }) @@ -103,11 +103,10 @@ test('tokens, passwords, connection-string credentials and keys are cut out of a 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 and the error', () => { +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') - expect(cleanProblem('Database Error: login wh-pa55-phrase refused', [HOME])).not.toContain('wh-pa55-phrase') } finally { clearRedactions() } @@ -128,34 +127,58 @@ test('the description keeps the person\'s own words but loses secrets and home p expect(cleanDescription('a\u0000b\u001b[31mc\r\nd', [HOME])).toBe('ab[31mc\nd') }) -test('an error is reduced: paths, SQL, relation and node names, secrets and home folders are all gone, in few short lines', () => { +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.`, - ' select order_id, secret_column from raw.orders where token = abc', - ' compiled code at /private/tmp/target/run/acme/fct_orders.sql', - ` config ${HOME}/.dbt/settings.json password: p4ssw0rd`, - ' relation "analytics"."marts"."fct_orders" missing', - ...Array.from({ length: 20 }, (_, i) => `extra line ${i}`), + " 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 = cleanProblem(raw, [HOME], ['fct_orders']) - for (const leaked of [ROOT, HOME, 'fct_orders', 'ACME_DB', 'RAW.ORDERS', 'secret_column', 'raw.orders', 'p4ssw0rd', '/private/tmp', 'analytics', 'marts']) expect(out).not.toContain(leaked) - expect(out).toContain('') - expect(out).toContain(' { +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('') + 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 { - const out = cleanProblem(`${'x '.repeat(3990)}sup3r-long-warehouse-sec`, [HOME]) - expect(out).not.toContain('sup3r') + 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 and C:\\Users\\Alice\\Client Files\\y.sql', ['C:\\Users\\Alice'])).toBe(' and ') +}) + // ─── The link ───────────────────────────────────────────────────────────────────────────────────────── test('the link is the new-issue page with the title and body URL-encoded, and decodes back to them', () => { @@ -199,7 +222,7 @@ type Gh = { createTimesOut?: boolean } -async function start($: any, on: any, options: { registerError?: string; gh?: Gh; env?: Record; platform?: string; claude?: string } = {}) { +async function start($: any, on: any, options: { holdVersion?: Promise; 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 ?? {} @@ -207,7 +230,10 @@ async function start($: any, on: any, options: { registerError?: string; gh?: Gh 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', () => ({ value: { version: options.claude ?? '2.1.329' } })) + 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 })) @@ -446,17 +472,28 @@ test('--with-error with no error recorded says so and attaches nothing', async ( expect(shownBody(text)).not.toContain('Last plugin error') }) -test('the last plugin error is attached only with --with-error, redacted, and without the file, model or relation names', async ($, on) => { +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** (') - expect(body).toContain('failed; redacted)') - expect(body).toContain('ENOENT: no such file ') - for (const leaked of [HOME, 'manifest.json', 'ACME.RAW.ORDERS', 'ghp_abc']) expect(body).not.toContain(leaked) + 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 new session starts with no draft', async ($, on) => { diff --git a/plugins/altimate-code/hooks/feedback.ts b/plugins/altimate-code/hooks/feedback.ts index 4273bea..8cb80ac 100644 --- a/plugins/altimate-code/hooks/feedback.ts +++ b/plugins/altimate-code/hooks/feedback.ts @@ -11,9 +11,9 @@ import type { EngineInterface, On, PluginOptions } from 'claude-code' import { MISSING_BINARY, parseVersion } from './altimate-cli' -import { redactValues, scrubDbt, withoutValueFragment } from './dbt-mods-core' +import { redactValues } from './dbt-mods-core' import { dbtModsDoctorFacts } from './dbt-mods' -import { MAX_RAW_PROBLEM, asVersion, forgetProblem, problemNoted, type DoctorFacts } from './last-problem' +import { asVersion, forgetProblem, problemNoted, type DoctorFacts } from './last-problem' import { pluginVersion } from './usage' export const REPO = 'AltimateAI/altimate-claude-plugin' @@ -23,8 +23,6 @@ export const LABEL = 'feedback' export const MAX_URL = 7000 export const MAX_DESCRIPTION = 4000 export const MAX_TITLE = 80 -export const MAX_PROBLEM_CHARS = 600 -export const MAX_PROBLEM_LINES = 6 const DRY_RUN_ENV = 'ALTIMATE_FEEDBACK_DRY_RUN' const CLI_NAMES = ['altimate', 'altimate-code'] as const const CONFIRM = '--confirm' @@ -50,7 +48,8 @@ const SECRET_PATTERNS: Array<[RegExp, string]> = [ [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, MASK], [/\beyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{4,}/g, MASK], [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, MASK], - [/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi, `Bearer ${MASK}`], + [/\b((?:proxy-)?authorization["']?\s*[:=])[^\n]*/gi, `$1 ${MASK}`], + [/\b(Bearer|Basic|Digest|Token)\s+[A-Za-z0-9._~+/=-]{8,}/g, `$1 ${MASK}`], // user:password@host in a connection string or URL. [/(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]*:[^\s/@]+@/gi, `$1${MASK}@`], [/\b((?:pass(?:word|wd)?|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret|authorization)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|\S+)/gi, `$1${MASK}`], @@ -79,63 +78,34 @@ function homeForms(homes: readonly string[]): string[] { return [...forms].sort((a, b) => b.length - a.length) } -/** Every path under the home folder, however long, replaced whole. */ -export function withoutHome(text: string, homes: readonly string[]): string { - return homeForms(homes).reduce((out, form) => out.replace(new RegExp(`${escapeRegex(form)}(?:[\\\\/][^\\s'"\`<>()]*)?`, 'gi'), ''), text) -} - -/** Every absolute path of two or more parts (a POSIX path, `~/…`, or a drive path), replaced whole. */ -export function withoutPaths(text: string): string { - return text - .replace(/(?()]+/g, '') - .replace(/(?()/]+\/[^\s'"`<>()]*/g, '') - .replace(/\b[A-Za-z]:\\[^\s'"`<>()]+/g, '') -} +const PATH_SEGMENT = `[^\\s'"\`<>()\\\\/]` +// The rest of a path after its home folder: segments, and a space inside one when a separator follows within three 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,2}${PATH_SEGMENT}+[\\\\/])${PATH_SEGMENT}+)*)*` -const SQL_LINE = /\b(?:select\b[^\n]*\bfrom\b|insert\s+into|delete\s+from|create\s+(?:or\s+replace\s+)?(?:temp(?:orary)?\s+)?(?:table|view)|merge\s+into|update\s+\S+\s+set|alter\s+table|drop\s+(?:table|view))\b|^\s*(?:select|with|from|where|join|(?:left|right|inner|outer|cross|full)\s+join|group\s+by|order\s+by|having|union|limit\s+\d+|on)\b\s*\S/i - -/** A line that reads as SQL is replaced by a fixed line; a dbt or warehouse error often quotes the statement. */ -export function withoutSql(text: string): string { - return text - .split('\n') - .map(line => (SQL_LINE.test(line) ? '' : line)) - .join('\n') -} - -/** Quoted or three-part relation names (`db.schema.table`, `"RAW"."ORDERS"`) and the names given. */ -function withoutNames(text: string, names: readonly string[]): string { - let out = text - for (const name of [...names].filter(one => one.length >= 2).sort((a, b) => b.length - a.length)) { - out = out.replace(new RegExp(`(?') - } - return out - .replace(/(["'`])[A-Za-z_][\w$]*(?:\.[A-Za-z_][\w$]*){1,2}\1/g, '') - .replace(/(?:"[\w$ -]+"|`[\w$ -]+`)(?:\.(?:"[\w$ -]+"|`[\w$ -]+`)){1,2}/g, '') - .replace(/\b[A-Za-z_][\w$]*\.[A-Za-z_][\w$]*\.[A-Za-z_][\w$]*\b/g, '') +/** Every path under the home folder replaced whole: a quoted one up to its closing quote, an unquoted one with the spaces inside its folder names. */ +export function withoutHome(text: string, homes: readonly string[]): string { + return homeForms(homes).reduce((out, form) => { + const home = escapeRegex(form) + return out + .replace(new RegExp(`(["'\`])${home}[^"'\`\\n]*\\1`, 'gi'), '$1$1') + .replace(new RegExp(`${home}${PATH_TAIL}`, 'gi'), '') + }, text) } 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 most of a description that is read: the rest is cut before anything is matched against it. */ +const MAX_READ = 100_000 -/** What the person typed, as it will be filed: secrets and home-folder paths out, cut to length. Their own words are otherwise kept. */ +/** + * 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 cut = Array.from(plain(text).trim()).slice(0, MAX_DESCRIPTION).join('') - return withoutHome(redactSecrets(withoutValueFragment(cut)), homes) -} - -/** A plugin error as it may be filed: nothing the plugin has not redacted or reduced, in at most a few short lines. */ -export function cleanProblem(raw: string, homes: readonly string[], names: readonly string[] = []): string { - const capped = withoutValueFragment(plain(raw).slice(0, MAX_RAW_PROBLEM)) - const clean = withoutNames(withoutPaths(withoutSql(withoutHome(redactSecrets(scrubDbt(capped)), homes))), names) - const lines = clean - .split('\n') - .map(line => line.trim()) - .filter(Boolean) - .slice(0, MAX_PROBLEM_LINES) - const joined = Array.from(lines.join('\n')).slice(0, MAX_PROBLEM_CHARS).join('') - // The text sits in a code fence: nothing in it may close the fence. - return joined.replace(/`{3,}/g, "'''") + const clean = withoutHome(redactSecrets(plain(text).trim().slice(0, MAX_READ)), homes) + return Array.from(clean.trim()).slice(0, MAX_DESCRIPTION).join('') } // ─── The facts ──────────────────────────────────────────────────────────────────────────────────────── @@ -178,7 +148,7 @@ 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, homes] = await Promise.all([ + const [plugin, altimate, claudeCode, os] = await Promise.all([ pluginVersion($).catch(() => 'unknown'), altimateFacts($).catch(() => null), $.session @@ -189,16 +159,14 @@ export async function collectFacts($: EngineInterface, ask: Ask, extra: { doctor .info() .then(info => (OS.has(info.platform) ? info.platform : 'unknown')) .catch(() => 'unknown'), - homesOf($), ]) 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 noted = problemNoted() - const problem = ask.withProblem && noted ? { source: noted.source, text: cleanProblem(noted.raw, homes, noted.names) } : null - return { plugin, altimate, claudeCode, os, doctor: extra.doctor, settings, problem: problem && problem.text ? problem : null } + const problem = ask.withProblem ? problemNoted() : null + return { plugin, altimate, claudeCode, os, doctor: extra.doctor, settings, problem } } // ─── The draft ──────────────────────────────────────────────────────────────────────────────────────── @@ -230,7 +198,7 @@ export function buildDraft(facts: Facts, description: string): Draft { 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}; redacted)`, '', '```text', facts.problem.text, '```') + 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 } } @@ -333,6 +301,8 @@ export async function send($: EngineInterface, draft: Draft): Promise { // ─── 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 = {} @@ -360,6 +330,7 @@ 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.' } @@ -367,6 +338,7 @@ export async function answer($: EngineInterface, args: string): Promise 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 { @@ -378,8 +350,11 @@ export async function answer($: EngineInterface, args: string): Promise 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 + const mine = ++epoch 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) @@ -393,12 +368,14 @@ export function registerFeedback(on: On, context: { options: PluginOptions }) { /** 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 index 7ed2bc6..3c54e86 100644 --- a/plugins/altimate-code/hooks/last-problem.ts +++ b/plugins/altimate-code/hooks/last-problem.ts @@ -1,13 +1,40 @@ // 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 raw problem text kept in memory, before it is redacted and cut. */ -export const MAX_RAW_PROBLEM = 8000 +// 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|process|session|ui|fs|env|store|state|prompt|clock|plugin|mcp|tool)\.[a-z]+`, + 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 -let lastProblem: { source: string; raw: string; names: string[] } | null = null +/** 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"), `raw` the error, `names` the nodes it is about. */ -export function noteProblem(source: string, raw: string, names: readonly string[] = []): void { - lastProblem = { source: source.slice(0, 80), raw: String(raw).slice(0, MAX_RAW_PROBLEM), names: names.slice(0, 20) } +/** + * 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. */ From 40d438a59d2502867554d53be517e95c27320bae Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 20 Nov 2026 22:29:31 +0530 Subject: [PATCH 04/14] fix: list the host calls an error may name, refuse an over-long description instead of cutting it, clear the shown draft while a replacement is built, and redact JSON-escaped home paths Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/feedback.test.tsx | 54 +++++++++++++++++-- plugins/altimate-code/hooks/feedback.ts | 12 +++-- plugins/altimate-code/hooks/last-problem.ts | 2 +- 3 files changed, 61 insertions(+), 7 deletions(-) diff --git a/plugins/altimate-code/hooks/feedback.test.tsx b/plugins/altimate-code/hooks/feedback.test.tsx index 53c8aab..1f4e29e 100644 --- a/plugins/altimate-code/hooks/feedback.test.tsx +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -146,6 +146,8 @@ test('an error is kept as its type, code and fixed phrases only: no part of its 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) @@ -222,7 +224,7 @@ type Gh = { createTimesOut?: boolean } -async function start($: any, on: any, options: { holdVersion?: Promise; registerError?: string; gh?: Gh; env?: Record; platform?: string; claude?: string } = {}) { +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 ?? {} @@ -231,7 +233,7 @@ async function start($: any, on: any, options: { holdVersion?: Promise; re 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 + await options.holdVersion?.() return { value: { version: options.claude ?? '2.1.329' } } }) on('session.start', (_: unknown, e: { cwd: string }) => ({ cwd: e.cwd })) @@ -487,7 +489,7 @@ test('the last plugin error is attached only with --with-error, as its type and 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 { run, creates } = await start($, on, { holdVersion: () => held }) const building = run('slow draft') await run('--cancel') release() @@ -496,6 +498,52 @@ test('a draft still being built when it is discarded, or when the session ends, 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 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') diff --git a/plugins/altimate-code/hooks/feedback.ts b/plugins/altimate-code/hooks/feedback.ts index 8cb80ac..9718dc4 100644 --- a/plugins/altimate-code/hooks/feedback.ts +++ b/plugins/altimate-code/hooks/feedback.ts @@ -74,6 +74,9 @@ function homeForms(homes: readonly string[]): string[] { 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) } @@ -96,15 +99,15 @@ export function withoutHome(text: string, homes: readonly string[]): string { 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 most of a description that is read: the rest is cut before anything is matched against it. */ -const MAX_READ = 100_000 +/** 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 = withoutHome(redactSecrets(plain(text).trim().slice(0, MAX_READ)), homes) + const clean = withoutHome(redactSecrets(plain(text).trim()), homes) return Array.from(clean.trim()).slice(0, MAX_DESCRIPTION).join('') } @@ -350,6 +353,9 @@ export async function answer($: EngineInterface, args: string): Promise 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 + if (description.length > MAX_INPUT) return `That is too long (over ${MAX_INPUT} characters). Say it shorter; nothing was drafted or sent.` + // The draft shown before is gone from this moment: a confirmation while this one is being built sends nothing. + pending = null const mine = ++epoch const homes = await homesOf($) const facts = await collectFacts($, { withProblem }, { doctor: await dbtModsDoctorFacts($).catch(() => null), settings }) diff --git a/plugins/altimate-code/hooks/last-problem.ts b/plugins/altimate-code/hooks/last-problem.ts index 3c54e86..312d310 100644 --- a/plugins/altimate-code/hooks/last-problem.ts +++ b/plugins/altimate-code/hooks/last-problem.ts @@ -10,7 +10,7 @@ const KNOWN_TOKENS = [ 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|process|session|ui|fs|env|store|state|prompt|clock|plugin|mcp|tool)\.[a-z]+`, + 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') From 35c8d9b4ec396923ede4d574412101dbf0be823f Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 20 Nov 2026 22:43:04 +0530 Subject: [PATCH 05/14] fix: redact quoted values and quoted home paths up to their own closing quote, and clear the shown draft before a refused replacement Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/feedback.test.tsx | 33 +++++++++++++++++++ plugins/altimate-code/hooks/feedback.ts | 15 +++++---- 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/plugins/altimate-code/hooks/feedback.test.tsx b/plugins/altimate-code/hooks/feedback.test.tsx index 1f4e29e..4463080 100644 --- a/plugins/altimate-code/hooks/feedback.test.tsx +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -534,6 +534,39 @@ test('a description at the read limit is redacted whole and quickly, whatever sh 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('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` }) diff --git a/plugins/altimate-code/hooks/feedback.ts b/plugins/altimate-code/hooks/feedback.ts index 9718dc4..4dd1421 100644 --- a/plugins/altimate-code/hooks/feedback.ts +++ b/plugins/altimate-code/hooks/feedback.ts @@ -52,7 +52,7 @@ const SECRET_PATTERNS: Array<[RegExp, string]> = [ [/\b(Bearer|Basic|Digest|Token)\s+[A-Za-z0-9._~+/=-]{8,}/g, `$1 ${MASK}`], // user:password@host in a connection string or URL. [/(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]*:[^\s/@]+@/gi, `$1${MASK}@`], - [/\b((?:pass(?:word|wd)?|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret|authorization)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|\S+)/gi, `$1${MASK}`], + [/\b((?:pass(?:word|wd)?|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret|authorization)["']?\s*[:=]\s*)(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\S+)/gi, `$1${MASK}`], // A long unbroken run of key-like characters. [/\b(?=[A-Za-z0-9_+-]*\d)[A-Za-z0-9_+-]{40,}={0,2}/g, MASK], ] @@ -81,17 +81,18 @@ function homeForms(homes: readonly string[]): string[] { return [...forms].sort((a, b) => b.length - a.length) } -const PATH_SEGMENT = `[^\\s'"\`<>()\\\\/]` +const PATH_SEGMENT = `(?:[^\\s'"\`<>()\\\\/]|'(?=[A-Za-z0-9]))` // The rest of a path after its home folder: segments, and a space inside one when a separator follows within three 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,2}${PATH_SEGMENT}+[\\\\/])${PATH_SEGMENT}+)*)*` +const PATH_TAIL = `(?:[\\\\/]${PATH_SEGMENT}*(?: (?=(?:${PATH_SEGMENT}+ ){0,7}${PATH_SEGMENT}+[\\\\/])${PATH_SEGMENT}+)*)*` /** Every path under the home folder replaced whole: a quoted one up to its closing quote, an unquoted one with the spaces inside its folder names. */ export function withoutHome(text: string, homes: readonly string[]): string { return homeForms(homes).reduce((out, form) => { const home = escapeRegex(form) - return out - .replace(new RegExp(`(["'\`])${home}[^"'\`\\n]*\\1`, 'gi'), '$1$1') + // A quoted path runs to its own closing quote (a quote of another kind, or an escaped one, is part of the name). + return ['"', "'", '`'] + .reduce((text, quote) => text.replace(new RegExp(`${quote}${home}(?:[^${quote}\\n\\\\]|\\\\.)*${quote}`, 'gi'), `${quote}${quote}`), out) .replace(new RegExp(`${home}${PATH_TAIL}`, 'gi'), '') }, text) } @@ -353,10 +354,10 @@ export async function answer($: EngineInterface, args: string): Promise 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 - if (description.length > MAX_INPUT) return `That is too long (over ${MAX_INPUT} characters). Say it shorter; nothing was drafted or sent.` - // The draft shown before is gone from this moment: a confirmation while this one is being built sends nothing. + // 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. From 58f66bbd29e93fbe7e6ed48966a756f47bad175e Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 20 Nov 2026 22:52:19 +0530 Subject: [PATCH 06/14] fix: redact prefixed credential keys, YAML block and doubled-quote values, ~/ paths and parenthesised folder names Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/dbt-mods-core.ts | 2 ++ plugins/altimate-code/hooks/feedback.test.tsx | 34 +++++++++++++++++++ plugins/altimate-code/hooks/feedback.ts | 14 +++++--- 3 files changed, 45 insertions(+), 5 deletions(-) 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/feedback.test.tsx b/plugins/altimate-code/hooks/feedback.test.tsx index 4463080..2a550d8 100644 --- a/plugins/altimate-code/hooks/feedback.test.tsx +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -567,6 +567,40 @@ test('a description that is refused as too long, or empty after the flag, leaves 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 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` }) diff --git a/plugins/altimate-code/hooks/feedback.ts b/plugins/altimate-code/hooks/feedback.ts index 4dd1421..256c85e 100644 --- a/plugins/altimate-code/hooks/feedback.ts +++ b/plugins/altimate-code/hooks/feedback.ts @@ -52,7 +52,10 @@ const SECRET_PATTERNS: Array<[RegExp, string]> = [ [/\b(Bearer|Basic|Digest|Token)\s+[A-Za-z0-9._~+/=-]{8,}/g, `$1 ${MASK}`], // user:password@host in a connection string or URL. [/(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]*:[^\s/@]+@/gi, `$1${MASK}@`], - [/\b((?:pass(?:word|wd)?|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret|authorization)["']?\s*[:=]\s*)(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\S+)/gi, `$1${MASK}`], + // A key that names a credential (DBT_PASSWORD, access_token, client_secret…), then its value: a YAML block scalar with its indented lines, + // a quoted value to its own closing quote (a backslash escape or a doubled quote is inside it), or the rest of the word. + [/((?][+-]?\d?[ \t]*(?:\r?\n[ \t]+[^\n]*)+/gi, `$1${MASK}`], + [/((? b.length - a.length) } -const PATH_SEGMENT = `(?:[^\\s'"\`<>()\\\\/]|'(?=[A-Za-z0-9]))` +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 three 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 replaced whole: a quoted one up to its closing quote, an unquoted one with the spaces inside its folder names. */ +/** Every path under the home folder, and every `~/…` path, replaced whole: a quoted one up to its closing quote, an unquoted one with the spaces inside its folder names. */ export function withoutHome(text: string, homes: readonly string[]): string { - return homeForms(homes).reduce((out, form) => { - const home = escapeRegex(form) + // `~` stands for the home folder whoever the user is, so it counts only before a separator. + const forms = [...homeForms(homes).map(form => escapeRegex(form)), '(? { // A quoted path runs to its own closing quote (a quote of another kind, or an escaped one, is part of the name). return ['"', "'", '`'] .reduce((text, quote) => text.replace(new RegExp(`${quote}${home}(?:[^${quote}\\n\\\\]|\\\\.)*${quote}`, 'gi'), `${quote}${quote}`), out) From a19061ff4530e46c7e6cda3b8c6ae9f4be847d0d Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 20 Nov 2026 23:06:43 +0530 Subject: [PATCH 07/14] fix: cut a YAML block scalar under a credential key whole, comments and blank lines included Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/feedback.test.tsx | 8 +++++ plugins/altimate-code/hooks/feedback.ts | 30 ++++++++++++++++--- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/plugins/altimate-code/hooks/feedback.test.tsx b/plugins/altimate-code/hooks/feedback.test.tsx index 2a550d8..a516991 100644 --- a/plugins/altimate-code/hooks/feedback.test.tsx +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -582,6 +582,14 @@ test('credential keys with a prefix or suffix (DBT_PASSWORD, access_token), YAML 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 profile value that YAML writes with doubled apostrophes is cut out too', () => { setRedactions(ROOT, ["alpha'omega-secret"]) try { diff --git a/plugins/altimate-code/hooks/feedback.ts b/plugins/altimate-code/hooks/feedback.ts index 256c85e..e2d995c 100644 --- a/plugins/altimate-code/hooks/feedback.ts +++ b/plugins/altimate-code/hooks/feedback.ts @@ -40,6 +40,29 @@ const SETTINGS: ReadonlyArray = [ // ─── Redaction ──────────────────────────────────────────────────────────────────────────────────────── const MASK = '‹redacted›' +// A line that ends in a credential key with a YAML block-scalar header (`password: |`, `secret: >- # note`): the value is the indented lines after it. +const BLOCK_HEADER = /^([ \t]*(?:-[ \t]+)?[\w.-]*?(?:pass(?:word|wd|phrase)?|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|credential|cookie|session[_-]?id|authorization)s?["']?[ \t]*:[ \t]*)[|>][+-]?\d?[ \t]*(?:#.*)?$/i + +/** Cuts out the indented lines (blank ones between them too) that follow a credential key's YAML block-scalar header. */ +export function redactBlockScalars(text: string): string { + const lines = text.split('\n') + const out: string[] = [] + for (let i = 0; i < lines.length; i++) { + const header = BLOCK_HEADER.exec(lines[i]!.replace(/\r$/, '')) + if (!header) { + out.push(lines[i]!) + continue + } + out.push(`${header[1]}${MASK}`) + let end = i + for (let next = i + 1; next < lines.length; next++) { + if (/^[ \t]+\S/.test(lines[next]!)) end = next + else if (!/^[ \t]*\r?$/.test(lines[next]!)) break + } + i = end + } + return out.join('\n') +} const SECRET_PATTERNS: Array<[RegExp, string]> = [ [/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g, MASK], [/\bgithub_pat_[A-Za-z0-9_]{20,}/g, MASK], @@ -52,9 +75,8 @@ const SECRET_PATTERNS: Array<[RegExp, string]> = [ [/\b(Bearer|Basic|Digest|Token)\s+[A-Za-z0-9._~+/=-]{8,}/g, `$1 ${MASK}`], // user:password@host in a connection string or URL. [/(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]*:[^\s/@]+@/gi, `$1${MASK}@`], - // A key that names a credential (DBT_PASSWORD, access_token, client_secret…), then its value: a YAML block scalar with its indented lines, - // a quoted value to its own closing quote (a backslash escape or a doubled quote is inside it), or the rest of the word. - [/((?][+-]?\d?[ \t]*(?:\r?\n[ \t]+[^\n]*)+/gi, `$1${MASK}`], + // A key that names a credential (DBT_PASSWORD, access_token, client_secret…), then its value: a quoted value to its own closing quote (a + // backslash escape or a doubled quote is inside it) or the rest of the word. A YAML block scalar is cut whole first (redactBlockScalars). [/((? = [ /** The text with every token, key, password and connection-string credential cut out. */ export function redactSecrets(text: string): string { - return SECRET_PATTERNS.reduce((out, [pattern, to]) => out.replace(pattern, to), redactValues(text)) + return SECRET_PATTERNS.reduce((out, [pattern, to]) => out.replace(pattern, to), redactBlockScalars(redactValues(text))) } const escapeRegex = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') From a7099ac728ee8407736707c7bf43d259749f4039 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 20 Nov 2026 23:12:39 +0530 Subject: [PATCH 08/14] fix: cut YAML credentials under quoted keys and plain multi-word values whole Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/feedback.test.tsx | 7 +++++++ plugins/altimate-code/hooks/feedback.ts | 15 ++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/plugins/altimate-code/hooks/feedback.test.tsx b/plugins/altimate-code/hooks/feedback.test.tsx index a516991..1ed8441 100644 --- a/plugins/altimate-code/hooks/feedback.test.tsx +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -590,6 +590,13 @@ test('a YAML block scalar under a credential key is cut whole: comments on its h 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('a profile value that YAML writes with doubled apostrophes is cut out too', () => { setRedactions(ROOT, ["alpha'omega-secret"]) try { diff --git a/plugins/altimate-code/hooks/feedback.ts b/plugins/altimate-code/hooks/feedback.ts index e2d995c..093e00e 100644 --- a/plugins/altimate-code/hooks/feedback.ts +++ b/plugins/altimate-code/hooks/feedback.ts @@ -41,14 +41,23 @@ const SETTINGS: ReadonlyArray = [ const MASK = '‹redacted›' // A line that ends in a credential key with a YAML block-scalar header (`password: |`, `secret: >- # note`): the value is the indented lines after it. -const BLOCK_HEADER = /^([ \t]*(?:-[ \t]+)?[\w.-]*?(?:pass(?:word|wd|phrase)?|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|credential|cookie|session[_-]?id|authorization)s?["']?[ \t]*:[ \t]*)[|>][+-]?\d?[ \t]*(?:#.*)?$/i +const KEY_LINE = String.raw`^([ \t]*(?:-[ \t]+)?["']?[\w.-]*?(?:pass(?:word|wd|phrase)?|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|credential|cookie|session[_-]?id|authorization)s?["']?[ \t]*:[ \t]*)` +const BLOCK_HEADER = new RegExp(String.raw`${KEY_LINE}[|>][+-]?\d?[ \t]*(?:#.*)?$`, 'i') +// `password: correct horse battery staple`: on a YAML line the value is the rest of the line, spaces and all. +const PLAIN_VALUE = new RegExp(String.raw`${KEY_LINE}(?![|>"'])(\S.*)$`, 'i') -/** Cuts out the indented lines (blank ones between them too) that follow a credential key's YAML block-scalar header. */ +/** Cuts out a YAML value under a credential key: the rest of its line, or the indented lines (blank ones between them too) after a block-scalar header. */ export function redactBlockScalars(text: string): string { const lines = text.split('\n') const out: string[] = [] for (let i = 0; i < lines.length; i++) { - const header = BLOCK_HEADER.exec(lines[i]!.replace(/\r$/, '')) + const line = lines[i]!.replace(/\r$/, '') + const plain = PLAIN_VALUE.exec(line) + if (plain) { + out.push(`${plain[1]}${MASK}`) + continue + } + const header = BLOCK_HEADER.exec(line) if (!header) { out.push(lines[i]!) continue From e13c484df0da139efdab6cb1f95260dd448c8654 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 20 Nov 2026 23:35:12 +0530 Subject: [PATCH 09/14] fix: cut braced and multi-word connection-string passwords and account keys whole Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/feedback.test.tsx | 11 +++++++++++ plugins/altimate-code/hooks/feedback.ts | 6 ++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/plugins/altimate-code/hooks/feedback.test.tsx b/plugins/altimate-code/hooks/feedback.test.tsx index 1ed8441..8494e8c 100644 --- a/plugins/altimate-code/hooks/feedback.test.tsx +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -597,6 +597,17 @@ test('a YAML credential under a quoted key, or with a value of several words, is 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 profile value that YAML writes with doubled apostrophes is cut out too', () => { setRedactions(ROOT, ["alpha'omega-secret"]) try { diff --git a/plugins/altimate-code/hooks/feedback.ts b/plugins/altimate-code/hooks/feedback.ts index 093e00e..a3a1f78 100644 --- a/plugins/altimate-code/hooks/feedback.ts +++ b/plugins/altimate-code/hooks/feedback.ts @@ -41,7 +41,7 @@ const SETTINGS: ReadonlyArray = [ const MASK = '‹redacted›' // A line that ends in a credential key with a YAML block-scalar header (`password: |`, `secret: >- # note`): the value is the indented lines after it. -const KEY_LINE = String.raw`^([ \t]*(?:-[ \t]+)?["']?[\w.-]*?(?:pass(?:word|wd|phrase)?|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|credential|cookie|session[_-]?id|authorization)s?["']?[ \t]*:[ \t]*)` +const KEY_LINE = String.raw`^([ \t]*(?:-[ \t]+)?["']?[\w.-]*?(?:pass(?:word|wd|phrase)?|pwd|secret|token|api[_-]?key|access[_-]?key|account[_-]?key|shared[_-]?access[_-]?key|private[_-]?key|credential|cookie|session[_-]?id|authorization)s?["']?[ \t]*:[ \t]*)` const BLOCK_HEADER = new RegExp(String.raw`${KEY_LINE}[|>][+-]?\d?[ \t]*(?:#.*)?$`, 'i') // `password: correct horse battery staple`: on a YAML line the value is the rest of the line, spaces and all. const PLAIN_VALUE = new RegExp(String.raw`${KEY_LINE}(?![|>"'])(\S.*)$`, 'i') @@ -84,9 +84,11 @@ const SECRET_PATTERNS: Array<[RegExp, string]> = [ [/\b(Bearer|Basic|Digest|Token)\s+[A-Za-z0-9._~+/=-]{8,}/g, `$1 ${MASK}`], // user:password@host in a connection string or URL. [/(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]*:[^\s/@]+@/gi, `$1${MASK}@`], + // A connection string's password: a braced value (ODBC `PWD={a b};`, `}}` is a literal brace) or a value that runs to the next `;`, spaces included. + [/((? Date: Fri, 20 Nov 2026 23:47:49 +0530 Subject: [PATCH 10/14] fix: cut quoted connection-string passwords with a semicolon inside, and a last unquoted one, whole Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/feedback.test.tsx | 7 +++++++ plugins/altimate-code/hooks/feedback.ts | 6 ++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/plugins/altimate-code/hooks/feedback.test.tsx b/plugins/altimate-code/hooks/feedback.test.tsx index 8494e8c..d867bd8 100644 --- a/plugins/altimate-code/hooks/feedback.test.tsx +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -608,6 +608,13 @@ test('connection-string passwords are cut whole: braced, multi-word, and an Azur 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('a profile value that YAML writes with doubled apostrophes is cut out too', () => { setRedactions(ROOT, ["alpha'omega-secret"]) try { diff --git a/plugins/altimate-code/hooks/feedback.ts b/plugins/altimate-code/hooks/feedback.ts index a3a1f78..188b015 100644 --- a/plugins/altimate-code/hooks/feedback.ts +++ b/plugins/altimate-code/hooks/feedback.ts @@ -84,8 +84,10 @@ const SECRET_PATTERNS: Array<[RegExp, string]> = [ [/\b(Bearer|Basic|Digest|Token)\s+[A-Za-z0-9._~+/=-]{8,}/g, `$1 ${MASK}`], // user:password@host in a connection string or URL. [/(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]*:[^\s/@]+@/gi, `$1${MASK}@`], - // A connection string's password: a braced value (ODBC `PWD={a b};`, `}}` is a literal brace) or a value that runs to the next `;`, spaces included. - [/((? Date: Fri, 20 Nov 2026 23:53:42 +0530 Subject: [PATCH 11/14] fix: read credential keys before the profile's own values are cut out, and treat doubled quotes in a quoted connection-string password as part of it Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/feedback.test.tsx | 12 ++++++++++++ plugins/altimate-code/hooks/feedback.ts | 5 +++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/plugins/altimate-code/hooks/feedback.test.tsx b/plugins/altimate-code/hooks/feedback.test.tsx index d867bd8..4dcf22b 100644 --- a/plugins/altimate-code/hooks/feedback.test.tsx +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -615,6 +615,18 @@ test('a quoted password with a semicolon inside, and a last unquoted connection- expect(out).toContain('and more') }) +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 { diff --git a/plugins/altimate-code/hooks/feedback.ts b/plugins/altimate-code/hooks/feedback.ts index 188b015..b932114 100644 --- a/plugins/altimate-code/hooks/feedback.ts +++ b/plugins/altimate-code/hooks/feedback.ts @@ -86,7 +86,7 @@ const SECRET_PATTERNS: Array<[RegExp, string]> = [ [/(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]*:[^\s/@]+@/gi, `$1${MASK}@`], // 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. - [/((? = [ /** The text with every token, key, password and connection-string credential cut out. */ export function redactSecrets(text: string): string { - return SECRET_PATTERNS.reduce((out, [pattern, to]) => out.replace(pattern, to), redactBlockScalars(redactValues(text))) + // The patterns read the text as written, before the profile's own values are cut out: a value that is also a key's name ("password") would hide the key from them. + return redactValues(SECRET_PATTERNS.reduce((out, [pattern, to]) => out.replace(pattern, to), redactBlockScalars(text))) } const escapeRegex = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') From 1e7d008fa5b3bfb86b7be6ac93327f74b4878045 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sat, 21 Nov 2026 00:05:16 +0530 Subject: [PATCH 12/14] fix: find secrets, profile values and home paths in the text as written and cut them in one pass, so no rule can hide another's match Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/feedback.test.tsx | 16 +- plugins/altimate-code/hooks/feedback.ts | 183 ++++++++++++------ 2 files changed, 141 insertions(+), 58 deletions(-) diff --git a/plugins/altimate-code/hooks/feedback.test.tsx b/plugins/altimate-code/hooks/feedback.test.tsx index 4dcf22b..f11a02e 100644 --- a/plugins/altimate-code/hooks/feedback.test.tsx +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -178,7 +178,10 @@ test('a home path with a space in a folder name is replaced whole, quoted or not 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 and C:\\Users\\Alice\\Client Files\\y.sql', ['C:\\Users\\Alice'])).toBe(' and ') + 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 ───────────────────────────────────────────────────────────────────────────────────────── @@ -615,6 +618,17 @@ test('a quoted password with a semicolon inside, and a last unquoted connection- 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('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/) diff --git a/plugins/altimate-code/hooks/feedback.ts b/plugins/altimate-code/hooks/feedback.ts index b932114..a617044 100644 --- a/plugins/altimate-code/hooks/feedback.ts +++ b/plugins/altimate-code/hooks/feedback.ts @@ -11,7 +11,7 @@ import type { EngineInterface, On, PluginOptions } from 'claude-code' import { MISSING_BINARY, parseVersion } from './altimate-cli' -import { redactValues } from './dbt-mods-core' +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' @@ -38,67 +38,97 @@ const SETTINGS: ReadonlyArray = [ ] // ─── 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›' -// A line that ends in a credential key with a YAML block-scalar header (`password: |`, `secret: >- # note`): the value is the indented lines after it. -const KEY_LINE = String.raw`^([ \t]*(?:-[ \t]+)?["']?[\w.-]*?(?:pass(?:word|wd|phrase)?|pwd|secret|token|api[_-]?key|access[_-]?key|account[_-]?key|shared[_-]?access[_-]?key|private[_-]?key|credential|cookie|session[_-]?id|authorization)s?["']?[ \t]*:[ \t]*)` +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') -// `password: correct horse battery staple`: on a YAML line the value is the rest of the line, spaces and all. const PLAIN_VALUE = new RegExp(String.raw`${KEY_LINE}(?![|>"'])(\S.*)$`, 'i') -/** Cuts out a YAML value under a credential key: the rest of its line, or the indented lines (blank ones between them too) after a block-scalar header. */ -export function redactBlockScalars(text: string): string { +/** 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') - const out: string[] = [] + 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 = lines[i]!.replace(/\r$/, '') - const plain = PLAIN_VALUE.exec(line) - if (plain) { - out.push(`${plain[1]}${MASK}`) + 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) { - out.push(lines[i]!) - continue - } - out.push(`${header[1]}${MASK}`) - let end = i + if (!header) continue + let last = i for (let next = i + 1; next < lines.length; next++) { - if (/^[ \t]+\S/.test(lines[next]!)) end = next + if (/^[ \t]+\S/.test(lines[next]!)) last = next else if (!/^[ \t]*\r?$/.test(lines[next]!)) break } - i = end + spans.push({ start: starts[i]! + header[1]!.length, end: starts[last]! + bare(lines[last]!).length, home: false }) + i = last } - return out.join('\n') + return spans } -const SECRET_PATTERNS: Array<[RegExp, string]> = [ - [/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g, MASK], - [/\bgithub_pat_[A-Za-z0-9_]{20,}/g, MASK], - [/\bsk-[A-Za-z0-9_-]{16,}/g, MASK], - [/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, MASK], - [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, MASK], - [/\beyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{4,}/g, MASK], - [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, MASK], - [/\b((?:proxy-)?authorization["']?\s*[:=])[^\n]*/gi, `$1 ${MASK}`], - [/\b(Bearer|Basic|Digest|Token)\s+[A-Za-z0-9._~+/=-]{8,}/g, `$1 ${MASK}`], - // user:password@host in a connection string or URL. - [/(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]*:[^\s/@]+@/gi, `$1${MASK}@`], - // 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. - [/((? out.replace(pattern, to), redactBlockScalars(text))) +/** 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, '\\$&') @@ -121,20 +151,59 @@ function homeForms(homes: readonly string[]): string[] { } 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 three words +// 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, replaced whole: a quoted one up to its closing quote, an unquoted one with the spaces inside its folder names. */ -export function withoutHome(text: string, homes: readonly string[]): string { +/** 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)), '(? { - // A quoted path runs to its own closing quote (a quote of another kind, or an escaped one, is part of the name). - return ['"', "'", '`'] - .reduce((text, quote) => text.replace(new RegExp(`${quote}${home}(?:[^${quote}\\n\\\\]|\\\\.)*${quote}`, 'gi'), `${quote}${quote}`), out) - .replace(new RegExp(`${home}${PATH_TAIL}`, 'gi'), '') - }, text) + for (const home of forms) { + for (const quote of ['"', "'", '`']) { + for (const match of text.matchAll(new RegExp(`${quote}${home}(?:[^${quote}\\n\\\\]|\\\\.)*${quote}`, 'gi'))) spans.push({ start: match.index + 1, end: match.index + match[0].length - 1, home: true }) + } + for (const match of text.matchAll(new RegExp(`${home}${PATH_TAIL}`, 'gi'))) spans.push({ start: match.index, end: match.index + match[0].length, home: true }) + } + return spans +} + +/** The text with every span cut: overlapping and touching spans become one, and say "redacted" unless every part was a home path. */ +function cut(text: string, spans: Span[]): string { + const sorted = spans.filter(span => 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 @@ -148,7 +217,7 @@ export const MAX_INPUT = 100_000 * 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 = withoutHome(redactSecrets(plain(text).trim()), homes) + const clean = redactAll(plain(text).trim(), homes) return Array.from(clean.trim()).slice(0, MAX_DESCRIPTION).join('') } @@ -284,7 +353,7 @@ async function openLink($: EngineInterface, url: string): Promise { /** A reason gh gave, in one short line: secrets and home-folder paths out. */ async function reasonOf($: EngineInterface, text: string): Promise { - return firstLine(withoutHome(redactSecrets(text), await homesOf($))) + return firstLine(redactAll(text, await homesOf($))) } async function linkAnswer($: EngineInterface, draft: Draft, lead: string, dry: boolean): Promise { From 64bcac7a499e3578407ff75f48915442fa757777 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sat, 21 Nov 2026 00:13:58 +0530 Subject: [PATCH 13/14] fix: cut a password inside a JSON string that is escaped one or more times Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/feedback.test.tsx | 6 ++++++ plugins/altimate-code/hooks/feedback.ts | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/plugins/altimate-code/hooks/feedback.test.tsx b/plugins/altimate-code/hooks/feedback.test.tsx index f11a02e..1884bdc 100644 --- a/plugins/altimate-code/hooks/feedback.test.tsx +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -629,6 +629,12 @@ test('the rules read the text as written: a profile value that is a key name or } }) +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('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/) diff --git a/plugins/altimate-code/hooks/feedback.ts b/plugins/altimate-code/hooks/feedback.ts index a617044..bb41ec2 100644 --- a/plugins/altimate-code/hooks/feedback.ts +++ b/plugins/altimate-code/hooks/feedback.ts @@ -51,7 +51,7 @@ 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 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') @@ -74,7 +74,7 @@ const SECRET_PATTERNS: RegExp[] = [ /((?:^|(?<=;))[ \t]*(?:pwd|password|pass|accountkey|sharedaccesskey)\s*=\s*)[^;\n]*$/gim, // A key that names a credential (DBT_PASSWORD, access_token, client_secret…), then its value: a quoted value to its own closing quote (a // backslash escape or a doubled quote is inside it) or the rest of the word, up to a `;` that starts the next `key=` field. - new RegExp(String.raw`((? Date: Sat, 21 Nov 2026 00:21:54 +0530 Subject: [PATCH 14/14] fix: cut a multi-word password inside JSON strings escaped any number of times Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/feedback.test.tsx | 10 ++++++++++ plugins/altimate-code/hooks/feedback.ts | 4 ++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/plugins/altimate-code/hooks/feedback.test.tsx b/plugins/altimate-code/hooks/feedback.test.tsx index 1884bdc..670a611 100644 --- a/plugins/altimate-code/hooks/feedback.test.tsx +++ b/plugins/altimate-code/hooks/feedback.test.tsx @@ -635,6 +635,16 @@ test('a password inside a JSON string that is itself JSON-escaped is cut whole', 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/) diff --git a/plugins/altimate-code/hooks/feedback.ts b/plugins/altimate-code/hooks/feedback.ts index bb41ec2..c16b195 100644 --- a/plugins/altimate-code/hooks/feedback.ts +++ b/plugins/altimate-code/hooks/feedback.ts @@ -73,8 +73,8 @@ const SECRET_PATTERNS: RegExp[] = [ /((?