From d4e8db6e2e0229d94b0c8077ce74d5393ab27540 Mon Sep 17 00:00:00 2001 From: A-PachecoT Date: Sat, 17 Oct 2026 22:25:39 +0000 Subject: [PATCH] fix(hooks): links band shows the docs a git push publishes and ignores basalt publish inside heredocs (#21, #22) - git push to main in a repo whose workflows run basalt publish: each .md/.mdx it changed under a vault.yaml lands in the band with its /{space}/{slug} URL (the app 307s it to the canonical one; reuses a workspace the band already knows). - isPublish/isGitPush read the command without heredoc bodies and quoted strings, and need basalt/git at the head of a shell segment (VAR=, npx/pnpm/bunx allowed). - one row per doc: flat and canonical URLs of the same doc dedupe. - README described the pre-0.3.2 behaviour (every link that entered the session). Closes #21 Closes #22 --- .claude-plugin/marketplace.json | 4 +- README.md | 10 +- plugins/basalt/.claude-plugin/plugin.json | 2 +- plugins/basalt/hooks/register.tsx | 145 ++++++++++++++++++++-- plugins/basalt/tests/links.test.tsx | 79 +++++++++++- 5 files changed, 221 insertions(+), 19 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 63691a4..f8c3e9a 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -6,14 +6,14 @@ }, "metadata": { "description": "Basalt — the trust layer for AI-generated work. Connect your AI to publish, update and share governed docs by URL.", - "version": "0.3.3" + "version": "0.3.4" }, "plugins": [ { "name": "basalt", "source": "./plugins/basalt", "description": "Connect your AI to Basalt — publish, update and share governed docs by URL. Bundles the Basalt MCP server (OAuth) + a skill that converges on it when you ask to publish or share written work.", - "version": "0.3.3", + "version": "0.3.4", "author": { "name": "Cofoundy SAC" }, diff --git a/README.md b/README.md index 473917e..680ca9f 100644 --- a/README.md +++ b/README.md @@ -126,8 +126,14 @@ a silent hook is worthless if it's silently dead. ## The links band (every doc of the session, one key away) Agents publish docs mid-conversation, and the URL scrolls away with the chat. The band -above the prompt keeps them: every `app.basalt.cofoundy.ai` link that enters the -session — from the CLI, the MCP, the model's own text or a subagent — lands there. +above the prompt keeps the docs the session (or one of its subagents) published, and only +those: the link a `basalt publish`/`basalt move` or an MCP `publish_doc`/`update_doc` +returns, and the docs a `git push` to `main` hands to a vault's publish Action (each +`.md`/`.mdx` the push changed under a `vault.yaml`, in a repo whose workflows run +`basalt publish`). A link the session merely read — in code, a log, an old transcript — +never lands there. A pushed doc gets its `/{space}/{slug}` URL, which the app redirects +to the canonical one; when the band already holds a doc of that space, it uses that +workspace directly.

A Claude Code session where the agent published three docs. Above the prompt, the Basalt band shows the mark, 3 docs and the latest one, architecture-v2, with the buttons Open, Copy and All; a side pane lists every doc of the session with its space, folder and link. diff --git a/plugins/basalt/.claude-plugin/plugin.json b/plugins/basalt/.claude-plugin/plugin.json index bcf09a9..3f105a4 100644 --- a/plugins/basalt/.claude-plugin/plugin.json +++ b/plugins/basalt/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "basalt", "description": "Connect your AI to Basalt — publish, update and share governed docs by URL. Bundles the Basalt MCP server (OAuth), a skill that converges on it when you ask to publish or share written work, and quiet session hooks (auth probe · edit tracking · publish nudge).", - "version": "0.3.3", + "version": "0.3.4", "author": { "name": "Cofoundy SAC", "url": "https://cofoundy.dev" diff --git a/plugins/basalt/hooks/register.tsx b/plugins/basalt/hooks/register.tsx index 800f866..c468eff 100644 --- a/plugins/basalt/hooks/register.tsx +++ b/plugins/basalt/hooks/register.tsx @@ -29,12 +29,109 @@ const strings = (value: unknown, out: string[] = []): string[] => { return out } +// The command as the shell runs it: heredoc bodies and quoted strings are text the +// command carries (an issue body, a commit message), not commands it runs. +export const commandText = (command: string): string => + command + .replace(/<<-?\s*(['"]?)([A-Za-z_][\w-]*)\1[^\n]*\n[\s\S]*?(?:\n[ \t]*\2[ \t]*(?=\n|$)|$)/g, ' ') + .replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, "''") + +// `basalt …` at the head of a shell segment, after any `VAR=value` and an npx/pnpm/bunx runner. +const AT_HEAD = String.raw`(?:^|[;&|(\n])\s*(?:\w+=\S*\s+)*(?:(?:npx|bunx|pnpm\s+(?:exec\s+|dlx\s+)?)\s*)?` +const BASALT_PUBLISH = new RegExp(AT_HEAD + String.raw`basalt(?:-cli)?\s+(?:publish|move)\b`) +const GIT_PUSH = new RegExp(AT_HEAD + String.raw`git(?:\s+-C\s+\S+)?\s+push\b`) + // The calls that publish: `basalt publish|move` from a shell, `publish_doc|update_doc` over MCP. export const isPublish = (tool: string, command: unknown): boolean => tool === 'Bash' - ? typeof command === 'string' && /(^|[\s;&|(])basalt\s+(publish|move)\b/.test(command) + ? typeof command === 'string' && BASALT_PUBLISH.test(commandText(command)) : /basalt/i.test(tool) && /__(publish_doc|update_doc)$/.test(tool) +export const isGitPush = (command: unknown): boolean => + typeof command === 'string' && GIT_PUSH.test(commandText(command)) + +// The ranges a `git push` moved onto a default branch (" 1a2b3c4..5d6e7f8 main -> main"). +// A new branch, a delete or a push to any other branch publishes nothing: the vault's +// Action publishes on a push to main. +export const pushedRanges = (output: string): { from: string; to: string }[] => + [...output.matchAll(/^\s*\+?\s*([0-9a-f]{7,40})\.\.\.?([0-9a-f]{7,40})\s+\S+\s+->\s+(\S+)/gm)] + .filter(m => m[3] === 'main' || m[3] === 'master') + .map(m => ({ from: m[1] ?? '', to: m[2] ?? '' })) + +// The directory the push ran in: `git -C

push`, else the last `cd ` before it, +// else the session's own (relative paths against it). +export const pushDir = (command: string, cwd: string, home = ''): string => { + const text = commandText(command) + const push = text.match(GIT_PUSH) + const head = push?.index === undefined ? text : text.slice(0, push.index + push[0].length) + const dashC = head.match(/git\s+-C\s+(\S+)\s+push\s*$/) + const cds = [...head.matchAll(/(?:^|[;&|(\n])\s*cd\s+([^\s;&|)]+)/g)] + const dir = dashC?.[1] ?? cds[cds.length - 1]?.[1] + if (!dir) return cwd + const expanded = dir.replace(/^~(?=\/|$)/, home) + + return expanded.startsWith('/') ? expanded : `${cwd.replace(/\/$/, '')}/${expanded}` +} + +// Byte-identical to the CLI's `normalizeSlug` (cli/src/local-docs.ts): the slug IS the +// path relative to the vault root, each segment normalized, the .md/.mdx suffix gone. +const segment = (seg: string) => + seg.normalize('NFD').replace(/\p{M}+/gu, '').toLowerCase() + .replace(/[^a-z0-9_-]+/g, '-').replace(/-+/g, '-').replace(/^-+|-+$/g, '') + +export const normalizeSlug = (relPath: string): string => + relPath.replace(/\.(md|mdx)$/i, '').split(/[\\/]/).map(segment).filter(Boolean).join('/') + +export const vaultName = (yaml: string): string | undefined => + yaml.match(/^name:[ \t]*(.+?)[ \t]*$/m)?.[1]?.replace(/^["']|["']$/g, '').trim() || undefined + +const BASE = 'https://app.basalt.cofoundy.ai' + +// What reading a push needs from outside: git in a directory, a file's text. +export type PushIo = { + git: (dir: string, args: string[]) => Promise<{ exitCode: number; stdout: string }> + read: (path: string) => Promise +} + +// The docs a push to main hands to the vault's publish Action: each .md/.mdx it added or +// changed under a vault.yaml, in a repo whose workflows run `basalt publish`. The URL is +// the flat /{space}/{slug} one: the app sends whoever may read it to the canonical URL, +// and the workspace is not knowable from the repo. +export async function pushedDocs(io: PushIo, dir: string, output: string): Promise<{ url: string; trail: string[]; title: string }[]> { + const ranges = pushedRanges(output) + if (ranges.length === 0) return [] + const top = await io.git(dir, ['rev-parse', '--show-toplevel']) + if (top.exitCode !== 0) return [] + const root = top.stdout.trim() + const docs: { url: string; trail: string[]; title: string }[] = [] + for (const { from, to } of ranges) { + const action = await io.git(root, ['grep', '-l', '-e', 'basalt publish', to, '--', '.github/workflows']) + if (action.exitCode !== 0) continue + const changed = await io.git(root, ['diff', '--name-only', '--diff-filter=AMR', `${from}..${to}`, '--', '*.md', '*.mdx']) + for (const file of changed.stdout.split('\n').filter(Boolean)) { + const parts = file.split('/') + for (let depth = parts.length - 1; depth >= 0; depth--) { + const yaml = await io.read([root, ...parts.slice(0, depth), 'vault.yaml'].join('/')) + if (yaml === undefined) continue + const space = vaultName(yaml) ?? segment(parts[depth - 1] ?? root.split('/').pop() ?? '') + const slug = normalizeSlug(parts.slice(depth).join('/')) + if (space && slug) { + const path = slug.split('/') + docs.push({ url: `${BASE}/${space}/${slug}`, trail: [space, ...path.slice(0, -1)], title: path[path.length - 1] ?? slug }) + } + break + } + } + } + + return docs +} + +const pushIo = ($: EngineInterface): PushIo => ({ + git: (dir, args) => $.process.run(['git', '-C', dir, ...args]).catch(() => ({ exitCode: 1, stdout: '' })), + read: path => $.fs.read(path).then(text => (typeof text === 'string' ? text : undefined), () => undefined), +}) + // Canonical URLs are /{workspace}/{space}/{doc…}; the workspace is always the // same for one person, so the trail starts at the space. export const toLink = (url: string, by: string, at: number): BasaltLink => { @@ -45,6 +142,19 @@ export const toLink = (url: string, by: string, at: number): BasaltLink => { return { url, title, trail: trail.slice(0, -1), by, at } } +// A flat /{space}/{slug} URL turns canonical when the band already holds a doc of that +// space under its workspace (the redirect costs a hop, and a copied link should not). +export const withWorkspace = (link: BasaltLink, list: BasaltLink[]): BasaltLink => { + const flat = new URL(link.url).pathname.split('/').filter(Boolean) + if (flat[0] !== link.trail[0] || flat.length !== link.trail.length + 1) return link + for (const other of list) { + const parts = new URL(other.url).pathname.split('/').filter(Boolean) + if (parts.length >= 3 && parts[1] === flat[0]) return { ...link, url: `${BASE}/${parts[0]}/${flat.join('/')}` } + } + + return link +} + // Rows stored by an earlier version carry no trail. const fresh = (link: BasaltLink) => (Array.isArray(link.trail) ? link : toLink(link.url, link.by, link.at)) @@ -180,21 +290,34 @@ export const register: Register = on => { }) // Only what this session published: the result of a publish, never a link it merely read - // (a subagent grepping old transcripts filled the band with docs nobody made). + // (a subagent grepping old transcripts filled the band with docs nobody made), and the + // docs a push to main hands to the vault's publish Action (no URL ever reaches the session). on('tool.call', async ($, e, next) => { const out = await next(e) - if (!isPublish(e.tool, (e as { command?: unknown }).command) || out.deny !== undefined || out.isError) return out - const found = strings([out.text, out.result]).flatMap(text => text.match(URL_RE) ?? []) + if (out.deny !== undefined || out.isError) return out + const command = (e as { command?: unknown }).command + const publish = isPublish(e.tool, command) + const push = e.tool === 'Bash' && !publish && isGitPush(command) + if (!publish && !push) return out + const text = strings([out.text, out.result]).join('\n') + const found: BasaltLink[] = [] + const by = e.agentId ? 'subagent' : 'session' + const now = await $.clock.now() + if (publish) { + for (const url of new Set((text.match(URL_RE) ?? []).map(url => url.replace(/[.,;:!?]+$/, '')))) + found.push(toLink(url, by, now)) + } else { + const dir = pushDir(command as string, await $.session.cwd(), (await $.env.get('HOME')) ?? '') + for (const doc of await pushedDocs(pushIo($), dir, text).catch(() => [])) found.push({ ...doc, by, at: now }) + } if (found.length > 0) { - const now = await $.clock.now() - const by = e.agentId ? 'subagent' : 'session' + // One doc, one row: a flat /{space}/{slug} and its canonical /{ws}/{space}/{slug} are the same doc. + const key = (link: BasaltLink) => [...link.trail, link.title].join('/') await update($, links, list => { - const known = new Set(list.map(link => link.url)) - const fresh = [...new Set(found.map(url => url.replace(/[.,;:!?]+$/, '')))] - .filter(url => !known.has(url)) - .map(url => toLink(url, by, now)) + const known = new Set(list.map(fresh).map(key)) + const added = found.filter(link => !known.has(key(link)) && known.add(key(link))).map(link => withWorkspace(link, list)) - return [...list, ...fresh] + return [...list, ...added] }) } diff --git a/plugins/basalt/tests/links.test.tsx b/plugins/basalt/tests/links.test.tsx index 8b8e348..9755778 100644 --- a/plugins/basalt/tests/links.test.tsx +++ b/plugins/basalt/tests/links.test.tsx @@ -1,19 +1,21 @@ import { describe, expect, mock, test } from 'claude-code/testing' -import { isPublish } from '../hooks/register' +import { isGitPush, isPublish, normalizeSlug, pushDir, pushedDocs, pushedRanges, vaultName, withWorkspace } from '../hooks/register' +import type { PushIo } from '../hooks/register' const Box = 'Box' as any const URL = 'https://app.basalt.cofoundy.ai/cofoundy/factory/intent/panel' const BAND = { component: 'AbovePrompt', props: { hasSurvey: false, isWorking: false, maxRows: 20 } } as const +const PUSH_OUT = 'To github.com:acme/notes.git\n 1a2b3c4..5d6e7f8 main -> main\n' -function engine(on: any) { +function engine(on: any, output = `ok ${URL}`) { mock.clock(on) mock.store(on) mock.env(on, {}) on('session.start', ($: any, e: any) => ({ cwd: e.cwd })) on('command.register', ($: any, e: any) => ({ value: { command: e.name } })) on('ui.render', () => ) - on('tool.call', () => ({ result: { stdout: `ok ${URL}` }, text: `ok ${URL}` })) + on('tool.call', () => ({ result: { stdout: output }, text: output })) } const band = async ($: any) => { @@ -24,6 +26,18 @@ const band = async ($: any) => { return shown } +// A repo at /r with a vault at /r/vault (name: notes) and, unless told, a workflow that runs `basalt publish`. +const repo = ({ action = true, changed = 'vault/research/Plan Q4.md\nREADME.md\n' } = {}): PushIo => ({ + git: async (dir, args) => { + const line = args.join(' ') + if (line === 'rev-parse --show-toplevel') return { exitCode: dir.startsWith('/r') ? 0 : 128, stdout: '/r\n' } + if (line.startsWith('grep')) return { exitCode: action ? 0 : 1, stdout: '' } + if (line.startsWith('diff --name-only --diff-filter=AMR 1a2b3c4..5d6e7f8')) return { exitCode: 0, stdout: changed } + return { exitCode: 1, stdout: '' } + }, + read: async path => (path === '/r/vault/vault.yaml' ? 'name: notes\npublish: auto\n' : undefined), +}) + describe('links band', () => { test('a link the session only read is not a doc it made', async ($, on) => { engine(on) @@ -37,9 +51,68 @@ describe('links band', () => { expect(await band($)).toBe(true) }) + test('a heredoc that mentions basalt publish is not a publish', async ($, on) => { + engine(on) + await $.tool.call({ tool: 'Bash', command: "gh issue create --body-file - <<'EOF'\nrun basalt publish docs/panel.md\nEOF" } as any) + expect(await band($)).toBe(false) + }) + + test('push output the session merely read is not a push', async ($, on) => { + engine(on, PUSH_OUT) + await $.tool.call({ tool: 'Bash', command: 'cat push.log' } as any) + expect(await band($)).toBe(false) + }) + + test('a push to main of a vault doc is the doc the Action publishes', async () => { + expect(await pushedDocs(repo(), '/r', PUSH_OUT)).toEqual([ + { url: 'https://app.basalt.cofoundy.ai/notes/research/plan-q4', trail: ['notes', 'research'], title: 'plan-q4' }, + ]) + }) + + test('a push that publishes nothing adds nothing', async () => { + expect(await pushedDocs(repo({ action: false }), '/r', PUSH_OUT)).toEqual([]) + expect(await pushedDocs(repo({ changed: 'README.md\ndocs/x.md\n' }), '/r', PUSH_OUT)).toEqual([]) + expect(await pushedDocs(repo(), '/r', ' 1a2b3c4..5d6e7f8 feat/x -> feat/x\n')).toEqual([]) + expect(await pushedDocs(repo(), '/elsewhere', PUSH_OUT)).toEqual([]) + }) + + test('a flat link takes the workspace the band already knows for its space', () => { + const flat = { url: 'https://app.basalt.cofoundy.ai/notes/research/plan-q4', trail: ['notes', 'research'], title: 'plan-q4', by: 'session', at: 1 } + const seen = { url: 'https://app.basalt.cofoundy.ai/acme/notes/old', trail: ['notes'], title: 'old', by: 'session', at: 0 } + expect(withWorkspace(flat, [seen]).url).toBe('https://app.basalt.cofoundy.ai/acme/notes/research/plan-q4') + expect(withWorkspace(flat, []).url).toBe(flat.url) + }) + + test('the slug is the CLI one', () => { + expect(normalizeSlug('research/Plan Q4.md')).toBe('research/plan-q4') + expect(normalizeSlug('Árbol/Ñandú_v2.mdx')).toBe('arbol/nandu_v2') + expect(vaultName('# c\nname: "basalt-pm"\n')).toBe('basalt-pm') + expect(vaultName('publish: auto\n')).toBeUndefined() + }) + + test('which pushes reach main', () => { + expect(pushedRanges(PUSH_OUT)).toEqual([{ from: '1a2b3c4', to: '5d6e7f8' }]) + expect(pushedRanges(' + 1a2b3c4...5d6e7f8 main -> main (forced update)')).toEqual([{ from: '1a2b3c4', to: '5d6e7f8' }]) + expect(pushedRanges(' 1a2b3c4..5d6e7f8 feat/x -> feat/x')).toEqual([]) + expect(pushedRanges(' * [new branch] main -> main')).toEqual([]) + }) + + test('where the push ran', () => { + expect(pushDir('cd /r && git push', '/w')).toBe('/r') + expect(pushDir('cd a; cd b && git push', '/w')).toBe('/w/b') + expect(pushDir('git -C ~/r push origin main', '/w', '/home/x')).toBe('/home/x/r') + expect(pushDir('git push', '/w')).toBe('/w') + expect(isGitPush('cd r && git push -q')).toBe(true) + expect(isGitPush('git commit -m "then git push"')).toBe(false) + }) + test('which calls publish', () => { expect(isPublish('Bash', 'cd vault && basalt publish a.md')).toBe(true) + expect(isPublish('Bash', 'BASALT_BASE_URL=https://x basalt publish a.md')).toBe(true) + expect(isPublish('Bash', 'npx basalt-cli publish a.md')).toBe(true) + expect(isPublish('Bash', "cat > x <<'EOF'\nbasalt publish\nEOF\nbasalt publish x")).toBe(true) expect(isPublish('Bash', 'basalt move p/a p/b')).toBe(true) + expect(isPublish('Bash', 'gh issue create -b "then; basalt publish a.md"')).toBe(false) expect(isPublish('Bash', 'basalt list')).toBe(false) expect(isPublish('Bash', 'cat basalt-publish.log')).toBe(false) expect(isPublish('mcp__plugin_basalt_basalt__publish_doc', undefined)).toBe(true)