wiseguru_ReWrite-Voice-Notes/CLAUDE.md
WiseGuru f3b93d5ab9 Fix secrets bootstrap + modal record UX; add ROADMAP lifecycle tracker
Secrets:
- Warm the secret-storage probe before loadSettings so a fresh install
  actually defaults to Obsidian secret storage instead of caching an
  unconfigured passphrase envelope first.
- setEncryptionMode no longer early-returns on same-mode: an unconfigured
  passphrase store now always builds its kdf/verifier, so creating a
  passphrase (incl. on Linux without a keyring) writes secrets.json.nosync
  instead of silently no-opping.

Modal:
- The Record tab closes the modal on Stop and runs the pipeline detached
  with Notice progress (per-stage setMessage) and Notice errors, mirroring
  the reprocess-audio flow. The persisted recording is the recovery path,
  so no inline Retry. Paste / From note keep the in-modal Retry flow.

Docs:
- Replace FEATURES.md with ROADMAP.md: Planned / Unreleased / Released
  lifecycle, wired into the RELEASING.md release steps.
- Update SECRETS.md, CLAUDE.md, and the Commands-and-Menus wiki page.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 22:16:46 -07:00

83 KiB
Raw Blame History

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project state

This is the ReWrite (Voice Notes) plugin for Obsidian: record or paste speech, transcribe via a user-configured provider, clean and structure via an LLM, insert per a chosen template. Desktop and mobile.

The v1 implementation is feature-complete against obsidian-voice-notes-spec.md and docs/IMPLEMENTATION_PLAN.md. The spec is still the source of truth for behavior; the implementation plan resolves the spec's internal discrepancies (notably manifest id, base URL handling for openai-compatible, and mobile safeStorage unavailability). docs/claude-scratch/STATUS.md tracks per-phase commit state and the running list of architectural decisions made during implementation; consult it when picking up work or before changing anything cross-cutting.

When extending the plugin, follow the file layout the spec prescribes: provider adapters under src/transcription/ and src/llm/, factories in each index.ts, no provider-specific logic leaking outside its own file.

Documentation maintenance

Update CLAUDE.md with every behavioral change. When modifying code that this document describes (pipeline stages, command IDs, settings keys, gotchas, conventions), update CLAUDE.md in the same change. If a behavioral change has no existing section, add one or drop a note under "Gotchas". Treat the doc update as part of the task, not a follow-up.

Some subsystems are documented in depth in linked docs/ files (currently docs/DIARIZATION.md, docs/SECRETS.md, docs/WHISPER_HOST.md) with only a summary + pointer left here. The same rule applies: when you change behavior covered by one of those files, update the linked doc in the same change AND keep the CLAUDE.md summary accurate. Each linked doc restates this at its top.

The user-facing guide to the template format is the wiki page wiki/Creating-Templates.md (no longer a file seeded into the vault; the old in-vault Template guide.md and its DEFAULT_TEMPLATE_GUIDE constant were removed in favor of the wiki). Any change to the template structure (a new/changed NoteTemplate field or frontmatter property, the prompt-assembly order, the default-template set or count, or what the shared core carries) must update that wiki page in the same change: add the property to its frontmatter table AND give the behavior its own ## section. See the Templates section for the full rule.

The user-facing reference docs live in the wiki (the wiki/ folder, mirrored to the GitHub Wiki; see the Wiki section below) and in the slimmed root README.md. Both are in the in-sync set: any behavioral change a user can observe (a settings field, a command, a provider, a self-hosting step, a limit, a default-template change) must update the relevant wiki page AND the README quick-start/links if affected, in the same change. The wiki/ source is canonical; never hand-edit the GitHub Wiki, which is a generated mirror.

Reorganize, do not just append. For every doc in the in-sync set (CLAUDE.md, the linked docs/ files, the template guide, the wiki, the README), when a change touches documented behavior, first ask whether the doc's structure should change to absorb the new material coherently (split an overgrown page, move a topic to a better-fitting page, retitle a section, update wiki/_Sidebar.md and Home.md's table of contents) and do that reorganization as part of the same change. Blindly appending a paragraph to the nearest section is a documented anti-pattern here; the goal is docs that stay well-organized as features accrue, not a growing pile of addenda.

Wiki

User-facing documentation lives in wiki/ as one Markdown file per page. It is the canonical source; a GitHub Action (.github/workflows/wiki-sync.yml) mirrors the folder to the separate ReWrite-Voice-Notes.wiki.git repo on every push to master that touches wiki/. The wiki repo is generated output; never edit it by hand. One-time setup (already done): the Wiki feature must be enabled and have a first page created in repo settings before the Action can push.

GitHub wiki conventions: filenames become page names (spaces as hyphens, no .md in links), Home.md is the landing page, _Sidebar.md is the nav rail, _Footer.md the footer. Internal links use the page name, e.g. [Quick start](Quick-Start).

Page map (keep _Sidebar.md and Home.md's contents list in sync when adding/removing pages):

  • Home.md, _Sidebar.md, _Footer.md: navigation.
  • Quick-Start.md: install, Populate, first note (Daily note example). Overlaps with the README quick-start by design.
  • Settings-Reference.md: every settings section (driven by src/settings/tab.ts).
  • Commands-and-Menus.md: command palette, ribbon, editor/file menus, Quick Record UI (src/main.ts).
  • Creating-Templates.md: template file format + authoring guide. This is the canonical user-facing template guide (it replaced the old in-vault Template guide.md); keep it in sync with the NoteTemplate schema.
  • Providers.md: provider tables, model selection, base-URL conventions, diarization, context hint, known nouns, recording limits.
  • Self-Hosting-Whisper.md: local whisper.cpp host (mirrors user-facing parts of docs/WHISPER_HOST.md).
  • Self-Hosting-LLMs.md: Ollama/llama.cpp local and remote, plus low-spec model recommendations (refresh these as models age).
  • Secrets-and-Sync.md: encryption modes summary + the 7 sync-exclusion recipes.
  • Mobile.md: mobile limitations.
  • Troubleshooting.md: triage that routes into the per-page detail.

When you move user content out of the README, it goes here, and the README's Documentation section links to it. The deep docs/ files (DIARIZATION/SECRETS/WHISPER_HOST) stay developer-facing; the wiki summarizes their user-relevant parts and points at them where useful.

Commands

npm install        # install deps
npm run dev        # esbuild watch mode → bundles src/main.ts to ./main.js with inline sourcemaps
npm run build      # tsc -noEmit type-check, then esbuild production (minified, no sourcemaps)
npm run lint       # eslint over the repo (uses eslint-plugin-obsidianmd recommended)
npm version <patch|minor|major>  # bumps manifest.json + versions.json via version-bump.mjs

There is no test runner configured. Verification is npm run build && npm run lint (CI parity) plus the manual checklist in obsidian-voice-notes-spec.md (lines 454-476).

To publish a new version, follow docs/RELEASING.md (version bump + bare-version tag + CI-built, attested assets; do not hand-upload).

CI (.github/workflows/lint.yml) runs npm ci, npm run build, and npm run lint on Node 20.x and 22.x for every push/PR.

Build architecture

  • Entry: src/main.ts → bundled to ./main.js at repo root (the file Obsidian loads). Kept minimal: settings load, ribbon icon, two commands, settings tab, plus a single activeQuickRecord ref so the Quick Record command can toggle.
  • Bundler: esbuild.config.mjs. obsidian, electron, all @codemirror/*, all @lezer/*, and Node built-ins are marked external. Never import other runtime deps without bundling them in.
  • Release artifacts are main.js, manifest.json, and styles.css at the repo root. Do not commit the generated main.js.
  • TypeScript config (tsconfig.json) is strict: noImplicitAny, strictNullChecks, noImplicitReturns, noUncheckedIndexedAccess, useUnknownInCatchVariables, baseUrl: "src". Target ES6, module ESNext, lib DOM + ES5/6/7 only. No Node lib, so don't reach for Node APIs in plugin code.
  • ESLint (eslint.config.mts) layers eslint-plugin-obsidianmd's recommended rules on top of typescript-eslint. These rules encode Obsidian-specific correctness checks; respect them rather than disabling.

Source layout

src/
├── main.ts                          # Lifecycle, commands, ribbon, settings tab registration
├── types.ts                         # Shared interfaces (provider IDs, configs, templates, settings)
├── http.ts                          # requestUrl wrappers: jsonPost/jsonGet/multipartPost + ProviderError
├── platform.ts                      # Active-profile resolver + MediaRecorder availability probe
├── secrets.ts                       # Obsidian secretStorage (preferred) + passphrase (Argon2id/PBKDF2) for API keys
├── passphrase-strength.ts           # zxcvbn-ts wrapper (lazy dynamic import, async API): evaluatePassphrase + MIN_PASSPHRASE_SCORE gate + warmPassphraseStrength
├── diceware.ts                      # generateDicewarePassphrase (EFF wordlist, crypto rejection sampling)
├── eff-large-wordlist.ts            # EFF large diceware wordlist (7776 words)
├── recorder.ts                      # MediaRecorder state machine + getBestMimeType + live input-level monitor (no size cap; per-provider limits live in transcription/limits.ts)
├── audio-transcode.ts               # WebAudio decode + resample to 16 kHz mono PCM WAV (shared by whisper-local and mistral-voxtral)
├── pipeline.ts                      # transcribe → cleanup → insert orchestrator
├── insert.ts                        # cursor/newFile/append + {{date}}/{{time}} expansion
├── whisper-host.ts                  # Spawns/stops a user-supplied whisper-server child process (desktop only)
├── templates-folder.ts              # Load templates from a vault folder + populate it with the 10 defaults
├── template-guide.ts                # Writes the "Template update report.md" (the Update button's worklist) next to the templates folder; never loaded by the plugin. (The in-vault user guide was removed; the template guide now lives in the wiki.)
├── shared-core.ts                   # Load the shared cleanup preface from a vault Markdown file + populate default (prepended to every template prompt)
├── assistant-prompt.ts              # Load the ad-hoc-instructions assistant prompt from a vault Markdown file + populate default
├── known-nouns.ts                   # Load a vault Markdown file of known nouns + populate default + build the system-prompt section
├── audio-persist.ts                 # Write the recorded Blob to an attachments folder, return vault-relative path
├── wake-name.ts                     # Extract "<assistantName>, <directive>" instructions from a transcript
├── settings/
│   ├── index.ts                     # DEFAULT_SETTINGS, load/save, per-profile secret hydration
│   ├── tab.ts                       # PluginSettingTab: active profile, two profile sections, templates folder, recording
│   └── default-templates.ts         # The 10 default templates used by the populate button (General cleanup, Todo list, Daily note, Meeting notes, Meeting transcript, Idea capture, Lecture, Podcast, Guides, Book log); each prompt = per-template rules only (the shared preface is prepended at runtime from shared-core.ts)
├── ui/
│   ├── modal.ts                     # Main modal: template select + Record/Paste/From note tabs + setup-card injection
│   ├── setup-card.ts                # Inline blocker when active profile is unconfigured (voice vs text purpose)
│   ├── quick-record.ts              # QuickRecordController + floating mini-UI for the Quick Record command
│   ├── template-picker.ts           # Lightweight modal for picking a template (used by Process text command and editor menu)
│   ├── text-source.ts               # resolveActiveTextSource + runTextPipeline helpers for text-source flows
│   └── whisper-status-bar.ts        # Status-bar dot for whisper-host start/stop (desktop + whisper-local profile only)
├── transcription/
│   ├── index.ts                     # TranscriptionProvider interface + createTranscriptionProvider()
│   ├── limits.ts                    # Per-provider maxBytes/maxDurationMs + validateRecording (called from pipeline)
│   ├── openai.ts                    # Whisper-shape POST (also used by openai-compatible + groq)
│   ├── assemblyai.ts                # upload → submit → poll
│   ├── deepgram.ts                  # single POST
│   ├── revai.ts                     # submit → poll → fetch text (JSON transcript when diarizing)
│   ├── mistral-voxtral.ts           # Mistral Voxtral STT (JSON response; always transcodes to WAV)
│   └── whisper-local.ts             # Thin shim that POSTs to the WhisperHost-managed local server
└── llm/
    ├── index.ts                     # LLMProvider interface + createLLMProvider()
    ├── openai.ts                    # /v1/chat/completions (also used by openai-compatible + mistral)
    ├── anthropic.ts                 # /v1/messages
    └── gemini.ts                    # :generateContent

Pipeline

src/pipeline.ts runs four stages with onStage callbacks for UI:

  1. Persist audio (audio source only): writes the raw Blob to the vault via src/audio-persist.ts before transcription, so the user keeps the recording even if later stages fail. Path resolution: when settings.attachmentsFolderPath is set, the file goes under that folder with manual de-collision (-1, -2, ...); when empty, the path comes from app.fileManager.getAvailablePathForAttachment(filename), which respects Obsidian's own attachments setting. Filename is ReWrite-YYYY-MM-DD-HHmmss.<ext> with the extension derived from the blob's mime type (webm / m4a / ogg / wav / mp3, default webm). Failure is non-fatal: a Notice fires and transcription proceeds. The resolved path is later prepended to the cleaned output as ![[<path>]]\n\n before insertion.
  2. Transcribe: audiocreateTranscriptionProvider(profile.transcriptionProvider).transcribe(blob, config). Skipped when the source is paste or text (input passes through). Just before dispatching, validateRecording(blobSize, durationMs, providerId) from src/transcription/limits.ts throws a friendly per-provider error if the recording exceeds the provider's documented byte or duration cap. Because validation runs after persist-audio, the user keeps the saved file and can switch providers + reprocess from the vault.
  3. Cleanup: createLLMProvider(profile.llmProvider).complete(systemPrompt, transcript, config). The system prompt is the template prompt, optionally augmented with an ## Ad-hoc instructions block when the wake-name scan (src/wake-name.ts) extracts directives from the transcript, a ## Context block when params.contextHint is non-empty (see Context hint below), a ## Known nouns block when plugin.knownNouns is non-empty (see Assistant prompt and Known nouns sections below), and a ## Note properties block when the template declares noteProperties (see Note properties below). cleanupTranscript returns { body, properties, title? }: when the template declares properties OR sets titleFromContent, the LLM is asked to emit a leading ```yaml block which extractFromBlock parses off the front (the rest is the body); otherwise properties is {}, title is undefined, and body is the full output. On error, the provider error propagates unchanged; nothing is written to the clipboard (the earlier clipboard fallback was removed as a sensitive-content exposure, and for audio sources the persisted recording is the recovery path).
  4. Insert: src/insert.ts routes to cursor / newFile / append per the template. cursor falls back to append when no editor is active; append falls back to newFile when no markdown file exists. {{date}} / {{time}} in filename templates expand via Obsidian's moment, and {{title}} expands to the LLM-generated title (empty when no title). The modal's per-invocation Destination control overrides insertMode / newFileFolder / newFileNameTemplate via PipelineParams.destinationOverride; the override is shallow-merged onto a copy of the template before the insert call, so the template file on disk is never mutated. Extracted properties are threaded via InsertParams.properties and written into the note's frontmatter via app.fileManager.processFrontMatter in newFile mode only (see Note properties below). An extracted title (from titleFromContent) is threaded via InsertParams.title and shapes the newFile filename via the {{title}} token / whole-name replacement (see Note title below).

The pipeline accepts an AbortSignal (forwarded to providers) and is consumed by src/ui/modal.ts, src/ui/quick-record.ts, and src/ui/text-source.ts (the runTextPipeline helper for command + editor-menu entry points). Every caller passes the plugin itself as host: PipelineHost; PipelineHost is a narrow interface ({ assistantPrompt, knownNouns }) so cleanupTranscript can read the loaded vault content without importing ReWritePlugin (which would form a circular dep through the UI layer).

The modal has two pipeline-running paths. The Record tab closes the modal the moment recording stops and runs the pipeline detached via startRecordingPipeline (src/ui/modal.ts), reporting progress through a sticky Notice (setMessage per stage) and surfacing errors as a Notice (no inline Retry) — mirroring runAudioFilePipeline in src/ui/audio-source.ts. This is safe because the persist-audio stage saved the recording before transcription, so the vault file is the recovery path. The Paste and From note tabs instead use execute, which keeps the modal open with an inline .rewrite-progress line and renders an inline Retry button on error (they have no persisted recovery, so closing would lose the input). Destination override and context hint are captured into locals before startRecordingPipeline closes the modal, so a recorded run still honors them.

The PipelineSource union has three variants: audio (recorded blob, optional sourcePath for reprocess flows), paste (textarea input), text (input from an existing note via selection or whole body). Text-source flows skip transcription entirely and only require the LLM half of the profile. The audio variant's sourcePath is set by the reprocess flow (src/ui/audio-source.ts) to point at an existing vault file; when present, the persist stage is skipped and that path is reused for the ![[<path>]]\n\n prepend.

Provider system

src/transcription/index.ts and src/llm/index.ts each define a small interface plus a create...Provider(id) factory. Provider families share one adapter file where the API shapes match: OpenAI Whisper, openai-compatible, and Groq all dispatch into src/transcription/openai.ts with different base URLs; OpenAI GPT, openai-compatible, and Mistral all dispatch into src/llm/openai.ts. Mistral Voxtral does NOT share with openai.ts (see src/transcription/mistral-voxtral.ts) because Voxtral's response is JSON-only (no response_format=text) and it rejects WebM input (so the blob is always transcoded to 16 kHz mono WAV via src/audio-transcode.ts).

API keys are stored per profile on EnvironmentProfile.transcriptionConfig.apiKey / llmConfig.apiKey. Two slots per profile, one for transcription and one for the LLM. No global by-family map; the desktop and mobile profiles each carry their own keys even when both use the same provider (deliberate: per-profile keys make per-function usage tracking easier). Persistence is in src/secrets.ts using the key IDs profile-desktop-transcription, profile-desktop-llm, profile-mobile-transcription, profile-mobile-llm. These ids (and the namespace prefix secrets.ts prepends for secretStorage) are dash-joined, NOT colon-joined: Obsidian's app.secretStorage.setSecret throws on any id that is not lowercase-alphanumeric + dashes, so a colon/underscore id silently fails the availability probe on every platform. Do not reintroduce colons or underscores into a secret id.

Providers may optionally implement listModels(config, signal) returning a string array of model IDs the configured API key can access. Implemented by: OpenAI / Groq / Mistral (via openai.ts shared adapter), Mistral Voxtral (own adapter, filters Mistral's /v1/models catalog by ID substring voxtral), Anthropic, Gemini, Deepgram. Not implemented for openai-compatible (URL-specific, list-shape varies), AssemblyAI, Rev.ai. The settings tab caches results to GlobalSettings.modelCache per side and provider ID; the Refresh button in the model field triggers listModels and updates the cache. The model field is a single adaptive control (populateModelField in src/settings/tab.ts, shared by both sides via a side: 'transcription' | 'llm' arg): a dropdown when the provider supports listModels and the cache is non-empty, otherwise a plain text field. There is never both at once. The dropdown carries a trailing "Custom..." option (sentinel CUSTOM_MODEL_OPTION, never written to config.model) that toggles the same control into the text field (the forceText arg) so a model ID not in the catalog can still be typed; a "Back to list" button returns to the dropdown. A custom value not in the cache is shown as a selected <id> (custom) dropdown option. The Refresh button accompanies the dropdown (and the empty-cache text field, so the first fetch can flip it to a dropdown); on success the field re-renders in dropdown mode. openai-compatible / AssemblyAI / Rev.ai (no listModels) always show a plain text field with no Refresh. For AssemblyAI and Rev.ai the field description appends a "list of models" external link to the provider's docs (transcriptionModelDocsUrl + applyModelFieldDesc in src/settings/tab.ts); openai-compatible has none (the model list is the user's own server). Whichever control is active, the canonical source is profile.config.model.

Speaker diarization

Opt-in Speaker X: labels, supported only on assemblyai / deepgram / revai. Two switches: a per-profile TranscriptionConfig.diarize toggle and a per-template NoteTemplate.diarize override (frontmatter diarize: true, raises the effective setting only; the Meeting transcript default ships with it). Capability is gated by transcriptionProviderSupportsDiarization(id) (src/transcription/index.ts); on a non-capable provider the flag is a documented no-op. Labels survive cleanup via a DEFAULT_SHARED_CORE clause.

Full detail (per-adapter formatting, pipeline merge rules, label survival) lives in docs/DIARIZATION.md.

Local whisper.cpp host (desktop)

WhisperHost (src/whisper-host.ts, instantiated in onload, stopped in onunload) manages a user-supplied whisper-server child process. Config lives at GlobalSettings.localWhisper = { binaryPath, modelPath, port, extraArgs }: no auto-discovery, no auto-download, no baked defaults. Desktop-only (Node modules lazy-required behind Platform.isDesktop; the option is filtered out of mobile dropdowns). Loopback binding is enforced (a non-loopback --host throws before spawn) because whisper-server has no auth/TLS. The whisper-local transcription provider (src/transcription/whisper-local.ts) is a thin shim POSTing transcoded 16 kHz mono WAV to http://127.0.0.1:<port>/inference; no API key.

Full detail (start/stop/probe lifecycle, the spawned/adopted/external ownership model, PID sidecar, Auto-detect, the build script, and all whisper-host gotchas) lives in docs/WHISPER_HOST.md.

Settings

GlobalSettings (defined in src/types.ts) is the shape of data.json. Loading flow:

  1. plugin.loadData() returns Partial<GlobalSettings> | null.
  2. mergeSettings(DEFAULT_SETTINGS, stored) deep-merges, preferring stored values.
  3. hydrateSecrets() reads keys from secrets.json.nosync and writes them into each profile's transcriptionConfig.apiKey / llmConfig.apiKey.

Saving flow strips secrets out of data.json and writes them to secrets.json.nosync instead (see src/secrets.ts). Never persist API keys to data.json.

Secrets encryption

src/secrets.ts encrypts API keys file-wide in one of two modes (no unencrypted at-rest option):

  • secretStorage (default/preferred when available) — Obsidian's first-party app.secretStorage, an OS-encrypted shared store. Reached via a narrow cast + round-trip self-test, falls back to passphrase when unavailable (old Obsidian, Linux without a keyring).
  • passphrase (always-available fallback) — WebCrypto AES-GCM-256 keyed by a user passphrase, KDF Argon2id (PBKDF2 fallback), stored in secrets.json.nosync. Entropy-gated at MIN_PASSPHRASE_SCORE (3/4). Locks/unlocks; the derived key never touches disk.

The two stores coexist: the on-disk envelope retains passphrase kdf/verifier/keys even while secretStorage is active (a preserved-at-rest snapshot), so mode is just the active-store flag. Switching the active method and transferring keys are decoupled into three separate operations (a switch never moves or drops keys): setEncryptionMode (switch only), copyKeys (copy inactive→active, source kept), clearKeys(mode) (wipe one method). The settings tab exposes the mode dropdown (pure switch) plus explicit Copy and Clear buttons (with ConfirmModal confirmations + a copied/cleared count Notice). The transfer button is labelled Copy, not "Migrate", because the source copy is kept; unlockPassphraseStore lets a secret-storage-active user unlock the passphrase snapshot to copy it.

ReWritePlugin.encryptionStatus ({ mode, locked, configured, secretStorageAvailable, passphraseConfigured }, refreshed via refreshEncryptionStatus()) is read synchronously by UI; pipeline entry points gate on locked and call promptUnlock(). passphraseConfigured is mode-independent (kdf+verifier on disk), used by the UI to distinguish switch-to vs create-passphrase and to know whether a snapshot is copyable. minAppVersion is 1.4.4 (driven by processFrontMatter, not secretStorage, which is feature-detected).

Full detail (envelope schema, KDF params, lock/unlock flow, opportunistic PBKDF2→Argon2id KDF upgrade, the setEncryptionMode / copyKeys / clearKeys / changePassphrase / resetSecrets model, locked-state behavior, and the secrets gotchas) lives in docs/SECRETS.md.

Templates

Templates are Markdown files in a vault folder, not entries in data.json. The folder path lives on GlobalSettings.templatesFolderPath (default ReWrite/Templates). Each .md file in the folder is one template: YAML frontmatter holds id, name, insertMode, newFileFolder, newFileNameTemplate, plus the three optional boolean flags disableSharedCore, enableContextHint, and diarize; the file body is the LLM prompt. Files are sorted by basename in the modal/picker so users can prefix names (01-..., 02-...) to control order.

src/templates-folder.ts exports loadTemplatesFromFolder(app, folderPath), populateDefaultTemplates(app, folderPath), and updateDefaultTemplates(app, folderPath) (see Updating defaults below). The plugin keeps a cache on plugin.templates: NoteTemplate[], refreshed in src/main.ts on:

  • workspace.onLayoutReady after onload (initial load, after the vault is ready)
  • vault create / modify / delete events scoped to the templates folder via isPathInTemplatesFolder
  • vault rename (checks both old and new path)
  • the Templates folder path field changing in settings
  • the populate button completing

Consumers (src/main.ts, src/ui/modal.ts, src/ui/quick-record.ts) read plugin.templates directly, never settings.templates (there is no such field). The populate button is non-destructive: it skips any default template whose id already exists on disk, and skips path collisions. Frontmatter id is canonical for identity, so renaming a file does not break the defaultTemplateId / lastUsedTemplateId reference. The first-launch experience is empty templates plus a setup nudge in the modal; the user clicks Populate to get the defaults.

The 10 defaults (src/settings/default-templates.ts) are General cleanup, Todo list, Daily note, Meeting notes, Meeting transcript, Idea capture, Lecture, Podcast, Guides, Book log. Each default template carries ONLY its per-template rules; the shared cleanup preface (guardrail + condensed cleanup + output discipline) is NOT baked into the prompt strings. It lives in the vault SharedCore.md file and is prepended at runtime by the pipeline (see Shared core below). General cleanup carries the full detailed prose-polishing ruleset as its body; the structured templates carry only their section layout. The Daily note default is a prompt-only structured fill (extracted ## Calendar / ## Goals / ## Tasks, each omitted when empty, then ## Braindump = the full cleaned transcript last); no NoteTemplate schema change was needed to drive it. Meeting transcript is the Meeting notes prompt adapted for speaker-labeled input, shipped with diarize: true so it forces diarization on (see Speaker diarization). Guides turns a spoken walkthrough into a step-by-step how-to (insertMode: newFile, enableContextHint: true); its prompt prescribes a strict two-level list format (ordered top-level steps, - bulleted sub-steps indented one tab, no deeper nesting, no a./i./* markers) because LLMs reliably mangle nested ordered lists, plus a trailing ## Gaps section for anything ambiguous or missing. Book log (insertMode: newFile, enableContextHint: true) turns spoken notes into a short book-log body. The five structured newFile defaults ship noteProperties (see Note properties below): Meeting notes / Meeting transcript carry subject / participants / date, Lecture carries subject / lecturer / course, Podcast carries podcast / episode / host / guests, Guides carries topic / tool, and Book log carries title / author / series.

NoteTemplate.disableSharedCore?: boolean (frontmatter disableSharedCore: true) opts a single template out of the shared-core prepend. renderTemplateFile ALWAYS emits the key so the knob is discoverable: empty (disableSharedCore:, parses to null = not disabled) by default, disableSharedCore: true when set. parseTemplateFile treats it as disabled only when the value is boolean true or the string "true" (case-insensitive) — the string form is tolerated because Obsidian's Properties UI may store an edited value as text; any other value (null/empty/false) means not disabled. The three opt-in boolean flags enableContextHint (see Context hint), diarize (see Speaker diarization), and titleFromContent (see Note title) follow the exact same render/parse convention (always-emitted empty key, boolean-or-"true" tolerance); their polarity is positive (set to turn ON), the reverse of disableSharedCore.

The Templates "Populate" button also seeds SharedCore.md when missing (non-destructive), because the shared core is load-bearing for the default templates' quality (it carries their guardrail + output discipline). Populating templates without it would yield prompts with no guardrail. (Populate no longer seeds an in-vault help file; the user-facing template guide lives in the wiki.) Keep wiki/Creating-Templates.md in sync with the template structure. Whenever you add or change a NoteTemplate field / frontmatter property, change the prompt-assembly order, alter what the shared core carries, or change the default-template set or count, update that wiki page in the SAME change: add the property to its frontmatter table AND give the behavior its own ## section. The settings tab links users to it from the Templates section ("Creating templates"); it is the user-facing contract for the template format, so treat updating it as part of the task, not a follow-up.

Updating defaults

The Templates section ships three buttons sharing one Setting row: Populate (.setCta() primary), Update, and Load prior versions (both secondary). Populate only ever adds missing files, so it can never push a changed default (new field, new noteProperty, reworded prompt) into a file the user already has. Update (updateDefaultTemplates(app, folderPath)) reconciles the user's default-derived files against the current built-ins; Load prior versions (loadPriorTemplateVersions(app, folderPath)) drops earlier shipped prompt versions in as their own selectable templates for comparison.

Default history. src/settings/template-history.ts holds TEMPLATE_HISTORY: Record<string, TemplateVersionSnapshot[]> — the plugin's in-code memory of what each default used to be, keyed by template id, each snapshot carrying { version, template }. It is the base for the merge and the source for Load prior versions. It starts EMPTY. MAINTENANCE RULE (treat like the keep-the-guide-in-sync rule): whenever you change a default in src/settings/default-templates.ts, append the OUTGOING template to TEMPLATE_HISTORY[id] under the manifest version it shipped in. Without the snapshot, Update cannot tell an unedited old prompt from a user edit and falls back to a body conflict. priorVersionsForId(id) and allPriorVersions() return clones so callers can't mutate the registry.

Per-field 3-way merge. mergeTemplate(onDisk, def, priors) (pure, synchronous; priors = priorVersionsForId(id)) treats a field as pristine (user never touched it) when its on-disk value equals the current default OR any prior shipped default; a pristine value is brought forward to the current default, a genuine edit is kept. The prompt body is the only field whose kept edit becomes a report body conflict — an unedited old body is silently updated (recorded in changes). Scalars + flags adopt-or-keep silently (a real adoption is noted in changes). noteProperties union by name: missing defaults appended; an instruction matching a prior default is brought forward; a genuinely edited instruction is kept + changedInstruction; a property the default dropped is always kept + removedProperty (with wasShippedDefault set when the user's value matches a prior default, so the report can say it is safe to delete). Because renderTemplateFile always emits the four flag stubs and emits noteProperties only when non-empty, re-rendering a pristine current default is byte-identical to Populate's output, so an already-current folder is a clean no-op.

updateDefaultTemplates walks the folder, matches files to defaults by frontmatter id (via readTemplateId, also now backing collectExistingIds; non-default-derived files skipped), merges, and vault.modifys in place only when the render differs (CRLF-normalized compare; never renames, even with an ordering prefix). It then recreates any default missing from disk entirely (superset top-up, same name + path-collision skip as Populate) but does NOT seed SharedCore.md (Populate's job). Counters are mutually exclusive: created + updated + unchanged + conflicts + parseFailed = files seen. A default-derived file that fails to parse is left untouched and reported as parseFailed.

Load prior versions writes each allPriorVersions() snapshot as a standalone template with a distinct id (<id>@<version>) and versioned name (<name> <version>), so it appears in the picker for comparison, never collides with the live template's identity, and is left untouched by Update (its id is not a current default) and Populate. Non-destructive (skips by id/path); reports available so the button can say "no prior versions yet" when the registry is empty.

Anything Update cannot auto-merge is written to Template update report.md via writeTemplateUpdateReport (src/template-guide.ts, TEMPLATE_UPDATE_REPORT_FILENAME), placed in the parent of the templates folder (OUTSIDE it so loadTemplatesFromFolder never parses it) and overwritten every run. It lists, per non-unchanged template: changes applied automatically, a body conflict (user file kept, default shown beside it in ~~~text fences), removedProperty / changedInstruction / parseFailed. The report types (TemplateUpdateConflict / TemplateUpdateEntry / UpdateResult) live in src/templates-folder.ts; template-guide.ts imports them type-only, so templates-folder.ts → template-guide.ts is the one runtime edge (acyclic). Caveat (documented in the report footer): a vault.modify re-serializes the frontmatter via stringifyYaml, which drops YAML comments; the prompt body is passed through untouched, and an already-current file is never rewritten.

Shared core

A vault Markdown file whose body is prepended to every template prompt at cleanup time. Path: GlobalSettings.sharedCorePath (default ReWrite/SharedCore.md). src/shared-core.ts exports loadSharedCoreFromFile(app, path), populateDefaultSharedCore(app, path), isPathSharedCore(path, configuredPath), and the DEFAULT_SHARED_CORE constant (the three-paragraph preface: anti-injection guardrail, condensed cleanup rules, output discipline) used as the populated file body. The loader strips any leading frontmatter (guidance only, never sent to the LLM) and returns the trimmed body, or null when the file is missing/empty. The plugin caches it on plugin.sharedCore: string | null, refreshed in src/main.ts on the same triggers as the assistant prompt (workspace.onLayoutReady, scoped vault create/modify/delete/rename, settings-path change, populate button).

src/pipeline.ts cleanupTranscript prepends it: systemPrompt = sharedCore ? ${sharedCore}\n\n${template.prompt} : template.prompt, where sharedCore = template.disableSharedCore ? null : host.sharedCore. So the order in the assembled system prompt is shared core → template prompt → ad-hoc instructions → known nouns. Deleting or emptying SharedCore.md disables it globally (no fallback to a baked-in default; null means inject nothing); disableSharedCore: true disables it for one template. PipelineHost gained sharedCore: string | null alongside assistantPrompt / knownNouns.

Injection caveat: vault and transcript text (the assistant prompt, wake-name ad-hoc directives, known nouns, and the cleaned input itself) all flow into the system prompt unescaped. The shared-core preface is the anti-injection defense, so a template with disableSharedCore: true runs without that guardrail. This is intentional (the user owns their vault), but renderTemplates in src/settings/tab.ts surfaces a .rewrite-warning-text line naming any loaded template whose disableSharedCore === true so the loss of protection is visible.

The settings "Shared core" section (renderSharedCore in src/settings/tab.ts) shows an Enabled/Disabled badge next to the heading (.rewrite-status-badge.is-enabled / .is-disabled, inserted into the heading's nameEl, driven by plugin.sharedCore !== null). Like the other settings status text, it reflects state as of the last full-container render, not live keystrokes in the path field. The Templates "Populate" button calls populateDefaultSharedCore after populateDefaultTemplates so a first-run Populate seeds the shared core too (it is load-bearing for the default prompts' guardrail/output discipline); non-destructive, skipped when the file exists.

Assistant prompt

The system-prompt preface inserted above extracted ad-hoc directives lives as a Markdown file in the vault, not a settings textarea. Path: GlobalSettings.assistantPromptPath (default ReWrite/AssistantPrompt.md). src/assistant-prompt.ts exports loadAssistantPromptFromFile(app, path), populateDefaultAssistantPrompt(app, path), isPathAssistantPrompt(path, configuredPath), and the DEFAULT_ASSISTANT_PROMPT constant used as the fallback when the file is missing or empty. The plugin caches the body on plugin.assistantPrompt: string | null, refreshed in src/main.ts on the same triggers as templates (workspace.onLayoutReady, scoped vault create/modify/delete/rename, settings-path change, populate button). The file body is the prompt; frontmatter is currently ignored (the loader tolerates it for future extensions). src/pipeline.ts reads params.host.assistantPrompt ?? DEFAULT_ASSISTANT_PROMPT inside cleanupTranscript.

Branding note: the "AI name" / "Agent control prompt" labels in older builds are replaced by "Assistant name" / "Assistant prompt file" everywhere. The wake-name feature itself keeps the term "wake name" (it's the trigger word, not the persona). The setting key is assistantName; the persona is "the assistant".

Known nouns

A vault Markdown file of proper nouns the LLM should preserve verbatim. Path: GlobalSettings.knownNounsPath (default ReWrite/KnownNouns.md). src/known-nouns.ts exports loadKnownNounsFromFile, populateDefaultKnownNouns, isPathKnownNouns, and buildKnownNounsSystemPromptSection(nouns). File format: YAML frontmatter for human-readable guidance (token-cost warning, format hint), Markdown body with one noun per line, optional canonical: alt1, alt2 for misheard variants. Lines starting with # and blank lines are skipped. Frontmatter is parsed but NOT sent to the LLM in v1; future opt-in is possible but should not become the default. The default file body includes both the guidance frontmatter and two illustrative example nouns.

Cache: plugin.knownNouns: KnownNoun[] (default []), refreshed on the same triggers as the assistant prompt. src/pipeline.ts appends the section returned by buildKnownNounsSystemPromptSection(host.knownNouns) to the system prompt when non-empty. Order in the assembled prompt: shared core, template prompt, ad-hoc instructions (if any), context hint (if any), known nouns (if any), note properties (if any).

Note properties

A template can declare frontmatter properties the LLM fills in from the content, written into the new note's YAML frontmatter. NoteTemplate.noteProperties?: NotePropertySpec[] (src/types.ts, NotePropertySpec = { name; instruction }). Authored in template frontmatter as a YAML map (key = property name, value = instruction string), parsed into an ordered array (object key order drives both the prompt and the write order). Unlike the three boolean flags, renderTemplateFile emits noteProperties ONLY when non-empty (a nested map has no useful always-empty stub); parseTemplateFile reads any object-map value, trims keys, coerces missing instructions to "", and skips blank keys (src/templates-folder.ts).

Pipeline (src/pipeline.ts): cleanupTranscript returns { body, properties, title? }. When template.noteProperties is non-empty OR wantsTitle is set (and llmProvider !== 'none'), a ## Note properties section is appended LAST in the system prompt (after known nouns) listing the exact keys + instructions and telling the model to emit ONE leading ```yaml block containing exactly those keys, then a blank line, then the note body. That section explicitly overrides the shared-core "no code fences / output only the note" output discipline, but only for the single leading block. extractFromBlock(raw, specs, wantsTitle) then: seeds properties with every declared key = '' (the scaffold), matches a leading ```yaml fence, parseYamls it, and overlays values for declared keys only (extras ignored, non-strings String()-coerced, null/undefined skipped); the reserved noteTitle key is pulled into title (when wantsTitle) and is NOT added to properties. When no block is present the whole output is the body. When a block IS present it is ALWAYS stripped from the body even if its YAML is malformed (the model emitted a properties block, not content); a strict parseYaml failure falls back to a tolerant line-based read (key: value lines, stripQuotes peels matched/stray quotes) so one bad value does not blank the whole scaffold. The prompt steers the model with an explicit unquoted example and "leave unknown values blank" wording.

Write side: runPipeline extracts BEFORE prepending the ![[audio]] embed (otherwise the embed pushes the YAML off byte 0), builds finalContent from body, and threads properties + title via InsertParams (src/insert.ts). Only insertNewFile applies properties, via app.fileManager.processFrontMatter after vault.create (which prepends a real ---...--- block above the embed); cursor / append ignore them (they write into a user-owned existing note). Scope is newFile-only by design (matches the "new files" use case; never silently rewrites an existing note's frontmatter). The Meeting notes, Meeting transcript, Lecture, Podcast, Guides, and Book log defaults ship with noteProperties.

Note title

A template can have the LLM name the new note from the content (and context). NoteTemplate.titleFromContent?: boolean (src/types.ts), parsed/rendered with the same always-emitted-stub convention as the other opt-in flags. The title rides the SAME leading ```yaml channel as Note properties, under the reserved key noteTitle (module constant RESERVED_TITLE_KEY in src/pipeline.ts). Activation: the block is requested when noteProps.length > 0 || wantsTitle, where wantsTitle = template.titleFromContent && !allowed.has('noteTitle') (a user property literally named noteTitle wins and is written to frontmatter; title-from-content is then disabled so the key is never double-defined). extractFromBlock returns the value on CleanupResult.title and deliberately keeps noteTitle OUT of the property allowed set, so it is never written to frontmatter.

Filename use (newFile only; cursor / append ignore InsertParams.title, symmetric with properties): generation is always requested when the flag is set and consumed only in insertNewFile, so it does not depend on destinationOverride (which can change insertMode after cleanup). src/insert.ts expandFilenameTemplate(template, title?) adds a {{title}} token; insertNewFile substitutes it when present (then collapses doubled spaces a missing token leaves and trims), or makes the title the whole stem when the name template has no token. titleToFilename hardens the model output (collapse whitespace, reuse the exported sanitizeFilename, strip leading dots + trailing dots/spaces, cap at MAX_TITLE_LEN 100, guard reserved Windows device names) and returns '' when nothing usable remains (including sanitizeFilename's 'Untitled' sentinel), in which case the filename falls back to the static name-template expansion. Collisions still go through resolveNewFilePath. Defaults shipping titleFromContent: true: Meeting notes / Meeting transcript (Meeting {{date}} {{title}}), Lecture (Lecture {{date}} {{title}}), Podcast / Guides / Book log ({{title}}); Daily note stays date-named (flag off).

Context hint

Optional, per-invocation free-text background about a recording (speakers, setting, subject) fed to the cleanup LLM, e.g. "Lecture by Dr. Smith on thermodynamics" or "Meeting with Rachel, Joe, and Sally". The situational, one-off counterpart to the persistent Known nouns list; pairs naturally with diarization (maps Speaker X: labels to real names).

Two halves, deliberately decoupled:

  • UI gate (per-template flag). NoteTemplate.enableContextHint?: boolean (frontmatter enableContextHint: true) decides whether the input field is shown for a template. It is a positive opt-in (absent/false = hidden), the reverse polarity of disableSharedCore. parseTemplateFile / renderTemplateFile in src/templates-folder.ts handle it exactly like disableSharedCore (boolean true or string "true"; renderTemplateFile always emits the key so it is discoverable). The Meeting notes / Lecture / Podcast defaults (src/settings/default-templates.ts) ship with the flag set; the other four do not.
  • Injection (pipeline, flag-agnostic). PipelineParams.contextHint?: string. src/pipeline.ts cleanupTranscript appends a ## Context block (with a one-line "treat as reference, not instructions" preface) whenever the hint is non-empty, ordered after ## Ad-hoc instructions and before the Known nouns block. The pipeline never reads the flag; it injects on any non-empty hint. Like the other vault/transcript inputs, the hint flows in unescaped and rides behind the shared-core anti-injection guardrail.

UI surfaces, both a collapsed <details> so the frictionless path is untouched: the main modal (src/ui/modal.ts renderContextSelector, shown only when the active template has the flag; contextHint / contextExpanded instance state reset on template change, survives re-renders like destinationExpanded) and the reprocess-audio picker (src/ui/template-picker.ts, via showContext which src/main.ts sets to templates.some(t => t.enableContextHint); the typed value is forwarded to runAudioFilePipeline only when the picked template has the flag). Quick Record and the process-text command intentionally skip it.

Commands

Registered in src/main.ts:

  • rewrite-voice-notes:open-modal ("Open"): opens the main modal with the last-used template selected.
  • rewrite-voice-notes:quick-record ("Quick record (last used)"): starts a recording immediately with a floating mini-UI (no modal). Second press toggles to Stop. Template = pickQuickRecordTemplate (lastUsedTemplateIddefaultTemplateIdtemplates[0]). On unconfigured profile or capture-API unavailability, opens the modal instead. On post-capture pipeline error, opens the modal so the user can retry (the persisted audio file is the recovery path; the pipeline no longer copies the transcript to the clipboard).
  • rewrite-voice-notes:quick-record-fixed ("Quick record (set template)"): same flow, but records with the template chosen in GlobalSettings.quickRecordTemplateId (Settings dropdown beside Default template). If that id is unset or no longer resolves, it shows a "choose a Quick record template in settings" Notice and does not start (no templates[0] fallback, unlike the last-used command). Both commands share toggleQuickRecord(opts?) and the single activeQuickRecord ref, so either one stops an in-flight recording. The floating UI shows a stop-hotkey hint ("Press or click Stop") read live from the command's binding; see the Gotcha on hotkeyManager.
  • rewrite-voice-notes:process-text ("Process text with template"): runs a template over the active editor's selection (or the whole note body if there's no selection). Opens a template quick-picker, then runs the pipeline in the background with progress shown via Notice. Gates on LLM-only configuration; opens the main modal's setup card when not configured. Bails with a Notice when no Markdown editor is active.
  • rewrite-voice-notes:reprocess-audio ("Reprocess audio file with template"): reruns the pipeline over an audio file already in the vault. Opens an AudioFilePickerModal (FuzzySuggestModal<TFile> filtered to AUDIO_EXTENSIONS from src/audio-persist.ts) then the template quick-picker, then calls runAudioFilePipeline in src/ui/audio-source.ts. The pipeline skips its persist-audio stage because the audio source variant carries a sourcePath (the existing vault path is reused for the ![[<path>]]\n\n prepend). Gates on the full voice profile (isProfileConfigured).
  • rewrite-voice-notes:start-whisper-host / rewrite-voice-notes:stop-whisper-host: start or stop the local whisper.cpp server. Both use checkCallback so the palette only shows them on desktop, when the active profile's transcription provider is whisper-local (start) or when the host is currently running / starting (stop). Errors surface via Notice. Same code paths as the settings-tab Start/Stop button.

Plus an editor-menu item "ReWrite with template..." registered via workspace.on('editor-menu', ...) (and a second "Reprocess audio with template..." item that appears only when the cursor sits inside an ![[<audio>]] embed, resolved via app.metadataCache.getFirstLinkpathDest), a workspace.on('file-menu', ...) handler that adds "Reprocess audio with template..." for audio files in the file explorer, an addRibbonIcon('mic', 'ReWrite', ...) that opens the modal, and a status-bar item (src/ui/whisper-status-bar.ts) showing the live whisper-host status. The status bar polls whisperHost.status() every 1 s via registerInterval, click toggles start/stop, and the item is hidden via the rewrite-hidden CSS class when on mobile or when the active profile is not whisper-local.

Code style

Per .editorconfig: tabs (width 4), LF, UTF-8, final newline. Matches the existing source.

Obsidian plugin conventions

AGENTS.md has the full Obsidian-specific playbook. The non-obvious rules that actually constrain implementation:

  • Never change manifest.json's id after release. It's rewrite-voice-notes. Locked. (Renamed once pre-release from the invalid rewrite-plugin, which Obsidian's manifest rules reject because an id may not end in plugin; no users were affected. Do not change it again.)
  • Use this.register* helpers (registerEvent, registerDomEvent, registerInterval) for anything that needs cleanup. Otherwise reload/unload leaks. The Quick Record floater is the one exception (a document.body div lifecycled by QuickRecordController.cancel(), which onunload calls).
  • Mobile compatibility: avoid Node/Electron APIs unless manifest.json sets isDesktopOnly: true. It's false, and the spec's mobile profile depends on this.
  • Keep src/main.ts minimal: only plugin lifecycle, command registration, settings tab registration. Feature logic belongs in dedicated modules.
  • Defer heavy work: no long tasks in onload. Providers/recorders lazy-init when first used.
  • Network policy: provider calls go to user-configured endpoints with user-provided keys. No telemetry, no auto-update of plugin code, no fetch+eval.
  • Releases: GitHub release tag must exactly match manifest.json's version (no leading v). Attach main.js, manifest.json, styles.css as individual binary assets (not zipped). This is automated by .github/workflows/release.yml: pushing a version tag builds the bundle, runs actions/attest-build-provenance (GitHub artifact attestations for provenance), and publishes the assets via softprops/action-gh-release. To cut a release, push a tag named exactly the version; do not hand-upload assets (that loses attestation). Before publishing any release, follow docs/RELEASING.md for the full step-by-step (version bump, tag, push, verify) and the guideline-conflict checklist that keeps the Obsidian community review green.

Gotchas

HTTP and provider requests

  • requestUrl multipart bodies are hand-built. requestUrl does not accept FormData. src/http.ts exports buildMultipart(parts) which produces a Uint8Array with a random boundary; transcription adapters (Whisper, Rev.ai) call into it. If you add a multipart-LLM provider, reuse this rather than reaching for FormData.
  • requestUrl uses throw: false + status check. All adapters surface non-2xx as ProviderError with status and body, so users see provider-attributed errors instead of opaque network failures.
  • Provider auth always goes in a header, never the URL query. Every adapter passes its key via a header (Authorization: Bearer, x-api-key, Token, and x-goog-api-key for Gemini). Do not add a ?key=/?token= query-auth provider: query strings leak into proxy/CDN logs, history, and requestUrl's network-failure message. As a backstop, the network-failure catch in src/http.ts providerRequest runs redactQueryStrings over the message (replaces any ?... with ?<redacted>) before building the ProviderError, so even a future query-auth slip cannot surface a secret in a Notice or log. The body.slice(0, 200) truncation in the ProviderError constructor is unrelated and left as-is (response bodies do not carry the request key).

Pipeline and provider system

  • Both provider unions include 'none'. src/types.ts TranscriptionProviderID and LLMProviderID carry a 'none' member for users who only want one half of the pipeline. The factories in src/transcription/index.ts and src/llm/index.ts return sentinel providers (transcription throws on transcribe(); LLM complete() returns the user message unchanged), but the pipeline never actually calls these because: (a) collectTranscript throws a friendlier error when transcriptionProvider === 'none' and source.kind === 'audio'; (b) cleanupTranscript short-circuits and returns the raw transcript when llmProvider === 'none' (this also skips wake-name extraction and known-nouns injection, since both only matter when an LLM consumes the system prompt). The settings tab + setup card hide model/baseUrl/apiKey fields for the 'none' side; isProfileConfigured / isProfileConfiguredForText treat 'none' as configured. The modal's Record tab, Quick Record, and the reprocess-audio command all gate on transcriptionProvider === 'none' with a "use Paste instead" hint.
  • PipelineHost decouples the pipeline from ReWritePlugin. src/pipeline.ts reads params.host.assistantPrompt and params.host.knownNouns through the narrow PipelineHost interface in src/types.ts. The plugin class implements PipelineHost, but the pipeline never imports ReWritePlugin directly, which would create a cycle through the UI layer. New cross-cutting cleanup-stage inputs should extend PipelineHost rather than reach for the plugin object.
  • Per-provider recording limits live in src/transcription/limits.ts, not the recorder. src/recorder.ts does not cap recordings at any size; validateRecording(blobSize, durationMs, providerId) runs in src/pipeline.ts between the persist-audio and transcribe stages, throwing a friendly provider-attributed error if the recording exceeds the documented byte or duration ceiling. Both modal and Quick Record thread the recorder's durationMs onto the audio pipeline source so the duration check has data; the reprocess flow (src/ui/audio-source.ts) omits durationMs (no cheap way to measure an arbitrary vault file), so reprocess only triggers the byte check. Limits source: openai/groq 25 MB, assemblyai 5 GB/10 h, deepgram 2 GB, revai 2 GB/17 h, mistral-voxtral 1 GB/30 min, openai-compatible/whisper-local/webspeech no client-side cap.
  • Async poll timeout is duration-aware, also in src/transcription/limits.ts via pollTimeoutMs(durationMs?). The two polling adapters (src/transcription/assemblyai.ts, src/transcription/revai.ts) used to share a flat POLL_TIMEOUT_MS = 60_000, which made any recording the server took longer than a minute to process fail before it finished. They now derive the timeout from the recorded length: min(60s + durationMs * 2, 2 h), so a short clip with a problem fails in ~1 min while a long job has room. durationMs is threaded as the optional 4th arg of TranscriptionProvider.transcribe(audio, config, signal?, durationMs?) from src/pipeline.ts (source.durationMs); the non-polling adapters ignore it (their impls simply omit the param). It is undefined for the reprocess flow (src/ui/audio-source.ts, no cheap way to measure a vault file), which then falls back to the 2 h ceiling.

LLM and token limits

  • maxTokens has two settings-tab views over one value. LLMConfig.maxTokens (per profile, default 2560) is the single source of truth. The normal-area "Maximum note length" dropdown (renderNoteLength in src/settings/tab.ts) frames it in minutes via NOTE_LENGTH_PRESETS at TOKENS_PER_MIN = 256 (≈150 wpm × ~1.3 tokens/word, padded ~20% for headings/bullets/Speaker X: labels; ~10 min → 2560). The Advanced "LLM max tokens" text field edits the same number raw; a value not matching a preset surfaces in the dropdown as a "Custom (N tokens, ~M min)" option. The dropdown calls this.display() on change so Advanced reflects the new number; the raw text field does not redraw (focus preservation), so the dropdown updates on the next full render. The Anthropic adapter's config.maxTokens > 0 ? ... : 2560 fallback (src/llm/anthropic.ts) must stay in sync with the default. The cap is on output tokens, so it bounds note length, not input.
  • maxTokens over a model's output cap is remapped to a friendly error. When the requested output cap exceeds a model's max output tokens, Anthropic and OpenAI return a cryptic HTTP 400. remapOutputLimitError (src/llm/index.ts), applied as a .catch() on the complete() POST in src/llm/anthropic.ts and src/llm/openai.ts, detects that specific 400 (body names max_tokens/max_completion_tokens + a "maximum/too large/at most/exceed" phrase) and rethrows a ProviderError pointing at the "Maximum note length" setting; all other errors pass through unchanged. Its never return preserves the awaited type. Gemini silently clamps maxOutputTokens instead of erroring, so it gets no remap (and can therefore truncate without warning on long notes).
  • OpenAI reasoning models need max_completion_tokens, not max_tokens. src/llm/openai.ts usesCompletionTokens(id, model) switches the param name to max_completion_tokens when id === 'openai' and the model matches /^(o\d|gpt-5)/i (o1/o3/o4 + gpt-5 families), which reject the legacy max_tokens. Scoped to the first-party openai id only; openai-compatible and mistral keep max_tokens, so a reasoning model proxied behind an openai-compatible endpoint is a known gap. This only fixes the token param; o1-mini/o1-preview also reject system messages, which is not handled.
  • No baked-in model defaults. Both profiles ship with model: "". The modal renders an inline setup card that blocks recording/paste until the active profile has a provider, model, key, and (for openai-compatible) base URL. If you add a provider, do not bake a default model string; surface it as placeholder hint text.
  • openai-compatible base URL asymmetry (literal interpretation of the spec): transcription appends /v1/audio/transcriptions to a root URL (http://localhost:8080); LLM appends /chat/completions to a URL that already includes /v1 (http://localhost:11434/v1). The settings UI hint text and setup card both guide users; do not "normalize" one to match the other. The openai-compatible LLM option is also the supported route for cloud OpenAI-compatible services (DeepSeek, Kimi/Moonshot, Qwen/DashScope, Zhipu GLM) — there are no first-class provider entries for them; the README's "Cloud OpenAI-compatible LLMs" section carries the per-provider base URLs. The LLM option label is "OpenAI-compatible (cloud or local)" to reflect this.

Templates, properties, and insertion

  • Templates are vault files, not settings. There is no settings.templates array. Consumers read plugin.templates (refreshed from disk). When you add a field to NoteTemplate, update src/templates-folder.ts on both sides: parseTemplateFile reads it out of frontmatter (with a sensible default if missing), and renderTemplateFile writes it into the frontmatter the populate button emits. The populate button is non-destructive: it skips files whose id already exists, so re-running it tops up the folder without clobbering user edits.
  • The two template frontmatter flags have opposite polarity. disableSharedCore is a negative opt-out (set it to turn a default OFF); enableContextHint is a positive opt-in (set it to turn a feature ON). Don't "harmonize" them. enableContextHint only gates whether the modal / reprocess-picker shows the Context field; the pipeline injects a ## Context block on any non-empty PipelineParams.contextHint without consulting the flag (see Context hint section).
  • Note-property extraction must run before the audio-embed prepend, and frontmatter is written newFile-only. src/pipeline.ts extractFromBlock strips the leading ```yaml block off the LLM output inside cleanupTranscript, BEFORE runPipeline prepends ![[<path>]]\n\n; prepending first would push the YAML off byte 0 and it would never parse as frontmatter. The parsed values are written via app.fileManager.processFrontMatter in insertNewFile only (after vault.create, before openLinkText) so the real ---...--- lands above the embed; cursor / append ignore InsertParams.properties. A present block is always stripped from the body (even when malformed YAML triggers the tolerant line-based fallback); a missing block leaves the whole output as the body. See Note properties.
  • noteTitle is filename-only — never a frontmatter property. The reserved noteTitle key (titleFromContent) shares the one leading ```yaml block with noteProperties, but extractFromBlock deliberately keeps it OUT of the property allowed set and returns it on CleanupResult.title. Do NOT "fix" the extractor to also write it into properties/frontmatter; it exists to name the file ({{title}} token or whole-name replacement in insertNewFile). It is the model's own generated string, independent of any title noteProperty (e.g. Book log's title property and its filename title are separate axes and need not match). Caveat: resolveNewFilePath collision detection is case-sensitive (getAbstractFileByPath), so on case-insensitive filesystems two titles differing only by case can still collide at vault.create; pre-existing, just likelier with content-derived names. See Note title.
  • Frontmatter parsing uses parseYaml from Obsidian, not the metadata cache. The metadata cache is async and may not be populated for newly created files; reading content via app.vault.read(file), splitting off the leading ---...--- block, and parsing it with parseYaml is synchronous-enough and works immediately after app.vault.create.
  • New-file collisions are resolved by insert.ts, not the caller. GlobalSettings.newFileCollisionMode is 'auto' (silently iterate name-1.md, name-2.md, ...) or 'prompt' (open RenamePromptModal defaulted to the next free path; Cancel throws Insert canceled: file already exists.). Threaded through InsertParams.collisionMode from pipeline.ts. The path search uses app.vault.getAbstractFileByPath and caps at 1000 iterations. nextFreePath is local to src/insert.ts; the equivalent deCollide in src/audio-persist.ts is intentionally not shared — audio always auto-iterates regardless of the setting (the file is a side-effect users keep; the new-note path is the target the user named).
  • Destination override does not mutate the template object. src/ui/modal.ts renders a per-invocation Destination control (insertMode + conditional newFile fields) and threads the result through PipelineParams.destinationOverride. src/pipeline.ts shallow-merges the override onto a copy of the template via applyDestinationOverride before calling insertOutput; the cached template and the file on disk remain untouched. The override is ephemeral: it resets when the modal closes and when the template selector changes. Not exposed in Quick Record, runTextPipeline, or runAudioFilePipeline (no UI surface). The UI is a collapsible <details> whose <summary> reads "Destination: Default (<description>)" (no override) or "Destination: Custom (<description>)" (override set, forced open); expand state is tracked on ReWriteModal.destinationExpanded so it survives the full-container re-renders that fire when the inner insertMode dropdown changes. describeDestination(mode, folder, name) formats the description (e.g. New file: ReWrite Notes/{{date}}-note).

Cleanup-prompt inputs

  • Wake-name extraction is regex-only, off by default. src/wake-name.ts requires <assistantName>, (vocative comma) to fire, captures up to the next sentence terminator or next name occurrence, and drops filler matches ("never mind", "scratch that", short tokens). It runs on ALL pipeline sources, including paste and text. The extracted instructions are appended to the LLM system prompt as a numbered ## Ad-hoc instructions block, prefaced by plugin.assistantPrompt (loaded from GlobalSettings.assistantPromptPath); when the file is missing or empty, DEFAULT_ASSISTANT_PROMPT from src/assistant-prompt.ts is used as the fallback so behavior is identical to the previous hardcoded textarea. Both the OpenAI and Anthropic adapters route this into the API's system slot. Whisper transcription homophones ("Scribner", "Scrivner") are not fuzzy-matched in v1; document the limitation if a user reports misses.
  • Known nouns frontmatter is NOT sent to the LLM. The vault file at GlobalSettings.knownNounsPath uses YAML frontmatter purely for human-readable guidance (token-cost warning, format hint). Only the body lines are parsed via loadKnownNounsFromFile and injected by buildKnownNounsSystemPromptSection. If a future change opts frontmatter in, it should be a per-vault opt-in setting, not the default. The body parser treats # lines and blank lines as ignored; an entry can be either bare canonical (Anthropic) or canonical + misheard alternates (Hoxhunt: hawks hunt, hocks hunt).

Recording and capture

  • Audio persistence runs before transcription, not after, so the user keeps the recording even if transcription fails. src/audio-persist.ts catches its own errors and emits a Notice; the pipeline always continues to the transcribe stage even when persistence throws. Cancel paths in src/ui/modal.ts and src/ui/quick-record.ts call recorder.cancel() before runPipeline(), so no orphan file is written on cancel. The ![[<path>]] embed is prepended to the cleaned output unconditionally when an audio file was saved, regardless of insert mode. The reprocess flow (src/ui/audio-source.ts) skips persistence by passing sourcePath on the audio source variant; the embed prepend still runs, reusing the existing vault path so reprocessed output links back to the original file.
  • A screen wake lock is held for the duration of active recording. Android (and iOS) suspend the Obsidian Capacitor WebView when the screen sleeps, which kills MediaRecorder capture mid-recording. src/recorder.ts requests navigator.wakeLock.request('screen') in start() (and re-acquires in resume()), releases it in pause(), and tears it down via stopWakeLock() from the shared releaseStream() (so both stop() and cancel() cover it). The OS auto-releases a screen wake lock whenever the document becomes hidden, so a visibilitychange listener (registered in startWakeLock, removed in stopWakeLock) re-requests on the next visible transition while state === 'recording'. The acquire is best-effort and degrades silently: where the Wake Lock API is absent (older WebView, desktop builds, insecure context) or denied (NotAllowedError), recording proceeds without it. The API is reached through a narrow local WakeLockLike / WakeLockSentinelLike interface + getWakeLock() cast (it is not in every TS DOM lib version), mirroring the hotkeyManager pattern. Cost: the screen stays lit while recording (a partial CPU-only wake lock would need native code Obsidian doesn't expose to plugins). A stop/cancel that races ahead of the async request('screen') is handled by re-checking state === 'recording' before retaining the sentinel.
  • Live silence detection is a Web Audio tap on the recording stream. src/recorder.ts builds an AnalyserNode off the mic MediaStream in start() (no connection to destination, so no monitoring feedback) and samples peak amplitude every 100 ms via a window.setInterval. It exposes getInputLevel() (0..1 peak), hasDetectedSound(), and getSilentMs() (ms of continuous silence; returns 0 while paused / stopped or when the analyser could not be created, so the UI never warns when there is nothing to listen to). resume() resets the silence baseline so the paused gap is not counted. Both recording UIs poll getSilentMs() in their existing 250 ms timer loop and show a "No audio detected" warning past SILENCE_WARNING_MS (3 s): the modal's Record tab (.rewrite-silence-warning, src/ui/modal.ts) and the Quick Record floater (.rewrite-quick-silence-warning below the controls row, src/ui/quick-record.ts setSilenceWarning, hidden while busy). The monitor is torn down in releaseStream() (called by stop()/cancel()); any setup failure (no AudioContext, e.g. a stripped environment) degrades to "monitoring unavailable" and the recording proceeds without a warning. The threshold SILENCE_LEVEL_THRESHOLD = 0.015 clears even quiet speech but flags a muted or dead mic.

Quick Record UI

  • Quick Record uses a custom floating div, not a Notice. Obsidian Notice does not support real interactive buttons. The floater is a position: fixed div on document.body, owned by QuickRecordController, with cancel() wired into onunload.
  • Quick Record floater holds its own popover. The floater grew a third button between the timer and Stop that opens a popover-style template list (src/ui/quick-record.ts). The popover is a child of the floater div, listens for outside-click via a capture-phase document listener and Escape via document keydown, and cleans up both listeners on dismiss. The popover dismisses on selection, Escape, outside click, and when setBusy runs (the pipeline is in flight). Selecting a template updates controller.template but does NOT update lastUsedTemplateId; that only happens after a successful completion, matching pre-popover behavior. The floater also shows an optional stop-hotkey hint span (.rewrite-quick-stop-hint) before the Stop button when startQuickRecord is passed a commandId whose binding resolves (see next Gotcha).
  • The stop-hotkey hint reads Obsidian's internal app.hotkeyManager. formatCommandHotkey(app, commandId) in src/ui/quick-record.ts prefers getHotkeys(id) (user binding) over getDefaultHotkeys(id) (plugin default), formats it platform-aware via Platform.isMacOS, and returns null when unbound (the floater then shows only the Stop button, no placeholder text). The manager is not in the public obsidian typings, so it is reached through a narrow local HotkeyManager interface + as unknown as cast rather than disabling a lint rule. The hint is computed fresh each time a recording starts (commandId is ${manifest.id}:quick-record or :quick-record-fixed), so rebinding takes effect on the next recording. If a future feature needs the same lookup, reuse this helper.

Settings tab UI

  • setHeading() instead of manual <h2> inside settings tabs. obsidianmd/settings-tab/no-manual-html-headings forbids manual headings. Same applies anywhere else inside a settings tab that needs a section header. In src/settings/tab.ts, section headings go through the sectionHeading(parent, name, icon) helper, which builds the setHeading() Setting and prepends a Lucide icon (via setIcon) to its nameEl styled by .rewrite-heading-icon. It returns the Setting so callers that attach a status badge (profile, shared core) still reach nameEl. Add new headings via this helper, not a bare new Setting(...).setHeading(), so they keep an icon.
  • window.confirm is banned by ESLint's no-alert. If a future phase needs an in-vault confirmation prompt, add a small Modal subclass rather than reaching for window.confirm.
  • Sentence-case lint covers brand and acronym lists in eslint.config.mts. Adding a new provider, model family, or product name means adding it to REWRITE_BRANDS (or REWRITE_ACRONYMS for things like LLM). Dropdown option labels also pass through the rule; in src/settings/tab.ts and src/ui/setup-card.ts, labels are iterated via opt.label (member access) to dodge the literal-string check.
  • Provider option arrays appear in both setup-card.ts and tab.ts. Intentionally duplicated rather than extracted, per the "don't refactor beyond what the task requires" rule. If the lists drift, fix the user-visible inconsistency, not the duplication.
  • Settings tab re-renders the entire container on dropdown changes that toggle conditional fields (provider, insertMode, activeProfileOverride). Text fields call saveSettings() on change but do not redraw, so focus is preserved while typing. Preserve this pattern when adding new conditional fields. (Obsidian's newer review linter flags the display() / this.display() redraw pattern as deprecated in favor of getSettingDefinitions, a declarative 1.13.0+ API that is not in our bundled typings. Migrating would force minAppVersion to 1.13.0+ and a full settings rewrite, so it is deliberately deferred; the redraw pattern still works.)
  • Profile sections wrap their settings in .rewrite-profile-section. src/settings/tab.ts renderProfile() creates a wrapper div per profile rather than rendering settings as direct children of containerEl. The active-on-this-device profile (per detectActiveProfileKind) gets is-active-profile (accent left border) and a .rewrite-profile-active-badge span inside the heading's nameEl. The inactive profile's body is wrapped in a <details class="rewrite-profile-collapsed"> whose expand state lives on ReWriteSettingTab.inactiveProfileExpanded so it survives the full-container redraws triggered by dropdowns. New per-profile settings must take body as their parent (the wrapper or the <details>), not the original parent arg, or they will render outside the section's visual frame.
  • Async settings-tab buttons are concurrency-guarded. Handlers that run an async op then this.display() (Populate buttons, whisper Start/Stop/probe, Lock) are wrapped in runGuardedButton(b, fn) in src/settings/tab.ts, which disables the button for the duration so a rapid double-click cannot launch the work (and its full-container re-render) twice. The encryption-mode dropdown uses a modeChangeInFlight flag for the same reason. Wrap new async-then-display buttons the same way. Each handler keeps its own try/catch; observability console.error('ReWrite: <context>', e) sits alongside the user-facing Notice in those catches (and in the swallowed catches in src/main.ts).

Secrets and encryption

See docs/SECRETS.md for the secrets/encryption gotchas (secretStorage probe, saveManyKeys no-op when locked, zxcvbn lazy-load, .nosync suffix).

Whisper host (desktop)

See docs/WHISPER_HOST.md for the whisper-host gotchas (lazy Node require, splitArgs, spawned/adopted/external ownership, PID sidecar, stop semantics, onunload fire-and-forget, status-bar poll).

Mobile

  • Mobile keyboard avoidance is CSS-only: pin our popups to the top. Obsidian mobile (Capacitor) overlays the soft keyboard on top of the WebView without resizing the layout or visual viewport, so there is no reliable JS signal (visualViewport does not shrink, the resize event does not fire) to react to. The earlier JS helper (installMobileKeyboardScrollFix, which read visualViewport and shrank .modal-container) was a confirmed no-op on the failing cases and has been removed. The fix lives entirely in styles.css: under .is-mobile, our modal classes (.rewrite-modal, which covers the main + passphrase modals, and .rewrite-rename-modal) get align-self: flex-start; margin-top: 8px; margin-bottom: auto; max-height: calc(100% - 16px), pinning the popup to the top of the flex container that centers modals. The keyboard opens from the bottom, so a top-anchored popup and its near-top input fields stay visible above it. Scoped to our classes so core Obsidian modals are untouched. The settings tab (a tall scrollable surface) was never affected and needs no rule: Chromium's native keyboard-aware focus-scroll handles it. If you add a new popup with a text field, give it one of these classes (or add its class to the selector) rather than reaching for a JS keyboard helper. Top-anchoring alone is not enough when something pushes the focused element low within a tall popup, so three companion tweaks keep the relevant element high: (a) .is-mobile .rewrite-modal .modal-content gets padding-top: 8px and .is-mobile .rewrite-modal h2 gets margin-top: 0 to reclaim the empty band Obsidian leaves above the title; (b) the Paste textarea renders at rows = 4 on mobile (vs 10 on desktop, set in src/ui/modal.ts) with the desktop 160px min-height floor dropped to 80px under .is-mobile, so its submit button stays above the keyboard; (c) the change-passphrase tips block is a <details> (src/ui/passphrase-modal.ts renderPassphraseTips) expanded by default on every platform (opt-out security guidance), but on mobile it auto-collapses (collapseTipsOnMobile) when a passphrase field receives focus, so it is seen on open yet stops pushing the fields into the keyboard once the user starts typing. The first field's autofocus is disabled on mobile (autofocus = !Platform.isMobile) so the auto-collapse fires on the user's tap rather than a premature programmatic focus.

Local install for testing

Build, then place/symlink main.js, manifest.json, and styles.css into <Vault>/.obsidian/plugins/rewrite-voice-notes/ and reload Obsidian (Settings, Community plugins).

Never use em dashes in your own writing.

Do not use the em dash character in any prose, lists, code comments, or analysis you produce. Use commas, periods, parentheses, semicolons, or colons instead, whichever fits the sentence best. Exception: when directly quoting a source inside quotation marks, preserve em dashes exactly as they appear. Do not silently edit quoted text.

Why: Consistent formatting preference for original writing, while keeping quoted material faithful to the source.