SLOPSHOPPER

vault-jot

Capture ideas, takes, and reading items into an Obsidian vault inbox from any Claude Code session

panebandspinnercommandtoaststatus
★ 1v0.2.0no licenseupdated 2026-10-23Hsiang-LinC/vault-jot
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · vault-jot
│ ┃ jot-draft ✕ › fix the failing auth test and add an audit log call │ ┃ Summarizing the discussion… │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /jot │ ⎿ vault-jot: draft is in your prompt. Edit it and press Enter to s │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ vault-jot: vault-jot: vaultPath is not set; set it in /config under vault-jot

Draws

Pane · jot-draft
Summarizing the discussion…
Pane · ingest
⏳ Preparing the ingest plan…
Pane · incubate
vault-jot: vaultPath is not set; set it in /config under vault-jot
README

vault-jot

A Claude Code plugin for capturing thoughts into an Obsidian vault without leaving the session you are working in, and for keeping the vault's inbox from going stale.

Design and roadmap: docs/design.md.

Use

Most of the time, just write the thought:

/jot Obsidian Bases can group by any property
/jot https://example.com/long-post — recommended in the hooks thread

With no kind it is saved as note, and ingest decides what it becomes (idea, concept, pitfall, reading, ...) from the text and its origin. Prefix a kind when you already know, or when it needs a target:

/jot idea: a mod that turns jots into design docs
/jot improve @cx: make the panel smaller and navigable by layer
/jot read: https://example.com/long-post — recommended in the hooks thread
/jot til: Obsidian Bases can group by any property
/jot pitfall: fs.write creates missing parent directories
/jot plugin: claude-obsidian — lint is fast, the router ignores custom types

Each capture becomes inbox/jot-<YYYYMMDD-HHMMSS>-<kind>-<slug>.md in the vault, with flat frontmatter: title, kind, captured, and the origin (origin_cwd, origin_repo, origin_branch, origin_session). /jot runs immediately, even mid-turn. Kinds and how ingest files them are defined in the vault's Vault Guide ("Capture Kinds").

improve @<target>: is a change to make to an app. <target> is the repo's folder name, so a session in that repo can find it; leave it out when the jot is not about one app. Ingest files it as an idea with a target.

The prompt footer shows the backlog (📥 inbox 4 · 9d), and 🛠 cx 3 when a session runs in a repo that has open ideas targeting it; problems such as an unset or unreadable vaultPath go to the status line instead. When the inbox reaches backlogCount captures or its oldest is backlogDays old, a band above the prompt offers Ingest and Hide (for this session). Ingest plans in two steps: a background agent drafts the transaction without applying it, and a pane shows the plan and the pages it would write (new pages in full, changed pages as the lines they add) for you to Confirm or Discard; confirming applies exactly that plan. While it runs the band shows ⏳ Ingesting…. Afterwards each capture whose archived copy under .raw/captured/ is byte-identical is removed from the inbox, so the band recounts; any other stays.

/jot ingest does the same on demand, at any backlog size: it starts the plan right away and opens the pane. An empty inbox says so and starts nothing. Text that merely starts with the word (/jot ingest is slow) is still captured.

Recall from the vault

/recall <question> sends a read-only background subagent into the vault, where it searches with claude-obsidian's wiki-query (and wiki-retrieve when needed). Its answer, with the notes it rests on, waits in the incubate pane under Recall (c); a toast says when it is ready. Nothing enters your conversation until you press Add to chat, which appends it to the session for the model to read on its next turn. /recall alone opens the answers. The last 10 are kept for the session; an answer is cut at 20,000 characters.

Draft from the conversation

Any kind can name the repo it is about: /jot note @usage-band: add a toggle command. That target is the note's subject, which may differ from the repo you were in when you jotted it; drafts fill it in when the conversation is about a specific repo.

While you type /jot, the kind and @target turn green when known and a mistyped kind turns red; on the terminal the hint line under the prompt lists the kinds or targets that match what you have typed. A mistyped kind (/jot iddea: …) is refused rather than saved as a note.

Each conversation starts with a short index of vault notes for Claude: captures and open ideas whose target is the session's repo, then the other inbox titles (titles and paths only, bounded). When your work relates to one of them, Claude says so and names the file.

/jot with no text asks a fork of the conversation for the one thing worth keeping from the last few turns, and puts it in your prompt as /jot <kind>: <draft>. A kind alone (/jot pitfall:, /jot improve @cx:) drafts that kind. Edit the draft and press Enter to save, or clear it. Nothing is saved until you do.

/jot summary summarizes the whole discussion instead: a title line with the insight, then the question, the wrong turns and what corrected them, and where you landed. It opens in a Summary draft pane: Save (s) writes it to the inbox, Edit in prompt (e) moves it into your prompt as a /jot command, Discard (d) drops it. The fork always reads the whole transcript; only its prompt decides what it looks at.

Incubate

/incubate opens a small pane you move through layer by layer:

Shelves            🌱 Ideas 2   📖 Reading 1   Review
└ Ideas            ‹ Shelves · 🌱 Replay Mode · developing · 🌱 Smaller Panel @cx · seed
  └ Replay Mode    open questions, options [Choose], a Decision box, [Expand], [Hand off to <repo>]
└ Reading
  └ Hooks Post     url, [Reading] [Done] [Drop]
└ Review           open ideas per app, seeds waiting 14+ days

/incubate <title> jumps straight to an idea. Every change is handed to a background subagent of the session, so the turn you are in is never interrupted; a toast says when it starts and finishes (recorded under "## Decisions", status moves, idea handed off to the repo), so claude-obsidian stays the only writer under wiki/. Within a state, ideas group by target.

Hand off appears when the session is in a repo other than the vault. If the repo has a harness (docs/harness/index.md), Claude uses that repo's to-issues (or to-prd) skill; otherwise it writes docs/design/<title>.md. Either way the idea gets handoff: (what was created), project:, and status: archived. Hotkeys: b back, i/r/v shelves and review, 1–9 choose an option, e expand, x hand off or drop.

Configure

In /config, under vault-jot:

FieldDefaultMeaning
vaultPath(unset)Vault root, absolute or ~/.... Required; /jot refuses and the status line says so until it is set.
backlogCount10Band threshold by count.
backlogDays7Band threshold by age of the oldest capture.

The mod never creates inbox/: a missing one means a wrong vaultPath, and the capture is refused rather than written elsewhere.

Install

The repo is its own plugin marketplace (.claude-plugin/marketplace.json).

From GitHub (the repo is private, so git must be able to clone it, e.g. after gh auth setup-git):

claude plugin marketplace add Hsiang-LinC/vault-jot
claude plugin install vault-jot@vault-jot

From a local clone, read live from the folder (after an edit, run /reload-plugins):

claude plugin marketplace add ~/Developer/personal/vault-jot
claude plugin install vault-jot@vault-jot

Then set the vault path, in Claude Code with /plugin configure vault-jot@vault-jot, or:

echo '{"vaultPath":"~/Developer/personal/notes"}' | claude plugin configure vault-jot@vault-jot --values-stdin

Update a GitHub install with claude plugin marketplace update vault-jot then claude plugin update vault-jot@vault-jot. Install it one way only: the same plugin also loaded through --plugin-dir or a mods folder runs twice.

For a one-off session without installing: claude --plugin-dir ~/Developer/personal/vault-jot.

Develop

claude plugin validate .
claude plugin test .
tsc -p .   # once the engine has loaded the mod and written .claude-plugin/types/

hooks/core.ts (captures, backlog), hooks/notes.ts (reading notes) and hooks/handoff.ts (prompts for the subagents) are pure; hooks/register.tsx is the only module that talks to Claude Code, because the engine follows $ only into functions declared in the hooks module itself.

Source 9 files
hooks/register.tsx 1090 lines
1import { atom, read, update } from 'claude-code'
2import type { CommandRunResult, CommandSpec, EngineInterface, PluginOptions, Register } from 'claude-code'
3
4import type { IngestRun, OpenForRepo, Recall, Shelf, SummaryDraft, View } from '../types'
5
6import {
7  KINDS,
8  backlogLabel,
9  expandHome,
10  fileName,
11  isOverdue,
12  localStamp,
13  parseRequest,
14  renderNote,
15  summarizeInbox,
16} from './core'
17import type { DraftRequest, Jot, Thresholds } from './core'
18import {
19  HARNESS_INDEX,
20  archivedHash,
21  decisionPrompt,
22  draftCommand,
23  draftPrompt,
24  expandPrompt,
25  handoffPrompt,
26  ingestAgentPrompt,
27  ingestApplyPrompt,
28  ingestPlanPrompt,
29  outcomeOf,
30  parseApplied,
31  parseBundle,
32  parseDraft,
33  parsePlan,
34  planList,
35  previewMarkdown,
36  readingPrompt,
37} from './handoff'
38import type { Plan, ReadingState } from './handoff'
39import { claudeArgv, settledOf } from './headless'
40import type { Phase, Settled } from './headless'
41import { addRecall, chatContext, failRecall, recallPrompt, settleRecall } from './recall'
42import { SHELVES, STALE_SEED_DAYS, findNote, openForTarget, parseNote, reviewIdeas, sortNotes, stateOf, targetOf, titleOf } from './notes'
43import type { Note } from './notes'
44import { relatedIndex } from './related'
45import { readDraft } from './composer'
46
47const backlog = atom({ plugin: 'vault-jot', key: 'backlog' } as const, null)
48// Why the vault could not be read on the last refresh; null when it could.
49const problem = atom({ plugin: 'vault-jot', key: 'problem' } as const, null as string | null)
50const isHidden = atom({ plugin: 'vault-jot', key: 'isHidden' } as const, false)
51const openForRepo = atom({ plugin: 'vault-jot', key: 'openForRepo' } as const, null as OpenForRepo | null)
52const summary = atom({ plugin: 'vault-jot', key: 'summary' } as const, null as SummaryDraft | null)
53// What the prompt-hint line says about a `/jot` draft being typed, and the
54// targets it offers: the session's repo and those the ideas name.
55const draftHint = atom({ plugin: 'vault-jot', key: 'draftHint' } as const, null as string | null)
56const knownTargets = atom({ plugin: 'vault-jot', key: 'knownTargets' } as const, [] as string[])
57const ingestRun = atom({ plugin: 'vault-jot', key: 'ingestRun' } as const, null as IngestRun | null)
58const recalls = atom({ plugin: 'vault-jot', key: 'recalls' } as const, [] as Recall[])
59
60// Command output carries no "vault-jot:" prefix: Claude Code already labels
61// a plugin command's output with the plugin's name.
62const USAGE = `Usage: /jot [${KINDS.join('|')}:] <text>; /jot [<kind>:] or /jot summary to draft one; or /jot ingest`
63const MAX_NAME_ATTEMPTS = 5
64// Each ingest run is bounded in time and spend; a run past either fails. The
65// host caps `timeoutMs` at 10 minutes.
66const INGEST_TIMEOUT_MS = 10 * 60 * 1000
67const INGEST_BUDGET_USD = 3
68const NO_VERDICT = /classifier gave no verdict/i
69// Inbox files read for the related-notes index; past this the oldest are left out.
70const INBOX_READ_MAX = 100
71const GIT_TIMEOUT_MS = 3000
72const STATUS_MAX = 80
73const TOAST_MAX = 160
74const FAILURE_TOAST_MS = 20000
75const ANSWER_LINES = 60
76const RECALL_ICON = { running: '⏳', done: '✓', failed: '✗' } as const
77
78// Requests for Claude run as background subagents of this session, so they
79// never type into the prompt box or interrupt a turn in progress. `jobs` maps
80// a running subagent's id to what it was asked, until its turn completes.
81// `onSettled` receives its end (for a request whose answer is the point).
82type Job = { label: string; onSettled?: (reason: string, answer: string) => Promise<void> }
83type Jobs = Map<string, Job>
84
85// `cwd` is where the subagent works; the vault for vault-only requests. A
86// request with `onSettled` needs the subagent's id to be answered, so
87// without one it fails; any other only loses its completion toast.
88async function dispatch(
89  $: EngineInterface,
90  jobs: Jobs,
91  label: string,
92  prompt: string,
93  cwd?: string,
94  onSettled?: Job['onSettled'],
95  subagentType?: string,
96) {
97  const request = {
98    prompt,
99    description: label,
100    ...(cwd === undefined ? {} : { cwd }),
101    ...(subagentType === undefined ? {} : { subagentType }),
102  }
103  let spawned = await $.agent.spawn(request)
104  if (spawned.deny !== undefined && NO_VERDICT.test(spawned.deny)) {
105    // The auto-mode classifier occasionally returns no verdict; its own
106    // message asks for the action to be issued again once, as-is.
107    $.ui.log(`vault-jot: retrying spawn once: ${spawned.deny}`, { to: 'debug' })
108    spawned = await $.agent.spawn(request)
109  }
110  if (spawned.deny !== undefined) {
111    throw new Error(spawned.deny)
112  }
113  if (spawned.agentId === undefined) {
114    if (onSettled !== undefined) {
115      throw new Error('the engine started the subagent without an id, so its answer cannot be collected')
116    }
117    $.ui.toast(`vault-jot: started in the background: ${label} (no completion notice)`)
118
119    return
120  }
121  jobs.set(spawned.agentId, onSettled === undefined ? { label } : { label, onSettled })
122  $.ui.toast(`vault-jot: started in the background: ${label}`)
123}
124
125const firstLine = (text: string) => (text.split('\n').find(line => line.trim() !== '') ?? '').trim().slice(0, TOAST_MAX)
126
127type Config = { vaultPath: string; thresholds: Thresholds }
128
129function readConfig(options: PluginOptions): Config {
130  return {
131    vaultPath: String(options.vaultPath ?? '').trim(),
132    thresholds: { count: Number(options.backlogCount ?? 10), days: Number(options.backlogDays ?? 7) },
133  }
134}
135
136const describe = (error: unknown) => (error instanceof Error ? error.message : String(error))
137
138// Resolves the vault root, failing loudly when it is unset or does not look
139// like a vault. `$.fs.write` creates missing directories, so writing without
140// this check would silently start a new "vault" at a mistyped path.
141async function resolveVault($: EngineInterface, config: Config) {
142  if (config.vaultPath === '') {
143    throw new Error('vaultPath is not set; set it in /config under vault-jot')
144  }
145  const vault = expandHome(config.vaultPath, await $.env.get('HOME')).replace(/\/+$/, '')
146  const inbox = `${vault}/inbox`
147  const stat = await $.fs.stat(inbox).catch((error: unknown) => {
148    throw new Error(`cannot read ${inbox}: ${describe(error)}`)
149  })
150  if (stat.kind !== 'dir') {
151    throw new Error(`${inbox} is not a directory`)
152  }
153
154  return { vault, inbox }
155}
156
157// Provenance is best effort: outside a repo, or where processes cannot run
158// (a desktop host), the capture is still saved without a branch.
159async function gitBranch($: EngineInterface, cwd: string): Promise<string | null> {
160  try {
161    const { exitCode, stdout } = await $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], {
162      cwd,
163      timeoutMs: GIT_TIMEOUT_MS,
164    })
165
166    return exitCode === 0 && stdout.trim() !== '' ? stdout.trim() : null
167  } catch (error) {
168    $.ui.log(`vault-jot: no branch recorded: ${describe(error)}`, { to: 'debug' })
169
170    return null
171  }
172}
173
174async function freePath($: EngineInterface, inbox: string, jot: Jot, compactStamp: string) {
175  for (let attempt = 0; attempt < MAX_NAME_ATTEMPTS; attempt += 1) {
176    const path = `${inbox}/${fileName(jot, compactStamp, attempt)}`
177    if (!(await $.fs.exists(path))) {
178      return path
179    }
180  }
181  throw new Error(`${MAX_NAME_ATTEMPTS} captures with the same name this second; try again`)
182}
183
184async function capture($: EngineInterface, config: Config, jot: Jot): Promise<string> {
185  const { inbox } = await resolveVault($, config)
186  const now = await $.clock.now()
187  const stamp = localStamp(now, -new Date(now).getTimezoneOffset())
188  const cwd = await $.session.cwd()
189  const [repo, branch, session] = await Promise.all([$.session.repo(), gitBranch($, cwd), $.session.id()])
190  const note = renderNote(jot, stamp.iso, {
191    cwd,
192    repo: repo === null ? null : (repo.remote ?? repo.root),
193    branch,
194    session,
195  })
196  const path = await freePath($, inbox, jot, stamp.compact)
197  await $.fs.write(path, note)
198
199  return path.slice(inbox.length + 1)
200}
201
202// The backlog shows as a prompt-footer label (see the SessionMode hook); the
203// status line is kept for problems, which the engine marks as notices.
204// A fork of the conversation drafts one capture; the reason when it cannot.
205async function requestDraft($: EngineInterface, request: DraftRequest): Promise<Jot | string> {
206  const reply = await $.model.fork({ prompt: draftPrompt(request) })
207  if (!reply.isAnswered) {
208    return reply.reason === 'nothing-to-fork'
209      ? `nothing to draft from yet. ${USAGE}`
210      : `could not draft a capture (${reply.reason}). ${USAGE}`
211  }
212
213  return parseDraft(reply.text, request) ?? `the draft came back empty. ${USAGE}`
214}
215
216// `/jot` or `/jot <kind>:`: the one-line draft goes into the prompt box as a
217// `/jot` command, so nothing is saved until the person edits or accepts it
218// with Enter. `/jot summary` previews its many lines in a pane instead.
219async function draft($: EngineInterface, request: DraftRequest): Promise<CommandRunResult> {
220  if (request.scope === 'summary') {
221    return draftSummary($)
222  }
223  const jot = await requestDraft($, request)
224  if (typeof jot === 'string') {
225    return { text: jot }
226  }
227  const command = draftCommand(jot, request.scope)
228  const filled = await $.prompt.fill({ text: command })
229  if (!filled.isFilled) {
230    return { text: `could not fill the prompt (${filled.refusal ?? 'refused'}). Draft: ${command}` }
231  }
232
233  return { text: 'draft is in your prompt. Edit it and press Enter to save, or clear it.' }
234}
235
236async function draftSummary($: EngineInterface): Promise<CommandRunResult> {
237  await update($, summary, () => ({ status: 'drafting' }))
238  const opened = await $.ui.open({ id: DRAFT_PANE, title: 'Summary draft' })
239  const jot = await requestDraft($, { scope: 'summary' })
240  const settled: SummaryDraft = typeof jot === 'string' ? { status: 'failed', reason: jot } : { status: 'ready', jot }
241  await update($, summary, () => settled)
242  if (typeof jot === 'string') {
243    return { text: jot }
244  }
245
246  return { text: opened.isPlaced ? 'summary draft is in the pane.' : `summary drafted; the pane is waiting: ${opened.reason}` }
247}
248
249const INGEST_PANE = 'ingest'
250const REMOVE_TIMEOUT_MS = 5000
251const PREVIEW_LINES = 30
252
253// Ingest runs as its own `claude -p` process, not a subagent of this session:
254// auto mode returns no verdict for a spawn a button made, and the process
255// needs no conversation. `$.process.run` is not awaited, so the band shows
256// `⏳ Ingesting…` while it runs; `onSettled` gets its end like a subagent's.
257async function startIngestRun(
258  $: EngineInterface,
259  config: Config,
260  label: string,
261  prompt: string,
262  vault: string,
263  phase: Phase,
264  onSettled: NonNullable<Job['onSettled']>,
265) {
266  const settle = async () => {
267    let settled: Settled
268    try {
269      const done = await $.process.run(claudeArgv({ vault, phase, systemPrompt: ingestAgentPrompt, budgetUsd: INGEST_BUDGET_USD }), {
270        stdin: prompt,
271        timeoutMs: INGEST_TIMEOUT_MS,
272      })
273      settled = settledOf(done)
274    } catch (error) {
275      settled = { reason: `could not run claude -p: ${describe(error)}`, answer: '' }
276    }
277    await onSettled(settled.reason, settled.answer)
278    const { failed, detail } = outcomeOf(settled.reason, settled.answer)
279    $.ui.toast(`vault-jot: ${failed ? 'failed' : 'done'}: ${label}${failed ? ` · ${firstLine(detail)}` : ''}`, {
280      timeoutMs: failed ? FAILURE_TOAST_MS : 8000,
281    })
282    await refresh($, config)
283    $.ui.invalidate('ui.render')
284  }
285  void settle().catch((error: unknown) => {
286    $.ui.log(`vault-jot: ingest run ended badly: ${describe(error)}`, { to: 'debug' })
287    $.ui.toast(`vault-jot: failed: ${label} · ${firstLine(describe(error))}`, { timeoutMs: FAILURE_TOAST_MS })
288  })
289}
290
291const failed = (reason: string): IngestRun => ({ status: 'failed', reason })
292const setRun = ($: EngineInterface, next: IngestRun | null) => update($, ingestRun, () => next)
293
294// The plan is back: read the pages its bundle will write and show them for
295// review, or why there is no plan. A plan whose pages cannot be shown is not
296// offered for confirmation.
297const planSettled =
298  ($: EngineInterface, config: Config, files: string[]): NonNullable<Job['onSettled']> =>
299  async (reason, answer) => {
300    const parsed = parsePlan(reason, answer)
301    if (!parsed.ok) {
302      await setRun($, failed(parsed.reason))
303
304      return
305    }
306    try {
307      const { vault } = await resolveVault($, config)
308      const writes = parseBundle(await $.fs.read(parsed.value.bundle))
309      const current: Record<string, string> = {}
310      for (const write of writes.filter(write => write.mode !== 'create' && !write.path.startsWith('.raw/'))) {
311        const path = `${vault}/${write.path}`
312        current[write.path] = (await $.fs.exists(path)) ? await $.fs.read(path) : ''
313      }
314      await setRun($, { status: 'review', files, plan: parsed.value, preview: previewMarkdown(writes, current, PREVIEW_LINES) })
315    } catch (error) {
316      await setRun($, failed(`could not read the plan's pages: ${describe(error)}`))
317    }
318  }
319
320// An inbox file is removed only once the apply archived it: the manifest
321// recorded its hash and `.raw/captured/<hash>.md` holds the same text.
322async function removeArchived($: EngineInterface, vault: string, inbox: string, names: readonly string[]) {
323  const manifest = await $.fs.read(`${vault}/.raw/.manifest.json`)
324  const removed: string[] = []
325  const kept: string[] = []
326  for (const name of names) {
327    const hash = archivedHash(manifest, name)
328    const copy = hash === null ? null : `${vault}/.raw/captured/${hash}.md`
329    const path = `${inbox}/${name}`
330    const isArchived =
331      copy !== null && (await $.fs.exists(copy)) && (await $.fs.exists(path)) && (await $.fs.read(copy)) === (await $.fs.read(path))
332    const done = isArchived ? await $.process.run(['rm', '--', path], { timeoutMs: REMOVE_TIMEOUT_MS }) : null
333    if (done !== null && done.exitCode === 0) {
334      removed.push(name)
335    } else {
336      kept.push(name)
337    }
338  }
339
340  return { removed, kept }
341}
342
343// The apply is back: clear the archived captures from the inbox, then report.
344const applySettled =
345  ($: EngineInterface, config: Config, files: string[]): NonNullable<Job['onSettled']> =>
346  async (reason, answer) => {
347    const applied = parseApplied(reason, answer)
348    if (!applied.ok) {
349      await setRun($, failed(applied.reason))
350
351      return
352    }
353    try {
354      const { vault, inbox } = await resolveVault($, config)
355      const { removed, kept } = await removeArchived($, vault, inbox, files)
356      await refresh($, config)
357      const left = kept.length === 0 ? '' : ` Kept in the inbox, with no verified archived copy: ${kept.join(', ')}.`
358      await setRun($, {
359        status: 'done',
360        message: `Filed ${files.length} captures; removed ${removed.length} from the inbox.${left}\n\n${applied.value}`,
361      })
362    } catch (error) {
363      await setRun($, failed(`applied, but clearing the inbox failed: ${describe(error)}`))
364    }
365  }
366
367// The pane's Confirm: apply exactly the plan that was reviewed.
368async function confirmIngest($: EngineInterface, config: Config, files: string[], plan: Plan) {
369  try {
370    const { vault } = await resolveVault($, config)
371    await setRun($, { status: 'applying', files })
372    await startIngestRun($, config, `apply ingest of ${files.length} captures`, ingestApplyPrompt(vault, plan), vault, 'apply', applySettled($, config, files))
373  } catch (error) {
374    await setRun($, failed(describe(error)))
375  }
376}
377
378// `/jot ingest` and the band's Ingest button, whatever the thresholds: plan the
379// inbox in the background and open the pane for the person to review it.
380async function ingest($: EngineInterface, config: Config): Promise<CommandRunResult> {
381  try {
382    const current = await read($, ingestRun)
383    if (current?.status === 'planning' || current?.status === 'applying') {
384      return { text: 'an ingest is already running.' }
385    }
386    if (current?.status === 'review') {
387      await $.ui.open({ id: INGEST_PANE, title: 'Ingest' })
388
389      return { text: 'a plan is waiting for your review in the pane.' }
390    }
391    const { vault, inbox } = await resolveVault($, config)
392    const names = (await $.fs.list(inbox)).filter(entry => entry.kind === 'file' && !entry.name.startsWith('.')).map(entry => entry.name)
393    if (names.length === 0) {
394      return { text: 'inbox is empty; nothing to ingest.' }
395    }
396    await setRun($, { status: 'planning', files: names })
397    await $.ui.open({ id: INGEST_PANE, title: 'Ingest' })
398    await startIngestRun($, config, `plan ingest of ${names.length} captures`, ingestPlanPrompt(vault, names), vault, 'plan', planSettled($, config, names))
399
400    return { text: `planning ${names.length} captures in the background; the plan opens in the pane.` }
401  } catch (error) {
402    return { text: `not started: ${describe(error)}` }
403  }
404}
405
406let recallSeq = 0
407
408// `/recall <question>`: a read-only subagent searches the vault with the
409// claude-obsidian skills; its answer lands in the pane, not the conversation.
410async function recall($: EngineInterface, config: Config, jobs: Jobs, question: string): Promise<CommandRunResult> {
411  const id = `${await $.clock.now()}-${(recallSeq += 1)}`
412  try {
413    const { vault } = await resolveVault($, config)
414    await update($, recalls, list => addRecall(list, { id, question, status: 'running', answer: '' }))
415    const settle = async (reason: string, answer: string) => {
416      await update($, recalls, list => settleRecall(list, id, reason, answer))
417    }
418    try {
419      await dispatch($, jobs, `recall: ${firstLine(question)}`, recallPrompt(vault, question), vault, settle)
420    } catch (error) {
421      await update($, recalls, list => failRecall(list, id, describe(error)))
422      throw error
423    }
424
425    return { text: 'asking the vault in the background; the answer shows under /recall.' }
426  } catch (error) {
427    return { text: `not started: ${describe(error)}` }
428  }
429}
430
431// The last path segment of the session's repo, which is what an idea's
432// `target` is matched against; null outside a repo and inside the vault.
433async function repoName($: EngineInterface, vault: string): Promise<string | null> {
434  const repo = await $.session.repo()
435
436  return repo === null || repo.root === vault ? null : (repo.root.replace(/\/+$/, '').split('/').at(-1) ?? null)
437}
438
439// The inbox backlog and the open ideas aimed at this repo, as short labels.
440async function footerLabels($: EngineInterface): Promise<string[]> {
441  const current = await read($, backlog)
442  const forRepo = await read($, openForRepo)
443
444  return [
445    current === null ? undefined : backlogLabel(current),
446    forRepo === null || forRepo.count === 0 ? undefined : `🛠 ${forRepo.target} ${forRepo.count}`,
447  ].filter(label => label !== undefined)
448}
449
450async function refresh($: EngineInterface, config: Config) {
451  try {
452    const { vault, inbox } = await resolveVault($, config)
453    const files = (await $.fs.list(inbox)).filter(entry => entry.kind === 'file')
454    const next = summarizeInbox(files, await $.clock.now())
455    const name = await repoName($, vault)
456    const ideas = (await loadShelf($, vault, 'ideas')).notes
457    $.ui.status(undefined)
458    await update($, problem, () => null)
459    await update($, backlog, () => next)
460    await update($, openForRepo, () => (name === null ? null : { target: name, count: openForTarget(ideas, name).length }))
461    const targets = [name, ...ideas.map(targetOf)].filter((target): target is string => target !== null && target !== undefined)
462    await update($, knownTargets, () => [...new Set(targets)].sort())
463  } catch (error) {
464    $.ui.status(`vault-jot: ${describe(error)}`.slice(0, STATUS_MAX))
465    await update($, problem, () => describe(error).slice(0, STATUS_MAX))
466    await update($, backlog, () => null)
467    await update($, openForRepo, () => null)
468  }
469}
470
471// The incubate pane browses wiki/ideas and wiki/reading; it only reads notes
472// and hands every change to Claude.
473const PANE = 'incubate'
474// Where `/jot summary` previews its draft before anything is saved.
475const DRAFT_PANE = 'jot-draft'
476const HOME: View = { layer: 'home' }
477const view = atom({ plugin: 'vault-jot', key: 'view' } as const, HOME)
478
479// Each draw reads a shelf's notes from disk, so the pane always shows what
480// Claude last wrote. Bounded: past this many notes a shelf says it is cut.
481const SHELF_MAX = 200
482
483type Loaded = { notes: Note[]; isTruncated: boolean }
484
485async function loadShelf($: EngineInterface, vault: string, shelf: Shelf): Promise<Loaded> {
486  const dir = `${vault}/${SHELVES[shelf].folder}`
487  // No folder yet means nothing has been ingested into this shelf.
488  if (!(await $.fs.exists(dir))) {
489    return { notes: [], isTruncated: false }
490  }
491  const files = (await $.fs.list(dir))
492    .filter(entry => entry.kind === 'file' && entry.name.endsWith('.md'))
493    .sort((a, b) => a.name.localeCompare(b.name))
494  const kept = files.slice(0, SHELF_MAX)
495  const notes = await Promise.all(kept.map(async entry => parseNote(entry.name, await $.fs.read(`${dir}/${entry.name}`))))
496
497  return { notes: sortNotes(shelf, notes), isTruncated: files.length > kept.length }
498}
499
500const notePath = (vault: string, shelf: Shelf, file: string) => `${vault}/${SHELVES[shelf].folder}/${file}`
501
502const RECALL_COMMAND: CommandSpec = {
503  name: 'recall',
504  description: 'Ask the vault a question in the background; the answer waits in the incubate pane',
505  argumentHint: '<question>, or nothing to open the answers',
506}
507
508const INCUBATE_COMMAND: CommandSpec = {
509  name: 'incubate',
510  description: 'Browse vault ideas and reading, and decide what to do with them',
511  argumentHint: '[idea title]',
512}
513
514export const register: Register = (on, options) => {
515  const config = readConfig(options)
516  const jobs: Jobs = new Map()
517
518  on('session.start', async ($, e, next) => {
519    await $.command.register({
520      name: 'jot',
521      description: 'Capture a thought into the vault inbox',
522      argumentHint: `[${KINDS.join('|')}:] [text] | summary | ingest`,
523      immediate: true,
524    })
525    await $.command.register(INCUBATE_COMMAND)
526    await $.command.register(RECALL_COMMAND)
527    await refresh($, config)
528
529    return next(e)
530  })
531
532  on('command.run', { command: 'jot' }, async ($, e) => {
533    await update($, draftHint, () => null)
534    const request = parseRequest(e.args)
535    if (request.mode === 'draft') {
536      return draft($, request)
537    }
538    if (request.mode === 'ingest') {
539      return ingest($, config)
540    }
541    if (request.mode === 'invalid') {
542      return { text: `not saved: ${request.reason}` }
543    }
544    const { jot } = request
545    try {
546      const name = await capture($, config, jot)
547      await refresh($, config)
548
549      return { text: `Jotted ${jot.kind} → inbox/${name}` }
550    } catch (error) {
551      return { text: `not saved: ${describe(error)}` }
552    }
553  })
554
555  // Ingest may run in any session, so recount after each main-agent turn;
556  // Claude may also have edited notes the incubate pane shows. A background
557  // job this mod started reports when its own turn completes.
558  on('turn.complete', async ($, e, next) => {
559    const job = e.agentId === undefined ? undefined : jobs.get(e.agentId)
560    if (e.agentId !== undefined && job !== undefined) {
561      jobs.delete(e.agentId)
562      await job.onSettled?.(e.reason, e.answer)
563      const { failed, detail: answered } = outcomeOf(e.reason, e.answer)
564      const detail = failed || job.onSettled === undefined ? firstLine(answered) : ''
565      const outcome = failed ? `failed: ${job.label}` : `done: ${job.label}`
566      $.ui.toast(`vault-jot: ${outcome}${detail === '' ? '' : ` · ${detail}`}`, { timeoutMs: failed ? FAILURE_TOAST_MS : 8000 })
567      await refresh($, config)
568      $.ui.invalidate('ui.render')
569    } else if (e.agentId === undefined) {
570      await refresh($, config)
571      $.ui.invalidate('ui.render')
572    }
573
574    return next(e)
575  })
576
577  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
578    const labels = await footerLabels($)
579
580    return labels.length === 0 ? next(e) : next({ ...e, props: { ...e.props, modes: [...e.props.modes, ...labels] } })
581  })
582
583  // The band other mods share: this one sets its items at the right end of
584  // what they drew (`next(e)`), never in place of it. On the desktop, which
585  // draws no footer labels, the items also carry them and any vault problem
586  // the status line would show; elsewhere they appear only while the inbox
587  // is overdue.
588  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
589    if (e.props.hasSurvey) {
590      return next(e)
591    }
592    const current = await read($, backlog)
593    const run = await read($, ingestRun)
594    const isRunning = run?.status === 'planning' || run?.status === 'applying'
595    const isReviewing = run?.status === 'review'
596    const isDue = current !== null && isOverdue(current, config.thresholds) && !(await read($, isHidden)) && !isRunning && !isReviewing
597    const isDesktop = e.surface === 'desktop'
598    // While a `/jot` draft is typed, its hint takes the labels' place, so the
599    // desktop (which draws no hint line) gets the candidates where the row
600    // already is, and nothing jumps.
601    const typing = isDesktop ? await read($, draftHint) : null
602    const labels = typing !== null ? [typing] : isDesktop ? await footerLabels($) : []
603    const fault = isDesktop ? await read($, problem) : null
604    if (!isDue && !isRunning && !isReviewing && labels.length === 0 && fault === null) {
605      return next(e)
606    }
607    const beneath = await next(e)
608    const { Box, Button, Text } = $.ui.resolve(e)
609    const runIngest = async () => {
610      $.ui.toast(`vault-jot: ${(await ingest($, config)).text}`)
611    }
612
613    // The desktop trims the whitespace at each flex item's edges, so the
614    // items are spaced with `gap`, not with spaces inside their text.
615    return (
616      <Box justifyContent="space-between" gap={2}>
617        <Box flexShrink={1}>{beneath}</Box>
618        <Box flexShrink={0} gap={1} paddingRight={1}>
619          {fault === null ? null : <Text color="red">vault-jot: {fault}</Text>}
620          {labels.length === 0 ? null : <Text dimColor>{labels.join(' · ')}</Text>}
621          {isRunning ? <Text key="running">⏳ Ingesting…</Text> : null}
622          {isReviewing ? <Button key="review" label="Review ingest plan" variant="primary" onPress={() => void $.ui.open({ id: INGEST_PANE, title: 'Ingest' })} /> : null}
623          {isDue ? <Button key="ingest" label="Ingest" variant="primary" onPress={runIngest} /> : null}
624          {isDue ? <Button key="hide" label="Hide" onPress={() => update($, isHidden, () => true)} /> : null}
625        </Box>
626      </Box>
627    )
628  })
629
630  // `/jot` as it is typed: the kind and target are painted (red for a
631  // mistyped kind), and the prompt-hint line lists what could come next.
632  on('prompt.edit', async ($, e, next) => {
633    const box = await next(e)
634    const reading = readDraft(box.text, await read($, knownTargets))
635    const hint = reading?.hint ?? null
636    if (hint !== (await read($, draftHint))) {
637      await update($, draftHint, () => hint)
638    }
639    if (reading === null || reading.marks.length === 0) {
640      return box
641    }
642    const painted = reading.marks.map(mark =>
643      mark.state === 'ok'
644        ? { start: mark.start, end: mark.end, color: 'green' }
645        : { start: mark.start, end: mark.end, color: 'red', underline: true },
646    )
647
648    return { ...box, decorations: [...(box.decorations ?? []), ...painted] }
649  })
650
651  // The terminal draws `tail` after the engine's hint line; no other surface
652  // draws it yet, so the desktop gets the painted draft alone.
653  on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
654    const hint = await read($, draftHint)
655
656    return hint === null || !e.props.isDraft ? next(e) : next({ ...e, props: { ...e.props, tail: `${e.props.tail ?? ''}  ${hint}` } })
657  })
658
659  // A conversation starts with the index of vault notes that may bear on it
660  // (see related.ts); computed once, re-read on compaction and /clear. A
661  // vault that cannot be read adds nothing: the status line already says why.
662  on('prompt.context', async ($, e, next) => {
663    const built = await next(e)
664    let text: string | null
665    try {
666      const { vault, inbox } = await resolveVault($, config)
667      const entries = (await $.fs.list(inbox))
668        .filter(entry => entry.kind === 'file' && entry.name.endsWith('.md') && !entry.name.startsWith('.'))
669        .sort((a, b) => b.mtimeMs - a.mtimeMs)
670        .slice(0, INBOX_READ_MAX)
671      const captures = await Promise.all(entries.map(async entry => parseNote(entry.name, await $.fs.read(`${inbox}/${entry.name}`))))
672      const repo = await repoName($, vault)
673      const ideas = repo === null ? [] : openForTarget((await loadShelf($, vault, 'ideas')).notes, repo)
674      text = relatedIndex({ vault, repo, captures, ideas })
675    } catch (error) {
676      $.ui.log(`vault-jot: no related-notes index: ${describe(error)}`)
677      text = null
678    }
679
680    return text === null ? built : { ...built, blocks: [...built.blocks, { name: 'vaultNotes', text }] }
681  })
682
683  // `/recall <question>` starts a search; `/recall` alone opens its answers.
684  on('command.run', { command: 'recall' }, async ($, e) => {
685    const question = e.args.trim()
686    if (question !== '') {
687      return recall($, config, jobs, question)
688    }
689    try {
690      await resolveVault($, config)
691      await update($, view, () => ({ layer: 'recalls' }))
692      const opened = await $.ui.open({ id: PANE, title: 'Incubate', focus: true })
693
694      return { text: opened.isPlaced ? 'recall answers opened.' : `The pane is waiting: ${opened.reason}` }
695    } catch (error) {
696      return { text: `cannot open recall: ${describe(error)}` }
697    }
698  })
699
700  // The incubate pane: shelves → notes → one note, with decisions handed to a background subagent.
701  on('command.run', { command: 'incubate' }, async ($, e) => {
702    try {
703      const { vault } = await resolveVault($, config)
704      const query = e.args.trim()
705      let next: View = HOME
706      let text = 'incubate pane opened.'
707      if (query !== '') {
708        const found = findNote((await loadShelf($, vault, 'ideas')).notes, query)
709        if (found === undefined || found === 'ambiguous') {
710          next = { layer: 'list', shelf: 'ideas' }
711          text =
712            found === undefined
713              ? `no idea matches "${query}"; showing all ideas.`
714              : `several ideas match "${query}"; pick one.`
715        } else {
716          next = { layer: 'detail', shelf: 'ideas', file: found.file }
717        }
718      }
719      await update($, view, () => next)
720      const opened = await $.ui.open({ id: PANE, title: 'Incubate', focus: true })
721
722      return { text: opened.isPlaced ? text : `${text} The pane is waiting: ${opened.reason}` }
723    } catch (error) {
724      return { text: `cannot open incubate: ${describe(error)}` }
725    }
726  })
727
728  on('ui.render', { component: 'Pane', requestId: DRAFT_PANE }, async ($, e) => {
729    const { Box, Button, Markdown, Text } = $.ui.resolve(e)
730    const current = await read($, summary)
731    const close = async () => {
732      await update($, summary, () => null)
733      await $.ui.close({ id: DRAFT_PANE })
734    }
735    if (current === null || current.status === 'drafting') {
736      return <Text dimColor>Summarizing the discussion…</Text>
737    }
738    if (current.status === 'failed') {
739      return (
740        <Box flexDirection="column">
741          <Text color="red">{current.reason}</Text>
742          <Button key="discard" hotkey="d" label="Close" onPress={close} />
743        </Box>
744      )
745    }
746    const { jot } = current
747    const save = async () => {
748      try {
749        const name = await capture($, config, jot)
750        await refresh($, config)
751        $.ui.toast(`vault-jot: Jotted ${jot.kind} → inbox/${name}`.slice(0, TOAST_MAX))
752        await close()
753      } catch (error) {
754        $.ui.toast(`vault-jot: not saved: ${describe(error)}`.slice(0, TOAST_MAX))
755      }
756    }
757    const edit = async () => {
758      const filled = await $.prompt.fill({ text: draftCommand(jot, 'summary') })
759      if (filled.isFilled) {
760        await close()
761      } else {
762        $.ui.toast(`vault-jot: could not fill the prompt (${filled.refusal ?? 'refused'})`)
763      }
764    }
765
766    return (
767      <Box flexDirection="column">
768        <Text dimColor>{jot.kind}</Text>
769        <Markdown text={`## ${jot.text}`} />
770        <Box>
771          <Button key="save" hotkey="s" label="Save" variant="primary" onPress={save} />
772          <Text> </Text>
773          <Button key="edit" hotkey="e" label="Edit in prompt" onPress={edit} />
774          <Text> </Text>
775          <Button key="discard" hotkey="d" label="Discard" onPress={close} />
776        </Box>
777      </Box>
778    )
779  })
780
781  on('ui.render', { component: 'Pane', requestId: INGEST_PANE }, async ($, e) => {
782    const { Box, Button, Markdown, Text } = $.ui.resolve(e)
783    const run = await read($, ingestRun)
784    const close = async () => {
785      await setRun($, null)
786      await $.ui.close({ id: INGEST_PANE })
787    }
788    if (run === null || run.status === 'planning') {
789      return <Text dimColor>⏳ Preparing the ingest plan…</Text>
790    }
791    if (run.status === 'applying') {
792      return <Text dimColor>⏳ Applying the ingest…</Text>
793    }
794    if (run.status === 'failed') {
795      return (
796        <Box flexDirection="column">
797          <Text color="red">{run.reason}</Text>
798          <Button key="close" hotkey="d" label="Close" onPress={close} />
799        </Box>
800      )
801    }
802    if (run.status === 'done') {
803      return (
804        <Box flexDirection="column">
805          <Markdown text={run.message.split('\n').slice(0, ANSWER_LINES).join('\n')} />
806          <Button key="close" hotkey="d" label="Close" onPress={close} />
807        </Box>
808      )
809    }
810    const { files, plan } = run
811
812    return (
813      <Box flexDirection="column">
814        <Text dimColor>Plan for {files.length} captures. Nothing is changed until you confirm.</Text>
815        <Markdown text={planList(plan.summary.split('\n').slice(0, ANSWER_LINES).join('\n'))} />
816        <Markdown text={run.preview} />
817        <Box>
818          <Button key="confirm" hotkey="c" label="Confirm" variant="primary" onPress={() => confirmIngest($, config, files, plan)} />
819          <Text> </Text>
820          <Button key="discard" hotkey="d" label="Discard" onPress={close} />
821        </Box>
822      </Box>
823    )
824  })
825
826  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
827    const { Box, Button, Text } = $.ui.resolve(e)
828    let vault: string
829    try {
830      vault = (await resolveVault($, config)).vault
831    } catch (error) {
832      return <Text color="red">vault-jot: {describe(error)}</Text>
833    }
834    const current = await read($, view)
835    const go = (to: View) => () => update($, view, () => to)
836    // `cwd` defaults to the vault, where these requests read and write.
837    const send = (text: string, what: string, cwd = vault) => async () => {
838      try {
839        await dispatch($, jobs, what, text, cwd)
840      } catch (error) {
841        $.ui.toast(`vault-jot: could not ${what}: ${describe(error)}`.slice(0, TOAST_MAX))
842      }
843    }
844
845    if (current.layer === 'home') {
846      const [ideas, reading] = await Promise.all([loadShelf($, vault, 'ideas'), loadShelf($, vault, 'reading')])
847      const asked = await read($, recalls)
848
849      return (
850        <Box flexDirection="column">
851          <Text dimColor>Pick a shelf.</Text>
852          <Box>
853            <Button key="ideas" hotkey="i" label={`${SHELVES.ideas.icon} Ideas ${ideas.notes.length}`} onPress={go({ layer: 'list', shelf: 'ideas' })} />
854            <Text> </Text>
855            <Button key="reading" hotkey="r" label={`${SHELVES.reading.icon} Reading ${reading.notes.length}`} onPress={go({ layer: 'list', shelf: 'reading' })} />
856            <Text> </Text>
857            <Button key="review" hotkey="v" label="Review" onPress={go({ layer: 'review' })} />
858            <Text> </Text>
859            <Button key="recalls" hotkey="c" label={`Recall ${asked.length}`} onPress={go({ layer: 'recalls' })} />
860          </Box>
861        </Box>
862      )
863    }
864
865    if (current.layer === 'review') {
866      const { notes: ideas } = await loadShelf($, vault, 'ideas')
867      const review = reviewIdeas(ideas, await $.clock.now())
868
869      return (
870        <Box flexDirection="column">
871          <Box>
872            <Button key="back" hotkey="b" plain label="‹ Shelves" onPress={go(HOME)} />
873            <Text bold> Review</Text>
874          </Box>
875          <Text bold>Open ideas by app</Text>
876          {review.openByTarget.length === 0 && review.openUntargeted === 0 && <Text dimColor> none</Text>}
877          {review.openByTarget.map(([target, count]) => (
878            <Text key={`app:${target}`}>  • {target}: {count}</Text>
879          ))}
880          {review.openUntargeted > 0 && <Text>  • no target: {review.openUntargeted}</Text>}
881          <Text bold>Seeds waiting {STALE_SEED_DAYS}+ days</Text>
882          {review.staleSeeds.length === 0 && <Text dimColor> none</Text>}
883          {review.staleSeeds.map(note => (
884            <Button
885              key={`stale:${note.file}`}
886              plain
887              label={`🌱 ${titleOf(note)}`}
888              onPress={go({ layer: 'detail', shelf: 'ideas', file: note.file })}
889            />
890          ))}
891        </Box>
892      )
893    }
894
895    if (current.layer === 'recalls') {
896      const asked = await read($, recalls)
897      const { Input } = $.ui.resolve(e)
898
899      return (
900        <Box flexDirection="column">
901          <Box>
902            <Button key="back" hotkey="b" plain label="‹ Shelves" onPress={go(HOME)} />
903            <Text bold> Recall</Text>
904          </Box>
905          {e.surface !== 'mobile' && (
906            <Input
907              key="question"
908              label="Ask"
909              placeholder="ask the vault; Enter runs it in the background"
910              onSubmit={value => {
911                if (value.trim() !== '') {
912                  void recall($, config, jobs, value.trim()).then(result => $.ui.toast(`vault-jot: ${result.text}`))
913                }
914              }}
915            />
916          )}
917          {asked.length === 0 && <Text dimColor>Nothing asked yet. Type a question, or /recall &lt;question&gt;.</Text>}
918          {asked.map(item => (
919            <Button
920              key={`recall:${item.id}`}
921              plain
922              label={`${RECALL_ICON[item.status]} ${firstLine(item.question)}`}
923              onPress={go({ layer: 'recall', id: item.id })}
924            />
925          ))}
926        </Box>
927      )
928    }
929
930    if (current.layer === 'recall') {
931      const item = (await read($, recalls)).find(candidate => candidate.id === current.id)
932      const back = <Button key="back" hotkey="b" plain label="‹ Recall" onPress={go({ layer: 'recalls' })} />
933      if (item === undefined) {
934        return (
935          <Box flexDirection="column">
936            {back}
937            <Text dimColor>That answer has dropped off the list.</Text>
938          </Box>
939        )
940      }
941      const lines = item.answer.split('\n')
942      const addToChat = async () => {
943        try {
944          const appended = await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: chatContext(item) }] } })
945          $.ui.toast(appended.deny === undefined ? 'vault-jot: added the answer to the conversation' : `vault-jot: not added: ${appended.deny}`)
946        } catch (error) {
947          $.ui.toast(`vault-jot: not added: ${describe(error)}`.slice(0, TOAST_MAX))
948        }
949      }
950
951      return (
952        <Box flexDirection="column">
953          <Box>
954            {back}
955            <Text bold> {firstLine(item.question)}</Text>
956          </Box>
957          {item.status === 'running' && <Text dimColor>Still searching the vault…</Text>}
958          {item.status === 'failed' && <Text color="red">{item.answer}</Text>}
959          {item.status === 'done' && lines.slice(0, ANSWER_LINES).map((line, index) => <Text key={`line:${index}`}>{line}</Text>)}
960          {item.status === 'done' && lines.length > ANSWER_LINES && (
961            <Text dimColor>… {lines.length - ANSWER_LINES} more lines; Add to chat sends all of it.</Text>
962          )}
963          {item.status === 'done' && <Button key="add" hotkey="a" label="Add to chat" variant="primary" onPress={addToChat} />}
964        </Box>
965      )
966    }
967
968    const shelf = SHELVES[current.shelf]
969    const { notes, isTruncated } = await loadShelf($, vault, current.shelf)
970
971    if (current.layer === 'list') {
972      return (
973        <Box flexDirection="column">
974          <Box>
975            <Button key="back" hotkey="b" plain label="‹ Shelves" onPress={go(HOME)} />
976            <Text bold> {shelf.label}</Text>
977          </Box>
978          {notes.length === 0 && (
979            <Text dimColor>
980              Nothing here yet. Captures of kind {current.shelf === 'ideas' ? 'idea' : 'read'} land here after ingest.
981            </Text>
982          )}
983          {notes.map(note => (
984            <Button
985              key={`note:${note.file}`}
986              plain
987              label={`${shelf.icon} ${titleOf(note)}${targetOf(note) === undefined || current.shelf !== 'ideas' ? '' : ` @${targetOf(note)}`} · ${stateOf(current.shelf, note)}`}
988              onPress={go({ layer: 'detail', shelf: current.shelf, file: note.file })}
989            />
990          ))}
991          {isTruncated && <Text dimColor>Showing the first {SHELF_MAX} notes.</Text>}
992        </Box>
993      )
994    }
995
996    const note = notes.find(candidate => candidate.file === current.file)
997    const back = <Button key="back" hotkey="b" plain label={`‹ ${shelf.label}`} onPress={go({ layer: 'list', shelf: current.shelf })} />
998    if (note === undefined) {
999      return (
1000        <Box flexDirection="column">
1001          {back}
1002          <Text dimColor>{current.file} is no longer in {shelf.folder}.</Text>
1003        </Box>
1004      )
1005    }
1006    const path = notePath(vault, current.shelf, note.file)
1007    const header = (
1008      <Box>
1009        {back}
1010        <Text bold> {titleOf(note)}</Text>
1011        <Text dimColor> · {stateOf(current.shelf, note)}</Text>
1012        {current.shelf === 'ideas' && targetOf(note) !== undefined && <Text dimColor> · @{targetOf(note)}</Text>}
1013      </Box>
1014    )
1015
1016    if (current.shelf === 'reading') {
1017      const mark = (state: ReadingState, label: string, hotkey: string) => (
1018        <Button key={`mark:${state}`} hotkey={hotkey} label={label} onPress={send(readingPrompt(vault, path, state), `mark it ${state}`)} />
1019      )
1020
1021      return (
1022        <Box flexDirection="column">
1023          {header}
1024          {note.props.url && <Text dimColor>{note.props.url}</Text>}
1025          <Box>
1026            {mark('reading', 'Reading', 'r')}
1027            <Text> </Text>
1028            {mark('done', 'Done', 'd')}
1029            <Text> </Text>
1030            {mark('dropped', 'Drop', 'x')}
1031          </Box>
1032        </Box>
1033      )
1034    }
1035
1036    const questions = note.sections['Open Questions'] ?? []
1037    const options = note.sections['Options'] ?? []
1038    const repo = await $.session.repo()
1039    const handoffRoot = repo !== null && repo.root !== vault ? repo.root : undefined
1040    const hasHarness = handoffRoot !== undefined && (await $.fs.exists(`${handoffRoot}/${HARNESS_INDEX}`))
1041    const decide = (decision: string) => send(decisionPrompt(vault, path, decision), 'record the decision')()
1042    // Mobile has no Input; there the options' Choose buttons still decide.
1043    let decisionInput = null
1044    if (e.surface !== 'mobile') {
1045      const { Input } = $.ui.resolve(e)
1046      decisionInput = (
1047        <Input
1048          key="decision"
1049          label="Decision"
1050          placeholder="type a decision, Enter records it in the background"
1051          onSubmit={value => {
1052            if (value.trim() !== '') {
1053              void decide(value.trim())
1054            }
1055          }}
1056        />
1057      )
1058    }
1059
1060    return (
1061      <Box flexDirection="column">
1062        {header}
1063        <Text bold>Open questions</Text>
1064        {questions.length === 0 ? <Text dimColor> none yet; Expand drafts some</Text> : questions.map(question => <Text>  • {question}</Text>)}
1065        <Text bold>Options</Text>
1066        {options.length === 0 && <Text dimColor> none yet; Expand drafts some</Text>}
1067        {options.map((option, index) => (
1068          <Box>
1069            <Button key={`choose:${index}`} hotkey={index < 9 ? String(index + 1) : undefined} plain label="Choose" onPress={() => decide(`Chose: ${option}`)} />
1070            <Text> {option}</Text>
1071          </Box>
1072        ))}
1073        {decisionInput}
1074        <Box>
1075          <Button key="expand" hotkey="e" label="Expand" onPress={send(expandPrompt(vault, path), 'expand the idea')} />
1076          {handoffRoot !== undefined && <Text> </Text>}
1077          {handoffRoot !== undefined && (
1078            <Button
1079              key="handoff"
1080              hotkey="x"
1081              label={`Hand off to ${handoffRoot.split('/').at(-1)}`}
1082              onPress={send(handoffPrompt(vault, path, handoffRoot, hasHarness), 'hand the idea off', handoffRoot)}
1083            />
1084          )}
1085        </Box>
1086      </Box>
1087    )
1088  })
1089}
1090
hooks/core.ts 224 lines
1// Pure logic for vault-jot: parsing captures, naming and rendering inbox
2// files, and summarizing the inbox backlog. No `$` calls here.
3
4import type { Backlog } from '../types'
5
6// Must match the "Capture Kinds" table in the vault's Vault Guide, which
7// says what ingest turns each kind into.
8export const KINDS = ['idea', 'improve', 'read', 'til', 'pitfall', 'plugin', 'note'] as const
9export type Kind = (typeof KINDS)[number]
10
11// `target` names the app or repo an `improve` capture is about; ingest files
12// it as the idea's `target`, and the incubate pane matches it to the repo
13// folder name.
14export type Jot = { kind: Kind; text: string; target?: string }
15
16export type Origin = {
17  cwd: string
18  repo: string | null
19  branch: string | null
20  session: string
21}
22
23export type InboxEntry = { name: string; mtimeMs: number }
24
25export type Thresholds = { count: number; days: number }
26
27const KIND_PREFIX = new RegExp(`^(${KINDS.join('|')})(?:\\s+@([\\p{L}\\p{N}_.-]+))?:\\s*`, 'iu')
28const DAY_MS = 24 * 60 * 60 * 1000
29const SLUG_MAX = 40
30const TITLE_MAX = 80
31
32// `/jot idea: text` → { kind: 'idea', text }; `/jot improve @cx: text` also
33// carries a target. No known prefix → kind `note`, so text like
34// "https://..." is never mistaken for a kind. Null when empty.
35export function parseJot(args: string): Jot | null {
36  const { kind, text, target } = splitKind(args)
37
38  if (text === '') {
39    return null
40  }
41
42  return target === undefined ? { kind, text } : { kind, text, target }
43}
44
45function splitKind(args: string): { kind: Kind; text: string; target?: string; hasPrefix: boolean } {
46  const trimmed = args.trim()
47  const match = KIND_PREFIX.exec(trimmed)
48  const kind = (match?.[1]?.toLowerCase() ?? 'note') as Kind
49  const text = (match ? trimmed.slice(match[0].length) : trimmed).trim()
50  const target = match?.[2]
51
52  return target === undefined ? { kind, text, hasPrefix: match !== null } : { kind, text, target, hasPrefix: match !== null }
53}
54
55// What a draft looks at: the last few turns, or the whole discussion's arc.
56export type DraftScope = 'recent' | 'summary'
57export type DraftRequest = { scope: DraftScope; kind?: Kind; target?: string }
58
59export type Request =
60  | { mode: 'capture'; jot: Jot }
61  | ({ mode: 'draft' } & DraftRequest)
62  | { mode: 'ingest' }
63  | { mode: 'invalid'; reason: string }
64
65// The words `/jot` takes alone, besides the kinds.
66export const WORDS = ['summary', 'ingest'] as const
67
68// A word followed by a colon (and maybe `@target`) where a kind would go.
69const KIND_SLOT = /^([\p{L}]+)(?:\s*@[\p{L}\p{N}_.-]*)?:/u
70
71function distance(a: string, b: string): number {
72  let row = Array.from({ length: b.length + 1 }, (_, j) => j)
73  for (let i = 1; i <= a.length; i++) {
74    const next = [i]
75    for (let j = 1; j <= b.length; j++) {
76      next[j] = Math.min((row[j] ?? 0) + 1, (next[j - 1] ?? 0) + 1, (row[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1))
77    }
78    row = next
79  }
80
81  return row[b.length] ?? 0
82}
83
84// The kind a mistyped word most likely meant: within two edits of it, and
85// not a kind itself. Words further off ("Remember:", "https:") are text.
86export function kindTypo(word: string): Kind | null {
87  const lower = word.toLowerCase()
88  if (lower.length < 3 || (KINDS as readonly string[]).includes(lower)) {
89    return null
90  }
91  const [best] = KINDS.map(kind => ({ kind, d: distance(lower, kind) }))
92    .filter(({ d }) => d <= 2)
93    .sort((a, b) => a.d - b.d)
94
95  return best?.kind ?? null
96}
97
98export const typoReason = (word: string, kind: Kind) => `unknown kind "${word}"; did you mean ${kind}?`
99
100// What `/jot <args>` asks for. The reserved words count only alone, so text
101// that merely starts with one (`/jot ingest is slow`) is still captured.
102export function parseRequest(args: string): Request {
103  const word = args.trim().toLowerCase()
104  if (word === 'ingest') {
105    return { mode: 'ingest' }
106  }
107  if (word === 'summary') {
108    return { mode: 'draft', scope: 'summary' }
109  }
110  const slot = KIND_SLOT.exec(args.trim())?.[1]
111  const meant = slot === undefined ? null : kindTypo(slot)
112  if (slot !== undefined && meant !== null) {
113    return { mode: 'invalid', reason: typoReason(slot, meant) }
114  }
115  const { kind, text, target, hasPrefix } = splitKind(args)
116  if (text !== '') {
117    return { mode: 'capture', jot: target === undefined ? { kind, text } : { kind, text, target } }
118  }
119  if (!hasPrefix) {
120    return { mode: 'draft', scope: 'recent' }
121  }
122
123  return target === undefined ? { mode: 'draft', scope: 'recent', kind } : { mode: 'draft', scope: 'recent', kind, target }
124}
125
126// Letters and digits in any script survive, so a non-English capture still
127// gets a readable name.
128export function slugify(text: string): string {
129  const slug = text
130    .toLowerCase()
131    .replace(/[^\p{L}\p{N}]+/gu, '-')
132    .replace(/^-+|-+$/g, '')
133
134  return [...slug].slice(0, SLUG_MAX).join('').replace(/-+$/, '')
135}
136
137export function titleOf(text: string): string {
138  const firstLine = (text.split('\n', 1)[0] ?? '').trim()
139  const chars = [...firstLine]
140
141  return chars.length > TITLE_MAX ? `${chars.slice(0, TITLE_MAX - 1).join('')}…` : firstLine
142}
143
144// Local wall-clock parts for `ms`, given the zone offset in minutes east of
145// UTC (the negation of Date#getTimezoneOffset).
146export function localStamp(ms: number, offsetMinutes: number) {
147  const shifted = new Date(ms + offsetMinutes * 60_000)
148  const pad = (n: number) => String(n).padStart(2, '0')
149  const date = `${shifted.getUTCFullYear()}-${pad(shifted.getUTCMonth() + 1)}-${pad(shifted.getUTCDate())}`
150  const time = `${pad(shifted.getUTCHours())}:${pad(shifted.getUTCMinutes())}:${pad(shifted.getUTCSeconds())}`
151  const sign = offsetMinutes < 0 ? '-' : '+'
152  const abs = Math.abs(offsetMinutes)
153  const zone = `${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`
154
155  return { iso: `${date}T${time}${zone}`, compact: `${date.replaceAll('-', '')}-${time.replaceAll(':', '')}` }
156}
157
158// `attempt` 0 is the plain name; later attempts add a suffix for the rare
159// capture landing in the same second with the same slug.
160export function fileName(jot: Jot, compactStamp: string, attempt = 0): string {
161  const slug = slugify(jot.text)
162  const base = ['jot', compactStamp, jot.kind, slug].filter(Boolean).join('-')
163
164  return attempt === 0 ? `${base}.md` : `${base}-${attempt + 1}.md`
165}
166
167// JSON strings are valid YAML double-quoted scalars.
168const yamlString = (value: string) => JSON.stringify(value)
169
170export function renderNote(jot: Jot, isoStamp: string, origin: Origin): string {
171  const lines = [
172    '---',
173    `title: ${yamlString(titleOf(jot.text))}`,
174    `kind: ${jot.kind}`,
175    jot.target === undefined ? null : `target: ${yamlString(jot.target)}`,
176    `captured: ${isoStamp}`,
177    `origin_cwd: ${yamlString(origin.cwd)}`,
178    origin.repo === null ? null : `origin_repo: ${yamlString(origin.repo)}`,
179    origin.branch === null ? null : `origin_branch: ${yamlString(origin.branch)}`,
180    `origin_session: ${yamlString(origin.session)}`,
181    '---',
182    '',
183    jot.text,
184    '',
185  ]
186
187  return lines.filter(line => line !== null).join('\n')
188}
189
190// Dotfiles (`.gitkeep`) are not captures.
191export function summarizeInbox(entries: readonly InboxEntry[], nowMs: number): Backlog {
192  const captures = entries.filter(entry => !entry.name.startsWith('.'))
193  if (captures.length === 0) {
194    return { count: 0, oldestDays: 0 }
195  }
196  const oldest = captures.reduce((min, entry) => Math.min(min, entry.mtimeMs), Infinity)
197
198  return { count: captures.length, oldestDays: Math.max(0, Math.floor((nowMs - oldest) / DAY_MS)) }
199}
200
201// The prompt-footer label; undefined for an empty inbox so nothing shows.
202export function backlogLabel(backlog: Backlog): string | undefined {
203  if (backlog.count === 0) {
204    return undefined
205  }
206
207  return `📥 inbox ${backlog.count} · ${backlog.oldestDays}d`
208}
209
210export function isOverdue(backlog: Backlog, thresholds: Thresholds): boolean {
211  return backlog.count > 0 && (backlog.count >= thresholds.count || backlog.oldestDays >= thresholds.days)
212}
213
214export function expandHome(path: string, home: string | undefined): string {
215  if (path !== '~' && !path.startsWith('~/')) {
216    return path
217  }
218  if (home === undefined || home === '') {
219    throw new Error(`cannot expand "${path}": HOME is not set`)
220  }
221
222  return home + path.slice(1)
223}
224
hooks/handoff.ts 292 lines
1// Pure builders for what vault-jot asks Claude to do. The mod never writes
2// under wiki/: claude-obsidian is the single writer there, so changes to
3// maintained notes are handed to Claude as prompts built here.
4
5import { KINDS, parseJot } from './core'
6import type { DraftRequest, DraftScope, Jot } from './core'
7
8const DRAFT_MAX: Record<DraftScope, number> = { recent: 500, summary: 4000 }
9
10const rules = (vault: string) =>
11  `Work in the vault at ${vault}: follow its CLAUDE.md and wiki/meta/Vault Guide.md, set \`updated\` to today, and record the change in wiki/log.md.`
12
13// An agent that cannot do its job starts its answer with this, so the person
14// is told it failed instead of seeing a "done" with an apology after it.
15const FAILED_MARK = 'FAILED:'
16
17export type Outcome = { failed: boolean; detail: string }
18
19// Turns how a background agent's turn ended into what the toast says.
20export function outcomeOf(reason: string, answer: string): Outcome {
21  const trimmed = answer.trim()
22  if (reason !== 'answer') {
23    return { failed: true, detail: reason }
24  }
25
26  return trimmed.startsWith(FAILED_MARK)
27    ? { failed: true, detail: trimmed.slice(FAILED_MARK.length).trim() }
28    : { failed: false, detail: trimmed }
29}
30
31// The system prompt of the ingest agent. It replaces the session's, so the
32// agent works from the task and the vault alone, never the conversation.
33export const ingestAgentPrompt = [
34  'You file raw captures from a vault inbox into its wiki. You know nothing of any conversation: work only from the task and the vault.',
35  'Your first step, before reading any capture, is to load the claude-obsidian:wiki-ingest skill with the Skill tool and follow it. If it cannot be loaded, or you cannot complete the ingest, stop without ingesting by hand and answer with one line that starts with \"FAILED:\" and gives the reason.',
36  "The vault is the parent of the inbox you are given. Then follow the vault's CLAUDE.md and wiki/meta/Vault Guide.md, and report what you changed in a few lines.",
37  'Your shell is restricted to single commands: no cd, pipes, redirects or chaining. Read files with the Read, Grep and Glob tools, and use Bash only for `shasum -a 256 <file>` and the claude-obsidian core script, run by its absolute path.',
38].join(' ')
39
40// Ingest is two agent runs with the person's review between them: the first
41// drafts and inspects the transaction without applying it, the second applies
42// exactly what was inspected. Each answers in a fixed first line so the mod can
43// tell a plan from a failure.
44export type Plan = { bundle: string; approval: string; summary: string }
45export type Parsed<T> = { ok: true; value: T } | { ok: false; reason: string }
46
47export const ingestPlanPrompt = (vault: string, names: readonly string[]) =>
48  [
49    `Prepare an ingest of exactly these captures from ${vault}/inbox: ${names.join(', ')}. Do not apply anything.`,
50    `Follow claude-obsidian wiki-ingest up to and including \`transaction inspect\`: draft one ingest bundle for the whole batch, with a create-only raw capture under .raw/captured/ for each file (named by its SHA-256, byte-identical to the inbox file), and save it as ${vault}/.vault-meta/ingest-bundle.json.`,
51    'Then answer. The first line is exactly: PLAN <absolute bundle path> <approval_sha256 from inspect>.',
52    'After it, keep the plan short, one line each. First, if any captures only get a raw copy because their pages already exist, a single line: Archived only (N): <names, comma-separated>. Then one line for each capture that creates or changes a page, in the form <capture>: <pages it creates or updates, or what it is merged into>. Do not mention ledger or manifest records. No other text.',
53    'If you cannot prepare it, answer with one line that starts with "FAILED:" and the reason.',
54  ].join(' ')
55
56export const ingestApplyPrompt = (vault: string, plan: Plan) =>
57  [
58    `Apply the reviewed ingest bundle ${plan.bundle} to the vault ${vault}: run the core's \`transaction apply\` with --approved-plan-sha256 ${plan.approval}, then run wiki-lint.`,
59    'If apply refuses because the bundle changed since it was inspected, do not rebuild it.',
60    'The first line of your answer is exactly: APPLIED <operation id>. After it, the changed paths and the lint result, briefly.',
61    'If you cannot finish, answer with one line that starts with "FAILED:" and the reason.',
62  ].join(' ')
63
64export function parsePlan(reason: string, answer: string): Parsed<Plan> {
65  const outcome = outcomeOf(reason, answer)
66  if (outcome.failed) {
67    return { ok: false, reason: outcome.detail }
68  }
69  const [first = '', ...rest] = answer.trim().split('\n')
70  const match = /^PLAN\s+(\S+)\s+([0-9a-f]{64})\s*$/.exec(first.trim())
71  if (match === null || match[1] === undefined || match[2] === undefined) {
72    return { ok: false, reason: `the agent did not return a plan: ${first.trim().slice(0, 120)}` }
73  }
74
75  return { ok: true, value: { bundle: match[1], approval: match[2], summary: rest.join('\n').trim() } }
76}
77
78// The plan's lines as a Markdown list, one item per capture with its name in
79// bold; Markdown would otherwise run the lines together into one paragraph.
80export function planList(summary: string): string {
81  return summary
82    .split('\n')
83    .map(line => line.trim())
84    .filter(line => line !== '')
85    .map(line => {
86      const cut = line.indexOf(': ')
87
88      return cut === -1 ? `- ${line}` : `- **${line.slice(0, cut)}**: ${line.slice(cut + 2)}`
89    })
90    .join('\n')
91}
92
93// What an ingest bundle will write: the pages the person reviews before
94// confirming. `writes` carry whole file contents.
95export type BundleWrite = { mode: string; path: string; content: string }
96
97export function parseBundle(text: string): BundleWrite[] {
98  const writes: unknown = (JSON.parse(text) as { writes?: unknown }).writes
99  if (!Array.isArray(writes)) {
100    throw new Error('the bundle has no writes')
101  }
102
103  return writes.map((write: unknown) => {
104    const { mode, path, content } = write as Record<string, unknown>
105    if (typeof mode !== 'string' || typeof path !== 'string' || typeof content !== 'string') {
106      throw new Error('a write in the bundle is malformed')
107    }
108
109    return { mode, path, content }
110  })
111}
112
113const isArchive = (path: string) => path.startsWith('.raw/') || path.startsWith('wiki/meta/ledgers/')
114
115const clipLines = (lines: readonly string[], max: number) =>
116  lines.length <= max ? [...lines] : [...lines.slice(0, max), `… ${lines.length - max} more lines`]
117
118// A new page as it will read; a replaced page as the lines it adds. `current`
119// maps a replaced path to the text it has now.
120export function previewMarkdown(writes: readonly BundleWrite[], current: Readonly<Record<string, string>>, maxLines: number): string {
121  const parts: string[] = []
122  for (const write of writes) {
123    if (isArchive(write.path)) {
124      continue
125    }
126    if (write.mode === 'create') {
127      const body = write.content.replace(/^---\n[\s\S]*?\n---\n?/, '').trim()
128      parts.push(`### New: ${write.path}`, clipLines(body.split('\n'), maxLines).join('\n'))
129    } else {
130      const before = new Set((current[write.path] ?? '').split('\n'))
131      const added = write.content.split('\n').filter(line => line.trim() !== '' && !before.has(line))
132      parts.push(
133        `### Updated: ${write.path}`,
134        added.length === 0 ? '_no new lines_' : ['```diff', ...clipLines(added, maxLines).map(line => `+ ${line}`), '```'].join('\n'),
135      )
136    }
137  }
138  const archived = writes.filter(write => isArchive(write.path)).length
139  if (archived > 0) {
140    parts.push(`_${archived} archive files (raw copies, source ledger) are written too._`)
141  }
142
143  return parts.join('\n\n')
144}
145
146export function parseApplied(reason: string, answer: string): Parsed<string> {
147  const outcome = outcomeOf(reason, answer)
148  if (outcome.failed) {
149    return { ok: false, reason: outcome.detail }
150  }
151  const [first = '', ...rest] = answer.trim().split('\n')
152  if (!/^APPLIED\s+\S+/.test(first.trim())) {
153    return { ok: false, reason: `the agent did not confirm the apply: ${first.trim().slice(0, 120)}` }
154  }
155
156  return { ok: true, value: [first.trim(), ...rest].join('\n').trim() }
157}
158
159// The SHA-256 the ingest manifest recorded for an inbox file, which names its
160// archived copy `.raw/captured/<hash>.md`; null when it recorded none.
161export function archivedHash(manifestText: string, name: string): string | null {
162  const manifest: unknown = JSON.parse(manifestText)
163  const sources = (manifest as { sources?: Record<string, { hash?: unknown }> }).sources ?? {}
164  const hash = sources[`inbox/${name}`]?.hash
165
166  return typeof hash === 'string' && /^[0-9a-f]{64}$/.test(hash) ? hash : null
167}
168
169export function expandPrompt(vault: string, notePath: string): string {
170  return [
171    `Incubate the idea note ${notePath}.`,
172    `Fill in "Why It's Interesting", "Open Questions" (concrete and answerable), "Options" (2-3 list items, one line each with its tradeoff), and "Next Step", from the note and anything related in the vault.`,
173    `If its status is seed, set it to developing.`,
174    rules(vault),
175  ].join(' ')
176}
177
178export function decisionPrompt(vault: string, notePath: string, decision: string): string {
179  return [
180    `Record a decision on the idea note ${notePath}: ${JSON.stringify(decision)}.`,
181    `Add it as a dated list item under a "## Decisions" section, remove open questions it answers, and update "Next Step".`,
182    `If the decision drops the idea, set status: archived and keep the reason; if it makes the idea ready to start, set status: mature.`,
183    rules(vault),
184  ].join(' ')
185}
186
187// Where a handed-off idea lands depends on the target repo: with a harness
188// (`docs/harness/index.md`) its own tracker skills decide the artifact; without
189// one, a design doc. Either way the vault side is fixed: `handoff:` points at
190// what was created and the idea is closed out.
191export const HARNESS_INDEX = 'docs/harness/index.md'
192
193export function handoffPrompt(vault: string, notePath: string, repoRoot: string, hasHarness: boolean): string {
194  const root = repoRoot.replace(/\/+$/, '')
195  const project = root.split('/').at(-1) ?? root
196  const repoStep = hasHarness
197    ? `Hand off the idea note ${notePath} to the repo at ${root}, which has a harness: read ${root}/${HARNESS_INDEX}, then use the to-issues skill there (to-prd if the idea is a whole feature), taking the note's Spark, Options, Decisions and Next Step as the plan, and publish through the harness tracker.`
198    : `Turn the idea note ${notePath} into a design doc at ${root}/docs/design/<kebab-case title>.md: problem, goals, non-goals, options with tradeoffs, decisions, open questions, next steps. Follow that repo's conventions.`
199
200  return [
201    repoStep,
202    `Then, in the vault, set the idea's \`project:\` to ${project}, \`handoff:\` to the path or URL of what you created, status: archived, and add it under "Related".`,
203    rules(vault),
204  ].join(' ')
205}
206
207export type ReadingState = 'reading' | 'done' | 'dropped'
208
209export function readingPrompt(vault: string, notePath: string, state: ReadingState): string {
210  const followUp = {
211    reading: '',
212    done: 'Then ask me for my takeaways, add them under "## Takeaways", and ask whether to ingest the item as a source.',
213    dropped: 'Ask me for a one-line reason and record it under "## Notes".',
214  }[state]
215
216  return [`Set reading_state: ${state} on the reading note ${notePath}.`, followUp, rules(vault)]
217    .filter(Boolean)
218    .join(' ')
219}
220
221const KIND_GUIDE = `(idea: something to explore or build; improve: a change to make to an app; read: something to read, with its URL; til: something learned; pitfall: a failure mode and how to prevent it; plugin: a take on a tool; note: anything else)`
222
223// The note's subject, not where it came up: the model knows what the
224// conversation is about, so it names the repo.
225const TARGET_RULE = `When it is about a specific app or repo, write "<kind> @<repo folder name>: <text>" instead.`
226
227function kindRule(request: DraftRequest): string {
228  if (request.kind === undefined) {
229    return `kind is one of ${KINDS.join(', ')} ${KIND_GUIDE}. ${TARGET_RULE}`
230  }
231  if (request.target === undefined) {
232    return `kind is ${request.kind}. ${TARGET_RULE}`
233  }
234  const about = request.target === undefined ? '' : `, about ${request.target}`
235
236  return `kind is ${request.kind}${about}.`
237}
238
239// What a fork of the conversation is asked for a draft. The fork always sees
240// the whole transcript, so only the prompt can narrow what it looks at.
241// `recent` is a quick capture of what just came up; `summary` traces how a
242// long discussion converged, where the insight usually is.
243export function draftPrompt(request: DraftRequest): string {
244  if (request.scope === 'summary') {
245    return [
246      `Summarize this whole discussion as one capture for my notes vault, tracing how our understanding converged.`,
247      `First line: \`<kind>: <title>\`, where ${kindRule(request)} Keep the title under 80 characters and make it the insight, not the topic.`,
248      `Then short markdown bullets under these headings: "Question" (what we set out to settle), "Wrong turns" (misunderstandings and assumptions we corrected, and what corrected them), "Agreed" (where we landed and why), "Insight" (what to remember next time).`,
249      `Skip a heading with nothing real under it. Under 3000 characters, in the language of the conversation. No other words.`,
250    ].join(' ')
251  }
252
253  return [
254    `Draft one capture for my notes vault from the most recent exchange (the last few turns): the single most useful thing there worth keeping, such as a finding, an answer, or a question it raised.`,
255    `Look further back only if nothing recent is worth keeping.`,
256    `Reply with exactly one line, \`<kind>: <text>\`, where ${kindRule(request)}`,
257    `Keep the text under 200 characters, in the language of the conversation. No other words.`,
258  ].join(' ')
259}
260
261const FENCE = /^```[^\n]*\n?|\n?```$/g
262
263// A recent draft is the model's first non-empty line, unwrapped from quotes
264// or backticks; a summary is the whole reply, unwrapped from a code fence.
265// A kind or target the person asked for wins over the model's choice.
266export function parseDraft(reply: string, request: DraftRequest = { scope: 'recent' }): Jot | null {
267  const body =
268    request.scope === 'summary'
269      ? reply.trim().replace(FENCE, '').trim()
270      : (reply
271          .split('\n')
272          .map(part => part.trim())
273          .find(part => part !== '') ?? '').replace(/^[`"']+|[`"']+$/g, '')
274  const jot = parseJot(body)
275  if (jot === null || request.kind === undefined) {
276    return jot
277  }
278
279  const target = request.target ?? jot.target
280
281  return target === undefined ? { kind: request.kind, text: jot.text } : { kind: request.kind, text: jot.text, target }
282}
283
284export function draftCommand(jot: Jot, scope: DraftScope = 'recent'): string {
285  const max = DRAFT_MAX[scope]
286  const chars = [...jot.text]
287  const text = chars.length > max ? `${chars.slice(0, max - 1).join('')}…` : jot.text
288  const target = jot.target === undefined ? '' : ` @${jot.target}`
289
290  return `/jot ${jot.kind}${target}: ${text}`
291}
292
hooks/headless.ts 106 lines
1// Pure builders for running Claude Code as an independent `claude -p` process:
2// the argv that starts it, the tools each ingest phase may use, and how its
3// JSON answer maps back to a subagent-style `(reason, answer)`.
4//
5// The process is its own session, so there is nobody to ask for permission:
6// `dontAsk` denies anything not allow-listed, and each phase lists only what
7// it needs (the plan cannot apply; the apply cannot draft).
8
9export type Phase = 'plan' | 'apply'
10
11// The vault's own scripts, wherever the plugin cache keeps them. The skill
12// resolves the path itself, so the rule matches the script name.
13const CORE = 'python3 *claude-obsidian.py'
14
15const READ_ONLY = ['Skill', 'Read', 'Grep', 'Glob', 'Bash(shasum *)', 'Bash(sha256sum *)']
16
17// An absolute path in a permission rule starts with `//`.
18const absolute = (path: string) => `/${path}`
19
20export function ingestTools(phase: Phase, vault: string): { allow: string[]; deny: string[] } {
21  const meta = absolute(`${vault}/.vault-meta`)
22  if (phase === 'plan') {
23    return {
24      allow: [...READ_ONLY, `Write(${meta}/**)`, `Edit(${meta}/**)`, `Bash(${CORE} *)`],
25      deny: [`Bash(${CORE} transaction apply*)`, `Bash(${CORE} transaction recover*)`],
26    }
27  }
28
29  return {
30    allow: [...READ_ONLY, `Bash(${CORE} transaction apply *)`, `Bash(${CORE} lint *)`],
31    deny: [],
32  }
33}
34
35// Starts `claude -p` in the vault with a scrubbed environment: the host
36// session's variables (and the engine's own) make a child's sign-in fail, and
37// `$.process.run`'s `env` option only adds to what is inherited. The prompt
38// goes in on stdin, which also keeps it clear of the variadic tool flags.
39const LAUNCH = [
40  'vault=$1; shift',
41  'cd "$vault" || exit 97',
42  'bin=$(command -v claude) || bin=$CLAUDE_CODE_EXECPATH',
43  '[ -n "$bin" ] || { echo "claude was not found on PATH" >&2; exit 127; }',
44  'exec env -i HOME="$HOME" PATH="$PATH" "$bin" "$@"',
45].join('\n')
46
47export type Launch = {
48  vault: string
49  phase: Phase
50  systemPrompt: string
51  budgetUsd: number
52}
53
54export function claudeArgv({ vault, phase, systemPrompt, budgetUsd }: Launch): string[] {
55  const { allow, deny } = ingestTools(phase, vault)
56
57  return [
58    'sh',
59    '-c',
60    LAUNCH,
61    'sh',
62    vault,
63    '-p',
64    '--output-format',
65    'json',
66    '--permission-mode',
67    'dontAsk',
68    '--max-budget-usd',
69    String(budgetUsd),
70    '--append-system-prompt',
71    systemPrompt,
72    '--allowedTools',
73    allow.join(','),
74    ...(deny.length === 0 ? [] : ['--disallowedTools', deny.join(',')]),
75  ]
76}
77
78export type Finished = { exitCode: number; stdout: string; stderr: string; isStdoutTruncated: boolean }
79export type Settled = { reason: string; answer: string }
80
81const REASON_MAX = 200
82
83const clip = (text: string) => text.trim().replace(/\s+/g, ' ').slice(0, REASON_MAX)
84
85// `claude -p --output-format json` prints one object; `is_error` is the
86// failure flag (an auth failure still says `subtype: "success"`).
87export function settledOf({ exitCode, stdout, stderr, isStdoutTruncated }: Finished): Settled {
88  if (!isStdoutTruncated) {
89    try {
90      const parsed: unknown = JSON.parse(stdout)
91      const { is_error: isError, subtype, result } = parsed as { is_error?: unknown; subtype?: unknown; result?: unknown }
92      const text = typeof result === 'string' ? result : ''
93      if (isError === false && typeof result === 'string') {
94        return { reason: 'answer', answer: text }
95      }
96
97      return { reason: clip(`claude -p failed${typeof subtype === 'string' && subtype !== 'success' ? ` (${subtype})` : ''}: ${text}`), answer: '' }
98    } catch {
99      // Not JSON: fall through to the exit status.
100    }
101  }
102  const detail = clip(stderr) || clip(stdout) || 'no output'
103
104  return { reason: `claude -p exited ${exitCode}${isStdoutTruncated ? ' with oversized output' : ''}: ${detail}`.slice(0, REASON_MAX + 40), answer: '' }
105}
106
hooks/recall.ts 47 lines
1// Pure logic for /recall: the prompt a subagent searches the vault with, the
2// bounded list of results the pane shows, and the text that joins the chat.
3// No `$` calls here.
4
5import type { Recall } from '../types'
6
7export const RECALLS_MAX = 10
8// A subagent's answer is cut here, so one runaway reply cannot fill the state
9// or, later, the conversation.
10export const ANSWER_MAX = 20_000
11
12// Read-only on purpose: a recall only fetches, and the vault's single writer
13// stays claude-obsidian via the ingest and incubate requests.
14export function recallPrompt(vault: string, question: string): string {
15  return [
16    `Answer a question from the notes vault at ${vault}. Read only: do not create, edit or delete any file.`,
17    `Use the claude-obsidian wiki-query skill scoped to that vault (add wiki-retrieve when the question needs passage-level search), and follow the vault's CLAUDE.md.`,
18    `Reply with a concise answer in the language of the question, then a "Sources" list of the vault-relative paths of the notes it rests on.`,
19    `If the vault has nothing relevant, say so in one line and stop.`,
20    `Question: ${JSON.stringify(question)}`,
21  ].join(' ')
22}
23
24export function addRecall(list: readonly Recall[], recall: Recall): Recall[] {
25  return [recall, ...list].slice(0, RECALLS_MAX)
26}
27
28// A finished subagent's turn: an answer is the result, anything else (an
29// error, an interrupt) marks the recall failed with why.
30export function settleRecall(list: readonly Recall[], id: string, reason: string, answer: string): Recall[] {
31  const result: Pick<Recall, 'status' | 'answer'> =
32    reason === 'answer' && answer.trim() !== ''
33      ? { status: 'done', answer: [...answer].slice(0, ANSWER_MAX).join('') }
34      : { status: 'failed', answer: reason === 'answer' ? 'the subagent returned no answer' : `the subagent ended: ${reason}` }
35
36  return list.map(recall => (recall.id === id ? { ...recall, ...result } : recall))
37}
38
39export function failRecall(list: readonly Recall[], id: string, why: string): Recall[] {
40  return list.map(recall => (recall.id === id ? { ...recall, status: 'failed' as const, answer: why } : recall))
41}
42
43// What the model reads when a recall is added to the conversation.
44export function chatContext(recall: Recall): string {
45  return `Context retrieved from my notes vault by a vault-jot recall. Question: ${JSON.stringify(recall.question)}\n\n${recall.answer}`
46}
47
hooks/notes.ts 160 lines
1// Pure reading of vault notes for the incubate pane: flat frontmatter, list
2// items per `##` section, and lookup by title. The pane only reads notes;
3// every write is handed to Claude (see handoff.ts).
4
5import type { Shelf } from '../types'
6
7export type Note = {
8  file: string
9  props: Readonly<Record<string, string>>
10  sections: Readonly<Record<string, readonly string[]>>
11}
12
13export const SHELVES: Readonly<Record<Shelf, { folder: string; label: string; icon: string }>> = {
14  ideas: { folder: 'wiki/ideas', label: 'Ideas', icon: '🌱' },
15  reading: { folder: 'wiki/reading', label: 'Reading', icon: '📖' },
16}
17
18// Lifecycles from the vault's Vault Guide, in the order the pane lists them:
19// what needs attention first.
20const STATE_ORDER: Readonly<Record<Shelf, readonly string[]>> = {
21  ideas: ['developing', 'seed', 'mature', 'archived'],
22  reading: ['reading', 'queued', 'done', 'dropped'],
23}
24
25const unquote = (raw: string): string => {
26  const value = raw.trim()
27  if (value.startsWith('"') && value.endsWith('"') && value.length >= 2) {
28    try {
29      return String(JSON.parse(value))
30    } catch {
31      return value.slice(1, -1)
32    }
33  }
34  if (value.startsWith("'") && value.endsWith("'") && value.length >= 2) {
35    return value.slice(1, -1).replaceAll("''", "'")
36  }
37
38  return value
39}
40
41// Scalar `key: value` lines only; block lists (tags, sources) are skipped,
42// since the pane needs none of them.
43export function parseNote(file: string, text: string): Note {
44  const lines = text.split(/\r?\n/)
45  const props: Record<string, string> = {}
46  let bodyStart = 0
47  if (lines[0]?.trim() === '---') {
48    const end = lines.findIndex((line, index) => index > 0 && line.trim() === '---')
49    if (end > 0) {
50      for (const line of lines.slice(1, end)) {
51        const match = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(line)
52        const value = match ? unquote(match[2] ?? '') : ''
53        if (match?.[1] && value !== '') {
54          props[match[1]] = value
55        }
56      }
57      bodyStart = end + 1
58    }
59  }
60
61  const sections: Record<string, string[]> = {}
62  let current: string[] | undefined
63  for (const line of lines.slice(bodyStart)) {
64    const heading = /^##\s+(.+?)\s*$/.exec(line)
65    if (heading?.[1]) {
66      current = sections[heading[1]] = []
67      continue
68    }
69    const item = /^\s*(?:[-*+]|\d+\.)\s+(?:\[[ xX]\]\s+)?(.+?)\s*$/.exec(line)
70    if (current && item?.[1]) {
71      current.push(item[1])
72    }
73  }
74
75  return { file, props, sections }
76}
77
78export const titleOf = (note: Note): string => note.props.title ?? note.file.replace(/\.md$/, '')
79
80export function stateOf(shelf: Shelf, note: Note): string {
81  return shelf === 'ideas' ? (note.props.status ?? 'seed') : (note.props.reading_state ?? 'queued')
82}
83
84// A note's `target` names the repo it is about (`/jot <kind> @<repo>:`); the
85// pane and the related-notes index match it to the repo folder name.
86export const targetOf = (note: Note): string | undefined => note.props.target
87
88// Ideas within a state group by target, then title; untargeted ideas last.
89export function sortNotes(shelf: Shelf, notes: readonly Note[]): Note[] {
90  const order = STATE_ORDER[shelf]
91  const rank = (note: Note) => {
92    const index = order.indexOf(stateOf(shelf, note))
93
94    return index === -1 ? order.length : index
95  }
96  const target = (note: Note) => (shelf === 'ideas' ? (targetOf(note)?.toLowerCase() ?? '\uffff') : '')
97
98  return [...notes].sort(
99    (a, b) => rank(a) - rank(b) || target(a).localeCompare(target(b)) || titleOf(a).localeCompare(titleOf(b)),
100  )
101}
102
103const isClosed = (note: Note) => stateOf('ideas', note) === 'archived'
104
105// Open (not archived) ideas aimed at `target`, compared case-insensitively.
106export function openForTarget(ideas: readonly Note[], target: string): Note[] {
107  const wanted = target.toLowerCase()
108
109  return ideas.filter(note => targetOf(note)?.toLowerCase() === wanted && !isClosed(note))
110}
111
112const DAY_MS = 24 * 60 * 60 * 1000
113export const STALE_SEED_DAYS = 14
114
115export type Review = { staleSeeds: Note[]; openByTarget: [string, number][]; openUntargeted: number }
116
117// What the review layer shows: seeds nobody has picked up, and how much open
118// feedback each app has. `created` is a YYYY-MM-DD date; seeds without a
119// readable one are not counted stale.
120export function reviewIdeas(ideas: readonly Note[], nowMs: number): Review {
121  const open = ideas.filter(note => !isClosed(note))
122  const age = (note: Note) => {
123    const created = Date.parse(note.props.created ?? '')
124
125    return Number.isNaN(created) ? 0 : Math.floor((nowMs - created) / DAY_MS)
126  }
127  const counts = new Map<string, number>()
128  let openUntargeted = 0
129  for (const note of open) {
130    const target = targetOf(note)?.toLowerCase()
131    if (target === undefined) {
132      openUntargeted += 1
133    } else {
134      counts.set(target, (counts.get(target) ?? 0) + 1)
135    }
136  }
137
138  return {
139    staleSeeds: open.filter(note => stateOf('ideas', note) === 'seed' && age(note) >= STALE_SEED_DAYS),
140    openByTarget: [...counts].sort(([a], [b]) => a.localeCompare(b)),
141    openUntargeted,
142  }
143}
144
145// Exact title or file name first (case-insensitive), then a unique substring.
146export function findNote(notes: readonly Note[], query: string): Note | 'ambiguous' | undefined {
147  const wanted = query.trim().toLowerCase()
148  const names = (note: Note) => [titleOf(note).toLowerCase(), note.file.replace(/\.md$/, '').toLowerCase()]
149  const exact = notes.find(note => names(note).includes(wanted))
150  if (exact) {
151    return exact
152  }
153  const partial = notes.filter(note => names(note).some(name => name.includes(wanted)))
154  if (partial.length > 1) {
155    return 'ambiguous'
156  }
157
158  return partial[0]
159}
160
hooks/related.ts 55 lines
1// The related-notes index a conversation starts with: what in the vault is
2// aimed at the session's repo, and the other inbox titles, so Claude can
3// point out a note that bears on the work. Titles and paths only, bounded;
4// bodies are read on demand (the vault's Lazy Context Loading).
5
6import { titleOf, targetOf } from './notes'
7import type { Note } from './notes'
8
9const RELATED_MAX = 15
10const INBOX_MAX = 20
11const TITLE_MAX = 100
12
13export type IndexInput = {
14  vault: string
15  // The session repo's folder name; null outside a repo or in the vault.
16  repo: string | null
17  // Inbox captures, newest first.
18  captures: readonly Note[]
19  // Open ideas.
20  ideas: readonly Note[]
21}
22
23function lines(notes: readonly Note[], folder: string, max: number): string[] {
24  const listed = notes.slice(0, max).map(note => {
25    const chars = [...titleOf(note)]
26    const title = chars.length > TITLE_MAX ? `${chars.slice(0, TITLE_MAX - 1).join('')}…` : chars.join('')
27
28    return `- ${title} — ${folder}/${note.file}`
29  })
30
31  return notes.length > max ? [...listed, `(${notes.length - max} more not listed)`] : listed
32}
33
34export function relatedIndex({ vault, repo, captures, ideas }: IndexInput): string | null {
35  const wanted = repo?.toLowerCase()
36  const isForRepo = (note: Note) => wanted !== undefined && targetOf(note)?.toLowerCase() === wanted
37  const forRepo = [
38    ...lines(captures.filter(isForRepo), `${vault}/inbox`, RELATED_MAX),
39    ...lines(ideas.filter(isForRepo), `${vault}/wiki/ideas`, RELATED_MAX),
40  ]
41  const others = lines(captures.filter(note => !isForRepo(note)), `${vault}/inbox`, INBOX_MAX)
42  if (forRepo.length === 0 && others.length === 0) {
43    return null
44  }
45
46  return [
47    `Notes in the vault at ${vault} that may bear on this session: titles only; read a file only when it matters.`,
48    forRepo.length === 0 ? null : [`For this repo (${repo}):`, ...forRepo].join('\n'),
49    others.length === 0 ? null : ['Other inbox captures:', ...others].join('\n'),
50    'When the current work relates to one of these, say so in one line and name the file. Do not edit the vault for it.',
51  ]
52    .filter(part => part !== null)
53    .join('\n\n')
54}
55
hooks/composer.ts 78 lines
1// Pure reading of a `/jot` draft as it is typed: which words are a kind or a
2// target, and what the next word could be. The engine offers no argument
3// completion, so the mod paints the draft and lists the candidates under the
4// prompt instead.
5
6import { KINDS, WORDS, kindTypo, typoReason } from './core'
7
8export type Mark = { start: number; end: number; state: 'ok' | 'bad' }
9export type Reading = { hint: string | null; marks: Mark[] }
10
11const COMMAND = '/jot'
12// The widest a hint gets, in characters; the band and the hint line share it.
13const HINT_WIDTH = 80
14
15const startingWith = (options: readonly string[], prefix: string) =>
16  options.filter(option => option.toLowerCase().startsWith(prefix.toLowerCase()))
17
18// Candidates in one line, cut with … when they do not fit.
19export function hintLine(options: readonly string[], width = HINT_WIDTH): string {
20  const line = options.join(' · ')
21
22  return line.length <= width ? line : `${line.slice(0, width - 1)}…`
23}
24
25export function readDraft(text: string, targets: readonly string[]): Reading | null {
26  if (!text.startsWith(`${COMMAND} `)) {
27    return null
28  }
29  const offset = COMMAND.length + (/^\s*/.exec(text.slice(COMMAND.length))?.[0].length ?? 0)
30  const rest = text.slice(offset)
31  const word = /^\p{L}*/u.exec(rest)?.[0] ?? ''
32  const after = rest.slice(word.length)
33  const end = offset + word.length
34
35  // Still typing the first word, painted as a shell paints a command: green
36  // once it is a kind or word, red once it can only be a mistyped kind, and
37  // plain while it may still become one, or is just the note's text.
38  if (after === '') {
39    const matches = startingWith([...KINDS, ...WORDS], word)
40    const isExact = matches.some(match => match === word.toLowerCase())
41    const meant = matches.length === 0 ? kindTypo(word) : null
42    const marks: Mark[] = isExact ? [{ start: offset, end, state: 'ok' }] : meant === null ? [] : [{ start: offset, end, state: 'bad' }]
43    const hint = meant !== null ? typoReason(word, meant) : matches.length === 0 ? null : hintLine(matches)
44
45    return { hint, marks }
46  }
47
48  const at = /^\s*@([\p{L}\p{N}_.-]*)/u.exec(after)
49  const closes = at === null ? after.startsWith(':') : after.slice(at[0].length).startsWith(':')
50  if (!closes && at === null) {
51    return { hint: null, marks: [] }
52  }
53  const isKind = (KINDS as readonly string[]).includes(word.toLowerCase())
54  const meant = isKind ? null : kindTypo(word)
55  if (!isKind && meant === null) {
56    return { hint: null, marks: [] }
57  }
58  if (meant !== null) {
59    return { hint: typoReason(word, meant), marks: [{ start: offset, end, state: 'bad' }] }
60  }
61  const marks: Mark[] = [{ start: offset, end, state: 'ok' }]
62  if (at === null) {
63    return { hint: null, marks }
64  }
65  // The target likewise: green as soon as it names a known one. An unknown
66  // one is allowed (a repo the vault has not seen yet), so it is never red.
67  const name = at[1] ?? ''
68  const atStart = end + at[0].indexOf('@')
69  const isKnown = targets.some(target => target.toLowerCase() === name.toLowerCase())
70  const targetMarks: Mark[] = isKnown ? [...marks, { start: atStart, end: atStart + 1 + name.length, state: 'ok' }] : marks
71  const matches = startingWith(targets, name)
72  if (isKnown || (!closes && matches.length > 0)) {
73    return { hint: closes ? null : hintLine(matches.map(target => `@${target}`)), marks: targetMarks }
74  }
75
76  return { hint: name === '' ? null : `new target @${name}`, marks }
77}
78
types/index.d.ts 54 lines
1// The inbox backlog the footer label and band show; null until first read or
2// when the inbox cannot be read.
3export type Backlog = { count: number; oldestDays: number }
4
5// Open ideas aimed at the session's repo, for the footer label; null when the
6// session is not in a repo other than the vault.
7export type OpenForRepo = { target: string; count: number }
8
9// The incubate pane's shelves, one per vault folder it browses.
10export type Shelf = 'ideas' | 'reading'
11
12// One /recall: a question handed to a background subagent, then its answer
13// (or why it failed), kept for the pane until it falls off the bounded list.
14export type Recall = { id: string; question: string; status: 'running' | 'done' | 'failed'; answer: string }
15
16// A drafted capture; the same shape as core's Jot, whose kinds it repeats
17// because this contract must be self-contained.
18export type DraftJot = {
19  kind: 'idea' | 'improve' | 'read' | 'til' | 'pitfall' | 'plugin' | 'note'
20  text: string
21  target?: string
22}
23
24// `/jot summary`'s draft while the preview pane shows it.
25export type SummaryDraft =
26  | { status: 'drafting' }
27  | { status: 'ready'; jot: DraftJot }
28  | { status: 'failed'; reason: string }
29
30// One ingest from the Ingest button or `/jot ingest`: an agent plans it, the
31// person reviews the plan in the pane, then an agent applies exactly that plan.
32// `files` are the inbox captures it was started for.
33export type IngestRun =
34  | { status: 'planning'; files: string[] }
35  | { status: 'review'; files: string[]; plan: { bundle: string; approval: string; summary: string }; preview: string }
36  | { status: 'applying'; files: string[] }
37  | { status: 'done'; message: string }
38  | { status: 'failed'; reason: string }
39
40// Where the incubate pane is: shelves, one shelf's notes, or one note.
41export type View =
42  | { layer: 'home' }
43  | { layer: 'review' }
44  | { layer: 'recalls' }
45  | { layer: 'recall'; id: string }
46  | { layer: 'list'; shelf: Shelf }
47  | { layer: 'detail'; shelf: Shelf; file: string }
48
49declare module 'claude-code' {
50  interface PluginState {
51    'vault-jot': { backlog: Backlog | null; problem: string | null; isHidden: boolean; view: View; openForRepo: OpenForRepo | null; recalls: Recall[]; summary: SummaryDraft | null; ingestRun: IngestRun | null; draftHint: string | null; knownTargets: string[] }
52  }
53}
54