Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): single-block template frontmatter (#2036)
tim-inkeep2dd55b4afbb1
diff --git a/.changeset/template-single-frontmatter-block.md b/.changeset/template-single-frontmatter-block.mdnew file mode 100644index 000000000..8667f0d20--- /dev/null+++ b/.changeset/template-single-frontmatter-block.md@@ -0,0 +1,11 @@+---+"@inkeep/open-knowledge": patch+---++Fix starter-pack templates showing their frontmatter as raw text in the editor.++Template files stored two stacked frontmatter blocks: the template's own title and description, then the frontmatter a new document receives. Editors only recognize the first block, so the second one leaked into the document body and showed up as raw `---` fences and `key: value` lines instead of editable properties.++Templates now use a single frontmatter block, with the template's identity under a reserved `template:` key and the new-document defaults as top-level keys. Creating a document from a template still produces the same frontmatter, with `{{date}}` and `{{user}}` substituted as before — including from an agent via `write({ document: { template } })`. Templates already on disk keep working and convert to the single-block shape the next time they are saved, so there is no migration step. This also fixes one starter template whose description contained an unquoted colon that broke YAML parsing, and adds a guard test so that class of bug cannot ship again.++The template edit dialog is reworked to match: the title field is labeled **Title**, a dedicated **Type** field carries the Open Knowledge Format `type`, and a **Default properties** editor exposes the rest of the new-document frontmatter as editable key/value rows — so the starter content is now plain markdown instead of a raw frontmatter block. Every document created from any starter template carries a semantic `type` plus a one-line `description` summarizing what that kind of document holds, which you then specialize per document.diff --git a/docs/content/advanced/folders-and-templates.mdx b/docs/content/advanced/folders-and-templates.mdxindex a32254d0b..e76721239 100644--- a/docs/content/advanced/folders-and-templates.mdx+++ b/docs/content/advanced/folders-and-templates.mdx@@ -55,8 +55,9 @@ A template body may use two placeholders, filled in automatically when a documen```md title=".ok/templates/standup.md"----title: Daily standup-description: Standup notes scaffold+template:+ title: Daily standup+ description: Standup notes scaffold---# Standup — {{date}}@@ -74,14 +75,17 @@ These two are the only placeholders Open Knowledge fills in. Any other `{{...}}`### Give new documents their own properties-The standup template above produces documents with just a body: a heading and some sections, no [properties](#properties-in-one-minute). This is also how you give every new doc in a folder the same **starting properties** (a `status`, a date, a `tags` array): add a second properties block (the same `---`-fenced frontmatter) at the very top of the **Starter content**:+The standup template above produces documents with just a body. To give every new doc in a folder the same **starting properties** (a `type`, a `status`, a date, a `tags` array), you don't hand-edit anything — the **Edit template** dialog has a **Type** field and a **Default properties** section (key/value rows) for exactly this. The starter content stays pure markdown.++On disk it all lives in one frontmatter block: the template's own identity sits under a reserved `template:` key, and every other top-level key is a property new documents start with:```md title=".ok/templates/daily.md"----title: Daily entry-description: Daily journal entry.--------+template:+ title: Daily entry+ description: Daily journal entry.+type: daily-note+description: Daily journal entry capturing intentions, notes, and reflections.title: {{date}}status: drafttags: [daily]@@ -92,7 +96,9 @@ tags: [daily](...)```-The first block is the template's own info: the name and description shown in the picker. The second block becomes the new document's own properties, written as real bytes into the file. Open Knowledge removes only the first block when a document is created, so everything else in the Starter content (including a properties block at the top) becomes the new document exactly as written. Because these are the new doc's *own* properties, the doc owns them outright: editing one doc never touches another.+The `template:` block is the template's own info (the name and description shown in the picker); Open Knowledge strips it when a document is created. Every other key — `type`, `description`, `title`, `status`, `tags` above — becomes the new document's own properties, written as real bytes into the file. `description` gives each new document a starting one-line summary; edit it per document. Because these are the new doc's *own* properties, the doc owns them outright: editing one doc never touches another.++(Older templates that used two stacked frontmatter blocks still work — Open Knowledge reads them and rewrites them to the single-block form the next time they're saved.)### Edit and deletediff --git a/packages/app/src/components/TemplateForm.dom.test.tsx b/packages/app/src/components/TemplateForm.dom.test.tsxindex 9ae1e49fe..1a8d764fc 100644--- a/packages/app/src/components/TemplateForm.dom.test.tsx+++ b/packages/app/src/components/TemplateForm.dom.test.tsx@@ -1,7 +1,66 @@import { afterEach, describe, expect, test } from 'bun:test';import { cleanup, render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import { slugifyTemplateName, TemplateFormFields, useTemplateForm } from './TemplateForm';+import {+ composeDocBody,+ parseDocBody,+ slugifyTemplateName,+ TemplateFormFields,+ useTemplateForm,+} from './TemplateForm';++const RESEARCH_BODY = `---\ntype: research-note\nstatus: provisional\nsources: []\ncreated: {{date}}\ntags: [research, provisional]\n---\n\n## Question\n`;++describe('parseDocBody / composeDocBody', () => {+ test('splits type, property rows, and markdown', () => {+ const parsed = parseDocBody(RESEARCH_BODY);+ expect(parsed.type).toBe('research-note');+ expect(parsed.markdown).toContain('## Question');+ expect(parsed.markdown).not.toContain('status:'); // frontmatter lifted out+ const byKey = Object.fromEntries(parsed.properties.map((p) => [p.key, p.value]));+ expect(byKey.status).toBe('provisional');+ expect(byKey.sources).toBe('[]'); // value shape preserved verbatim+ expect(byKey.created).toBe('{{date}}'); // token preserved+ expect(byKey.tags).toBe('[research, provisional]');+ expect(parsed.properties.some((p) => p.key === 'type')).toBe(false);+ });++ test('round-trips parse -> compose with type first and tokens intact', () => {+ const parsed = parseDocBody(RESEARCH_BODY);+ const composed = composeDocBody({+ type: parsed.type,+ properties: parsed.properties,+ markdown: parsed.markdown,+ });+ expect(composed).toContain('created: {{date}}');+ expect(composed.indexOf('type: research-note')).toBeLessThan(composed.indexOf('status:'));+ expect(composed).toContain('## Question');+ const reparsed = parseDocBody(composed);+ expect(reparsed.type).toBe('research-note');+ expect(reparsed.properties.map((p) => p.key)).toEqual(['status', 'sources', 'created', 'tags']);+ });++ test('no type and no rows → markdown only (no empty frontmatter block)', () => {+ expect(composeDocBody({ type: '', properties: [], markdown: '## Body\n' })).toBe('## Body\n');+ });++ test('empty-key rows are dropped on compose', () => {+ const composed = composeDocBody({+ type: 'note',+ properties: [{ id: 'a', key: '', value: 'ignored' }],+ markdown: '# B',+ });+ expect(composed).toContain('type: note');+ expect(composed).not.toContain('ignored');+ });++ test('plain markdown template parses to empty doc-frontmatter', () => {+ const parsed = parseDocBody('# Just markdown\n');+ expect(parsed.type).toBe('');+ expect(parsed.properties).toEqual([]);+ expect(parsed.markdown).toBe('# Just markdown\n');+ });+});describe('slugifyTemplateName', () => {test('lowercases and hyphenates a human name', () => {@@ -51,9 +110,68 @@ describe('TemplateFormFields — create mode', () => {test('shows the required-name error only after the field is blurred empty', async () => {const user = userEvent.setup();render(<CreateFormHarness />);- expect(screen.queryByText('Enter a name for this template.')).toBeNull();+ expect(screen.queryByText('Enter a title for this template.')).toBeNull();await user.click(screen.getByTestId('template-name-input'));await user.tab();- expect(screen.getByText('Enter a name for this template.')).toBeDefined();+ expect(screen.getByText('Enter a title for this template.')).toBeDefined();+ });+});++test('composeDocBody drops a property row also named `type` (no duplicate key)', () => {+ const composed = composeDocBody({+ type: 'research-note',+ properties: [{ id: 'a', key: 'type', value: 'should-be-dropped' }],+ markdown: '# B',+ });+ expect((composed.match(/type:/g) ?? []).length).toBe(1);+ expect(composed).toContain('type: research-note');+ expect(composed).not.toContain('should-be-dropped');+});++function EditFormHarness({ body }: { body: string }) {+ const form = useTemplateForm({+ mode: 'edit',+ folderPath: 'notes',+ scope: 'local',+ initial: { name: 'tpl', title: 'T', description: '', body },+ onCommitted: () => {},+ });+ return <TemplateFormFields form={form} />;+}++describe('TemplateDefaultProperties — interactions', () => {+ afterEach(() => {+ cleanup();+ });++ test('seeds one row per existing doc-frontmatter property', () => {+ render(<EditFormHarness body={'---\nstatus: provisional\ntags: [a]\n---\n\n# B'} />);+ const keyInputs = screen.getAllByLabelText('Property name') as HTMLInputElement[];+ expect(keyInputs.map((i) => i.value).sort()).toEqual(['status', 'tags']);+ });++ test('Add property appends an empty row', async () => {+ const user = userEvent.setup();+ render(<CreateFormHarness />);+ expect(screen.queryAllByLabelText('Property name')).toHaveLength(0);+ await user.click(screen.getByRole('button', { name: 'Add property' }));+ expect(screen.getAllByLabelText('Property name')).toHaveLength(1);+ });++ test('Remove property deletes its row', async () => {+ const user = userEvent.setup();+ render(<EditFormHarness body={'---\nstatus: provisional\n---\n\n# B'} />);+ expect(screen.getAllByLabelText('Property name')).toHaveLength(1);+ await user.click(screen.getByRole('button', { name: 'Remove property' }));+ expect(screen.queryAllByLabelText('Property name')).toHaveLength(0);+ });++ test('typing into a property value updates the input', async () => {+ const user = userEvent.setup();+ render(<EditFormHarness body={'---\nstatus: provisional\n---\n\n# B'} />);+ const valueInput = screen.getByLabelText('Property value') as HTMLInputElement;+ await user.clear(valueInput);+ await user.type(valueInput, 'done');+ expect(valueInput.value).toBe('done');});});diff --git a/packages/app/src/components/TemplateForm.tsx b/packages/app/src/components/TemplateForm.tsxindex aab5db02e..da760a84d 100644--- a/packages/app/src/components/TemplateForm.tsx+++ b/packages/app/src/components/TemplateForm.tsx@@ -1,5 +1,7 @@+import { stripFrontmatter, unwrapFrontmatterFences } from '@inkeep/open-knowledge-core';import { t } from '@lingui/core/macro';import { Trans, useLingui } from '@lingui/react/macro';+import { X } from 'lucide-react';import { useId, useState } from 'react';import { toast } from 'sonner';import { TemplateBodyTextarea } from '@/components/TemplateBody';@@ -30,6 +32,72 @@ function buildTemplateFrontmatter(args: { title: string; description: string }):return out;}+export interface PropRow {+ id: string;+ key: string;+ value: string;+}++let propRowSeq = 0;+function nextRowId(): string {+ propRowSeq += 1;+ return `prop-${propRowSeq}`;+}++export function parseDocBody(rawBody: string): {+ type: string;+ properties: PropRow[];+ markdown: string;+} {+ const { frontmatter, body } = stripFrontmatter(rawBody);+ if (frontmatter === '') return { type: '', properties: [], markdown: rawBody };++ const parsed: { key: string; value: string }[] = [];+ for (const line of unwrapFrontmatterFences(frontmatter).split('\n')) {+ if (line.trim() === '') continue;+ const colon = line.indexOf(':');+ if ((/^\s/.test(line) || colon === -1) && parsed.length > 0) {+ const prev = parsed[parsed.length - 1];+ if (prev) prev.value += `\n${line}`;+ continue;+ }+ if (colon === -1) continue;+ parsed.push({+ key: line.slice(0, colon).trim(),+ value: line.slice(colon + 1).replace(/^ /, ''),+ });+ }++ let type = '';+ const properties: PropRow[] = [];+ for (const row of parsed) {+ if (row.key === 'type' && type === '') {+ type = row.value.trim();+ continue;+ }+ properties.push({ id: nextRowId(), key: row.key, value: row.value });+ }+ return { type, properties, markdown: body };+}++export function composeDocBody(args: {+ type: string;+ properties: PropRow[];+ markdown: string;+}): string {+ const lines: string[] = [];+ const type = args.type.trim();+ if (type) lines.push(`type: ${type}`);+ for (const row of args.properties) {+ const key = row.key.trim();+ if (key === '' || key === 'type') continue;+ lines.push(row.value === '' ? `${key}:` : `${key}: ${row.value}`);+ }+ if (lines.length === 0) return args.markdown.replace(/^\n+/, '');+ const md = args.markdown.startsWith('\n') ? args.markdown : `\n${args.markdown}`;+ return `---\n${lines.join('\n')}\n---\n${md}`;+}+interface TemplateFormInitial {name: string;title: string;@@ -51,10 +119,16 @@ export interface TemplateFormState {title: string;slug: string;description: string;+ type: string;+ properties: PropRow[];body: string;setTitle: (next: string) => void;setSlug: (next: string) => void;setDescription: (next: string) => void;+ setType: (next: string) => void;+ setProperty: (id: string, patch: Partial<Pick<PropRow, 'key' | 'value'>>) => void;+ addProperty: () => void;+ removeProperty: (id: string) => void;setBody: (next: string) => void;markTitleTouched: () => void;titleTouched: boolean;@@ -80,11 +154,24 @@ export function useTemplateForm({const [title, setTitleState] = useState(initial.title);const [slug, setSlugState] = useState(initial.name);const [description, setDescription] = useState(initial.description);- const [body, setBody] = useState(initial.body);+ const initialDoc = useState(() => parseDocBody(initial.body))[0];+ const [type, setType] = useState(initialDoc.type);+ const [properties, setProperties] = useState<PropRow[]>(initialDoc.properties);+ const [body, setBody] = useState(initialDoc.markdown);const [saving, setSaving] = useState(false);const [slugManuallyEdited, setSlugManuallyEdited] = useState(false);const [titleTouched, setTitleTouched] = useState(false);+ function setProperty(id: string, patch: Partial<Pick<PropRow, 'key' | 'value'>>) {+ setProperties((rows) => rows.map((row) => (row.id === id ? { ...row, ...patch } : row)));+ }+ function addProperty() {+ setProperties((rows) => [...rows, { id: nextRowId(), key: '', value: '' }]);+ }+ function removeProperty(id: string) {+ setProperties((rows) => rows.filter((row) => row.id !== id));+ }+function setTitle(next: string) {setTitleState(next);if (mode === 'create' && !slugManuallyEdited) {@@ -115,6 +202,7 @@ export function useTemplateForm({}setSaving(true);const frontmatter = buildTemplateFrontmatter({ title, description });+ const composedBody = composeDocBody({ type, properties, markdown: body });const renaming = canRename && trimmedSlug !== initial.name;const result = renaming? await moveTemplate({@@ -123,13 +211,13 @@ export function useTemplateForm({toFolder: folderPath,toName: trimmedSlug,frontmatter,- body,+ body: composedBody,}): await saveTemplate({folder: folderPath,name: mode === 'create' ? trimmedSlug : initial.name,frontmatter,- body,+ body: composedBody,});setSaving(false);if (!result.ok) {@@ -158,10 +246,16 @@ export function useTemplateForm({title,slug,description,+ type,+ properties,body,setTitle,setSlug,setDescription,+ setType,+ setProperty,+ addProperty,+ removeProperty,setBody,markTitleTouched: () => setTitleTouched(true),titleTouched,@@ -187,6 +281,7 @@ export function TemplateFormFields({const { t } = useLingui();const nameId = useId();const descriptionId = useId();+ const typeId = useId();const showNameError = form.titleTouched && form.titleInvalid;const { fixedName } = form;@@ -194,7 +289,7 @@ export function TemplateFormFields({<FieldGroup><Field><FieldLabel htmlFor={nameId}>- <Trans>Name</Trans>+ <Trans>Title</Trans><span className="text-destructive">*</span></FieldLabel><Input@@ -209,7 +304,7 @@ export function TemplateFormFields({/>{showNameError ? (<FieldError>- <Trans>Enter a name for this template.</Trans>+ <Trans>Enter a title for this template.</Trans></FieldError>) : null}</Field>@@ -244,6 +339,30 @@ export function TemplateFormFields({rows={2}/></Field>+ <Field>+ <FieldLabel htmlFor={typeId}>+ <Trans>Type</Trans>+ </FieldLabel>+ <Input+ id={typeId}+ value={form.type}+ onChange={(e) => form.setType(e.target.value)}+ placeholder={t`research-note`}+ disabled={form.isSaving}+ spellCheck={false}+ autoCapitalize="off"+ autoCorrect="off"+ className="font-mono"+ />+ <FieldDescription>+ <Trans>+ The <code className="font-mono">type</code> every document created from this template+ gets (e.g. <code className="font-mono">research-note</code>). Keeps new docs Open+ Knowledge Format–conformant.+ </Trans>+ </FieldDescription>+ </Field>+ <TemplateDefaultProperties form={form} /><TemplateBodyTextareavalue={form.body}onChange={form.setBody}@@ -254,6 +373,72 @@ export function TemplateFormFields({);}+function TemplateDefaultProperties({ form }: { form: TemplateFormState }) {+ const { t } = useLingui();+ return (+ <Field>+ <FieldLabel>+ <Trans>Default properties</Trans>+ </FieldLabel>+ <FieldDescription>+ <Trans>+ Frontmatter every document created from this template starts with. Values are YAML — a+ list is <code className="font-mono">[a, b]</code>;{' '}+ <code className="font-mono">{'{{date}}'}</code> fills in on create.+ </Trans>+ </FieldDescription>+ {form.properties.length > 0 ? (+ <div className="flex flex-col gap-2">+ {form.properties.map((row) => (+ <div key={row.id} className="flex items-center gap-2">+ <Input+ aria-label={t`Property name`}+ value={row.key}+ onChange={(e) => form.setProperty(row.id, { key: e.target.value })}+ placeholder={t`status`}+ disabled={form.isSaving}+ spellCheck={false}+ autoCapitalize="off"+ autoCorrect="off"+ className="font-mono w-1/3"+ />+ <Input+ aria-label={t`Property value`}+ value={row.value}+ onChange={(e) => form.setProperty(row.id, { value: e.target.value })}+ placeholder={t`provisional`}+ disabled={form.isSaving}+ spellCheck={false}+ className="font-mono flex-1"+ />+ <Button+ type="button"+ variant="ghost"+ size="icon"+ aria-label={t`Remove property`}+ onClick={() => form.removeProperty(row.id)}+ disabled={form.isSaving}+ >+ <X aria-hidden="true" />+ </Button>+ </div>+ ))}+ </div>+ ) : null}+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="self-start"+ onClick={form.addProperty}+ disabled={form.isSaving}+ >+ <Trans>Add property</Trans>+ </Button>+ </Field>+ );+}+function DerivedFilename({ form }: { form: TemplateFormState }) {const { t } = useLingui();const slugId = useId();diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 3ea35f4e4..257f99092 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -18,6 +18,7 @@"-QCLWk": ["Templates available"],"-Qw-1t": ["GitHub authentication failed. Try signing in again."],"-RXIMO": ["Couldn't read the selection — please try again."],+ "-WFFG2": ["Default properties"],"-YV1Uo": ["Pattern ", ["patternNumber"]],"-g6KIS": ["Unrecognized link"],"-gdcIo": ["Auto-sync is on — your commits push and remote changes pull on intervals."],@@ -30,13 +31,13 @@"-wePNM": ["Search matches file names, paths, and folders. Open a file to search its body (⌘F)."],+ "-zy2Nq": ["Type"],"0-31GV": ["Removing"],"02P3hL": ["Upload failed: ", ["message"]],"04RA0-": ["Failed to enable sync — ", ["detail"]],"06SZfb": ["Template \"", ["trimmedTitle"], "\" created"],"07gHun": ["You don't have access to this private repo. Sign in with an account that does."],"07q4Qk": ["File sidebar"],- "092Wah": ["Enter a name for this template."],"09Tv5j": ["Reconnecting…"],"0BB9ID": ["No headings yet."],"0Gd0NU": ["Shared"],@@ -408,6 +409,7 @@],"Aif3E7": ["Enable semantic search"],"Am78jY": ["Drag ", ["keyName"], " to reorder"],+ "Aq-O0x": ["status"],"AqnqMJ": ["API key set"],"ArBWJf": ["Undo last edit"],"B11p-O": ["Edit markdown link"],@@ -998,6 +1000,7 @@"VZGh8G": ["Fold, unfold, fold all, or unfold all source ranges."],"VZSBXL": ["Semantic ranking activates the first time an agent runs a search."],"V_6bJ4": ["Terminal settings not loaded yet — try again in a moment."],+ "V_wltx": ["Enter a title for this template."],"VbqhBI": ["Already at ", ["assetContentPath"], " — reusing."],"VcqWBy": ["Upload may have succeeded but the sidebar is out of date — refresh to resync"],"VdXv4D": ["Clone from GitHub"],@@ -1405,6 +1408,7 @@"iH8pgl": ["Back"],"iHAJDj": ["Resolving default location"],"iKSP5j": ["Word wrap"],+ "iKZkk1": ["Property value"],"iMkWoF": ["Turn on"],"iNFKkm": ["No diff."],"iOHg1t": ["Open embedded URL in new tab"],@@ -1419,6 +1423,9 @@"ig5vUe": ["Failed to load file"],"iilQXA": ["Folder duplicated"],"ijLc3m": ["Bullet list"],+ "ipn17C": [+ "The <0>type</0> every document created from this template gets (e.g. <1>research-note</1>). Keeps new docs Open Knowledge Format–conformant."+ ],"iqIDv4": ["Sync status unavailable"],"iqugog": ["Initialize failed: ", ["errorDetail"]],"irFGwu": ["Template list"],@@ -1429,6 +1436,7 @@"This project's running server doesn't support live editing. Restart Open Knowledge to fix."],"j9Vqvc": ["inherited"],+ "jEZ6Lf": ["provisional"],"jEdF24": ["Missing page: ", ["linkTitle"], ". Click to create."],"jGJy-9": ["Downloads ", ["shareOwner"], "/", ["shareRepo"], " from GitHub."],"jKd3AP": ["Could not enable the terminal: ", ["0"]],@@ -1592,6 +1600,7 @@"o5gfs1": ["This setting is per-machine and isn't shared with collaborators. It needs an API key set with <0>ok embeddings set-key</0>."],+ "o9CrsQ": ["research-note"],"oAFVKX": ["Failed to update the project sync default — ", ["detail"]],"oBXkm2": ["Delete code block"],"oCZkaG": ["Copy path"],@@ -1687,6 +1696,7 @@"rBc32v": ["Couldn't reach the embeddings provider — press ↵ to retry"],"rFw02Q": ["Uploading ", ["keyName"]],"rJVoVX": ["Source find results"],+ "rNifQd": ["Remove property"],"rQAQus": ["Couldn't save template: ", ["error"]],"rQRrkB": ["yesterday"],"rVgSRB": ["Collapse ", ["docName"]],@@ -1964,6 +1974,11 @@"zkz0Fg": ["Set up syncing"],"zlErBl": ["Page headings error response did not match RFC 9457"],"zo3Dl7": ["Toggle thumbnails"],+ "zrP8HX": [+ "Frontmatter every document created from this template starts with. Values are YAML — a list is <0>[a, b]</0>; <1>{",+ ["date"],+ "}</1> fills in on create."+ ],"ztKII6": ["Failed to add item"],"zwBp5t": ["Private"]}diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 55be63a63..8b2f4a861 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -554,6 +554,7 @@ msgid "Add properties"msgstr "Add properties"#: src/components/PropertyPanel.tsx+#: src/components/TemplateForm.tsxmsgid "Add property"msgstr "Add property"@@ -1747,6 +1748,10 @@ msgstr "Customize how the editor looks and behaves."msgid "Date"msgstr "Date"+#: src/components/TemplateForm.tsx+msgid "Default properties"+msgstr "Default properties"+#: src/components/DeleteConfirmationDialog.tsx#: src/components/TemplateRow.tsx#: src/editor/extensions/JsxComponentView.tsx@@ -2174,10 +2179,6 @@ msgstr "Eng specs"msgid "Enter a folder name (e.g. brain)."msgstr "Enter a folder name (e.g. brain)."-#: src/components/TemplateForm.tsx-msgid "Enter a name for this template."-msgstr "Enter a name for this template."-#: src/components/CreateProjectDialog.tsxmsgid "Enter a project name"msgstr "Enter a project name"@@ -2186,6 +2187,10 @@ msgstr "Enter a project name"msgid "Enter a repository URL or owner/repo"msgstr "Enter a repository URL or owner/repo"+#: src/components/TemplateForm.tsx+msgid "Enter a title for this template."+msgstr "Enter a title for this template."+#: src/components/ShareReceiveDialog.tsxmsgid "Error:"msgstr "Error:"@@ -2620,6 +2625,10 @@ msgstr "Found the repo but could not open the project. Please try again."msgid "From template"msgstr "From template"+#: src/components/TemplateForm.tsx+msgid "Frontmatter every document created from this template starts with. Values are YAML — a list is <0>[a, b]</0>; <1>{{date}}</1> fills in on create."+msgstr "Frontmatter every document created from this template starts with. Values are YAML — a list is <0>[a, b]</0>; <1>{{date}}</1> fills in on create."+#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "Full guide"msgstr "Full guide"@@ -3425,7 +3434,6 @@ msgstr "Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)#: src/components/AuthModal.tsx#: src/components/FolderOverview.tsx-#: src/components/TemplateForm.tsx#: src/editor/slash-command/items.tsxmsgid "Name"msgstr "Name"@@ -4415,13 +4423,22 @@ msgid "Property \"{trimmed}\" already exists"msgstr "Property \"{trimmed}\" already exists"#: src/components/FrontmatterRow.tsx+#: src/components/TemplateForm.tsxmsgid "Property name"msgstr "Property name"+#: src/components/TemplateForm.tsx+msgid "Property value"+msgstr "Property value"+#: src/components/SyncStatusBadge.tsxmsgid "Protected branch — cannot push"msgstr "Protected branch — cannot push"+#: src/components/TemplateForm.tsx+msgid "provisional"+msgstr "provisional"+#: src/components/PublishToGitHubDialog.tsxmsgid "Public"msgstr "Public"@@ -4600,6 +4617,10 @@ msgstr "Remove item {0}"msgid "Remove link"msgstr "Remove link"+#: src/components/TemplateForm.tsx+msgid "Remove property"+msgstr "Remove property"+#: src/components/CreateProjectDialog.tsxmsgid "Remove the parent <0>.git</0> folder"msgstr "Remove the parent <0>.git</0> folder"@@ -4687,6 +4708,10 @@ msgstr "Repository not found. It may have been renamed, deleted, or moved."msgid "Requires {brand}."msgstr "Requires {brand}."+#: src/components/TemplateForm.tsx+msgid "research-note"+msgstr "research-note"+#: src/components/settings/SettingsDialogBody.tsxmsgid "Reset {labelText} to default"msgstr "Reset {labelText} to default"@@ -5366,6 +5391,10 @@ msgstr "Starting clone"msgid "Starting sign-in flow"msgstr "Starting sign-in flow"+#: src/components/TemplateForm.tsx+msgid "status"+msgstr "status"+#: src/components/settings/SharingSection.tsx#: src/components/SharingModeField.tsxmsgid "Stays on this computer."@@ -5617,6 +5646,10 @@ msgstr "That folder isn't an Open Knowledge project yet. Initialize it and open?msgid "The {targetNoun} could not be opened — try navigating to it manually."msgstr "The {targetNoun} could not be opened — try navigating to it manually."+#: src/components/TemplateForm.tsx+msgid "The <0>type</0> every document created from this template gets (e.g. <1>research-note</1>). Keeps new docs Open Knowledge Format–conformant."+msgstr "The <0>type</0> every document created from this template gets (e.g. <1>research-note</1>). Keeps new docs Open Knowledge Format–conformant."+#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr "The Claude Desktop App didn't open the file. Is it installed? ({msg})"@@ -5813,6 +5846,7 @@ msgstr "This will replace the current document content with the version from <0>msgid "Timeline"msgstr "Timeline"+#: src/components/TemplateForm.tsx#: src/editor/extensions/CodeBlockView.tsxmsgid "Title"msgstr "Title"@@ -5924,6 +5958,10 @@ msgstr "Two-page (even)"msgid "Two-page (odd)"msgstr "Two-page (odd)"+#: src/components/TemplateForm.tsx+msgid "Type"+msgstr "Type"+#: src/components/CommandPalette.tsxmsgid "Type a query, then press ↵ to search your pages by meaning."msgstr "Type a query, then press ↵ to search your pages by meaning."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 091d9a8f4..be439342e 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -18,6 +18,7 @@"-QCLWk": ["Ţēḿƥĺàţēś àvàĩĺàƀĺē"],"-Qw-1t": ["ĜĩţĤũƀ àũţĥēńţĩćàţĩōń ƒàĩĺēď. Ţŕŷ śĩĝńĩńĝ ĩń àĝàĩń."],"-RXIMO": ["Ćōũĺďń'ţ ŕēàď ţĥē śēĺēćţĩōń — ƥĺēàśē ţŕŷ àĝàĩń."],+ "-WFFG2": ["Ďēƒàũĺţ ƥŕōƥēŕţĩēś"],"-YV1Uo": ["Ƥàţţēŕń ", ["patternNumber"]],"-g6KIS": ["Ũńŕēćōĝńĩźēď ĺĩńķ"],"-gdcIo": ["Àũţō-śŷńć ĩś ōń — ŷōũŕ ćōḿḿĩţś ƥũśĥ àńď ŕēḿōţē ćĥàńĝēś ƥũĺĺ ōń ĩńţēŕvàĺś."],@@ -30,13 +31,13 @@"-wePNM": ["Śēàŕćĥ ḿàţćĥēś ƒĩĺē ńàḿēś, ƥàţĥś, àńď ƒōĺďēŕś. Ōƥēń à ƒĩĺē ţō śēàŕćĥ ĩţś ƀōďŷ (⌘Ƒ)."],+ "-zy2Nq": ["Ţŷƥē"],"0-31GV": ["Ŕēḿōvĩńĝ"],"02P3hL": ["Ũƥĺōàď ƒàĩĺēď: ", ["message"]],"04RA0-": ["Ƒàĩĺēď ţō ēńàƀĺē śŷńć — ", ["detail"]],"06SZfb": ["Ţēḿƥĺàţē \"", ["trimmedTitle"], "\" ćŕēàţēď"],"07gHun": ["Ŷōũ ďōń'ţ ĥàvē àććēśś ţō ţĥĩś ƥŕĩvàţē ŕēƥō. Śĩĝń ĩń ŵĩţĥ àń àććōũńţ ţĥàţ ďōēś."],"07q4Qk": ["Ƒĩĺē śĩďēƀàŕ"],- "092Wah": ["Ēńţēŕ à ńàḿē ƒōŕ ţĥĩś ţēḿƥĺàţē."],"09Tv5j": ["Ŕēćōńńēćţĩńĝ…"],"0BB9ID": ["Ńō ĥēàďĩńĝś ŷēţ."],"0Gd0NU": ["Śĥàŕēď"],@@ -408,6 +409,7 @@],"Aif3E7": ["Ēńàƀĺē śēḿàńţĩć śēàŕćĥ"],"Am78jY": ["Ďŕàĝ ", ["keyName"], " ţō ŕēōŕďēŕ"],+ "Aq-O0x": ["śţàţũś"],"AqnqMJ": ["ÀƤĨ ķēŷ śēţ"],"ArBWJf": ["Ũńďō ĺàśţ ēďĩţ"],"B11p-O": ["Ēďĩţ ḿàŕķďōŵń ĺĩńķ"],@@ -998,6 +1000,7 @@"VZGh8G": ["Ƒōĺď, ũńƒōĺď, ƒōĺď àĺĺ, ōŕ ũńƒōĺď àĺĺ śōũŕćē ŕàńĝēś."],"VZSBXL": ["Śēḿàńţĩć ŕàńķĩńĝ àćţĩvàţēś ţĥē ƒĩŕśţ ţĩḿē àń àĝēńţ ŕũńś à śēàŕćĥ."],"V_6bJ4": ["Ţēŕḿĩńàĺ śēţţĩńĝś ńōţ ĺōàďēď ŷēţ — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ."],+ "V_wltx": ["Ēńţēŕ à ţĩţĺē ƒōŕ ţĥĩś ţēḿƥĺàţē."],"VbqhBI": ["Àĺŕēàďŷ àţ ", ["assetContentPath"], " — ŕēũśĩńĝ."],"VcqWBy": ["Ũƥĺōàď ḿàŷ ĥàvē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ĩś ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],"VdXv4D": ["Ćĺōńē ƒŕōḿ ĜĩţĤũƀ"],@@ -1405,6 +1408,7 @@"iH8pgl": ["ßàćķ"],"iHAJDj": ["Ŕēśōĺvĩńĝ ďēƒàũĺţ ĺōćàţĩōń"],"iKSP5j": ["Ŵōŕď ŵŕàƥ"],+ "iKZkk1": ["Ƥŕōƥēŕţŷ vàĺũē"],"iMkWoF": ["Ţũŕń ōń"],"iNFKkm": ["Ńō ďĩƒƒ."],"iOHg1t": ["Ōƥēń ēḿƀēďďēď ŨŔĹ ĩń ńēŵ ţàƀ"],@@ -1419,6 +1423,9 @@"ig5vUe": ["Ƒàĩĺēď ţō ĺōàď ƒĩĺē"],"iilQXA": ["Ƒōĺďēŕ ďũƥĺĩćàţēď"],"ijLc3m": ["ßũĺĺēţ ĺĩśţ"],+ "ipn17C": [+ "Ţĥē <0>ţŷƥē</0> ēvēŕŷ ďōćũḿēńţ ćŕēàţēď ƒŕōḿ ţĥĩś ţēḿƥĺàţē ĝēţś (ē.ĝ. <1>ŕēśēàŕćĥ-ńōţē</1>). Ķēēƥś ńēŵ ďōćś Ōƥēń Ķńōŵĺēďĝē Ƒōŕḿàţ–ćōńƒōŕḿàńţ."+ ],"iqIDv4": ["Śŷńć śţàţũś ũńàvàĩĺàƀĺē"],"iqugog": ["Ĩńĩţĩàĺĩźē ƒàĩĺēď: ", ["errorDetail"]],"irFGwu": ["Ţēḿƥĺàţē ĺĩśţ"],@@ -1429,6 +1436,7 @@"Ţĥĩś ƥŕōĴēćţ'ś ŕũńńĩńĝ śēŕvēŕ ďōēśń'ţ śũƥƥōŕţ ĺĩvē ēďĩţĩńĝ. Ŕēśţàŕţ Ōƥēń Ķńōŵĺēďĝē ţō ƒĩx."],"j9Vqvc": ["ĩńĥēŕĩţēď"],+ "jEZ6Lf": ["ƥŕōvĩśĩōńàĺ"],"jEdF24": ["Ḿĩśśĩńĝ ƥàĝē: ", ["linkTitle"], ". Ćĺĩćķ ţō ćŕēàţē."],"jGJy-9": ["Ďōŵńĺōàďś ", ["shareOwner"], "/", ["shareRepo"], " ƒŕōḿ ĜĩţĤũƀ."],"jKd3AP": ["Ćōũĺď ńōţ ēńàƀĺē ţĥē ţēŕḿĩńàĺ: ", ["0"]],@@ -1592,6 +1600,7 @@"o5gfs1": ["Ţĥĩś śēţţĩńĝ ĩś ƥēŕ-ḿàćĥĩńē àńď ĩśń'ţ śĥàŕēď ŵĩţĥ ćōĺĺàƀōŕàţōŕś. Ĩţ ńēēďś àń ÀƤĨ ķēŷ śēţ ŵĩţĥ <0>ōķ ēḿƀēďďĩńĝś śēţ-ķēŷ</0>."],+ "o9CrsQ": ["ŕēśēàŕćĥ-ńōţē"],"oAFVKX": ["Ƒàĩĺēď ţō ũƥďàţē ţĥē ƥŕōĴēćţ śŷńć ďēƒàũĺţ — ", ["detail"]],"oBXkm2": ["Ďēĺēţē ćōďē ƀĺōćķ"],"oCZkaG": ["Ćōƥŷ ƥàţĥ"],@@ -1687,6 +1696,7 @@"rBc32v": ["Ćōũĺďń'ţ ŕēàćĥ ţĥē ēḿƀēďďĩńĝś ƥŕōvĩďēŕ — ƥŕēśś ↵ ţō ŕēţŕŷ"],"rFw02Q": ["Ũƥĺōàďĩńĝ ", ["keyName"]],"rJVoVX": ["Śōũŕćē ƒĩńď ŕēśũĺţś"],+ "rNifQd": ["Ŕēḿōvē ƥŕōƥēŕţŷ"],"rQAQus": ["Ćōũĺďń'ţ śàvē ţēḿƥĺàţē: ", ["error"]],"rQRrkB": ["ŷēśţēŕďàŷ"],"rVgSRB": ["Ćōĺĺàƥśē ", ["docName"]],@@ -1964,6 +1974,11 @@"zkz0Fg": ["Śēţ ũƥ śŷńćĩńĝ"],"zlErBl": ["Ƥàĝē ĥēàďĩńĝś ēŕŕōŕ ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ŔƑĆ 9457"],"zo3Dl7": ["Ţōĝĝĺē ţĥũḿƀńàĩĺś"],+ "zrP8HX": [+ "Ƒŕōńţḿàţţēŕ ēvēŕŷ ďōćũḿēńţ ćŕēàţēď ƒŕōḿ ţĥĩś ţēḿƥĺàţē śţàŕţś ŵĩţĥ. Vàĺũēś àŕē ŶÀḾĹ — à ĺĩśţ ĩś <0>[à, ƀ]</0>; <1>{",+ ["date"],+ "}</1> ƒĩĺĺś ĩń ōń ćŕēàţē."+ ],"ztKII6": ["Ƒàĩĺēď ţō àďď ĩţēḿ"],"zwBp5t": ["Ƥŕĩvàţē"]}diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 5afd35133..b36561316 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -549,6 +549,7 @@ msgid "Add properties"msgstr ""#: src/components/PropertyPanel.tsx+#: src/components/TemplateForm.tsxmsgid "Add property"msgstr ""@@ -1742,6 +1743,10 @@ msgstr ""msgid "Date"msgstr ""+#: src/components/TemplateForm.tsx+msgid "Default properties"+msgstr ""+#: src/components/DeleteConfirmationDialog.tsx#: src/components/TemplateRow.tsx#: src/editor/extensions/JsxComponentView.tsx@@ -2169,10 +2174,6 @@ msgstr ""msgid "Enter a folder name (e.g. brain)."msgstr ""-#: src/components/TemplateForm.tsx-msgid "Enter a name for this template."-msgstr ""-#: src/components/CreateProjectDialog.tsxmsgid "Enter a project name"msgstr ""@@ -2181,6 +2182,10 @@ msgstr ""msgid "Enter a repository URL or owner/repo"msgstr ""+#: src/components/TemplateForm.tsx+msgid "Enter a title for this template."+msgstr ""+#: src/components/ShareReceiveDialog.tsxmsgid "Error:"msgstr ""@@ -2615,6 +2620,10 @@ msgstr ""msgid "From template"msgstr ""+#: src/components/TemplateForm.tsx+msgid "Frontmatter every document created from this template starts with. Values are YAML — a list is <0>[a, b]</0>; <1>{{date}}</1> fills in on create."+msgstr ""+#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "Full guide"msgstr ""@@ -3420,7 +3429,6 @@ msgstr ""#: src/components/AuthModal.tsx#: src/components/FolderOverview.tsx-#: src/components/TemplateForm.tsx#: src/editor/slash-command/items.tsxmsgid "Name"msgstr ""@@ -4410,13 +4418,22 @@ msgid "Property \"{trimmed}\" already exists"msgstr ""#: src/components/FrontmatterRow.tsx+#: src/components/TemplateForm.tsxmsgid "Property name"msgstr ""+#: src/components/TemplateForm.tsx+msgid "Property value"+msgstr ""+#: src/components/SyncStatusBadge.tsxmsgid "Protected branch — cannot push"msgstr ""+#: src/components/TemplateForm.tsx+msgid "provisional"+msgstr ""+#: src/components/PublishToGitHubDialog.tsxmsgid "Public"msgstr ""@@ -4595,6 +4612,10 @@ msgstr ""msgid "Remove link"msgstr ""+#: src/components/TemplateForm.tsx+msgid "Remove property"+msgstr ""+#: src/components/CreateProjectDialog.tsxmsgid "Remove the parent <0>.git</0> folder"msgstr ""@@ -4682,6 +4703,10 @@ msgstr ""msgid "Requires {brand}."msgstr ""+#: src/components/TemplateForm.tsx+msgid "research-note"+msgstr ""+#: src/components/settings/SettingsDialogBody.tsxmsgid "Reset {labelText} to default"msgstr ""@@ -5361,6 +5386,10 @@ msgstr ""msgid "Starting sign-in flow"msgstr ""+#: src/components/TemplateForm.tsx+msgid "status"+msgstr ""+#: src/components/settings/SharingSection.tsx#: src/components/SharingModeField.tsxmsgid "Stays on this computer."@@ -5612,6 +5641,10 @@ msgstr ""msgid "The {targetNoun} could not be opened — try navigating to it manually."msgstr ""+#: src/components/TemplateForm.tsx+msgid "The <0>type</0> every document created from this template gets (e.g. <1>research-note</1>). Keeps new docs Open Knowledge Format–conformant."+msgstr ""+#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "The Claude Desktop App didn't open the file. Is it installed? ({msg})"msgstr ""@@ -5808,6 +5841,7 @@ msgstr ""msgid "Timeline"msgstr ""+#: src/components/TemplateForm.tsx#: src/editor/extensions/CodeBlockView.tsxmsgid "Title"msgstr ""@@ -5919,6 +5953,10 @@ msgstr ""msgid "Two-page (odd)"msgstr ""+#: src/components/TemplateForm.tsx+msgid "Type"+msgstr ""+#: src/components/CommandPalette.tsxmsgid "Type a query, then press ↵ to search your pages by meaning."msgstr ""diff --git a/packages/app/tests/integration/create-page.test.ts b/packages/app/tests/integration/create-page.test.tsindex bf828f810..4fe17a678 100644--- a/packages/app/tests/integration/create-page.test.ts+++ b/packages/app/tests/integration/create-page.test.ts@@ -156,6 +156,24 @@ describe('/api/create-page — template seeding', () => {expect(created).toMatch(/\d{4}-\d{2}-\d{2}/);});+ test('single-block template: strips `template:` identity, keeps doc-frontmatter, substitutes tokens', async () => {+ seedRootTemplate(+ 'research-tpl',+ '---\ntemplate:\n title: Research Log\n description: provisional\ntype: research-note\nstatus: provisional\ncreated: {{date}}\ntags: [research]\n---\n\n## Question\n',+ );+ const { status } = await createPageWithTemplate('from-single-block.md', 'research-tpl');+ expect(status).toBe(200);++ const created = readFileSync(join(server.contentDir, 'from-single-block.md'), 'utf-8');+ expect(created).toContain('type: research-note');+ expect(created).toContain('status: provisional');+ expect(created).toContain('## Question');+ expect(created).not.toContain('template:');+ expect(created).not.toContain('title: Research Log');+ expect(created).not.toContain('{{date}}');+ expect(created).toMatch(/created: \d{4}-\d{2}-\d{2}/);+ });+test('returns 400 when the template name does not resolve', async () => {const { status, body } = await createPageWithTemplate('no-such-tpl.md', 'does-not-exist');expect(status).toBe(400);diff --git a/packages/app/tests/integration/mcp-write-extension.test.ts b/packages/app/tests/integration/mcp-write-extension.test.tsindex 506f80ae8..2054fdde8 100644--- a/packages/app/tests/integration/mcp-write-extension.test.ts+++ b/packages/app/tests/integration/mcp-write-extension.test.ts@@ -1,6 +1,6 @@import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';-import { existsSync } from 'node:fs';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';import { createTestServer, pollUntil, type TestServer } from './test-harness.ts';@@ -122,6 +122,35 @@ test('the `extension` field wins over an extension typed into `path`', async ()expect(existsSync(join(server.contentDir, `${docName}.md`))).toBe(false);});+test('write({ document: { template } }) keeps a single-block template doc-frontmatter', async () => {+ const session = await openMcpSession(server.port);+ mkdirSync(join(server.contentDir, '.ok', 'templates'), { recursive: true });+ writeFileSync(+ join(server.contentDir, '.ok', 'templates', 'research-tpl.md'),+ '---\ntemplate:\n title: Research Log\n description: provisional\ntype: research-note\nstatus: provisional\ncreated: {{date}}\ntags: [research]\n---\n\n## Question\n',+ 'utf-8',+ );++ const docName = `from-tpl-${randomUUID().slice(0, 8)}`;+ const result = await callWrite(+ server.port,+ session,+ { document: { path: docName, template: 'research-tpl' } },+ server.contentDir,+ );+ expect(result.isError ?? false).toBe(false);++ await pollUntil(() => existsSync(join(server.contentDir, `${docName}.md`)));+ const created = readFileSync(join(server.contentDir, `${docName}.md`), 'utf-8');+ expect(created).toContain('type: research-note');+ expect(created).toContain('status: provisional');+ expect(created).toContain('## Question');+ expect(created).not.toContain('template:');+ expect(created).not.toContain('title: Research Log');+ expect(created).not.toContain('{{date}}');+ expect(created).toMatch(/created: \d{4}-\d{2}-\d{2}/);+});+test('batch `documents` write honors a per-entry `extension`', async () => {const session = await openMcpSession(server.port);const a = `mdx-batch-a-${randomUUID().slice(0, 8)}`;diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex f7a956ace..0b0ee9897 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -912,6 +912,14 @@ export {type SkillStateTarget,type SkillStateTargetEntry,} from './skill-state/schema.ts';+export {+ composeTemplateFile,+ instantiateDoc,+ parseTemplateFile,+ TEMPLATE_IDENTITY_KEY,+ type TemplateIdentity,+ type TemplateModel,+} from './templates/template-format.ts';export type { Actor, PrincipalId, SessionId } from './types/actor.ts';export type {AgentFlashEntry,diff --git a/packages/core/src/templates/template-format.test.ts b/packages/core/src/templates/template-format.test.tsnew file mode 100644index 000000000..bca78d50f--- /dev/null+++ b/packages/core/src/templates/template-format.test.ts@@ -0,0 +1,128 @@+import { describe, expect, test } from 'bun:test';+import {+ composeTemplateFile,+ instantiateDoc,+ parseTemplateFile,+ TEMPLATE_IDENTITY_KEY,+} from './template-format.ts';++const SINGLE_BLOCK = `---+template:+ title: Research Log+ description: Provisional analysis synthesizing external sources.+status: provisional+sources: []+created: {{date}}+author: {{user}}+tags: [research, provisional]+---++## Question++## Sources cited+`;++const LEGACY_TWO_BLOCK = `---+title: Research Log+description: Provisional analysis synthesizing external sources.+---+---+status: provisional+sources: []+created: {{date}}+author: {{user}}+tags: [research, provisional]+---++## Question++## Sources cited+`;++describe('parseTemplateFile', () => {+ test('parses a single-block template: identity from template:, doc-fm as starter content', () => {+ const m = parseTemplateFile(SINGLE_BLOCK);+ expect(m.identity.title).toBe('Research Log');+ expect(m.identity.description).toContain('Provisional analysis');+ expect(m.starterContent).toContain('status: provisional');+ expect(m.starterContent).toContain('## Question');+ expect(m.starterContent).not.toContain('title: Research Log');+ expect(m.starterContent).not.toContain(`${TEMPLATE_IDENTITY_KEY}:`);+ });++ test('strips a leading UTF-8 BOM so identity is not lost', () => {+ const m = parseTemplateFile(`\uFEFF${SINGLE_BLOCK}`);+ expect(m.identity.title).toBe('Research Log');+ expect(m.starterContent).toContain('## Question');+ });++ test('handles a blank line inside the template: identity block', () => {+ const raw = `---\ntemplate:\n title: T\n\n description: D\nstatus: provisional\n---\n\n## Body\n`;+ const m = parseTemplateFile(raw);+ expect(m.identity.title).toBe('T');+ expect(m.identity.description).toBe('D');+ expect(m.starterContent).toContain('status: provisional');+ expect(m.starterContent).not.toContain('title: T');+ });++ test('parses a legacy two-block template to the SAME logical model', () => {+ const legacy = parseTemplateFile(LEGACY_TWO_BLOCK);+ const modern = parseTemplateFile(SINGLE_BLOCK);+ expect(legacy.identity.title).toBe(modern.identity.title);+ expect(legacy.identity.description).toBe(modern.identity.description);+ expect(legacy.starterContent).toContain('status: provisional');+ expect(legacy.starterContent).toContain('## Question');+ expect(legacy.starterContent).not.toContain('title: Research Log');+ });++ test('never throws on malformed yaml', () => {+ const broken = `---\ntemplate:\n title: X\nbad: a: b: c\n---\n\nbody`;+ expect(() => parseTemplateFile(broken)).not.toThrow();+ });+});++describe('composeTemplateFile + round-trip', () => {+ test('compose produces a single block with template: first and no second fence', () => {+ const m = parseTemplateFile(SINGLE_BLOCK);+ const composed = composeTemplateFile(m.identity, m.starterContent);+ const fenceCount = (composed.match(/^---[ \t]*$/gm) ?? []).length;+ expect(fenceCount).toBe(2);+ expect(composed).toContain(`${TEMPLATE_IDENTITY_KEY}:`);+ expect(composed).toContain('status: provisional');+ expect(composed).toContain('## Question');+ });++ test('parse -> compose -> parse is stable (idempotent model)', () => {+ const m1 = parseTemplateFile(SINGLE_BLOCK);+ const composed = composeTemplateFile(m1.identity, m1.starterContent);+ const m2 = parseTemplateFile(composed);+ expect(m2.identity.title).toBe(m1.identity.title);+ expect(m2.starterContent.trim()).toBe(m1.starterContent.trim());+ });++ test('migrates legacy -> single block on compose', () => {+ const legacy = parseTemplateFile(LEGACY_TWO_BLOCK);+ const composed = composeTemplateFile(legacy.identity, legacy.starterContent);+ const fenceCount = (composed.match(/^---[ \t]*$/gm) ?? []).length;+ expect(fenceCount).toBe(2); // single block, not the legacy two+ expect(parseTemplateFile(composed).identity.title).toBe('Research Log');+ });+});++describe('instantiateDoc', () => {+ test('new doc = doc-frontmatter + markdown, identity stripped', () => {+ const doc = instantiateDoc(SINGLE_BLOCK);+ expect(doc).toContain('status: provisional');+ expect(doc).toContain('## Question');+ expect(doc).not.toContain('title: Research Log');+ expect(doc).not.toContain(`${TEMPLATE_IDENTITY_KEY}:`);+ expect(doc).toContain('{{date}}');+ });++ test('legacy template instantiates to the same doc shape', () => {+ const doc = instantiateDoc(LEGACY_TWO_BLOCK);+ expect(doc).toContain('status: provisional');+ expect(doc).toContain('## Question');+ expect(doc).not.toContain('title: Research Log');+ });+});diff --git a/packages/core/src/templates/template-format.ts b/packages/core/src/templates/template-format.tsnew file mode 100644index 000000000..185fd5979--- /dev/null+++ b/packages/core/src/templates/template-format.ts@@ -0,0 +1,120 @@+import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';+import { stripFrontmatter, unwrapFrontmatterFences } from '../extensions/frontmatter.ts';++export const TEMPLATE_IDENTITY_KEY = 'template';++export interface TemplateIdentity {+ title?: string;+ description?: string;+ tags?: string[];+ [key: string]: unknown;+}++export interface TemplateModel {+ identity: TemplateIdentity;+ starterContent: string;+}++function parseYamlObject(yaml: string): Record<string, unknown> {+ if (yaml.trim() === '') return {};+ let parsed: unknown;+ try {+ parsed = parseYaml(yaml);+ } catch {+ return {};+ }+ if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed)) return {};+ return parsed as Record<string, unknown>;+}++function composeStarterContent(docFrontmatterText: string, markdown: string): string {+ if (docFrontmatterText.trim() === '') return markdown;+ return `---\n${docFrontmatterText}\n---\n${markdown}`;+}++function splitStarterContent(starterContent: string): {+ docFrontmatterText: string;+ markdown: string;+} {+ const { frontmatter, body } = stripFrontmatter(starterContent);+ if (frontmatter === '') return { docFrontmatterText: '', markdown: starterContent };+ return { docFrontmatterText: unwrapFrontmatterFences(frontmatter), markdown: body };+}++function peelTemplateIdentity(+ blockText: string,+): { identity: TemplateIdentity; docFrontmatterText: string } | null {+ const lines = blockText.split('\n');+ if (!(lines[0] ?? '').startsWith(`${TEMPLATE_IDENTITY_KEY}:`)) return null;+ const identityLines = [lines[0] ?? ''];+ let i = 1;+ while (i < lines.length) {+ const line = lines[i] ?? '';+ if (/^[ \t]/.test(line)) {+ identityLines.push(line);+ i++;+ continue;+ }+ if (line.trim() === '') {+ let j = i + 1;+ while (j < lines.length && (lines[j] ?? '').trim() === '') j++;+ if (j < lines.length && /^[ \t]/.test(lines[j] ?? '')) {+ identityLines.push(line);+ i++;+ continue;+ }+ }+ break;+ }+ const rawIdentity = parseYamlObject(identityLines.join('\n'))[TEMPLATE_IDENTITY_KEY];+ const identity: TemplateIdentity =+ rawIdentity != null && typeof rawIdentity === 'object' && !Array.isArray(rawIdentity)+ ? (rawIdentity as TemplateIdentity)+ : {};+ const docFrontmatterText = lines.slice(i).join('\n').replace(/\n+$/, '');+ return { identity, docFrontmatterText };+}++export function parseTemplateFile(raw: string): TemplateModel {+ const cleaned = raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw;+ const { frontmatter, body } = stripFrontmatter(cleaned);+ if (frontmatter === '') {+ return { identity: {}, starterContent: cleaned };+ }+ const block1Text = unwrapFrontmatterFences(frontmatter);++ const peeled = peelTemplateIdentity(block1Text);+ if (peeled) {+ return {+ identity: peeled.identity,+ starterContent: composeStarterContent(peeled.docFrontmatterText, body),+ };+ }++ const { frontmatter: block2Fenced } = stripFrontmatter(body);+ if (block2Fenced !== '') {+ return { identity: parseYamlObject(block1Text) as TemplateIdentity, starterContent: body };+ }++ const block1 = parseYamlObject(block1Text);+ if (typeof block1.title === 'string') {+ return { identity: block1 as TemplateIdentity, starterContent: body };+ }+ return { identity: {}, starterContent: composeStarterContent(block1Text, body) };+}++export function composeTemplateFile(identity: TemplateIdentity, starterContent: string): string {+ const { docFrontmatterText, markdown } = splitStarterContent(starterContent);+ const cleanIdentity: Record<string, unknown> = {};+ for (const [k, v] of Object.entries(identity)) {+ if (v !== undefined) cleanIdentity[k] = v;+ }+ const identityYaml = stringifyYaml({ [TEMPLATE_IDENTITY_KEY]: cleanIdentity });+ const inner =+ docFrontmatterText.trim() === '' ? identityYaml : `${identityYaml}${docFrontmatterText}\n`;+ return `---\n${inner}---\n${markdown}`;+}++export function instantiateDoc(raw: string): string {+ return parseTemplateFile(raw).starterContent;+}diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex fe3832286..6ccea47c6 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -86,6 +86,7 @@ import {type InlineAssetMediaKind,InstallSkillRequestSchema,InstallSkillSuccessSchema,+ instantiateDoc,isHiddenDocName,LINKABLE_ASSET_EXTENSIONS,type LifecycleStatus,@@ -111,6 +112,7 @@ import {type Principal,PrincipalSuccessSchema,type ProblemType,+ parseTemplateFile,prependFrontmatter,RenamePathRequestSchema,RenamePathSuccessSchema,@@ -170,7 +172,6 @@ import {TrashCleanupSuccessSchema,UploadAssetSuccessSchema,UploadRequestSchema,- unwrapFrontmatterFences,type WorkspaceSearchCorpus,type WorkspaceSearchDocument,type WorkspaceSearchIntent,@@ -6695,10 +6696,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {);return;}- const { body: templateBody } = stripFrontmatter(templateRaw);+ const templateStarter = instantiateDoc(templateRaw);const userDisplayName =actor.kind === 'agent' || actor.kind === 'principal' ? (actor.displayName ?? '') : '';- initialContent = applySubstitution(templateBody, {+ initialContent = applySubstitution(templateStarter, {date: todayIsoUtc(),user: userDisplayName,});@@ -9874,22 +9875,6 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {});}- const parseTemplateFile = (- raw: string,- ): { frontmatter: Record<string, unknown>; body: string } => {- const { frontmatter: fenced, body } = stripFrontmatter(raw);- let frontmatter: Record<string, unknown> = {};- if (fenced !== '') {- try {- const parsed = parseYaml(unwrapFrontmatterFences(fenced));- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {- frontmatter = parsed as Record<string, unknown>;- }- } catch {}- }- return { frontmatter, body };- };-const handleTemplateGet = withValidation(EmptyRequestSchema,async (req, res) => {@@ -9918,7 +9903,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {const { abs: foundAbs, folder: foundFolder, scope: foundScope } = found;const raw = await readFile(foundAbs, 'utf-8');- const { frontmatter, body } = parseTemplateFile(raw);+ const model = parseTemplateFile(raw);+ const frontmatter = model.identity as Record<string, unknown>;+ const body = model.starterContent;const relPath = relative(resolvedContentDir, foundAbs).split(/[\\/]/)@@ -10213,9 +10200,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {writeBody = body.body;} else {try {- writeBody = parseTemplateFile(+ writeBody = instantiateDoc(readFileSync(resolve(toValidated.resolvedContentDir, result.toPath), 'utf-8'),- ).body;+ );} catch {writeBody = null;}diff --git a/packages/server/src/content/templates-resolver.ts b/packages/server/src/content/templates-resolver.tsindex 72b58539b..333b86440 100644--- a/packages/server/src/content/templates-resolver.ts+++ b/packages/server/src/content/templates-resolver.ts@@ -1,7 +1,6 @@import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';import { join, posix } from 'node:path';-import { stripFrontmatter, unwrapFrontmatterFences } from '@inkeep/open-knowledge-core';-import { parse as parseYaml } from 'yaml';+import { parseTemplateFile } from '@inkeep/open-knowledge-core';type TemplateScope = 'local' | 'inherited';@@ -200,34 +199,15 @@ function readTemplateMeta(absPath: string): TemplateMeta {}return {};}- const fmYaml = extractFrontmatterYaml(content);- if (fmYaml === null) return {};-- let parsed: unknown;- try {- parsed = parseYaml(fmYaml);- } catch (err) {- if (!templateMetaWarnedPaths.has(absPath)) {- templateMetaWarnedPaths.add(absPath);- const reason = err instanceof Error ? err.message : String(err);- console.warn(- `[ok-templates] malformed YAML frontmatter at ${absPath} — title/description unavailable. Reason: ${reason}`,- );- }- return {};+ const { identity } = parseTemplateFile(content);+ if (typeof identity.title !== 'string' && !templateMetaWarnedPaths.has(absPath)) {+ templateMetaWarnedPaths.add(absPath);+ console.warn(+ `[ok-templates] template at ${absPath} has no title — YAML may be malformed or the title is missing.`,+ );}- if (parsed == null || typeof parsed !== 'object') return {};-- const fm = parsed as Record<string, unknown>;const result: TemplateMeta = {};- if (typeof fm.title === 'string') result.title = fm.title;- if (typeof fm.description === 'string') result.description = fm.description;+ if (typeof identity.title === 'string') result.title = identity.title;+ if (typeof identity.description === 'string') result.description = identity.description;return result;}--function extractFrontmatterYaml(content: string): string | null {- const normalized = content.replace(/^/, '');- const { frontmatter } = stripFrontmatter(normalized);- if (frontmatter === '') return null;- return unwrapFrontmatterFences(frontmatter);-}diff --git a/packages/server/src/content/templates-write.test.ts b/packages/server/src/content/templates-write.test.tsindex 781c816b0..a0effe937 100644--- a/packages/server/src/content/templates-write.test.ts+++ b/packages/server/src/content/templates-write.test.ts@@ -187,10 +187,22 @@ describe('applyTemplateWrite', () => {if (!result.ok) return;const abs = join(projectDir, 'meetings', '.ok', 'templates', 'minimal.md');const content = readFileSync(abs, 'utf-8');- expect(content).toContain('---\ntitle: Minimal\n---');+ expect(content).toContain('---\ntemplate:\n title: Minimal\n---');expect(content).toContain('just body');expect(result.warnings.some((w) => w.match(/description is missing/))).toBe(true);});++ test('rejects body frontmatter containing the reserved template: key', () => {+ const result = applyTemplateWrite({+ projectDir,+ folder: 'meetings',+ name: 'bad-reserved',+ body: '---\ntemplate:\n title: Inner\nstatus: ok\n---\n# Body',+ frontmatter: { title: 'My Template', description: 'desc' },+ });+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.error.code).toBe('TEMPLATE_RESERVED_KEY');+ });});describe('applyTemplateDelete', () => {diff --git a/packages/server/src/content/templates-write.ts b/packages/server/src/content/templates-write.tsindex 629862161..20d05be66 100644--- a/packages/server/src/content/templates-write.ts+++ b/packages/server/src/content/templates-write.ts@@ -8,7 +8,13 @@ import {writeFileSync,} from 'node:fs';import { isAbsolute, join, normalize, resolve, sep } from 'node:path';-import { stringify as stringifyYaml } from 'yaml';+import {+ composeTemplateFile,+ stripFrontmatter,+ TEMPLATE_IDENTITY_KEY,+ type TemplateIdentity,+ unwrapFrontmatterFences,+} from '@inkeep/open-knowledge-core';import { validateSubstitution } from './substitution.ts';type TemplateWriteResult =@@ -67,14 +73,24 @@ export function applyTemplateWrite(input: WriteTemplateInput): TemplateWriteResuconst subsCheck = validateSubstitutionAllowlist(input.body);if (!subsCheck.ok) return { ok: false, error: subsCheck.error };+ const reservedCheck = validateNoReservedDocKey(input.body);+ if (!reservedCheck.ok) return { ok: false, error: reservedCheck.error };+const { templatesDir, filePath } = templatePaths(input.projectDir,validation.folderRel,input.name,);- const fmYaml = serializeFrontmatter(input.frontmatter);- const content = fmYaml ? `---\n${fmYaml}---\n${input.body}` : input.body;+ const identity: TemplateIdentity = {};+ if (input.frontmatter.title !== undefined) identity.title = input.frontmatter.title;+ if (input.frontmatter.description !== undefined) {+ identity.description = input.frontmatter.description;+ }+ if (Array.isArray(input.frontmatter.tags) && input.frontmatter.tags.length > 0) {+ identity.tags = input.frontmatter.tags;+ }+ const content = composeTemplateFile(identity, input.body);try {mkdirSync(templatesDir, { recursive: true });@@ -368,13 +384,22 @@ function relPathOf(projectDir: string, abs: string): string {return normalize(rel).split(sep).join('/');}-function serializeFrontmatter(fm: TemplateFrontmatter): string {- const obj: Record<string, unknown> = {};- if (fm.title !== undefined) obj.title = fm.title;- if (fm.description !== undefined) obj.description = fm.description;- if (Array.isArray(fm.tags) && fm.tags.length > 0) obj.tags = fm.tags;- if (Object.keys(obj).length === 0) return '';- return stringifyYaml(obj);+function validateNoReservedDocKey(+ body: string,+): { ok: true } | { ok: false; error: { code: string; message: string } } {+ const { frontmatter } = stripFrontmatter(body);+ if (frontmatter === '') return { ok: true };+ const inner = unwrapFrontmatterFences(frontmatter);+ if (new RegExp(`^${TEMPLATE_IDENTITY_KEY}:`, 'm').test(inner)) {+ return {+ ok: false,+ error: {+ code: 'TEMPLATE_RESERVED_KEY',+ message: `Template starter content may not declare a top-level \`${TEMPLATE_IDENTITY_KEY}:\` frontmatter key — it is reserved for the template's identity.`,+ },+ };+ }+ return { ok: true };}function isEmpty(absDir: string): boolean {diff --git a/packages/server/src/mcp/tools/verb-schemas.ts b/packages/server/src/mcp/tools/verb-schemas.tsindex a62b02766..f7f598526 100644--- a/packages/server/src/mcp/tools/verb-schemas.ts+++ b/packages/server/src/mcp/tools/verb-schemas.ts@@ -42,7 +42,7 @@ const TEMPLATE_NAME_REGEX = /^[A-Za-z0-9_-]+$/;export const TEMPLATE_PATH_DESCRIBE ='Template path = `<folder>/<name>` (e.g. "fishing-log/trip-log"). The slashes are the folder it belongs to; the final segment is the template name (letters, digits, `_`, `-` only — no dots/spaces). Stored at `<folder>/.ok/templates/<name>.md`.';export const TEMPLATE_CONTENT_DESCRIBE =- 'Template Markdown body. Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time.';+ "Starter content — the Markdown a new document becomes. A leading `---…---` frontmatter block here sets the STARTING PROPERTIES every doc created from this template gets (e.g. `type`, `status`, `tags`); the markdown below it is the body. The template's own picker identity (title/description) is the separate `frontmatter` field, NOT this block — it is stripped at instantiation and never copied onto created docs. (On disk this composes to one frontmatter block with the identity under a reserved `template:` key; you don't author that — just give the starter content here.) Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time.";export function resolveTemplatePath(path: string,diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.tsindex 23ea6c7d3..bbd34947c 100644--- a/packages/server/src/mcp/tools/write.ts+++ b/packages/server/src/mcp/tools/write.ts@@ -4,6 +4,7 @@ import {type DocExtension,type FrontmatterMap,type FrontmatterPatch,+ instantiateDoc,normalizeBridge,parseFrontmatterYaml,renderInventoryFooter,@@ -237,7 +238,7 @@ async function writeOneDoc(error: `failed to read template at ${matched.path}: ${(err as Error).message}`,};}- const { body: templateBody } = stripFrontmatter(templateContent);+ const templateBody = instantiateDoc(templateContent);effectiveMarkdown = applySubstitution(templateBody, {date: todayIsoUtc(),user: identity?.displayName ?? '',diff --git a/packages/server/src/seed/okf-conformance.test.ts b/packages/server/src/seed/okf-conformance.test.tsindex c9ef02fd8..306d4c9c5 100644--- a/packages/server/src/seed/okf-conformance.test.ts+++ b/packages/server/src/seed/okf-conformance.test.ts@@ -4,6 +4,7 @@ import { mkdtemp, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join, relative } from 'node:path';import {+ instantiateDoc,parseFrontmatterYaml,stripFrontmatter,unwrapFrontmatterFences,@@ -39,7 +40,7 @@ function collectMarkdown(root: string, dir = root): string[] {function consumerFrontmatterYaml(relPath: string, raw: string): string | null {const isTemplate = relPath.includes('/.ok/templates/');const docSource = isTemplate- ? applySubstitution(stripFrontmatter(raw).body, { date: '2026-01-01', user: 'Test User' })+ ? applySubstitution(instantiateDoc(raw), { date: '2026-01-01', user: 'Test User' }): raw;const { frontmatter } = stripFrontmatter(docSource);if (frontmatter === '') return null;@@ -205,7 +206,7 @@ describe('okf pack — OKF §9 conformance by construction', () => {});describe('all starter packs — OKF §9 rule 2 (every template instantiates a typed doc)', () => {- test('every template in every pack carries a non-empty type in its instantiated (block-2) frontmatter', () => {+ test('every template in every pack carries a non-empty type in its instantiated doc-frontmatter', () => {const packs = Object.values(STARTER_PACKS);expect(packs.length).toBeGreaterThanOrEqual(7);diff --git a/packages/server/src/seed/seed-frontmatter-guard.test.ts b/packages/server/src/seed/seed-frontmatter-guard.test.tsnew file mode 100644index 000000000..df3034fda--- /dev/null+++ b/packages/server/src/seed/seed-frontmatter-guard.test.ts@@ -0,0 +1,70 @@+import { describe, expect, test } from 'bun:test';+import {+ parseTemplateFile,+ stripFrontmatter,+ unwrapFrontmatterFences,+} from '@inkeep/open-knowledge-core';+import { parse as parseYaml } from 'yaml';+import { STARTER_PACKS } from './starter.ts';++function frontmatterParseError(content: string): string | null {+ const { frontmatter } = stripFrontmatter(content);+ if (frontmatter === '') return null;+ try {+ parseYaml(unwrapFrontmatterFences(frontmatter), { logLevel: 'silent' });+ return null;+ } catch (e) {+ return e instanceof Error ? e.message.split('\n')[0] : String(e);+ }+}++describe('starter-pack frontmatter guard', () => {+ test('every template frontmatter block is valid YAML', () => {+ for (const pack of Object.values(STARTER_PACKS)) {+ for (const [name, content] of Object.entries(pack.templates)) {+ expect(+ frontmatterParseError(content),+ `Pack "${pack.id}" template "${name}" has invalid YAML frontmatter`,+ ).toBeNull();+ }+ }+ });++ test('every root-file frontmatter block is valid YAML', () => {+ for (const pack of Object.values(STARTER_PACKS)) {+ for (const [name, content] of Object.entries(pack.rootFiles ?? {})) {+ expect(+ frontmatterParseError(content),+ `Pack "${pack.id}" rootFile "${name}" has invalid YAML frontmatter`,+ ).toBeNull();+ }+ }+ });++ test('every template is a SINGLE-block file (no stacked frontmatter)', () => {+ for (const pack of Object.values(STARTER_PACKS)) {+ for (const [name, content] of Object.entries(pack.templates)) {+ expect(+ /\n---\n---\n/.test(content),+ `Pack "${pack.id}" template "${name}" still has a stacked second frontmatter block`,+ ).toBe(false);+ }+ }+ });++ test('every template carries a non-empty identity title under template:', () => {+ for (const pack of Object.values(STARTER_PACKS)) {+ for (const [name, content] of Object.entries(pack.templates)) {+ const { identity, starterContent } = parseTemplateFile(content);+ expect(+ typeof identity.title === 'string' && identity.title.trim().length > 0,+ `Pack "${pack.id}" template "${name}" missing template.title`,+ ).toBe(true);+ expect(+ starterContent.includes('template:'),+ `Pack "${pack.id}" template "${name}" leaks template: into starter content`,+ ).toBe(false);+ }+ }+ });+});diff --git a/packages/server/src/seed/starter.test.ts b/packages/server/src/seed/starter.test.tsindex 3fd747693..485f68c8b 100644--- a/packages/server/src/seed/starter.test.ts+++ b/packages/server/src/seed/starter.test.ts@@ -1,4 +1,5 @@import { describe, expect, test } from 'bun:test';+import { parseTemplateFile } from '@inkeep/open-knowledge-core';import {buildStarterFolderFrontmatterYaml,listStarterPacks,@@ -16,9 +17,7 @@ if (!LOG_MD_TEMPLATE) throw new Error('knowledge-base pack is missing log.md');const ENTITY_VAULT_PACK = STARTER_PACKS['entity-vault'];function stripTemplateMetadata(body: string): string {- const match = /^---\n[\s\S]*?\n---\n([\s\S]*)$/.exec(body);- if (!match?.[1]) throw new Error('template missing outer metadata frontmatter');- return match[1];+ return parseTemplateFile(body).starterContent;}function documentFrontmatter(body: string): string {@@ -221,10 +220,11 @@ describe('STARTER_PACKS — all packs structural validation', () => {test('every template body has a description: frontmatter line (load-bearing customer convention)', () => {for (const pack of Object.values(STARTER_PACKS)) {for (const [name, body] of Object.entries(pack.templates)) {+ const { description } = parseTemplateFile(body).identity;expect(- body,- `Pack "${pack.id}" template "${name}" missing description: frontmatter line`,- ).toMatch(/^description:\s*\S/m);+ typeof description === 'string' && description.trim().length > 0,+ `Pack "${pack.id}" template "${name}" missing template.description`,+ ).toBe(true);}}});diff --git a/packages/server/src/seed/starter.ts b/packages/server/src/seed/starter.tsindex 20a1b2209..8cc5d0a2f 100644--- a/packages/server/src/seed/starter.ts+++ b/packages/server/src/seed/starter.ts@@ -57,11 +57,11 @@ const KNOWLEDGE_BASE_FOLDERS: readonly StarterFolder[] = [const KNOWLEDGE_BASE_TEMPLATES: Readonly<Record<string, string>> = {clip: `----title: External Source-description: Capture a URL or article text verbatim as raw reference material. For binary files (PDFs, images, audio), use the \`ingest\` tool instead — this \`clip\` template is for text sources only.--------+template:+ title: External Source+ description: Capture a URL or article text verbatim as raw reference material. For binary files (PDFs, images, audio), use the \`ingest\` tool instead — this \`clip\` template is for text sources only.type: source+description: "Raw source text captured verbatim for reference, with its original URL and fetch date."source_url:date_fetched: {{date}}preservation: text-extracted@@ -75,11 +75,11 @@ tags: [source, immutable, layer-ingest, text]## My notes`,'research-log': `----title: Research Log-description: Provisional analysis synthesizing external sources. Every factual claim cites a doc in external-sources/. Promoted to articles/ via consolidate once findings are stable.--------+template:+ title: Research Log+ description: Provisional analysis synthesizing external sources. Every factual claim cites a doc in external-sources/. Promoted to articles/ via consolidate once findings are stable.type: research-note+description: "Provisional findings that synthesize the cited sources, pending promotion to a canonical article."status: provisionalsources: []created: {{date}}@@ -96,11 +96,11 @@ tags: [research, provisional]## Open questions`,article: `----title: Canonical Article-description: Canonical knowledge committed after a team decision. Carries status:canonical plus a supersedes chain tying back to the research/ docs it replaces. Source-of-truth for the domain.--------+template:+ title: Canonical Article+ description: Canonical knowledge committed after a team decision. Carries status:canonical plus a supersedes chain tying back to the research/ docs it replaces. Source-of-truth for the domain.type: article+description: "Canonical, team-approved reference for this topic."status: canonicalsupersedes: []authored: {{date}}@@ -173,11 +173,11 @@ const SOFTWARE_LIFECYCLE_FOLDERS: readonly StarterFolder[] = [const SOFTWARE_LIFECYCLE_TEMPLATES: Readonly<Record<string, string>> = {proposal: `----title: Proposal Title-description: One-line summary of the proposal.--------+template:+ title: Proposal Title+ description: One-line summary of the proposal.type: proposal+description: "A proposal put forward for discussion and a decision."status: draftauthors: [{{user}}]created: {{date}}@@ -195,11 +195,11 @@ tags: [proposal]## Unresolved questions`,decision: `----title: Decision Title-description: One-line decision summary.--------+template:+ title: Decision Title+ description: One-line decision summary.type: decision+description: "A recorded decision with its context and rationale."status: proposeddate: {{date}}deciders: [{{user}}]@@ -214,11 +214,11 @@ tags: [decision]## Consequences`,spec: `----title: Spec Title-description: One-line description of what's being built.--------+template:+ title: Spec Title+ description: One-line description of what's being built.type: spec+description: "Specification of the problem, requirements, and intended solution."status: draftowner: {{user}}target_release:@@ -238,11 +238,11 @@ tags: [spec]## Test plan`,'spec-plan': `----title: 'Plan: <Spec Title>'-description: Implementation plan derived from the parent spec. Pairs with spec.md and tasks.md (github/spec-kit triple shape).--------+template:+ title: 'Plan: <Spec Title>'+ description: Implementation plan derived from the parent spec. Pairs with spec.md and tasks.md (github/spec-kit triple shape).type: spec-plan+description: "Implementation plan breaking the spec into an ordered approach."parent_spec:created: {{date}}author: {{user}}@@ -260,11 +260,11 @@ tags: [spec, plan]## Rollout`,'spec-tasks': `----title: 'Tasks: <Spec Title>'-description: Task checklist for the parent spec. Pairs with spec.md and plan.md (github/spec-kit triple shape).--------+template:+ title: 'Tasks: <Spec Title>'+ description: Task checklist for the parent spec. Pairs with spec.md and plan.md (github/spec-kit triple shape).type: spec-tasks+description: "Task breakdown tracking the work needed to deliver the spec."parent_spec:created: {{date}}author: {{user}}@@ -282,11 +282,11 @@ tags: [spec, tasks]## Out of scope`,guide: `----title: '<Topic>: <Action>'-description: One-line summary of what the reader will accomplish.--------+template:+ title: '<Topic>: <Action>'+ description: One-line summary of what the reader will accomplish.type: guide+description: "Step-by-step guide for completing a task."category: how-tolast_verified: {{date}}tags: [guide]@@ -301,11 +301,11 @@ tags: [guide]## Links`,'onboarding-guide': `----title: 'Onboarding: <Audience>'-description: First-N-days setup path for <audience> (e.g. new engineer, new contributor, new oncall).--------+template:+ title: 'Onboarding: <Audience>'+ description: First-N-days setup path for <audience> (e.g. new engineer, new contributor, new oncall).type: guide+description: "Onboarding guide that orients a new audience and gets them started."category: onboardingaudience:last_verified: {{date}}@@ -325,11 +325,11 @@ tags: [guide, onboarding]## Links`,runbook: `----title: '<Service>: <Symptom>'-description: Oncall procedure for diagnosing and remediating <symptom> in <service>.--------+template:+ title: '<Service>: <Symptom>'+ description: Oncall procedure for diagnosing and remediating <symptom> in <service>.type: guide+description: "Troubleshooting guide for diagnosing and resolving a symptom."category: runbookservice:severity:@@ -348,11 +348,11 @@ tags: [guide, runbook, oncall]## Links`,postmortem: `----title: 'Incident: <short name>'-description: Blameless postmortem for <incident>.--------+template:+ title: 'Incident: <short name>'+ description: Blameless postmortem for <incident>.type: postmortem+description: "Post-incident review covering impact, timeline, root cause, and follow-ups."severity:duration:services: []@@ -395,22 +395,22 @@ const PLAIN_NOTES_FOLDERS: readonly StarterFolder[] = [const PLAIN_NOTES_TEMPLATES: Readonly<Record<string, string>> = {note: `----title: Note title-description: One-line summary.--------+template:+ title: Note title+ description: One-line summary.type: note+description: "A short freeform note."created: {{date}}author: {{user}}tags: []---`,daily: `----title: Daily entry-description: Daily journal entry.--------+template:+ title: Daily entry+ description: Daily journal entry.type: daily-note+description: "Daily journal entry capturing intentions, notes, and reflections."title: {{date}}date: {{date}}author: {{user}}@@ -479,11 +479,11 @@ const WORLDBUILDING_FOLDERS: readonly StarterFolder[] = [const WORLDBUILDING_TEMPLATES: Readonly<Record<string, string>> = {character: `----title: Character Name-description: One-line characterization.--------+template:+ title: Character Name+ description: One-line characterization.type: character+description: "Profile of a character: traits, motivations, relationships, and arc."status: alivefaction: []first_appeared:@@ -501,11 +501,11 @@ tags: [character]## Links`,setting: `----title: Setting Name-description: One-line atmospheric summary.--------+template:+ title: Setting Name+ description: One-line atmospheric summary.type: setting+description: "Description of a place or setting in the world."region:controlling_faction:danger_level:@@ -521,11 +521,11 @@ tags: [setting]## What's hidden`,theme: `----title: Theme Name-description: One-line statement of the recurring concern.--------+template:+ title: Theme Name+ description: One-line statement of the recurring concern.type: theme+description: "A recurring theme and how it surfaces across the work."created: {{date}}author: {{user}}tags: [theme]@@ -538,11 +538,11 @@ tags: [theme]## Tension`,faction: `----title: Faction Name-description: One-line description of who they are and what they want.--------+template:+ title: Faction Name+ description: One-line description of who they are and what they want.type: faction+description: "Profile of a faction: goals, members, and allegiances."alignment:leader:members: []@@ -559,11 +559,11 @@ tags: [faction]## Internal tensions`,'political-faction': `----title: Faction Name-description: One-line summary of their politics and their ambition.--------+template:+ title: Faction Name+ description: One-line summary of their politics and their ambition.type: political-faction+description: "Profile of a political faction: ideology, power base, and aims."form: monarchyseat:leader:@@ -587,11 +587,11 @@ tags: [faction, politics]## Pressure points`,religion: `----title: Religion Name-description: One-line summary of the faith and its central tension.--------+template:+ title: Religion Name+ description: One-line summary of the faith and its central tension.type: religion+description: "Profile of a religion: beliefs, practices, and followers."deity:pantheon: []clergy_structure:@@ -615,11 +615,11 @@ tags: [faction, religion]## Relations with power`,lore: `----title: Lore Topic-description: One-line summary.--------+template:+ title: Lore Topic+ description: One-line summary.type: lore+description: "A piece of world lore and its place in the larger canon."era:scope: historycreated: {{date}}@@ -634,11 +634,11 @@ tags: [lore]## Implications`,'magic-system': `----title: Magic System Name-description: One-line summary of the source and the cost.--------+template:+ title: Magic System Name+ description: One-line summary of the source and the cost.type: magic-system+description: "The rules, costs, and limits of a magic system."source:cost:discoverable_by: []@@ -660,11 +660,11 @@ tags: [lore, magic]## How it shapes the world`,'historical-event': `----title: Event Name-description: One-line summary of what happened and why it mattered.--------+template:+ title: Event Name+ description: One-line summary of what happened and why it mattered.type: historical-event+description: "Account of a historical event: what happened, when, and why it matters."when:where:duration:@@ -717,11 +717,11 @@ const WRITING_PIPELINE_FOLDERS: readonly StarterFolder[] = [const WRITING_PIPELINE_TEMPLATES: Readonly<Record<string, string>> = {idea: `----title: Idea title-description: One-line hook.--------+template:+ title: Idea title+ description: One-line hook.type: idea+description: "An early idea captured for later development."captured_at: {{date}}hook:tags: [idea]@@ -730,11 +730,11 @@ tags: [idea]## Stimulus`,draft: `----title: Draft title-description: What's this piece about?--------+template:+ title: Draft title+ description: What's this piece about?type: draft+description: "A work-in-progress draft."status: draftingtarget_form:target_words:@@ -746,11 +746,11 @@ tags: [draft]`,published: `----title: Published title-description: One-line summary.--------+template:+ title: Published title+ description: One-line summary.type: publication+description: "A finished, published piece."status: publishedpublished_at:canonical_url:@@ -816,11 +816,11 @@ const ENTITY_VAULT_FOLDERS: readonly StarterFolder[] = [const ENTITY_VAULT_TEMPLATES: Readonly<Record<string, string>> = {person: `----title: Person Name-description: One-line characterization. Who they are, why they matter to you.--------+template:+ title: Person Name+ description: One-line characterization. Who they are, why they matter to you.type: person+description: "Profile of a person: role, context, and how you know them."title: Person Namecreated: {{date}}author: {{user}}@@ -838,11 +838,11 @@ tags: [person]- **{{date}}** | source | @{{user}} — First evidence entry. Confidence: draft.`,company: `----title: Company Name-description: One-line company summary. What they do, who's involved.--------+template:+ title: Company Name+ description: One-line company summary. What they do, who's involved.type: company+description: "Profile of a company: what it does and why it matters to you."title: Company Namecreated: {{date}}author: {{user}}@@ -860,11 +860,11 @@ tags: [company]- **{{date}}** | source | @{{user}} — First evidence entry. Confidence: draft.`,meeting: `----title: Meeting Title-description: One-line meeting summary. Fill in after the meeting.--------+template:+ title: Meeting Title+ description: One-line meeting summary. Fill in after the meeting.type: meeting+description: "Meeting notes: attendees, discussion, decisions, and action items."title: Meeting Titledate: {{date}}attendees: []@@ -881,11 +881,11 @@ tags: [meeting]- [ ]`,concept: `----title: Concept Name-description: One-line concept summary. What it names and why it recurs.--------+template:+ title: Concept Name+ description: One-line concept summary. What it names and why it recurs.type: concept+description: "Explanation of a concept and how it connects to related ideas."title: Concept Namecreated: {{date}}author: {{user}}@@ -903,11 +903,11 @@ tags: [concept]- **{{date}}** | source | @{{user}} — First evidence entry. Confidence: draft.`,original: `----title: Idea Title-description: One-line summary of the idea or take.--------+template:+ title: Idea Title+ description: One-line summary of the idea or take.type: original+description: "An original idea in its initial form."title: Idea Titledate: {{date}}author: {{user}}@@ -917,11 +917,11 @@ tags: [original](Your own thinking. Link to anything that should become its own entity, preferably with path-qualified wikilinks once the entity dossier exists.)`,transcript: `----title: Transcript-description: One-line transcript summary. Source and key topic.--------+template:+ title: Transcript+ description: One-line transcript summary. Source and key topic.type: transcript+description: "Verbatim transcript of a conversation or recording."title: Transcriptdate: {{date}}source:@@ -1041,7 +1041,7 @@ description: What the agent may read, write, and surface. A 4-tier privacy modelconst ENTITY_VAULT_HEARTBEAT_MD = `---title: Operational cadence-description: When the agent does scheduled work: daily briefings, end-of-day dossier maintenance, weekly audits. If you also use GBrain, note its sync/dream cadence here.+description: "When the agent does scheduled work: daily briefings, end-of-day dossier maintenance, weekly audits. If you also use GBrain, note its sync/dream cadence here."---# Heartbeat@@ -1094,11 +1094,11 @@ const OKF_FOLDERS: readonly StarterFolder[] = [const OKF_TEMPLATES: Readonly<Record<string, string>> = {concept: `----title: Concept Name-description: One-line definition of the concept.--------+template:+ title: Concept Name+ description: One-line definition of the concept.type: concept+description: "Explanation of a concept and how it connects to related ideas."created: {{date}}author: {{user}}tags: [concept]@@ -1113,11 +1113,11 @@ tags: [concept]- Link a related idea, e.g. [another concept](./another-concept.md).`,reference: `----title: Reference Title-description: One-line summary of the source.--------+template:+ title: Reference Title+ description: One-line summary of the source.type: reference+description: "A reference entry kept for quick lookup."created: {{date}}author: {{user}}tags: [reference]@@ -1132,11 +1132,11 @@ tags: [reference]- Link the docs that cite this reference.`,note: `----title: Note Title-description: One-line summary of the note.--------+template:+ title: Note Title+ description: One-line summary of the note.type: note+description: "A freeform note."created: {{date}}author: {{user}}tags: [note]