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.6"
"version": "0.3.7"
},
"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.6",
"version": "0.3.7",
"author": {
"name": "Cofoundy SAC"
},
Expand Down
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,13 @@ a silent hook is worthless if it's silently dead.

Agents publish docs mid-conversation, and the URL scrolls away with the chat. The band
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 —
those: the link a `basalt publish`/`basalt move` returns (however it is run: `npx -y
basalt-cli@…`, `pnpm exec`, a path to the binary; a `--strict` run that exits red still
counts the docs it put up), the MCP tools that leave a doc at a new URL or version
(`publish_doc`, `update_doc`, `edit_doc`, `move_doc`, `restore_version`, `publish_space`,
`publish_vault`), and the docs a `git push` to `main` or a `gh pr merge` into it hands to a
vault's publish Action (each `.md`/`.mdx` it 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.
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.6",
"version": "0.3.7",
"author": {
"name": "Cofoundy SAC",
"url": "https://cofoundy.dev"
Expand Down
140 changes: 104 additions & 36 deletions plugins/basalt/hooks/register.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,47 @@ export const commandText = (command: string): string =>
.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`)
// A command at the head of a shell segment, after any `VAR=value`.
const AT_HEAD = String.raw`(?:^|[;&|(\n])\s*(?:\w+=\S*\s+)*`
// An npx/bunx/pnpm/yarn runner with its flags (`npx -y`, `pnpm --dir cli exec`), then the
// binary by name or path (`./node_modules/.bin/basalt`), pinned or not (`basalt-cli@0.16.1`).
const RUNNER = String.raw`(?:(?:npx|bunx|yarn|pnpm)(?:\s+(?:exec|dlx|-[\w-]+(?:[= ](?!\S*basalt)[^\s-]\S*)?))*\s+)?`
const BASALT_PUBLISH = new RegExp(AT_HEAD + RUNNER + String.raw`(?:\S*/)?basalt(?:-cli)?(?:@\S+)?\s+(?:publish|move)\b`)
const GIT_PUSH = new RegExp(AT_HEAD + String.raw`git(?:\s+-C\s+\S+)?\s+push\b`)
const GH_MERGE = new RegExp(AT_HEAD + String.raw`gh\s+pr\s+merge\b`)

// The calls that publish: `basalt publish|move` from a shell, `publish_doc|update_doc` over MCP.
// The MCP tools that leave a doc at a new URL or version.
const MCP_PUBLISH = /__(publish_doc|update_doc|edit_doc|move_doc|restore_version|publish_space|publish_vault)$/

// The calls that publish: `basalt publish|move` from a shell (a `--dry-run` publishes
// nothing), and the MCP tools above.
export const isPublish = (tool: string, command: unknown): boolean =>
tool === 'Bash'
? typeof command === 'string' && BASALT_PUBLISH.test(commandText(command))
: /basalt/i.test(tool) && /__(publish_doc|update_doc)$/.test(tool)
? typeof command === 'string' && BASALT_PUBLISH.test(commandText(command)) && !/\s--dry-run\b/.test(commandText(command))
: /basalt/i.test(tool) && MCP_PUBLISH.test(tool)

export const isGitPush = (command: unknown): boolean =>
typeof command === 'string' && GIT_PUSH.test(commandText(command))

// `gh pr merge` now (`--auto` merges later, when nobody is watching the call).
export const isPrMerge = (command: unknown): boolean =>
typeof command === 'string' && GH_MERGE.test(commandText(command)) && !/\s--auto\b/.test(commandText(command))

// The PR a `gh pr merge` names: its number, URL or branch; none means the current branch's.
export const mergedPr = (command: string): string | undefined => {
const text = commandText(command)
const at = text.match(GH_MERGE)
const rest = at?.index === undefined ? '' : text.slice(at.index + at[0].length)
const args = (rest.split(/[;&|\n]/)[0] ?? '').trim().split(/\s+/).filter(Boolean)
for (let i = 0; i < args.length; i++) {
const arg = args[i] ?? ''
if (/^-(R|-repo|t|-subject|b|-body|F|-body-file|A|-author-email|-match-head-commit)$/.test(arg)) i++
else if (!arg.startsWith('-')) return arg
}

return undefined
}

// What a publish said about each URL it printed: created or a new version, and which one.
// The CLI prints one row per doc — `new space/slug <url> v1` — and `--json` / MCP return
// objects with `status` and `version`. Version 1 IS a creation, whichever surface said it.
Expand Down Expand Up @@ -108,11 +135,11 @@ export const pushedRanges = (output: string): { from: string; to: string }[] =>
.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 => {
// The directory the push (or merge) 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 = '', at = GIT_PUSH): string => {
const text = commandText(command)
const push = text.match(GIT_PUSH)
const push = text.match(at)
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)]
Expand All @@ -137,52 +164,86 @@ export const vaultName = (yaml: string): string | undefined =>

const BASE = 'https://app.basalt.cofoundy.ai'

// What reading a push needs from outside: git in a directory, a file's text.
// What reading a push or a merge needs from outside: git and gh in a directory, a file's text.
export type PushIo = {
git: (dir: string, args: string[]) => Promise<{ exitCode: number; stdout: string }>
gh: (dir: string, args: string[]) => Promise<{ exitCode: number; stdout: string }>
read: (path: string) => Promise<string | undefined>
}

type PushedDoc = { url: string; trail: string[]; title: string; kind: 'new' | 'edited' }

// Each .md/.mdx under a vault.yaml, as the doc the vault's publish Action makes of it. 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.
async function vaultDocs(io: PushIo, root: string, files: { path: string; kind: PushedDoc['kind'] }[]): Promise<PushedDoc[]> {
const docs: PushedDoc[] = []
for (const { path: file, kind } of files) {
if (!/\.mdx?$/i.test(file)) continue
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, kind })
}
break
}
}

return docs
}

// 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; kind: 'new' | 'edited' }[]> {
// changed under a vault.yaml, in a repo whose workflows run `basalt publish`.
export async function pushedDocs(io: PushIo, dir: string, output: string): Promise<PushedDoc[]> {
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; kind: 'new' | 'edited' }[] = []
const docs: PushedDoc[] = []
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
// `A` is a doc the push created; `M`/`R` a new version of one that existed.
const changed = await io.git(root, ['diff', '--name-status', '--diff-filter=AMR', `${from}..${to}`, '--', '*.md', '*.mdx'])
for (const row of changed.stdout.split('\n').filter(Boolean)) {
const files = changed.stdout.split('\n').filter(Boolean).map(row => {
const cols = row.split('\t')
const kind = cols[0]?.startsWith('A') ? 'new' : 'edited'
const file = cols[cols.length - 1] ?? ''
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, kind })
}
break
}
}
return { path: cols[cols.length - 1] ?? '', kind: cols[0]?.startsWith('A') ? 'new' as const : 'edited' as const }
})
docs.push(...(await vaultDocs(io, root, files)))
}

return docs
}

// The docs a merged PR hands to the same Action: a `gh pr merge` into main of a vault repo
// (the PR road never runs a `git push` to main in the session).
export async function mergedDocs(io: PushIo, dir: string, pr: string | undefined): Promise<PushedDoc[]> {
const view = await io.gh(dir, ['pr', 'view', ...(pr ? [pr] : []), '--json', 'files,baseRefName,mergedAt'])
if (view.exitCode !== 0) return []
let info: { files?: { path: string; changeType: string }[]; baseRefName?: string; mergedAt?: string | null }
try { info = JSON.parse(view.stdout) } catch { return [] }
if (!info.mergedAt || !['main', 'master'].includes(info.baseRefName ?? '')) return []
const top = await io.git(dir, ['rev-parse', '--show-toplevel'])
if (top.exitCode !== 0) return []
const root = top.stdout.trim()
const action = await io.git(root, ['grep', '-l', '-e', 'basalt publish', 'HEAD', '--', '.github/workflows'])
if (action.exitCode !== 0) return []
const files = (info.files ?? [])
.filter(f => ['ADDED', 'MODIFIED', 'RENAMED'].includes(f.changeType))
.map(f => ({ path: f.path, kind: f.changeType === 'ADDED' ? 'new' as const : 'edited' as const }))

return vaultDocs(io, root, files)
}

const pushIo = ($: EngineInterface): PushIo => ({
git: (dir, args) => $.process.run(['git', '-C', dir, ...args]).catch(() => ({ exitCode: 1, stdout: '' })),
gh: (dir, args) => $.process.run(['gh', ...args], { cwd: dir }).catch(() => ({ exitCode: 1, stdout: '' })),
read: path => $.fs.read(path).then(text => (typeof text === 'string' ? text : undefined), () => undefined),
})

Expand Down Expand Up @@ -403,20 +464,27 @@ export const register: Register = on => {
// 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 (out.deny !== undefined || out.isError) return out
if (out.deny !== undefined) 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 prMerge = e.tool === 'Bash' && !publish && !push && isPrMerge(command)
// A CLI run that exits non-zero may still have published: `--strict` fails the run over a
// broken link AFTER the doc went up, and a failed row prints no URL. Anything else that
// errored published nothing.
if (out.isError && !(publish && e.tool === 'Bash')) return out
if (!publish && !push && !prMerge) 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, fact] of publishFacts(text)) found.push({ ...toLink(url, by, now), ...fact })
} 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 })
const at = push ? GIT_PUSH : GH_MERGE
const dir = pushDir(command as string, await $.session.cwd(), (await $.env.get('HOME')) ?? '', at)
const docs = push ? pushedDocs(pushIo($), dir, text) : mergedDocs(pushIo($), dir, mergedPr(command as string))
for (const doc of await docs.catch(() => [])) found.push({ ...doc, by, at: now })
}
if (found.length > 0) {
// One doc, one row: a flat /{space}/{slug} and its canonical /{ws}/{space}/{slug} are the same doc.
Expand Down
43 changes: 41 additions & 2 deletions plugins/basalt/tests/links.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, mock, test } from 'claude-code/testing'

import { isGitPush, isPublish, isUnseen, markSeen, merge, normalizeSlug, ordered, publishFacts, pushDir, pushedDocs, pushedRanges, tally, tag, vaultName, withWorkspace } from '../hooks/register'
import { isGitPush, isPrMerge, isPublish, isUnseen, markSeen, merge, mergedDocs, mergedPr, normalizeSlug, ordered, publishFacts, pushDir, pushedDocs, pushedRanges, tally, tag, vaultName, withWorkspace } from '../hooks/register'
import type { PushIo } from '../hooks/register'

const Box = 'Box' as any
Expand All @@ -27,7 +27,8 @@ const band = async ($: any) => {
}

// 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 = 'A\tvault/research/Plan Q4.md\nM\tREADME.md\n' } = {}): PushIo => ({
const repo = ({ action = true, changed = 'A\tvault/research/Plan Q4.md\nM\tREADME.md\n', pr = '' } = {}): PushIo => ({
gh: async (dir, args) => (args[0] === 'pr' && args[1] === 'view' && dir.startsWith('/r') && pr ? { exitCode: 0, stdout: pr } : { exitCode: 1, stdout: '' }),
git: async (dir, args) => {
const line = args.join(' ')
if (line === 'rev-parse --show-toplevel') return { exitCode: dir.startsWith('/r') ? 0 : 128, stdout: '/r\n' }
Expand Down Expand Up @@ -108,6 +109,38 @@ describe('links band', () => {
expect(await pushedDocs(repo(), '/elsewhere', PUSH_OUT)).toEqual([])
})

test('a merged PR into main of a vault repo is the doc the Action publishes', async () => {
const pr = (o: object) => JSON.stringify({ baseRefName: 'main', mergedAt: '2026-11-02T20:00:00Z', files: [{ path: 'vault/research/Plan Q4.md', changeType: 'ADDED' }, { path: 'vault/personas.md', changeType: 'MODIFIED' }, { path: 'README.md', changeType: 'MODIFIED' }], ...o })
expect(await mergedDocs(repo({ pr: pr({}) }), '/r', '12')).toEqual([
{ url: 'https://app.basalt.cofoundy.ai/notes/research/plan-q4', trail: ['notes', 'research'], title: 'plan-q4', kind: 'new' },
{ url: 'https://app.basalt.cofoundy.ai/notes/personas', trail: ['notes'], title: 'personas', kind: 'edited' },
])
expect(await mergedDocs(repo({ pr: pr({ mergedAt: null }) }), '/r', '12')).toEqual([])
expect(await mergedDocs(repo({ pr: pr({ baseRefName: 'staging' }) }), '/r', '12')).toEqual([])
expect(await mergedDocs(repo({ pr: pr({}), action: false }), '/r', '12')).toEqual([])
})

test('which gh pr merge, and which PR', () => {
expect(isPrMerge('cd /r && gh pr merge 12 --squash --delete-branch')).toBe(true)
expect(isPrMerge('gh pr merge 12 --auto --squash')).toBe(false)
expect(isPrMerge('gh pr view 12')).toBe(false)
expect(mergedPr('gh pr merge 12 --squash')).toBe('12')
expect(mergedPr('gh pr merge --squash -R acme/notes 34')).toBe('34')
expect(mergedPr('gh pr merge --squash && git pull')).toBeUndefined()
})

test('a --strict run that exits red still put its published docs in the band', async ($, on) => {
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', () => ({ isError: true, text: `✗ new notes/ship-log/plan ${A} v1 [links: 1 broken]\nerror notes/x ✗ boom`, result: {} }))
await $.tool.call({ tool: 'Bash', command: 'basalt publish --strict ship-log' } as any)
expect(await drawn($, 'AbovePrompt')).toContain('plan')
})

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 }
Expand Down Expand Up @@ -150,6 +183,12 @@ describe('links band', () => {
expect(isPublish('mcp__plugin_basalt_basalt__publish_doc', undefined)).toBe(true)
expect(isPublish('mcp__basalt__update_doc', undefined)).toBe(true)
expect(isPublish('mcp__basalt__get_doc', undefined)).toBe(false)
expect(isPublish('Bash', 'npx -y basalt-cli@0.16.1 publish a.md')).toBe(true)
expect(isPublish('Bash', 'pnpm --dir cli exec basalt publish a.md')).toBe(true)
expect(isPublish('Bash', './node_modules/.bin/basalt publish a.md')).toBe(true)
expect(isPublish('Bash', 'basalt publish --dry-run a.md')).toBe(false)
expect(isPublish('mcp__plugin_basalt_basalt__edit_doc', undefined)).toBe(true)
expect(isPublish('mcp__plugin_basalt_basalt__move_doc', undefined)).toBe(true)
})
test('the CLI row says whether the doc was created or got a new version, and which', () => {
const facts = publishFacts(`new notes/ship-log/plan ${A} v1 [assets: 3↑ 0✓]\nmodified notes/personas ${B} v7`)
Expand Down
Loading