Obsidian Workspace — project-scoped vault productivity (capture / notes / PM). Skills own folder layout and templates; /obw:pm splits a spec into blocking…

Project-scoped Obsidian vault productivity for Claude Code — quick capture, long-form notes, and project management. Skills own folder layout + file templates + PM conventions, while the /issue Claude Mod lists a view of the project's dashboard in a pane; vault I/O runs through the Obsidian CLI, deferring to the official obsidian:obsidian-cli skill for syntax. Each skill file is kept small so it doesn't burn your context budget.
Plugin identifier: obw (skills invoked as /obw:<name> or via natural language).
| Skill | Purpose |
|---|---|
/obw:init | Pick a vault, write .obsidian.yaml, install starter templates, bootstrap the project workspace, migrate an older layout |
/obw:jot <text> | Quick capture (timestamped bullet to today's daily note) or long-form note — triages by input shape |
/obw:pm [intent] | Task / document lifecycle, project-scoped; split a spec into blocking tickets |
obsidian CLI, run directly in the main context (no sub-agent). This plugin does not duplicate CLI syntax; it defers to the official obsidian:obsidian-cli skill and obsidian help.daily:append.task, doc) live in your vault's Obsidian Templates folder. On /obw:init the plugin copies starter files from templates/ only if the same name doesn't already exist — it never overwrites your edits..base files — core in Obsidian 1.9+) generated from plugin-internal templates via shell substitution, so contents never enter Claude's context.Run /issue <view> to list a view from the configured project's dashboard.base, created by /obw:pm, then select one to read its title, status, priority, and markdown body in the same pane. /issue with no argument opens the All Tasks view as a Button list under the view picker, on every surface: cards grouped by status (todo, in-progress, blocked, done), each heading with its card count, each row reading [H|M|L] <title> <tags> sorted by priority, and done folded at the start. The pane takes the keys when it opens: ↑↓ move the focus ring (and the window follows it), Enter opens a card or folds a heading, and Escape closes the pane. f focuses the filter field, which narrows the list to cards whose title or tags contain what you type; Enter or ↓ there hands the keys back to the first match. p cycles the priority filter, s switches the order inside each group between priority and title, and x clears the filters while any is set. The filter, the folds and the sort stay for the session. Arrow keys walk the list in the terminal; elsewhere Tab and touch do. Other views stay flat lists. A dashboard without All Tasks opens Active and says to run /obw:pm refresh dashboard. The pane reports missing configuration, unavailable CLI output, and missing cards in place without adding vault content to the conversation.
A card opened from the list, or by /issue <card> while All Tasks is shown, takes the whole pane under a list › breadcrumb and a back Button. Escape or b goes back, one card at a time, to the list with the focus on the row you left. The card's parent, blocked_by and related links are Buttons that open the linked card; a link to a note outside All Tasks, a doc for example, shows as dim text. A thin rule sets the card off from the header. Status and priority are coloured labels, followed by an AC <checked>/<total> count when the card's Acceptance Criteria section has checkboxes. Colours are Claude Code theme keys, so the pane follows your /theme. Errors are drawn in the error colour; progress and empty-list notices stay dim.
Mermaid blocks in the card body are drawn in the pane as text diagrams by uvx termaid@0.9.0, which needs uv. uv is optional: without it, a block stays the code block it is in the card. A block also stays a code block when its diagram type is not supported, when it starts with a %% comment or --- frontmatter, or when termaid fails, prints nothing, or takes longer than 5 s. The card is drawn first and each diagram replaces its code block when it is ready, so the first run may show the code block until uv has fetched termaid.
A shown card has an Open in browser Button that renders the card body, Mermaid included, through the viz plugin's render.sh. The Button appears only when viz is installed, found through installed_plugins.json under $CLAUDE_CONFIG_DIR or ~/.claude, and only in the terminal. Opening the browser uses macOS open; over SSH the pane shows the page's URL instead. The pane reports where the card was rendered, or why it was not. The page opens on the machine running Claude Code: when you reach the session through a terminal multiplexer or relay that does not set the SSH variables (herdr, for example), the browser opens on that host, not on the device you are looking at.
To read the page from another device on your tailnet, proxy viz's port once with tailscale serve --bg --https=18090 18090. After each render the pane reads tailscale serve status --json and, when a mapping covers the page's port, adds a Tailnet: https://<machine>.<tailnet>.ts.net:18090/… line. The pane never creates a mapping itself; without one it shows only the opened page.
Test the plugin with:
claude plugin test obsidian-workspace
The pane needs Claude Code 2.1.287 or later, where Claude Mods are on by default. Built and tested against Claude Code 2.1.287.
A session is bound to a task card by a file at ~/.claude-mobile/launches/<session_id>.json (cardPath, vault, project, createdAt, plus paneId from cc-mobile), or under $OBW_LAUNCHES_DIR when that is set. Three things write it: cc-mobile when it starts a session for a card, the Bind this session Button under any card the /issue pane shows in the terminal, and Claude setting a pm/<project>/tasks/ card's status to in-progress once the CLI confirms it. The Unbind this session Button, or a confirmed done of the bound card, removes it. While bound, the band above the prompt shows the card's name, title and AC x/y, reread after each turn. Three hooks in hooks/hooks.json run hooks/writeback.sh on every prompt, stop and permission prompt of every session; a session without that file leaves in a few milliseconds and touches nothing. For a bound session they write to the card:
session and appends 工作中 to ## Agent;pm/<project>/runs/<card>.md, linked from that line;需要核准.Writes go through obsidian eval and are read back; a failed write is logged to ~/.claude-mobile/writeback.log and never blocks the session.
The obw Claude Mod registers three tools that Claude can call to change a task card:
pm_tick {card, index, checked} sets one checkbox of the card to checked.pm_note {card, line} adds line to the card.pm_status {card, status} sets the card's status. It does not bind or unbind the session.card is the card's file name without .md, such as a for pm/<project>/tasks/a.md; the project comes from .obsidian.yaml. An empty name, a name with /, or one with a control character is rejected with isError set, and nothing is written. Every result is one JSON line in the tool's text: {"ok":true,"path":"pm/<project>/tasks/a.md"} on success, {"ok":false,"reason":"..."} otherwise; the platform accepts only text or content blocks as a tool result, so the object is never returned bare.
obsidian plugin (from the obsidian-skills marketplace) — declared as a plugin dependency, so it auto-installs with this plugin as long as that marketplace is added (claude plugin marketplace add)obsidian-cli installed and enabled. The plugin's name is obsidian-cli but the executable it installs is obsidian (invoked as obsidian vault=<name> ...). This is not the unrelated standalone obsidian-cli binary by Yakitrak./obw:pm — task / doc templates)/obw:jot quick capture)/obw:pm dashboards — bundled in Obsidian 1.9+)/obw:init, which reads Obsidian's vault list and Templates settings with it)/obw:pm refresh dashboard, which compares dashboards through uv run --with pyyaml; optional for the /issue pane, where it draws Mermaid blocks as text diagrams through uvx termaid@0.9.0 — without it they show as code blocks)/issue pane's Open in browser Button — without it the Button is not drawn)/issue pane; the skills do not need it)/plugin install obsidian-workspace
Vault operations shell out to the obsidian CLI plus a few Unix helpers. To avoid repeated permission prompts, add these to user settings.json (~/.claude/settings.json) once:
{
"permissions": {
"allow": [
"Bash(obsidian:*)",
"Bash(cat:*)",
"Bash(jq:*)",
"Bash(cp:*)",
"Bash(sed:*)"
]
}
}
Or run /fewer-permission-prompts after a stuck /obw:init and it will scan transcripts and propose the same list.
Run /obw:init in a project root. The generated .obsidian.yaml:
vault: MyVault
note:
default_folder: Inbox
filename_strategy: title # title | slug | timestamp-title
pm:
project: my-project # Omit this section to disable /obw:pm
Daily note folder / filename / template are not in .obsidian.yaml — they come from Obsidian's Daily Notes settings.
/obw:pm)pm/
├── dashboard.base # Cross-project dashboard (optional, Bases)
└── {project}/
├── dashboard.base # Project dashboard (Bases)
├── tasks/ # Active tasks
│ └── archive/ # Completed tasks
└── docs/ # Docs
Every project gets tasks/, docs/, and dashboard.base — /obw:init creates all three up front, so a project is never a bare folder.
Upgrading a vault from before 0.9: re-run /obw:init. It detects the old layout and offers, each separately, to move archive/ into tasks/archive/ (through the CLI, so links follow), backfill the title property on existing notes, and regenerate the dashboards with the new views. Existing filenames are never renamed.
A plugin update can change dashboard views, formulas, columns, and filters. Run /obw:pm refresh dashboard to bring in All Tasks (and any other template change) on an existing vault. The refresh compares dashboard.base with every template version as parsed YAML. A dashboard identical to one of them is regenerated at once; one with hand edits lists them, warns that regenerating overwrites them, and asks first.
All notes are kebab-cased (Implement Auth → implement-auth.md), for both /obw:jot notes and /obw:pm tasks / docs. Because Obsidian's {{title}} resolves to the filename, the human-readable title lives in the title property — that is what the dashboards display.
Dashboards and searches depend on these frontmatter fields. If you edit the installed templates, keep the field names.
title, type: task, status (todo / in-progress / blocked / done), priority (high / medium / low), project, due (date), tags (list), parent (link), blocked_by (list of links), related (list of links), session (the Claude session UUID bound to the task), created, completed; the task body's ## Agent section holds one line per event of that sessiontitle, type: doc, project, created, updatedTasks link to each other by wikilink through three properties — blocked_by, related, and parent (epic → subtask). There is no separate issue ID: the kebab filename is the handle, and Obsidian rewrites links when a note is renamed.
Only one direction is stored. What a task blocks, and what its subtasks are, come from Obsidian's backlinks pane — a blocks field alongside blocked_by would only drift. Adding a blocker sets status: blocked; archiving a task lists whatever still depends on it and asks before unblocking. Ticket splitting writes its blocking edges to blocked_by; the unblocked frontier is a search excluding -[blocked_by: wikilinks, not a view.
/obw:jot #worklog 完成 API 重構 PR,等 review
/obw:jot API Redesign Proposal --folder Architecture --tag design
/obw:pm add task implement-auth, high priority, due 2026-05-01
/obw:pm implement-auth is blocked by db-migration
/obw:pm implement-auth is done, archive it
/obw:pm split this spec into tickets
/obw:pm refresh dashboard
Ticket splitting adapted from mattpocock/skills to-tickets (MIT, Copyright (c) 2026 Matt Pocock), commit 3cca18b368ae95cdbdebbff572ccafa662551015. Upstream's wide refactor expand-contract sequencing is not imported: the pm skill keeps the three vertical-slice rules plus prefactor and maps blocking edges onto existing blocked_by.
hooks/register.ts 917 lines1import { atom, read, update } from 'claude-code'
2import type { On } from 'claude-code'
3import { bounded, MAX_CHARS } from './bounds.ts'
4import { configOf } from './config.ts'
5import { isBadCardName, dashboardPath, taskFolder } from './argv.ts'
6import { baseQueryArgv, cardPathArgv, viewsArgv } from './base-argv.ts'
7import type { Scope } from './base-argv.ts'
8import { baseQueryOutput, viewsOutput, readOutput, evalOutput, OBSIDIAN_TIMEOUT_MS } from './cli-output.ts'
9import type { Run } from './cli-output.ts'
10import { cardName, listRows, resolveArgument, rowNamed, rowSlug, rowsOutside } from './rows.ts'
11import { COUNT_VIEW, missingViewHint, missingViewText } from './counts.ts'
12import { listGroups, listItems } from './list.ts'
13import { listChildren, listHints } from './list-view.ts'
14import type { ListHandlers } from './list-view.ts'
15import { acLabel, headerOf, relationsOf } from './card.ts'
16import { vizManifestPath, vizInstallPath, renderTarget, renderArgv, renderOutcome, RENDER_TIMEOUT_MS, isLoopbackUrl, tailnetUrl, SERVE_STATUS_ARGV, SERVE_TIMEOUT_MS } from './viz.ts'
17import { splitFences, termaidHeaderAllowed, diagramOutcome, TERMAID_ARGV, TERMAID_TIMEOUT_MS } from './mermaid.ts'
18import type { Segment } from './mermaid.ts'
19import { BACK_KEY, QUERY_KEY, arrowMove, backTarget, closeGoesBack, nextRing, reorderTarget, submitTarget } from './ring.ts'
20import { LIST_START, LOADING, RING_START } from './state.ts'
21import { ACCENT, ERROR, INACTIVE, SUBTLE, priorityColor, statusColor } from './style.ts'
22import { fitWidth } from './width.ts'
23import type { ObwBound, ObwBrowser, ObwCard, ObwLine, ObwList, ObwPane } from '../types/index.d.ts'
24import { bindingAction, bindingOf, bindingPath, sameBinding, statusChanges } from './bind.ts'
25import type { Binding } from './bind.ts'
26import { PM_TOOLS, cardText, evalArgv, pmEdit } from './pm-tools.ts'
27
28// The scan that checks `update` and `read` follows an atom only when it is made in the file that uses it.
29// Bump the shape tag when ObwPane changes meaning: a reload then declines what the old code wrote.
30export const pane = atom({ plugin: 'obw', key: 'pane' } as const, LOADING, { shape: 'pane-2' })
31export const list = atom({ plugin: 'obw', key: 'list' } as const, LIST_START)
32export const ring = atom({ plugin: 'obw', key: 'ring' } as const, RING_START)
33
34// $.state values stop at 4 MiB, and a write over it skips the whole command: what the pane keeps from the vault is cut well short of that.
35const MAX_LABEL = 200
36const MAX_STORED_BODY = 1_000_000
37
38const PANE_ID = 'obw-issue'
39const PANE = { id: PANE_ID, title: 'obw issue', focus: true, closeOnEscape: true, holdToasts: true } as const
40
41type Line = ObwLine
42type Shown = Extract<ObwCard, { kind: 'shown' }>
43
44type Stored = Omit<ObwBound, 'card'>
45
46// The session's binding as loaded from its file; null while the session has none.
47export const binding = atom({ plugin: 'obw', key: 'binding' } as const, null as ObwBound | null)
48
49async function runProcess($: any, argv: string[], timeoutMs = OBSIDIAN_TIMEOUT_MS, stdin?: string): Promise<Run> {
50 try {
51 const result = await $.process.run(argv, { ...(stdin === undefined ? {} : { stdin }), timeoutMs })
52 return { kind: 'exited', exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr }
53 } catch {
54 return { kind: 'rejected' }
55 }
56}
57
58// A CLI call can settle after a newer /issue, pick, card open or back step: each one numbers its own request,
59// and a write from an older one is dropped inside the compare-and-set.
60async function begin($: any, change: (state: ObwPane) => ObwPane): Promise<number> {
61 const written = await update($, pane, (state) => ({ ...change(state), request: state.request + 1 }))
62 return written.request
63}
64
65async function put($: any, request: number, change: (state: ObwPane) => ObwPane): Promise<boolean> {
66 const written = await update($, pane, (state) => (state.request === request ? change(state) : state))
67 return written.request === request
68}
69
70// A refused focus (the pane does not hold the keys, a key not drawn) leaves the ring where it is.
71async function focus($: any, key: string): Promise<boolean> {
72 try {
73 const moved = await $.ui.focus({ requestId: PANE_ID, key })
74 return !moved?.deny
75 } catch {
76 return false
77 }
78}
79
80function showMessage($: any, request: number, message: string) {
81 return put($, request, (state) => ({ ...LOADING, request: state.request, loading: false, message: { kind: 'error', text: message } }))
82}
83
84// Any fault while looking for viz only leaves viz unfound; the card still draws.
85async function findViz($: any): Promise<string | null> {
86 try {
87 const path = vizManifestPath(await $.env.get('CLAUDE_CONFIG_DIR'), await $.env.get('HOME'))
88 return path ? vizInstallPath(await $.fs.read(path)) : null
89 } catch {
90 return null
91 }
92}
93
94// What a card step leaves behind: the trail, and the card to read, or none when the list is back.
95type Step = { trail: string[]; path: string | null }
96
97// Where the ring goes after a step, from the trail before it and the keys the list draws after it.
98type RingAfter = (before: string[], keys: string[]) => string | null
99
100// The step is taken from the trail inside the write, so two steps in a row each start from what the one before left.
101// The trail change and the new request are one write, so no drawing shows the old card under the new trail.
102async function show($: any, step: (before: string[]) => Step, ringAfter: RingAfter | null = null) {
103 const { scope } = await read($, pane)
104 if (!scope) return
105 let before: string[] = []
106 let taken: Step = { trail: [], path: null }
107 const request = await begin($, (state) => {
108 before = state.trail
109 taken = step(state.trail)
110 const built = taken.path === null ? null : cardPathArgv(scope, taken.path)
111 const card: ObwCard | null =
112 taken.path === null ? null : built && 'argv' in built ? { kind: 'loading', path: taken.path } : { kind: 'error', message: `"${taken.path}" is not a card path.` }
113 return { ...state, trail: taken.trail, selected: taken.path, card }
114 })
115 const { path } = taken
116 if (ringAfter) {
117 const target = ringAfter(before, path === null ? (await drawnItems($)).keys : [])
118 if (target) void focus($, target)
119 }
120 if (path === null) return
121 const built = cardPathArgv(scope, path)
122 if (!('argv' in built)) return
123 const settle = (card: ObwCard) => put($, request, (state) => ({ ...state, card }))
124 const output = readOutput(await runProcess($, built.argv))
125 if (output.kind === 'error') return settle({ kind: 'error', message: output.message })
126 const vizRoot = await findViz($)
127 const segments = splitFences(bounded(output.body).text)
128 await settle({
129 kind: 'shown',
130 path,
131 header: headerOf(output.frontmatter),
132 body: output.body.slice(0, MAX_STORED_BODY),
133 segments,
134 relations: relationsOf(output.frontmatter),
135 vizRoot,
136 browser: null,
137 diagrams: segments.map(() => null),
138 bindLine: null,
139 })
140 // termaid never holds /issue: an offline uvx can take seconds, and the card is already drawn.
141 void drawDiagrams($, request, segments).catch(() => {})
142}
143
144// One run at a time: a rejected run means uvx fails for every block, and a superseded read never draws.
145async function drawDiagrams($: any, request: number, segments: Segment[]) {
146 for (const [index, segment] of segments.entries()) {
147 if (segment.kind !== 'mermaid' || !termaidHeaderAllowed(segment.source) || (await read($, pane)).request !== request) continue
148 const run = await runProcess($, TERMAID_ARGV, TERMAID_TIMEOUT_MS, segment.source)
149 if (run.kind === 'rejected') return
150 const diagram = diagramOutcome(run)
151 if (diagram !== null) await patchShown($, request, (card) => ({ ...card, diagrams: card.diagrams.map((drawn, at) => (at === index ? diagram : drawn)) }))
152 }
153}
154
155// A diagram or press result writes only under the card read it came from: a newer read, even of the same card, drops it.
156function patchShown($: any, request: number, patch: (card: Shown) => Shown) {
157 return put($, request, (state) => (state.card?.kind === 'shown' ? { ...state, card: patch(state.card) } : state))
158}
159
160function showBrowser($: any, request: number, browser: ObwBrowser) {
161 return patchShown($, request, (card) => ({ ...card, browser }))
162}
163
164async function openInBrowser($: any) {
165 const { card, scope, request } = await read($, pane)
166 if (card?.kind !== 'shown' || !card.vizRoot || !scope) return
167 const target = renderTarget(rowSlug(scope.project, card.path))
168 await showBrowser($, request, { kind: 'rendering' })
169 try {
170 await $.fs.write(target.file, card.body)
171 } catch (error) {
172 await showBrowser($, request, { kind: 'error', message: `Could not write ${target.file}: ${reasonOf(error)}` })
173 return
174 }
175 const outcome = renderOutcome(await runProcess($, renderArgv(card.vizRoot, target), RENDER_TIMEOUT_MS))
176 await showBrowser($, request, outcome)
177 if (outcome.kind !== 'opened' || !outcome.url || !isLoopbackUrl(outcome.url)) return
178 const status = await runProcess($, SERVE_STATUS_ARGV, SERVE_TIMEOUT_MS)
179 const tailnet = status.kind === 'exited' && status.exitCode === 0 ? tailnetUrl(outcome.url, status.stdout) : null
180 if (tailnet) await showBrowser($, request, { ...outcome, tailnet })
181}
182
183async function bindShown($: any) {
184 const { card, scope, request } = await read($, pane)
185 if (card?.kind !== 'shown' || !scope) return
186 const outcome = await writeBinding($, { cardPath: card.path, vault: scope.vault, project: scope.project })
187 await patchShown($, request, (card) => ({ ...card, bindLine: outcome.ok ? null : { kind: 'error', text: `Could not bind: ${outcome.reason}` } }))
188}
189
190async function unbindShown($: any) {
191 const { request } = await read($, pane)
192 const outcome = await removeBinding($)
193 await patchShown($, request, (card) => ({ ...card, bindLine: outcome.ok ? null : { kind: 'error', text: `Could not unbind: ${outcome.reason}` } }))
194}
195
196// A block without a drawn diagram stays inside the markdown around it, so a pending or failed block reads as code.
197function bodyParts(segments: Segment[], diagrams: (string | null)[]): ({ markdown: string } | { diagram: string })[] {
198 if (!diagrams.some((diagram) => diagram !== null)) return [{ markdown: segments.map((segment) => segment.text).join('') }]
199 const parts: ({ markdown: string } | { diagram: string })[] = []
200 let markdown = ''
201 for (const [index, segment] of segments.entries()) {
202 const diagram = diagrams[index]
203 if (diagram === null || diagram === undefined) markdown += segment.text
204 else {
205 if (markdown) parts.push({ markdown })
206 markdown = ''
207 parts.push({ diagram })
208 }
209 }
210 if (markdown) parts.push({ markdown })
211 return parts
212}
213
214function browserLines(browser: ObwBrowser | null): Line[] {
215 const notice = (text: string): Line => ({ kind: 'notice', text })
216 if (browser?.kind === 'error') return [{ kind: 'error', text: browser.message }]
217 if (browser?.kind === 'rendering') return [notice('Rendering in the browser…')]
218 if (browser?.kind !== 'opened') return []
219 // Over SSH render.sh opens nothing and prints a URL instead; a local render opens its loopback URL.
220 if (browser.url && !isLoopbackUrl(browser.url)) return [`Rendered: ${browser.path}`, `URL: ${browser.url}`].map(notice)
221 const tailnet = browser.tailnet ? [`Tailnet: ${browser.tailnet}`] : []
222 return [`Opened in the browser: ${browser.path}`, ...tailnet].map(notice)
223}
224
225type Config = (Scope & { path: string }) | { error: string }
226
227function configPathIn(dir: string) {
228 return dir === '/' ? '/.obsidian.yaml' : `${dir}/.obsidian.yaml`
229}
230
231function parentOf(dir: string) {
232 const slash = dir.lastIndexOf('/')
233 return slash > 0 ? dir.slice(0, slash) : '/'
234}
235
236async function readConfig($: any, path: string): Promise<Config> {
237 let text: string
238 try {
239 text = await $.fs.read(path)
240 } catch {
241 return { error: `Could not read ${path}.` }
242 }
243 const { vault, project } = configOf(text)
244 if (!vault && !project) return { error: `${path} has no vault or pm.project.` }
245 if (!vault) return { error: `${path} has no vault.` }
246 if (!project) return { error: `${path} has no pm.project.` }
247 return { vault, project, path }
248}
249
250// `fs.exists` never rejects on the host, so a rejection here is a fault to show, not an absent file.
251async function resolveConfig($: any): Promise<Config> {
252 const cwd = await $.session.cwd()
253 for (let dir = cwd; ; dir = parentOf(dir)) {
254 const path = configPathIn(dir)
255 if (await $.fs.exists(path)) return readConfig($, path)
256 if (dir === '/') return { error: `No .obsidian.yaml in ${cwd} or any directory above it.` }
257 }
258}
259
260const NO_BINDING_DIR = 'neither OBW_LAUNCHES_DIR nor HOME is set.'
261const RELATIVE_BINDING_DIR = 'OBW_LAUNCHES_DIR or HOME is not an absolute path.'
262
263async function bindingFile($: any): Promise<{ path: string | null; reason: string }> {
264 const launchesDir = await $.env.get('OBW_LAUNCHES_DIR')
265 const home = await $.env.get('HOME')
266 const path = bindingPath(launchesDir || undefined, home || undefined, await $.session.id())
267 return { path, reason: launchesDir || home ? RELATIVE_BINDING_DIR : NO_BINDING_DIR }
268}
269
270function clearBinding($: any) {
271 return update($, binding, () => null)
272}
273
274// The card read patches only the binding it was started for: a later binding, or none, drops it.
275async function showBinding($: any, record: Stored) {
276 await update($, binding, (bound) => ({ ...record, card: bound && sameBinding(bound, record) ? bound.card : null }))
277 if (!record.project) return
278 const built = cardPathArgv({ vault: record.vault, project: record.project }, record.cardPath)
279 if (!('argv' in built)) return
280 const output = readOutput(await runProcess($, built.argv))
281 const title = output.kind === 'card' ? headerOf(output.frontmatter).title : undefined
282 const card = output.kind === 'card' ? { title: title ? bounded(title).text || null : null, ac: acLabel(output.body) } : null
283 await update($, binding, (bound) => (bound && sameBinding(bound, record) ? { ...bound, card } : bound))
284}
285
286async function loadBinding($: any) {
287 const { path } = await bindingFile($)
288 if (!path) return
289 if (!(await $.fs.exists(path))) return clearBinding($)
290 const record = bindingOf(await $.fs.read(path))
291 if (!record) return clearBinding($)
292 await showBinding($, record)
293}
294
295type Outcome = { ok: true } | { ok: false; reason: string }
296
297async function writeBinding($: any, card: Binding): Promise<Outcome> {
298 try {
299 const { path, reason } = await bindingFile($)
300 if (!path) return { ok: false, reason }
301 const createdAt = new Date(await $.clock.now()).toISOString()
302 await $.fs.write(path, `${JSON.stringify({ cardPath: card.cardPath, vault: card.vault, project: card.project, createdAt })}\n`)
303 } catch (error) {
304 return { ok: false, reason: reasonOf(error) }
305 }
306 await showBinding($, card).catch(() => {})
307 return { ok: true }
308}
309
310// What Claude's Bash result says: the tool's stdout, or the text the model reads when stdout is not a string.
311function outputOf(result: any): string {
312 const stdout = result?.result?.stdout
313 if (typeof stdout === 'string') return stdout
314 return typeof result?.text === 'string' ? result.text : ''
315}
316
317async function removeBinding($: any): Promise<Outcome> {
318 let file: { path: string | null; reason: string }
319 try {
320 file = await bindingFile($)
321 } catch (error) {
322 return { ok: false, reason: reasonOf(error) }
323 }
324 const { path } = file
325 if (!path) return { ok: false, reason: file.reason }
326 const run = await runProcess($, ['rm', '-f', path])
327 if (run.kind === 'rejected') return { ok: false, reason: 'rm did not run.' }
328 if (run.exitCode !== 0) return { ok: false, reason: run.stderr.trim() || `rm exited ${run.exitCode}` }
329 clearBinding($)
330 return { ok: true }
331}
332
333async function followStatus($: any, command: unknown, output: string) {
334 if (typeof command !== 'string') return
335 const changes = statusChanges(command, output)
336 if (!changes.length) return
337 let config: Scope | null = null
338 if (changes.some(change => change.vault === null || 'file' in change.target)) {
339 const found = await resolveConfig($)
340 if (!('error' in found)) config = { vault: found.vault, project: found.project }
341 }
342 const action = bindingAction(changes, config, await read($, binding))
343 if (action?.kind === 'bind') await writeBinding($, action.card)
344 else if (action?.kind === 'unbind') await removeBinding($)
345}
346
347// The only writer of this hint: a dashboard the CLI could not read may simply not exist yet, while a
348// configuration fault names the file it read and says nothing about /obw:pm.
349function pmHint(project: string) {
350 return `If ${dashboardPath(project)} is missing, run /obw:pm to create it.`
351}
352
353// Rows the dashboard sent that the pane cannot open are their own outcome, not an empty view.
354function outsideNotice(count: number, chosen: string, project: string) {
355 return count === 1
356 ? `1 row of the ${chosen} view is not a card under pm/${project} and was left out.`
357 : `${count} rows of the ${chosen} view are not cards under pm/${project} and were left out.`
358}
359
360// A dashboard whose views were renamed or reordered may have no Active view; its own first view is then the one to open.
361function defaultView(names: string[]) {
362 if (names.includes(COUNT_VIEW)) return COUNT_VIEW
363 return !names.length || names.includes('Active') ? 'Active' : names[0]
364}
365
366// The argument names a row wherever the view put it; a name no row carries falls back to the task folder.
367function cardPathIn(cards: ReturnType<typeof listRows>, project: string, name: string) {
368 return rowNamed(cards, project, name) ?? `${taskFolder(project)}${name}.md`
369}
370
371// A card argument stays on the view the pane is already showing, so the row the user is looking at is the row it opens.
372function shownView(chosen: string | null, names: string[]) {
373 return chosen && names.includes(chosen) ? chosen : defaultView(names)
374}
375
376function reasonOf(error: unknown) {
377 return error instanceof Error ? error.message : String(error)
378}
379
380async function openView($: any, scope: Scope, views: string[], chosen: string, named: string | null, request: number | null, listing: Line | null = null) {
381 const loading = (state: ObwPane): ObwPane => ({ ...LOADING, request: state.request, scope, views, chosen, listing })
382 let current = request
383 if (current === null) current = await begin($, loading)
384 else if (!(await put($, current, loading))) return
385 const built = baseQueryArgv(scope, chosen)
386 if (!('argv' in built)) {
387 await showMessage($, current, `"${chosen}" is not a view.`)
388 return
389 }
390 const result = baseQueryOutput(await runProcess($, built.argv))
391 if (result.kind === 'error') {
392 const message: Line = { kind: 'error', text: bounded(result.message).text }
393 const hint = missingViewHint(scope.project, result.message) ?? pmHint(scope.project)
394 await put($, current, (state) => ({ ...state, loading: false, message, hint }))
395 return
396 }
397 const listed = result.kind === 'rows' ? listRows(scope.project, result.rows) : []
398 const cards = listed.map((card) => ({ path: card.path, label: bounded(card.label, MAX_LABEL).text, status: card.status === null ? null : bounded(card.status, MAX_LABEL).text }))
399 const outside = result.kind === 'rows' ? rowsOutside(scope.project, result.rows) : 0
400 const message: Line | null = outside
401 ? { kind: 'notice', text: outsideNotice(outside, chosen, scope.project) }
402 : !cards.length
403 ? { kind: 'notice', text: `No cards in the ${chosen} view of pm/${scope.project}.` }
404 : null
405 const allTasks = chosen === COUNT_VIEW && result.kind === 'rows' ? listGroups(scope.project, result.rows) : null
406 const drawn = await put($, current, (state) => ({ ...LOADING, request: state.request, loading: false, message, listing, scope, views, chosen, cards, allTasks }))
407 if (!drawn || !named) return
408 // All Tasks draws a card in its card view, so back leads to the list; any other view keeps its list above the card.
409 const path = cardPathIn(cards, scope.project, named)
410 await show($, (before) => ({ trail: chosen === COUNT_VIEW ? [path] : before, path }))
411}
412
413// A pick is taken from a drawing the pane has already replaced: a later /issue whose config resolution
414// failed leaves no scope, and there is nothing to query then. Writing the loading state and failing on
415// the way to the CLI would strand the pane on "Reading the vault…" with no picker to come back through.
416async function pickView($: any, name: string) {
417 const { scope, views } = await read($, pane)
418 if (!scope) return
419 await openView($, scope, views, name, null, null)
420}
421
422async function openIssue($: any, request: number, argument: string, chosen: string | null) {
423 // A name holding `/` can still be a view name, which only the dashboard's listing can tell; every other bad name is refused here.
424 if (argument && !argument.includes('/') && isBadCardName(argument)) {
425 await showMessage($, request, `"${argument}" is not a card name.`)
426 return
427 }
428 let config: Config
429 try {
430 config = await resolveConfig($)
431 } catch (error) {
432 await showMessage($, request, `Could not look for .obsidian.yaml: ${reasonOf(error)}`)
433 return
434 }
435 if ('error' in config) {
436 await showMessage($, request, config.error)
437 return
438 }
439 const scope: Scope = { vault: config.vault, project: config.project }
440 const listed = viewsArgv(config)
441 if (!('argv' in listed)) {
442 await showMessage(
443 $,
444 request,
445 listed.refused === 'vault'
446 ? `${config.path}: vault "${config.vault}" is not a vault name.`
447 : `${config.path}: pm.project "${config.project}" cannot name a folder under pm/.`,
448 )
449 return
450 }
451 const listing = viewsOutput(await runProcess($, listed.argv))
452 if ((await read($, pane)).request !== request) return
453 const names = listing.kind === 'views' ? listing.views : []
454 // Prefixed: beside a list the query did draw, the CLI's bare complaint reads as a contradiction.
455 const listingLine: Line | null =
456 listing.kind === 'error'
457 ? { kind: 'error', text: `The dashboard's views could not be listed: ${bounded(listing.message).text}` }
458 : names.includes(COUNT_VIEW)
459 ? null
460 : { kind: 'notice', text: missingViewText(config.project) }
461 const resolved = resolveArgument(argument, names)
462 if (resolved.kind === 'card') {
463 if (isBadCardName(resolved.card)) {
464 await showMessage($, request, `"${resolved.card}" is not a card name.`)
465 return
466 }
467 if (!names.length) {
468 const message: Line | null = listing.kind === 'error' ? { kind: 'error', text: bounded(listing.message).text } : null
469 const hint = listing.kind === 'error' ? pmHint(config.project) : null
470 const drawn = await put($, request, (state) => ({ ...LOADING, request: state.request, loading: false, scope, message, hint }))
471 if (drawn) await show($, (before) => ({ trail: before, path: `${taskFolder(config.project)}${resolved.card}.md` }))
472 return
473 }
474 return openView($, scope, names, shownView(chosen, names), resolved.card, request, listingLine)
475 }
476 return openView($, scope, names, resolved.kind === 'view' ? resolved.view : defaultView(names), null, request, listingLine)
477}
478
479function clipNotice(clipped: { text: string; clippedFrom: number | null }) {
480 return clipped.clippedFrom === null ? null : `Clipped: showing ${clipped.text.length} of ${clipped.clippedFrom} characters.`
481}
482
483const RELATIONS = [
484 ['parent', 'parent'],
485 ['blocked_by', 'blocked by'],
486 ['related', 'related'],
487] as const
488
489// The keys the list draws now, for the ring decisions that need to know what is on screen.
490async function drawnItems($: any, listValue?: ObwList) {
491 const state = await read($, pane)
492 const items = state.allTasks && !state.trail.length ? listItems(state.allTasks.groups, listValue ?? (await read($, list))).items : []
493 return { state, items, keys: items.map((item) => item.key) }
494}
495
496async function toggleFold($: any, key: string) {
497 await update($, list, (value) => ({ ...value, folded: value.folded.includes(key) ? value.folded.filter((entry) => entry !== key) : [...value.folded, key] }))
498}
499
500// The ring goes back to the card it was on when a filter or an order change still draws that card.
501async function restoreRing($: any, next: ObwList) {
502 const { keys } = await drawnItems($, next)
503 const target = reorderTarget((await read($, ring)).item, keys)
504 if (target) await focus($, target)
505}
506
507const PRIORITY_CYCLE: ObwList['priority'][] = [null, 'high', 'medium', 'low']
508
509async function cyclePriority($: any) {
510 const next = await update($, list, (value) => ({ ...value, priority: PRIORITY_CYCLE[(PRIORITY_CYCLE.indexOf(value.priority) + 1) % PRIORITY_CYCLE.length] }))
511 await restoreRing($, next)
512}
513
514async function cycleSort($: any) {
515 const next = await update($, list, (value) => ({ ...value, sort: (value.sort === 'title' ? 'priority' : 'title') as ObwList['sort'] }))
516 await restoreRing($, next)
517}
518
519async function submitQuery($: any, text: string) {
520 const next = await update($, list, (value) => ({ ...value, query: text }))
521 const { items } = await drawnItems($, next)
522 const target = submitTarget(items.map((item) => ({ key: item.key, kind: item.kind })))
523 if (target) await focus($, target)
524}
525
526// The ring lands on `back` while a card remains, else on the row the person left.
527function back($: any) {
528 return show($, (before) => ({ trail: before.slice(0, -1), path: before.length > 1 ? before[before.length - 2] : null }), backTarget)
529}
530
531// Escape hands the keys back to the prompt before it closes the pane, so a refused close reopens the pane to take them again.
532async function escapeBack($: any) {
533 try {
534 await $.ui.open(PANE)
535 } catch {
536 // A refused reopen leaves the pane open without the keys; the back step still happens.
537 }
538 await back($)
539}
540
541function listHandlers($: any): ListHandlers {
542 const quiet = (work: Promise<unknown>) => void work.catch(() => {})
543 return {
544 fold: (key) => quiet(toggleFold($, key)),
545 open: (path) => quiet(show($, () => ({ trail: [path], path }), () => BACK_KEY)),
546 focusQuery: () => quiet(focus($, QUERY_KEY)),
547 query: (text) => quiet(update($, list, (value) => ({ ...value, query: text }))),
548 submit: (text) => quiet(submitQuery($, text)),
549 priority: () => quiet(cyclePriority($)),
550 sort: () => quiet(cycleSort($)),
551 clear: () => quiet(update($, list, (value) => ({ ...value, query: '', priority: null }))),
552 }
553}
554
555async function drawPane($: any, e: any) {
556 const ui = await $.ui.resolve(e)
557 const { Box, Text, Select } = ui
558 const state = await read($, pane)
559 const settings = await read($, list)
560 const safe = (text: string) => bounded(text).text
561 const dim = (text: string) => Text({ dimColor: true, children: [safe(text)] })
562 const error = (text: string) => Text({ color: ERROR, children: [safe(text)] })
563 const line = ({ kind, text }: Line) => (kind === 'error' ? error(text) : dim(text))
564 const span = (text: string, color?: string) => Text({ ...(color ? { color } : {}), children: [safe(text)] })
565 const bodyColumns = Number.isInteger(e.props?.bodyColumns) && e.props.bodyColumns > 0 ? e.props.bodyColumns : null
566 const columns = bodyColumns ?? 80
567 const ruleWidth = Math.min(bodyColumns ?? 40, MAX_CHARS)
568 const draw: DrawContext = { ui, state, bound: await read($, binding), e, dim, error, line, span }
569
570 if (state.trail.length) return cardView($, draw, { columns, ruleWidth })
571
572 const children: any[] = []
573 if (state.listing) children.push(line(state.listing))
574 if (!state.loading && state.views.length && state.scope && state.chosen) {
575 children.push(
576 Select({
577 key: 'views',
578 options: state.views.map((name) => ({ value: safe(name), label: safe(name) })),
579 value: safe(state.chosen),
580 onSelect: (name: string) => void pickView($, name).catch(() => {}),
581 }),
582 )
583 }
584 const drawnList = state.allTasks && state.allTasks.groups.length ? state.allTasks : null
585 if (drawnList) {
586 children.push(...listChildren(ui, { surface: e.surface, columns, ruleWidth, allTasks: drawnList, list: settings, handlers: listHandlers($) }))
587 } else if (state.cards.length) {
588 children.push(
589 Select({
590 key: 'cards',
591 options: state.cards.map((card) => ({ value: safe(card.path), label: safe(card.label) })),
592 ...(state.selected ? { value: safe(state.selected) } : {}),
593 onSelect: (path: string) => void show($, (before) => ({ trail: before, path })).catch(() => {}),
594 }),
595 )
596 }
597 if (state.message) children.push(line(state.message))
598 if (state.hint) children.push(dim(state.hint))
599 if (drawnList) children.push(listHints(ui, e.surface))
600 const card = state.card
601 if (!card) return Box({ flexDirection: 'column', children })
602 // A blank row and a thin rule set the card off from the list above it.
603 children.push(Box({ flexDirection: 'column', marginTop: 1, children: [dim('─'.repeat(ruleWidth)), ...cardRegion($, draw, card)] }))
604 return Box({ flexDirection: 'column', children })
605}
606
607// What every drawing function of the pane needs besides `$`, which the hooks scan only accepts spelled out at its call sites.
608type DrawContext = {
609 ui: any
610 state: ObwPane
611 bound: ObwBound | null
612 e: any
613 dim: (text: string) => any
614 error: (text: string) => any
615 line: (line: Line) => any
616 span: (text: string, color?: string) => any
617}
618
619// One relation line per link: a Button when the link names an All Tasks row, dim text when it names anything else.
620function relationLines($: any, { ui, state }: DrawContext, card: Shown) {
621 const { Box, Text, Button } = ui
622 const rows = new Map((state.allTasks?.groups ?? []).flatMap((group) => group.rows.map((row) => [row.path, row] as const)))
623 const lines: any[] = []
624 for (const [field, label] of RELATIONS) {
625 for (const name of card.relations[field]) {
626 const path = state.scope ? rowNamed(state.cards, state.scope.project, name) : null
627 const target = path === null ? null : { path, title: rows.get(path)?.title ?? cardName(path) }
628 lines.push(
629 Box({
630 flexDirection: 'row',
631 children: [
632 Text({ color: ACCENT, children: ['› '] }),
633 Text({ color: INACTIVE, children: [label.padEnd(11)] }),
634 target
635 ? Button({ plain: true, key: `rel:${field}:${target.path}`, label: bounded(target.title).text || '—', onPress: () => void show($, (before) => ({ trail: [...before, target.path], path: target.path })).catch(() => {}) })
636 : Text({ color: SUBTLE, children: [bounded(`${name} · not in all tasks`).text] }),
637 ],
638 }),
639 )
640 }
641 }
642 return lines
643}
644
645function cardRegion($: any, draw: DrawContext, card: ObwCard) {
646 const { ui, state, bound, e, dim, error, line, span } = draw
647 const { Text, Markdown, Button, Code, Box } = ui
648 const region: any[] = []
649 if (card.kind === 'loading') region.push(dim(`Reading ${cardName(card.path)}…`))
650 if (card.kind === 'error') region.push(error(card.message))
651 if (card.kind === 'shown') {
652 const { title, status, priority } = card.header
653 const body = bounded(card.body)
654 const ac = acLabel(card.body)
655 region.push(Text({ bold: true, children: [bounded(title ?? cardName(card.path)).text] }))
656 region.push(
657 Text({
658 children: [
659 dim('status: '),
660 span(status ?? '—', statusColor(status)),
661 dim(' · priority: '),
662 span(priority ?? '—', priorityColor(priority)),
663 ...(ac ? [dim(' · '), span(ac)] : []),
664 ],
665 }),
666 )
667 // Only the All Tasks card view knows the rows a link can name; another view's cards are not all of them.
668 const relations = state.trail.length ? relationLines($, draw, card) : []
669 if (relations.length) region.push(Box({ flexDirection: 'column', children: relations }))
670 if (e.surface === 'terminal') {
671 region.push(Button({ key: 'bind', label: 'Bind this session', onPress: () => { void bindShown($).catch(() => {}) } }))
672 if (bound && state.scope && sameBinding(bound, { cardPath: card.path, vault: state.scope.vault })) {
673 region.push(Button({ key: 'unbind', label: 'Unbind this session', onPress: () => { void unbindShown($).catch(() => {}) } }))
674 }
675 if (card.bindLine) region.push(line(card.bindLine))
676 }
677 // Only the terminal can run render.sh: `process` is CLI only.
678 if (card.vizRoot && e.surface === 'terminal') {
679 region.push(
680 Button({
681 key: 'open-in-browser',
682 label: 'Open in browser',
683 onPress: () => {
684 void openInBrowser($).catch(() => {})
685 },
686 }),
687 ...browserLines(card.browser).map(line),
688 )
689 }
690 const bodyClip = clipNotice(body)
691 if (bodyClip) region.push(dim(bodyClip))
692 for (const part of bodyParts(card.segments, card.diagrams)) {
693 if ('markdown' in part) region.push(Markdown({ text: bounded(part.markdown).text }))
694 else {
695 const diagram = bounded(part.diagram)
696 const diagramClip = clipNotice(diagram)
697 if (diagramClip) region.push(dim(diagramClip))
698 region.push(Code({ source: diagram.text, wrap: 'truncate-end' }))
699 }
700 }
701 }
702 return region
703}
704
705// The card view: the path taken from the list, a back Button, the card, and what the keys do here.
706function cardView($: any, draw: DrawContext, { columns, ruleWidth }: { columns: number; ruleWidth: number }) {
707 const { ui, state, dim } = draw
708 const { Box, Text, Button } = ui
709 const { card } = state
710 const crumbs = ['list', ...state.trail.slice(0, -1).map((path) => bounded(cardName(path)).text)]
711 const hasRelations = card?.kind === 'shown' && Object.values(card.relations).some((names) => names.length > 0)
712 const hints = ['↑↓ scroll', ...(hasRelations ? ['tab links'] : []), 'esc or b back']
713 return Box({
714 flexDirection: 'column',
715 children: [
716 Box({
717 flexDirection: 'row',
718 justifyContent: 'space-between',
719 width: Math.max(0, columns - 2),
720 children: [
721 Text({ color: INACTIVE, wrap: 'truncate-end', children: [bounded(fitWidth(`${crumbs.join(' › ')} ›`, Math.max(10, columns - 12)).trimEnd()).text] }),
722 Button({ plain: true, key: BACK_KEY, hotkey: 'b', label: 'back', autoFocus: true, onPress: () => void back($).catch(() => {}) }),
723 ],
724 }),
725 Box({ flexDirection: 'column', marginTop: 1, children: [dim('─'.repeat(ruleWidth)), ...(card ? cardRegion($, draw, card) : [])] }),
726 Box({ marginTop: 1, children: [Text({ color: SUBTLE, wrap: 'truncate-end', children: [hints.join(' · ')] })] }),
727 ],
728 })
729}
730
731// A write carries the whole card in one eval, so it may take longer than a read.
732const EVAL_TIMEOUT_MS = 30_000
733
734// A tool result is text or content blocks, never a bare object: the body is one JSON line.
735// A refusal or failure names what went wrong; the reason never carries card text.
736function pmFail(reason: string) {
737 return { result: JSON.stringify({ ok: false, reason }), isError: true }
738}
739
740// A failed read is reported from the CLI's complaint only. A card printed on stdout is never quoted:
741// the one stdout line named is the CLI's own not-found line for this path.
742function readFailure(path: string, run: Run) {
743 if (run.kind === 'exited' && run.exitCode === 0) {
744 const out = run.stdout.trim()
745 return out === `Error: File "${path}" not found.` ? out : `${path} did not return a card.`
746 }
747 const complaint = run.kind === 'exited' ? { ...run, stdout: '' } : run
748 const failed = readOutput(complaint)
749 return failed.kind === 'error' ? failed.message : `${path} did not return a card.`
750}
751
752// A card counts as written only when reading it back gives the text that was written.
753async function pmCall($: any, tool: string, event: Record<string, unknown>) {
754 const edit = pmEdit(tool, event)
755 if ('refused' in edit) return pmFail(edit.refused)
756 const config = await resolveConfig($)
757 if ('error' in config) return pmFail(config.error)
758 const scope: Scope = { vault: config.vault, project: config.project }
759 const path = `${taskFolder(config.project)}${edit.card}.md`
760 const built = cardPathArgv(scope, path)
761 if (!('argv' in built)) return pmFail(`${config.path}: the vault or pm.project cannot name a card.`)
762 const firstRun = await runProcess($, built.argv)
763 const first = readOutput(firstRun)
764 if (first.kind === 'error') return pmFail(readFailure(path, firstRun))
765 const current = cardText(first)
766 if ('refused' in current) return pmFail(current.refused)
767 const next = edit.apply(current.text)
768 if ('refused' in next) return pmFail(next.refused)
769 const written = evalArgv(scope, path, next.text)
770 if ('refused' in written) return pmFail(written.refused)
771 const evaluated = evalOutput(await runProcess($, written.argv, EVAL_TIMEOUT_MS))
772 if (evaluated.kind === 'error') return pmFail(evaluated.message)
773 const backRun = await runProcess($, built.argv)
774 const back = readOutput(backRun)
775 if (back.kind === 'error') return pmFail(`${path} was written, but its read back failed: ${readFailure(path, backRun)}`)
776 const readBack = cardText(back)
777 if ('refused' in readBack || readBack.text !== next.text) return pmFail(`${path} was written, but the read back differs from the text written.`)
778 return { result: JSON.stringify({ ok: true, path }) }
779}
780
781// Calls that arrive together run one after another, so a call's read never misses an edit another has written.
782let queue: Promise<unknown> = Promise.resolve()
783
784function queued<T>(work: () => Promise<T>): Promise<T> {
785 const next = queue.then(work)
786 queue = next.catch(() => {})
787 return next
788}
789
790async function pmHook($: any, tool: string, event: Record<string, unknown>) {
791 try {
792 return await pmCall($, tool, event)
793 } catch (error) {
794 return pmFail(`The pm tool could not run: ${reasonOf(error)}`)
795 }
796}
797
798export function register(on: On) {
799 on('session.start', async ($, e, next) => {
800 try {
801 await $.command.register({
802 name: 'issue',
803 description: 'Show an obw dashboard view or card in a pane',
804 argumentHint: '[view|card]',
805 immediate: true,
806 })
807 } catch {
808 // A refused /issue must not stop the session.
809 }
810 for (const tool of PM_TOOLS) {
811 try {
812 await $.tool.register(tool)
813 } catch {
814 // A refused tool must not stop the others, /issue or the session.
815 }
816 }
817 void loadBinding($).catch(() => {})
818 return next(e)
819 })
820
821 // The filter, the folds and the sort a person set stay for the session; only what the pane shows is read again.
822 on('command.run', { command: 'issue' }, async ($, e) => {
823 const argument = (e.args ?? '').trim()
824 const { chosen } = await read($, pane)
825 const request = await begin($, () => LOADING)
826 await update($, ring, () => RING_START)
827 try {
828 await $.ui.open(PANE)
829 } catch {
830 return { text: 'obw: the /issue pane could not open.' }
831 }
832 await openIssue($, request, argument, chosen)
833 // Card text never goes into the result: the model would read it.
834 return {}
835 })
836
837 // In a card, Escape (the person's close) goes back a step instead; in the list it closes the pane.
838 on('ui.close', { id: PANE_ID }, async ($, e, next) => {
839 if (!closeGoesBack(e.origin, (await read($, pane)).trail.length)) return next(e)
840 void escapeBack($).catch(() => {})
841 return { deny: 'Escape in a card goes back' }
842 })
843
844 on('ui.focus', { requestId: PANE_ID }, async ($, e, next) => {
845 const moved = await next(e)
846 if (!('deny' in moved && moved.deny)) await update($, ring, (previous) => nextRing(previous, e.element))
847 return moved
848 })
849
850 // An arrow in the list walks the ring and the window follows it; the wheel, the page keys and a card keep the engine's scrolling.
851 on('ui.scroll', { requestId: PANE_ID }, async ($, e, next) => {
852 const { state, items } = await drawnItems($)
853 const at = (await read($, ring)).at
854 const first = submitTarget(items.map((item) => ({ key: item.key, kind: item.kind })))
855 const target = arrowMove(e, { isList: !state.loading && !state.trail.length && items.length > 0, items: items.map((item) => item.key), firstMatch: first, at })
856 if (target === null || !(await focus($, target))) return next(e)
857 try {
858 await $.ui.scroll({ in: PANE_ID, to: { key: target } })
859 } catch {
860 // The ring moved; a window that cannot follow it only leaves the item off screen.
861 }
862 return {}
863 })
864
865 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
866 if (e.requestId !== PANE_ID) return next(e)
867 try {
868 return await drawPane($, e)
869 } catch {
870 try {
871 const { Text } = await $.ui.resolve(e)
872 return Text({ dimColor: true, children: ['obw: the card could not be drawn.'] })
873 } catch {
874 return next(e)
875 }
876 }
877 })
878 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
879 const result = await next(e)
880 void followStatus($, e.command, outputOf(result)).catch(() => {})
881 return result
882 })
883
884 on('tool.call', { tool: 'mcp__obw__pm_tick' }, ($, e) => queued(() => pmHook($, 'pm_tick', e)))
885 on('tool.call', { tool: 'mcp__obw__pm_note' }, ($, e) => queued(() => pmHook($, 'pm_note', e)))
886 on('tool.call', { tool: 'mcp__obw__pm_status' }, ($, e) => queued(() => pmHook($, 'pm_status', e)))
887
888 on('turn.complete', async ($, e, next) => {
889 const result = await next(e)
890 if (e.agentId === undefined) void loadBinding($).catch(() => {})
891 return result
892 })
893
894 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
895 const bound = await read($, binding)
896 if (!bound || e.props?.hasSurvey) return next(e)
897 const beneath = await next(e)
898 try {
899 const { Box, Text } = await $.ui.resolve(e)
900 const { cardPath, card } = bound
901 const title = card?.title
902 const line = Text({
903 wrap: 'truncate-end',
904 children: [
905 Text({ color: 'success', children: ['●'] }),
906 ` ${bounded(cardName(cardPath)).text}`,
907 ...(title ? [` ${title}`] : []),
908 ...(card?.ac ? [` ${card.ac}`] : []),
909 ],
910 })
911 return Box({ flexDirection: 'column', children: [line, beneath] })
912 } catch {
913 return beneath
914 }
915 })
916}
917hooks/bounds.ts 13 lines1const CONTROLS_BUT_TAB_AND_NEWLINE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g
2
3export const MAX_CHARS = 10000
4
5export function bounded(text: string, max = MAX_CHARS) {
6 const clean = text.replace(CONTROLS_BUT_TAB_AND_NEWLINE, '')
7 if (clean.length <= max) return { text: clean, clippedFrom: null }
8 let end = max
9 const last = clean.charCodeAt(end - 1)
10 if (last >= 0xd800 && last <= 0xdbff) end -= 1
11 return { text: clean.slice(0, end), clippedFrom: clean.length }
12}
13hooks/config.ts 27 lines1// A quoted value keeps any `#` inside its quotes and drops a comment after them.
2const QUOTED = /^(["'])(.*)\1\s*(#.*)?$/
3
4export function valueOf(raw: string) {
5 const trimmed = raw.trim()
6 const quoted = QUOTED.exec(trimmed)
7 const value = quoted ? quoted[2] : trimmed.replace(/(^|\s+)#.*$/, '')
8 return value || undefined
9}
10
11export function configOf(text: string): { vault?: string; project?: string } {
12 let vault: string | undefined
13 let project: string | undefined
14 let inPm = false
15 for (const raw of text.split('\n')) {
16 const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw
17 if (/^\s*(#|$)/.test(line)) continue
18 if (/^\S/.test(line)) {
19 inPm = /^pm:(\s+#.*)?\s*$/.test(line)
20 if (/^vault:/.test(line)) vault = valueOf(line.slice('vault:'.length))
21 } else if (inPm && /^\s+project:/.test(line)) {
22 project = valueOf(line.replace(/^\s+project:/, ''))
23 }
24 }
25 return { vault, project }
26}
27hooks/argv.ts 19 lines1const CONTROLS = /[\u0000-\u001f\u007f-\u009f]/
2
3// A name that would empty, widen or escape the path it is put into.
4export function isBadCardName(value: string) {
5 return !value || value === '.' || value === '..' || value.includes('/') || CONTROLS.test(value)
6}
7
8export function projectRoot(project: string) {
9 return `pm/${project}/`
10}
11
12export function dashboardPath(project: string) {
13 return `${projectRoot(project)}dashboard.base`
14}
15
16export function taskFolder(project: string) {
17 return `${projectRoot(project)}tasks/`
18}
19hooks/base-argv.ts 53 lines1import { isBadCardName, dashboardPath, projectRoot } from './argv.ts'
2import { bounded } from './bounds.ts'
3import type { ObwScope } from '../types/index.d.ts'
4
5type ArgvResult = { argv: string[] } | { refused: 'vault' | 'project' | 'view' | 'path' }
6
7export type Scope = ObwScope
8
9function isBadProject(value: string) {
10 return isBadCardName(value) || /[\[\]"\s]/.test(value)
11}
12
13function isBadVault(value: string) {
14 return !value || bounded(value).text !== value
15}
16
17function isBadView(value: string) {
18 return !value || bounded(value).text !== value || /[\t\n\r]/.test(value)
19}
20
21function scopeRefusal(scope: Scope): { refused: 'vault' | 'project' } | null {
22 if (isBadVault(scope.vault)) return { refused: 'vault' }
23 if (isBadProject(scope.project)) return { refused: 'project' }
24 return null
25}
26
27export function baseQueryArgv(scope: Scope, view: string): ArgvResult {
28 const refused = scopeRefusal(scope)
29 if (refused) return refused
30 if (isBadView(view)) return { refused: 'view' }
31 return { argv: ['obsidian', `vault=${scope.vault}`, 'base:query', `path=${dashboardPath(scope.project)}`, `view=${view}`, 'format=json'] }
32}
33
34export function isBadCardPath(project: string, path: string) {
35 const root = projectRoot(project)
36 return !path.startsWith(root) || !path.endsWith('.md') || path.endsWith('/.md') ||
37 bounded(path).text !== path || /[\t\n\r]/.test(path) ||
38 path.split('/').some(segment => segment === '.' || segment === '..' || isBadCardName(segment))
39}
40
41export function cardPathArgv(scope: Scope, path: string): ArgvResult {
42 const refused = scopeRefusal(scope)
43 if (refused) return refused
44 if (isBadCardPath(scope.project, path)) return { refused: 'path' }
45 return { argv: ['obsidian', `vault=${scope.vault}`, 'read', `path=${path}`] }
46}
47
48export function viewsArgv(scope: Scope): ArgvResult {
49 const refused = scopeRefusal(scope)
50 if (refused) return refused
51 return { argv: ['obsidian', `vault=${scope.vault}`, 'read', `path=${dashboardPath(scope.project)}`] }
52}
53hooks/cli-output.ts 130 lines1import { valueOf } from './config.ts'
2
3export type Run = { kind: 'exited'; exitCode: number; stdout: string; stderr: string } | { kind: 'rejected' }
4
5export const OBSIDIAN_TIMEOUT_MS = 10_000
6
7const NOT_RUN = `The obsidian CLI did not run: it is not on PATH, or it did not answer within ${OBSIDIAN_TIMEOUT_MS / 1000} s.`
8
9// Anything that is not a known success shape is shown as the CLI printed it.
10// The CLI prints its own errors on stdout with exit 0, so stdout is read first there;
11// a non-zero exit is the shell's failure and its complaint is on stderr.
12function errorMessage(run: Run) {
13 if (run.kind === 'rejected') return NOT_RUN
14 const [first, second] = run.exitCode === 0 ? [run.stdout, run.stderr] : [run.stderr, run.stdout]
15 return first.trim() || second.trim() || `obsidian exited ${run.exitCode} with no output.`
16}
17
18type BaseRow = { path: string; status: string | null; priority: string | null; title: string | null; due: string | null; tags: string | null }
19
20const text = (value: unknown) => (typeof value === 'string' ? value : null)
21
22function tagsOf(value: unknown) {
23 if (typeof value === 'string') return value
24 if (!Array.isArray(value)) return null
25 return value.filter((tag) => typeof tag === 'string').join(', ') || null
26}
27
28export function baseQueryOutput(run: Run): { kind: 'rows'; rows: BaseRow[] } | { kind: 'empty' } | { kind: 'error'; message: string } {
29 if (run.kind !== 'exited' || run.exitCode !== 0) return { kind: 'error', message: errorMessage(run) }
30 try {
31 const parsed = JSON.parse(run.stdout)
32 if (!Array.isArray(parsed) || !parsed.every((row) => row && typeof row === 'object' && typeof row.path === 'string')) {
33 return { kind: 'error', message: errorMessage(run) }
34 }
35 const rows = parsed.map((row) => ({ path: row.path, status: text(row.status), priority: text(row.priority), title: text(row.title), due: text(row.due), tags: tagsOf(row.tags) }))
36 return rows.length ? { kind: 'rows', rows } : { kind: 'empty' }
37 } catch {
38 return { kind: 'error', message: errorMessage(run) }
39 }
40}
41
42const DRAWABLE = /^[^\x00-\x08\x0b-\x1f\x7f-\x9f\t\n\r]{1,10000}$/
43
44// A listing is the dashboard file's top-level views: list; any other stdout is the CLI
45// saying something else, which is shown rather than read as "this dashboard has no view".
46// Items whose names the pane could not draw are dropped; if every item is undrawable the
47// listing is an error. Only a views: block with no item is empty.
48function viewsFrom(stdout: string): { kind: 'views'; views: string[] } | { kind: 'empty' } | null {
49 let inViews = false
50 let sawViews = false
51 let itemIndent: number | null = null
52 let keyCol: number | null = null
53 let started = false
54 let current: string | undefined
55 const names: (string | undefined)[] = []
56
57 const finish = () => {
58 if (started) names.push(current)
59 current = undefined
60 started = false
61 }
62
63 for (const raw of stdout.split('\n')) {
64 const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw
65 if (/^\s*(#|$)/.test(line)) continue
66
67 if (/^\S/.test(line) && !line.startsWith('- ')) {
68 if (inViews) finish()
69 inViews = false
70 if (/^views:/.test(line)) {
71 const rest = line.slice('views:'.length).trim()
72 if (rest !== '' && rest !== '[]' && !rest.startsWith('#')) return null
73 sawViews = true
74 inViews = true
75 itemIndent = null
76 keyCol = null
77 }
78 continue
79 }
80
81 if (!inViews) continue
82
83 const item = /^(\s*)-(\s+)(.*)$/.exec(line)
84 if (item) {
85 const indent = item[1].length
86 if (itemIndent === null) itemIndent = indent
87 if (indent === itemIndent) {
88 finish()
89 started = true
90 keyCol = indent + 1 + item[2].length
91 if (item[3].startsWith('name:')) current = valueOf(item[3].slice('name:'.length))
92 continue
93 }
94 }
95
96 if (keyCol !== null && started && line.slice(0, keyCol).trim() === '' && line.slice(keyCol).startsWith('name:') && current === undefined) {
97 current = valueOf(line.slice(keyCol + 'name:'.length))
98 }
99 }
100 finish()
101 if (!sawViews) return null
102 const views = names.flatMap((name) => (name && DRAWABLE.test(name) ? [name] : []))
103 if (views.length) return { kind: 'views', views }
104 return names.length ? null : { kind: 'empty' }
105}
106
107export function viewsOutput(run: Run): { kind: 'views'; views: string[] } | { kind: 'empty' } | { kind: 'error'; message: string } {
108 if (run.kind !== 'exited' || run.exitCode !== 0) return { kind: 'error', message: errorMessage(run) }
109 return viewsFrom(run.stdout) ?? { kind: 'error', message: errorMessage(run) }
110}
111
112function noteOf(stdout: string): { frontmatter: string; body: string } | null {
113 if (!stdout.startsWith('---\n')) return null
114 const lines = stdout.split('\n')
115 const close = lines.indexOf('---', 1)
116 if (close < 0) return null
117 return { frontmatter: lines.slice(1, close).join('\n'), body: lines.slice(close + 1).join('\n') }
118}
119
120export function readOutput(run: Run): { kind: 'card'; frontmatter: string; body: string } | { kind: 'error'; message: string } {
121 const note = run.kind === 'exited' && run.exitCode === 0 ? noteOf(run.stdout) : null
122 if (!note) return { kind: 'error', message: errorMessage(run) }
123 return { kind: 'card', ...note }
124}
125
126export function evalOutput(run: Run): { kind: 'written' } | { kind: 'error'; message: string } {
127 if (run.kind === 'exited' && run.exitCode === 0 && run.stdout.trim() === '=> OK') return { kind: 'written' }
128 return { kind: 'error', message: errorMessage(run) }
129}
130hooks/rows.ts 61 lines1import { projectRoot, taskFolder } from './argv.ts'
2import { isBadCardPath } from './base-argv.ts'
3import { bounded } from './bounds.ts'
4
5type Row = { path: string; status?: string | null }
6type ListRow = { path: string; label: string; status: string | null }
7
8export function resolveArgument(argument: string, views: string[]): { kind: 'none' } | { kind: 'view'; view: string } | { kind: 'card'; card: string } {
9 if (!argument.trim()) return { kind: 'none' }
10 return views.includes(argument) ? { kind: 'view', view: argument } : { kind: 'card', card: argument }
11}
12
13export function cardName(path: string) {
14 return path.slice(path.lastIndexOf('/') + 1, -'.md'.length)
15}
16
17// The row an argument names: a view can list a card from any folder under the project, so the name the
18// pane drew is the one to match. Two folders can spell one name, and the task folder keeps it.
19export function rowNamed(rows: ListRow[], project: string, name: string): string | null {
20 const named = rows.filter((row) => cardName(row.path) === name)
21 const task = `${taskFolder(project)}${name}.md`
22 if (named.some((row) => row.path === task)) return task
23 return named.length ? named[0].path : null
24}
25
26export function keptRows<R extends Row>(project: string, rows: R[]): R[] {
27 const paths = new Set<string>()
28 return rows.filter((row) => {
29 if (paths.has(row.path) || isBadCardPath(project, row.path)) return false
30 paths.add(row.path)
31 return true
32 })
33}
34
35export function listRows(project: string, rows: Row[]): ListRow[] {
36 const grouped = new Map<string, ListRow[]>()
37 const withoutStatus: ListRow[] = []
38 for (const row of keptRows(project, rows)) {
39 const status = typeof row.status === 'string' ? row.status : null
40 const name = cardName(row.path)
41 const listed = { path: row.path, label: bounded(status ? `${status} · ${name}` : name).text, status }
42 if (status === null) withoutStatus.push(listed)
43 else {
44 const group = grouped.get(status)
45 if (group) group.push(listed)
46 else grouped.set(status, [listed])
47 }
48 }
49 return [...grouped.values()].flat().concat(withoutStatus)
50}
51
52// Rows the dashboard sent that no card path can be built from: a filter widened past the project, or a row that is not a note.
53// Counted by path, as the list itself is: a path the view sent twice is one row left out, not two.
54export function rowsOutside(project: string, rows: Row[]) {
55 return new Set(rows.filter((row) => isBadCardPath(project, row.path)).map((row) => row.path)).size
56}
57
58export function rowSlug(project: string, path: string) {
59 return path.slice(projectRoot(project).length, -'.md'.length).replaceAll('/', '-')
60}
61hooks/counts.ts 41 lines1import { keptRows, rowsOutside } from './rows.ts'
2
3export const COUNT_VIEW = 'All Tasks'
4
5type Row = { path: string; status?: string | null; priority?: string | null }
6
7export function isMissing(value: string | null | undefined): value is null | undefined | '' {
8 return typeof value !== 'string' || value === ''
9}
10
11function tally(values: (string | null | undefined)[]) {
12 const counts = new Map<string, number>()
13 let missing = 0
14 for (const value of values) {
15 if (isMissing(value)) {
16 missing++
17 continue
18 }
19 counts.set(value, (counts.get(value) ?? 0) + 1)
20 }
21 return { values: [...counts].map(([value, count]) => ({ value, count })), missing }
22}
23
24export function countRows(project: string, rows: Row[]) {
25 const counted = keptRows(project, rows)
26 return {
27 total: counted.length,
28 outside: rowsOutside(project, rows),
29 status: tally(counted.map((row) => row.status)),
30 priority: tally(counted.map((row) => row.priority)),
31 }
32}
33
34export function missingViewText(project: string) {
35 return `pm/${project}/dashboard.base has no ${COUNT_VIEW} view. Run /obw:pm refresh dashboard to regenerate it from the plugin template; hand edits to that file are overwritten.`
36}
37
38export function missingViewHint(project: string, message: string) {
39 return message.split('\n', 1)[0] === `Error: View not found: ${COUNT_VIEW}` ? missingViewText(project) : null
40}
41hooks/list.ts 152 lines1import { bounded, MAX_CHARS } from './bounds.ts'
2import { countRows, isMissing } from './counts.ts'
3import { cardName, keptRows } from './rows.ts'
4import { PRIORITY_ORDER, STATUS_ORDER } from './style.ts'
5import type { ObwGroup, ObwList, ObwRow } from '../types/index.d.ts'
6
7type Row = { path: string; status?: string | null; priority?: string | null; title?: string | null; tags?: string | null }
8
9export type BoardRow = ObwRow
10export type BoardGroup = ObwGroup
11
12// The one place a list item's focus address is built and told apart.
13export const rowKey = (path: string) => `row:${path}`
14export const groupKey = (n: number, label: string) => `group:${n}:${label}`
15export const isListKey = (key: string) => key.startsWith('row:') || key.startsWith('group:')
16
17export type ListSettings = ObwList
18
19export type Item =
20 | { kind: 'heading'; key: string; label: string; status: string | null; count: number; open: boolean }
21 | { kind: 'row'; key: string; row: BoardRow }
22
23const BADGES: Record<string, BoardRow['badge']> = { high: 'H', medium: 'M', low: 'L' }
24const MAX_PATH = 200
25const MAX_TITLE = 80
26const MAX_TAGS = 48
27const MAX_STATUS = 32
28// What the filter matches against is the CLI's own text up to the engine's string bound, the drawing far less.
29// The engine refuses a $.state value over 4 MiB, so all the rows share this much match text; a row past it matches on its drawn cut.
30const MAX_MATCH = MAX_CHARS
31const MATCH_BUDGET = 500_000
32// The engine bounds a tree at 100,000 serialized characters; the list keeps 20,000 of them for everything around it.
33export const LIST_BUDGET = 80000
34// An upper bound of what one heading or row draws besides its key, label and tags.
35const ITEM_OVERHEAD = 900
36
37// bounded keeps tab and newline; either would break a list line in two or skew its columns.
38const oneLine = (text: string, max: number) => bounded(text, max).text.replace(/[\t\n]+/g, ' ')
39
40// A cut status ends in …, so two statuses sharing a capped prefix are not taken for one.
41function statusLabel(status: string) {
42 return bounded(status, MAX_STATUS).clippedFrom === null ? oneLine(status, MAX_STATUS) : `${oneLine(status, MAX_STATUS - 1)}…`
43}
44
45function statusCount(counted: ReturnType<typeof countRows>, status: string | null) {
46 return status === null ? counted.status.missing : counted.status.values.find((entry) => entry.value === status)!.count
47}
48
49function byPriority<R extends Row>(rows: R[]) {
50 const buckets = new Map<string | null, R[]>()
51 const extras: string[] = []
52 for (const row of rows) {
53 const priority = isMissing(row.priority) ? null : row.priority
54 if (!buckets.has(priority)) {
55 buckets.set(priority, [])
56 if (priority !== null && !PRIORITY_ORDER.includes(priority)) extras.push(priority)
57 }
58 buckets.get(priority)!.push(row)
59 }
60 return [...PRIORITY_ORDER.filter((priority) => buckets.has(priority)), ...extras, ...(buckets.has(null) ? [null] : [])].flatMap(
61 (priority) => buckets.get(priority)!,
62 )
63}
64
65function boardRow(row: Row, room: number): BoardRow {
66 const fullTitle = oneLine(row.title ?? '', Math.min(MAX_MATCH, Math.max(room, MAX_TITLE))) || oneLine(cardName(row.path), MAX_TITLE)
67 const fullTags = oneLine(row.tags ?? '', Math.min(MAX_MATCH, Math.max(room - fullTitle.length, MAX_TAGS)))
68 return {
69 path: row.path,
70 key: rowKey(row.path),
71 badge: (typeof row.priority === 'string' && Object.hasOwn(BADGES, row.priority) && BADGES[row.priority]) || ' ',
72 title: oneLine(row.title ?? '', MAX_TITLE) || oneLine(cardName(row.path), MAX_TITLE),
73 tags: oneLine(row.tags ?? '', MAX_TAGS),
74 fullTitle,
75 fullTags,
76 priority: isMissing(row.priority) ? null : oneLine(row.priority, MAX_STATUS),
77 }
78}
79
80export function listGroups(project: string, rows: Row[]): { groups: BoardGroup[]; hidden: number } {
81 const counted = countRows(project, rows)
82 const kept = keptRows(project, rows)
83 const named = counted.status.values.map((entry) => entry.value)
84 const statuses: (string | null)[] = [
85 ...STATUS_ORDER.filter((status) => named.includes(status)),
86 ...named.filter((status) => !STATUS_ORDER.includes(status)),
87 ...(counted.status.missing > 0 ? [null] : []),
88 ]
89 const groups: BoardGroup[] = []
90 const labelled = new Map<string, number>()
91 let hidden = 0
92 let room = MATCH_BUDGET
93 for (const status of statuses) {
94 const ofStatus = byPriority(kept.filter((row) => (status === null ? isMissing(row.status) : row.status === status)))
95 const drawn: BoardRow[] = []
96 for (const row of ofStatus) {
97 if (row.path.length > MAX_PATH) hidden++
98 else {
99 const made = boardRow(row, room)
100 room -= made.fullTitle.length + made.fullTags.length
101 drawn.push(made)
102 }
103 }
104 if (!drawn.length) continue
105 const label = status === null ? null : statusLabel(status)
106 // `n` counts the earlier groups of the same label, so a cut status never shares a key and no filter moves one.
107 const n = labelled.get(label ?? '') ?? 0
108 labelled.set(label ?? '', n + 1)
109 groups.push({ status: label, key: groupKey(n, label ?? ''), count: statusCount(counted, status), rows: drawn })
110 }
111 return { groups, hidden }
112}
113
114const cost = (...parts: string[]) => ITEM_OVERHEAD + parts.reduce((sum, part) => sum + JSON.stringify(part).length, 0)
115
116// The heading and row items to draw, in order: filtered, ordered, unfolded, and cut before the item that would pass the budget.
117export function listItems(groups: BoardGroup[], list: ListSettings): { items: Item[]; hidden: number } {
118 const query = list.query.trim().toLowerCase()
119 const matches = (row: BoardRow) =>
120 (!list.priority || row.priority === list.priority) &&
121 (!query || row.fullTitle.toLowerCase().includes(query) || row.fullTags.toLowerCase().includes(query))
122 const items: Item[] = []
123 let hidden = 0
124 let spent = 0
125 let full = false
126 const place = (item: Item, size: number) => {
127 if (!full && spent + size <= LIST_BUDGET) {
128 items.push(item)
129 spent += size
130 return true
131 }
132 full = true
133 return false
134 }
135 for (const group of groups) {
136 const rows = group.rows.filter(matches)
137 if (!rows.length) continue
138 const open = !list.folded.includes(group.key)
139 const ordered = list.sort === 'title' ? [...rows].sort((a, b) => a.fullTitle.localeCompare(b.fullTitle)) : rows
140 const label = group.status ?? ''
141 if (!place({ kind: 'heading', key: group.key, label, status: group.status, count: rows.length, open }, cost(group.key, label))) {
142 hidden += rows.length
143 continue
144 }
145 if (!open) continue
146 for (const row of ordered) {
147 if (!place({ kind: 'row', key: row.key, row }, cost(row.key, row.title, row.tags))) hidden++
148 }
149 }
150 return { items, hidden }
151}
152hooks/list-view.ts 112 lines1import { bounded } from './bounds.ts'
2import { listItems } from './list.ts'
3import { QUERY_KEY } from './ring.ts'
4import type { BoardGroup, Item } from './list.ts'
5import { ACCENT, INACTIVE, RULE, SUBTLE, priorityColor, statusColor } from './style.ts'
6import { displayWidth, fitWidth } from './width.ts'
7import type { ObwList } from '../types/index.d.ts'
8
9export type ListHandlers = {
10 fold: (key: string) => void
11 open: (path: string) => void
12 focusQuery: () => void
13 query: (text: string) => void
14 submit: (text: string) => void
15 priority: () => void
16 sort: () => void
17 clear: () => void
18}
19
20const TAGS_MAX = 26
21
22const safe = (text: string) => bounded(text).text
23const fitted = (text: string, width: number) => fitWidth(text, width).trimEnd()
24
25const tint = (ui: any, color: string | undefined, text: string, more: Record<string, unknown> = {}) =>
26 ui.Text({ ...(color ? { color } : {}), ...more, children: [safe(text)] })
27
28export const isFiltered = (list: ObwList) => Boolean(list.query.trim() || list.priority)
29
30function toolbar(ui: any, handlers: ListHandlers, surface: string, list: ObwList) {
31 const button = (key: string, hotkey: string, label: string, onPress: () => void, more: Record<string, unknown> = {}) =>
32 ui.Button({ plain: true, key, hotkey, label, ...more, onPress })
33 return ui.Box({
34 flexDirection: 'row',
35 gap: 2,
36 children: [
37 // A phone has no text field to filter with.
38 ...(surface === 'mobile'
39 ? []
40 : [
41 ui.Box({
42 flexDirection: 'row',
43 children: [
44 button('focus-query', 'f', 'filter', handlers.focusQuery),
45 tint(ui, ACCENT, ' › '),
46 ui.Input({ key: QUERY_KEY, placeholder: 'tag or title', value: safe(list.query), onInput: handlers.query, onSubmit: handlers.submit }),
47 ],
48 }),
49 ]),
50 button('priority', 'p', `priority ${list.priority ?? 'all'}`, handlers.priority, list.priority ? {} : { dimColor: true }),
51 button('sort', 's', `sort ${list.sort}`, handlers.sort, { dimColor: true }),
52 ...(isFiltered(list) ? [button('clear', 'x', 'clear', handlers.clear)] : []),
53 ],
54 })
55}
56
57function heading(ui: any, handlers: ListHandlers, item: Extract<Item, { kind: 'heading' }>, isFirst: boolean) {
58 return ui.Box({
59 flexDirection: 'row',
60 marginTop: 1,
61 children: [
62 tint(ui, INACTIVE, item.open ? '▾ ' : '▸ '),
63 tint(ui, item.status === null ? undefined : statusColor(item.status), '● '),
64 ui.Button({ plain: true, key: item.key, label: safe(item.label || 'no status'), ...(isFirst ? { autoFocus: true } : {}), onPress: () => handlers.fold(item.key) }),
65 tint(ui, SUBTLE, ` ${item.count}`),
66 ],
67 })
68}
69
70function row(ui: any, handlers: ListHandlers, columns: number, { row }: Extract<Item, { kind: 'row' }>) {
71 const tags = fitted(row.tags, TAGS_MAX)
72 const titleWidth = Math.max(10, columns - 10 - (tags ? displayWidth(tags) + 2 : 0))
73 const letter = row.badge === ' ' ? '-' : row.badge
74 return ui.Box({
75 flexDirection: 'row',
76 justifyContent: 'space-between',
77 width: Math.max(0, columns - 2),
78 children: [
79 ui.Box({
80 flexDirection: 'row',
81 children: [
82 ui.Text({ children: [' '] }),
83 ui.Text({ children: [tint(ui, SUBTLE, '['), tint(ui, priorityColor(row.priority ?? undefined), letter, { bold: true }), tint(ui, SUBTLE, ']')] }),
84 ui.Text({ children: [' '] }),
85 ui.Button({ plain: true, key: row.key, label: safe(fitted(row.title, titleWidth) || '—'), onPress: () => handlers.open(row.path) }),
86 ],
87 }),
88 ...(tags ? [tint(ui, INACTIVE, tags, { wrap: 'truncate-end' })] : []),
89 ],
90 })
91}
92
93// The toolbar, the rule and the headings with their rows, under whatever the pane drew above.
94export function listChildren(
95 ui: any,
96 args: { surface: string; columns: number; ruleWidth: number; allTasks: { groups: BoardGroup[]; hidden: number }; list: ObwList; handlers: ListHandlers },
97) {
98 const { surface, columns, ruleWidth, allTasks, list, handlers } = args
99 const { items, hidden } = listItems(allTasks.groups, list)
100 const children: any[] = [toolbar(ui, handlers, surface, list), tint(ui, RULE, '─'.repeat(ruleWidth))]
101 if (!items.length) children.push(tint(ui, INACTIVE, '› no cards match'))
102 items.forEach((item, index) => children.push(item.kind === 'heading' ? heading(ui, handlers, item, index === 0) : row(ui, handlers, columns, item)))
103 const left = hidden + allTasks.hidden
104 if (left > 0) children.push(ui.Text({ dimColor: true, children: [`${left} more not shown`] }))
105 return children
106}
107
108export function listHints(ui: any, surface: string) {
109 const parts = ['↑↓ move', 'enter open or fold', ...(surface === 'mobile' ? [] : ['f filter']), 'esc close']
110 return ui.Box({ marginTop: 1, children: [tint(ui, SUBTLE, parts.join(' · '), { wrap: 'truncate-end' })] })
111}
112hooks/card.ts 62 lines1import type { ObwHeader, ObwRelations } from '../types/index.d.ts'
2import { unquote } from './yaml-scalar.ts'
3
4export type CardHeader = ObwHeader
5
6export function headerOf(frontmatter: string): CardHeader {
7 const header: CardHeader = {}
8 for (const line of frontmatter.split('\n')) {
9 // `s`: a value may hold a carriage return; drawing strips it, parsing must not drop the line.
10 const match = /^(title|status|priority):\s*(.*)$/s.exec(line)
11 if (!match) continue
12 const value = unquote(match[2].trim())
13 if (value) header[match[1] as keyof CardHeader] = value
14 }
15 return header
16}
17
18export const AC_HEADING = /^## acceptance criteria\s*$/i
19export const CHECKBOX =/^\s*[-*+] \[( |x|X)\](\s|$)/
20
21// The section runs to the next `#` or `##` heading; a `###` subheading stays inside it.
22export function acLabel(body: string): string | null {
23 const lines = body.split('\n')
24 const start = lines.findIndex((line) => AC_HEADING.test(line))
25 if (start < 0) return null
26 let checked = 0
27 let total = 0
28 for (const line of lines.slice(start + 1)) {
29 if (line.startsWith('# ') || line.startsWith('## ')) break
30 const box = CHECKBOX.exec(line)
31 if (!box) continue
32 total += 1
33 if (box[1] !== ' ') checked += 1
34 }
35 return total ? `AC ${checked}/${total}` : null
36}
37
38export type Relations = ObwRelations
39
40const RELATION_FIELD = /^(parent|blocked_by|related):(.*)$/s
41const WIKILINK = /\[\[([^\]]*)\]\]/g
42
43function targetsIn(line: string) {
44 return [...line.matchAll(WIKILINK)].map((match) => match[1].split(/[|#]/)[0].trim()).filter(Boolean)
45}
46
47// A field's list items follow it as `- ` lines; any other line closes the field.
48export function relationsOf(frontmatter: string): Relations {
49 const relations: Relations = { parent: [], blocked_by: [], related: [] }
50 let open: keyof Relations | null = null
51 for (const line of frontmatter.split('\n')) {
52 const field = RELATION_FIELD.exec(line)
53 if (field) open = field[1] as keyof Relations
54 else if (!open || !/^\s*-/.test(line)) {
55 open = null
56 continue
57 }
58 for (const target of targetsIn(field ? field[2] : line)) if (!relations[open!].includes(target)) relations[open!].push(target)
59 }
60 return relations
61}
62hooks/viz.ts 108 lines1import type { Run } from './cli-output.ts'
2
3export const RENDER_TIMEOUT_MS = 15_000
4
5// A relative directory has no defined base for $.fs, so it gives no manifest rather than a guessed one.
6export function vizManifestPath(configDir: string | undefined, home: string | undefined): string | null {
7 if (configDir) return configDir.startsWith('/') ? `${configDir}/plugins/installed_plugins.json` : null
8 if (home?.startsWith('/')) return `${home}/.claude/plugins/installed_plugins.json`
9 return null
10}
11
12function isRecord(value: unknown): value is Record<string, unknown> {
13 return typeof value === 'object' && value !== null && !Array.isArray(value)
14}
15
16function parsed(text: string): unknown {
17 try {
18 return JSON.parse(text)
19 } catch {
20 return null
21 }
22}
23
24// Two viz installs from different marketplaces give null rather than an arbitrary pick.
25export function vizInstallPath(text: string): string | null {
26 const manifest = parsed(text)
27 if (!isRecord(manifest) || !isRecord(manifest.plugins)) return null
28 const plugins = manifest.plugins
29 const keys = Object.keys(plugins).filter((key) => key.startsWith('viz@'))
30 if (keys.length !== 1) return null
31 const entries = plugins[keys[0]]
32 if (!Array.isArray(entries) || entries.length === 0) return null
33 const entry = entries.find((item) => isRecord(item) && item.scope === 'user') ?? entries[0]
34 if (!isRecord(entry)) return null
35 const { installPath } = entry
36 return typeof installPath === 'string' && installPath.startsWith('/') ? installPath : null
37}
38
39// The name lands unescaped in viz's HTML <title> and in a file name, so only a plain, capped slug passes.
40const SLUG = /^[A-Za-z0-9._-]+$/
41
42export function renderTarget(card: string): { file: string; name: string } {
43 const slug = SLUG.test(card) ? card.slice(0, 64) : 'card'
44 return { file: `/tmp/viz/obw/${slug}.md`, name: `obw-${slug}` }
45}
46
47export function renderArgv(vizRoot: string, target: { file: string; name: string }): string[] {
48 return ['bash', `${vizRoot}/lib/render.sh`, target.file, target.name]
49}
50
51const NOT_RUN = `viz did not render: render.sh could not start, or it did not finish within ${RENDER_TIMEOUT_MS / 1000} s.`
52
53// Only a first line that is an absolute path counts as success; anything else is shown as printed.
54export function renderOutcome(
55 run: Run,
56): { kind: 'opened'; path: string; url: string | null } | { kind: 'error'; message: string } {
57 if (run.kind === 'rejected') return { kind: 'error', message: NOT_RUN }
58 if (run.exitCode !== 0) {
59 const message = run.stderr.trim() || run.stdout.trim() || `viz render.sh exited ${run.exitCode} with no output.`
60 return { kind: 'error', message }
61 }
62 const [first, ...rest] = run.stdout.split('\n')
63 const path = first.trim()
64 if (!path.startsWith('/')) return { kind: 'error', message: run.stdout.trim() || 'viz render.sh printed no output path.' }
65 const urlLine = rest.find((line) => line.startsWith('URL: '))
66 return { kind: 'opened', path, url: urlLine ? urlLine.slice('URL: '.length).trim() : null }
67}
68
69export const SERVE_STATUS_ARGV = ['tailscale', 'serve', 'status', '--json']
70export const SERVE_TIMEOUT_MS = 5_000
71
72const LOOPBACK = new Set(['127.0.0.1', 'localhost'])
73
74function httpUrl(text: string): URL | null {
75 try {
76 const url = new URL(text)
77 return url.protocol === 'http:' ? url : null
78 } catch {
79 return null
80 }
81}
82
83export function isLoopbackUrl(text: string): boolean {
84 const url = httpUrl(text)
85 return url !== null && LOOPBACK.has(url.hostname)
86}
87
88// Only a port tailscale serve already proxies over HTTPS counts: reading the status never maps one.
89export function tailnetUrl(localUrl: string, statusJson: string): string | null {
90 const local = httpUrl(localUrl)
91 const status = parsed(statusJson)
92 if (!local || !LOOPBACK.has(local.hostname) || !isRecord(status) || !isRecord(status.Web)) return null
93 const tcp = isRecord(status.TCP) ? status.TCP : {}
94 for (const [hostPort, web] of Object.entries(status.Web)) {
95 const root = isRecord(web) && isRecord(web.Handlers) ? web.Handlers['/'] : null
96 const proxy = isRecord(root) && typeof root.Proxy === 'string' ? httpUrl(root.Proxy) : null
97 if (!proxy || !LOOPBACK.has(proxy.hostname) || proxy.port !== local.port || proxy.pathname !== '/') continue
98 const listener = tcp[hostPort.slice(hostPort.lastIndexOf(':') + 1)]
99 if (!isRecord(listener) || listener.HTTPS !== true) continue
100 try {
101 return new URL(`${local.pathname}${local.search}`, `https://${hostPort}`).href
102 } catch {
103 continue
104 }
105 }
106 return null
107}
108