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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<p align="center">
<img src="./assets/readme/links-band.svg" width="100%" alt="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.">
Expand Down
2 changes: 1 addition & 1 deletion plugins/basalt/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
145 changes: 134 additions & 11 deletions plugins/basalt/hooks/register.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <dir> push`, else the last `cd <dir>` 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<string | undefined>
}

// 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 => {
Expand All @@ -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))

Expand Down Expand Up @@ -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]
})
}

Expand Down
79 changes: 76 additions & 3 deletions plugins/basalt/tests/links.test.tsx
Original file line number Diff line number Diff line change
@@ -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', () => <Box key="engine" />)
on('tool.call', () => ({ result: { stdout: `ok ${URL}` }, text: `ok ${URL}` }))
on('tool.call', () => ({ result: { stdout: output }, text: output }))
}

const band = async ($: any) => {
Expand All @@ -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)
Expand All @@ -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)
Expand Down
Loading